FileDownloader.py 42 KB

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