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.

981 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() and os.name != 'nt':
  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() and os.name != 'nt':
  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.report_error(u'Erroneous output template')
  359. return None
  360. except ValueError as err:
  361. self.report_error(u'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. if ie_results is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  402. break
  403. results = []
  404. for ie_result in ie_results:
  405. if not 'extractor' in ie_result:
  406. #The extractor has already been set somewhere else
  407. ie_result['extractor'] = ie.IE_NAME
  408. results.append(self.process_ie_result(ie_result, download))
  409. return results
  410. except ExtractorError as de: # An error we somewhat expected
  411. self.report_error(compat_str(de), de.format_traceback())
  412. break
  413. except Exception as e:
  414. if self.params.get('ignoreerrors', False):
  415. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  416. break
  417. else:
  418. raise
  419. if not suitable_found:
  420. self.report_error(u'no suitable InfoExtractor: %s' % url)
  421. def process_ie_result(self, ie_result, download = True):
  422. """
  423. Take the result of the ie and return a list of videos.
  424. For url elements it will search the suitable ie and get the videos
  425. For playlist elements it will process each of the elements of the 'entries' key
  426. It will also download the videos if 'download'.
  427. """
  428. result_type = ie_result.get('_type', 'video') #If not given we suppose it's a video, support the dafault old system
  429. if result_type == 'video':
  430. if 'playlist' not in ie_result:
  431. #It isn't part of a playlist
  432. ie_result['playlist'] = None
  433. ie_result['playlist_index'] = None
  434. if download:
  435. #Do the download:
  436. self.process_info(ie_result)
  437. return ie_result
  438. elif result_type == 'url':
  439. #We get the video pointed by the url
  440. result = self.extract_info(ie_result['url'], download, ie_name = ie_result['ie_key'])[0]
  441. return result
  442. elif result_type == 'playlist':
  443. #We process each entry in the playlist
  444. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  445. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  446. playlist_results = []
  447. n_all_entries = len(ie_result['entries'])
  448. playliststart = self.params.get('playliststart', 1) - 1
  449. playlistend = self.params.get('playlistend', -1)
  450. if playlistend == -1:
  451. entries = ie_result['entries'][playliststart:]
  452. else:
  453. entries = ie_result['entries'][playliststart:playlistend]
  454. n_entries = len(entries)
  455. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  456. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  457. for i,entry in enumerate(entries,1):
  458. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  459. entry_result = self.process_ie_result(entry, False)
  460. entry_result['playlist'] = playlist
  461. entry_result['playlist_index'] = i + playliststart
  462. #We must do the download here to correctly set the 'playlist' key
  463. if download:
  464. self.process_info(entry_result)
  465. playlist_results.append(entry_result)
  466. result = ie_result.copy()
  467. result['entries'] = playlist_results
  468. return result
  469. def process_info(self, info_dict):
  470. """Process a single dictionary returned by an InfoExtractor."""
  471. #We increment the download the download count here to match the previous behaviour.
  472. self.increment_downloads()
  473. info_dict['fulltitle'] = info_dict['title']
  474. if len(info_dict['title']) > 200:
  475. info_dict['title'] = info_dict['title'][:197] + u'...'
  476. # Keep for backwards compatibility
  477. info_dict['stitle'] = info_dict['title']
  478. if not 'format' in info_dict:
  479. info_dict['format'] = info_dict['ext']
  480. reason = self._match_entry(info_dict)
  481. if reason is not None:
  482. self.to_screen(u'[download] ' + reason)
  483. return
  484. max_downloads = self.params.get('max_downloads')
  485. if max_downloads is not None:
  486. if self._num_downloads > int(max_downloads):
  487. raise MaxDownloadsReached()
  488. filename = self.prepare_filename(info_dict)
  489. # Forced printings
  490. if self.params.get('forcetitle', False):
  491. compat_print(info_dict['title'])
  492. if self.params.get('forceurl', False):
  493. compat_print(info_dict['url'])
  494. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  495. compat_print(info_dict['thumbnail'])
  496. if self.params.get('forcedescription', False) and 'description' in info_dict:
  497. compat_print(info_dict['description'])
  498. if self.params.get('forcefilename', False) and filename is not None:
  499. compat_print(filename)
  500. if self.params.get('forceformat', False):
  501. compat_print(info_dict['format'])
  502. # Do nothing else if in simulate mode
  503. if self.params.get('simulate', False):
  504. return
  505. if filename is None:
  506. return
  507. try:
  508. dn = os.path.dirname(encodeFilename(filename))
  509. if dn != '' and not os.path.exists(dn): # dn is already encoded
  510. os.makedirs(dn)
  511. except (OSError, IOError) as err:
  512. self.report_error(u'unable to create directory ' + compat_str(err))
  513. return
  514. if self.params.get('writedescription', False):
  515. try:
  516. descfn = filename + u'.description'
  517. self.report_writedescription(descfn)
  518. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  519. descfile.write(info_dict['description'])
  520. except (OSError, IOError):
  521. self.report_error(u'Cannot write description file ' + descfn)
  522. return
  523. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  524. # subtitles download errors are already managed as troubles in relevant IE
  525. # that way it will silently go on when used with unsupporting IE
  526. subtitle = info_dict['subtitles'][0]
  527. (sub_error, sub_lang, sub) = subtitle
  528. sub_format = self.params.get('subtitlesformat')
  529. if sub_error:
  530. self.report_warning("Some error while getting the subtitles")
  531. else:
  532. try:
  533. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  534. self.report_writesubtitles(sub_filename)
  535. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  536. subfile.write(sub)
  537. except (OSError, IOError):
  538. self.report_error(u'Cannot write subtitles file ' + descfn)
  539. return
  540. if self.params.get('onlysubtitles', False):
  541. return
  542. if self.params.get('allsubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  543. subtitles = info_dict['subtitles']
  544. sub_format = self.params.get('subtitlesformat')
  545. for subtitle in subtitles:
  546. (sub_error, sub_lang, sub) = subtitle
  547. if sub_error:
  548. self.report_warning("Some error while getting the subtitles")
  549. else:
  550. try:
  551. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  552. self.report_writesubtitles(sub_filename)
  553. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  554. subfile.write(sub)
  555. except (OSError, IOError):
  556. self.report_error(u'Cannot write subtitles file ' + descfn)
  557. return
  558. if self.params.get('onlysubtitles', False):
  559. return
  560. if self.params.get('writeinfojson', False):
  561. infofn = filename + u'.info.json'
  562. self.report_writeinfojson(infofn)
  563. try:
  564. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  565. write_json_file(json_info_dict, encodeFilename(infofn))
  566. except (OSError, IOError):
  567. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  568. return
  569. if not self.params.get('skip_download', False):
  570. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  571. success = True
  572. else:
  573. try:
  574. success = self._do_download(filename, info_dict)
  575. except (OSError, IOError) as err:
  576. raise UnavailableVideoError()
  577. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  578. self.report_error(u'unable to download video data: %s' % str(err))
  579. return
  580. except (ContentTooShortError, ) as err:
  581. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  582. return
  583. if success:
  584. try:
  585. self.post_process(filename, info_dict)
  586. except (PostProcessingError) as err:
  587. self.report_error(u'postprocessing: %s' % str(err))
  588. return
  589. def download(self, url_list):
  590. """Download a given list of URLs."""
  591. if len(url_list) > 1 and self.fixed_template():
  592. raise SameFileError(self.params['outtmpl'])
  593. for url in url_list:
  594. try:
  595. #It also downloads the videos
  596. videos = self.extract_info(url)
  597. except UnavailableVideoError:
  598. self.report_error(u'unable to download video')
  599. except MaxDownloadsReached:
  600. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  601. raise
  602. return self._download_retcode
  603. def post_process(self, filename, ie_info):
  604. """Run all the postprocessors on the given file."""
  605. info = dict(ie_info)
  606. info['filepath'] = filename
  607. keep_video = None
  608. for pp in self._pps:
  609. try:
  610. keep_video_wish,new_info = pp.run(info)
  611. if keep_video_wish is not None:
  612. if keep_video_wish:
  613. keep_video = keep_video_wish
  614. elif keep_video is None:
  615. # No clear decision yet, let IE decide
  616. keep_video = keep_video_wish
  617. except PostProcessingError as e:
  618. self.to_stderr(u'ERROR: ' + e.msg)
  619. if keep_video is False and not self.params.get('keepvideo', False):
  620. try:
  621. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  622. os.remove(encodeFilename(filename))
  623. except (IOError, OSError):
  624. self.report_warning(u'Unable to remove downloaded video file')
  625. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path):
  626. self.report_destination(filename)
  627. tmpfilename = self.temp_name(filename)
  628. # Check for rtmpdump first
  629. try:
  630. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  631. except (OSError, IOError):
  632. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  633. return False
  634. # Download using rtmpdump. rtmpdump returns exit code 2 when
  635. # the connection was interrumpted and resuming appears to be
  636. # possible. This is part of rtmpdump's normal usage, AFAIK.
  637. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  638. if player_url is not None:
  639. basic_args += ['-W', player_url]
  640. if page_url is not None:
  641. basic_args += ['--pageUrl', page_url]
  642. if play_path is not None:
  643. basic_args += ['-y', play_path]
  644. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  645. if self.params.get('verbose', False):
  646. try:
  647. import pipes
  648. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  649. except ImportError:
  650. shell_quote = repr
  651. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  652. retval = subprocess.call(args)
  653. while retval == 2 or retval == 1:
  654. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  655. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  656. time.sleep(5.0) # This seems to be needed
  657. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  658. cursize = os.path.getsize(encodeFilename(tmpfilename))
  659. if prevsize == cursize and retval == 1:
  660. break
  661. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  662. if prevsize == cursize and retval == 2 and cursize > 1024:
  663. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  664. retval = 0
  665. break
  666. if retval == 0:
  667. fsize = os.path.getsize(encodeFilename(tmpfilename))
  668. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  669. self.try_rename(tmpfilename, filename)
  670. self._hook_progress({
  671. 'downloaded_bytes': fsize,
  672. 'total_bytes': fsize,
  673. 'filename': filename,
  674. 'status': 'finished',
  675. })
  676. return True
  677. else:
  678. self.to_stderr(u"\n")
  679. self.report_error(u'rtmpdump exited with code %d' % retval)
  680. return False
  681. def _do_download(self, filename, info_dict):
  682. url = info_dict['url']
  683. # Check file already present
  684. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  685. self.report_file_already_downloaded(filename)
  686. self._hook_progress({
  687. 'filename': filename,
  688. 'status': 'finished',
  689. })
  690. return True
  691. # Attempt to download using rtmpdump
  692. if url.startswith('rtmp'):
  693. return self._download_with_rtmpdump(filename, url,
  694. info_dict.get('player_url', None),
  695. info_dict.get('page_url', None),
  696. info_dict.get('play_path', None))
  697. tmpfilename = self.temp_name(filename)
  698. stream = None
  699. # Do not include the Accept-Encoding header
  700. headers = {'Youtubedl-no-compression': 'True'}
  701. if 'user_agent' in info_dict:
  702. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  703. basic_request = compat_urllib_request.Request(url, None, headers)
  704. request = compat_urllib_request.Request(url, None, headers)
  705. if self.params.get('test', False):
  706. request.add_header('Range','bytes=0-10240')
  707. # Establish possible resume length
  708. if os.path.isfile(encodeFilename(tmpfilename)):
  709. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  710. else:
  711. resume_len = 0
  712. open_mode = 'wb'
  713. if resume_len != 0:
  714. if self.params.get('continuedl', False):
  715. self.report_resuming_byte(resume_len)
  716. request.add_header('Range','bytes=%d-' % resume_len)
  717. open_mode = 'ab'
  718. else:
  719. resume_len = 0
  720. count = 0
  721. retries = self.params.get('retries', 0)
  722. while count <= retries:
  723. # Establish connection
  724. try:
  725. if count == 0 and 'urlhandle' in info_dict:
  726. data = info_dict['urlhandle']
  727. data = compat_urllib_request.urlopen(request)
  728. break
  729. except (compat_urllib_error.HTTPError, ) as err:
  730. if (err.code < 500 or err.code >= 600) and err.code != 416:
  731. # Unexpected HTTP error
  732. raise
  733. elif err.code == 416:
  734. # Unable to resume (requested range not satisfiable)
  735. try:
  736. # Open the connection again without the range header
  737. data = compat_urllib_request.urlopen(basic_request)
  738. content_length = data.info()['Content-Length']
  739. except (compat_urllib_error.HTTPError, ) as err:
  740. if err.code < 500 or err.code >= 600:
  741. raise
  742. else:
  743. # Examine the reported length
  744. if (content_length is not None and
  745. (resume_len - 100 < int(content_length) < resume_len + 100)):
  746. # The file had already been fully downloaded.
  747. # Explanation to the above condition: in issue #175 it was revealed that
  748. # YouTube sometimes adds or removes a few bytes from the end of the file,
  749. # changing the file size slightly and causing problems for some users. So
  750. # I decided to implement a suggested change and consider the file
  751. # completely downloaded if the file size differs less than 100 bytes from
  752. # the one in the hard drive.
  753. self.report_file_already_downloaded(filename)
  754. self.try_rename(tmpfilename, filename)
  755. self._hook_progress({
  756. 'filename': filename,
  757. 'status': 'finished',
  758. })
  759. return True
  760. else:
  761. # The length does not match, we start the download over
  762. self.report_unable_to_resume()
  763. open_mode = 'wb'
  764. break
  765. # Retry
  766. count += 1
  767. if count <= retries:
  768. self.report_retry(count, retries)
  769. if count > retries:
  770. self.report_error(u'giving up after %s retries' % retries)
  771. return False
  772. data_len = data.info().get('Content-length', None)
  773. if data_len is not None:
  774. data_len = int(data_len) + resume_len
  775. min_data_len = self.params.get("min_filesize", None)
  776. max_data_len = self.params.get("max_filesize", None)
  777. if min_data_len is not None and data_len < min_data_len:
  778. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  779. return False
  780. if max_data_len is not None and data_len > max_data_len:
  781. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  782. return False
  783. data_len_str = self.format_bytes(data_len)
  784. byte_counter = 0 + resume_len
  785. block_size = self.params.get('buffersize', 1024)
  786. start = time.time()
  787. while True:
  788. # Download and write
  789. before = time.time()
  790. data_block = data.read(block_size)
  791. after = time.time()
  792. if len(data_block) == 0:
  793. break
  794. byte_counter += len(data_block)
  795. # Open file just in time
  796. if stream is None:
  797. try:
  798. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  799. assert stream is not None
  800. filename = self.undo_temp_name(tmpfilename)
  801. self.report_destination(filename)
  802. except (OSError, IOError) as err:
  803. self.report_error(u'unable to open for writing: %s' % str(err))
  804. return False
  805. try:
  806. stream.write(data_block)
  807. except (IOError, OSError) as err:
  808. self.to_stderr(u"\n")
  809. self.report_error(u'unable to write data: %s' % str(err))
  810. return False
  811. if not self.params.get('noresizebuffer', False):
  812. block_size = self.best_block_size(after - before, len(data_block))
  813. # Progress message
  814. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  815. if data_len is None:
  816. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  817. else:
  818. percent_str = self.calc_percent(byte_counter, data_len)
  819. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  820. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  821. self._hook_progress({
  822. 'downloaded_bytes': byte_counter,
  823. 'total_bytes': data_len,
  824. 'tmpfilename': tmpfilename,
  825. 'filename': filename,
  826. 'status': 'downloading',
  827. })
  828. # Apply rate limit
  829. self.slow_down(start, byte_counter - resume_len)
  830. if stream is None:
  831. self.to_stderr(u"\n")
  832. self.report_error(u'Did not get any data blocks')
  833. return False
  834. stream.close()
  835. self.report_finish()
  836. if data_len is not None and byte_counter != data_len:
  837. raise ContentTooShortError(byte_counter, int(data_len))
  838. self.try_rename(tmpfilename, filename)
  839. # Update file modification time
  840. if self.params.get('updatetime', True):
  841. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  842. self._hook_progress({
  843. 'downloaded_bytes': byte_counter,
  844. 'total_bytes': byte_counter,
  845. 'filename': filename,
  846. 'status': 'finished',
  847. })
  848. return True
  849. def _hook_progress(self, status):
  850. for ph in self._progress_hooks:
  851. ph(status)
  852. def add_progress_hook(self, ph):
  853. """ ph gets called on download progress, with a dictionary with the entries
  854. * filename: The final filename
  855. * status: One of "downloading" and "finished"
  856. It can also have some of the following entries:
  857. * downloaded_bytes: Bytes on disks
  858. * total_bytes: Total bytes, None if unknown
  859. * tmpfilename: The filename we're currently writing to
  860. Hooks are guaranteed to be called at least once (with status "finished")
  861. if the download is successful.
  862. """
  863. self._progress_hooks.append(ph)