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.

2117 lines
94 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
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 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 contextlib
  6. import datetime
  7. import errno
  8. import fileinput
  9. import io
  10. import itertools
  11. import json
  12. import locale
  13. import operator
  14. import os
  15. import platform
  16. import re
  17. import shutil
  18. import subprocess
  19. import socket
  20. import sys
  21. import time
  22. import tokenize
  23. import traceback
  24. from .compat import (
  25. compat_basestring,
  26. compat_cookiejar,
  27. compat_expanduser,
  28. compat_get_terminal_size,
  29. compat_http_client,
  30. compat_kwargs,
  31. compat_os_name,
  32. compat_str,
  33. compat_tokenize_tokenize,
  34. compat_urllib_error,
  35. compat_urllib_request,
  36. compat_urllib_request_DataHandler,
  37. )
  38. from .utils import (
  39. age_restricted,
  40. args_to_str,
  41. ContentTooShortError,
  42. date_from_str,
  43. DateRange,
  44. DEFAULT_OUTTMPL,
  45. determine_ext,
  46. determine_protocol,
  47. DownloadError,
  48. encode_compat_str,
  49. encodeFilename,
  50. error_to_compat_str,
  51. ExtractorError,
  52. format_bytes,
  53. formatSeconds,
  54. locked_file,
  55. make_HTTPS_handler,
  56. MaxDownloadsReached,
  57. PagedList,
  58. parse_filesize,
  59. PerRequestProxyHandler,
  60. platform_name,
  61. PostProcessingError,
  62. preferredencoding,
  63. prepend_extension,
  64. register_socks_protocols,
  65. render_table,
  66. replace_extension,
  67. SameFileError,
  68. sanitize_filename,
  69. sanitize_path,
  70. sanitize_url,
  71. sanitized_Request,
  72. std_headers,
  73. subtitles_filename,
  74. UnavailableVideoError,
  75. url_basename,
  76. version_tuple,
  77. write_json_file,
  78. write_string,
  79. YoutubeDLCookieProcessor,
  80. YoutubeDLHandler,
  81. )
  82. from .cache import Cache
  83. from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
  84. from .downloader import get_suitable_downloader
  85. from .downloader.rtmp import rtmpdump_version
  86. from .postprocessor import (
  87. FFmpegFixupM3u8PP,
  88. FFmpegFixupM4aPP,
  89. FFmpegFixupStretchedPP,
  90. FFmpegMergerPP,
  91. FFmpegPostProcessor,
  92. get_postprocessor,
  93. )
  94. from .version import __version__
  95. if compat_os_name == 'nt':
  96. import ctypes
  97. class YoutubeDL(object):
  98. """YoutubeDL class.
  99. YoutubeDL objects are the ones responsible of downloading the
  100. actual video file and writing it to disk if the user has requested
  101. it, among some other tasks. In most cases there should be one per
  102. program. As, given a video URL, the downloader doesn't know how to
  103. extract all the needed information, task that InfoExtractors do, it
  104. has to pass the URL to one of them.
  105. For this, YoutubeDL objects have a method that allows
  106. InfoExtractors to be registered in a given order. When it is passed
  107. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  108. finds that reports being able to handle it. The InfoExtractor extracts
  109. all the information about the video or videos the URL refers to, and
  110. YoutubeDL process the extracted information, possibly using a File
  111. Downloader to download the video.
  112. YoutubeDL objects accept a lot of parameters. In order not to saturate
  113. the object constructor with arguments, it receives a dictionary of
  114. options instead. These options are available through the params
  115. attribute for the InfoExtractors to use. The YoutubeDL also
  116. registers itself as the downloader in charge for the InfoExtractors
  117. that are added to it, so this is a "mutual registration".
  118. Available options:
  119. username: Username for authentication purposes.
  120. password: Password for authentication purposes.
  121. videopassword: Password for accessing a video.
  122. usenetrc: Use netrc for authentication instead.
  123. verbose: Print additional info to stdout.
  124. quiet: Do not print messages to stdout.
  125. no_warnings: Do not print out anything for warnings.
  126. forceurl: Force printing final URL.
  127. forcetitle: Force printing title.
  128. forceid: Force printing ID.
  129. forcethumbnail: Force printing thumbnail URL.
  130. forcedescription: Force printing description.
  131. forcefilename: Force printing final filename.
  132. forceduration: Force printing duration.
  133. forcejson: Force printing info_dict as JSON.
  134. dump_single_json: Force printing the info_dict of the whole playlist
  135. (or video) as a single JSON line.
  136. simulate: Do not download the video files.
  137. format: Video format code. See options.py for more information.
  138. outtmpl: Template for output names.
  139. restrictfilenames: Do not allow "&" and spaces in file names
  140. ignoreerrors: Do not stop on download errors.
  141. force_generic_extractor: Force downloader to use the generic extractor
  142. nooverwrites: Prevent overwriting files.
  143. playliststart: Playlist item to start at.
  144. playlistend: Playlist item to end at.
  145. playlist_items: Specific indices of playlist to download.
  146. playlistreverse: Download playlist items in reverse order.
  147. matchtitle: Download only matching titles.
  148. rejecttitle: Reject downloads for matching titles.
  149. logger: Log messages to a logging.Logger instance.
  150. logtostderr: Log messages to stderr instead of stdout.
  151. writedescription: Write the video description to a .description file
  152. writeinfojson: Write the video description to a .info.json file
  153. writeannotations: Write the video annotations to a .annotations.xml file
  154. writethumbnail: Write the thumbnail image to a file
  155. write_all_thumbnails: Write all thumbnail formats to files
  156. writesubtitles: Write the video subtitles to a file
  157. writeautomaticsub: Write the automatically generated subtitles to a file
  158. allsubtitles: Downloads all the subtitles of the video
  159. (requires writesubtitles or writeautomaticsub)
  160. listsubtitles: Lists all available subtitles for the video
  161. subtitlesformat: The format code for subtitles
  162. subtitleslangs: List of languages of the subtitles to download
  163. keepvideo: Keep the video file after post-processing
  164. daterange: A DateRange object, download only if the upload_date is in the range.
  165. skip_download: Skip the actual download of the video file
  166. cachedir: Location of the cache files in the filesystem.
  167. False to disable filesystem cache.
  168. noplaylist: Download single video instead of a playlist if in doubt.
  169. age_limit: An integer representing the user's age in years.
  170. Unsuitable videos for the given age are skipped.
  171. min_views: An integer representing the minimum view count the video
  172. must have in order to not be skipped.
  173. Videos without view count information are always
  174. downloaded. None for no limit.
  175. max_views: An integer representing the maximum view count.
  176. Videos that are more popular than that are not
  177. downloaded.
  178. Videos without view count information are always
  179. downloaded. None for no limit.
  180. download_archive: File name of a file where all downloads are recorded.
  181. Videos already present in the file are not downloaded
  182. again.
  183. cookiefile: File name where cookies should be read from and dumped to.
  184. nocheckcertificate:Do not verify SSL certificates
  185. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  186. At the moment, this is only supported by YouTube.
  187. proxy: URL of the proxy server to use
  188. cn_verification_proxy: URL of the proxy to use for IP address verification
  189. on Chinese sites. (Experimental)
  190. socket_timeout: Time to wait for unresponsive hosts, in seconds
  191. bidi_workaround: Work around buggy terminals without bidirectional text
  192. support, using fridibi
  193. debug_printtraffic:Print out sent and received HTTP traffic
  194. include_ads: Download ads as well
  195. default_search: Prepend this string if an input url is not valid.
  196. 'auto' for elaborate guessing
  197. encoding: Use this encoding instead of the system-specified.
  198. extract_flat: Do not resolve URLs, return the immediate result.
  199. Pass in 'in_playlist' to only show this behavior for
  200. playlist items.
  201. postprocessors: A list of dictionaries, each with an entry
  202. * key: The name of the postprocessor. See
  203. youtube_dl/postprocessor/__init__.py for a list.
  204. as well as any further keyword arguments for the
  205. postprocessor.
  206. progress_hooks: A list of functions that get called on download
  207. progress, with a dictionary with the entries
  208. * status: One of "downloading", "error", or "finished".
  209. Check this first and ignore unknown values.
  210. If status is one of "downloading", or "finished", the
  211. following properties may also be present:
  212. * filename: The final filename (always present)
  213. * tmpfilename: The filename we're currently writing to
  214. * downloaded_bytes: Bytes on disk
  215. * total_bytes: Size of the whole file, None if unknown
  216. * total_bytes_estimate: Guess of the eventual file size,
  217. None if unavailable.
  218. * elapsed: The number of seconds since download started.
  219. * eta: The estimated time in seconds, None if unknown
  220. * speed: The download speed in bytes/second, None if
  221. unknown
  222. * fragment_index: The counter of the currently
  223. downloaded video fragment.
  224. * fragment_count: The number of fragments (= individual
  225. files that will be merged)
  226. Progress hooks are guaranteed to be called at least once
  227. (with status "finished") if the download is successful.
  228. merge_output_format: Extension to use when merging formats.
  229. fixup: Automatically correct known faults of the file.
  230. One of:
  231. - "never": do nothing
  232. - "warn": only emit a warning
  233. - "detect_or_warn": check whether we can do anything
  234. about it, warn otherwise (default)
  235. source_address: (Experimental) Client-side IP address to bind to.
  236. call_home: Boolean, true iff we are allowed to contact the
  237. youtube-dl servers for debugging.
  238. sleep_interval: Number of seconds to sleep before each download.
  239. listformats: Print an overview of available video formats and exit.
  240. list_thumbnails: Print a table of all thumbnails and exit.
  241. match_filter: A function that gets called with the info_dict of
  242. every video.
  243. If it returns a message, the video is ignored.
  244. If it returns None, the video is downloaded.
  245. match_filter_func in utils.py is one example for this.
  246. no_color: Do not emit color codes in output.
  247. The following options determine which downloader is picked:
  248. external_downloader: Executable of the external downloader to call.
  249. None or unset for standard (built-in) downloader.
  250. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
  251. if True, otherwise use ffmpeg/avconv if False, otherwise
  252. use downloader suggested by extractor if None.
  253. The following parameters are not used by YoutubeDL itself, they are used by
  254. the downloader (see youtube_dl/downloader/common.py):
  255. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  256. noresizebuffer, retries, continuedl, noprogress, consoletitle,
  257. xattr_set_filesize, external_downloader_args, hls_use_mpegts.
  258. The following options are used by the post processors:
  259. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  260. otherwise prefer avconv.
  261. postprocessor_args: A list of additional command-line arguments for the
  262. postprocessor.
  263. """
  264. params = None
  265. _ies = []
  266. _pps = []
  267. _download_retcode = None
  268. _num_downloads = None
  269. _screen_file = None
  270. def __init__(self, params=None, auto_init=True):
  271. """Create a FileDownloader object with the given options."""
  272. if params is None:
  273. params = {}
  274. self._ies = []
  275. self._ies_instances = {}
  276. self._pps = []
  277. self._progress_hooks = []
  278. self._download_retcode = 0
  279. self._num_downloads = 0
  280. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  281. self._err_file = sys.stderr
  282. self.params = {
  283. # Default parameters
  284. 'nocheckcertificate': False,
  285. }
  286. self.params.update(params)
  287. self.cache = Cache(self)
  288. if params.get('bidi_workaround', False):
  289. try:
  290. import pty
  291. master, slave = pty.openpty()
  292. width = compat_get_terminal_size().columns
  293. if width is None:
  294. width_args = []
  295. else:
  296. width_args = ['-w', str(width)]
  297. sp_kwargs = dict(
  298. stdin=subprocess.PIPE,
  299. stdout=slave,
  300. stderr=self._err_file)
  301. try:
  302. self._output_process = subprocess.Popen(
  303. ['bidiv'] + width_args, **sp_kwargs
  304. )
  305. except OSError:
  306. self._output_process = subprocess.Popen(
  307. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  308. self._output_channel = os.fdopen(master, 'rb')
  309. except OSError as ose:
  310. if ose.errno == 2:
  311. 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.')
  312. else:
  313. raise
  314. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  315. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968'] and
  316. not params.get('restrictfilenames', False)):
  317. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  318. self.report_warning(
  319. 'Assuming --restrict-filenames since file system encoding '
  320. 'cannot encode all characters. '
  321. 'Set the LC_ALL environment variable to fix this.')
  322. self.params['restrictfilenames'] = True
  323. if isinstance(params.get('outtmpl'), bytes):
  324. self.report_warning(
  325. 'Parameter outtmpl is bytes, but should be a unicode string. '
  326. 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
  327. self._setup_opener()
  328. if auto_init:
  329. self.print_debug_header()
  330. self.add_default_info_extractors()
  331. for pp_def_raw in self.params.get('postprocessors', []):
  332. pp_class = get_postprocessor(pp_def_raw['key'])
  333. pp_def = dict(pp_def_raw)
  334. del pp_def['key']
  335. pp = pp_class(self, **compat_kwargs(pp_def))
  336. self.add_post_processor(pp)
  337. for ph in self.params.get('progress_hooks', []):
  338. self.add_progress_hook(ph)
  339. register_socks_protocols()
  340. def warn_if_short_id(self, argv):
  341. # short YouTube ID starting with dash?
  342. idxs = [
  343. i for i, a in enumerate(argv)
  344. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  345. if idxs:
  346. correct_argv = (
  347. ['youtube-dl'] +
  348. [a for i, a in enumerate(argv) if i not in idxs] +
  349. ['--'] + [argv[i] for i in idxs]
  350. )
  351. self.report_warning(
  352. 'Long argument string detected. '
  353. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  354. args_to_str(correct_argv))
  355. def add_info_extractor(self, ie):
  356. """Add an InfoExtractor object to the end of the list."""
  357. self._ies.append(ie)
  358. if not isinstance(ie, type):
  359. self._ies_instances[ie.ie_key()] = ie
  360. ie.set_downloader(self)
  361. def get_info_extractor(self, ie_key):
  362. """
  363. Get an instance of an IE with name ie_key, it will try to get one from
  364. the _ies list, if there's no instance it will create a new one and add
  365. it to the extractor list.
  366. """
  367. ie = self._ies_instances.get(ie_key)
  368. if ie is None:
  369. ie = get_info_extractor(ie_key)()
  370. self.add_info_extractor(ie)
  371. return ie
  372. def add_default_info_extractors(self):
  373. """
  374. Add the InfoExtractors returned by gen_extractors to the end of the list
  375. """
  376. for ie in gen_extractor_classes():
  377. self.add_info_extractor(ie)
  378. def add_post_processor(self, pp):
  379. """Add a PostProcessor object to the end of the chain."""
  380. self._pps.append(pp)
  381. pp.set_downloader(self)
  382. def add_progress_hook(self, ph):
  383. """Add the progress hook (currently only for the file downloader)"""
  384. self._progress_hooks.append(ph)
  385. def _bidi_workaround(self, message):
  386. if not hasattr(self, '_output_channel'):
  387. return message
  388. assert hasattr(self, '_output_process')
  389. assert isinstance(message, compat_str)
  390. line_count = message.count('\n') + 1
  391. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  392. self._output_process.stdin.flush()
  393. res = ''.join(self._output_channel.readline().decode('utf-8')
  394. for _ in range(line_count))
  395. return res[:-len('\n')]
  396. def to_screen(self, message, skip_eol=False):
  397. """Print message to stdout if not in quiet mode."""
  398. return self.to_stdout(message, skip_eol, check_quiet=True)
  399. def _write_string(self, s, out=None):
  400. write_string(s, out=out, encoding=self.params.get('encoding'))
  401. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  402. """Print message to stdout if not in quiet mode."""
  403. if self.params.get('logger'):
  404. self.params['logger'].debug(message)
  405. elif not check_quiet or not self.params.get('quiet', False):
  406. message = self._bidi_workaround(message)
  407. terminator = ['\n', ''][skip_eol]
  408. output = message + terminator
  409. self._write_string(output, self._screen_file)
  410. def to_stderr(self, message):
  411. """Print message to stderr."""
  412. assert isinstance(message, compat_str)
  413. if self.params.get('logger'):
  414. self.params['logger'].error(message)
  415. else:
  416. message = self._bidi_workaround(message)
  417. output = message + '\n'
  418. self._write_string(output, self._err_file)
  419. def to_console_title(self, message):
  420. if not self.params.get('consoletitle', False):
  421. return
  422. if compat_os_name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  423. # c_wchar_p() might not be necessary if `message` is
  424. # already of type unicode()
  425. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  426. elif 'TERM' in os.environ:
  427. self._write_string('\033]0;%s\007' % message, self._screen_file)
  428. def save_console_title(self):
  429. if not self.params.get('consoletitle', False):
  430. return
  431. if 'TERM' in os.environ:
  432. # Save the title on stack
  433. self._write_string('\033[22;0t', self._screen_file)
  434. def restore_console_title(self):
  435. if not self.params.get('consoletitle', False):
  436. return
  437. if 'TERM' in os.environ:
  438. # Restore the title from stack
  439. self._write_string('\033[23;0t', self._screen_file)
  440. def __enter__(self):
  441. self.save_console_title()
  442. return self
  443. def __exit__(self, *args):
  444. self.restore_console_title()
  445. if self.params.get('cookiefile') is not None:
  446. self.cookiejar.save()
  447. def trouble(self, message=None, tb=None):
  448. """Determine action to take when a download problem appears.
  449. Depending on if the downloader has been configured to ignore
  450. download errors or not, this method may throw an exception or
  451. not when errors are found, after printing the message.
  452. tb, if given, is additional traceback information.
  453. """
  454. if message is not None:
  455. self.to_stderr(message)
  456. if self.params.get('verbose'):
  457. if tb is None:
  458. if sys.exc_info()[0]: # if .trouble has been called from an except block
  459. tb = ''
  460. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  461. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  462. tb += encode_compat_str(traceback.format_exc())
  463. else:
  464. tb_data = traceback.format_list(traceback.extract_stack())
  465. tb = ''.join(tb_data)
  466. self.to_stderr(tb)
  467. if not self.params.get('ignoreerrors', False):
  468. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  469. exc_info = sys.exc_info()[1].exc_info
  470. else:
  471. exc_info = sys.exc_info()
  472. raise DownloadError(message, exc_info)
  473. self._download_retcode = 1
  474. def report_warning(self, message):
  475. '''
  476. Print the message to stderr, it will be prefixed with 'WARNING:'
  477. If stderr is a tty file the 'WARNING:' will be colored
  478. '''
  479. if self.params.get('logger') is not None:
  480. self.params['logger'].warning(message)
  481. else:
  482. if self.params.get('no_warnings'):
  483. return
  484. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  485. _msg_header = '\033[0;33mWARNING:\033[0m'
  486. else:
  487. _msg_header = 'WARNING:'
  488. warning_message = '%s %s' % (_msg_header, message)
  489. self.to_stderr(warning_message)
  490. def report_error(self, message, tb=None):
  491. '''
  492. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  493. in red if stderr is a tty file.
  494. '''
  495. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  496. _msg_header = '\033[0;31mERROR:\033[0m'
  497. else:
  498. _msg_header = 'ERROR:'
  499. error_message = '%s %s' % (_msg_header, message)
  500. self.trouble(error_message, tb)
  501. def report_file_already_downloaded(self, file_name):
  502. """Report file has already been fully downloaded."""
  503. try:
  504. self.to_screen('[download] %s has already been downloaded' % file_name)
  505. except UnicodeEncodeError:
  506. self.to_screen('[download] The file has already been downloaded')
  507. def prepare_filename(self, info_dict):
  508. """Generate the output filename."""
  509. try:
  510. template_dict = dict(info_dict)
  511. template_dict['epoch'] = int(time.time())
  512. autonumber_size = self.params.get('autonumber_size')
  513. if autonumber_size is None:
  514. autonumber_size = 5
  515. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  516. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  517. if template_dict.get('playlist_index') is not None:
  518. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  519. if template_dict.get('resolution') is None:
  520. if template_dict.get('width') and template_dict.get('height'):
  521. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  522. elif template_dict.get('height'):
  523. template_dict['resolution'] = '%sp' % template_dict['height']
  524. elif template_dict.get('width'):
  525. template_dict['resolution'] = '%dx?' % template_dict['width']
  526. sanitize = lambda k, v: sanitize_filename(
  527. compat_str(v),
  528. restricted=self.params.get('restrictfilenames'),
  529. is_id=(k == 'id'))
  530. template_dict = dict((k, sanitize(k, v))
  531. for k, v in template_dict.items()
  532. if v is not None and not isinstance(v, (list, tuple, dict)))
  533. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  534. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  535. tmpl = compat_expanduser(outtmpl)
  536. filename = tmpl % template_dict
  537. # Temporary fix for #4787
  538. # 'Treat' all problem characters by passing filename through preferredencoding
  539. # to workaround encoding issues with subprocess on python2 @ Windows
  540. if sys.version_info < (3, 0) and sys.platform == 'win32':
  541. filename = encodeFilename(filename, True).decode(preferredencoding())
  542. return sanitize_path(filename)
  543. except ValueError as err:
  544. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  545. return None
  546. def _match_entry(self, info_dict, incomplete):
  547. """ Returns None iff the file should be downloaded """
  548. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  549. if 'title' in info_dict:
  550. # This can happen when we're just evaluating the playlist
  551. title = info_dict['title']
  552. matchtitle = self.params.get('matchtitle', False)
  553. if matchtitle:
  554. if not re.search(matchtitle, title, re.IGNORECASE):
  555. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  556. rejecttitle = self.params.get('rejecttitle', False)
  557. if rejecttitle:
  558. if re.search(rejecttitle, title, re.IGNORECASE):
  559. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  560. date = info_dict.get('upload_date')
  561. if date is not None:
  562. dateRange = self.params.get('daterange', DateRange())
  563. if date not in dateRange:
  564. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  565. view_count = info_dict.get('view_count')
  566. if view_count is not None:
  567. min_views = self.params.get('min_views')
  568. if min_views is not None and view_count < min_views:
  569. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  570. max_views = self.params.get('max_views')
  571. if max_views is not None and view_count > max_views:
  572. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  573. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  574. return 'Skipping "%s" because it is age restricted' % video_title
  575. if self.in_download_archive(info_dict):
  576. return '%s has already been recorded in archive' % video_title
  577. if not incomplete:
  578. match_filter = self.params.get('match_filter')
  579. if match_filter is not None:
  580. ret = match_filter(info_dict)
  581. if ret is not None:
  582. return ret
  583. return None
  584. @staticmethod
  585. def add_extra_info(info_dict, extra_info):
  586. '''Set the keys from extra_info in info dict if they are missing'''
  587. for key, value in extra_info.items():
  588. info_dict.setdefault(key, value)
  589. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  590. process=True, force_generic_extractor=False):
  591. '''
  592. Returns a list with a dictionary for each video we find.
  593. If 'download', also downloads the videos.
  594. extra_info is a dict containing the extra values to add to each result
  595. '''
  596. if not ie_key and force_generic_extractor:
  597. ie_key = 'Generic'
  598. if ie_key:
  599. ies = [self.get_info_extractor(ie_key)]
  600. else:
  601. ies = self._ies
  602. for ie in ies:
  603. if not ie.suitable(url):
  604. continue
  605. ie = self.get_info_extractor(ie.ie_key())
  606. if not ie.working():
  607. self.report_warning('The program functionality for this site has been marked as broken, '
  608. 'and will probably not work.')
  609. try:
  610. ie_result = ie.extract(url)
  611. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  612. break
  613. if isinstance(ie_result, list):
  614. # Backwards compatibility: old IE result format
  615. ie_result = {
  616. '_type': 'compat_list',
  617. 'entries': ie_result,
  618. }
  619. self.add_default_extra_info(ie_result, ie, url)
  620. if process:
  621. return self.process_ie_result(ie_result, download, extra_info)
  622. else:
  623. return ie_result
  624. except ExtractorError as e: # An error we somewhat expected
  625. self.report_error(compat_str(e), e.format_traceback())
  626. break
  627. except MaxDownloadsReached:
  628. raise
  629. except Exception as e:
  630. if self.params.get('ignoreerrors', False):
  631. self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
  632. break
  633. else:
  634. raise
  635. else:
  636. self.report_error('no suitable InfoExtractor for URL %s' % url)
  637. def add_default_extra_info(self, ie_result, ie, url):
  638. self.add_extra_info(ie_result, {
  639. 'extractor': ie.IE_NAME,
  640. 'webpage_url': url,
  641. 'webpage_url_basename': url_basename(url),
  642. 'extractor_key': ie.ie_key(),
  643. })
  644. def process_ie_result(self, ie_result, download=True, extra_info={}):
  645. """
  646. Take the result of the ie(may be modified) and resolve all unresolved
  647. references (URLs, playlist items).
  648. It will also download the videos if 'download'.
  649. Returns the resolved ie_result.
  650. """
  651. result_type = ie_result.get('_type', 'video')
  652. if result_type in ('url', 'url_transparent'):
  653. extract_flat = self.params.get('extract_flat', False)
  654. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  655. extract_flat is True):
  656. if self.params.get('forcejson', False):
  657. self.to_stdout(json.dumps(ie_result))
  658. return ie_result
  659. if result_type == 'video':
  660. self.add_extra_info(ie_result, extra_info)
  661. return self.process_video_result(ie_result, download=download)
  662. elif result_type == 'url':
  663. # We have to add extra_info to the results because it may be
  664. # contained in a playlist
  665. return self.extract_info(ie_result['url'],
  666. download,
  667. ie_key=ie_result.get('ie_key'),
  668. extra_info=extra_info)
  669. elif result_type == 'url_transparent':
  670. # Use the information from the embedding page
  671. info = self.extract_info(
  672. ie_result['url'], ie_key=ie_result.get('ie_key'),
  673. extra_info=extra_info, download=False, process=False)
  674. force_properties = dict(
  675. (k, v) for k, v in ie_result.items() if v is not None)
  676. for f in ('_type', 'url', 'ie_key'):
  677. if f in force_properties:
  678. del force_properties[f]
  679. new_result = info.copy()
  680. new_result.update(force_properties)
  681. assert new_result.get('_type') != 'url_transparent'
  682. return self.process_ie_result(
  683. new_result, download=download, extra_info=extra_info)
  684. elif result_type == 'playlist' or result_type == 'multi_video':
  685. # We process each entry in the playlist
  686. playlist = ie_result.get('title') or ie_result.get('id')
  687. self.to_screen('[download] Downloading playlist: %s' % playlist)
  688. playlist_results = []
  689. playliststart = self.params.get('playliststart', 1) - 1
  690. playlistend = self.params.get('playlistend')
  691. # For backwards compatibility, interpret -1 as whole list
  692. if playlistend == -1:
  693. playlistend = None
  694. playlistitems_str = self.params.get('playlist_items')
  695. playlistitems = None
  696. if playlistitems_str is not None:
  697. def iter_playlistitems(format):
  698. for string_segment in format.split(','):
  699. if '-' in string_segment:
  700. start, end = string_segment.split('-')
  701. for item in range(int(start), int(end) + 1):
  702. yield int(item)
  703. else:
  704. yield int(string_segment)
  705. playlistitems = iter_playlistitems(playlistitems_str)
  706. ie_entries = ie_result['entries']
  707. if isinstance(ie_entries, list):
  708. n_all_entries = len(ie_entries)
  709. if playlistitems:
  710. entries = [
  711. ie_entries[i - 1] for i in playlistitems
  712. if -n_all_entries <= i - 1 < n_all_entries]
  713. else:
  714. entries = ie_entries[playliststart:playlistend]
  715. n_entries = len(entries)
  716. self.to_screen(
  717. '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
  718. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  719. elif isinstance(ie_entries, PagedList):
  720. if playlistitems:
  721. entries = []
  722. for item in playlistitems:
  723. entries.extend(ie_entries.getslice(
  724. item - 1, item
  725. ))
  726. else:
  727. entries = ie_entries.getslice(
  728. playliststart, playlistend)
  729. n_entries = len(entries)
  730. self.to_screen(
  731. '[%s] playlist %s: Downloading %d videos' %
  732. (ie_result['extractor'], playlist, n_entries))
  733. else: # iterable
  734. if playlistitems:
  735. entry_list = list(ie_entries)
  736. entries = [entry_list[i - 1] for i in playlistitems]
  737. else:
  738. entries = list(itertools.islice(
  739. ie_entries, playliststart, playlistend))
  740. n_entries = len(entries)
  741. self.to_screen(
  742. '[%s] playlist %s: Downloading %d videos' %
  743. (ie_result['extractor'], playlist, n_entries))
  744. if self.params.get('playlistreverse', False):
  745. entries = entries[::-1]
  746. for i, entry in enumerate(entries, 1):
  747. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  748. extra = {
  749. 'n_entries': n_entries,
  750. 'playlist': playlist,
  751. 'playlist_id': ie_result.get('id'),
  752. 'playlist_title': ie_result.get('title'),
  753. 'playlist_index': i + playliststart,
  754. 'extractor': ie_result['extractor'],
  755. 'webpage_url': ie_result['webpage_url'],
  756. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  757. 'extractor_key': ie_result['extractor_key'],
  758. }
  759. reason = self._match_entry(entry, incomplete=True)
  760. if reason is not None:
  761. self.to_screen('[download] ' + reason)
  762. continue
  763. entry_result = self.process_ie_result(entry,
  764. download=download,
  765. extra_info=extra)
  766. playlist_results.append(entry_result)
  767. ie_result['entries'] = playlist_results
  768. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  769. return ie_result
  770. elif result_type == 'compat_list':
  771. self.report_warning(
  772. 'Extractor %s returned a compat_list result. '
  773. 'It needs to be updated.' % ie_result.get('extractor'))
  774. def _fixup(r):
  775. self.add_extra_info(
  776. r,
  777. {
  778. 'extractor': ie_result['extractor'],
  779. 'webpage_url': ie_result['webpage_url'],
  780. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  781. 'extractor_key': ie_result['extractor_key'],
  782. }
  783. )
  784. return r
  785. ie_result['entries'] = [
  786. self.process_ie_result(_fixup(r), download, extra_info)
  787. for r in ie_result['entries']
  788. ]
  789. return ie_result
  790. else:
  791. raise Exception('Invalid result type: %s' % result_type)
  792. def _build_format_filter(self, filter_spec):
  793. " Returns a function to filter the formats according to the filter_spec "
  794. OPERATORS = {
  795. '<': operator.lt,
  796. '<=': operator.le,
  797. '>': operator.gt,
  798. '>=': operator.ge,
  799. '=': operator.eq,
  800. '!=': operator.ne,
  801. }
  802. operator_rex = re.compile(r'''(?x)\s*
  803. (?P<key>width|height|tbr|abr|vbr|asr|filesize|fps)
  804. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  805. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  806. $
  807. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  808. m = operator_rex.search(filter_spec)
  809. if m:
  810. try:
  811. comparison_value = int(m.group('value'))
  812. except ValueError:
  813. comparison_value = parse_filesize(m.group('value'))
  814. if comparison_value is None:
  815. comparison_value = parse_filesize(m.group('value') + 'B')
  816. if comparison_value is None:
  817. raise ValueError(
  818. 'Invalid value %r in format specification %r' % (
  819. m.group('value'), filter_spec))
  820. op = OPERATORS[m.group('op')]
  821. if not m:
  822. STR_OPERATORS = {
  823. '=': operator.eq,
  824. '!=': operator.ne,
  825. '^=': lambda attr, value: attr.startswith(value),
  826. '$=': lambda attr, value: attr.endswith(value),
  827. '*=': lambda attr, value: value in attr,
  828. }
  829. str_operator_rex = re.compile(r'''(?x)
  830. \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id)
  831. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?
  832. \s*(?P<value>[a-zA-Z0-9._-]+)
  833. \s*$
  834. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  835. m = str_operator_rex.search(filter_spec)
  836. if m:
  837. comparison_value = m.group('value')
  838. op = STR_OPERATORS[m.group('op')]
  839. if not m:
  840. raise ValueError('Invalid filter specification %r' % filter_spec)
  841. def _filter(f):
  842. actual_value = f.get(m.group('key'))
  843. if actual_value is None:
  844. return m.group('none_inclusive')
  845. return op(actual_value, comparison_value)
  846. return _filter
  847. def build_format_selector(self, format_spec):
  848. def syntax_error(note, start):
  849. message = (
  850. 'Invalid format specification: '
  851. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  852. return SyntaxError(message)
  853. PICKFIRST = 'PICKFIRST'
  854. MERGE = 'MERGE'
  855. SINGLE = 'SINGLE'
  856. GROUP = 'GROUP'
  857. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  858. def _parse_filter(tokens):
  859. filter_parts = []
  860. for type, string, start, _, _ in tokens:
  861. if type == tokenize.OP and string == ']':
  862. return ''.join(filter_parts)
  863. else:
  864. filter_parts.append(string)
  865. def _remove_unused_ops(tokens):
  866. # Remove operators that we don't use and join them with the surrounding strings
  867. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  868. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  869. last_string, last_start, last_end, last_line = None, None, None, None
  870. for type, string, start, end, line in tokens:
  871. if type == tokenize.OP and string == '[':
  872. if last_string:
  873. yield tokenize.NAME, last_string, last_start, last_end, last_line
  874. last_string = None
  875. yield type, string, start, end, line
  876. # everything inside brackets will be handled by _parse_filter
  877. for type, string, start, end, line in tokens:
  878. yield type, string, start, end, line
  879. if type == tokenize.OP and string == ']':
  880. break
  881. elif type == tokenize.OP and string in ALLOWED_OPS:
  882. if last_string:
  883. yield tokenize.NAME, last_string, last_start, last_end, last_line
  884. last_string = None
  885. yield type, string, start, end, line
  886. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  887. if not last_string:
  888. last_string = string
  889. last_start = start
  890. last_end = end
  891. else:
  892. last_string += string
  893. if last_string:
  894. yield tokenize.NAME, last_string, last_start, last_end, last_line
  895. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  896. selectors = []
  897. current_selector = None
  898. for type, string, start, _, _ in tokens:
  899. # ENCODING is only defined in python 3.x
  900. if type == getattr(tokenize, 'ENCODING', None):
  901. continue
  902. elif type in [tokenize.NAME, tokenize.NUMBER]:
  903. current_selector = FormatSelector(SINGLE, string, [])
  904. elif type == tokenize.OP:
  905. if string == ')':
  906. if not inside_group:
  907. # ')' will be handled by the parentheses group
  908. tokens.restore_last_token()
  909. break
  910. elif inside_merge and string in ['/', ',']:
  911. tokens.restore_last_token()
  912. break
  913. elif inside_choice and string == ',':
  914. tokens.restore_last_token()
  915. break
  916. elif string == ',':
  917. if not current_selector:
  918. raise syntax_error('"," must follow a format selector', start)
  919. selectors.append(current_selector)
  920. current_selector = None
  921. elif string == '/':
  922. if not current_selector:
  923. raise syntax_error('"/" must follow a format selector', start)
  924. first_choice = current_selector
  925. second_choice = _parse_format_selection(tokens, inside_choice=True)
  926. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  927. elif string == '[':
  928. if not current_selector:
  929. current_selector = FormatSelector(SINGLE, 'best', [])
  930. format_filter = _parse_filter(tokens)
  931. current_selector.filters.append(format_filter)
  932. elif string == '(':
  933. if current_selector:
  934. raise syntax_error('Unexpected "("', start)
  935. group = _parse_format_selection(tokens, inside_group=True)
  936. current_selector = FormatSelector(GROUP, group, [])
  937. elif string == '+':
  938. video_selector = current_selector
  939. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  940. if not video_selector or not audio_selector:
  941. raise syntax_error('"+" must be between two format selectors', start)
  942. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  943. else:
  944. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  945. elif type == tokenize.ENDMARKER:
  946. break
  947. if current_selector:
  948. selectors.append(current_selector)
  949. return selectors
  950. def _build_selector_function(selector):
  951. if isinstance(selector, list):
  952. fs = [_build_selector_function(s) for s in selector]
  953. def selector_function(formats):
  954. for f in fs:
  955. for format in f(formats):
  956. yield format
  957. return selector_function
  958. elif selector.type == GROUP:
  959. selector_function = _build_selector_function(selector.selector)
  960. elif selector.type == PICKFIRST:
  961. fs = [_build_selector_function(s) for s in selector.selector]
  962. def selector_function(formats):
  963. for f in fs:
  964. picked_formats = list(f(formats))
  965. if picked_formats:
  966. return picked_formats
  967. return []
  968. elif selector.type == SINGLE:
  969. format_spec = selector.selector
  970. def selector_function(formats):
  971. formats = list(formats)
  972. if not formats:
  973. return
  974. if format_spec == 'all':
  975. for f in formats:
  976. yield f
  977. elif format_spec in ['best', 'worst', None]:
  978. format_idx = 0 if format_spec == 'worst' else -1
  979. audiovideo_formats = [
  980. f for f in formats
  981. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  982. if audiovideo_formats:
  983. yield audiovideo_formats[format_idx]
  984. # for audio only (soundcloud) or video only (imgur) urls, select the best/worst audio format
  985. elif (all(f.get('acodec') != 'none' for f in formats) or
  986. all(f.get('vcodec') != 'none' for f in formats)):
  987. yield formats[format_idx]
  988. elif format_spec == 'bestaudio':
  989. audio_formats = [
  990. f for f in formats
  991. if f.get('vcodec') == 'none']
  992. if audio_formats:
  993. yield audio_formats[-1]
  994. elif format_spec == 'worstaudio':
  995. audio_formats = [
  996. f for f in formats
  997. if f.get('vcodec') == 'none']
  998. if audio_formats:
  999. yield audio_formats[0]
  1000. elif format_spec == 'bestvideo':
  1001. video_formats = [
  1002. f for f in formats
  1003. if f.get('acodec') == 'none']
  1004. if video_formats:
  1005. yield video_formats[-1]
  1006. elif format_spec == 'worstvideo':
  1007. video_formats = [
  1008. f for f in formats
  1009. if f.get('acodec') == 'none']
  1010. if video_formats:
  1011. yield video_formats[0]
  1012. else:
  1013. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1014. if format_spec in extensions:
  1015. filter_f = lambda f: f['ext'] == format_spec
  1016. else:
  1017. filter_f = lambda f: f['format_id'] == format_spec
  1018. matches = list(filter(filter_f, formats))
  1019. if matches:
  1020. yield matches[-1]
  1021. elif selector.type == MERGE:
  1022. def _merge(formats_info):
  1023. format_1, format_2 = [f['format_id'] for f in formats_info]
  1024. # The first format must contain the video and the
  1025. # second the audio
  1026. if formats_info[0].get('vcodec') == 'none':
  1027. self.report_error('The first format must '
  1028. 'contain the video, try using '
  1029. '"-f %s+%s"' % (format_2, format_1))
  1030. return
  1031. # Formats must be opposite (video+audio)
  1032. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1033. self.report_error(
  1034. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1035. % (format_1, format_2))
  1036. return
  1037. output_ext = (
  1038. formats_info[0]['ext']
  1039. if self.params.get('merge_output_format') is None
  1040. else self.params['merge_output_format'])
  1041. return {
  1042. 'requested_formats': formats_info,
  1043. 'format': '%s+%s' % (formats_info[0].get('format'),
  1044. formats_info[1].get('format')),
  1045. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1046. formats_info[1].get('format_id')),
  1047. 'width': formats_info[0].get('width'),
  1048. 'height': formats_info[0].get('height'),
  1049. 'resolution': formats_info[0].get('resolution'),
  1050. 'fps': formats_info[0].get('fps'),
  1051. 'vcodec': formats_info[0].get('vcodec'),
  1052. 'vbr': formats_info[0].get('vbr'),
  1053. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1054. 'acodec': formats_info[1].get('acodec'),
  1055. 'abr': formats_info[1].get('abr'),
  1056. 'ext': output_ext,
  1057. }
  1058. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1059. def selector_function(formats):
  1060. formats = list(formats)
  1061. for pair in itertools.product(video_selector(formats), audio_selector(formats)):
  1062. yield _merge(pair)
  1063. filters = [self._build_format_filter(f) for f in selector.filters]
  1064. def final_selector(formats):
  1065. for _filter in filters:
  1066. formats = list(filter(_filter, formats))
  1067. return selector_function(formats)
  1068. return final_selector
  1069. stream = io.BytesIO(format_spec.encode('utf-8'))
  1070. try:
  1071. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1072. except tokenize.TokenError:
  1073. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1074. class TokenIterator(object):
  1075. def __init__(self, tokens):
  1076. self.tokens = tokens
  1077. self.counter = 0
  1078. def __iter__(self):
  1079. return self
  1080. def __next__(self):
  1081. if self.counter >= len(self.tokens):
  1082. raise StopIteration()
  1083. value = self.tokens[self.counter]
  1084. self.counter += 1
  1085. return value
  1086. next = __next__
  1087. def restore_last_token(self):
  1088. self.counter -= 1
  1089. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1090. return _build_selector_function(parsed_selector)
  1091. def _calc_headers(self, info_dict):
  1092. res = std_headers.copy()
  1093. add_headers = info_dict.get('http_headers')
  1094. if add_headers:
  1095. res.update(add_headers)
  1096. cookies = self._calc_cookies(info_dict)
  1097. if cookies:
  1098. res['Cookie'] = cookies
  1099. return res
  1100. def _calc_cookies(self, info_dict):
  1101. pr = sanitized_Request(info_dict['url'])
  1102. self.cookiejar.add_cookie_header(pr)
  1103. return pr.get_header('Cookie')
  1104. def process_video_result(self, info_dict, download=True):
  1105. assert info_dict.get('_type', 'video') == 'video'
  1106. if 'id' not in info_dict:
  1107. raise ExtractorError('Missing "id" field in extractor result')
  1108. if 'title' not in info_dict:
  1109. raise ExtractorError('Missing "title" field in extractor result')
  1110. if 'playlist' not in info_dict:
  1111. # It isn't part of a playlist
  1112. info_dict['playlist'] = None
  1113. info_dict['playlist_index'] = None
  1114. thumbnails = info_dict.get('thumbnails')
  1115. if thumbnails is None:
  1116. thumbnail = info_dict.get('thumbnail')
  1117. if thumbnail:
  1118. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1119. if thumbnails:
  1120. thumbnails.sort(key=lambda t: (
  1121. t.get('preference'), t.get('width'), t.get('height'),
  1122. t.get('id'), t.get('url')))
  1123. for i, t in enumerate(thumbnails):
  1124. t['url'] = sanitize_url(t['url'])
  1125. if t.get('width') and t.get('height'):
  1126. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1127. if t.get('id') is None:
  1128. t['id'] = '%d' % i
  1129. if self.params.get('list_thumbnails'):
  1130. self.list_thumbnails(info_dict)
  1131. return
  1132. thumbnail = info_dict.get('thumbnail')
  1133. if thumbnail:
  1134. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1135. elif thumbnails:
  1136. info_dict['thumbnail'] = thumbnails[-1]['url']
  1137. if 'display_id' not in info_dict and 'id' in info_dict:
  1138. info_dict['display_id'] = info_dict['id']
  1139. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  1140. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1141. # see http://bugs.python.org/issue1646728)
  1142. try:
  1143. upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
  1144. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  1145. except (ValueError, OverflowError, OSError):
  1146. pass
  1147. # Auto generate title fields corresponding to the *_number fields when missing
  1148. # in order to always have clean titles. This is very common for TV series.
  1149. for field in ('chapter', 'season', 'episode'):
  1150. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1151. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1152. subtitles = info_dict.get('subtitles')
  1153. if subtitles:
  1154. for _, subtitle in subtitles.items():
  1155. for subtitle_format in subtitle:
  1156. if subtitle_format.get('url'):
  1157. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1158. if 'ext' not in subtitle_format:
  1159. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1160. if self.params.get('listsubtitles', False):
  1161. if 'automatic_captions' in info_dict:
  1162. self.list_subtitles(info_dict['id'], info_dict.get('automatic_captions'), 'automatic captions')
  1163. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1164. return
  1165. info_dict['requested_subtitles'] = self.process_subtitles(
  1166. info_dict['id'], subtitles,
  1167. info_dict.get('automatic_captions'))
  1168. # We now pick which formats have to be downloaded
  1169. if info_dict.get('formats') is None:
  1170. # There's only one format available
  1171. formats = [info_dict]
  1172. else:
  1173. formats = info_dict['formats']
  1174. if not formats:
  1175. raise ExtractorError('No video formats found!')
  1176. formats_dict = {}
  1177. # We check that all the formats have the format and format_id fields
  1178. for i, format in enumerate(formats):
  1179. if 'url' not in format:
  1180. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  1181. format['url'] = sanitize_url(format['url'])
  1182. if format.get('format_id') is None:
  1183. format['format_id'] = compat_str(i)
  1184. else:
  1185. # Sanitize format_id from characters used in format selector expression
  1186. format['format_id'] = re.sub('[\s,/+\[\]()]', '_', format['format_id'])
  1187. format_id = format['format_id']
  1188. if format_id not in formats_dict:
  1189. formats_dict[format_id] = []
  1190. formats_dict[format_id].append(format)
  1191. # Make sure all formats have unique format_id
  1192. for format_id, ambiguous_formats in formats_dict.items():
  1193. if len(ambiguous_formats) > 1:
  1194. for i, format in enumerate(ambiguous_formats):
  1195. format['format_id'] = '%s-%d' % (format_id, i)
  1196. for i, format in enumerate(formats):
  1197. if format.get('format') is None:
  1198. format['format'] = '{id} - {res}{note}'.format(
  1199. id=format['format_id'],
  1200. res=self.format_resolution(format),
  1201. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1202. )
  1203. # Automatically determine file extension if missing
  1204. if 'ext' not in format:
  1205. format['ext'] = determine_ext(format['url']).lower()
  1206. # Automatically determine protocol if missing (useful for format
  1207. # selection purposes)
  1208. if 'protocol' not in format:
  1209. format['protocol'] = determine_protocol(format)
  1210. # Add HTTP headers, so that external programs can use them from the
  1211. # json output
  1212. full_format_info = info_dict.copy()
  1213. full_format_info.update(format)
  1214. format['http_headers'] = self._calc_headers(full_format_info)
  1215. # TODO Central sorting goes here
  1216. if formats[0] is not info_dict:
  1217. # only set the 'formats' fields if the original info_dict list them
  1218. # otherwise we end up with a circular reference, the first (and unique)
  1219. # element in the 'formats' field in info_dict is info_dict itself,
  1220. # which can't be exported to json
  1221. info_dict['formats'] = formats
  1222. if self.params.get('listformats'):
  1223. self.list_formats(info_dict)
  1224. return
  1225. req_format = self.params.get('format')
  1226. if req_format is None:
  1227. req_format_list = []
  1228. if (self.params.get('outtmpl', DEFAULT_OUTTMPL) != '-' and
  1229. not info_dict.get('is_live')):
  1230. merger = FFmpegMergerPP(self)
  1231. if merger.available and merger.can_merge():
  1232. req_format_list.append('bestvideo+bestaudio')
  1233. req_format_list.append('best')
  1234. req_format = '/'.join(req_format_list)
  1235. format_selector = self.build_format_selector(req_format)
  1236. formats_to_download = list(format_selector(formats))
  1237. if not formats_to_download:
  1238. raise ExtractorError('requested format not available',
  1239. expected=True)
  1240. if download:
  1241. if len(formats_to_download) > 1:
  1242. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1243. for format in formats_to_download:
  1244. new_info = dict(info_dict)
  1245. new_info.update(format)
  1246. self.process_info(new_info)
  1247. # We update the info dict with the best quality format (backwards compatibility)
  1248. info_dict.update(formats_to_download[-1])
  1249. return info_dict
  1250. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1251. """Select the requested subtitles and their format"""
  1252. available_subs = {}
  1253. if normal_subtitles and self.params.get('writesubtitles'):
  1254. available_subs.update(normal_subtitles)
  1255. if automatic_captions and self.params.get('writeautomaticsub'):
  1256. for lang, cap_info in automatic_captions.items():
  1257. if lang not in available_subs:
  1258. available_subs[lang] = cap_info
  1259. if (not self.params.get('writesubtitles') and not
  1260. self.params.get('writeautomaticsub') or not
  1261. available_subs):
  1262. return None
  1263. if self.params.get('allsubtitles', False):
  1264. requested_langs = available_subs.keys()
  1265. else:
  1266. if self.params.get('subtitleslangs', False):
  1267. requested_langs = self.params.get('subtitleslangs')
  1268. elif 'en' in available_subs:
  1269. requested_langs = ['en']
  1270. else:
  1271. requested_langs = [list(available_subs.keys())[0]]
  1272. formats_query = self.params.get('subtitlesformat', 'best')
  1273. formats_preference = formats_query.split('/') if formats_query else []
  1274. subs = {}
  1275. for lang in requested_langs:
  1276. formats = available_subs.get(lang)
  1277. if formats is None:
  1278. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1279. continue
  1280. for ext in formats_preference:
  1281. if ext == 'best':
  1282. f = formats[-1]
  1283. break
  1284. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1285. if matches:
  1286. f = matches[-1]
  1287. break
  1288. else:
  1289. f = formats[-1]
  1290. self.report_warning(
  1291. 'No subtitle format found matching "%s" for language %s, '
  1292. 'using %s' % (formats_query, lang, f['ext']))
  1293. subs[lang] = f
  1294. return subs
  1295. def process_info(self, info_dict):
  1296. """Process a single resolved IE result."""
  1297. assert info_dict.get('_type', 'video') == 'video'
  1298. max_downloads = self.params.get('max_downloads')
  1299. if max_downloads is not None:
  1300. if self._num_downloads >= int(max_downloads):
  1301. raise MaxDownloadsReached()
  1302. info_dict['fulltitle'] = info_dict['title']
  1303. if len(info_dict['title']) > 200:
  1304. info_dict['title'] = info_dict['title'][:197] + '...'
  1305. if 'format' not in info_dict:
  1306. info_dict['format'] = info_dict['ext']
  1307. reason = self._match_entry(info_dict, incomplete=False)
  1308. if reason is not None:
  1309. self.to_screen('[download] ' + reason)
  1310. return
  1311. self._num_downloads += 1
  1312. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1313. # Forced printings
  1314. if self.params.get('forcetitle', False):
  1315. self.to_stdout(info_dict['fulltitle'])
  1316. if self.params.get('forceid', False):
  1317. self.to_stdout(info_dict['id'])
  1318. if self.params.get('forceurl', False):
  1319. if info_dict.get('requested_formats') is not None:
  1320. for f in info_dict['requested_formats']:
  1321. self.to_stdout(f['url'] + f.get('play_path', ''))
  1322. else:
  1323. # For RTMP URLs, also include the playpath
  1324. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1325. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1326. self.to_stdout(info_dict['thumbnail'])
  1327. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1328. self.to_stdout(info_dict['description'])
  1329. if self.params.get('forcefilename', False) and filename is not None:
  1330. self.to_stdout(filename)
  1331. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1332. self.to_stdout(formatSeconds(info_dict['duration']))
  1333. if self.params.get('forceformat', False):
  1334. self.to_stdout(info_dict['format'])
  1335. if self.params.get('forcejson', False):
  1336. self.to_stdout(json.dumps(info_dict))
  1337. # Do nothing else if in simulate mode
  1338. if self.params.get('simulate', False):
  1339. return
  1340. if filename is None:
  1341. return
  1342. try:
  1343. dn = os.path.dirname(sanitize_path(encodeFilename(filename)))
  1344. if dn and not os.path.exists(dn):
  1345. os.makedirs(dn)
  1346. except (OSError, IOError) as err:
  1347. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1348. return
  1349. if self.params.get('writedescription', False):
  1350. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1351. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1352. self.to_screen('[info] Video description is already present')
  1353. elif info_dict.get('description') is None:
  1354. self.report_warning('There\'s no description to write.')
  1355. else:
  1356. try:
  1357. self.to_screen('[info] Writing video description to: ' + descfn)
  1358. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1359. descfile.write(info_dict['description'])
  1360. except (OSError, IOError):
  1361. self.report_error('Cannot write description file ' + descfn)
  1362. return
  1363. if self.params.get('writeannotations', False):
  1364. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1365. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1366. self.to_screen('[info] Video annotations are already present')
  1367. else:
  1368. try:
  1369. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1370. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1371. annofile.write(info_dict['annotations'])
  1372. except (KeyError, TypeError):
  1373. self.report_warning('There are no annotations to write.')
  1374. except (OSError, IOError):
  1375. self.report_error('Cannot write annotations file: ' + annofn)
  1376. return
  1377. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1378. self.params.get('writeautomaticsub')])
  1379. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1380. # subtitles download errors are already managed as troubles in relevant IE
  1381. # that way it will silently go on when used with unsupporting IE
  1382. subtitles = info_dict['requested_subtitles']
  1383. ie = self.get_info_extractor(info_dict['extractor_key'])
  1384. for sub_lang, sub_info in subtitles.items():
  1385. sub_format = sub_info['ext']
  1386. if sub_info.get('data') is not None:
  1387. sub_data = sub_info['data']
  1388. else:
  1389. try:
  1390. sub_data = ie._download_webpage(
  1391. sub_info['url'], info_dict['id'], note=False)
  1392. except ExtractorError as err:
  1393. self.report_warning('Unable to download subtitle for "%s": %s' %
  1394. (sub_lang, error_to_compat_str(err.cause)))
  1395. continue
  1396. try:
  1397. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1398. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1399. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1400. else:
  1401. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1402. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1403. subfile.write(sub_data)
  1404. except (OSError, IOError):
  1405. self.report_error('Cannot write subtitles file ' + sub_filename)
  1406. return
  1407. if self.params.get('writeinfojson', False):
  1408. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1409. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1410. self.to_screen('[info] Video description metadata is already present')
  1411. else:
  1412. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1413. try:
  1414. write_json_file(self.filter_requested_info(info_dict), infofn)
  1415. except (OSError, IOError):
  1416. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1417. return
  1418. self._write_thumbnails(info_dict, filename)
  1419. if not self.params.get('skip_download', False):
  1420. try:
  1421. def dl(name, info):
  1422. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1423. for ph in self._progress_hooks:
  1424. fd.add_progress_hook(ph)
  1425. if self.params.get('verbose'):
  1426. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1427. return fd.download(name, info)
  1428. if info_dict.get('requested_formats') is not None:
  1429. downloaded = []
  1430. success = True
  1431. merger = FFmpegMergerPP(self)
  1432. if not merger.available:
  1433. postprocessors = []
  1434. self.report_warning('You have requested multiple '
  1435. 'formats but ffmpeg or avconv are not installed.'
  1436. ' The formats won\'t be merged.')
  1437. else:
  1438. postprocessors = [merger]
  1439. def compatible_formats(formats):
  1440. video, audio = formats
  1441. # Check extension
  1442. video_ext, audio_ext = audio.get('ext'), video.get('ext')
  1443. if video_ext and audio_ext:
  1444. COMPATIBLE_EXTS = (
  1445. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v'),
  1446. ('webm')
  1447. )
  1448. for exts in COMPATIBLE_EXTS:
  1449. if video_ext in exts and audio_ext in exts:
  1450. return True
  1451. # TODO: Check acodec/vcodec
  1452. return False
  1453. filename_real_ext = os.path.splitext(filename)[1][1:]
  1454. filename_wo_ext = (
  1455. os.path.splitext(filename)[0]
  1456. if filename_real_ext == info_dict['ext']
  1457. else filename)
  1458. requested_formats = info_dict['requested_formats']
  1459. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1460. info_dict['ext'] = 'mkv'
  1461. self.report_warning(
  1462. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1463. # Ensure filename always has a correct extension for successful merge
  1464. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1465. if os.path.exists(encodeFilename(filename)):
  1466. self.to_screen(
  1467. '[download] %s has already been downloaded and '
  1468. 'merged' % filename)
  1469. else:
  1470. for f in requested_formats:
  1471. new_info = dict(info_dict)
  1472. new_info.update(f)
  1473. fname = self.prepare_filename(new_info)
  1474. fname = prepend_extension(fname, 'f%s' % f['format_id'], new_info['ext'])
  1475. downloaded.append(fname)
  1476. partial_success = dl(fname, new_info)
  1477. success = success and partial_success
  1478. info_dict['__postprocessors'] = postprocessors
  1479. info_dict['__files_to_merge'] = downloaded
  1480. else:
  1481. # Just a single file
  1482. success = dl(filename, info_dict)
  1483. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1484. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1485. return
  1486. except (OSError, IOError) as err:
  1487. raise UnavailableVideoError(err)
  1488. except (ContentTooShortError, ) as err:
  1489. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1490. return
  1491. if success and filename != '-':
  1492. # Fixup content
  1493. fixup_policy = self.params.get('fixup')
  1494. if fixup_policy is None:
  1495. fixup_policy = 'detect_or_warn'
  1496. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1497. stretched_ratio = info_dict.get('stretched_ratio')
  1498. if stretched_ratio is not None and stretched_ratio != 1:
  1499. if fixup_policy == 'warn':
  1500. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1501. info_dict['id'], stretched_ratio))
  1502. elif fixup_policy == 'detect_or_warn':
  1503. stretched_pp = FFmpegFixupStretchedPP(self)
  1504. if stretched_pp.available:
  1505. info_dict.setdefault('__postprocessors', [])
  1506. info_dict['__postprocessors'].append(stretched_pp)
  1507. else:
  1508. self.report_warning(
  1509. '%s: Non-uniform pixel ratio (%s). %s'
  1510. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1511. else:
  1512. assert fixup_policy in ('ignore', 'never')
  1513. if (info_dict.get('requested_formats') is None and
  1514. info_dict.get('container') == 'm4a_dash'):
  1515. if fixup_policy == 'warn':
  1516. self.report_warning(
  1517. '%s: writing DASH m4a. '
  1518. 'Only some players support this container.'
  1519. % info_dict['id'])
  1520. elif fixup_policy == 'detect_or_warn':
  1521. fixup_pp = FFmpegFixupM4aPP(self)
  1522. if fixup_pp.available:
  1523. info_dict.setdefault('__postprocessors', [])
  1524. info_dict['__postprocessors'].append(fixup_pp)
  1525. else:
  1526. self.report_warning(
  1527. '%s: writing DASH m4a. '
  1528. 'Only some players support this container. %s'
  1529. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1530. else:
  1531. assert fixup_policy in ('ignore', 'never')
  1532. if (info_dict.get('protocol') == 'm3u8_native' or
  1533. info_dict.get('protocol') == 'm3u8' and
  1534. self.params.get('hls_prefer_native')):
  1535. if fixup_policy == 'warn':
  1536. self.report_warning('%s: malformated aac bitstream.' % (
  1537. info_dict['id']))
  1538. elif fixup_policy == 'detect_or_warn':
  1539. fixup_pp = FFmpegFixupM3u8PP(self)
  1540. if fixup_pp.available:
  1541. info_dict.setdefault('__postprocessors', [])
  1542. info_dict['__postprocessors'].append(fixup_pp)
  1543. else:
  1544. self.report_warning(
  1545. '%s: malformated aac bitstream. %s'
  1546. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1547. else:
  1548. assert fixup_policy in ('ignore', 'never')
  1549. try:
  1550. self.post_process(filename, info_dict)
  1551. except (PostProcessingError) as err:
  1552. self.report_error('postprocessing: %s' % str(err))
  1553. return
  1554. self.record_download_archive(info_dict)
  1555. def download(self, url_list):
  1556. """Download a given list of URLs."""
  1557. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1558. if (len(url_list) > 1 and
  1559. '%' not in outtmpl and
  1560. self.params.get('max_downloads') != 1):
  1561. raise SameFileError(outtmpl)
  1562. for url in url_list:
  1563. try:
  1564. # It also downloads the videos
  1565. res = self.extract_info(
  1566. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1567. except UnavailableVideoError:
  1568. self.report_error('unable to download video')
  1569. except MaxDownloadsReached:
  1570. self.to_screen('[info] Maximum number of downloaded files reached.')
  1571. raise
  1572. else:
  1573. if self.params.get('dump_single_json', False):
  1574. self.to_stdout(json.dumps(res))
  1575. return self._download_retcode
  1576. def download_with_info_file(self, info_filename):
  1577. with contextlib.closing(fileinput.FileInput(
  1578. [info_filename], mode='r',
  1579. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1580. # FileInput doesn't have a read method, we can't call json.load
  1581. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1582. try:
  1583. self.process_ie_result(info, download=True)
  1584. except DownloadError:
  1585. webpage_url = info.get('webpage_url')
  1586. if webpage_url is not None:
  1587. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1588. return self.download([webpage_url])
  1589. else:
  1590. raise
  1591. return self._download_retcode
  1592. @staticmethod
  1593. def filter_requested_info(info_dict):
  1594. return dict(
  1595. (k, v) for k, v in info_dict.items()
  1596. if k not in ['requested_formats', 'requested_subtitles'])
  1597. def post_process(self, filename, ie_info):
  1598. """Run all the postprocessors on the given file."""
  1599. info = dict(ie_info)
  1600. info['filepath'] = filename
  1601. pps_chain = []
  1602. if ie_info.get('__postprocessors') is not None:
  1603. pps_chain.extend(ie_info['__postprocessors'])
  1604. pps_chain.extend(self._pps)
  1605. for pp in pps_chain:
  1606. files_to_delete = []
  1607. try:
  1608. files_to_delete, info = pp.run(info)
  1609. except PostProcessingError as e:
  1610. self.report_error(e.msg)
  1611. if files_to_delete and not self.params.get('keepvideo', False):
  1612. for old_filename in files_to_delete:
  1613. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1614. try:
  1615. os.remove(encodeFilename(old_filename))
  1616. except (IOError, OSError):
  1617. self.report_warning('Unable to remove downloaded original file')
  1618. def _make_archive_id(self, info_dict):
  1619. # Future-proof against any change in case
  1620. # and backwards compatibility with prior versions
  1621. extractor = info_dict.get('extractor_key')
  1622. if extractor is None:
  1623. if 'id' in info_dict:
  1624. extractor = info_dict.get('ie_key') # key in a playlist
  1625. if extractor is None:
  1626. return None # Incomplete video information
  1627. return extractor.lower() + ' ' + info_dict['id']
  1628. def in_download_archive(self, info_dict):
  1629. fn = self.params.get('download_archive')
  1630. if fn is None:
  1631. return False
  1632. vid_id = self._make_archive_id(info_dict)
  1633. if vid_id is None:
  1634. return False # Incomplete video information
  1635. try:
  1636. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1637. for line in archive_file:
  1638. if line.strip() == vid_id:
  1639. return True
  1640. except IOError as ioe:
  1641. if ioe.errno != errno.ENOENT:
  1642. raise
  1643. return False
  1644. def record_download_archive(self, info_dict):
  1645. fn = self.params.get('download_archive')
  1646. if fn is None:
  1647. return
  1648. vid_id = self._make_archive_id(info_dict)
  1649. assert vid_id
  1650. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1651. archive_file.write(vid_id + '\n')
  1652. @staticmethod
  1653. def format_resolution(format, default='unknown'):
  1654. if format.get('vcodec') == 'none':
  1655. return 'audio only'
  1656. if format.get('resolution') is not None:
  1657. return format['resolution']
  1658. if format.get('height') is not None:
  1659. if format.get('width') is not None:
  1660. res = '%sx%s' % (format['width'], format['height'])
  1661. else:
  1662. res = '%sp' % format['height']
  1663. elif format.get('width') is not None:
  1664. res = '%dx?' % format['width']
  1665. else:
  1666. res = default
  1667. return res
  1668. def _format_note(self, fdict):
  1669. res = ''
  1670. if fdict.get('ext') in ['f4f', 'f4m']:
  1671. res += '(unsupported) '
  1672. if fdict.get('language'):
  1673. if res:
  1674. res += ' '
  1675. res += '[%s] ' % fdict['language']
  1676. if fdict.get('format_note') is not None:
  1677. res += fdict['format_note'] + ' '
  1678. if fdict.get('tbr') is not None:
  1679. res += '%4dk ' % fdict['tbr']
  1680. if fdict.get('container') is not None:
  1681. if res:
  1682. res += ', '
  1683. res += '%s container' % fdict['container']
  1684. if (fdict.get('vcodec') is not None and
  1685. fdict.get('vcodec') != 'none'):
  1686. if res:
  1687. res += ', '
  1688. res += fdict['vcodec']
  1689. if fdict.get('vbr') is not None:
  1690. res += '@'
  1691. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1692. res += 'video@'
  1693. if fdict.get('vbr') is not None:
  1694. res += '%4dk' % fdict['vbr']
  1695. if fdict.get('fps') is not None:
  1696. if res:
  1697. res += ', '
  1698. res += '%sfps' % fdict['fps']
  1699. if fdict.get('acodec') is not None:
  1700. if res:
  1701. res += ', '
  1702. if fdict['acodec'] == 'none':
  1703. res += 'video only'
  1704. else:
  1705. res += '%-5s' % fdict['acodec']
  1706. elif fdict.get('abr') is not None:
  1707. if res:
  1708. res += ', '
  1709. res += 'audio'
  1710. if fdict.get('abr') is not None:
  1711. res += '@%3dk' % fdict['abr']
  1712. if fdict.get('asr') is not None:
  1713. res += ' (%5dHz)' % fdict['asr']
  1714. if fdict.get('filesize') is not None:
  1715. if res:
  1716. res += ', '
  1717. res += format_bytes(fdict['filesize'])
  1718. elif fdict.get('filesize_approx') is not None:
  1719. if res:
  1720. res += ', '
  1721. res += '~' + format_bytes(fdict['filesize_approx'])
  1722. return res
  1723. def list_formats(self, info_dict):
  1724. formats = info_dict.get('formats', [info_dict])
  1725. table = [
  1726. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1727. for f in formats
  1728. if f.get('preference') is None or f['preference'] >= -1000]
  1729. if len(formats) > 1:
  1730. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1731. header_line = ['format code', 'extension', 'resolution', 'note']
  1732. self.to_screen(
  1733. '[info] Available formats for %s:\n%s' %
  1734. (info_dict['id'], render_table(header_line, table)))
  1735. def list_thumbnails(self, info_dict):
  1736. thumbnails = info_dict.get('thumbnails')
  1737. if not thumbnails:
  1738. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  1739. return
  1740. self.to_screen(
  1741. '[info] Thumbnails for %s:' % info_dict['id'])
  1742. self.to_screen(render_table(
  1743. ['ID', 'width', 'height', 'URL'],
  1744. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1745. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1746. if not subtitles:
  1747. self.to_screen('%s has no %s' % (video_id, name))
  1748. return
  1749. self.to_screen(
  1750. 'Available %s for %s:' % (name, video_id))
  1751. self.to_screen(render_table(
  1752. ['Language', 'formats'],
  1753. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  1754. for lang, formats in subtitles.items()]))
  1755. def urlopen(self, req):
  1756. """ Start an HTTP download """
  1757. if isinstance(req, compat_basestring):
  1758. req = sanitized_Request(req)
  1759. return self._opener.open(req, timeout=self._socket_timeout)
  1760. def print_debug_header(self):
  1761. if not self.params.get('verbose'):
  1762. return
  1763. if type('') is not compat_str:
  1764. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1765. self.report_warning(
  1766. 'Your Python is broken! Update to a newer and supported version')
  1767. stdout_encoding = getattr(
  1768. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1769. encoding_str = (
  1770. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1771. locale.getpreferredencoding(),
  1772. sys.getfilesystemencoding(),
  1773. stdout_encoding,
  1774. self.get_encoding()))
  1775. write_string(encoding_str, encoding=None)
  1776. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1777. if _LAZY_LOADER:
  1778. self._write_string('[debug] Lazy loading extractors enabled' + '\n')
  1779. try:
  1780. sp = subprocess.Popen(
  1781. ['git', 'rev-parse', '--short', 'HEAD'],
  1782. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1783. cwd=os.path.dirname(os.path.abspath(__file__)))
  1784. out, err = sp.communicate()
  1785. out = out.decode().strip()
  1786. if re.match('[0-9a-f]+', out):
  1787. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1788. except Exception:
  1789. try:
  1790. sys.exc_clear()
  1791. except Exception:
  1792. pass
  1793. self._write_string('[debug] Python version %s - %s\n' % (
  1794. platform.python_version(), platform_name()))
  1795. exe_versions = FFmpegPostProcessor.get_versions(self)
  1796. exe_versions['rtmpdump'] = rtmpdump_version()
  1797. exe_str = ', '.join(
  1798. '%s %s' % (exe, v)
  1799. for exe, v in sorted(exe_versions.items())
  1800. if v
  1801. )
  1802. if not exe_str:
  1803. exe_str = 'none'
  1804. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1805. proxy_map = {}
  1806. for handler in self._opener.handlers:
  1807. if hasattr(handler, 'proxies'):
  1808. proxy_map.update(handler.proxies)
  1809. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1810. if self.params.get('call_home', False):
  1811. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1812. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1813. latest_version = self.urlopen(
  1814. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1815. if version_tuple(latest_version) > version_tuple(__version__):
  1816. self.report_warning(
  1817. 'You are using an outdated version (newest version: %s)! '
  1818. 'See https://yt-dl.org/update if you need help updating.' %
  1819. latest_version)
  1820. def _setup_opener(self):
  1821. timeout_val = self.params.get('socket_timeout')
  1822. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1823. opts_cookiefile = self.params.get('cookiefile')
  1824. opts_proxy = self.params.get('proxy')
  1825. if opts_cookiefile is None:
  1826. self.cookiejar = compat_cookiejar.CookieJar()
  1827. else:
  1828. opts_cookiefile = compat_expanduser(opts_cookiefile)
  1829. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1830. opts_cookiefile)
  1831. if os.access(opts_cookiefile, os.R_OK):
  1832. self.cookiejar.load()
  1833. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  1834. if opts_proxy is not None:
  1835. if opts_proxy == '':
  1836. proxies = {}
  1837. else:
  1838. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1839. else:
  1840. proxies = compat_urllib_request.getproxies()
  1841. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1842. if 'http' in proxies and 'https' not in proxies:
  1843. proxies['https'] = proxies['http']
  1844. proxy_handler = PerRequestProxyHandler(proxies)
  1845. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1846. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1847. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1848. data_handler = compat_urllib_request_DataHandler()
  1849. # When passing our own FileHandler instance, build_opener won't add the
  1850. # default FileHandler and allows us to disable the file protocol, which
  1851. # can be used for malicious purposes (see
  1852. # https://github.com/rg3/youtube-dl/issues/8227)
  1853. file_handler = compat_urllib_request.FileHandler()
  1854. def file_open(*args, **kwargs):
  1855. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  1856. file_handler.file_open = file_open
  1857. opener = compat_urllib_request.build_opener(
  1858. proxy_handler, https_handler, cookie_processor, ydlh, data_handler, file_handler)
  1859. # Delete the default user-agent header, which would otherwise apply in
  1860. # cases where our custom HTTP handler doesn't come into play
  1861. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1862. opener.addheaders = []
  1863. self._opener = opener
  1864. def encode(self, s):
  1865. if isinstance(s, bytes):
  1866. return s # Already encoded
  1867. try:
  1868. return s.encode(self.get_encoding())
  1869. except UnicodeEncodeError as err:
  1870. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1871. raise
  1872. def get_encoding(self):
  1873. encoding = self.params.get('encoding')
  1874. if encoding is None:
  1875. encoding = preferredencoding()
  1876. return encoding
  1877. def _write_thumbnails(self, info_dict, filename):
  1878. if self.params.get('writethumbnail', False):
  1879. thumbnails = info_dict.get('thumbnails')
  1880. if thumbnails:
  1881. thumbnails = [thumbnails[-1]]
  1882. elif self.params.get('write_all_thumbnails', False):
  1883. thumbnails = info_dict.get('thumbnails')
  1884. else:
  1885. return
  1886. if not thumbnails:
  1887. # No thumbnails present, so return immediately
  1888. return
  1889. for t in thumbnails:
  1890. thumb_ext = determine_ext(t['url'], 'jpg')
  1891. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1892. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1893. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1894. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1895. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1896. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1897. else:
  1898. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1899. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1900. try:
  1901. uf = self.urlopen(t['url'])
  1902. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  1903. shutil.copyfileobj(uf, thumbf)
  1904. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1905. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1906. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1907. self.report_warning('Unable to download thumbnail "%s": %s' %
  1908. (t['url'], error_to_compat_str(err)))