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.

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