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.

2278 lines
103 KiB

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