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.

2272 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
9 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
9 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_get_terminal_size,
  30. compat_http_client,
  31. compat_kwargs,
  32. compat_numeric_types,
  33. compat_os_name,
  34. compat_str,
  35. compat_tokenize_tokenize,
  36. compat_urllib_error,
  37. compat_urllib_request,
  38. compat_urllib_request_DataHandler,
  39. )
  40. from .utils import (
  41. age_restricted,
  42. args_to_str,
  43. ContentTooShortError,
  44. date_from_str,
  45. DateRange,
  46. DEFAULT_OUTTMPL,
  47. determine_ext,
  48. determine_protocol,
  49. DownloadError,
  50. encode_compat_str,
  51. encodeFilename,
  52. error_to_compat_str,
  53. expand_path,
  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' or k.endswith('_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 = expand_path(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. # extract_info may return None when ignoreerrors is enabled and
  762. # extraction failed with an error, don't crash and return early
  763. # in this case
  764. if not info:
  765. return info
  766. force_properties = dict(
  767. (k, v) for k, v in ie_result.items() if v is not None)
  768. for f in ('_type', 'url', 'ie_key'):
  769. if f in force_properties:
  770. del force_properties[f]
  771. new_result = info.copy()
  772. new_result.update(force_properties)
  773. assert new_result.get('_type') != 'url_transparent'
  774. return self.process_ie_result(
  775. new_result, download=download, extra_info=extra_info)
  776. elif result_type == 'playlist' or result_type == 'multi_video':
  777. # We process each entry in the playlist
  778. playlist = ie_result.get('title') or ie_result.get('id')
  779. self.to_screen('[download] Downloading playlist: %s' % playlist)
  780. playlist_results = []
  781. playliststart = self.params.get('playliststart', 1) - 1
  782. playlistend = self.params.get('playlistend')
  783. # For backwards compatibility, interpret -1 as whole list
  784. if playlistend == -1:
  785. playlistend = None
  786. playlistitems_str = self.params.get('playlist_items')
  787. playlistitems = None
  788. if playlistitems_str is not None:
  789. def iter_playlistitems(format):
  790. for string_segment in format.split(','):
  791. if '-' in string_segment:
  792. start, end = string_segment.split('-')
  793. for item in range(int(start), int(end) + 1):
  794. yield int(item)
  795. else:
  796. yield int(string_segment)
  797. playlistitems = iter_playlistitems(playlistitems_str)
  798. ie_entries = ie_result['entries']
  799. if isinstance(ie_entries, list):
  800. n_all_entries = len(ie_entries)
  801. if playlistitems:
  802. entries = [
  803. ie_entries[i - 1] for i in playlistitems
  804. if -n_all_entries <= i - 1 < n_all_entries]
  805. else:
  806. entries = ie_entries[playliststart:playlistend]
  807. n_entries = len(entries)
  808. self.to_screen(
  809. '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
  810. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  811. elif isinstance(ie_entries, PagedList):
  812. if playlistitems:
  813. entries = []
  814. for item in playlistitems:
  815. entries.extend(ie_entries.getslice(
  816. item - 1, item
  817. ))
  818. else:
  819. entries = ie_entries.getslice(
  820. playliststart, playlistend)
  821. n_entries = len(entries)
  822. self.to_screen(
  823. '[%s] playlist %s: Downloading %d videos' %
  824. (ie_result['extractor'], playlist, n_entries))
  825. else: # iterable
  826. if playlistitems:
  827. entry_list = list(ie_entries)
  828. entries = [entry_list[i - 1] for i in playlistitems]
  829. else:
  830. entries = list(itertools.islice(
  831. ie_entries, playliststart, playlistend))
  832. n_entries = len(entries)
  833. self.to_screen(
  834. '[%s] playlist %s: Downloading %d videos' %
  835. (ie_result['extractor'], playlist, n_entries))
  836. if self.params.get('playlistreverse', False):
  837. entries = entries[::-1]
  838. if self.params.get('playlistrandom', False):
  839. random.shuffle(entries)
  840. x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
  841. for i, entry in enumerate(entries, 1):
  842. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  843. # This __x_forwarded_for_ip thing is a bit ugly but requires
  844. # minimal changes
  845. if x_forwarded_for:
  846. entry['__x_forwarded_for_ip'] = x_forwarded_for
  847. extra = {
  848. 'n_entries': n_entries,
  849. 'playlist': playlist,
  850. 'playlist_id': ie_result.get('id'),
  851. 'playlist_title': ie_result.get('title'),
  852. 'playlist_index': i + playliststart,
  853. 'extractor': ie_result['extractor'],
  854. 'webpage_url': ie_result['webpage_url'],
  855. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  856. 'extractor_key': ie_result['extractor_key'],
  857. }
  858. reason = self._match_entry(entry, incomplete=True)
  859. if reason is not None:
  860. self.to_screen('[download] ' + reason)
  861. continue
  862. entry_result = self.process_ie_result(entry,
  863. download=download,
  864. extra_info=extra)
  865. playlist_results.append(entry_result)
  866. ie_result['entries'] = playlist_results
  867. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  868. return ie_result
  869. elif result_type == 'compat_list':
  870. self.report_warning(
  871. 'Extractor %s returned a compat_list result. '
  872. 'It needs to be updated.' % ie_result.get('extractor'))
  873. def _fixup(r):
  874. self.add_extra_info(
  875. r,
  876. {
  877. 'extractor': ie_result['extractor'],
  878. 'webpage_url': ie_result['webpage_url'],
  879. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  880. 'extractor_key': ie_result['extractor_key'],
  881. }
  882. )
  883. return r
  884. ie_result['entries'] = [
  885. self.process_ie_result(_fixup(r), download, extra_info)
  886. for r in ie_result['entries']
  887. ]
  888. return ie_result
  889. else:
  890. raise Exception('Invalid result type: %s' % result_type)
  891. def _build_format_filter(self, filter_spec):
  892. " Returns a function to filter the formats according to the filter_spec "
  893. OPERATORS = {
  894. '<': operator.lt,
  895. '<=': operator.le,
  896. '>': operator.gt,
  897. '>=': operator.ge,
  898. '=': operator.eq,
  899. '!=': operator.ne,
  900. }
  901. operator_rex = re.compile(r'''(?x)\s*
  902. (?P<key>width|height|tbr|abr|vbr|asr|filesize|fps)
  903. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  904. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  905. $
  906. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  907. m = operator_rex.search(filter_spec)
  908. if m:
  909. try:
  910. comparison_value = int(m.group('value'))
  911. except ValueError:
  912. comparison_value = parse_filesize(m.group('value'))
  913. if comparison_value is None:
  914. comparison_value = parse_filesize(m.group('value') + 'B')
  915. if comparison_value is None:
  916. raise ValueError(
  917. 'Invalid value %r in format specification %r' % (
  918. m.group('value'), filter_spec))
  919. op = OPERATORS[m.group('op')]
  920. if not m:
  921. STR_OPERATORS = {
  922. '=': operator.eq,
  923. '!=': operator.ne,
  924. '^=': lambda attr, value: attr.startswith(value),
  925. '$=': lambda attr, value: attr.endswith(value),
  926. '*=': lambda attr, value: value in attr,
  927. }
  928. str_operator_rex = re.compile(r'''(?x)
  929. \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id)
  930. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?
  931. \s*(?P<value>[a-zA-Z0-9._-]+)
  932. \s*$
  933. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  934. m = str_operator_rex.search(filter_spec)
  935. if m:
  936. comparison_value = m.group('value')
  937. op = STR_OPERATORS[m.group('op')]
  938. if not m:
  939. raise ValueError('Invalid filter specification %r' % filter_spec)
  940. def _filter(f):
  941. actual_value = f.get(m.group('key'))
  942. if actual_value is None:
  943. return m.group('none_inclusive')
  944. return op(actual_value, comparison_value)
  945. return _filter
  946. def build_format_selector(self, format_spec):
  947. def syntax_error(note, start):
  948. message = (
  949. 'Invalid format specification: '
  950. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  951. return SyntaxError(message)
  952. PICKFIRST = 'PICKFIRST'
  953. MERGE = 'MERGE'
  954. SINGLE = 'SINGLE'
  955. GROUP = 'GROUP'
  956. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  957. def _parse_filter(tokens):
  958. filter_parts = []
  959. for type, string, start, _, _ in tokens:
  960. if type == tokenize.OP and string == ']':
  961. return ''.join(filter_parts)
  962. else:
  963. filter_parts.append(string)
  964. def _remove_unused_ops(tokens):
  965. # Remove operators that we don't use and join them with the surrounding strings
  966. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  967. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  968. last_string, last_start, last_end, last_line = None, None, None, None
  969. for type, string, start, end, line in tokens:
  970. if type == tokenize.OP and string == '[':
  971. if last_string:
  972. yield tokenize.NAME, last_string, last_start, last_end, last_line
  973. last_string = None
  974. yield type, string, start, end, line
  975. # everything inside brackets will be handled by _parse_filter
  976. for type, string, start, end, line in tokens:
  977. yield type, string, start, end, line
  978. if type == tokenize.OP and string == ']':
  979. break
  980. elif type == tokenize.OP and string in ALLOWED_OPS:
  981. if last_string:
  982. yield tokenize.NAME, last_string, last_start, last_end, last_line
  983. last_string = None
  984. yield type, string, start, end, line
  985. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  986. if not last_string:
  987. last_string = string
  988. last_start = start
  989. last_end = end
  990. else:
  991. last_string += string
  992. if last_string:
  993. yield tokenize.NAME, last_string, last_start, last_end, last_line
  994. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  995. selectors = []
  996. current_selector = None
  997. for type, string, start, _, _ in tokens:
  998. # ENCODING is only defined in python 3.x
  999. if type == getattr(tokenize, 'ENCODING', None):
  1000. continue
  1001. elif type in [tokenize.NAME, tokenize.NUMBER]:
  1002. current_selector = FormatSelector(SINGLE, string, [])
  1003. elif type == tokenize.OP:
  1004. if string == ')':
  1005. if not inside_group:
  1006. # ')' will be handled by the parentheses group
  1007. tokens.restore_last_token()
  1008. break
  1009. elif inside_merge and string in ['/', ',']:
  1010. tokens.restore_last_token()
  1011. break
  1012. elif inside_choice and string == ',':
  1013. tokens.restore_last_token()
  1014. break
  1015. elif string == ',':
  1016. if not current_selector:
  1017. raise syntax_error('"," must follow a format selector', start)
  1018. selectors.append(current_selector)
  1019. current_selector = None
  1020. elif string == '/':
  1021. if not current_selector:
  1022. raise syntax_error('"/" must follow a format selector', start)
  1023. first_choice = current_selector
  1024. second_choice = _parse_format_selection(tokens, inside_choice=True)
  1025. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  1026. elif string == '[':
  1027. if not current_selector:
  1028. current_selector = FormatSelector(SINGLE, 'best', [])
  1029. format_filter = _parse_filter(tokens)
  1030. current_selector.filters.append(format_filter)
  1031. elif string == '(':
  1032. if current_selector:
  1033. raise syntax_error('Unexpected "("', start)
  1034. group = _parse_format_selection(tokens, inside_group=True)
  1035. current_selector = FormatSelector(GROUP, group, [])
  1036. elif string == '+':
  1037. video_selector = current_selector
  1038. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  1039. if not video_selector or not audio_selector:
  1040. raise syntax_error('"+" must be between two format selectors', start)
  1041. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  1042. else:
  1043. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  1044. elif type == tokenize.ENDMARKER:
  1045. break
  1046. if current_selector:
  1047. selectors.append(current_selector)
  1048. return selectors
  1049. def _build_selector_function(selector):
  1050. if isinstance(selector, list):
  1051. fs = [_build_selector_function(s) for s in selector]
  1052. def selector_function(ctx):
  1053. for f in fs:
  1054. for format in f(ctx):
  1055. yield format
  1056. return selector_function
  1057. elif selector.type == GROUP:
  1058. selector_function = _build_selector_function(selector.selector)
  1059. elif selector.type == PICKFIRST:
  1060. fs = [_build_selector_function(s) for s in selector.selector]
  1061. def selector_function(ctx):
  1062. for f in fs:
  1063. picked_formats = list(f(ctx))
  1064. if picked_formats:
  1065. return picked_formats
  1066. return []
  1067. elif selector.type == SINGLE:
  1068. format_spec = selector.selector
  1069. def selector_function(ctx):
  1070. formats = list(ctx['formats'])
  1071. if not formats:
  1072. return
  1073. if format_spec == 'all':
  1074. for f in formats:
  1075. yield f
  1076. elif format_spec in ['best', 'worst', None]:
  1077. format_idx = 0 if format_spec == 'worst' else -1
  1078. audiovideo_formats = [
  1079. f for f in formats
  1080. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  1081. if audiovideo_formats:
  1082. yield audiovideo_formats[format_idx]
  1083. # for extractors with incomplete formats (audio only (soundcloud)
  1084. # or video only (imgur)) we will fallback to best/worst
  1085. # {video,audio}-only format
  1086. elif ctx['incomplete_formats']:
  1087. yield formats[format_idx]
  1088. elif format_spec == 'bestaudio':
  1089. audio_formats = [
  1090. f for f in formats
  1091. if f.get('vcodec') == 'none']
  1092. if audio_formats:
  1093. yield audio_formats[-1]
  1094. elif format_spec == 'worstaudio':
  1095. audio_formats = [
  1096. f for f in formats
  1097. if f.get('vcodec') == 'none']
  1098. if audio_formats:
  1099. yield audio_formats[0]
  1100. elif format_spec == 'bestvideo':
  1101. video_formats = [
  1102. f for f in formats
  1103. if f.get('acodec') == 'none']
  1104. if video_formats:
  1105. yield video_formats[-1]
  1106. elif format_spec == 'worstvideo':
  1107. video_formats = [
  1108. f for f in formats
  1109. if f.get('acodec') == 'none']
  1110. if video_formats:
  1111. yield video_formats[0]
  1112. else:
  1113. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1114. if format_spec in extensions:
  1115. filter_f = lambda f: f['ext'] == format_spec
  1116. else:
  1117. filter_f = lambda f: f['format_id'] == format_spec
  1118. matches = list(filter(filter_f, formats))
  1119. if matches:
  1120. yield matches[-1]
  1121. elif selector.type == MERGE:
  1122. def _merge(formats_info):
  1123. format_1, format_2 = [f['format_id'] for f in formats_info]
  1124. # The first format must contain the video and the
  1125. # second the audio
  1126. if formats_info[0].get('vcodec') == 'none':
  1127. self.report_error('The first format must '
  1128. 'contain the video, try using '
  1129. '"-f %s+%s"' % (format_2, format_1))
  1130. return
  1131. # Formats must be opposite (video+audio)
  1132. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1133. self.report_error(
  1134. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1135. % (format_1, format_2))
  1136. return
  1137. output_ext = (
  1138. formats_info[0]['ext']
  1139. if self.params.get('merge_output_format') is None
  1140. else self.params['merge_output_format'])
  1141. return {
  1142. 'requested_formats': formats_info,
  1143. 'format': '%s+%s' % (formats_info[0].get('format'),
  1144. formats_info[1].get('format')),
  1145. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1146. formats_info[1].get('format_id')),
  1147. 'width': formats_info[0].get('width'),
  1148. 'height': formats_info[0].get('height'),
  1149. 'resolution': formats_info[0].get('resolution'),
  1150. 'fps': formats_info[0].get('fps'),
  1151. 'vcodec': formats_info[0].get('vcodec'),
  1152. 'vbr': formats_info[0].get('vbr'),
  1153. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1154. 'acodec': formats_info[1].get('acodec'),
  1155. 'abr': formats_info[1].get('abr'),
  1156. 'ext': output_ext,
  1157. }
  1158. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1159. def selector_function(ctx):
  1160. for pair in itertools.product(
  1161. video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
  1162. yield _merge(pair)
  1163. filters = [self._build_format_filter(f) for f in selector.filters]
  1164. def final_selector(ctx):
  1165. ctx_copy = copy.deepcopy(ctx)
  1166. for _filter in filters:
  1167. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  1168. return selector_function(ctx_copy)
  1169. return final_selector
  1170. stream = io.BytesIO(format_spec.encode('utf-8'))
  1171. try:
  1172. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1173. except tokenize.TokenError:
  1174. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1175. class TokenIterator(object):
  1176. def __init__(self, tokens):
  1177. self.tokens = tokens
  1178. self.counter = 0
  1179. def __iter__(self):
  1180. return self
  1181. def __next__(self):
  1182. if self.counter >= len(self.tokens):
  1183. raise StopIteration()
  1184. value = self.tokens[self.counter]
  1185. self.counter += 1
  1186. return value
  1187. next = __next__
  1188. def restore_last_token(self):
  1189. self.counter -= 1
  1190. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1191. return _build_selector_function(parsed_selector)
  1192. def _calc_headers(self, info_dict):
  1193. res = std_headers.copy()
  1194. add_headers = info_dict.get('http_headers')
  1195. if add_headers:
  1196. res.update(add_headers)
  1197. cookies = self._calc_cookies(info_dict)
  1198. if cookies:
  1199. res['Cookie'] = cookies
  1200. if 'X-Forwarded-For' not in res:
  1201. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  1202. if x_forwarded_for_ip:
  1203. res['X-Forwarded-For'] = x_forwarded_for_ip
  1204. return res
  1205. def _calc_cookies(self, info_dict):
  1206. pr = sanitized_Request(info_dict['url'])
  1207. self.cookiejar.add_cookie_header(pr)
  1208. return pr.get_header('Cookie')
  1209. def process_video_result(self, info_dict, download=True):
  1210. assert info_dict.get('_type', 'video') == 'video'
  1211. if 'id' not in info_dict:
  1212. raise ExtractorError('Missing "id" field in extractor result')
  1213. if 'title' not in info_dict:
  1214. raise ExtractorError('Missing "title" field in extractor result')
  1215. if not isinstance(info_dict['id'], compat_str):
  1216. self.report_warning('"id" field is not a string - forcing string conversion')
  1217. info_dict['id'] = compat_str(info_dict['id'])
  1218. if 'playlist' not in info_dict:
  1219. # It isn't part of a playlist
  1220. info_dict['playlist'] = None
  1221. info_dict['playlist_index'] = None
  1222. thumbnails = info_dict.get('thumbnails')
  1223. if thumbnails is None:
  1224. thumbnail = info_dict.get('thumbnail')
  1225. if thumbnail:
  1226. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1227. if thumbnails:
  1228. thumbnails.sort(key=lambda t: (
  1229. t.get('preference') if t.get('preference') is not None else -1,
  1230. t.get('width') if t.get('width') is not None else -1,
  1231. t.get('height') if t.get('height') is not None else -1,
  1232. t.get('id') if t.get('id') is not None else '', t.get('url')))
  1233. for i, t in enumerate(thumbnails):
  1234. t['url'] = sanitize_url(t['url'])
  1235. if t.get('width') and t.get('height'):
  1236. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1237. if t.get('id') is None:
  1238. t['id'] = '%d' % i
  1239. if self.params.get('list_thumbnails'):
  1240. self.list_thumbnails(info_dict)
  1241. return
  1242. thumbnail = info_dict.get('thumbnail')
  1243. if thumbnail:
  1244. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1245. elif thumbnails:
  1246. info_dict['thumbnail'] = thumbnails[-1]['url']
  1247. if 'display_id' not in info_dict and 'id' in info_dict:
  1248. info_dict['display_id'] = info_dict['id']
  1249. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  1250. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1251. # see http://bugs.python.org/issue1646728)
  1252. try:
  1253. upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
  1254. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  1255. except (ValueError, OverflowError, OSError):
  1256. pass
  1257. # Auto generate title fields corresponding to the *_number fields when missing
  1258. # in order to always have clean titles. This is very common for TV series.
  1259. for field in ('chapter', 'season', 'episode'):
  1260. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1261. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1262. subtitles = info_dict.get('subtitles')
  1263. if subtitles:
  1264. for _, subtitle in subtitles.items():
  1265. for subtitle_format in subtitle:
  1266. if subtitle_format.get('url'):
  1267. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1268. if subtitle_format.get('ext') is None:
  1269. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1270. if self.params.get('listsubtitles', False):
  1271. if 'automatic_captions' in info_dict:
  1272. self.list_subtitles(info_dict['id'], info_dict.get('automatic_captions'), 'automatic captions')
  1273. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1274. return
  1275. info_dict['requested_subtitles'] = self.process_subtitles(
  1276. info_dict['id'], subtitles,
  1277. info_dict.get('automatic_captions'))
  1278. # We now pick which formats have to be downloaded
  1279. if info_dict.get('formats') is None:
  1280. # There's only one format available
  1281. formats = [info_dict]
  1282. else:
  1283. formats = info_dict['formats']
  1284. if not formats:
  1285. raise ExtractorError('No video formats found!')
  1286. formats_dict = {}
  1287. # We check that all the formats have the format and format_id fields
  1288. for i, format in enumerate(formats):
  1289. if 'url' not in format:
  1290. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  1291. format['url'] = sanitize_url(format['url'])
  1292. if format.get('format_id') is None:
  1293. format['format_id'] = compat_str(i)
  1294. else:
  1295. # Sanitize format_id from characters used in format selector expression
  1296. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  1297. format_id = format['format_id']
  1298. if format_id not in formats_dict:
  1299. formats_dict[format_id] = []
  1300. formats_dict[format_id].append(format)
  1301. # Make sure all formats have unique format_id
  1302. for format_id, ambiguous_formats in formats_dict.items():
  1303. if len(ambiguous_formats) > 1:
  1304. for i, format in enumerate(ambiguous_formats):
  1305. format['format_id'] = '%s-%d' % (format_id, i)
  1306. for i, format in enumerate(formats):
  1307. if format.get('format') is None:
  1308. format['format'] = '{id} - {res}{note}'.format(
  1309. id=format['format_id'],
  1310. res=self.format_resolution(format),
  1311. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1312. )
  1313. # Automatically determine file extension if missing
  1314. if format.get('ext') is None:
  1315. format['ext'] = determine_ext(format['url']).lower()
  1316. # Automatically determine protocol if missing (useful for format
  1317. # selection purposes)
  1318. if format.get('protocol') is None:
  1319. format['protocol'] = determine_protocol(format)
  1320. # Add HTTP headers, so that external programs can use them from the
  1321. # json output
  1322. full_format_info = info_dict.copy()
  1323. full_format_info.update(format)
  1324. format['http_headers'] = self._calc_headers(full_format_info)
  1325. # Remove private housekeeping stuff
  1326. if '__x_forwarded_for_ip' in info_dict:
  1327. del info_dict['__x_forwarded_for_ip']
  1328. # TODO Central sorting goes here
  1329. if formats[0] is not info_dict:
  1330. # only set the 'formats' fields if the original info_dict list them
  1331. # otherwise we end up with a circular reference, the first (and unique)
  1332. # element in the 'formats' field in info_dict is info_dict itself,
  1333. # which can't be exported to json
  1334. info_dict['formats'] = formats
  1335. if self.params.get('listformats'):
  1336. self.list_formats(info_dict)
  1337. return
  1338. req_format = self.params.get('format')
  1339. if req_format is None:
  1340. req_format_list = []
  1341. if (self.params.get('outtmpl', DEFAULT_OUTTMPL) != '-' and
  1342. not info_dict.get('is_live')):
  1343. merger = FFmpegMergerPP(self)
  1344. if merger.available and merger.can_merge():
  1345. req_format_list.append('bestvideo+bestaudio')
  1346. req_format_list.append('best')
  1347. req_format = '/'.join(req_format_list)
  1348. format_selector = self.build_format_selector(req_format)
  1349. # While in format selection we may need to have an access to the original
  1350. # format set in order to calculate some metrics or do some processing.
  1351. # For now we need to be able to guess whether original formats provided
  1352. # by extractor are incomplete or not (i.e. whether extractor provides only
  1353. # video-only or audio-only formats) for proper formats selection for
  1354. # extractors with such incomplete formats (see
  1355. # https://github.com/rg3/youtube-dl/pull/5556).
  1356. # Since formats may be filtered during format selection and may not match
  1357. # the original formats the results may be incorrect. Thus original formats
  1358. # or pre-calculated metrics should be passed to format selection routines
  1359. # as well.
  1360. # We will pass a context object containing all necessary additional data
  1361. # instead of just formats.
  1362. # This fixes incorrect format selection issue (see
  1363. # https://github.com/rg3/youtube-dl/issues/10083).
  1364. incomplete_formats = (
  1365. # All formats are video-only or
  1366. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats) or
  1367. # all formats are audio-only
  1368. all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
  1369. ctx = {
  1370. 'formats': formats,
  1371. 'incomplete_formats': incomplete_formats,
  1372. }
  1373. formats_to_download = list(format_selector(ctx))
  1374. if not formats_to_download:
  1375. raise ExtractorError('requested format not available',
  1376. expected=True)
  1377. if download:
  1378. if len(formats_to_download) > 1:
  1379. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1380. for format in formats_to_download:
  1381. new_info = dict(info_dict)
  1382. new_info.update(format)
  1383. self.process_info(new_info)
  1384. # We update the info dict with the best quality format (backwards compatibility)
  1385. info_dict.update(formats_to_download[-1])
  1386. return info_dict
  1387. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1388. """Select the requested subtitles and their format"""
  1389. available_subs = {}
  1390. if normal_subtitles and self.params.get('writesubtitles'):
  1391. available_subs.update(normal_subtitles)
  1392. if automatic_captions and self.params.get('writeautomaticsub'):
  1393. for lang, cap_info in automatic_captions.items():
  1394. if lang not in available_subs:
  1395. available_subs[lang] = cap_info
  1396. if (not self.params.get('writesubtitles') and not
  1397. self.params.get('writeautomaticsub') or not
  1398. available_subs):
  1399. return None
  1400. if self.params.get('allsubtitles', False):
  1401. requested_langs = available_subs.keys()
  1402. else:
  1403. if self.params.get('subtitleslangs', False):
  1404. requested_langs = self.params.get('subtitleslangs')
  1405. elif 'en' in available_subs:
  1406. requested_langs = ['en']
  1407. else:
  1408. requested_langs = [list(available_subs.keys())[0]]
  1409. formats_query = self.params.get('subtitlesformat', 'best')
  1410. formats_preference = formats_query.split('/') if formats_query else []
  1411. subs = {}
  1412. for lang in requested_langs:
  1413. formats = available_subs.get(lang)
  1414. if formats is None:
  1415. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1416. continue
  1417. for ext in formats_preference:
  1418. if ext == 'best':
  1419. f = formats[-1]
  1420. break
  1421. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1422. if matches:
  1423. f = matches[-1]
  1424. break
  1425. else:
  1426. f = formats[-1]
  1427. self.report_warning(
  1428. 'No subtitle format found matching "%s" for language %s, '
  1429. 'using %s' % (formats_query, lang, f['ext']))
  1430. subs[lang] = f
  1431. return subs
  1432. def process_info(self, info_dict):
  1433. """Process a single resolved IE result."""
  1434. assert info_dict.get('_type', 'video') == 'video'
  1435. max_downloads = self.params.get('max_downloads')
  1436. if max_downloads is not None:
  1437. if self._num_downloads >= int(max_downloads):
  1438. raise MaxDownloadsReached()
  1439. info_dict['fulltitle'] = info_dict['title']
  1440. if len(info_dict['title']) > 200:
  1441. info_dict['title'] = info_dict['title'][:197] + '...'
  1442. if 'format' not in info_dict:
  1443. info_dict['format'] = info_dict['ext']
  1444. reason = self._match_entry(info_dict, incomplete=False)
  1445. if reason is not None:
  1446. self.to_screen('[download] ' + reason)
  1447. return
  1448. self._num_downloads += 1
  1449. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1450. # Forced printings
  1451. if self.params.get('forcetitle', False):
  1452. self.to_stdout(info_dict['fulltitle'])
  1453. if self.params.get('forceid', False):
  1454. self.to_stdout(info_dict['id'])
  1455. if self.params.get('forceurl', False):
  1456. if info_dict.get('requested_formats') is not None:
  1457. for f in info_dict['requested_formats']:
  1458. self.to_stdout(f['url'] + f.get('play_path', ''))
  1459. else:
  1460. # For RTMP URLs, also include the playpath
  1461. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1462. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1463. self.to_stdout(info_dict['thumbnail'])
  1464. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1465. self.to_stdout(info_dict['description'])
  1466. if self.params.get('forcefilename', False) and filename is not None:
  1467. self.to_stdout(filename)
  1468. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1469. self.to_stdout(formatSeconds(info_dict['duration']))
  1470. if self.params.get('forceformat', False):
  1471. self.to_stdout(info_dict['format'])
  1472. if self.params.get('forcejson', False):
  1473. self.to_stdout(json.dumps(info_dict))
  1474. # Do nothing else if in simulate mode
  1475. if self.params.get('simulate', False):
  1476. return
  1477. if filename is None:
  1478. return
  1479. try:
  1480. dn = os.path.dirname(sanitize_path(encodeFilename(filename)))
  1481. if dn and not os.path.exists(dn):
  1482. os.makedirs(dn)
  1483. except (OSError, IOError) as err:
  1484. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1485. return
  1486. if self.params.get('writedescription', False):
  1487. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1488. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1489. self.to_screen('[info] Video description is already present')
  1490. elif info_dict.get('description') is None:
  1491. self.report_warning('There\'s no description to write.')
  1492. else:
  1493. try:
  1494. self.to_screen('[info] Writing video description to: ' + descfn)
  1495. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1496. descfile.write(info_dict['description'])
  1497. except (OSError, IOError):
  1498. self.report_error('Cannot write description file ' + descfn)
  1499. return
  1500. if self.params.get('writeannotations', False):
  1501. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1502. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1503. self.to_screen('[info] Video annotations are already present')
  1504. else:
  1505. try:
  1506. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1507. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1508. annofile.write(info_dict['annotations'])
  1509. except (KeyError, TypeError):
  1510. self.report_warning('There are no annotations to write.')
  1511. except (OSError, IOError):
  1512. self.report_error('Cannot write annotations file: ' + annofn)
  1513. return
  1514. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1515. self.params.get('writeautomaticsub')])
  1516. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1517. # subtitles download errors are already managed as troubles in relevant IE
  1518. # that way it will silently go on when used with unsupporting IE
  1519. subtitles = info_dict['requested_subtitles']
  1520. ie = self.get_info_extractor(info_dict['extractor_key'])
  1521. for sub_lang, sub_info in subtitles.items():
  1522. sub_format = sub_info['ext']
  1523. if sub_info.get('data') is not None:
  1524. sub_data = sub_info['data']
  1525. else:
  1526. try:
  1527. sub_data = ie._download_webpage(
  1528. sub_info['url'], info_dict['id'], note=False)
  1529. except ExtractorError as err:
  1530. self.report_warning('Unable to download subtitle for "%s": %s' %
  1531. (sub_lang, error_to_compat_str(err.cause)))
  1532. continue
  1533. try:
  1534. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1535. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1536. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1537. else:
  1538. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1539. # Use newline='' to prevent conversion of newline characters
  1540. # See https://github.com/rg3/youtube-dl/issues/10268
  1541. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
  1542. subfile.write(sub_data)
  1543. except (OSError, IOError):
  1544. self.report_error('Cannot write subtitles file ' + sub_filename)
  1545. return
  1546. if self.params.get('writeinfojson', False):
  1547. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1548. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1549. self.to_screen('[info] Video description metadata is already present')
  1550. else:
  1551. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1552. try:
  1553. write_json_file(self.filter_requested_info(info_dict), infofn)
  1554. except (OSError, IOError):
  1555. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1556. return
  1557. self._write_thumbnails(info_dict, filename)
  1558. if not self.params.get('skip_download', False):
  1559. try:
  1560. def dl(name, info):
  1561. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1562. for ph in self._progress_hooks:
  1563. fd.add_progress_hook(ph)
  1564. if self.params.get('verbose'):
  1565. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1566. return fd.download(name, info)
  1567. if info_dict.get('requested_formats') is not None:
  1568. downloaded = []
  1569. success = True
  1570. merger = FFmpegMergerPP(self)
  1571. if not merger.available:
  1572. postprocessors = []
  1573. self.report_warning('You have requested multiple '
  1574. 'formats but ffmpeg or avconv are not installed.'
  1575. ' The formats won\'t be merged.')
  1576. else:
  1577. postprocessors = [merger]
  1578. def compatible_formats(formats):
  1579. video, audio = formats
  1580. # Check extension
  1581. video_ext, audio_ext = audio.get('ext'), video.get('ext')
  1582. if video_ext and audio_ext:
  1583. COMPATIBLE_EXTS = (
  1584. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
  1585. ('webm')
  1586. )
  1587. for exts in COMPATIBLE_EXTS:
  1588. if video_ext in exts and audio_ext in exts:
  1589. return True
  1590. # TODO: Check acodec/vcodec
  1591. return False
  1592. filename_real_ext = os.path.splitext(filename)[1][1:]
  1593. filename_wo_ext = (
  1594. os.path.splitext(filename)[0]
  1595. if filename_real_ext == info_dict['ext']
  1596. else filename)
  1597. requested_formats = info_dict['requested_formats']
  1598. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1599. info_dict['ext'] = 'mkv'
  1600. self.report_warning(
  1601. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1602. # Ensure filename always has a correct extension for successful merge
  1603. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1604. if os.path.exists(encodeFilename(filename)):
  1605. self.to_screen(
  1606. '[download] %s has already been downloaded and '
  1607. 'merged' % filename)
  1608. else:
  1609. for f in requested_formats:
  1610. new_info = dict(info_dict)
  1611. new_info.update(f)
  1612. fname = self.prepare_filename(new_info)
  1613. fname = prepend_extension(fname, 'f%s' % f['format_id'], new_info['ext'])
  1614. downloaded.append(fname)
  1615. partial_success = dl(fname, new_info)
  1616. success = success and partial_success
  1617. info_dict['__postprocessors'] = postprocessors
  1618. info_dict['__files_to_merge'] = downloaded
  1619. else:
  1620. # Just a single file
  1621. success = dl(filename, info_dict)
  1622. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1623. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1624. return
  1625. except (OSError, IOError) as err:
  1626. raise UnavailableVideoError(err)
  1627. except (ContentTooShortError, ) as err:
  1628. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1629. return
  1630. if success and filename != '-':
  1631. # Fixup content
  1632. fixup_policy = self.params.get('fixup')
  1633. if fixup_policy is None:
  1634. fixup_policy = 'detect_or_warn'
  1635. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1636. stretched_ratio = info_dict.get('stretched_ratio')
  1637. if stretched_ratio is not None and stretched_ratio != 1:
  1638. if fixup_policy == 'warn':
  1639. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1640. info_dict['id'], stretched_ratio))
  1641. elif fixup_policy == 'detect_or_warn':
  1642. stretched_pp = FFmpegFixupStretchedPP(self)
  1643. if stretched_pp.available:
  1644. info_dict.setdefault('__postprocessors', [])
  1645. info_dict['__postprocessors'].append(stretched_pp)
  1646. else:
  1647. self.report_warning(
  1648. '%s: Non-uniform pixel ratio (%s). %s'
  1649. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1650. else:
  1651. assert fixup_policy in ('ignore', 'never')
  1652. if (info_dict.get('requested_formats') is None and
  1653. info_dict.get('container') == 'm4a_dash'):
  1654. if fixup_policy == 'warn':
  1655. self.report_warning(
  1656. '%s: writing DASH m4a. '
  1657. 'Only some players support this container.'
  1658. % info_dict['id'])
  1659. elif fixup_policy == 'detect_or_warn':
  1660. fixup_pp = FFmpegFixupM4aPP(self)
  1661. if fixup_pp.available:
  1662. info_dict.setdefault('__postprocessors', [])
  1663. info_dict['__postprocessors'].append(fixup_pp)
  1664. else:
  1665. self.report_warning(
  1666. '%s: writing DASH m4a. '
  1667. 'Only some players support this container. %s'
  1668. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1669. else:
  1670. assert fixup_policy in ('ignore', 'never')
  1671. if (info_dict.get('protocol') == 'm3u8_native' or
  1672. info_dict.get('protocol') == 'm3u8' and
  1673. self.params.get('hls_prefer_native')):
  1674. if fixup_policy == 'warn':
  1675. self.report_warning('%s: malformated aac bitstream.' % (
  1676. info_dict['id']))
  1677. elif fixup_policy == 'detect_or_warn':
  1678. fixup_pp = FFmpegFixupM3u8PP(self)
  1679. if fixup_pp.available:
  1680. info_dict.setdefault('__postprocessors', [])
  1681. info_dict['__postprocessors'].append(fixup_pp)
  1682. else:
  1683. self.report_warning(
  1684. '%s: malformated aac bitstream. %s'
  1685. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1686. else:
  1687. assert fixup_policy in ('ignore', 'never')
  1688. try:
  1689. self.post_process(filename, info_dict)
  1690. except (PostProcessingError) as err:
  1691. self.report_error('postprocessing: %s' % str(err))
  1692. return
  1693. self.record_download_archive(info_dict)
  1694. def download(self, url_list):
  1695. """Download a given list of URLs."""
  1696. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1697. if (len(url_list) > 1 and
  1698. outtmpl != '-' and
  1699. '%' not in outtmpl and
  1700. self.params.get('max_downloads') != 1):
  1701. raise SameFileError(outtmpl)
  1702. for url in url_list:
  1703. try:
  1704. # It also downloads the videos
  1705. res = self.extract_info(
  1706. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1707. except UnavailableVideoError:
  1708. self.report_error('unable to download video')
  1709. except MaxDownloadsReached:
  1710. self.to_screen('[info] Maximum number of downloaded files reached.')
  1711. raise
  1712. else:
  1713. if self.params.get('dump_single_json', False):
  1714. self.to_stdout(json.dumps(res))
  1715. return self._download_retcode
  1716. def download_with_info_file(self, info_filename):
  1717. with contextlib.closing(fileinput.FileInput(
  1718. [info_filename], mode='r',
  1719. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1720. # FileInput doesn't have a read method, we can't call json.load
  1721. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1722. try:
  1723. self.process_ie_result(info, download=True)
  1724. except DownloadError:
  1725. webpage_url = info.get('webpage_url')
  1726. if webpage_url is not None:
  1727. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1728. return self.download([webpage_url])
  1729. else:
  1730. raise
  1731. return self._download_retcode
  1732. @staticmethod
  1733. def filter_requested_info(info_dict):
  1734. return dict(
  1735. (k, v) for k, v in info_dict.items()
  1736. if k not in ['requested_formats', 'requested_subtitles'])
  1737. def post_process(self, filename, ie_info):
  1738. """Run all the postprocessors on the given file."""
  1739. info = dict(ie_info)
  1740. info['filepath'] = filename
  1741. pps_chain = []
  1742. if ie_info.get('__postprocessors') is not None:
  1743. pps_chain.extend(ie_info['__postprocessors'])
  1744. pps_chain.extend(self._pps)
  1745. for pp in pps_chain:
  1746. files_to_delete = []
  1747. try:
  1748. files_to_delete, info = pp.run(info)
  1749. except PostProcessingError as e:
  1750. self.report_error(e.msg)
  1751. if files_to_delete and not self.params.get('keepvideo', False):
  1752. for old_filename in files_to_delete:
  1753. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1754. try:
  1755. os.remove(encodeFilename(old_filename))
  1756. except (IOError, OSError):
  1757. self.report_warning('Unable to remove downloaded original file')
  1758. def _make_archive_id(self, info_dict):
  1759. # Future-proof against any change in case
  1760. # and backwards compatibility with prior versions
  1761. extractor = info_dict.get('extractor_key')
  1762. if extractor is None:
  1763. if 'id' in info_dict:
  1764. extractor = info_dict.get('ie_key') # key in a playlist
  1765. if extractor is None:
  1766. return None # Incomplete video information
  1767. return extractor.lower() + ' ' + info_dict['id']
  1768. def in_download_archive(self, info_dict):
  1769. fn = self.params.get('download_archive')
  1770. if fn is None:
  1771. return False
  1772. vid_id = self._make_archive_id(info_dict)
  1773. if vid_id is None:
  1774. return False # Incomplete video information
  1775. try:
  1776. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1777. for line in archive_file:
  1778. if line.strip() == vid_id:
  1779. return True
  1780. except IOError as ioe:
  1781. if ioe.errno != errno.ENOENT:
  1782. raise
  1783. return False
  1784. def record_download_archive(self, info_dict):
  1785. fn = self.params.get('download_archive')
  1786. if fn is None:
  1787. return
  1788. vid_id = self._make_archive_id(info_dict)
  1789. assert vid_id
  1790. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1791. archive_file.write(vid_id + '\n')
  1792. @staticmethod
  1793. def format_resolution(format, default='unknown'):
  1794. if format.get('vcodec') == 'none':
  1795. return 'audio only'
  1796. if format.get('resolution') is not None:
  1797. return format['resolution']
  1798. if format.get('height') is not None:
  1799. if format.get('width') is not None:
  1800. res = '%sx%s' % (format['width'], format['height'])
  1801. else:
  1802. res = '%sp' % format['height']
  1803. elif format.get('width') is not None:
  1804. res = '%dx?' % format['width']
  1805. else:
  1806. res = default
  1807. return res
  1808. def _format_note(self, fdict):
  1809. res = ''
  1810. if fdict.get('ext') in ['f4f', 'f4m']:
  1811. res += '(unsupported) '
  1812. if fdict.get('language'):
  1813. if res:
  1814. res += ' '
  1815. res += '[%s] ' % fdict['language']
  1816. if fdict.get('format_note') is not None:
  1817. res += fdict['format_note'] + ' '
  1818. if fdict.get('tbr') is not None:
  1819. res += '%4dk ' % fdict['tbr']
  1820. if fdict.get('container') is not None:
  1821. if res:
  1822. res += ', '
  1823. res += '%s container' % fdict['container']
  1824. if (fdict.get('vcodec') is not None and
  1825. fdict.get('vcodec') != 'none'):
  1826. if res:
  1827. res += ', '
  1828. res += fdict['vcodec']
  1829. if fdict.get('vbr') is not None:
  1830. res += '@'
  1831. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1832. res += 'video@'
  1833. if fdict.get('vbr') is not None:
  1834. res += '%4dk' % fdict['vbr']
  1835. if fdict.get('fps') is not None:
  1836. if res:
  1837. res += ', '
  1838. res += '%sfps' % fdict['fps']
  1839. if fdict.get('acodec') is not None:
  1840. if res:
  1841. res += ', '
  1842. if fdict['acodec'] == 'none':
  1843. res += 'video only'
  1844. else:
  1845. res += '%-5s' % fdict['acodec']
  1846. elif fdict.get('abr') is not None:
  1847. if res:
  1848. res += ', '
  1849. res += 'audio'
  1850. if fdict.get('abr') is not None:
  1851. res += '@%3dk' % fdict['abr']
  1852. if fdict.get('asr') is not None:
  1853. res += ' (%5dHz)' % fdict['asr']
  1854. if fdict.get('filesize') is not None:
  1855. if res:
  1856. res += ', '
  1857. res += format_bytes(fdict['filesize'])
  1858. elif fdict.get('filesize_approx') is not None:
  1859. if res:
  1860. res += ', '
  1861. res += '~' + format_bytes(fdict['filesize_approx'])
  1862. return res
  1863. def list_formats(self, info_dict):
  1864. formats = info_dict.get('formats', [info_dict])
  1865. table = [
  1866. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1867. for f in formats
  1868. if f.get('preference') is None or f['preference'] >= -1000]
  1869. if len(formats) > 1:
  1870. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1871. header_line = ['format code', 'extension', 'resolution', 'note']
  1872. self.to_screen(
  1873. '[info] Available formats for %s:\n%s' %
  1874. (info_dict['id'], render_table(header_line, table)))
  1875. def list_thumbnails(self, info_dict):
  1876. thumbnails = info_dict.get('thumbnails')
  1877. if not thumbnails:
  1878. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  1879. return
  1880. self.to_screen(
  1881. '[info] Thumbnails for %s:' % info_dict['id'])
  1882. self.to_screen(render_table(
  1883. ['ID', 'width', 'height', 'URL'],
  1884. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1885. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1886. if not subtitles:
  1887. self.to_screen('%s has no %s' % (video_id, name))
  1888. return
  1889. self.to_screen(
  1890. 'Available %s for %s:' % (name, video_id))
  1891. self.to_screen(render_table(
  1892. ['Language', 'formats'],
  1893. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  1894. for lang, formats in subtitles.items()]))
  1895. def urlopen(self, req):
  1896. """ Start an HTTP download """
  1897. if isinstance(req, compat_basestring):
  1898. req = sanitized_Request(req)
  1899. return self._opener.open(req, timeout=self._socket_timeout)
  1900. def print_debug_header(self):
  1901. if not self.params.get('verbose'):
  1902. return
  1903. if type('') is not compat_str:
  1904. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1905. self.report_warning(
  1906. 'Your Python is broken! Update to a newer and supported version')
  1907. stdout_encoding = getattr(
  1908. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1909. encoding_str = (
  1910. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1911. locale.getpreferredencoding(),
  1912. sys.getfilesystemencoding(),
  1913. stdout_encoding,
  1914. self.get_encoding()))
  1915. write_string(encoding_str, encoding=None)
  1916. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1917. if _LAZY_LOADER:
  1918. self._write_string('[debug] Lazy loading extractors enabled' + '\n')
  1919. try:
  1920. sp = subprocess.Popen(
  1921. ['git', 'rev-parse', '--short', 'HEAD'],
  1922. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1923. cwd=os.path.dirname(os.path.abspath(__file__)))
  1924. out, err = sp.communicate()
  1925. out = out.decode().strip()
  1926. if re.match('[0-9a-f]+', out):
  1927. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1928. except Exception:
  1929. try:
  1930. sys.exc_clear()
  1931. except Exception:
  1932. pass
  1933. self._write_string('[debug] Python version %s - %s\n' % (
  1934. platform.python_version(), platform_name()))
  1935. exe_versions = FFmpegPostProcessor.get_versions(self)
  1936. exe_versions['rtmpdump'] = rtmpdump_version()
  1937. exe_str = ', '.join(
  1938. '%s %s' % (exe, v)
  1939. for exe, v in sorted(exe_versions.items())
  1940. if v
  1941. )
  1942. if not exe_str:
  1943. exe_str = 'none'
  1944. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1945. proxy_map = {}
  1946. for handler in self._opener.handlers:
  1947. if hasattr(handler, 'proxies'):
  1948. proxy_map.update(handler.proxies)
  1949. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1950. if self.params.get('call_home', False):
  1951. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1952. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1953. latest_version = self.urlopen(
  1954. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1955. if version_tuple(latest_version) > version_tuple(__version__):
  1956. self.report_warning(
  1957. 'You are using an outdated version (newest version: %s)! '
  1958. 'See https://yt-dl.org/update if you need help updating.' %
  1959. latest_version)
  1960. def _setup_opener(self):
  1961. timeout_val = self.params.get('socket_timeout')
  1962. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1963. opts_cookiefile = self.params.get('cookiefile')
  1964. opts_proxy = self.params.get('proxy')
  1965. if opts_cookiefile is None:
  1966. self.cookiejar = compat_cookiejar.CookieJar()
  1967. else:
  1968. opts_cookiefile = expand_path(opts_cookiefile)
  1969. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1970. opts_cookiefile)
  1971. if os.access(opts_cookiefile, os.R_OK):
  1972. self.cookiejar.load()
  1973. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  1974. if opts_proxy is not None:
  1975. if opts_proxy == '':
  1976. proxies = {}
  1977. else:
  1978. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1979. else:
  1980. proxies = compat_urllib_request.getproxies()
  1981. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1982. if 'http' in proxies and 'https' not in proxies:
  1983. proxies['https'] = proxies['http']
  1984. proxy_handler = PerRequestProxyHandler(proxies)
  1985. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1986. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1987. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1988. data_handler = compat_urllib_request_DataHandler()
  1989. # When passing our own FileHandler instance, build_opener won't add the
  1990. # default FileHandler and allows us to disable the file protocol, which
  1991. # can be used for malicious purposes (see
  1992. # https://github.com/rg3/youtube-dl/issues/8227)
  1993. file_handler = compat_urllib_request.FileHandler()
  1994. def file_open(*args, **kwargs):
  1995. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  1996. file_handler.file_open = file_open
  1997. opener = compat_urllib_request.build_opener(
  1998. proxy_handler, https_handler, cookie_processor, ydlh, data_handler, file_handler)
  1999. # Delete the default user-agent header, which would otherwise apply in
  2000. # cases where our custom HTTP handler doesn't come into play
  2001. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  2002. opener.addheaders = []
  2003. self._opener = opener
  2004. def encode(self, s):
  2005. if isinstance(s, bytes):
  2006. return s # Already encoded
  2007. try:
  2008. return s.encode(self.get_encoding())
  2009. except UnicodeEncodeError as err:
  2010. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  2011. raise
  2012. def get_encoding(self):
  2013. encoding = self.params.get('encoding')
  2014. if encoding is None:
  2015. encoding = preferredencoding()
  2016. return encoding
  2017. def _write_thumbnails(self, info_dict, filename):
  2018. if self.params.get('writethumbnail', False):
  2019. thumbnails = info_dict.get('thumbnails')
  2020. if thumbnails:
  2021. thumbnails = [thumbnails[-1]]
  2022. elif self.params.get('write_all_thumbnails', False):
  2023. thumbnails = info_dict.get('thumbnails')
  2024. else:
  2025. return
  2026. if not thumbnails:
  2027. # No thumbnails present, so return immediately
  2028. return
  2029. for t in thumbnails:
  2030. thumb_ext = determine_ext(t['url'], 'jpg')
  2031. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  2032. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  2033. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  2034. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  2035. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  2036. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2037. else:
  2038. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  2039. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2040. try:
  2041. uf = self.urlopen(t['url'])
  2042. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  2043. shutil.copyfileobj(uf, thumbf)
  2044. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  2045. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  2046. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2047. self.report_warning('Unable to download thumbnail "%s": %s' %
  2048. (t['url'], error_to_compat_str(err)))