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

2265 lines
102 KiB

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