FileDownloader.py 38 KB

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