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.

1587 lines
69 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import datetime
  6. import errno
  7. import io
  8. import itertools
  9. import json
  10. import locale
  11. import operator
  12. import os
  13. import platform
  14. import re
  15. import shutil
  16. import subprocess
  17. import socket
  18. import sys
  19. import time
  20. import traceback
  21. if os.name == 'nt':
  22. import ctypes
  23. from .compat import (
  24. compat_cookiejar,
  25. compat_expanduser,
  26. compat_http_client,
  27. compat_kwargs,
  28. compat_str,
  29. compat_urllib_error,
  30. compat_urllib_request,
  31. )
  32. from .utils import (
  33. escape_url,
  34. ContentTooShortError,
  35. date_from_str,
  36. DateRange,
  37. DEFAULT_OUTTMPL,
  38. determine_ext,
  39. DownloadError,
  40. encodeFilename,
  41. ExtractorError,
  42. format_bytes,
  43. formatSeconds,
  44. get_term_width,
  45. locked_file,
  46. make_HTTPS_handler,
  47. MaxDownloadsReached,
  48. PagedList,
  49. parse_filesize,
  50. PostProcessingError,
  51. platform_name,
  52. preferredencoding,
  53. SameFileError,
  54. sanitize_filename,
  55. subtitles_filename,
  56. takewhile_inclusive,
  57. UnavailableVideoError,
  58. url_basename,
  59. version_tuple,
  60. write_json_file,
  61. write_string,
  62. YoutubeDLHandler,
  63. prepend_extension,
  64. args_to_str,
  65. age_restricted,
  66. )
  67. from .cache import Cache
  68. from .extractor import get_info_extractor, gen_extractors
  69. from .downloader import get_suitable_downloader
  70. from .downloader.rtmp import rtmpdump_version
  71. from .postprocessor import (
  72. FFmpegFixupStretchedPP,
  73. FFmpegMergerPP,
  74. FFmpegPostProcessor,
  75. get_postprocessor,
  76. )
  77. from .version import __version__
  78. class YoutubeDL(object):
  79. """YoutubeDL class.
  80. YoutubeDL objects are the ones responsible of downloading the
  81. actual video file and writing it to disk if the user has requested
  82. it, among some other tasks. In most cases there should be one per
  83. program. As, given a video URL, the downloader doesn't know how to
  84. extract all the needed information, task that InfoExtractors do, it
  85. has to pass the URL to one of them.
  86. For this, YoutubeDL objects have a method that allows
  87. InfoExtractors to be registered in a given order. When it is passed
  88. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  89. finds that reports being able to handle it. The InfoExtractor extracts
  90. all the information about the video or videos the URL refers to, and
  91. YoutubeDL process the extracted information, possibly using a File
  92. Downloader to download the video.
  93. YoutubeDL objects accept a lot of parameters. In order not to saturate
  94. the object constructor with arguments, it receives a dictionary of
  95. options instead. These options are available through the params
  96. attribute for the InfoExtractors to use. The YoutubeDL also
  97. registers itself as the downloader in charge for the InfoExtractors
  98. that are added to it, so this is a "mutual registration".
  99. Available options:
  100. username: Username for authentication purposes.
  101. password: Password for authentication purposes.
  102. videopassword: Password for acces a video.
  103. usenetrc: Use netrc for authentication instead.
  104. verbose: Print additional info to stdout.
  105. quiet: Do not print messages to stdout.
  106. no_warnings: Do not print out anything for warnings.
  107. forceurl: Force printing final URL.
  108. forcetitle: Force printing title.
  109. forceid: Force printing ID.
  110. forcethumbnail: Force printing thumbnail URL.
  111. forcedescription: Force printing description.
  112. forcefilename: Force printing final filename.
  113. forceduration: Force printing duration.
  114. forcejson: Force printing info_dict as JSON.
  115. dump_single_json: Force printing the info_dict of the whole playlist
  116. (or video) as a single JSON line.
  117. simulate: Do not download the video files.
  118. format: Video format code. See options.py for more information.
  119. format_limit: Highest quality format to try.
  120. outtmpl: Template for output names.
  121. restrictfilenames: Do not allow "&" and spaces in file names
  122. ignoreerrors: Do not stop on download errors.
  123. nooverwrites: Prevent overwriting files.
  124. playliststart: Playlist item to start at.
  125. playlistend: Playlist item to end at.
  126. playlistreverse: Download playlist items in reverse order.
  127. matchtitle: Download only matching titles.
  128. rejecttitle: Reject downloads for matching titles.
  129. logger: Log messages to a logging.Logger instance.
  130. logtostderr: Log messages to stderr instead of stdout.
  131. writedescription: Write the video description to a .description file
  132. writeinfojson: Write the video description to a .info.json file
  133. writeannotations: Write the video annotations to a .annotations.xml file
  134. writethumbnail: Write the thumbnail image to a file
  135. writesubtitles: Write the video subtitles to a file
  136. writeautomaticsub: Write the automatic subtitles to a file
  137. allsubtitles: Downloads all the subtitles of the video
  138. (requires writesubtitles or writeautomaticsub)
  139. listsubtitles: Lists all available subtitles for the video
  140. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  141. subtitleslangs: List of languages of the subtitles to download
  142. keepvideo: Keep the video file after post-processing
  143. daterange: A DateRange object, download only if the upload_date is in the range.
  144. skip_download: Skip the actual download of the video file
  145. cachedir: Location of the cache files in the filesystem.
  146. False to disable filesystem cache.
  147. noplaylist: Download single video instead of a playlist if in doubt.
  148. age_limit: An integer representing the user's age in years.
  149. Unsuitable videos for the given age are skipped.
  150. min_views: An integer representing the minimum view count the video
  151. must have in order to not be skipped.
  152. Videos without view count information are always
  153. downloaded. None for no limit.
  154. max_views: An integer representing the maximum view count.
  155. Videos that are more popular than that are not
  156. downloaded.
  157. Videos without view count information are always
  158. downloaded. None for no limit.
  159. download_archive: File name of a file where all downloads are recorded.
  160. Videos already present in the file are not downloaded
  161. again.
  162. cookiefile: File name where cookies should be read from and dumped to.
  163. nocheckcertificate:Do not verify SSL certificates
  164. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  165. At the moment, this is only supported by YouTube.
  166. proxy: URL of the proxy server to use
  167. socket_timeout: Time to wait for unresponsive hosts, in seconds
  168. bidi_workaround: Work around buggy terminals without bidirectional text
  169. support, using fridibi
  170. debug_printtraffic:Print out sent and received HTTP traffic
  171. include_ads: Download ads as well
  172. default_search: Prepend this string if an input url is not valid.
  173. 'auto' for elaborate guessing
  174. encoding: Use this encoding instead of the system-specified.
  175. extract_flat: Do not resolve URLs, return the immediate result.
  176. Pass in 'in_playlist' to only show this behavior for
  177. playlist items.
  178. postprocessors: A list of dictionaries, each with an entry
  179. * key: The name of the postprocessor. See
  180. youtube_dl/postprocessor/__init__.py for a list.
  181. as well as any further keyword arguments for the
  182. postprocessor.
  183. progress_hooks: A list of functions that get called on download
  184. progress, with a dictionary with the entries
  185. * filename: The final filename
  186. * status: One of "downloading" and "finished"
  187. The dict may also have some of the following entries:
  188. * downloaded_bytes: Bytes on disk
  189. * total_bytes: Size of the whole file, None if unknown
  190. * tmpfilename: The filename we're currently writing to
  191. * eta: The estimated time in seconds, None if unknown
  192. * speed: The download speed in bytes/second, None if
  193. unknown
  194. Progress hooks are guaranteed to be called at least once
  195. (with status "finished") if the download is successful.
  196. merge_output_format: Extension to use when merging formats.
  197. fixup: Automatically correct known faults of the file.
  198. One of:
  199. - "never": do nothing
  200. - "warn": only emit a warning
  201. - "detect_or_warn": check whether we can do anything
  202. about it, warn otherwise
  203. source_address: (Experimental) Client-side IP address to bind to.
  204. call_home: Boolean, true iff we are allowed to contact the
  205. youtube-dl servers for debugging.
  206. The following parameters are not used by YoutubeDL itself, they are used by
  207. the FileDownloader:
  208. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  209. noresizebuffer, retries, continuedl, noprogress, consoletitle
  210. The following options are used by the post processors:
  211. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  212. otherwise prefer avconv.
  213. exec_cmd: Arbitrary command to run after downloading
  214. """
  215. params = None
  216. _ies = []
  217. _pps = []
  218. _download_retcode = None
  219. _num_downloads = None
  220. _screen_file = None
  221. def __init__(self, params=None, auto_init=True):
  222. """Create a FileDownloader object with the given options."""
  223. if params is None:
  224. params = {}
  225. self._ies = []
  226. self._ies_instances = {}
  227. self._pps = []
  228. self._progress_hooks = []
  229. self._download_retcode = 0
  230. self._num_downloads = 0
  231. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  232. self._err_file = sys.stderr
  233. self.params = params
  234. self.cache = Cache(self)
  235. if params.get('bidi_workaround', False):
  236. try:
  237. import pty
  238. master, slave = pty.openpty()
  239. width = get_term_width()
  240. if width is None:
  241. width_args = []
  242. else:
  243. width_args = ['-w', str(width)]
  244. sp_kwargs = dict(
  245. stdin=subprocess.PIPE,
  246. stdout=slave,
  247. stderr=self._err_file)
  248. try:
  249. self._output_process = subprocess.Popen(
  250. ['bidiv'] + width_args, **sp_kwargs
  251. )
  252. except OSError:
  253. self._output_process = subprocess.Popen(
  254. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  255. self._output_channel = os.fdopen(master, 'rb')
  256. except OSError as ose:
  257. if ose.errno == 2:
  258. self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  259. else:
  260. raise
  261. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  262. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  263. and not params.get('restrictfilenames', False)):
  264. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  265. self.report_warning(
  266. 'Assuming --restrict-filenames since file system encoding '
  267. 'cannot encode all characters. '
  268. 'Set the LC_ALL environment variable to fix this.')
  269. self.params['restrictfilenames'] = True
  270. if '%(stitle)s' in self.params.get('outtmpl', ''):
  271. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  272. self._setup_opener()
  273. if auto_init:
  274. self.print_debug_header()
  275. self.add_default_info_extractors()
  276. for pp_def_raw in self.params.get('postprocessors', []):
  277. pp_class = get_postprocessor(pp_def_raw['key'])
  278. pp_def = dict(pp_def_raw)
  279. del pp_def['key']
  280. pp = pp_class(self, **compat_kwargs(pp_def))
  281. self.add_post_processor(pp)
  282. for ph in self.params.get('progress_hooks', []):
  283. self.add_progress_hook(ph)
  284. def warn_if_short_id(self, argv):
  285. # short YouTube ID starting with dash?
  286. idxs = [
  287. i for i, a in enumerate(argv)
  288. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  289. if idxs:
  290. correct_argv = (
  291. ['youtube-dl'] +
  292. [a for i, a in enumerate(argv) if i not in idxs] +
  293. ['--'] + [argv[i] for i in idxs]
  294. )
  295. self.report_warning(
  296. 'Long argument string detected. '
  297. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  298. args_to_str(correct_argv))
  299. def add_info_extractor(self, ie):
  300. """Add an InfoExtractor object to the end of the list."""
  301. self._ies.append(ie)
  302. self._ies_instances[ie.ie_key()] = ie
  303. ie.set_downloader(self)
  304. def get_info_extractor(self, ie_key):
  305. """
  306. Get an instance of an IE with name ie_key, it will try to get one from
  307. the _ies list, if there's no instance it will create a new one and add
  308. it to the extractor list.
  309. """
  310. ie = self._ies_instances.get(ie_key)
  311. if ie is None:
  312. ie = get_info_extractor(ie_key)()
  313. self.add_info_extractor(ie)
  314. return ie
  315. def add_default_info_extractors(self):
  316. """
  317. Add the InfoExtractors returned by gen_extractors to the end of the list
  318. """
  319. for ie in gen_extractors():
  320. self.add_info_extractor(ie)
  321. def add_post_processor(self, pp):
  322. """Add a PostProcessor object to the end of the chain."""
  323. self._pps.append(pp)
  324. pp.set_downloader(self)
  325. def add_progress_hook(self, ph):
  326. """Add the progress hook (currently only for the file downloader)"""
  327. self._progress_hooks.append(ph)
  328. def _bidi_workaround(self, message):
  329. if not hasattr(self, '_output_channel'):
  330. return message
  331. assert hasattr(self, '_output_process')
  332. assert isinstance(message, compat_str)
  333. line_count = message.count('\n') + 1
  334. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  335. self._output_process.stdin.flush()
  336. res = ''.join(self._output_channel.readline().decode('utf-8')
  337. for _ in range(line_count))
  338. return res[:-len('\n')]
  339. def to_screen(self, message, skip_eol=False):
  340. """Print message to stdout if not in quiet mode."""
  341. return self.to_stdout(message, skip_eol, check_quiet=True)
  342. def _write_string(self, s, out=None):
  343. write_string(s, out=out, encoding=self.params.get('encoding'))
  344. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  345. """Print message to stdout if not in quiet mode."""
  346. if self.params.get('logger'):
  347. self.params['logger'].debug(message)
  348. elif not check_quiet or not self.params.get('quiet', False):
  349. message = self._bidi_workaround(message)
  350. terminator = ['\n', ''][skip_eol]
  351. output = message + terminator
  352. self._write_string(output, self._screen_file)
  353. def to_stderr(self, message):
  354. """Print message to stderr."""
  355. assert isinstance(message, compat_str)
  356. if self.params.get('logger'):
  357. self.params['logger'].error(message)
  358. else:
  359. message = self._bidi_workaround(message)
  360. output = message + '\n'
  361. self._write_string(output, self._err_file)
  362. def to_console_title(self, message):
  363. if not self.params.get('consoletitle', False):
  364. return
  365. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  366. # c_wchar_p() might not be necessary if `message` is
  367. # already of type unicode()
  368. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  369. elif 'TERM' in os.environ:
  370. self._write_string('\033]0;%s\007' % message, self._screen_file)
  371. def save_console_title(self):
  372. if not self.params.get('consoletitle', False):
  373. return
  374. if 'TERM' in os.environ:
  375. # Save the title on stack
  376. self._write_string('\033[22;0t', self._screen_file)
  377. def restore_console_title(self):
  378. if not self.params.get('consoletitle', False):
  379. return
  380. if 'TERM' in os.environ:
  381. # Restore the title from stack
  382. self._write_string('\033[23;0t', self._screen_file)
  383. def __enter__(self):
  384. self.save_console_title()
  385. return self
  386. def __exit__(self, *args):
  387. self.restore_console_title()
  388. if self.params.get('cookiefile') is not None:
  389. self.cookiejar.save()
  390. def trouble(self, message=None, tb=None):
  391. """Determine action to take when a download problem appears.
  392. Depending on if the downloader has been configured to ignore
  393. download errors or not, this method may throw an exception or
  394. not when errors are found, after printing the message.
  395. tb, if given, is additional traceback information.
  396. """
  397. if message is not None:
  398. self.to_stderr(message)
  399. if self.params.get('verbose'):
  400. if tb is None:
  401. if sys.exc_info()[0]: # if .trouble has been called from an except block
  402. tb = ''
  403. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  404. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  405. tb += compat_str(traceback.format_exc())
  406. else:
  407. tb_data = traceback.format_list(traceback.extract_stack())
  408. tb = ''.join(tb_data)
  409. self.to_stderr(tb)
  410. if not self.params.get('ignoreerrors', False):
  411. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  412. exc_info = sys.exc_info()[1].exc_info
  413. else:
  414. exc_info = sys.exc_info()
  415. raise DownloadError(message, exc_info)
  416. self._download_retcode = 1
  417. def report_warning(self, message):
  418. '''
  419. Print the message to stderr, it will be prefixed with 'WARNING:'
  420. If stderr is a tty file the 'WARNING:' will be colored
  421. '''
  422. if self.params.get('logger') is not None:
  423. self.params['logger'].warning(message)
  424. else:
  425. if self.params.get('no_warnings'):
  426. return
  427. if self._err_file.isatty() and os.name != 'nt':
  428. _msg_header = '\033[0;33mWARNING:\033[0m'
  429. else:
  430. _msg_header = 'WARNING:'
  431. warning_message = '%s %s' % (_msg_header, message)
  432. self.to_stderr(warning_message)
  433. def report_error(self, message, tb=None):
  434. '''
  435. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  436. in red if stderr is a tty file.
  437. '''
  438. if self._err_file.isatty() and os.name != 'nt':
  439. _msg_header = '\033[0;31mERROR:\033[0m'
  440. else:
  441. _msg_header = 'ERROR:'
  442. error_message = '%s %s' % (_msg_header, message)
  443. self.trouble(error_message, tb)
  444. def report_file_already_downloaded(self, file_name):
  445. """Report file has already been fully downloaded."""
  446. try:
  447. self.to_screen('[download] %s has already been downloaded' % file_name)
  448. except UnicodeEncodeError:
  449. self.to_screen('[download] The file has already been downloaded')
  450. def prepare_filename(self, info_dict):
  451. """Generate the output filename."""
  452. try:
  453. template_dict = dict(info_dict)
  454. template_dict['epoch'] = int(time.time())
  455. autonumber_size = self.params.get('autonumber_size')
  456. if autonumber_size is None:
  457. autonumber_size = 5
  458. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  459. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  460. if template_dict.get('playlist_index') is not None:
  461. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  462. if template_dict.get('resolution') is None:
  463. if template_dict.get('width') and template_dict.get('height'):
  464. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  465. elif template_dict.get('height'):
  466. template_dict['resolution'] = '%sp' % template_dict['height']
  467. elif template_dict.get('width'):
  468. template_dict['resolution'] = '?x%d' % template_dict['width']
  469. sanitize = lambda k, v: sanitize_filename(
  470. compat_str(v),
  471. restricted=self.params.get('restrictfilenames'),
  472. is_id=(k == 'id'))
  473. template_dict = dict((k, sanitize(k, v))
  474. for k, v in template_dict.items()
  475. if v is not None)
  476. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  477. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  478. tmpl = compat_expanduser(outtmpl)
  479. filename = tmpl % template_dict
  480. return filename
  481. except ValueError as err:
  482. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  483. return None
  484. def _match_entry(self, info_dict):
  485. """ Returns None iff the file should be downloaded """
  486. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  487. if 'title' in info_dict:
  488. # This can happen when we're just evaluating the playlist
  489. title = info_dict['title']
  490. matchtitle = self.params.get('matchtitle', False)
  491. if matchtitle:
  492. if not re.search(matchtitle, title, re.IGNORECASE):
  493. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  494. rejecttitle = self.params.get('rejecttitle', False)
  495. if rejecttitle:
  496. if re.search(rejecttitle, title, re.IGNORECASE):
  497. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  498. date = info_dict.get('upload_date', None)
  499. if date is not None:
  500. dateRange = self.params.get('daterange', DateRange())
  501. if date not in dateRange:
  502. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  503. view_count = info_dict.get('view_count', None)
  504. if view_count is not None:
  505. min_views = self.params.get('min_views')
  506. if min_views is not None and view_count < min_views:
  507. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  508. max_views = self.params.get('max_views')
  509. if max_views is not None and view_count > max_views:
  510. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  511. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  512. return 'Skipping "%s" because it is age restricted' % title
  513. if self.in_download_archive(info_dict):
  514. return '%s has already been recorded in archive' % video_title
  515. return None
  516. @staticmethod
  517. def add_extra_info(info_dict, extra_info):
  518. '''Set the keys from extra_info in info dict if they are missing'''
  519. for key, value in extra_info.items():
  520. info_dict.setdefault(key, value)
  521. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  522. process=True):
  523. '''
  524. Returns a list with a dictionary for each video we find.
  525. If 'download', also downloads the videos.
  526. extra_info is a dict containing the extra values to add to each result
  527. '''
  528. if ie_key:
  529. ies = [self.get_info_extractor(ie_key)]
  530. else:
  531. ies = self._ies
  532. for ie in ies:
  533. if not ie.suitable(url):
  534. continue
  535. if not ie.working():
  536. self.report_warning('The program functionality for this site has been marked as broken, '
  537. 'and will probably not work.')
  538. try:
  539. ie_result = ie.extract(url)
  540. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  541. break
  542. if isinstance(ie_result, list):
  543. # Backwards compatibility: old IE result format
  544. ie_result = {
  545. '_type': 'compat_list',
  546. 'entries': ie_result,
  547. }
  548. self.add_default_extra_info(ie_result, ie, url)
  549. if process:
  550. return self.process_ie_result(ie_result, download, extra_info)
  551. else:
  552. return ie_result
  553. except ExtractorError as de: # An error we somewhat expected
  554. self.report_error(compat_str(de), de.format_traceback())
  555. break
  556. except MaxDownloadsReached:
  557. raise
  558. except Exception as e:
  559. if self.params.get('ignoreerrors', False):
  560. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  561. break
  562. else:
  563. raise
  564. else:
  565. self.report_error('no suitable InfoExtractor for URL %s' % url)
  566. def add_default_extra_info(self, ie_result, ie, url):
  567. self.add_extra_info(ie_result, {
  568. 'extractor': ie.IE_NAME,
  569. 'webpage_url': url,
  570. 'webpage_url_basename': url_basename(url),
  571. 'extractor_key': ie.ie_key(),
  572. })
  573. def process_ie_result(self, ie_result, download=True, extra_info={}):
  574. """
  575. Take the result of the ie(may be modified) and resolve all unresolved
  576. references (URLs, playlist items).
  577. It will also download the videos if 'download'.
  578. Returns the resolved ie_result.
  579. """
  580. result_type = ie_result.get('_type', 'video')
  581. if result_type in ('url', 'url_transparent'):
  582. extract_flat = self.params.get('extract_flat', False)
  583. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  584. extract_flat is True):
  585. if self.params.get('forcejson', False):
  586. self.to_stdout(json.dumps(ie_result))
  587. return ie_result
  588. if result_type == 'video':
  589. self.add_extra_info(ie_result, extra_info)
  590. return self.process_video_result(ie_result, download=download)
  591. elif result_type == 'url':
  592. # We have to add extra_info to the results because it may be
  593. # contained in a playlist
  594. return self.extract_info(ie_result['url'],
  595. download,
  596. ie_key=ie_result.get('ie_key'),
  597. extra_info=extra_info)
  598. elif result_type == 'url_transparent':
  599. # Use the information from the embedding page
  600. info = self.extract_info(
  601. ie_result['url'], ie_key=ie_result.get('ie_key'),
  602. extra_info=extra_info, download=False, process=False)
  603. force_properties = dict(
  604. (k, v) for k, v in ie_result.items() if v is not None)
  605. for f in ('_type', 'url'):
  606. if f in force_properties:
  607. del force_properties[f]
  608. new_result = info.copy()
  609. new_result.update(force_properties)
  610. assert new_result.get('_type') != 'url_transparent'
  611. return self.process_ie_result(
  612. new_result, download=download, extra_info=extra_info)
  613. elif result_type == 'playlist' or result_type == 'multi_video':
  614. # We process each entry in the playlist
  615. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  616. self.to_screen('[download] Downloading playlist: %s' % playlist)
  617. playlist_results = []
  618. playliststart = self.params.get('playliststart', 1) - 1
  619. playlistend = self.params.get('playlistend', None)
  620. # For backwards compatibility, interpret -1 as whole list
  621. if playlistend == -1:
  622. playlistend = None
  623. ie_entries = ie_result['entries']
  624. if isinstance(ie_entries, list):
  625. n_all_entries = len(ie_entries)
  626. entries = ie_entries[playliststart:playlistend]
  627. n_entries = len(entries)
  628. self.to_screen(
  629. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  630. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  631. elif isinstance(ie_entries, PagedList):
  632. entries = ie_entries.getslice(
  633. playliststart, playlistend)
  634. n_entries = len(entries)
  635. self.to_screen(
  636. "[%s] playlist %s: Downloading %d videos" %
  637. (ie_result['extractor'], playlist, n_entries))
  638. else: # iterable
  639. entries = list(itertools.islice(
  640. ie_entries, playliststart, playlistend))
  641. n_entries = len(entries)
  642. self.to_screen(
  643. "[%s] playlist %s: Downloading %d videos" %
  644. (ie_result['extractor'], playlist, n_entries))
  645. if self.params.get('playlistreverse', False):
  646. entries = entries[::-1]
  647. for i, entry in enumerate(entries, 1):
  648. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  649. extra = {
  650. 'n_entries': n_entries,
  651. 'playlist': playlist,
  652. 'playlist_id': ie_result.get('id'),
  653. 'playlist_title': ie_result.get('title'),
  654. 'playlist_index': i + playliststart,
  655. 'extractor': ie_result['extractor'],
  656. 'webpage_url': ie_result['webpage_url'],
  657. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  658. 'extractor_key': ie_result['extractor_key'],
  659. }
  660. reason = self._match_entry(entry)
  661. if reason is not None:
  662. self.to_screen('[download] ' + reason)
  663. continue
  664. entry_result = self.process_ie_result(entry,
  665. download=download,
  666. extra_info=extra)
  667. playlist_results.append(entry_result)
  668. ie_result['entries'] = playlist_results
  669. return ie_result
  670. elif result_type == 'compat_list':
  671. self.report_warning(
  672. 'Extractor %s returned a compat_list result. '
  673. 'It needs to be updated.' % ie_result.get('extractor'))
  674. def _fixup(r):
  675. self.add_extra_info(
  676. r,
  677. {
  678. 'extractor': ie_result['extractor'],
  679. 'webpage_url': ie_result['webpage_url'],
  680. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  681. 'extractor_key': ie_result['extractor_key'],
  682. }
  683. )
  684. return r
  685. ie_result['entries'] = [
  686. self.process_ie_result(_fixup(r), download, extra_info)
  687. for r in ie_result['entries']
  688. ]
  689. return ie_result
  690. else:
  691. raise Exception('Invalid result type: %s' % result_type)
  692. def _apply_format_filter(self, format_spec, available_formats):
  693. " Returns a tuple of the remaining format_spec and filtered formats "
  694. OPERATORS = {
  695. '<': operator.lt,
  696. '<=': operator.le,
  697. '>': operator.gt,
  698. '>=': operator.ge,
  699. '=': operator.eq,
  700. '!=': operator.ne,
  701. }
  702. operator_rex = re.compile(r'''(?x)\s*\[
  703. (?P<key>width|height|tbr|abr|vbr|filesize)
  704. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  705. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  706. \]$
  707. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  708. m = operator_rex.search(format_spec)
  709. if not m:
  710. raise ValueError('Invalid format specification %r' % format_spec)
  711. try:
  712. comparison_value = int(m.group('value'))
  713. except ValueError:
  714. comparison_value = parse_filesize(m.group('value'))
  715. if comparison_value is None:
  716. comparison_value = parse_filesize(m.group('value') + 'B')
  717. if comparison_value is None:
  718. raise ValueError(
  719. 'Invalid value %r in format specification %r' % (
  720. m.group('value'), format_spec))
  721. op = OPERATORS[m.group('op')]
  722. def _filter(f):
  723. actual_value = f.get(m.group('key'))
  724. if actual_value is None:
  725. return m.group('none_inclusive')
  726. return op(actual_value, comparison_value)
  727. new_formats = [f for f in available_formats if _filter(f)]
  728. new_format_spec = format_spec[:-len(m.group(0))]
  729. if not new_format_spec:
  730. new_format_spec = 'best'
  731. return (new_format_spec, new_formats)
  732. def select_format(self, format_spec, available_formats):
  733. while format_spec.endswith(']'):
  734. format_spec, available_formats = self._apply_format_filter(
  735. format_spec, available_formats)
  736. if not available_formats:
  737. return None
  738. if format_spec == 'best' or format_spec is None:
  739. return available_formats[-1]
  740. elif format_spec == 'worst':
  741. return available_formats[0]
  742. elif format_spec == 'bestaudio':
  743. audio_formats = [
  744. f for f in available_formats
  745. if f.get('vcodec') == 'none']
  746. if audio_formats:
  747. return audio_formats[-1]
  748. elif format_spec == 'worstaudio':
  749. audio_formats = [
  750. f for f in available_formats
  751. if f.get('vcodec') == 'none']
  752. if audio_formats:
  753. return audio_formats[0]
  754. elif format_spec == 'bestvideo':
  755. video_formats = [
  756. f for f in available_formats
  757. if f.get('acodec') == 'none']
  758. if video_formats:
  759. return video_formats[-1]
  760. elif format_spec == 'worstvideo':
  761. video_formats = [
  762. f for f in available_formats
  763. if f.get('acodec') == 'none']
  764. if video_formats:
  765. return video_formats[0]
  766. else:
  767. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  768. if format_spec in extensions:
  769. filter_f = lambda f: f['ext'] == format_spec
  770. else:
  771. filter_f = lambda f: f['format_id'] == format_spec
  772. matches = list(filter(filter_f, available_formats))
  773. if matches:
  774. return matches[-1]
  775. return None
  776. def process_video_result(self, info_dict, download=True):
  777. assert info_dict.get('_type', 'video') == 'video'
  778. if 'id' not in info_dict:
  779. raise ExtractorError('Missing "id" field in extractor result')
  780. if 'title' not in info_dict:
  781. raise ExtractorError('Missing "title" field in extractor result')
  782. if 'playlist' not in info_dict:
  783. # It isn't part of a playlist
  784. info_dict['playlist'] = None
  785. info_dict['playlist_index'] = None
  786. thumbnails = info_dict.get('thumbnails')
  787. if thumbnails:
  788. thumbnails.sort(key=lambda t: (
  789. t.get('width'), t.get('height'), t.get('url')))
  790. for t in thumbnails:
  791. if 'width' in t and 'height' in t:
  792. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  793. if thumbnails and 'thumbnail' not in info_dict:
  794. info_dict['thumbnail'] = thumbnails[-1]['url']
  795. if 'display_id' not in info_dict and 'id' in info_dict:
  796. info_dict['display_id'] = info_dict['id']
  797. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  798. # Working around negative timestamps in Windows
  799. # (see http://bugs.python.org/issue1646728)
  800. if info_dict['timestamp'] < 0 and os.name == 'nt':
  801. info_dict['timestamp'] = 0
  802. upload_date = datetime.datetime.utcfromtimestamp(
  803. info_dict['timestamp'])
  804. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  805. # This extractors handle format selection themselves
  806. if info_dict['extractor'] in ['Youku']:
  807. if download:
  808. self.process_info(info_dict)
  809. return info_dict
  810. # We now pick which formats have to be downloaded
  811. if info_dict.get('formats') is None:
  812. # There's only one format available
  813. formats = [info_dict]
  814. else:
  815. formats = info_dict['formats']
  816. if not formats:
  817. raise ExtractorError('No video formats found!')
  818. # We check that all the formats have the format and format_id fields
  819. for i, format in enumerate(formats):
  820. if 'url' not in format:
  821. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  822. if format.get('format_id') is None:
  823. format['format_id'] = compat_str(i)
  824. if format.get('format') is None:
  825. format['format'] = '{id} - {res}{note}'.format(
  826. id=format['format_id'],
  827. res=self.format_resolution(format),
  828. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  829. )
  830. # Automatically determine file extension if missing
  831. if 'ext' not in format:
  832. format['ext'] = determine_ext(format['url']).lower()
  833. format_limit = self.params.get('format_limit', None)
  834. if format_limit:
  835. formats = list(takewhile_inclusive(
  836. lambda f: f['format_id'] != format_limit, formats
  837. ))
  838. # TODO Central sorting goes here
  839. if formats[0] is not info_dict:
  840. # only set the 'formats' fields if the original info_dict list them
  841. # otherwise we end up with a circular reference, the first (and unique)
  842. # element in the 'formats' field in info_dict is info_dict itself,
  843. # wich can't be exported to json
  844. info_dict['formats'] = formats
  845. if self.params.get('listformats', None):
  846. self.list_formats(info_dict)
  847. return
  848. req_format = self.params.get('format')
  849. if req_format is None:
  850. req_format = 'best'
  851. formats_to_download = []
  852. # The -1 is for supporting YoutubeIE
  853. if req_format in ('-1', 'all'):
  854. formats_to_download = formats
  855. else:
  856. for rfstr in req_format.split(','):
  857. # We can accept formats requested in the format: 34/5/best, we pick
  858. # the first that is available, starting from left
  859. req_formats = rfstr.split('/')
  860. for rf in req_formats:
  861. if re.match(r'.+?\+.+?', rf) is not None:
  862. # Two formats have been requested like '137+139'
  863. format_1, format_2 = rf.split('+')
  864. formats_info = (self.select_format(format_1, formats),
  865. self.select_format(format_2, formats))
  866. if all(formats_info):
  867. # The first format must contain the video and the
  868. # second the audio
  869. if formats_info[0].get('vcodec') == 'none':
  870. self.report_error('The first format must '
  871. 'contain the video, try using '
  872. '"-f %s+%s"' % (format_2, format_1))
  873. return
  874. output_ext = (
  875. formats_info[0]['ext']
  876. if self.params.get('merge_output_format') is None
  877. else self.params['merge_output_format'])
  878. selected_format = {
  879. 'requested_formats': formats_info,
  880. 'format': rf,
  881. 'ext': formats_info[0]['ext'],
  882. 'width': formats_info[0].get('width'),
  883. 'height': formats_info[0].get('height'),
  884. 'resolution': formats_info[0].get('resolution'),
  885. 'fps': formats_info[0].get('fps'),
  886. 'vcodec': formats_info[0].get('vcodec'),
  887. 'vbr': formats_info[0].get('vbr'),
  888. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  889. 'acodec': formats_info[1].get('acodec'),
  890. 'abr': formats_info[1].get('abr'),
  891. 'ext': output_ext,
  892. }
  893. else:
  894. selected_format = None
  895. else:
  896. selected_format = self.select_format(rf, formats)
  897. if selected_format is not None:
  898. formats_to_download.append(selected_format)
  899. break
  900. if not formats_to_download:
  901. raise ExtractorError('requested format not available',
  902. expected=True)
  903. if download:
  904. if len(formats_to_download) > 1:
  905. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  906. for format in formats_to_download:
  907. new_info = dict(info_dict)
  908. new_info.update(format)
  909. self.process_info(new_info)
  910. # We update the info dict with the best quality format (backwards compatibility)
  911. info_dict.update(formats_to_download[-1])
  912. return info_dict
  913. def process_info(self, info_dict):
  914. """Process a single resolved IE result."""
  915. assert info_dict.get('_type', 'video') == 'video'
  916. max_downloads = self.params.get('max_downloads')
  917. if max_downloads is not None:
  918. if self._num_downloads >= int(max_downloads):
  919. raise MaxDownloadsReached()
  920. info_dict['fulltitle'] = info_dict['title']
  921. if len(info_dict['title']) > 200:
  922. info_dict['title'] = info_dict['title'][:197] + '...'
  923. # Keep for backwards compatibility
  924. info_dict['stitle'] = info_dict['title']
  925. if 'format' not in info_dict:
  926. info_dict['format'] = info_dict['ext']
  927. reason = self._match_entry(info_dict)
  928. if reason is not None:
  929. self.to_screen('[download] ' + reason)
  930. return
  931. self._num_downloads += 1
  932. filename = self.prepare_filename(info_dict)
  933. # Forced printings
  934. if self.params.get('forcetitle', False):
  935. self.to_stdout(info_dict['fulltitle'])
  936. if self.params.get('forceid', False):
  937. self.to_stdout(info_dict['id'])
  938. if self.params.get('forceurl', False):
  939. if info_dict.get('requested_formats') is not None:
  940. for f in info_dict['requested_formats']:
  941. self.to_stdout(f['url'] + f.get('play_path', ''))
  942. else:
  943. # For RTMP URLs, also include the playpath
  944. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  945. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  946. self.to_stdout(info_dict['thumbnail'])
  947. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  948. self.to_stdout(info_dict['description'])
  949. if self.params.get('forcefilename', False) and filename is not None:
  950. self.to_stdout(filename)
  951. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  952. self.to_stdout(formatSeconds(info_dict['duration']))
  953. if self.params.get('forceformat', False):
  954. self.to_stdout(info_dict['format'])
  955. if self.params.get('forcejson', False):
  956. info_dict['_filename'] = filename
  957. self.to_stdout(json.dumps(info_dict))
  958. if self.params.get('dump_single_json', False):
  959. info_dict['_filename'] = filename
  960. # Do nothing else if in simulate mode
  961. if self.params.get('simulate', False):
  962. return
  963. if filename is None:
  964. return
  965. try:
  966. dn = os.path.dirname(encodeFilename(filename))
  967. if dn and not os.path.exists(dn):
  968. os.makedirs(dn)
  969. except (OSError, IOError) as err:
  970. self.report_error('unable to create directory ' + compat_str(err))
  971. return
  972. if self.params.get('writedescription', False):
  973. descfn = filename + '.description'
  974. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  975. self.to_screen('[info] Video description is already present')
  976. elif info_dict.get('description') is None:
  977. self.report_warning('There\'s no description to write.')
  978. else:
  979. try:
  980. self.to_screen('[info] Writing video description to: ' + descfn)
  981. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  982. descfile.write(info_dict['description'])
  983. except (OSError, IOError):
  984. self.report_error('Cannot write description file ' + descfn)
  985. return
  986. if self.params.get('writeannotations', False):
  987. annofn = filename + '.annotations.xml'
  988. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  989. self.to_screen('[info] Video annotations are already present')
  990. else:
  991. try:
  992. self.to_screen('[info] Writing video annotations to: ' + annofn)
  993. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  994. annofile.write(info_dict['annotations'])
  995. except (KeyError, TypeError):
  996. self.report_warning('There are no annotations to write.')
  997. except (OSError, IOError):
  998. self.report_error('Cannot write annotations file: ' + annofn)
  999. return
  1000. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1001. self.params.get('writeautomaticsub')])
  1002. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  1003. # subtitles download errors are already managed as troubles in relevant IE
  1004. # that way it will silently go on when used with unsupporting IE
  1005. subtitles = info_dict['subtitles']
  1006. sub_format = self.params.get('subtitlesformat', 'srt')
  1007. for sub_lang in subtitles.keys():
  1008. sub = subtitles[sub_lang]
  1009. if sub is None:
  1010. continue
  1011. try:
  1012. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1013. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1014. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1015. else:
  1016. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1017. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1018. subfile.write(sub)
  1019. except (OSError, IOError):
  1020. self.report_error('Cannot write subtitles file ' + sub_filename)
  1021. return
  1022. if self.params.get('writeinfojson', False):
  1023. infofn = os.path.splitext(filename)[0] + '.info.json'
  1024. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1025. self.to_screen('[info] Video description metadata is already present')
  1026. else:
  1027. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1028. try:
  1029. write_json_file(info_dict, infofn)
  1030. except (OSError, IOError):
  1031. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1032. return
  1033. if self.params.get('writethumbnail', False):
  1034. if info_dict.get('thumbnail') is not None:
  1035. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  1036. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  1037. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1038. self.to_screen('[%s] %s: Thumbnail is already present' %
  1039. (info_dict['extractor'], info_dict['id']))
  1040. else:
  1041. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  1042. (info_dict['extractor'], info_dict['id']))
  1043. try:
  1044. uf = self.urlopen(info_dict['thumbnail'])
  1045. with open(thumb_filename, 'wb') as thumbf:
  1046. shutil.copyfileobj(uf, thumbf)
  1047. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  1048. (info_dict['extractor'], info_dict['id'], thumb_filename))
  1049. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1050. self.report_warning('Unable to download thumbnail "%s": %s' %
  1051. (info_dict['thumbnail'], compat_str(err)))
  1052. if not self.params.get('skip_download', False):
  1053. try:
  1054. def dl(name, info):
  1055. fd = get_suitable_downloader(info)(self, self.params)
  1056. for ph in self._progress_hooks:
  1057. fd.add_progress_hook(ph)
  1058. if self.params.get('verbose'):
  1059. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1060. return fd.download(name, info)
  1061. if info_dict.get('requested_formats') is not None:
  1062. downloaded = []
  1063. success = True
  1064. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1065. if not merger._executable:
  1066. postprocessors = []
  1067. self.report_warning('You have requested multiple '
  1068. 'formats but ffmpeg or avconv are not installed.'
  1069. ' The formats won\'t be merged')
  1070. else:
  1071. postprocessors = [merger]
  1072. for f in info_dict['requested_formats']:
  1073. new_info = dict(info_dict)
  1074. new_info.update(f)
  1075. fname = self.prepare_filename(new_info)
  1076. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1077. downloaded.append(fname)
  1078. partial_success = dl(fname, new_info)
  1079. success = success and partial_success
  1080. info_dict['__postprocessors'] = postprocessors
  1081. info_dict['__files_to_merge'] = downloaded
  1082. else:
  1083. # Just a single file
  1084. success = dl(filename, info_dict)
  1085. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1086. self.report_error('unable to download video data: %s' % str(err))
  1087. return
  1088. except (OSError, IOError) as err:
  1089. raise UnavailableVideoError(err)
  1090. except (ContentTooShortError, ) as err:
  1091. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1092. return
  1093. if success:
  1094. # Fixup content
  1095. stretched_ratio = info_dict.get('stretched_ratio')
  1096. if stretched_ratio is not None and stretched_ratio != 1:
  1097. fixup_policy = self.params.get('fixup')
  1098. if fixup_policy is None:
  1099. fixup_policy = 'detect_or_warn'
  1100. if fixup_policy == 'warn':
  1101. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1102. info_dict['id'], stretched_ratio))
  1103. elif fixup_policy == 'detect_or_warn':
  1104. stretched_pp = FFmpegFixupStretchedPP(self)
  1105. if stretched_pp.available:
  1106. info_dict.setdefault('__postprocessors', [])
  1107. info_dict['__postprocessors'].append(stretched_pp)
  1108. else:
  1109. self.report_warning(
  1110. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1111. info_dict['id'], stretched_ratio))
  1112. else:
  1113. assert fixup_policy == 'ignore'
  1114. try:
  1115. self.post_process(filename, info_dict)
  1116. except (PostProcessingError) as err:
  1117. self.report_error('postprocessing: %s' % str(err))
  1118. return
  1119. self.record_download_archive(info_dict)
  1120. def download(self, url_list):
  1121. """Download a given list of URLs."""
  1122. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1123. if (len(url_list) > 1 and
  1124. '%' not in outtmpl
  1125. and self.params.get('max_downloads') != 1):
  1126. raise SameFileError(outtmpl)
  1127. for url in url_list:
  1128. try:
  1129. # It also downloads the videos
  1130. res = self.extract_info(url)
  1131. except UnavailableVideoError:
  1132. self.report_error('unable to download video')
  1133. except MaxDownloadsReached:
  1134. self.to_screen('[info] Maximum number of downloaded files reached.')
  1135. raise
  1136. else:
  1137. if self.params.get('dump_single_json', False):
  1138. self.to_stdout(json.dumps(res))
  1139. return self._download_retcode
  1140. def download_with_info_file(self, info_filename):
  1141. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1142. info = json.load(f)
  1143. try:
  1144. self.process_ie_result(info, download=True)
  1145. except DownloadError:
  1146. webpage_url = info.get('webpage_url')
  1147. if webpage_url is not None:
  1148. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1149. return self.download([webpage_url])
  1150. else:
  1151. raise
  1152. return self._download_retcode
  1153. def post_process(self, filename, ie_info):
  1154. """Run all the postprocessors on the given file."""
  1155. info = dict(ie_info)
  1156. info['filepath'] = filename
  1157. pps_chain = []
  1158. if ie_info.get('__postprocessors') is not None:
  1159. pps_chain.extend(ie_info['__postprocessors'])
  1160. pps_chain.extend(self._pps)
  1161. for pp in pps_chain:
  1162. keep_video = None
  1163. old_filename = info['filepath']
  1164. try:
  1165. keep_video_wish, info = pp.run(info)
  1166. if keep_video_wish is not None:
  1167. if keep_video_wish:
  1168. keep_video = keep_video_wish
  1169. elif keep_video is None:
  1170. # No clear decision yet, let IE decide
  1171. keep_video = keep_video_wish
  1172. except PostProcessingError as e:
  1173. self.report_error(e.msg)
  1174. if keep_video is False and not self.params.get('keepvideo', False):
  1175. try:
  1176. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1177. os.remove(encodeFilename(old_filename))
  1178. except (IOError, OSError):
  1179. self.report_warning('Unable to remove downloaded video file')
  1180. def _make_archive_id(self, info_dict):
  1181. # Future-proof against any change in case
  1182. # and backwards compatibility with prior versions
  1183. extractor = info_dict.get('extractor_key')
  1184. if extractor is None:
  1185. if 'id' in info_dict:
  1186. extractor = info_dict.get('ie_key') # key in a playlist
  1187. if extractor is None:
  1188. return None # Incomplete video information
  1189. return extractor.lower() + ' ' + info_dict['id']
  1190. def in_download_archive(self, info_dict):
  1191. fn = self.params.get('download_archive')
  1192. if fn is None:
  1193. return False
  1194. vid_id = self._make_archive_id(info_dict)
  1195. if vid_id is None:
  1196. return False # Incomplete video information
  1197. try:
  1198. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1199. for line in archive_file:
  1200. if line.strip() == vid_id:
  1201. return True
  1202. except IOError as ioe:
  1203. if ioe.errno != errno.ENOENT:
  1204. raise
  1205. return False
  1206. def record_download_archive(self, info_dict):
  1207. fn = self.params.get('download_archive')
  1208. if fn is None:
  1209. return
  1210. vid_id = self._make_archive_id(info_dict)
  1211. assert vid_id
  1212. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1213. archive_file.write(vid_id + '\n')
  1214. @staticmethod
  1215. def format_resolution(format, default='unknown'):
  1216. if format.get('vcodec') == 'none':
  1217. return 'audio only'
  1218. if format.get('resolution') is not None:
  1219. return format['resolution']
  1220. if format.get('height') is not None:
  1221. if format.get('width') is not None:
  1222. res = '%sx%s' % (format['width'], format['height'])
  1223. else:
  1224. res = '%sp' % format['height']
  1225. elif format.get('width') is not None:
  1226. res = '?x%d' % format['width']
  1227. else:
  1228. res = default
  1229. return res
  1230. def _format_note(self, fdict):
  1231. res = ''
  1232. if fdict.get('ext') in ['f4f', 'f4m']:
  1233. res += '(unsupported) '
  1234. if fdict.get('format_note') is not None:
  1235. res += fdict['format_note'] + ' '
  1236. if fdict.get('tbr') is not None:
  1237. res += '%4dk ' % fdict['tbr']
  1238. if fdict.get('container') is not None:
  1239. if res:
  1240. res += ', '
  1241. res += '%s container' % fdict['container']
  1242. if (fdict.get('vcodec') is not None and
  1243. fdict.get('vcodec') != 'none'):
  1244. if res:
  1245. res += ', '
  1246. res += fdict['vcodec']
  1247. if fdict.get('vbr') is not None:
  1248. res += '@'
  1249. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1250. res += 'video@'
  1251. if fdict.get('vbr') is not None:
  1252. res += '%4dk' % fdict['vbr']
  1253. if fdict.get('fps') is not None:
  1254. res += ', %sfps' % fdict['fps']
  1255. if fdict.get('acodec') is not None:
  1256. if res:
  1257. res += ', '
  1258. if fdict['acodec'] == 'none':
  1259. res += 'video only'
  1260. else:
  1261. res += '%-5s' % fdict['acodec']
  1262. elif fdict.get('abr') is not None:
  1263. if res:
  1264. res += ', '
  1265. res += 'audio'
  1266. if fdict.get('abr') is not None:
  1267. res += '@%3dk' % fdict['abr']
  1268. if fdict.get('asr') is not None:
  1269. res += ' (%5dHz)' % fdict['asr']
  1270. if fdict.get('filesize') is not None:
  1271. if res:
  1272. res += ', '
  1273. res += format_bytes(fdict['filesize'])
  1274. elif fdict.get('filesize_approx') is not None:
  1275. if res:
  1276. res += ', '
  1277. res += '~' + format_bytes(fdict['filesize_approx'])
  1278. return res
  1279. def list_formats(self, info_dict):
  1280. def line(format, idlen=20):
  1281. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1282. format['format_id'],
  1283. format['ext'],
  1284. self.format_resolution(format),
  1285. self._format_note(format),
  1286. ))
  1287. formats = info_dict.get('formats', [info_dict])
  1288. idlen = max(len('format code'),
  1289. max(len(f['format_id']) for f in formats))
  1290. formats_s = [
  1291. line(f, idlen) for f in formats
  1292. if f.get('preference') is None or f['preference'] >= -1000]
  1293. if len(formats) > 1:
  1294. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1295. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1296. header_line = line({
  1297. 'format_id': 'format code', 'ext': 'extension',
  1298. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1299. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1300. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1301. def urlopen(self, req):
  1302. """ Start an HTTP download """
  1303. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1304. # always respected by websites, some tend to give out URLs with non percent-encoded
  1305. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1306. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1307. # To work around aforementioned issue we will replace request's original URL with
  1308. # percent-encoded one
  1309. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1310. url = req if req_is_string else req.get_full_url()
  1311. url_escaped = escape_url(url)
  1312. # Substitute URL if any change after escaping
  1313. if url != url_escaped:
  1314. if req_is_string:
  1315. req = url_escaped
  1316. else:
  1317. req = compat_urllib_request.Request(
  1318. url_escaped, data=req.data, headers=req.headers,
  1319. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1320. return self._opener.open(req, timeout=self._socket_timeout)
  1321. def print_debug_header(self):
  1322. if not self.params.get('verbose'):
  1323. return
  1324. if type('') is not compat_str:
  1325. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1326. self.report_warning(
  1327. 'Your Python is broken! Update to a newer and supported version')
  1328. stdout_encoding = getattr(
  1329. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1330. encoding_str = (
  1331. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1332. locale.getpreferredencoding(),
  1333. sys.getfilesystemencoding(),
  1334. stdout_encoding,
  1335. self.get_encoding()))
  1336. write_string(encoding_str, encoding=None)
  1337. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1338. try:
  1339. sp = subprocess.Popen(
  1340. ['git', 'rev-parse', '--short', 'HEAD'],
  1341. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1342. cwd=os.path.dirname(os.path.abspath(__file__)))
  1343. out, err = sp.communicate()
  1344. out = out.decode().strip()
  1345. if re.match('[0-9a-f]+', out):
  1346. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1347. except:
  1348. try:
  1349. sys.exc_clear()
  1350. except:
  1351. pass
  1352. self._write_string('[debug] Python version %s - %s\n' % (
  1353. platform.python_version(), platform_name()))
  1354. exe_versions = FFmpegPostProcessor.get_versions()
  1355. exe_versions['rtmpdump'] = rtmpdump_version()
  1356. exe_str = ', '.join(
  1357. '%s %s' % (exe, v)
  1358. for exe, v in sorted(exe_versions.items())
  1359. if v
  1360. )
  1361. if not exe_str:
  1362. exe_str = 'none'
  1363. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1364. proxy_map = {}
  1365. for handler in self._opener.handlers:
  1366. if hasattr(handler, 'proxies'):
  1367. proxy_map.update(handler.proxies)
  1368. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1369. if self.params.get('call_home', False):
  1370. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1371. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1372. latest_version = self.urlopen(
  1373. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1374. if version_tuple(latest_version) > version_tuple(__version__):
  1375. self.report_warning(
  1376. 'You are using an outdated version (newest version: %s)! '
  1377. 'See https://yt-dl.org/update if you need help updating.' %
  1378. latest_version)
  1379. def _setup_opener(self):
  1380. timeout_val = self.params.get('socket_timeout')
  1381. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1382. opts_cookiefile = self.params.get('cookiefile')
  1383. opts_proxy = self.params.get('proxy')
  1384. if opts_cookiefile is None:
  1385. self.cookiejar = compat_cookiejar.CookieJar()
  1386. else:
  1387. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1388. opts_cookiefile)
  1389. if os.access(opts_cookiefile, os.R_OK):
  1390. self.cookiejar.load()
  1391. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1392. self.cookiejar)
  1393. if opts_proxy is not None:
  1394. if opts_proxy == '':
  1395. proxies = {}
  1396. else:
  1397. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1398. else:
  1399. proxies = compat_urllib_request.getproxies()
  1400. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1401. if 'http' in proxies and 'https' not in proxies:
  1402. proxies['https'] = proxies['http']
  1403. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1404. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1405. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1406. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1407. opener = compat_urllib_request.build_opener(
  1408. https_handler, proxy_handler, cookie_processor, ydlh)
  1409. # Delete the default user-agent header, which would otherwise apply in
  1410. # cases where our custom HTTP handler doesn't come into play
  1411. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1412. opener.addheaders = []
  1413. self._opener = opener
  1414. def encode(self, s):
  1415. if isinstance(s, bytes):
  1416. return s # Already encoded
  1417. try:
  1418. return s.encode(self.get_encoding())
  1419. except UnicodeEncodeError as err:
  1420. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1421. raise
  1422. def get_encoding(self):
  1423. encoding = self.params.get('encoding')
  1424. if encoding is None:
  1425. encoding = preferredencoding()
  1426. return encoding