FileDownloader.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import math
  5. import io
  6. import os
  7. import re
  8. import socket
  9. import subprocess
  10. import sys
  11. import time
  12. import traceback
  13. if os.name == 'nt':
  14. import ctypes
  15. from .utils import *
  16. class FileDownloader(object):
  17. """File Downloader class.
  18. File downloader objects are the ones responsible of downloading the
  19. actual video file and writing it to disk if the user has requested
  20. it, among some other tasks. In most cases there should be one per
  21. program. As, given a video URL, the downloader doesn't know how to
  22. extract all the needed information, task that InfoExtractors do, it
  23. has to pass the URL to one of them.
  24. For this, file downloader objects have a method that allows
  25. InfoExtractors to be registered in a given order. When it is passed
  26. a URL, the file downloader handles it to the first InfoExtractor it
  27. finds that reports being able to handle it. The InfoExtractor extracts
  28. all the information about the video or videos the URL refers to, and
  29. asks the FileDownloader to process the video information, possibly
  30. downloading the video.
  31. File downloaders accept a lot of parameters. In order not to saturate
  32. the object constructor with arguments, it receives a dictionary of
  33. options instead. These options are available through the params
  34. attribute for the InfoExtractors to use. The FileDownloader also
  35. registers itself as the downloader in charge for the InfoExtractors
  36. that are added to it, so this is a "mutual registration".
  37. Available options:
  38. username: Username for authentication purposes.
  39. password: Password for authentication purposes.
  40. usenetrc: Use netrc for authentication instead.
  41. quiet: Do not print messages to stdout.
  42. forceurl: Force printing final URL.
  43. forcetitle: Force printing title.
  44. forcethumbnail: Force printing thumbnail URL.
  45. forcedescription: Force printing description.
  46. forcefilename: Force printing final filename.
  47. simulate: Do not download the video files.
  48. format: Video format code.
  49. format_limit: Highest quality format to try.
  50. outtmpl: Template for output names.
  51. restrictfilenames: Do not allow "&" and spaces in file names
  52. ignoreerrors: Do not stop on download errors.
  53. ratelimit: Download speed limit, in bytes/sec.
  54. nooverwrites: Prevent overwriting files.
  55. retries: Number of times to retry for HTTP error 5xx
  56. buffersize: Size of download buffer in bytes.
  57. noresizebuffer: Do not automatically resize the download buffer.
  58. continuedl: Try to continue downloads if possible.
  59. noprogress: Do not print the progress bar.
  60. playliststart: Playlist item to start at.
  61. playlistend: Playlist item to end at.
  62. matchtitle: Download only matching titles.
  63. rejecttitle: Reject downloads for matching titles.
  64. logtostderr: Log messages to stderr instead of stdout.
  65. consoletitle: Display progress in console window's titlebar.
  66. nopart: Do not use temporary .part files.
  67. updatetime: Use the Last-modified header to set output file timestamps.
  68. writedescription: Write the video description to a .description file
  69. writeinfojson: Write the video description to a .info.json file
  70. writesubtitles: Write the video subtitles to a file
  71. onlysubtitles: Downloads only the subtitles of the video
  72. allsubtitles: Downloads all the subtitles of the video
  73. subtitlesformat: Subtitle format [sbv/srt] (default=srt)
  74. subtitleslang: Language of the subtitles to download
  75. test: Download only first bytes to test the downloader.
  76. keepvideo: Keep the video file after post-processing
  77. min_filesize: Skip files smaller than this size
  78. max_filesize: Skip files larger than this size
  79. """
  80. params = None
  81. _ies = []
  82. _pps = []
  83. _download_retcode = None
  84. _num_downloads = None
  85. _screen_file = None
  86. def __init__(self, params):
  87. """Create a FileDownloader object with the given options."""
  88. self._ies = []
  89. self._pps = []
  90. self._progress_hooks = []
  91. self._download_retcode = 0
  92. self._num_downloads = 0
  93. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  94. self.params = params
  95. if '%(stitle)s' in self.params['outtmpl']:
  96. self.to_stderr(u'WARNING: %(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  97. @staticmethod
  98. def format_bytes(bytes):
  99. if bytes is None:
  100. return 'N/A'
  101. if type(bytes) is str:
  102. bytes = float(bytes)
  103. if bytes == 0.0:
  104. exponent = 0
  105. else:
  106. exponent = int(math.log(bytes, 1024.0))
  107. suffix = 'bkMGTPEZY'[exponent]
  108. converted = float(bytes) / float(1024 ** exponent)
  109. return '%.2f%s' % (converted, suffix)
  110. @staticmethod
  111. def calc_percent(byte_counter, data_len):
  112. if data_len is None:
  113. return '---.-%'
  114. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  115. @staticmethod
  116. def calc_eta(start, now, total, current):
  117. if total is None:
  118. return '--:--'
  119. dif = now - start
  120. if current == 0 or dif < 0.001: # One millisecond
  121. return '--:--'
  122. rate = float(current) / dif
  123. eta = int((float(total) - float(current)) / rate)
  124. (eta_mins, eta_secs) = divmod(eta, 60)
  125. if eta_mins > 99:
  126. return '--:--'
  127. return '%02d:%02d' % (eta_mins, eta_secs)
  128. @staticmethod
  129. def calc_speed(start, now, bytes):
  130. dif = now - start
  131. if bytes == 0 or dif < 0.001: # One millisecond
  132. return '%10s' % '---b/s'
  133. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  134. @staticmethod
  135. def best_block_size(elapsed_time, bytes):
  136. new_min = max(bytes / 2.0, 1.0)
  137. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  138. if elapsed_time < 0.001:
  139. return int(new_max)
  140. rate = bytes / elapsed_time
  141. if rate > new_max:
  142. return int(new_max)
  143. if rate < new_min:
  144. return int(new_min)
  145. return int(rate)
  146. @staticmethod
  147. def parse_bytes(bytestr):
  148. """Parse a string indicating a byte quantity into an integer."""
  149. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  150. if matchobj is None:
  151. return None
  152. number = float(matchobj.group(1))
  153. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  154. return int(round(number * multiplier))
  155. def add_info_extractor(self, ie):
  156. """Add an InfoExtractor object to the end of the list."""
  157. self._ies.append(ie)
  158. ie.set_downloader(self)
  159. def add_post_processor(self, pp):
  160. """Add a PostProcessor object to the end of the chain."""
  161. self._pps.append(pp)
  162. pp.set_downloader(self)
  163. def to_screen(self, message, skip_eol=False):
  164. """Print message to stdout if not in quiet mode."""
  165. assert type(message) == type(u'')
  166. if not self.params.get('quiet', False):
  167. terminator = [u'\n', u''][skip_eol]
  168. output = message + terminator
  169. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  170. output = output.encode(preferredencoding(), 'ignore')
  171. self._screen_file.write(output)
  172. self._screen_file.flush()
  173. def to_stderr(self, message):
  174. """Print message to stderr."""
  175. assert type(message) == type(u'')
  176. output = message + u'\n'
  177. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  178. output = output.encode(preferredencoding())
  179. sys.stderr.write(output)
  180. def to_cons_title(self, message):
  181. """Set console/terminal window title to message."""
  182. if not self.params.get('consoletitle', False):
  183. return
  184. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  185. # c_wchar_p() might not be necessary if `message` is
  186. # already of type unicode()
  187. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  188. elif 'TERM' in os.environ:
  189. self.to_screen('\033]0;%s\007' % message, skip_eol=True)
  190. def fixed_template(self):
  191. """Checks if the output template is fixed."""
  192. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  193. def trouble(self, message=None, tb=None):
  194. """Determine action to take when a download problem appears.
  195. Depending on if the downloader has been configured to ignore
  196. download errors or not, this method may throw an exception or
  197. not when errors are found, after printing the message.
  198. tb, if given, is additional traceback information.
  199. """
  200. if message is not None:
  201. self.to_stderr(message)
  202. if self.params.get('verbose'):
  203. if tb is None:
  204. tb_data = traceback.format_list(traceback.extract_stack())
  205. tb = u''.join(tb_data)
  206. self.to_stderr(tb)
  207. if not self.params.get('ignoreerrors', False):
  208. raise DownloadError(message)
  209. self._download_retcode = 1
  210. def slow_down(self, start_time, byte_counter):
  211. """Sleep if the download speed is over the rate limit."""
  212. rate_limit = self.params.get('ratelimit', None)
  213. if rate_limit is None or byte_counter == 0:
  214. return
  215. now = time.time()
  216. elapsed = now - start_time
  217. if elapsed <= 0.0:
  218. return
  219. speed = float(byte_counter) / elapsed
  220. if speed > rate_limit:
  221. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  222. def temp_name(self, filename):
  223. """Returns a temporary filename for the given filename."""
  224. if self.params.get('nopart', False) or filename == u'-' or \
  225. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  226. return filename
  227. return filename + u'.part'
  228. def undo_temp_name(self, filename):
  229. if filename.endswith(u'.part'):
  230. return filename[:-len(u'.part')]
  231. return filename
  232. def try_rename(self, old_filename, new_filename):
  233. try:
  234. if old_filename == new_filename:
  235. return
  236. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  237. except (IOError, OSError) as err:
  238. self.trouble(u'ERROR: unable to rename file')
  239. def try_utime(self, filename, last_modified_hdr):
  240. """Try to set the last-modified time of the given file."""
  241. if last_modified_hdr is None:
  242. return
  243. if not os.path.isfile(encodeFilename(filename)):
  244. return
  245. timestr = last_modified_hdr
  246. if timestr is None:
  247. return
  248. filetime = timeconvert(timestr)
  249. if filetime is None:
  250. return filetime
  251. try:
  252. os.utime(filename, (time.time(), filetime))
  253. except:
  254. pass
  255. return filetime
  256. def report_writedescription(self, descfn):
  257. """ Report that the description file is being written """
  258. self.to_screen(u'[info] Writing video description to: ' + descfn)
  259. def report_writesubtitles(self, sub_filename):
  260. """ Report that the subtitles file is being written """
  261. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  262. def report_writeinfojson(self, infofn):
  263. """ Report that the metadata file has been written """
  264. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  265. def report_destination(self, filename):
  266. """Report destination filename."""
  267. self.to_screen(u'[download] Destination: ' + filename)
  268. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  269. """Report download progress."""
  270. if self.params.get('noprogress', False):
  271. return
  272. if self.params.get('progress_with_newline', False):
  273. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  274. (percent_str, data_len_str, speed_str, eta_str))
  275. else:
  276. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  277. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  278. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  279. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  280. def report_resuming_byte(self, resume_len):
  281. """Report attempt to resume at given byte."""
  282. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  283. def report_retry(self, count, retries):
  284. """Report retry in case of HTTP error 5xx"""
  285. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  286. def report_file_already_downloaded(self, file_name):
  287. """Report file has already been fully downloaded."""
  288. try:
  289. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  290. except (UnicodeEncodeError) as err:
  291. self.to_screen(u'[download] The file has already been downloaded')
  292. def report_unable_to_resume(self):
  293. """Report it was impossible to resume download."""
  294. self.to_screen(u'[download] Unable to resume')
  295. def report_finish(self):
  296. """Report download finished."""
  297. if self.params.get('noprogress', False):
  298. self.to_screen(u'[download] Download completed')
  299. else:
  300. self.to_screen(u'')
  301. def increment_downloads(self):
  302. """Increment the ordinal that assigns a number to each file."""
  303. self._num_downloads += 1
  304. def prepare_filename(self, info_dict):
  305. """Generate the output filename."""
  306. try:
  307. template_dict = dict(info_dict)
  308. template_dict['epoch'] = int(time.time())
  309. template_dict['autonumber'] = u'%05d' % self._num_downloads
  310. sanitize = lambda k,v: sanitize_filename(
  311. u'NA' if v is None else compat_str(v),
  312. restricted=self.params.get('restrictfilenames'),
  313. is_id=(k==u'id'))
  314. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  315. filename = self.params['outtmpl'] % template_dict
  316. return filename
  317. except (ValueError, KeyError) as err:
  318. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  319. return None
  320. def _match_entry(self, info_dict):
  321. """ Returns None iff the file should be downloaded """
  322. title = info_dict['title']
  323. matchtitle = self.params.get('matchtitle', False)
  324. if matchtitle:
  325. if not re.search(matchtitle, title, re.IGNORECASE):
  326. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  327. rejecttitle = self.params.get('rejecttitle', False)
  328. if rejecttitle:
  329. if re.search(rejecttitle, title, re.IGNORECASE):
  330. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  331. return None
  332. def process_info(self, info_dict):
  333. """Process a single dictionary returned by an InfoExtractor."""
  334. # Keep for backwards compatibility
  335. info_dict['stitle'] = info_dict['title']
  336. if not 'format' in info_dict:
  337. info_dict['format'] = info_dict['ext']
  338. reason = self._match_entry(info_dict)
  339. if reason is not None:
  340. self.to_screen(u'[download] ' + reason)
  341. return
  342. max_downloads = self.params.get('max_downloads')
  343. if max_downloads is not None:
  344. if self._num_downloads > int(max_downloads):
  345. raise MaxDownloadsReached()
  346. filename = self.prepare_filename(info_dict)
  347. # Forced printings
  348. if self.params.get('forcetitle', False):
  349. compat_print(info_dict['title'])
  350. if self.params.get('forceurl', False):
  351. compat_print(info_dict['url'])
  352. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  353. compat_print(info_dict['thumbnail'])
  354. if self.params.get('forcedescription', False) and 'description' in info_dict:
  355. compat_print(info_dict['description'])
  356. if self.params.get('forcefilename', False) and filename is not None:
  357. compat_print(filename)
  358. if self.params.get('forceformat', False):
  359. compat_print(info_dict['format'])
  360. # Do nothing else if in simulate mode
  361. if self.params.get('simulate', False):
  362. return
  363. if filename is None:
  364. return
  365. try:
  366. dn = os.path.dirname(encodeFilename(filename))
  367. if dn != '' and not os.path.exists(dn): # dn is already encoded
  368. os.makedirs(dn)
  369. except (OSError, IOError) as err:
  370. self.trouble(u'ERROR: unable to create directory ' + compat_str(err))
  371. return
  372. if self.params.get('writedescription', False):
  373. try:
  374. descfn = filename + u'.description'
  375. self.report_writedescription(descfn)
  376. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  377. descfile.write(info_dict['description'])
  378. except (OSError, IOError):
  379. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  380. return
  381. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  382. # subtitles download errors are already managed as troubles in relevant IE
  383. # that way it will silently go on when used with unsupporting IE
  384. subtitle = info_dict['subtitles'][0]
  385. (sub_error, sub_lang, sub) = subtitle
  386. sub_format = self.params.get('subtitlesformat')
  387. try:
  388. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  389. self.report_writesubtitles(sub_filename)
  390. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  391. subfile.write(sub)
  392. except (OSError, IOError):
  393. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  394. return
  395. if self.params.get('onlysubtitles', False):
  396. return
  397. if self.params.get('allsubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  398. subtitles = info_dict['subtitles']
  399. sub_format = self.params.get('subtitlesformat')
  400. for subtitle in subtitles:
  401. (sub_error, sub_lang, sub) = subtitle
  402. try:
  403. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  404. self.report_writesubtitles(sub_filename)
  405. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  406. subfile.write(sub)
  407. except (OSError, IOError):
  408. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  409. return
  410. if self.params.get('onlysubtitles', False):
  411. return
  412. if self.params.get('writeinfojson', False):
  413. infofn = filename + u'.info.json'
  414. self.report_writeinfojson(infofn)
  415. try:
  416. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  417. write_json_file(json_info_dict, encodeFilename(infofn))
  418. except (OSError, IOError):
  419. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  420. return
  421. if not self.params.get('skip_download', False):
  422. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  423. success = True
  424. else:
  425. try:
  426. success = self._do_download(filename, info_dict)
  427. except (OSError, IOError) as err:
  428. raise UnavailableVideoError()
  429. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  430. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  431. return
  432. except (ContentTooShortError, ) as err:
  433. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  434. return
  435. if success:
  436. try:
  437. self.post_process(filename, info_dict)
  438. except (PostProcessingError) as err:
  439. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  440. return
  441. def download(self, url_list):
  442. """Download a given list of URLs."""
  443. if len(url_list) > 1 and self.fixed_template():
  444. raise SameFileError(self.params['outtmpl'])
  445. for url in url_list:
  446. suitable_found = False
  447. for ie in self._ies:
  448. # Go to next InfoExtractor if not suitable
  449. if not ie.suitable(url):
  450. continue
  451. # Warn if the _WORKING attribute is False
  452. if not ie.working():
  453. self.to_stderr(u'WARNING: the program functionality for this site has been marked as broken, '
  454. u'and will probably not work. If you want to go on, use the -i option.')
  455. # Suitable InfoExtractor found
  456. suitable_found = True
  457. # Extract information from URL and process it
  458. try:
  459. videos = ie.extract(url)
  460. except ExtractorError as de: # An error we somewhat expected
  461. self.trouble(u'ERROR: ' + compat_str(de), de.format_traceback())
  462. break
  463. except Exception as e:
  464. if self.params.get('ignoreerrors', False):
  465. self.trouble(u'ERROR: ' + compat_str(e), tb=compat_str(traceback.format_exc()))
  466. break
  467. else:
  468. raise
  469. if len(videos or []) > 1 and self.fixed_template():
  470. raise SameFileError(self.params['outtmpl'])
  471. for video in videos or []:
  472. video['extractor'] = ie.IE_NAME
  473. try:
  474. self.increment_downloads()
  475. self.process_info(video)
  476. except UnavailableVideoError:
  477. self.trouble(u'\nERROR: unable to download video')
  478. # Suitable InfoExtractor had been found; go to next URL
  479. break
  480. if not suitable_found:
  481. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  482. return self._download_retcode
  483. def post_process(self, filename, ie_info):
  484. """Run all the postprocessors on the given file."""
  485. info = dict(ie_info)
  486. info['filepath'] = filename
  487. keep_video = None
  488. for pp in self._pps:
  489. try:
  490. keep_video_wish,new_info = pp.run(info)
  491. if keep_video_wish is not None:
  492. if keep_video_wish:
  493. keep_video = keep_video_wish
  494. elif keep_video is None:
  495. # No clear decision yet, let IE decide
  496. keep_video = keep_video_wish
  497. except PostProcessingError as e:
  498. self.to_stderr(u'ERROR: ' + e.msg)
  499. if keep_video is False and not self.params.get('keepvideo', False):
  500. try:
  501. self.to_stderr(u'Deleting original file %s (pass -k to keep)' % filename)
  502. os.remove(encodeFilename(filename))
  503. except (IOError, OSError):
  504. self.to_stderr(u'WARNING: Unable to remove downloaded video file')
  505. def _download_with_rtmpdump(self, filename, url, player_url, page_url):
  506. self.report_destination(filename)
  507. tmpfilename = self.temp_name(filename)
  508. # Check for rtmpdump first
  509. try:
  510. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  511. except (OSError, IOError):
  512. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  513. return False
  514. # Download using rtmpdump. rtmpdump returns exit code 2 when
  515. # the connection was interrumpted and resuming appears to be
  516. # possible. This is part of rtmpdump's normal usage, AFAIK.
  517. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  518. if player_url is not None:
  519. basic_args += ['-W', player_url]
  520. if page_url is not None:
  521. basic_args += ['--pageUrl', page_url]
  522. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  523. if self.params.get('verbose', False):
  524. try:
  525. import pipes
  526. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  527. except ImportError:
  528. shell_quote = repr
  529. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  530. retval = subprocess.call(args)
  531. while retval == 2 or retval == 1:
  532. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  533. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  534. time.sleep(5.0) # This seems to be needed
  535. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  536. cursize = os.path.getsize(encodeFilename(tmpfilename))
  537. if prevsize == cursize and retval == 1:
  538. break
  539. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  540. if prevsize == cursize and retval == 2 and cursize > 1024:
  541. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  542. retval = 0
  543. break
  544. if retval == 0:
  545. fsize = os.path.getsize(encodeFilename(tmpfilename))
  546. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  547. self.try_rename(tmpfilename, filename)
  548. self._hook_progress({
  549. 'downloaded_bytes': fsize,
  550. 'total_bytes': fsize,
  551. 'filename': filename,
  552. 'status': 'finished',
  553. })
  554. return True
  555. else:
  556. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  557. return False
  558. def _do_download(self, filename, info_dict):
  559. url = info_dict['url']
  560. # Check file already present
  561. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  562. self.report_file_already_downloaded(filename)
  563. self._hook_progress({
  564. 'filename': filename,
  565. 'status': 'finished',
  566. })
  567. return True
  568. # Attempt to download using rtmpdump
  569. if url.startswith('rtmp'):
  570. return self._download_with_rtmpdump(filename, url,
  571. info_dict.get('player_url', None),
  572. info_dict.get('page_url', None))
  573. tmpfilename = self.temp_name(filename)
  574. stream = None
  575. # Do not include the Accept-Encoding header
  576. headers = {'Youtubedl-no-compression': 'True'}
  577. if 'user_agent' in info_dict:
  578. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  579. basic_request = compat_urllib_request.Request(url, None, headers)
  580. request = compat_urllib_request.Request(url, None, headers)
  581. if self.params.get('test', False):
  582. request.add_header('Range','bytes=0-10240')
  583. # Establish possible resume length
  584. if os.path.isfile(encodeFilename(tmpfilename)):
  585. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  586. else:
  587. resume_len = 0
  588. open_mode = 'wb'
  589. if resume_len != 0:
  590. if self.params.get('continuedl', False):
  591. self.report_resuming_byte(resume_len)
  592. request.add_header('Range','bytes=%d-' % resume_len)
  593. open_mode = 'ab'
  594. else:
  595. resume_len = 0
  596. count = 0
  597. retries = self.params.get('retries', 0)
  598. while count <= retries:
  599. # Establish connection
  600. try:
  601. if count == 0 and 'urlhandle' in info_dict:
  602. data = info_dict['urlhandle']
  603. data = compat_urllib_request.urlopen(request)
  604. break
  605. except (compat_urllib_error.HTTPError, ) as err:
  606. if (err.code < 500 or err.code >= 600) and err.code != 416:
  607. # Unexpected HTTP error
  608. raise
  609. elif err.code == 416:
  610. # Unable to resume (requested range not satisfiable)
  611. try:
  612. # Open the connection again without the range header
  613. data = compat_urllib_request.urlopen(basic_request)
  614. content_length = data.info()['Content-Length']
  615. except (compat_urllib_error.HTTPError, ) as err:
  616. if err.code < 500 or err.code >= 600:
  617. raise
  618. else:
  619. # Examine the reported length
  620. if (content_length is not None and
  621. (resume_len - 100 < int(content_length) < resume_len + 100)):
  622. # The file had already been fully downloaded.
  623. # Explanation to the above condition: in issue #175 it was revealed that
  624. # YouTube sometimes adds or removes a few bytes from the end of the file,
  625. # changing the file size slightly and causing problems for some users. So
  626. # I decided to implement a suggested change and consider the file
  627. # completely downloaded if the file size differs less than 100 bytes from
  628. # the one in the hard drive.
  629. self.report_file_already_downloaded(filename)
  630. self.try_rename(tmpfilename, filename)
  631. self._hook_progress({
  632. 'filename': filename,
  633. 'status': 'finished',
  634. })
  635. return True
  636. else:
  637. # The length does not match, we start the download over
  638. self.report_unable_to_resume()
  639. open_mode = 'wb'
  640. break
  641. # Retry
  642. count += 1
  643. if count <= retries:
  644. self.report_retry(count, retries)
  645. if count > retries:
  646. self.trouble(u'ERROR: giving up after %s retries' % retries)
  647. return False
  648. data_len = data.info().get('Content-length', None)
  649. if data_len is not None:
  650. data_len = int(data_len) + resume_len
  651. min_data_len = self.params.get("min_filesize", None)
  652. max_data_len = self.params.get("max_filesize", None)
  653. if min_data_len is not None and data_len < min_data_len:
  654. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  655. return False
  656. if max_data_len is not None and data_len > max_data_len:
  657. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  658. return False
  659. data_len_str = self.format_bytes(data_len)
  660. byte_counter = 0 + resume_len
  661. block_size = self.params.get('buffersize', 1024)
  662. start = time.time()
  663. while True:
  664. # Download and write
  665. before = time.time()
  666. data_block = data.read(block_size)
  667. after = time.time()
  668. if len(data_block) == 0:
  669. break
  670. byte_counter += len(data_block)
  671. # Open file just in time
  672. if stream is None:
  673. try:
  674. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  675. assert stream is not None
  676. filename = self.undo_temp_name(tmpfilename)
  677. self.report_destination(filename)
  678. except (OSError, IOError) as err:
  679. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  680. return False
  681. try:
  682. stream.write(data_block)
  683. except (IOError, OSError) as err:
  684. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  685. return False
  686. if not self.params.get('noresizebuffer', False):
  687. block_size = self.best_block_size(after - before, len(data_block))
  688. # Progress message
  689. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  690. if data_len is None:
  691. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  692. else:
  693. percent_str = self.calc_percent(byte_counter, data_len)
  694. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  695. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  696. self._hook_progress({
  697. 'downloaded_bytes': byte_counter,
  698. 'total_bytes': data_len,
  699. 'tmpfilename': tmpfilename,
  700. 'filename': filename,
  701. 'status': 'downloading',
  702. })
  703. # Apply rate limit
  704. self.slow_down(start, byte_counter - resume_len)
  705. if stream is None:
  706. self.trouble(u'\nERROR: Did not get any data blocks')
  707. return False
  708. stream.close()
  709. self.report_finish()
  710. if data_len is not None and byte_counter != data_len:
  711. raise ContentTooShortError(byte_counter, int(data_len))
  712. self.try_rename(tmpfilename, filename)
  713. # Update file modification time
  714. if self.params.get('updatetime', True):
  715. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  716. self._hook_progress({
  717. 'downloaded_bytes': byte_counter,
  718. 'total_bytes': byte_counter,
  719. 'filename': filename,
  720. 'status': 'finished',
  721. })
  722. return True
  723. def _hook_progress(self, status):
  724. for ph in self._progress_hooks:
  725. ph(status)
  726. def add_progress_hook(self, ph):
  727. """ ph gets called on download progress, with a dictionary with the entries
  728. * filename: The final filename
  729. * status: One of "downloading" and "finished"
  730. It can also have some of the following entries:
  731. * downloaded_bytes: Bytes on disks
  732. * total_bytes: Total bytes, None if unknown
  733. * tmpfilename: The filename we're currently writing to
  734. Hooks are guaranteed to be called at least once (with status "finished")
  735. if the download is successful.
  736. """
  737. self._progress_hooks.append(ph)