You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

979 lines
42 KiB

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