logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

YoutubeDL.py (122316B)


  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import copy
  6. import datetime
  7. import errno
  8. import io
  9. import itertools
  10. import json
  11. import locale
  12. import operator
  13. import os
  14. import platform
  15. import re
  16. import shutil
  17. import subprocess
  18. import socket
  19. import sys
  20. import time
  21. import tokenize
  22. import traceback
  23. import random
  24. try:
  25. from ssl import OPENSSL_VERSION
  26. except ImportError:
  27. # Must be Python 2.6, should be built against 1.0.2
  28. OPENSSL_VERSION = 'OpenSSL 1.0.2(?)'
  29. from string import ascii_letters
  30. from .compat import (
  31. compat_basestring,
  32. compat_collections_chain_map as ChainMap,
  33. compat_filter as filter,
  34. compat_get_terminal_size,
  35. compat_http_client,
  36. compat_http_cookiejar_Cookie,
  37. compat_http_cookies_SimpleCookie,
  38. compat_integer_types,
  39. compat_kwargs,
  40. compat_map as map,
  41. compat_numeric_types,
  42. compat_open as open,
  43. compat_os_name,
  44. compat_str,
  45. compat_tokenize_tokenize,
  46. compat_urllib_error,
  47. compat_urllib_parse,
  48. compat_urllib_request,
  49. compat_urllib_request_DataHandler,
  50. )
  51. from .utils import (
  52. age_restricted,
  53. args_to_str,
  54. bug_reports_message,
  55. ContentTooShortError,
  56. date_from_str,
  57. DateRange,
  58. DEFAULT_OUTTMPL,
  59. determine_ext,
  60. determine_protocol,
  61. DownloadError,
  62. encode_compat_str,
  63. encodeFilename,
  64. error_to_compat_str,
  65. expand_path,
  66. ExtractorError,
  67. format_bytes,
  68. formatSeconds,
  69. GeoRestrictedError,
  70. int_or_none,
  71. ISO3166Utils,
  72. join_nonempty,
  73. locked_file,
  74. LazyList,
  75. make_HTTPS_handler,
  76. MaxDownloadsReached,
  77. orderedSet,
  78. PagedList,
  79. parse_filesize,
  80. PerRequestProxyHandler,
  81. platform_name,
  82. PostProcessingError,
  83. preferredencoding,
  84. prepend_extension,
  85. process_communicate_or_kill,
  86. register_socks_protocols,
  87. render_table,
  88. replace_extension,
  89. SameFileError,
  90. sanitize_filename,
  91. sanitize_path,
  92. sanitize_url,
  93. sanitized_Request,
  94. std_headers,
  95. str_or_none,
  96. subtitles_filename,
  97. traverse_obj,
  98. UnavailableVideoError,
  99. url_basename,
  100. version_tuple,
  101. write_json_file,
  102. write_string,
  103. YoutubeDLCookieJar,
  104. YoutubeDLCookieProcessor,
  105. YoutubeDLHandler,
  106. YoutubeDLRedirectHandler,
  107. ytdl_is_updateable,
  108. )
  109. from .cache import Cache
  110. from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
  111. from .extractor.openload import PhantomJSwrapper
  112. from .downloader import get_suitable_downloader
  113. from .downloader.rtmp import rtmpdump_version
  114. from .postprocessor import (
  115. FFmpegFixupM3u8PP,
  116. FFmpegFixupM4aPP,
  117. FFmpegFixupStretchedPP,
  118. FFmpegMergerPP,
  119. FFmpegPostProcessor,
  120. get_postprocessor,
  121. )
  122. from .version import __version__
  123. if compat_os_name == 'nt':
  124. import ctypes
  125. class YoutubeDL(object):
  126. """YoutubeDL class.
  127. YoutubeDL objects are the ones responsible of downloading the
  128. actual video file and writing it to disk if the user has requested
  129. it, among some other tasks. In most cases there should be one per
  130. program. As, given a video URL, the downloader doesn't know how to
  131. extract all the needed information, task that InfoExtractors do, it
  132. has to pass the URL to one of them.
  133. For this, YoutubeDL objects have a method that allows
  134. InfoExtractors to be registered in a given order. When it is passed
  135. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  136. finds that reports being able to handle it. The InfoExtractor extracts
  137. all the information about the video or videos the URL refers to, and
  138. YoutubeDL process the extracted information, possibly using a File
  139. Downloader to download the video.
  140. YoutubeDL objects accept a lot of parameters. In order not to saturate
  141. the object constructor with arguments, it receives a dictionary of
  142. options instead. These options are available through the params
  143. attribute for the InfoExtractors to use. The YoutubeDL also
  144. registers itself as the downloader in charge for the InfoExtractors
  145. that are added to it, so this is a "mutual registration".
  146. Available options:
  147. username: Username for authentication purposes.
  148. password: Password for authentication purposes.
  149. videopassword: Password for accessing a video.
  150. ap_mso: Adobe Pass multiple-system operator identifier.
  151. ap_username: Multiple-system operator account username.
  152. ap_password: Multiple-system operator account password.
  153. usenetrc: Use netrc for authentication instead.
  154. verbose: Print additional info to stdout.
  155. quiet: Do not print messages to stdout.
  156. no_warnings: Do not print out anything for warnings.
  157. forceurl: Force printing final URL.
  158. forcetitle: Force printing title.
  159. forceid: Force printing ID.
  160. forcethumbnail: Force printing thumbnail URL.
  161. forcedescription: Force printing description.
  162. forcefilename: Force printing final filename.
  163. forceduration: Force printing duration.
  164. forcejson: Force printing info_dict as JSON.
  165. dump_single_json: Force printing the info_dict of the whole playlist
  166. (or video) as a single JSON line.
  167. simulate: Do not download the video files.
  168. format: Video format code. See options.py for more information.
  169. outtmpl: Template for output names.
  170. outtmpl_na_placeholder: Placeholder for unavailable meta fields.
  171. restrictfilenames: Do not allow "&" and spaces in file names
  172. ignoreerrors: Do not stop on download errors.
  173. force_generic_extractor: Force downloader to use the generic extractor
  174. nooverwrites: Prevent overwriting files.
  175. playliststart: Playlist item to start at.
  176. playlistend: Playlist item to end at.
  177. playlist_items: Specific indices of playlist to download.
  178. playlistreverse: Download playlist items in reverse order.
  179. playlistrandom: Download playlist items in random order.
  180. matchtitle: Download only matching titles.
  181. rejecttitle: Reject downloads for matching titles.
  182. logger: Log messages to a logging.Logger instance.
  183. logtostderr: Log messages to stderr instead of stdout.
  184. writedescription: Write the video description to a .description file
  185. writeinfojson: Write the video description to a .info.json file
  186. writeannotations: Write the video annotations to a .annotations.xml file
  187. writethumbnail: Write the thumbnail image to a file
  188. write_all_thumbnails: Write all thumbnail formats to files
  189. writesubtitles: Write the video subtitles to a file
  190. writeautomaticsub: Write the automatically generated subtitles to a file
  191. allsubtitles: Downloads all the subtitles of the video
  192. (requires writesubtitles or writeautomaticsub)
  193. listsubtitles: Lists all available subtitles for the video
  194. subtitlesformat: The format code for subtitles
  195. subtitleslangs: List of languages of the subtitles to download
  196. keepvideo: Keep the video file after post-processing
  197. daterange: A DateRange object, download only if the upload_date is in the range.
  198. skip_download: Skip the actual download of the video file
  199. cachedir: Location of the cache files in the filesystem.
  200. False to disable filesystem cache.
  201. noplaylist: Download single video instead of a playlist if in doubt.
  202. age_limit: An integer representing the user's age in years.
  203. Unsuitable videos for the given age are skipped.
  204. min_views: An integer representing the minimum view count the video
  205. must have in order to not be skipped.
  206. Videos without view count information are always
  207. downloaded. None for no limit.
  208. max_views: An integer representing the maximum view count.
  209. Videos that are more popular than that are not
  210. downloaded.
  211. Videos without view count information are always
  212. downloaded. None for no limit.
  213. download_archive: File name of a file where all downloads are recorded.
  214. Videos already present in the file are not downloaded
  215. again.
  216. cookiefile: File name where cookies should be read from and dumped to.
  217. nocheckcertificate:Do not verify SSL certificates
  218. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  219. At the moment, this is only supported by YouTube.
  220. proxy: URL of the proxy server to use
  221. geo_verification_proxy: URL of the proxy to use for IP address verification
  222. on geo-restricted sites.
  223. socket_timeout: Time to wait for unresponsive hosts, in seconds
  224. bidi_workaround: Work around buggy terminals without bidirectional text
  225. support, using fridibi
  226. debug_printtraffic:Print out sent and received HTTP traffic
  227. include_ads: Download ads as well
  228. default_search: Prepend this string if an input url is not valid.
  229. 'auto' for elaborate guessing
  230. encoding: Use this encoding instead of the system-specified.
  231. extract_flat: Do not resolve URLs, return the immediate result.
  232. Pass in 'in_playlist' to only show this behavior for
  233. playlist items.
  234. postprocessors: A list of dictionaries, each with an entry
  235. * key: The name of the postprocessor. See
  236. youtube_dl/postprocessor/__init__.py for a list.
  237. as well as any further keyword arguments for the
  238. postprocessor.
  239. progress_hooks: A list of functions that get called on download
  240. progress, with a dictionary with the entries
  241. * status: One of "downloading", "error", or "finished".
  242. Check this first and ignore unknown values.
  243. If status is one of "downloading", or "finished", the
  244. following properties may also be present:
  245. * filename: The final filename (always present)
  246. * tmpfilename: The filename we're currently writing to
  247. * downloaded_bytes: Bytes on disk
  248. * total_bytes: Size of the whole file, None if unknown
  249. * total_bytes_estimate: Guess of the eventual file size,
  250. None if unavailable.
  251. * elapsed: The number of seconds since download started.
  252. * eta: The estimated time in seconds, None if unknown
  253. * speed: The download speed in bytes/second, None if
  254. unknown
  255. * fragment_index: The counter of the currently
  256. downloaded video fragment.
  257. * fragment_count: The number of fragments (= individual
  258. files that will be merged)
  259. Progress hooks are guaranteed to be called at least once
  260. (with status "finished") if the download is successful.
  261. merge_output_format: Extension to use when merging formats.
  262. fixup: Automatically correct known faults of the file.
  263. One of:
  264. - "never": do nothing
  265. - "warn": only emit a warning
  266. - "detect_or_warn": check whether we can do anything
  267. about it, warn otherwise (default)
  268. source_address: Client-side IP address to bind to.
  269. call_home: Boolean, true iff we are allowed to contact the
  270. youtube-dl servers for debugging.
  271. sleep_interval: Number of seconds to sleep before each download when
  272. used alone or a lower bound of a range for randomized
  273. sleep before each download (minimum possible number
  274. of seconds to sleep) when used along with
  275. max_sleep_interval.
  276. max_sleep_interval:Upper bound of a range for randomized sleep before each
  277. download (maximum possible number of seconds to sleep).
  278. Must only be used along with sleep_interval.
  279. Actual sleep time will be a random float from range
  280. [sleep_interval; max_sleep_interval].
  281. listformats: Print an overview of available video formats and exit.
  282. list_thumbnails: Print a table of all thumbnails and exit.
  283. match_filter: A function that gets called with the info_dict of
  284. every video.
  285. If it returns a message, the video is ignored.
  286. If it returns None, the video is downloaded.
  287. match_filter_func in utils.py is one example for this.
  288. no_color: Do not emit color codes in output.
  289. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
  290. HTTP header
  291. geo_bypass_country:
  292. Two-letter ISO 3166-2 country code that will be used for
  293. explicit geographic restriction bypassing via faking
  294. X-Forwarded-For HTTP header
  295. geo_bypass_ip_block:
  296. IP range in CIDR notation that will be used similarly to
  297. geo_bypass_country
  298. The following options determine which downloader is picked:
  299. external_downloader: Executable of the external downloader to call.
  300. None or unset for standard (built-in) downloader.
  301. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
  302. if True, otherwise use ffmpeg/avconv if False, otherwise
  303. use downloader suggested by extractor if None.
  304. The following parameters are not used by YoutubeDL itself, they are used by
  305. the downloader (see youtube_dl/downloader/common.py):
  306. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  307. noresizebuffer, retries, continuedl, noprogress, consoletitle,
  308. xattr_set_filesize, external_downloader_args, hls_use_mpegts,
  309. http_chunk_size.
  310. The following options are used by the post processors:
  311. prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
  312. otherwise prefer ffmpeg.
  313. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
  314. to the binary or its containing directory.
  315. postprocessor_args: A list of additional command-line arguments for the
  316. postprocessor.
  317. The following options are used by the Youtube extractor:
  318. youtube_include_dash_manifest: If True (default), DASH manifests and related
  319. data will be downloaded and processed by extractor.
  320. You can reduce network I/O by disabling it if you don't
  321. care about DASH.
  322. """
  323. _NUMERIC_FIELDS = set((
  324. 'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
  325. 'timestamp', 'upload_year', 'upload_month', 'upload_day',
  326. 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
  327. 'average_rating', 'comment_count', 'age_limit',
  328. 'start_time', 'end_time',
  329. 'chapter_number', 'season_number', 'episode_number',
  330. 'track_number', 'disc_number', 'release_year',
  331. 'playlist_index',
  332. ))
  333. params = None
  334. _ies = []
  335. _pps = []
  336. _download_retcode = None
  337. _num_downloads = None
  338. _playlist_level = 0
  339. _playlist_urls = set()
  340. _screen_file = None
  341. def __init__(self, params=None, auto_init=True):
  342. """Create a FileDownloader object with the given options."""
  343. if params is None:
  344. params = {}
  345. self._ies = []
  346. self._ies_instances = {}
  347. self._pps = []
  348. self._progress_hooks = []
  349. self._download_retcode = 0
  350. self._num_downloads = 0
  351. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  352. self._err_file = sys.stderr
  353. self.params = {
  354. # Default parameters
  355. 'nocheckcertificate': False,
  356. }
  357. self.params.update(params)
  358. self.cache = Cache(self)
  359. self._header_cookies = []
  360. self._load_cookies_from_headers(self.params.get('http_headers'))
  361. def check_deprecated(param, option, suggestion):
  362. if self.params.get(param) is not None:
  363. self.report_warning(
  364. '%s is deprecated. Use %s instead.' % (option, suggestion))
  365. return True
  366. return False
  367. if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
  368. if self.params.get('geo_verification_proxy') is None:
  369. self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
  370. check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
  371. check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
  372. check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
  373. if params.get('bidi_workaround', False):
  374. try:
  375. import pty
  376. master, slave = pty.openpty()
  377. width = compat_get_terminal_size().columns
  378. if width is None:
  379. width_args = []
  380. else:
  381. width_args = ['-w', str(width)]
  382. sp_kwargs = dict(
  383. stdin=subprocess.PIPE,
  384. stdout=slave,
  385. stderr=self._err_file)
  386. try:
  387. self._output_process = subprocess.Popen(
  388. ['bidiv'] + width_args, **sp_kwargs
  389. )
  390. except OSError:
  391. self._output_process = subprocess.Popen(
  392. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  393. self._output_channel = os.fdopen(master, 'rb')
  394. except OSError as ose:
  395. if ose.errno == errno.ENOENT:
  396. 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.')
  397. else:
  398. raise
  399. if (sys.platform != 'win32'
  400. and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  401. and not params.get('restrictfilenames', False)):
  402. # Unicode filesystem API will throw errors (#1474, #13027)
  403. self.report_warning(
  404. 'Assuming --restrict-filenames since file system encoding '
  405. 'cannot encode all characters. '
  406. 'Set the LC_ALL environment variable to fix this.')
  407. self.params['restrictfilenames'] = True
  408. if isinstance(params.get('outtmpl'), bytes):
  409. self.report_warning(
  410. 'Parameter outtmpl is bytes, but should be a unicode string. '
  411. 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
  412. self._setup_opener()
  413. if auto_init:
  414. self.print_debug_header()
  415. self.add_default_info_extractors()
  416. for pp_def_raw in self.params.get('postprocessors', []):
  417. pp_class = get_postprocessor(pp_def_raw['key'])
  418. pp_def = dict(pp_def_raw)
  419. del pp_def['key']
  420. pp = pp_class(self, **compat_kwargs(pp_def))
  421. self.add_post_processor(pp)
  422. for ph in self.params.get('progress_hooks', []):
  423. self.add_progress_hook(ph)
  424. register_socks_protocols()
  425. def warn_if_short_id(self, argv):
  426. # short YouTube ID starting with dash?
  427. idxs = [
  428. i for i, a in enumerate(argv)
  429. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  430. if idxs:
  431. correct_argv = (
  432. ['youtube-dl']
  433. + [a for i, a in enumerate(argv) if i not in idxs]
  434. + ['--'] + [argv[i] for i in idxs]
  435. )
  436. self.report_warning(
  437. 'Long argument string detected. '
  438. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  439. args_to_str(correct_argv))
  440. def add_info_extractor(self, ie):
  441. """Add an InfoExtractor object to the end of the list."""
  442. self._ies.append(ie)
  443. if not isinstance(ie, type):
  444. self._ies_instances[ie.ie_key()] = ie
  445. ie.set_downloader(self)
  446. def get_info_extractor(self, ie_key):
  447. """
  448. Get an instance of an IE with name ie_key, it will try to get one from
  449. the _ies list, if there's no instance it will create a new one and add
  450. it to the extractor list.
  451. """
  452. ie = self._ies_instances.get(ie_key)
  453. if ie is None:
  454. ie = get_info_extractor(ie_key)()
  455. self.add_info_extractor(ie)
  456. return ie
  457. def add_default_info_extractors(self):
  458. """
  459. Add the InfoExtractors returned by gen_extractors to the end of the list
  460. """
  461. for ie in gen_extractor_classes():
  462. self.add_info_extractor(ie)
  463. def add_post_processor(self, pp):
  464. """Add a PostProcessor object to the end of the chain."""
  465. self._pps.append(pp)
  466. pp.set_downloader(self)
  467. def add_progress_hook(self, ph):
  468. """Add the progress hook (currently only for the file downloader)"""
  469. self._progress_hooks.append(ph)
  470. def _bidi_workaround(self, message):
  471. if not hasattr(self, '_output_channel'):
  472. return message
  473. assert hasattr(self, '_output_process')
  474. assert isinstance(message, compat_str)
  475. line_count = message.count('\n') + 1
  476. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  477. self._output_process.stdin.flush()
  478. res = ''.join(self._output_channel.readline().decode('utf-8')
  479. for _ in range(line_count))
  480. return res[:-len('\n')]
  481. def to_screen(self, message, skip_eol=False):
  482. """Print message to stdout if not in quiet mode."""
  483. return self.to_stdout(message, skip_eol, check_quiet=True)
  484. def _write_string(self, s, out=None):
  485. write_string(s, out=out, encoding=self.params.get('encoding'))
  486. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  487. """Print message to stdout if not in quiet mode."""
  488. if self.params.get('logger'):
  489. self.params['logger'].debug(message)
  490. elif not check_quiet or not self.params.get('quiet', False):
  491. message = self._bidi_workaround(message)
  492. terminator = ['\n', ''][skip_eol]
  493. output = message + terminator
  494. self._write_string(output, self._screen_file)
  495. def to_stderr(self, message):
  496. """Print message to stderr."""
  497. assert isinstance(message, compat_str)
  498. if self.params.get('logger'):
  499. self.params['logger'].error(message)
  500. else:
  501. message = self._bidi_workaround(message)
  502. output = message + '\n'
  503. self._write_string(output, self._err_file)
  504. def to_console_title(self, message):
  505. if not self.params.get('consoletitle', False):
  506. return
  507. if compat_os_name == 'nt':
  508. if ctypes.windll.kernel32.GetConsoleWindow():
  509. # c_wchar_p() might not be necessary if `message` is
  510. # already of type unicode()
  511. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  512. elif 'TERM' in os.environ:
  513. self._write_string('\033]0;%s\007' % message, self._screen_file)
  514. def save_console_title(self):
  515. if not self.params.get('consoletitle', False):
  516. return
  517. if self.params.get('simulate', False):
  518. return
  519. if compat_os_name != 'nt' and 'TERM' in os.environ:
  520. # Save the title on stack
  521. self._write_string('\033[22;0t', self._screen_file)
  522. def restore_console_title(self):
  523. if not self.params.get('consoletitle', False):
  524. return
  525. if self.params.get('simulate', False):
  526. return
  527. if compat_os_name != 'nt' and 'TERM' in os.environ:
  528. # Restore the title from stack
  529. self._write_string('\033[23;0t', self._screen_file)
  530. def __enter__(self):
  531. self.save_console_title()
  532. return self
  533. def __exit__(self, *args):
  534. self.restore_console_title()
  535. if self.params.get('cookiefile') is not None:
  536. self.cookiejar.save(ignore_discard=True, ignore_expires=True)
  537. def trouble(self, *args, **kwargs):
  538. """Determine action to take when a download problem appears.
  539. Depending on if the downloader has been configured to ignore
  540. download errors or not, this method may throw an exception or
  541. not when errors are found, after printing the message.
  542. tb, if given, is additional traceback information.
  543. """
  544. # message=None, tb=None, is_error=True
  545. message = args[0] if len(args) > 0 else kwargs.get('message', None)
  546. tb = args[1] if len(args) > 1 else kwargs.get('tb', None)
  547. is_error = args[2] if len(args) > 2 else kwargs.get('is_error', True)
  548. if message is not None:
  549. self.to_stderr(message)
  550. if self.params.get('verbose'):
  551. if tb is None:
  552. if sys.exc_info()[0]: # if .trouble has been called from an except block
  553. tb = ''
  554. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  555. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  556. tb += encode_compat_str(traceback.format_exc())
  557. else:
  558. tb_data = traceback.format_list(traceback.extract_stack())
  559. tb = ''.join(tb_data)
  560. if tb:
  561. self.to_stderr(tb)
  562. if not is_error:
  563. return
  564. if not self.params.get('ignoreerrors', False):
  565. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  566. exc_info = sys.exc_info()[1].exc_info
  567. else:
  568. exc_info = sys.exc_info()
  569. raise DownloadError(message, exc_info)
  570. self._download_retcode = 1
  571. def report_warning(self, message, only_once=False, _cache={}):
  572. '''
  573. Print the message to stderr, it will be prefixed with 'WARNING:'
  574. If stderr is a tty file the 'WARNING:' will be colored
  575. '''
  576. if only_once:
  577. m_hash = hash((self, message))
  578. m_cnt = _cache.setdefault(m_hash, 0)
  579. _cache[m_hash] = m_cnt + 1
  580. if m_cnt > 0:
  581. return
  582. if self.params.get('logger') is not None:
  583. self.params['logger'].warning(message)
  584. else:
  585. if self.params.get('no_warnings'):
  586. return
  587. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  588. _msg_header = '\033[0;33mWARNING:\033[0m'
  589. else:
  590. _msg_header = 'WARNING:'
  591. warning_message = '%s %s' % (_msg_header, message)
  592. self.to_stderr(warning_message)
  593. def report_error(self, message, *args, **kwargs):
  594. '''
  595. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  596. in red if stderr is a tty file.
  597. '''
  598. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  599. _msg_header = '\033[0;31mERROR:\033[0m'
  600. else:
  601. _msg_header = 'ERROR:'
  602. kwargs['message'] = '%s %s' % (_msg_header, message)
  603. self.trouble(*args, **kwargs)
  604. def report_unscoped_cookies(self, *args, **kwargs):
  605. # message=None, tb=False, is_error=False
  606. if len(args) <= 2:
  607. kwargs.setdefault('is_error', False)
  608. if len(args) <= 0:
  609. kwargs.setdefault(
  610. 'message',
  611. 'Unscoped cookies are not allowed: please specify some sort of scoping')
  612. self.report_error(*args, **kwargs)
  613. def report_file_already_downloaded(self, file_name):
  614. """Report file has already been fully downloaded."""
  615. try:
  616. self.to_screen('[download] %s has already been downloaded' % file_name)
  617. except UnicodeEncodeError:
  618. self.to_screen('[download] The file has already been downloaded')
  619. def prepare_filename(self, info_dict):
  620. """Generate the output filename."""
  621. try:
  622. template_dict = dict(info_dict)
  623. template_dict['epoch'] = int(time.time())
  624. autonumber_size = self.params.get('autonumber_size')
  625. if autonumber_size is None:
  626. autonumber_size = 5
  627. template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
  628. if template_dict.get('resolution') is None:
  629. if template_dict.get('width') and template_dict.get('height'):
  630. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  631. elif template_dict.get('height'):
  632. template_dict['resolution'] = '%sp' % template_dict['height']
  633. elif template_dict.get('width'):
  634. template_dict['resolution'] = '%dx?' % template_dict['width']
  635. sanitize = lambda k, v: sanitize_filename(
  636. compat_str(v),
  637. restricted=self.params.get('restrictfilenames'),
  638. is_id=(k == 'id' or k.endswith('_id')))
  639. template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
  640. for k, v in template_dict.items()
  641. if v is not None and not isinstance(v, (list, tuple, dict)))
  642. template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
  643. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  644. # For fields playlist_index and autonumber convert all occurrences
  645. # of %(field)s to %(field)0Nd for backward compatibility
  646. field_size_compat_map = {
  647. 'playlist_index': len(str(template_dict['n_entries'])),
  648. 'autonumber': autonumber_size,
  649. }
  650. FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
  651. mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
  652. if mobj:
  653. outtmpl = re.sub(
  654. FIELD_SIZE_COMPAT_RE,
  655. r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
  656. outtmpl)
  657. # Missing numeric fields used together with integer presentation types
  658. # in format specification will break the argument substitution since
  659. # string NA placeholder is returned for missing fields. We will patch
  660. # output template for missing fields to meet string presentation type.
  661. for numeric_field in self._NUMERIC_FIELDS:
  662. if numeric_field not in template_dict:
  663. # As of [1] format syntax is:
  664. # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
  665. # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
  666. FORMAT_RE = r'''(?x)
  667. (?<!%)
  668. %
  669. \({0}\) # mapping key
  670. (?:[#0\-+ ]+)? # conversion flags (optional)
  671. (?:\d+)? # minimum field width (optional)
  672. (?:\.\d+)? # precision (optional)
  673. [hlL]? # length modifier (optional)
  674. [diouxXeEfFgGcrs%] # conversion type
  675. '''
  676. outtmpl = re.sub(
  677. FORMAT_RE.format(numeric_field),
  678. r'%({0})s'.format(numeric_field), outtmpl)
  679. # expand_path translates '%%' into '%' and '$$' into '$'
  680. # correspondingly that is not what we want since we need to keep
  681. # '%%' intact for template dict substitution step. Working around
  682. # with boundary-alike separator hack.
  683. sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
  684. outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
  685. # outtmpl should be expand_path'ed before template dict substitution
  686. # because meta fields may contain env variables we don't want to
  687. # be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
  688. # title "Hello $PATH", we don't want `$PATH` to be expanded.
  689. filename = expand_path(outtmpl).replace(sep, '') % template_dict
  690. # Temporary fix for #4787
  691. # 'Treat' all problem characters by passing filename through preferredencoding
  692. # to workaround encoding issues with subprocess on python2 @ Windows
  693. if sys.version_info < (3, 0) and sys.platform == 'win32':
  694. filename = encodeFilename(filename, True).decode(preferredencoding())
  695. return sanitize_path(filename)
  696. except ValueError as err:
  697. self.report_error('Error in output template: ' + error_to_compat_str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  698. return None
  699. def _match_entry(self, info_dict, incomplete):
  700. """ Returns None iff the file should be downloaded """
  701. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  702. if 'title' in info_dict:
  703. # This can happen when we're just evaluating the playlist
  704. title = info_dict['title']
  705. matchtitle = self.params.get('matchtitle', False)
  706. if matchtitle:
  707. if not re.search(matchtitle, title, re.IGNORECASE):
  708. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  709. rejecttitle = self.params.get('rejecttitle', False)
  710. if rejecttitle:
  711. if re.search(rejecttitle, title, re.IGNORECASE):
  712. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  713. date = info_dict.get('upload_date')
  714. if date is not None:
  715. dateRange = self.params.get('daterange', DateRange())
  716. if date not in dateRange:
  717. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  718. view_count = info_dict.get('view_count')
  719. if view_count is not None:
  720. min_views = self.params.get('min_views')
  721. if min_views is not None and view_count < min_views:
  722. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  723. max_views = self.params.get('max_views')
  724. if max_views is not None and view_count > max_views:
  725. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  726. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  727. return 'Skipping "%s" because it is age restricted' % video_title
  728. if self.in_download_archive(info_dict):
  729. return '%s has already been recorded in archive' % video_title
  730. if not incomplete:
  731. match_filter = self.params.get('match_filter')
  732. if match_filter is not None:
  733. ret = match_filter(info_dict)
  734. if ret is not None:
  735. return ret
  736. return None
  737. @staticmethod
  738. def add_extra_info(info_dict, extra_info):
  739. '''Set the keys from extra_info in info dict if they are missing'''
  740. for key, value in extra_info.items():
  741. info_dict.setdefault(key, value)
  742. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  743. process=True, force_generic_extractor=False):
  744. """
  745. Return a list with a dictionary for each video extracted.
  746. Arguments:
  747. url -- URL to extract
  748. Keyword arguments:
  749. download -- whether to download videos during extraction
  750. ie_key -- extractor key hint
  751. extra_info -- dictionary containing the extra values to add to each result
  752. process -- whether to resolve all unresolved references (URLs, playlist items),
  753. must be True for download to work.
  754. force_generic_extractor -- force using the generic extractor
  755. """
  756. if not ie_key and force_generic_extractor:
  757. ie_key = 'Generic'
  758. if ie_key:
  759. ies = [self.get_info_extractor(ie_key)]
  760. else:
  761. ies = self._ies
  762. for ie in ies:
  763. if not ie.suitable(url):
  764. continue
  765. ie = self.get_info_extractor(ie.ie_key())
  766. if not ie.working():
  767. self.report_warning('The program functionality for this site has been marked as broken, '
  768. 'and will probably not work.')
  769. return self.__extract_info(url, ie, download, extra_info, process)
  770. else:
  771. self.report_error('no suitable InfoExtractor for URL %s' % url)
  772. def __handle_extraction_exceptions(func):
  773. def wrapper(self, *args, **kwargs):
  774. try:
  775. return func(self, *args, **kwargs)
  776. except GeoRestrictedError as e:
  777. msg = e.msg
  778. if e.countries:
  779. msg += '\nThis video is available in %s.' % ', '.join(
  780. map(ISO3166Utils.short2full, e.countries))
  781. msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
  782. self.report_error(msg)
  783. except ExtractorError as e: # An error we somewhat expected
  784. self.report_error(compat_str(e), tb=e.format_traceback())
  785. except MaxDownloadsReached:
  786. raise
  787. except Exception as e:
  788. if self.params.get('ignoreerrors', False):
  789. self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
  790. else:
  791. raise
  792. return wrapper
  793. def _remove_cookie_header(self, http_headers):
  794. """Filters out `Cookie` header from an `http_headers` dict
  795. The `Cookie` header is removed to prevent leaks as a result of unscoped cookies.
  796. See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  797. @param http_headers An `http_headers` dict from which any `Cookie` header
  798. should be removed, or None
  799. """
  800. return dict(filter(lambda pair: pair[0].lower() != 'cookie', (http_headers or {}).items()))
  801. def _load_cookies(self, data, **kwargs):
  802. """Loads cookies from a `Cookie` header
  803. This tries to work around the security vulnerability of passing cookies to every domain.
  804. @param data The Cookie header as a string to load the cookies from
  805. @param autoscope If `False`, scope cookies using Set-Cookie syntax and error for cookie without domains
  806. If `True`, save cookies for later to be stored in the jar with a limited scope
  807. If a URL, save cookies in the jar with the domain of the URL
  808. """
  809. # autoscope=True (kw-only)
  810. autoscope = kwargs.get('autoscope', True)
  811. for cookie in compat_http_cookies_SimpleCookie(data).values() if data else []:
  812. if autoscope and any(cookie.values()):
  813. raise ValueError('Invalid syntax in Cookie Header')
  814. domain = cookie.get('domain') or ''
  815. expiry = cookie.get('expires')
  816. if expiry == '': # 0 is valid so we check for `''` explicitly
  817. expiry = None
  818. prepared_cookie = compat_http_cookiejar_Cookie(
  819. cookie.get('version') or 0, cookie.key, cookie.value, None, False,
  820. domain, True, True, cookie.get('path') or '', bool(cookie.get('path')),
  821. bool(cookie.get('secure')), expiry, False, None, None, {})
  822. if domain:
  823. self.cookiejar.set_cookie(prepared_cookie)
  824. elif autoscope is True:
  825. self.report_warning(
  826. 'Passing cookies as a header is a potential security risk; '
  827. 'they will be scoped to the domain of the downloaded urls. '
  828. 'Please consider loading cookies from a file or browser instead.',
  829. only_once=True)
  830. self._header_cookies.append(prepared_cookie)
  831. elif autoscope:
  832. self.report_warning(
  833. 'The extractor result contains an unscoped cookie as an HTTP header. '
  834. 'If you are specifying an input URL, ' + bug_reports_message(),
  835. only_once=True)
  836. self._apply_header_cookies(autoscope, [prepared_cookie])
  837. else:
  838. self.report_unscoped_cookies()
  839. def _load_cookies_from_headers(self, headers):
  840. self._load_cookies(traverse_obj(headers, 'cookie', casesense=False))
  841. def _apply_header_cookies(self, url, cookies=None):
  842. """This method applies stray header cookies to the provided url
  843. This loads header cookies and scopes them to the domain provided in `url`.
  844. While this is not ideal, it helps reduce the risk of them being sent to
  845. an unintended destination.
  846. """
  847. parsed = compat_urllib_parse.urlparse(url)
  848. if not parsed.hostname:
  849. return
  850. for cookie in map(copy.copy, cookies or self._header_cookies):
  851. cookie.domain = '.' + parsed.hostname
  852. self.cookiejar.set_cookie(cookie)
  853. @__handle_extraction_exceptions
  854. def __extract_info(self, url, ie, download, extra_info, process):
  855. # Compat with passing cookies in http headers
  856. self._apply_header_cookies(url)
  857. ie_result = ie.extract(url)
  858. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  859. return
  860. if isinstance(ie_result, list):
  861. # Backwards compatibility: old IE result format
  862. ie_result = {
  863. '_type': 'compat_list',
  864. 'entries': ie_result,
  865. }
  866. self.add_default_extra_info(ie_result, ie, url)
  867. if process:
  868. return self.process_ie_result(ie_result, download, extra_info)
  869. else:
  870. return ie_result
  871. def add_default_extra_info(self, ie_result, ie, url):
  872. self.add_extra_info(ie_result, {
  873. 'extractor': ie.IE_NAME,
  874. 'webpage_url': url,
  875. 'webpage_url_basename': url_basename(url),
  876. 'extractor_key': ie.ie_key(),
  877. })
  878. def process_ie_result(self, ie_result, download=True, extra_info={}):
  879. """
  880. Take the result of the ie (may be modified) and resolve all unresolved
  881. references (URLs, playlist items).
  882. It will also download the videos if 'download'.
  883. Returns the resolved ie_result.
  884. """
  885. result_type = ie_result.get('_type', 'video')
  886. if result_type in ('url', 'url_transparent'):
  887. ie_result['url'] = sanitize_url(ie_result['url'])
  888. extract_flat = self.params.get('extract_flat', False)
  889. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
  890. or extract_flat is True):
  891. self.__forced_printings(
  892. ie_result, self.prepare_filename(ie_result),
  893. incomplete=True)
  894. return ie_result
  895. if result_type == 'video':
  896. self.add_extra_info(ie_result, extra_info)
  897. return self.process_video_result(ie_result, download=download)
  898. elif result_type == 'url':
  899. # We have to add extra_info to the results because it may be
  900. # contained in a playlist
  901. return self.extract_info(ie_result['url'],
  902. download,
  903. ie_key=ie_result.get('ie_key'),
  904. extra_info=extra_info)
  905. elif result_type == 'url_transparent':
  906. # Use the information from the embedding page
  907. info = self.extract_info(
  908. ie_result['url'], ie_key=ie_result.get('ie_key'),
  909. extra_info=extra_info, download=False, process=False)
  910. # extract_info may return None when ignoreerrors is enabled and
  911. # extraction failed with an error, don't crash and return early
  912. # in this case
  913. if not info:
  914. return info
  915. force_properties = dict(
  916. (k, v) for k, v in ie_result.items() if v is not None)
  917. for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
  918. if f in force_properties:
  919. del force_properties[f]
  920. new_result = info.copy()
  921. new_result.update(force_properties)
  922. # Extracted info may not be a video result (i.e.
  923. # info.get('_type', 'video') != video) but rather an url or
  924. # url_transparent. In such cases outer metadata (from ie_result)
  925. # should be propagated to inner one (info). For this to happen
  926. # _type of info should be overridden with url_transparent. This
  927. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  928. if new_result.get('_type') == 'url':
  929. new_result['_type'] = 'url_transparent'
  930. return self.process_ie_result(
  931. new_result, download=download, extra_info=extra_info)
  932. elif result_type in ('playlist', 'multi_video'):
  933. # Protect from infinite recursion due to recursively nested playlists
  934. # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
  935. webpage_url = ie_result['webpage_url']
  936. if webpage_url in self._playlist_urls:
  937. self.to_screen(
  938. '[download] Skipping already downloaded playlist: %s'
  939. % ie_result.get('title') or ie_result.get('id'))
  940. return
  941. self._playlist_level += 1
  942. self._playlist_urls.add(webpage_url)
  943. try:
  944. return self.__process_playlist(ie_result, download)
  945. finally:
  946. self._playlist_level -= 1
  947. if not self._playlist_level:
  948. self._playlist_urls.clear()
  949. elif result_type == 'compat_list':
  950. self.report_warning(
  951. 'Extractor %s returned a compat_list result. '
  952. 'It needs to be updated.' % ie_result.get('extractor'))
  953. def _fixup(r):
  954. self.add_extra_info(
  955. r,
  956. {
  957. 'extractor': ie_result['extractor'],
  958. 'webpage_url': ie_result['webpage_url'],
  959. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  960. 'extractor_key': ie_result['extractor_key'],
  961. }
  962. )
  963. return r
  964. ie_result['entries'] = [
  965. self.process_ie_result(_fixup(r), download, extra_info)
  966. for r in ie_result['entries']
  967. ]
  968. return ie_result
  969. else:
  970. raise Exception('Invalid result type: %s' % result_type)
  971. def __process_playlist(self, ie_result, download):
  972. # We process each entry in the playlist
  973. playlist = ie_result.get('title') or ie_result.get('id')
  974. self.to_screen('[download] Downloading playlist: %s' % playlist)
  975. playlist_results = []
  976. playliststart = self.params.get('playliststart', 1) - 1
  977. playlistend = self.params.get('playlistend')
  978. # For backwards compatibility, interpret -1 as whole list
  979. if playlistend == -1:
  980. playlistend = None
  981. playlistitems_str = self.params.get('playlist_items')
  982. playlistitems = None
  983. if playlistitems_str is not None:
  984. def iter_playlistitems(format):
  985. for string_segment in format.split(','):
  986. if '-' in string_segment:
  987. start, end = string_segment.split('-')
  988. for item in range(int(start), int(end) + 1):
  989. yield int(item)
  990. else:
  991. yield int(string_segment)
  992. playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
  993. ie_entries = ie_result['entries']
  994. def make_playlistitems_entries(list_ie_entries):
  995. num_entries = len(list_ie_entries)
  996. return [
  997. list_ie_entries[i - 1] for i in playlistitems
  998. if -num_entries <= i - 1 < num_entries]
  999. def report_download(num_entries):
  1000. self.to_screen(
  1001. '[%s] playlist %s: Downloading %d videos' %
  1002. (ie_result['extractor'], playlist, num_entries))
  1003. if isinstance(ie_entries, list):
  1004. n_all_entries = len(ie_entries)
  1005. if playlistitems:
  1006. entries = make_playlistitems_entries(ie_entries)
  1007. else:
  1008. entries = ie_entries[playliststart:playlistend]
  1009. n_entries = len(entries)
  1010. self.to_screen(
  1011. '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
  1012. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  1013. elif isinstance(ie_entries, PagedList):
  1014. if playlistitems:
  1015. entries = []
  1016. for item in playlistitems:
  1017. entries.extend(ie_entries.getslice(
  1018. item - 1, item
  1019. ))
  1020. else:
  1021. entries = ie_entries.getslice(
  1022. playliststart, playlistend)
  1023. n_entries = len(entries)
  1024. report_download(n_entries)
  1025. else: # iterable
  1026. if playlistitems:
  1027. entries = make_playlistitems_entries(list(itertools.islice(
  1028. ie_entries, 0, max(playlistitems))))
  1029. else:
  1030. entries = list(itertools.islice(
  1031. ie_entries, playliststart, playlistend))
  1032. n_entries = len(entries)
  1033. report_download(n_entries)
  1034. if self.params.get('playlistreverse', False):
  1035. entries = entries[::-1]
  1036. if self.params.get('playlistrandom', False):
  1037. random.shuffle(entries)
  1038. x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
  1039. for i, entry in enumerate(entries, 1):
  1040. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  1041. # This __x_forwarded_for_ip thing is a bit ugly but requires
  1042. # minimal changes
  1043. if x_forwarded_for:
  1044. entry['__x_forwarded_for_ip'] = x_forwarded_for
  1045. extra = {
  1046. 'n_entries': n_entries,
  1047. 'playlist': playlist,
  1048. 'playlist_id': ie_result.get('id'),
  1049. 'playlist_title': ie_result.get('title'),
  1050. 'playlist_uploader': ie_result.get('uploader'),
  1051. 'playlist_uploader_id': ie_result.get('uploader_id'),
  1052. 'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
  1053. 'extractor': ie_result['extractor'],
  1054. 'webpage_url': ie_result['webpage_url'],
  1055. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1056. 'extractor_key': ie_result['extractor_key'],
  1057. }
  1058. reason = self._match_entry(entry, incomplete=True)
  1059. if reason is not None:
  1060. self.to_screen('[download] ' + reason)
  1061. continue
  1062. entry_result = self.__process_iterable_entry(entry, download, extra)
  1063. # TODO: skip failed (empty) entries?
  1064. playlist_results.append(entry_result)
  1065. ie_result['entries'] = playlist_results
  1066. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  1067. return ie_result
  1068. @__handle_extraction_exceptions
  1069. def __process_iterable_entry(self, entry, download, extra_info):
  1070. return self.process_ie_result(
  1071. entry, download=download, extra_info=extra_info)
  1072. def _build_format_filter(self, filter_spec):
  1073. " Returns a function to filter the formats according to the filter_spec "
  1074. OPERATORS = {
  1075. '<': operator.lt,
  1076. '<=': operator.le,
  1077. '>': operator.gt,
  1078. '>=': operator.ge,
  1079. '=': operator.eq,
  1080. '!=': operator.ne,
  1081. }
  1082. operator_rex = re.compile(r'''(?x)\s*
  1083. (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
  1084. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1085. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  1086. $
  1087. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  1088. m = operator_rex.search(filter_spec)
  1089. if m:
  1090. try:
  1091. comparison_value = int(m.group('value'))
  1092. except ValueError:
  1093. comparison_value = parse_filesize(m.group('value'))
  1094. if comparison_value is None:
  1095. comparison_value = parse_filesize(m.group('value') + 'B')
  1096. if comparison_value is None:
  1097. raise ValueError(
  1098. 'Invalid value %r in format specification %r' % (
  1099. m.group('value'), filter_spec))
  1100. op = OPERATORS[m.group('op')]
  1101. if not m:
  1102. STR_OPERATORS = {
  1103. '=': operator.eq,
  1104. '^=': lambda attr, value: attr.startswith(value),
  1105. '$=': lambda attr, value: attr.endswith(value),
  1106. '*=': lambda attr, value: value in attr,
  1107. }
  1108. str_operator_rex = re.compile(r'''(?x)
  1109. \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
  1110. \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
  1111. \s*(?P<value>[a-zA-Z0-9._-]+)
  1112. \s*$
  1113. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  1114. m = str_operator_rex.search(filter_spec)
  1115. if m:
  1116. comparison_value = m.group('value')
  1117. str_op = STR_OPERATORS[m.group('op')]
  1118. if m.group('negation'):
  1119. op = lambda attr, value: not str_op(attr, value)
  1120. else:
  1121. op = str_op
  1122. if not m:
  1123. raise ValueError('Invalid filter specification %r' % filter_spec)
  1124. def _filter(f):
  1125. actual_value = f.get(m.group('key'))
  1126. if actual_value is None:
  1127. return m.group('none_inclusive')
  1128. return op(actual_value, comparison_value)
  1129. return _filter
  1130. def _default_format_spec(self, info_dict, download=True):
  1131. def can_merge():
  1132. merger = FFmpegMergerPP(self)
  1133. return merger.available and merger.can_merge()
  1134. def prefer_best():
  1135. if self.params.get('simulate', False):
  1136. return False
  1137. if not download:
  1138. return False
  1139. if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
  1140. return True
  1141. if info_dict.get('is_live'):
  1142. return True
  1143. if not can_merge():
  1144. return True
  1145. return False
  1146. req_format_list = ['bestvideo+bestaudio', 'best']
  1147. if prefer_best():
  1148. req_format_list.reverse()
  1149. return '/'.join(req_format_list)
  1150. def build_format_selector(self, format_spec):
  1151. def syntax_error(note, start):
  1152. message = (
  1153. 'Invalid format specification: '
  1154. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  1155. return SyntaxError(message)
  1156. PICKFIRST = 'PICKFIRST'
  1157. MERGE = 'MERGE'
  1158. SINGLE = 'SINGLE'
  1159. GROUP = 'GROUP'
  1160. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  1161. def _parse_filter(tokens):
  1162. filter_parts = []
  1163. for type, string, start, _, _ in tokens:
  1164. if type == tokenize.OP and string == ']':
  1165. return ''.join(filter_parts)
  1166. else:
  1167. filter_parts.append(string)
  1168. def _remove_unused_ops(tokens):
  1169. # Remove operators that we don't use and join them with the surrounding strings
  1170. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  1171. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  1172. last_string, last_start, last_end, last_line = None, None, None, None
  1173. for type, string, start, end, line in tokens:
  1174. if type == tokenize.OP and string == '[':
  1175. if last_string:
  1176. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1177. last_string = None
  1178. yield type, string, start, end, line
  1179. # everything inside brackets will be handled by _parse_filter
  1180. for type, string, start, end, line in tokens:
  1181. yield type, string, start, end, line
  1182. if type == tokenize.OP and string == ']':
  1183. break
  1184. elif type == tokenize.OP and string in ALLOWED_OPS:
  1185. if last_string:
  1186. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1187. last_string = None
  1188. yield type, string, start, end, line
  1189. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  1190. if not last_string:
  1191. last_string = string
  1192. last_start = start
  1193. last_end = end
  1194. else:
  1195. last_string += string
  1196. if last_string:
  1197. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1198. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  1199. selectors = []
  1200. current_selector = None
  1201. for type, string, start, _, _ in tokens:
  1202. # ENCODING is only defined in python 3.x
  1203. if type == getattr(tokenize, 'ENCODING', None):
  1204. continue
  1205. elif type in [tokenize.NAME, tokenize.NUMBER]:
  1206. current_selector = FormatSelector(SINGLE, string, [])
  1207. elif type == tokenize.OP:
  1208. if string == ')':
  1209. if not inside_group:
  1210. # ')' will be handled by the parentheses group
  1211. tokens.restore_last_token()
  1212. break
  1213. elif inside_merge and string in ['/', ',']:
  1214. tokens.restore_last_token()
  1215. break
  1216. elif inside_choice and string == ',':
  1217. tokens.restore_last_token()
  1218. break
  1219. elif string == ',':
  1220. if not current_selector:
  1221. raise syntax_error('"," must follow a format selector', start)
  1222. selectors.append(current_selector)
  1223. current_selector = None
  1224. elif string == '/':
  1225. if not current_selector:
  1226. raise syntax_error('"/" must follow a format selector', start)
  1227. first_choice = current_selector
  1228. second_choice = _parse_format_selection(tokens, inside_choice=True)
  1229. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  1230. elif string == '[':
  1231. if not current_selector:
  1232. current_selector = FormatSelector(SINGLE, 'best', [])
  1233. format_filter = _parse_filter(tokens)
  1234. current_selector.filters.append(format_filter)
  1235. elif string == '(':
  1236. if current_selector:
  1237. raise syntax_error('Unexpected "("', start)
  1238. group = _parse_format_selection(tokens, inside_group=True)
  1239. current_selector = FormatSelector(GROUP, group, [])
  1240. elif string == '+':
  1241. if inside_merge:
  1242. raise syntax_error('Unexpected "+"', start)
  1243. video_selector = current_selector
  1244. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  1245. if not video_selector or not audio_selector:
  1246. raise syntax_error('"+" must be between two format selectors', start)
  1247. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  1248. else:
  1249. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  1250. elif type == tokenize.ENDMARKER:
  1251. break
  1252. if current_selector:
  1253. selectors.append(current_selector)
  1254. return selectors
  1255. def _build_selector_function(selector):
  1256. if isinstance(selector, list):
  1257. fs = [_build_selector_function(s) for s in selector]
  1258. def selector_function(ctx):
  1259. for f in fs:
  1260. for format in f(ctx):
  1261. yield format
  1262. return selector_function
  1263. elif selector.type == GROUP:
  1264. selector_function = _build_selector_function(selector.selector)
  1265. elif selector.type == PICKFIRST:
  1266. fs = [_build_selector_function(s) for s in selector.selector]
  1267. def selector_function(ctx):
  1268. for f in fs:
  1269. picked_formats = list(f(ctx))
  1270. if picked_formats:
  1271. return picked_formats
  1272. return []
  1273. elif selector.type == SINGLE:
  1274. format_spec = selector.selector
  1275. def selector_function(ctx):
  1276. formats = list(ctx['formats'])
  1277. if not formats:
  1278. return
  1279. if format_spec == 'all':
  1280. for f in formats:
  1281. yield f
  1282. elif format_spec in ['best', 'worst', None]:
  1283. format_idx = 0 if format_spec == 'worst' else -1
  1284. audiovideo_formats = [
  1285. f for f in formats
  1286. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  1287. if audiovideo_formats:
  1288. yield audiovideo_formats[format_idx]
  1289. # for extractors with incomplete formats (audio only (soundcloud)
  1290. # or video only (imgur)) we will fallback to best/worst
  1291. # {video,audio}-only format
  1292. elif ctx['incomplete_formats']:
  1293. yield formats[format_idx]
  1294. elif format_spec == 'bestaudio':
  1295. audio_formats = [
  1296. f for f in formats
  1297. if f.get('vcodec') == 'none']
  1298. if audio_formats:
  1299. yield audio_formats[-1]
  1300. elif format_spec == 'worstaudio':
  1301. audio_formats = [
  1302. f for f in formats
  1303. if f.get('vcodec') == 'none']
  1304. if audio_formats:
  1305. yield audio_formats[0]
  1306. elif format_spec == 'bestvideo':
  1307. video_formats = [
  1308. f for f in formats
  1309. if f.get('acodec') == 'none']
  1310. if video_formats:
  1311. yield video_formats[-1]
  1312. elif format_spec == 'worstvideo':
  1313. video_formats = [
  1314. f for f in formats
  1315. if f.get('acodec') == 'none']
  1316. if video_formats:
  1317. yield video_formats[0]
  1318. else:
  1319. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1320. if format_spec in extensions:
  1321. filter_f = lambda f: f['ext'] == format_spec
  1322. else:
  1323. filter_f = lambda f: f['format_id'] == format_spec
  1324. matches = list(filter(filter_f, formats))
  1325. if matches:
  1326. yield matches[-1]
  1327. elif selector.type == MERGE:
  1328. def _merge(formats_info):
  1329. format_1, format_2 = [f['format_id'] for f in formats_info]
  1330. # The first format must contain the video and the
  1331. # second the audio
  1332. if formats_info[0].get('vcodec') == 'none':
  1333. self.report_error('The first format must '
  1334. 'contain the video, try using '
  1335. '"-f %s+%s"' % (format_2, format_1))
  1336. return
  1337. # Formats must be opposite (video+audio)
  1338. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1339. self.report_error(
  1340. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1341. % (format_1, format_2))
  1342. return
  1343. output_ext = (
  1344. formats_info[0]['ext']
  1345. if self.params.get('merge_output_format') is None
  1346. else self.params['merge_output_format'])
  1347. return {
  1348. 'requested_formats': formats_info,
  1349. 'format': '%s+%s' % (formats_info[0].get('format'),
  1350. formats_info[1].get('format')),
  1351. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1352. formats_info[1].get('format_id')),
  1353. 'width': formats_info[0].get('width'),
  1354. 'height': formats_info[0].get('height'),
  1355. 'resolution': formats_info[0].get('resolution'),
  1356. 'fps': formats_info[0].get('fps'),
  1357. 'vcodec': formats_info[0].get('vcodec'),
  1358. 'vbr': formats_info[0].get('vbr'),
  1359. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1360. 'acodec': formats_info[1].get('acodec'),
  1361. 'abr': formats_info[1].get('abr'),
  1362. 'ext': output_ext,
  1363. }
  1364. def selector_function(ctx):
  1365. selector_fn = lambda x: _build_selector_function(x)(ctx)
  1366. for pair in itertools.product(*map(selector_fn, selector.selector)):
  1367. yield _merge(pair)
  1368. filters = [self._build_format_filter(f) for f in selector.filters]
  1369. def final_selector(ctx):
  1370. ctx_copy = dict(ctx)
  1371. for _filter in filters:
  1372. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  1373. return selector_function(ctx_copy)
  1374. return final_selector
  1375. stream = io.BytesIO(format_spec.encode('utf-8'))
  1376. try:
  1377. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1378. except tokenize.TokenError:
  1379. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1380. class TokenIterator(object):
  1381. def __init__(self, tokens):
  1382. self.tokens = tokens
  1383. self.counter = 0
  1384. def __iter__(self):
  1385. return self
  1386. def __next__(self):
  1387. if self.counter >= len(self.tokens):
  1388. raise StopIteration()
  1389. value = self.tokens[self.counter]
  1390. self.counter += 1
  1391. return value
  1392. next = __next__
  1393. def restore_last_token(self):
  1394. self.counter -= 1
  1395. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1396. return _build_selector_function(parsed_selector)
  1397. def _calc_headers(self, info_dict, load_cookies=False):
  1398. if load_cookies: # For --load-info-json
  1399. # load cookies from http_headers in legacy info.json
  1400. self._load_cookies(traverse_obj(info_dict, ('http_headers', 'Cookie'), casesense=False),
  1401. autoscope=info_dict['url'])
  1402. # load scoped cookies from info.json
  1403. self._load_cookies(info_dict.get('cookies'), autoscope=False)
  1404. cookies = self.cookiejar.get_cookies_for_url(info_dict['url'])
  1405. if cookies:
  1406. # Make a string like name1=val1; attr1=a_val1; ...name2=val2; ...
  1407. # By convention a cookie name can't be a well-known attribute name
  1408. # so this syntax is unambiguous and can be parsed by (eg) SimpleCookie
  1409. encoder = compat_http_cookies_SimpleCookie()
  1410. values = []
  1411. attributes = (('Domain', '='), ('Path', '='), ('Secure',), ('Expires', '='), ('Version', '='))
  1412. attributes = tuple([x[0].lower()] + list(x) for x in attributes)
  1413. for cookie in cookies:
  1414. _, value = encoder.value_encode(cookie.value)
  1415. # Py 2 '' --> '', Py 3 '' --> '""'
  1416. if value == '':
  1417. value = '""'
  1418. values.append('='.join((cookie.name, value)))
  1419. for attr in attributes:
  1420. value = getattr(cookie, attr[0], None)
  1421. if value:
  1422. values.append('%s%s' % (''.join(attr[1:]), value if len(attr) == 3 else ''))
  1423. info_dict['cookies'] = '; '.join(values)
  1424. res = std_headers.copy()
  1425. res.update(info_dict.get('http_headers') or {})
  1426. res = self._remove_cookie_header(res)
  1427. if 'X-Forwarded-For' not in res:
  1428. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  1429. if x_forwarded_for_ip:
  1430. res['X-Forwarded-For'] = x_forwarded_for_ip
  1431. return res or None
  1432. def _calc_cookies(self, info_dict):
  1433. pr = sanitized_Request(info_dict['url'])
  1434. self.cookiejar.add_cookie_header(pr)
  1435. return pr.get_header('Cookie')
  1436. def process_video_result(self, info_dict, download=True):
  1437. assert info_dict.get('_type', 'video') == 'video'
  1438. if 'id' not in info_dict:
  1439. raise ExtractorError('Missing "id" field in extractor result')
  1440. if 'title' not in info_dict:
  1441. raise ExtractorError('Missing "title" field in extractor result')
  1442. def report_force_conversion(field, field_not, conversion):
  1443. self.report_warning(
  1444. '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
  1445. % (field, field_not, conversion))
  1446. def sanitize_string_field(info, string_field):
  1447. field = info.get(string_field)
  1448. if field is None or isinstance(field, compat_str):
  1449. return
  1450. report_force_conversion(string_field, 'a string', 'string')
  1451. info[string_field] = compat_str(field)
  1452. def sanitize_numeric_fields(info):
  1453. for numeric_field in self._NUMERIC_FIELDS:
  1454. field = info.get(numeric_field)
  1455. if field is None or isinstance(field, compat_numeric_types):
  1456. continue
  1457. report_force_conversion(numeric_field, 'numeric', 'int')
  1458. info[numeric_field] = int_or_none(field)
  1459. sanitize_string_field(info_dict, 'id')
  1460. sanitize_numeric_fields(info_dict)
  1461. if 'playlist' not in info_dict:
  1462. # It isn't part of a playlist
  1463. info_dict['playlist'] = None
  1464. info_dict['playlist_index'] = None
  1465. thumbnails = info_dict.get('thumbnails')
  1466. if thumbnails is None:
  1467. thumbnail = info_dict.get('thumbnail')
  1468. if thumbnail:
  1469. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1470. if thumbnails:
  1471. thumbnails.sort(key=lambda t: (
  1472. t.get('preference') if t.get('preference') is not None else -1,
  1473. t.get('width') if t.get('width') is not None else -1,
  1474. t.get('height') if t.get('height') is not None else -1,
  1475. t.get('id') if t.get('id') is not None else '', t.get('url')))
  1476. for i, t in enumerate(thumbnails):
  1477. t['url'] = sanitize_url(t['url'])
  1478. if t.get('width') and t.get('height'):
  1479. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1480. if t.get('id') is None:
  1481. t['id'] = '%d' % i
  1482. if self.params.get('list_thumbnails'):
  1483. self.list_thumbnails(info_dict)
  1484. return
  1485. thumbnail = info_dict.get('thumbnail')
  1486. if thumbnail:
  1487. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1488. elif thumbnails:
  1489. info_dict['thumbnail'] = thumbnails[-1]['url']
  1490. if 'display_id' not in info_dict and 'id' in info_dict:
  1491. info_dict['display_id'] = info_dict['id']
  1492. for ts_key, date_key in (
  1493. ('timestamp', 'upload_date'),
  1494. ('release_timestamp', 'release_date'),
  1495. ):
  1496. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  1497. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1498. # see http://bugs.python.org/issue1646728)
  1499. try:
  1500. upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
  1501. info_dict[date_key] = compat_str(upload_date.strftime('%Y%m%d'))
  1502. except (ValueError, OverflowError, OSError):
  1503. pass
  1504. # Auto generate title fields corresponding to the *_number fields when missing
  1505. # in order to always have clean titles. This is very common for TV series.
  1506. for field in ('chapter', 'season', 'episode'):
  1507. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1508. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1509. for cc_kind in ('subtitles', 'automatic_captions'):
  1510. cc = info_dict.get(cc_kind)
  1511. if cc:
  1512. for _, subtitle in cc.items():
  1513. for subtitle_format in subtitle:
  1514. if subtitle_format.get('url'):
  1515. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1516. if subtitle_format.get('ext') is None:
  1517. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1518. automatic_captions = info_dict.get('automatic_captions')
  1519. subtitles = info_dict.get('subtitles')
  1520. if self.params.get('listsubtitles', False):
  1521. if 'automatic_captions' in info_dict:
  1522. self.list_subtitles(
  1523. info_dict['id'], automatic_captions, 'automatic captions')
  1524. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1525. return
  1526. info_dict['requested_subtitles'] = self.process_subtitles(
  1527. info_dict['id'], subtitles, automatic_captions)
  1528. # We now pick which formats have to be downloaded
  1529. if info_dict.get('formats') is None:
  1530. # There's only one format available
  1531. formats = [info_dict]
  1532. else:
  1533. formats = info_dict['formats']
  1534. def is_wellformed(f):
  1535. url = f.get('url')
  1536. if not url:
  1537. self.report_warning(
  1538. '"url" field is missing or empty - skipping format, '
  1539. 'there is an error in extractor')
  1540. return False
  1541. if isinstance(url, bytes):
  1542. sanitize_string_field(f, 'url')
  1543. return True
  1544. # Filter out malformed formats for better extraction robustness
  1545. formats = list(filter(is_wellformed, formats or []))
  1546. if not formats:
  1547. raise ExtractorError('No video formats found!')
  1548. formats_dict = {}
  1549. # We check that all the formats have the format and format_id fields
  1550. for i, format in enumerate(formats):
  1551. sanitize_string_field(format, 'format_id')
  1552. sanitize_numeric_fields(format)
  1553. format['url'] = sanitize_url(format['url'])
  1554. if not format.get('format_id'):
  1555. format['format_id'] = compat_str(i)
  1556. else:
  1557. # Sanitize format_id from characters used in format selector expression
  1558. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  1559. format_id = format['format_id']
  1560. if format_id not in formats_dict:
  1561. formats_dict[format_id] = []
  1562. formats_dict[format_id].append(format)
  1563. # Make sure all formats have unique format_id
  1564. for format_id, ambiguous_formats in formats_dict.items():
  1565. if len(ambiguous_formats) > 1:
  1566. for i, format in enumerate(ambiguous_formats):
  1567. format['format_id'] = '%s-%d' % (format_id, i)
  1568. for i, format in enumerate(formats):
  1569. if format.get('format') is None:
  1570. format['format'] = '{id} - {res}{note}'.format(
  1571. id=format['format_id'],
  1572. res=self.format_resolution(format),
  1573. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1574. )
  1575. # Automatically determine file extension if missing
  1576. if format.get('ext') is None:
  1577. format['ext'] = determine_ext(format['url']).lower()
  1578. # Automatically determine protocol if missing (useful for format
  1579. # selection purposes)
  1580. if format.get('protocol') is None:
  1581. format['protocol'] = determine_protocol(format)
  1582. # Add HTTP headers, so that external programs can use them from the
  1583. # json output
  1584. format['http_headers'] = self._calc_headers(ChainMap(format, info_dict), load_cookies=True)
  1585. # Safeguard against old/insecure infojson when using --load-info-json
  1586. info_dict['http_headers'] = self._remove_cookie_header(
  1587. info_dict.get('http_headers') or {}) or None
  1588. # Remove private housekeeping stuff (copied to http_headers in _calc_headers())
  1589. if '__x_forwarded_for_ip' in info_dict:
  1590. del info_dict['__x_forwarded_for_ip']
  1591. # TODO Central sorting goes here
  1592. if formats[0] is not info_dict:
  1593. # only set the 'formats' fields if the original info_dict list them
  1594. # otherwise we end up with a circular reference, the first (and unique)
  1595. # element in the 'formats' field in info_dict is info_dict itself,
  1596. # which can't be exported to json
  1597. info_dict['formats'] = formats
  1598. if self.params.get('listformats'):
  1599. self.list_formats(info_dict)
  1600. return
  1601. req_format = self.params.get('format')
  1602. if req_format is None:
  1603. req_format = self._default_format_spec(info_dict, download=download)
  1604. if self.params.get('verbose'):
  1605. self._write_string('[debug] Default format spec: %s\n' % req_format)
  1606. format_selector = self.build_format_selector(req_format)
  1607. # While in format selection we may need to have an access to the original
  1608. # format set in order to calculate some metrics or do some processing.
  1609. # For now we need to be able to guess whether original formats provided
  1610. # by extractor are incomplete or not (i.e. whether extractor provides only
  1611. # video-only or audio-only formats) for proper formats selection for
  1612. # extractors with such incomplete formats (see
  1613. # https://github.com/ytdl-org/youtube-dl/pull/5556).
  1614. # Since formats may be filtered during format selection and may not match
  1615. # the original formats the results may be incorrect. Thus original formats
  1616. # or pre-calculated metrics should be passed to format selection routines
  1617. # as well.
  1618. # We will pass a context object containing all necessary additional data
  1619. # instead of just formats.
  1620. # This fixes incorrect format selection issue (see
  1621. # https://github.com/ytdl-org/youtube-dl/issues/10083).
  1622. incomplete_formats = (
  1623. # All formats are video-only or
  1624. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
  1625. # all formats are audio-only
  1626. or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
  1627. ctx = {
  1628. 'formats': formats,
  1629. 'incomplete_formats': incomplete_formats,
  1630. }
  1631. formats_to_download = list(format_selector(ctx))
  1632. if not formats_to_download:
  1633. raise ExtractorError('requested format not available',
  1634. expected=True)
  1635. if download:
  1636. if len(formats_to_download) > 1:
  1637. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1638. for format in formats_to_download:
  1639. new_info = dict(info_dict)
  1640. new_info.update(format)
  1641. self.process_info(new_info)
  1642. # We update the info dict with the best quality format (backwards compatibility)
  1643. info_dict.update(formats_to_download[-1])
  1644. return info_dict
  1645. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1646. """Select the requested subtitles and their format"""
  1647. available_subs = {}
  1648. if normal_subtitles and self.params.get('writesubtitles'):
  1649. available_subs.update(normal_subtitles)
  1650. if automatic_captions and self.params.get('writeautomaticsub'):
  1651. for lang, cap_info in automatic_captions.items():
  1652. if lang not in available_subs:
  1653. available_subs[lang] = cap_info
  1654. if (not self.params.get('writesubtitles') and not
  1655. self.params.get('writeautomaticsub') or not
  1656. available_subs):
  1657. return None
  1658. if self.params.get('allsubtitles', False):
  1659. requested_langs = available_subs.keys()
  1660. else:
  1661. if self.params.get('subtitleslangs', False):
  1662. requested_langs = self.params.get('subtitleslangs')
  1663. elif 'en' in available_subs:
  1664. requested_langs = ['en']
  1665. else:
  1666. requested_langs = [list(available_subs.keys())[0]]
  1667. formats_query = self.params.get('subtitlesformat', 'best')
  1668. formats_preference = formats_query.split('/') if formats_query else []
  1669. subs = {}
  1670. for lang in requested_langs:
  1671. formats = available_subs.get(lang)
  1672. if formats is None:
  1673. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1674. continue
  1675. for ext in formats_preference:
  1676. if ext == 'best':
  1677. f = formats[-1]
  1678. break
  1679. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1680. if matches:
  1681. f = matches[-1]
  1682. break
  1683. else:
  1684. f = formats[-1]
  1685. self.report_warning(
  1686. 'No subtitle format found matching "%s" for language %s, '
  1687. 'using %s' % (formats_query, lang, f['ext']))
  1688. subs[lang] = f
  1689. return subs
  1690. def __forced_printings(self, info_dict, filename, incomplete):
  1691. def print_mandatory(field):
  1692. if (self.params.get('force%s' % field, False)
  1693. and (not incomplete or info_dict.get(field) is not None)):
  1694. self.to_stdout(info_dict[field])
  1695. def print_optional(field):
  1696. if (self.params.get('force%s' % field, False)
  1697. and info_dict.get(field) is not None):
  1698. self.to_stdout(info_dict[field])
  1699. print_mandatory('title')
  1700. print_mandatory('id')
  1701. if self.params.get('forceurl', False) and not incomplete:
  1702. if info_dict.get('requested_formats') is not None:
  1703. for f in info_dict['requested_formats']:
  1704. self.to_stdout(f['url'] + f.get('play_path', ''))
  1705. else:
  1706. # For RTMP URLs, also include the playpath
  1707. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1708. print_optional('thumbnail')
  1709. print_optional('description')
  1710. if self.params.get('forcefilename', False) and filename is not None:
  1711. self.to_stdout(filename)
  1712. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1713. self.to_stdout(formatSeconds(info_dict['duration']))
  1714. print_mandatory('format')
  1715. if self.params.get('forcejson', False):
  1716. self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
  1717. def process_info(self, info_dict):
  1718. """Process a single resolved IE result."""
  1719. assert info_dict.get('_type', 'video') == 'video'
  1720. max_downloads = int_or_none(self.params.get('max_downloads')) or float('inf')
  1721. if self._num_downloads >= max_downloads:
  1722. raise MaxDownloadsReached()
  1723. # TODO: backward compatibility, to be removed
  1724. info_dict['fulltitle'] = info_dict['title']
  1725. if 'format' not in info_dict:
  1726. info_dict['format'] = info_dict['ext']
  1727. reason = self._match_entry(info_dict, incomplete=False)
  1728. if reason is not None:
  1729. self.to_screen('[download] ' + reason)
  1730. return
  1731. self._num_downloads += 1
  1732. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1733. # Forced printings
  1734. self.__forced_printings(info_dict, filename, incomplete=False)
  1735. # Do nothing else if in simulate mode
  1736. if self.params.get('simulate', False):
  1737. return
  1738. if filename is None:
  1739. return
  1740. def ensure_dir_exists(path):
  1741. try:
  1742. dn = os.path.dirname(path)
  1743. if dn and not os.path.exists(dn):
  1744. os.makedirs(dn)
  1745. return True
  1746. except (OSError, IOError) as err:
  1747. if isinstance(err, OSError) and err.errno == errno.EEXIST:
  1748. return True
  1749. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1750. return False
  1751. if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
  1752. return
  1753. if self.params.get('writedescription', False):
  1754. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1755. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1756. self.to_screen('[info] Video description is already present')
  1757. elif info_dict.get('description') is None:
  1758. self.report_warning('There\'s no description to write.')
  1759. else:
  1760. try:
  1761. self.to_screen('[info] Writing video description to: ' + descfn)
  1762. with open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1763. descfile.write(info_dict['description'])
  1764. except (OSError, IOError):
  1765. self.report_error('Cannot write description file ' + descfn)
  1766. return
  1767. if self.params.get('writeannotations', False):
  1768. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1769. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1770. self.to_screen('[info] Video annotations are already present')
  1771. elif not info_dict.get('annotations'):
  1772. self.report_warning('There are no annotations to write.')
  1773. else:
  1774. try:
  1775. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1776. with open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1777. annofile.write(info_dict['annotations'])
  1778. except (KeyError, TypeError):
  1779. self.report_warning('There are no annotations to write.')
  1780. except (OSError, IOError):
  1781. self.report_error('Cannot write annotations file: ' + annofn)
  1782. return
  1783. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1784. self.params.get('writeautomaticsub')])
  1785. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1786. # subtitles download errors are already managed as troubles in relevant IE
  1787. # that way it will silently go on when used with unsupporting IE
  1788. subtitles = info_dict['requested_subtitles']
  1789. ie = self.get_info_extractor(info_dict['extractor_key'])
  1790. for sub_lang, sub_info in subtitles.items():
  1791. sub_format = sub_info['ext']
  1792. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  1793. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1794. self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
  1795. else:
  1796. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1797. if sub_info.get('data') is not None:
  1798. try:
  1799. # Use newline='' to prevent conversion of newline characters
  1800. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  1801. with open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
  1802. subfile.write(sub_info['data'])
  1803. except (OSError, IOError):
  1804. self.report_error('Cannot write subtitles file ' + sub_filename)
  1805. return
  1806. else:
  1807. try:
  1808. sub_data = ie._request_webpage(
  1809. sub_info['url'], info_dict['id'], note=False).read()
  1810. with open(encodeFilename(sub_filename), 'wb') as subfile:
  1811. subfile.write(sub_data)
  1812. except (ExtractorError, IOError, OSError, ValueError) as err:
  1813. self.report_warning('Unable to download subtitle for "%s": %s' %
  1814. (sub_lang, error_to_compat_str(err)))
  1815. continue
  1816. self._write_info_json(
  1817. 'video description', info_dict,
  1818. replace_extension(filename, 'info.json', info_dict.get('ext')))
  1819. self._write_thumbnails(info_dict, filename)
  1820. if not self.params.get('skip_download', False):
  1821. try:
  1822. def checked_get_suitable_downloader(info_dict, params):
  1823. ed_args = params.get('external_downloader_args')
  1824. dler = get_suitable_downloader(info_dict, params)
  1825. if ed_args and not params.get('external_downloader_args'):
  1826. # external_downloader_args was cleared because external_downloader was rejected
  1827. self.report_warning('Requested external downloader cannot be used: '
  1828. 'ignoring --external-downloader-args.')
  1829. return dler
  1830. def dl(name, info):
  1831. fd = checked_get_suitable_downloader(info, self.params)(self, self.params)
  1832. for ph in self._progress_hooks:
  1833. fd.add_progress_hook(ph)
  1834. if self.params.get('verbose'):
  1835. self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
  1836. new_info = dict((k, v) for k, v in info.items() if not k.startswith('__p'))
  1837. new_info['http_headers'] = self._calc_headers(new_info)
  1838. return fd.download(name, new_info)
  1839. if info_dict.get('requested_formats') is not None:
  1840. downloaded = []
  1841. success = True
  1842. merger = FFmpegMergerPP(self)
  1843. if not merger.available:
  1844. postprocessors = []
  1845. self.report_warning('You have requested multiple '
  1846. 'formats but ffmpeg or avconv are not installed.'
  1847. ' The formats won\'t be merged.')
  1848. else:
  1849. postprocessors = [merger]
  1850. def compatible_formats(formats):
  1851. video, audio = formats
  1852. # Check extension
  1853. video_ext, audio_ext = video.get('ext'), audio.get('ext')
  1854. if video_ext and audio_ext:
  1855. COMPATIBLE_EXTS = (
  1856. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
  1857. ('webm')
  1858. )
  1859. for exts in COMPATIBLE_EXTS:
  1860. if video_ext in exts and audio_ext in exts:
  1861. return True
  1862. # TODO: Check acodec/vcodec
  1863. return False
  1864. filename_real_ext = os.path.splitext(filename)[1][1:]
  1865. filename_wo_ext = (
  1866. os.path.splitext(filename)[0]
  1867. if filename_real_ext == info_dict['ext']
  1868. else filename)
  1869. requested_formats = info_dict['requested_formats']
  1870. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1871. info_dict['ext'] = 'mkv'
  1872. self.report_warning(
  1873. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1874. # Ensure filename always has a correct extension for successful merge
  1875. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1876. if os.path.exists(encodeFilename(filename)):
  1877. self.to_screen(
  1878. '[download] %s has already been downloaded and '
  1879. 'merged' % filename)
  1880. else:
  1881. for f in requested_formats:
  1882. new_info = dict(info_dict)
  1883. new_info.update(f)
  1884. fname = prepend_extension(
  1885. self.prepare_filename(new_info),
  1886. 'f%s' % f['format_id'], new_info['ext'])
  1887. if not ensure_dir_exists(fname):
  1888. return
  1889. downloaded.append(fname)
  1890. partial_success = dl(fname, new_info)
  1891. success = success and partial_success
  1892. info_dict['__postprocessors'] = postprocessors
  1893. info_dict['__files_to_merge'] = downloaded
  1894. else:
  1895. # Just a single file
  1896. success = dl(filename, info_dict)
  1897. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1898. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1899. return
  1900. except (OSError, IOError) as err:
  1901. raise UnavailableVideoError(err)
  1902. except (ContentTooShortError, ) as err:
  1903. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1904. return
  1905. if success and filename != '-':
  1906. # Fixup content
  1907. fixup_policy = self.params.get('fixup')
  1908. if fixup_policy is None:
  1909. fixup_policy = 'detect_or_warn'
  1910. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1911. stretched_ratio = info_dict.get('stretched_ratio')
  1912. if stretched_ratio is not None and stretched_ratio != 1:
  1913. if fixup_policy == 'warn':
  1914. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1915. info_dict['id'], stretched_ratio))
  1916. elif fixup_policy == 'detect_or_warn':
  1917. stretched_pp = FFmpegFixupStretchedPP(self)
  1918. if stretched_pp.available:
  1919. info_dict.setdefault('__postprocessors', [])
  1920. info_dict['__postprocessors'].append(stretched_pp)
  1921. else:
  1922. self.report_warning(
  1923. '%s: Non-uniform pixel ratio (%s). %s'
  1924. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1925. else:
  1926. assert fixup_policy in ('ignore', 'never')
  1927. if (info_dict.get('requested_formats') is None
  1928. and info_dict.get('container') == 'm4a_dash'):
  1929. if fixup_policy == 'warn':
  1930. self.report_warning(
  1931. '%s: writing DASH m4a. '
  1932. 'Only some players support this container.'
  1933. % info_dict['id'])
  1934. elif fixup_policy == 'detect_or_warn':
  1935. fixup_pp = FFmpegFixupM4aPP(self)
  1936. if fixup_pp.available:
  1937. info_dict.setdefault('__postprocessors', [])
  1938. info_dict['__postprocessors'].append(fixup_pp)
  1939. else:
  1940. self.report_warning(
  1941. '%s: writing DASH m4a. '
  1942. 'Only some players support this container. %s'
  1943. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1944. else:
  1945. assert fixup_policy in ('ignore', 'never')
  1946. if (info_dict.get('protocol') == 'm3u8_native'
  1947. or info_dict.get('protocol') == 'm3u8'
  1948. and self.params.get('hls_prefer_native')):
  1949. if fixup_policy == 'warn':
  1950. self.report_warning('%s: malformed AAC bitstream detected.' % (
  1951. info_dict['id']))
  1952. elif fixup_policy == 'detect_or_warn':
  1953. fixup_pp = FFmpegFixupM3u8PP(self)
  1954. if fixup_pp.available:
  1955. info_dict.setdefault('__postprocessors', [])
  1956. info_dict['__postprocessors'].append(fixup_pp)
  1957. else:
  1958. self.report_warning(
  1959. '%s: malformed AAC bitstream detected. %s'
  1960. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1961. else:
  1962. assert fixup_policy in ('ignore', 'never')
  1963. try:
  1964. self.post_process(filename, info_dict)
  1965. except (PostProcessingError) as err:
  1966. self.report_error('postprocessing: %s' % error_to_compat_str(err))
  1967. return
  1968. self.record_download_archive(info_dict)
  1969. # avoid possible nugatory search for further items (PR #26638)
  1970. if self._num_downloads >= max_downloads:
  1971. raise MaxDownloadsReached()
  1972. def download(self, url_list):
  1973. """Download a given list of URLs."""
  1974. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1975. if (len(url_list) > 1
  1976. and outtmpl != '-'
  1977. and '%' not in outtmpl
  1978. and self.params.get('max_downloads') != 1):
  1979. raise SameFileError(outtmpl)
  1980. for url in url_list:
  1981. try:
  1982. # It also downloads the videos
  1983. res = self.extract_info(
  1984. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1985. except UnavailableVideoError:
  1986. self.report_error('unable to download video')
  1987. except MaxDownloadsReached:
  1988. self.to_screen('[info] Maximum number of downloaded files reached.')
  1989. raise
  1990. else:
  1991. if self.params.get('dump_single_json', False):
  1992. self.to_stdout(json.dumps(self.sanitize_info(res)))
  1993. return self._download_retcode
  1994. def download_with_info_file(self, info_filename):
  1995. with open(info_filename, encoding='utf-8') as f:
  1996. info = self.filter_requested_info(json.load(f))
  1997. try:
  1998. self.process_ie_result(info, download=True)
  1999. except DownloadError:
  2000. webpage_url = info.get('webpage_url')
  2001. if webpage_url is not None:
  2002. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  2003. return self.download([webpage_url])
  2004. else:
  2005. raise
  2006. return self._download_retcode
  2007. @staticmethod
  2008. def sanitize_info(info_dict, remove_private_keys=False):
  2009. ''' Sanitize the infodict for converting to json '''
  2010. if info_dict is None:
  2011. return info_dict
  2012. if remove_private_keys:
  2013. reject = lambda k, v: (v is None
  2014. or k.startswith('__')
  2015. or k in ('requested_formats',
  2016. 'requested_subtitles'))
  2017. else:
  2018. reject = lambda k, v: False
  2019. def filter_fn(obj):
  2020. if isinstance(obj, dict):
  2021. return dict((k, filter_fn(v)) for k, v in obj.items() if not reject(k, v))
  2022. elif isinstance(obj, (list, tuple, set, LazyList)):
  2023. return list(map(filter_fn, obj))
  2024. elif obj is None or any(isinstance(obj, c)
  2025. for c in (compat_integer_types,
  2026. (compat_str, float, bool))):
  2027. return obj
  2028. else:
  2029. return repr(obj)
  2030. return filter_fn(info_dict)
  2031. @classmethod
  2032. def filter_requested_info(cls, info_dict):
  2033. return cls.sanitize_info(info_dict, True)
  2034. def post_process(self, filename, ie_info):
  2035. """Run all the postprocessors on the given file."""
  2036. info = dict(ie_info)
  2037. info['filepath'] = filename
  2038. pps_chain = []
  2039. if ie_info.get('__postprocessors') is not None:
  2040. pps_chain.extend(ie_info['__postprocessors'])
  2041. pps_chain.extend(self._pps)
  2042. for pp in pps_chain:
  2043. files_to_delete = []
  2044. try:
  2045. files_to_delete, info = pp.run(info)
  2046. except PostProcessingError as e:
  2047. self.report_error(e.msg)
  2048. if files_to_delete and not self.params.get('keepvideo', False):
  2049. for old_filename in files_to_delete:
  2050. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  2051. try:
  2052. os.remove(encodeFilename(old_filename))
  2053. except (IOError, OSError):
  2054. self.report_warning('Unable to remove downloaded original file')
  2055. def _make_archive_id(self, info_dict):
  2056. video_id = info_dict.get('id')
  2057. if not video_id:
  2058. return
  2059. # Future-proof against any change in case
  2060. # and backwards compatibility with prior versions
  2061. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  2062. if extractor is None:
  2063. url = str_or_none(info_dict.get('url'))
  2064. if not url:
  2065. return
  2066. # Try to find matching extractor for the URL and take its ie_key
  2067. for ie in self._ies:
  2068. if ie.suitable(url):
  2069. extractor = ie.ie_key()
  2070. break
  2071. else:
  2072. return
  2073. return extractor.lower() + ' ' + video_id
  2074. def in_download_archive(self, info_dict):
  2075. fn = self.params.get('download_archive')
  2076. if fn is None:
  2077. return False
  2078. vid_id = self._make_archive_id(info_dict)
  2079. if not vid_id:
  2080. return False # Incomplete video information
  2081. try:
  2082. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  2083. for line in archive_file:
  2084. if line.strip() == vid_id:
  2085. return True
  2086. except IOError as ioe:
  2087. if ioe.errno != errno.ENOENT:
  2088. raise
  2089. return False
  2090. def record_download_archive(self, info_dict):
  2091. fn = self.params.get('download_archive')
  2092. if fn is None:
  2093. return
  2094. vid_id = self._make_archive_id(info_dict)
  2095. assert vid_id
  2096. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  2097. archive_file.write(vid_id + '\n')
  2098. @staticmethod
  2099. def format_resolution(format, default='unknown'):
  2100. if format.get('vcodec') == 'none':
  2101. return 'audio only'
  2102. if format.get('resolution') is not None:
  2103. return format['resolution']
  2104. if format.get('height') is not None:
  2105. if format.get('width') is not None:
  2106. res = '%sx%s' % (format['width'], format['height'])
  2107. else:
  2108. res = '%sp' % format['height']
  2109. elif format.get('width') is not None:
  2110. res = '%dx?' % format['width']
  2111. else:
  2112. res = default
  2113. return res
  2114. def _format_note(self, fdict):
  2115. res = ''
  2116. if fdict.get('ext') in ['f4f', 'f4m']:
  2117. res += '(unsupported) '
  2118. if fdict.get('language'):
  2119. if res:
  2120. res += ' '
  2121. res += '[%s] ' % fdict['language']
  2122. if fdict.get('format_note') is not None:
  2123. res += fdict['format_note'] + ' '
  2124. if fdict.get('tbr') is not None:
  2125. res += '%4dk ' % fdict['tbr']
  2126. if fdict.get('container') is not None:
  2127. if res:
  2128. res += ', '
  2129. res += '%s container' % fdict['container']
  2130. if (fdict.get('vcodec') is not None
  2131. and fdict.get('vcodec') != 'none'):
  2132. if res:
  2133. res += ', '
  2134. res += fdict['vcodec']
  2135. if fdict.get('vbr') is not None:
  2136. res += '@'
  2137. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  2138. res += 'video@'
  2139. if fdict.get('vbr') is not None:
  2140. res += '%4dk' % fdict['vbr']
  2141. if fdict.get('fps') is not None:
  2142. if res:
  2143. res += ', '
  2144. res += '%sfps' % fdict['fps']
  2145. if fdict.get('acodec') is not None:
  2146. if res:
  2147. res += ', '
  2148. if fdict['acodec'] == 'none':
  2149. res += 'video only'
  2150. else:
  2151. res += '%-5s' % fdict['acodec']
  2152. elif fdict.get('abr') is not None:
  2153. if res:
  2154. res += ', '
  2155. res += 'audio'
  2156. if fdict.get('abr') is not None:
  2157. res += '@%3dk' % fdict['abr']
  2158. if fdict.get('asr') is not None:
  2159. res += ' (%5dHz)' % fdict['asr']
  2160. if fdict.get('filesize') is not None:
  2161. if res:
  2162. res += ', '
  2163. res += format_bytes(fdict['filesize'])
  2164. elif fdict.get('filesize_approx') is not None:
  2165. if res:
  2166. res += ', '
  2167. res += '~' + format_bytes(fdict['filesize_approx'])
  2168. return res
  2169. def list_formats(self, info_dict):
  2170. formats = info_dict.get('formats', [info_dict])
  2171. table = [
  2172. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  2173. for f in formats
  2174. if f.get('preference') is None or f['preference'] >= -1000]
  2175. if len(formats) > 1:
  2176. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  2177. header_line = ['format code', 'extension', 'resolution', 'note']
  2178. self.to_screen(
  2179. '[info] Available formats for %s:\n%s' %
  2180. (info_dict['id'], render_table(header_line, table)))
  2181. def list_thumbnails(self, info_dict):
  2182. thumbnails = info_dict.get('thumbnails')
  2183. if not thumbnails:
  2184. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  2185. return
  2186. self.to_screen(
  2187. '[info] Thumbnails for %s:' % info_dict['id'])
  2188. self.to_screen(render_table(
  2189. ['ID', 'width', 'height', 'URL'],
  2190. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  2191. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  2192. if not subtitles:
  2193. self.to_screen('%s has no %s' % (video_id, name))
  2194. return
  2195. self.to_screen(
  2196. 'Available %s for %s:' % (name, video_id))
  2197. self.to_screen(render_table(
  2198. ['Language', 'formats'],
  2199. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  2200. for lang, formats in subtitles.items()]))
  2201. def urlopen(self, req):
  2202. """ Start an HTTP download """
  2203. if isinstance(req, compat_basestring):
  2204. req = sanitized_Request(req)
  2205. return self._opener.open(req, timeout=self._socket_timeout)
  2206. def print_debug_header(self):
  2207. if not self.params.get('verbose'):
  2208. return
  2209. if type('') is not compat_str:
  2210. # Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
  2211. self.report_warning(
  2212. 'Your Python is broken! Update to a newer and supported version')
  2213. stdout_encoding = getattr(
  2214. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  2215. encoding_str = (
  2216. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  2217. locale.getpreferredencoding(),
  2218. sys.getfilesystemencoding(),
  2219. stdout_encoding,
  2220. self.get_encoding()))
  2221. write_string(encoding_str, encoding=None)
  2222. writeln_debug = lambda *s: self._write_string('[debug] %s\n' % (''.join(s), ))
  2223. writeln_debug('youtube-dl version ', __version__)
  2224. if _LAZY_LOADER:
  2225. writeln_debug('Lazy loading extractors enabled')
  2226. if ytdl_is_updateable():
  2227. writeln_debug('Single file build')
  2228. try:
  2229. sp = subprocess.Popen(
  2230. ['git', 'rev-parse', '--short', 'HEAD'],
  2231. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2232. cwd=os.path.dirname(os.path.abspath(__file__)))
  2233. out, err = process_communicate_or_kill(sp)
  2234. out = out.decode().strip()
  2235. if re.match('[0-9a-f]+', out):
  2236. writeln_debug('Git HEAD: ', out)
  2237. except Exception:
  2238. try:
  2239. sys.exc_clear()
  2240. except Exception:
  2241. pass
  2242. def python_implementation():
  2243. impl_name = platform.python_implementation()
  2244. if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
  2245. return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
  2246. return impl_name
  2247. def libc_ver():
  2248. try:
  2249. return platform.libc_ver()
  2250. except OSError: # We may not have access to the executable
  2251. return []
  2252. libc = join_nonempty(*libc_ver(), delim=' ')
  2253. writeln_debug('Python %s (%s %s %s) - %s - %s%s' % (
  2254. platform.python_version(),
  2255. python_implementation(),
  2256. platform.machine(),
  2257. platform.architecture()[0],
  2258. platform_name(),
  2259. OPENSSL_VERSION,
  2260. (' - %s' % (libc, )) if libc else ''
  2261. ))
  2262. exe_versions = FFmpegPostProcessor.get_versions(self)
  2263. exe_versions['rtmpdump'] = rtmpdump_version()
  2264. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  2265. exe_str = ', '.join(
  2266. '%s %s' % (exe, v)
  2267. for exe, v in sorted(exe_versions.items())
  2268. if v
  2269. )
  2270. if not exe_str:
  2271. exe_str = 'none'
  2272. writeln_debug('exe versions: %s' % (exe_str, ))
  2273. proxy_map = {}
  2274. for handler in self._opener.handlers:
  2275. if hasattr(handler, 'proxies'):
  2276. proxy_map.update(handler.proxies)
  2277. writeln_debug('Proxy map: ', compat_str(proxy_map))
  2278. if self.params.get('call_home', False):
  2279. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  2280. writeln_debug('Public IP address: %s' % (ipaddr, ))
  2281. latest_version = self.urlopen(
  2282. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  2283. if version_tuple(latest_version) > version_tuple(__version__):
  2284. self.report_warning(
  2285. 'You are using an outdated version (newest version: %s)! '
  2286. 'See https://yt-dl.org/update if you need help updating.' %
  2287. latest_version)
  2288. def _setup_opener(self):
  2289. timeout_val = self.params.get('socket_timeout')
  2290. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  2291. opts_cookiefile = self.params.get('cookiefile')
  2292. opts_proxy = self.params.get('proxy')
  2293. if opts_cookiefile is None:
  2294. self.cookiejar = YoutubeDLCookieJar()
  2295. else:
  2296. opts_cookiefile = expand_path(opts_cookiefile)
  2297. self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
  2298. if os.access(opts_cookiefile, os.R_OK):
  2299. self.cookiejar.load(ignore_discard=True, ignore_expires=True)
  2300. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  2301. if opts_proxy is not None:
  2302. if opts_proxy == '':
  2303. proxies = {}
  2304. else:
  2305. proxies = {'http': opts_proxy, 'https': opts_proxy}
  2306. else:
  2307. proxies = compat_urllib_request.getproxies()
  2308. # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
  2309. if 'http' in proxies and 'https' not in proxies:
  2310. proxies['https'] = proxies['http']
  2311. proxy_handler = PerRequestProxyHandler(proxies)
  2312. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  2313. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  2314. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  2315. redirect_handler = YoutubeDLRedirectHandler()
  2316. data_handler = compat_urllib_request_DataHandler()
  2317. # When passing our own FileHandler instance, build_opener won't add the
  2318. # default FileHandler and allows us to disable the file protocol, which
  2319. # can be used for malicious purposes (see
  2320. # https://github.com/ytdl-org/youtube-dl/issues/8227)
  2321. file_handler = compat_urllib_request.FileHandler()
  2322. def file_open(*args, **kwargs):
  2323. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  2324. file_handler.file_open = file_open
  2325. opener = compat_urllib_request.build_opener(
  2326. proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
  2327. # Delete the default user-agent header, which would otherwise apply in
  2328. # cases where our custom HTTP handler doesn't come into play
  2329. # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
  2330. opener.addheaders = []
  2331. self._opener = opener
  2332. def encode(self, s):
  2333. if isinstance(s, bytes):
  2334. return s # Already encoded
  2335. try:
  2336. return s.encode(self.get_encoding())
  2337. except UnicodeEncodeError as err:
  2338. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  2339. raise
  2340. def get_encoding(self):
  2341. encoding = self.params.get('encoding')
  2342. if encoding is None:
  2343. encoding = preferredencoding()
  2344. return encoding
  2345. def _write_info_json(self, label, info_dict, infofn, overwrite=None):
  2346. if not self.params.get('writeinfojson', False):
  2347. return False
  2348. def msg(fmt, lbl):
  2349. return fmt % (lbl + ' metadata',)
  2350. if overwrite is None:
  2351. overwrite = not self.params.get('nooverwrites', False)
  2352. if not overwrite and os.path.exists(encodeFilename(infofn)):
  2353. self.to_screen(msg('[info] %s is already present', label.title()))
  2354. return 'exists'
  2355. else:
  2356. self.to_screen(msg('[info] Writing %s as JSON to: ', label) + infofn)
  2357. try:
  2358. write_json_file(self.filter_requested_info(info_dict), infofn)
  2359. return True
  2360. except (OSError, IOError):
  2361. self.report_error(msg('Cannot write %s to JSON file ', label) + infofn)
  2362. return
  2363. def _write_thumbnails(self, info_dict, filename):
  2364. if self.params.get('writethumbnail', False):
  2365. thumbnails = info_dict.get('thumbnails')
  2366. if thumbnails:
  2367. thumbnails = [thumbnails[-1]]
  2368. elif self.params.get('write_all_thumbnails', False):
  2369. thumbnails = info_dict.get('thumbnails')
  2370. else:
  2371. return
  2372. if not thumbnails:
  2373. # No thumbnails present, so return immediately
  2374. return
  2375. for t in thumbnails:
  2376. thumb_ext = determine_ext(t['url'], 'jpg')
  2377. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  2378. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  2379. t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
  2380. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  2381. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  2382. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2383. else:
  2384. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  2385. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2386. try:
  2387. uf = self.urlopen(t['url'])
  2388. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  2389. shutil.copyfileobj(uf, thumbf)
  2390. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  2391. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  2392. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2393. self.report_warning('Unable to download thumbnail "%s": %s' %
  2394. (t['url'], error_to_compat_str(err)))