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.

2170 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') if t.get('preference') is not None else -1,
  1142. t.get('width') if t.get('width') is not None else -1,
  1143. t.get('height') if t.get('height') is not None else -1,
  1144. t.get('id') if t.get('id') is not None else '', t.get('url')))
  1145. for i, t in enumerate(thumbnails):
  1146. t['url'] = sanitize_url(t['url'])
  1147. if t.get('width') and t.get('height'):
  1148. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1149. if t.get('id') is None:
  1150. t['id'] = '%d' % i
  1151. if self.params.get('list_thumbnails'):
  1152. self.list_thumbnails(info_dict)
  1153. return
  1154. thumbnail = info_dict.get('thumbnail')
  1155. if thumbnail:
  1156. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1157. elif thumbnails:
  1158. info_dict['thumbnail'] = thumbnails[-1]['url']
  1159. if 'display_id' not in info_dict and 'id' in info_dict:
  1160. info_dict['display_id'] = info_dict['id']
  1161. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  1162. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1163. # see http://bugs.python.org/issue1646728)
  1164. try:
  1165. upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
  1166. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  1167. except (ValueError, OverflowError, OSError):
  1168. pass
  1169. # Auto generate title fields corresponding to the *_number fields when missing
  1170. # in order to always have clean titles. This is very common for TV series.
  1171. for field in ('chapter', 'season', 'episode'):
  1172. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1173. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1174. subtitles = info_dict.get('subtitles')
  1175. if subtitles:
  1176. for _, subtitle in subtitles.items():
  1177. for subtitle_format in subtitle:
  1178. if subtitle_format.get('url'):
  1179. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1180. if subtitle_format.get('ext') is None:
  1181. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1182. if self.params.get('listsubtitles', False):
  1183. if 'automatic_captions' in info_dict:
  1184. self.list_subtitles(info_dict['id'], info_dict.get('automatic_captions'), 'automatic captions')
  1185. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1186. return
  1187. info_dict['requested_subtitles'] = self.process_subtitles(
  1188. info_dict['id'], subtitles,
  1189. info_dict.get('automatic_captions'))
  1190. # We now pick which formats have to be downloaded
  1191. if info_dict.get('formats') is None:
  1192. # There's only one format available
  1193. formats = [info_dict]
  1194. else:
  1195. formats = info_dict['formats']
  1196. if not formats:
  1197. raise ExtractorError('No video formats found!')
  1198. formats_dict = {}
  1199. # We check that all the formats have the format and format_id fields
  1200. for i, format in enumerate(formats):
  1201. if 'url' not in format:
  1202. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  1203. format['url'] = sanitize_url(format['url'])
  1204. if format.get('format_id') is None:
  1205. format['format_id'] = compat_str(i)
  1206. else:
  1207. # Sanitize format_id from characters used in format selector expression
  1208. format['format_id'] = re.sub('[\s,/+\[\]()]', '_', format['format_id'])
  1209. format_id = format['format_id']
  1210. if format_id not in formats_dict:
  1211. formats_dict[format_id] = []
  1212. formats_dict[format_id].append(format)
  1213. # Make sure all formats have unique format_id
  1214. for format_id, ambiguous_formats in formats_dict.items():
  1215. if len(ambiguous_formats) > 1:
  1216. for i, format in enumerate(ambiguous_formats):
  1217. format['format_id'] = '%s-%d' % (format_id, i)
  1218. for i, format in enumerate(formats):
  1219. if format.get('format') is None:
  1220. format['format'] = '{id} - {res}{note}'.format(
  1221. id=format['format_id'],
  1222. res=self.format_resolution(format),
  1223. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1224. )
  1225. # Automatically determine file extension if missing
  1226. if format.get('ext') is None:
  1227. format['ext'] = determine_ext(format['url']).lower()
  1228. # Automatically determine protocol if missing (useful for format
  1229. # selection purposes)
  1230. if 'protocol' not in format:
  1231. format['protocol'] = determine_protocol(format)
  1232. # Add HTTP headers, so that external programs can use them from the
  1233. # json output
  1234. full_format_info = info_dict.copy()
  1235. full_format_info.update(format)
  1236. format['http_headers'] = self._calc_headers(full_format_info)
  1237. # TODO Central sorting goes here
  1238. if formats[0] is not info_dict:
  1239. # only set the 'formats' fields if the original info_dict list them
  1240. # otherwise we end up with a circular reference, the first (and unique)
  1241. # element in the 'formats' field in info_dict is info_dict itself,
  1242. # which can't be exported to json
  1243. info_dict['formats'] = formats
  1244. if self.params.get('listformats'):
  1245. self.list_formats(info_dict)
  1246. return
  1247. req_format = self.params.get('format')
  1248. if req_format is None:
  1249. req_format_list = []
  1250. if (self.params.get('outtmpl', DEFAULT_OUTTMPL) != '-' and
  1251. not info_dict.get('is_live')):
  1252. merger = FFmpegMergerPP(self)
  1253. if merger.available and merger.can_merge():
  1254. req_format_list.append('bestvideo+bestaudio')
  1255. req_format_list.append('best')
  1256. req_format = '/'.join(req_format_list)
  1257. format_selector = self.build_format_selector(req_format)
  1258. # While in format selection we may need to have an access to the original
  1259. # format set in order to calculate some metrics or do some processing.
  1260. # For now we need to be able to guess whether original formats provided
  1261. # by extractor are incomplete or not (i.e. whether extractor provides only
  1262. # video-only or audio-only formats) for proper formats selection for
  1263. # extractors with such incomplete formats (see
  1264. # https://github.com/rg3/youtube-dl/pull/5556).
  1265. # Since formats may be filtered during format selection and may not match
  1266. # the original formats the results may be incorrect. Thus original formats
  1267. # or pre-calculated metrics should be passed to format selection routines
  1268. # as well.
  1269. # We will pass a context object containing all necessary additional data
  1270. # instead of just formats.
  1271. # This fixes incorrect format selection issue (see
  1272. # https://github.com/rg3/youtube-dl/issues/10083).
  1273. incomplete_formats = (
  1274. # All formats are video-only or
  1275. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats) or
  1276. # all formats are audio-only
  1277. all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
  1278. ctx = {
  1279. 'formats': formats,
  1280. 'incomplete_formats': incomplete_formats,
  1281. }
  1282. formats_to_download = list(format_selector(ctx))
  1283. if not formats_to_download:
  1284. raise ExtractorError('requested format not available',
  1285. expected=True)
  1286. if download:
  1287. if len(formats_to_download) > 1:
  1288. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1289. for format in formats_to_download:
  1290. new_info = dict(info_dict)
  1291. new_info.update(format)
  1292. self.process_info(new_info)
  1293. # We update the info dict with the best quality format (backwards compatibility)
  1294. info_dict.update(formats_to_download[-1])
  1295. return info_dict
  1296. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1297. """Select the requested subtitles and their format"""
  1298. available_subs = {}
  1299. if normal_subtitles and self.params.get('writesubtitles'):
  1300. available_subs.update(normal_subtitles)
  1301. if automatic_captions and self.params.get('writeautomaticsub'):
  1302. for lang, cap_info in automatic_captions.items():
  1303. if lang not in available_subs:
  1304. available_subs[lang] = cap_info
  1305. if (not self.params.get('writesubtitles') and not
  1306. self.params.get('writeautomaticsub') or not
  1307. available_subs):
  1308. return None
  1309. if self.params.get('allsubtitles', False):
  1310. requested_langs = available_subs.keys()
  1311. else:
  1312. if self.params.get('subtitleslangs', False):
  1313. requested_langs = self.params.get('subtitleslangs')
  1314. elif 'en' in available_subs:
  1315. requested_langs = ['en']
  1316. else:
  1317. requested_langs = [list(available_subs.keys())[0]]
  1318. formats_query = self.params.get('subtitlesformat', 'best')
  1319. formats_preference = formats_query.split('/') if formats_query else []
  1320. subs = {}
  1321. for lang in requested_langs:
  1322. formats = available_subs.get(lang)
  1323. if formats is None:
  1324. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1325. continue
  1326. for ext in formats_preference:
  1327. if ext == 'best':
  1328. f = formats[-1]
  1329. break
  1330. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1331. if matches:
  1332. f = matches[-1]
  1333. break
  1334. else:
  1335. f = formats[-1]
  1336. self.report_warning(
  1337. 'No subtitle format found matching "%s" for language %s, '
  1338. 'using %s' % (formats_query, lang, f['ext']))
  1339. subs[lang] = f
  1340. return subs
  1341. def process_info(self, info_dict):
  1342. """Process a single resolved IE result."""
  1343. assert info_dict.get('_type', 'video') == 'video'
  1344. max_downloads = self.params.get('max_downloads')
  1345. if max_downloads is not None:
  1346. if self._num_downloads >= int(max_downloads):
  1347. raise MaxDownloadsReached()
  1348. info_dict['fulltitle'] = info_dict['title']
  1349. if len(info_dict['title']) > 200:
  1350. info_dict['title'] = info_dict['title'][:197] + '...'
  1351. if 'format' not in info_dict:
  1352. info_dict['format'] = info_dict['ext']
  1353. reason = self._match_entry(info_dict, incomplete=False)
  1354. if reason is not None:
  1355. self.to_screen('[download] ' + reason)
  1356. return
  1357. self._num_downloads += 1
  1358. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1359. # Forced printings
  1360. if self.params.get('forcetitle', False):
  1361. self.to_stdout(info_dict['fulltitle'])
  1362. if self.params.get('forceid', False):
  1363. self.to_stdout(info_dict['id'])
  1364. if self.params.get('forceurl', False):
  1365. if info_dict.get('requested_formats') is not None:
  1366. for f in info_dict['requested_formats']:
  1367. self.to_stdout(f['url'] + f.get('play_path', ''))
  1368. else:
  1369. # For RTMP URLs, also include the playpath
  1370. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1371. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1372. self.to_stdout(info_dict['thumbnail'])
  1373. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1374. self.to_stdout(info_dict['description'])
  1375. if self.params.get('forcefilename', False) and filename is not None:
  1376. self.to_stdout(filename)
  1377. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1378. self.to_stdout(formatSeconds(info_dict['duration']))
  1379. if self.params.get('forceformat', False):
  1380. self.to_stdout(info_dict['format'])
  1381. if self.params.get('forcejson', False):
  1382. self.to_stdout(json.dumps(info_dict))
  1383. # Do nothing else if in simulate mode
  1384. if self.params.get('simulate', False):
  1385. return
  1386. if filename is None:
  1387. return
  1388. try:
  1389. dn = os.path.dirname(sanitize_path(encodeFilename(filename)))
  1390. if dn and not os.path.exists(dn):
  1391. os.makedirs(dn)
  1392. except (OSError, IOError) as err:
  1393. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1394. return
  1395. if self.params.get('writedescription', False):
  1396. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1397. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1398. self.to_screen('[info] Video description is already present')
  1399. elif info_dict.get('description') is None:
  1400. self.report_warning('There\'s no description to write.')
  1401. else:
  1402. try:
  1403. self.to_screen('[info] Writing video description to: ' + descfn)
  1404. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1405. descfile.write(info_dict['description'])
  1406. except (OSError, IOError):
  1407. self.report_error('Cannot write description file ' + descfn)
  1408. return
  1409. if self.params.get('writeannotations', False):
  1410. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1411. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1412. self.to_screen('[info] Video annotations are already present')
  1413. else:
  1414. try:
  1415. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1416. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1417. annofile.write(info_dict['annotations'])
  1418. except (KeyError, TypeError):
  1419. self.report_warning('There are no annotations to write.')
  1420. except (OSError, IOError):
  1421. self.report_error('Cannot write annotations file: ' + annofn)
  1422. return
  1423. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1424. self.params.get('writeautomaticsub')])
  1425. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1426. # subtitles download errors are already managed as troubles in relevant IE
  1427. # that way it will silently go on when used with unsupporting IE
  1428. subtitles = info_dict['requested_subtitles']
  1429. ie = self.get_info_extractor(info_dict['extractor_key'])
  1430. for sub_lang, sub_info in subtitles.items():
  1431. sub_format = sub_info['ext']
  1432. if sub_info.get('data') is not None:
  1433. sub_data = sub_info['data']
  1434. else:
  1435. try:
  1436. sub_data = ie._download_webpage(
  1437. sub_info['url'], info_dict['id'], note=False)
  1438. except ExtractorError as err:
  1439. self.report_warning('Unable to download subtitle for "%s": %s' %
  1440. (sub_lang, error_to_compat_str(err.cause)))
  1441. continue
  1442. try:
  1443. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1444. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1445. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1446. else:
  1447. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1448. # Use newline='' to prevent conversion of newline characters
  1449. # See https://github.com/rg3/youtube-dl/issues/10268
  1450. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
  1451. subfile.write(sub_data)
  1452. except (OSError, IOError):
  1453. self.report_error('Cannot write subtitles file ' + sub_filename)
  1454. return
  1455. if self.params.get('writeinfojson', False):
  1456. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1457. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1458. self.to_screen('[info] Video description metadata is already present')
  1459. else:
  1460. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1461. try:
  1462. write_json_file(self.filter_requested_info(info_dict), infofn)
  1463. except (OSError, IOError):
  1464. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1465. return
  1466. self._write_thumbnails(info_dict, filename)
  1467. if not self.params.get('skip_download', False):
  1468. try:
  1469. def dl(name, info):
  1470. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1471. for ph in self._progress_hooks:
  1472. fd.add_progress_hook(ph)
  1473. if self.params.get('verbose'):
  1474. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1475. return fd.download(name, info)
  1476. if info_dict.get('requested_formats') is not None:
  1477. downloaded = []
  1478. success = True
  1479. merger = FFmpegMergerPP(self)
  1480. if not merger.available:
  1481. postprocessors = []
  1482. self.report_warning('You have requested multiple '
  1483. 'formats but ffmpeg or avconv are not installed.'
  1484. ' The formats won\'t be merged.')
  1485. else:
  1486. postprocessors = [merger]
  1487. def compatible_formats(formats):
  1488. video, audio = formats
  1489. # Check extension
  1490. video_ext, audio_ext = audio.get('ext'), video.get('ext')
  1491. if video_ext and audio_ext:
  1492. COMPATIBLE_EXTS = (
  1493. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v'),
  1494. ('webm')
  1495. )
  1496. for exts in COMPATIBLE_EXTS:
  1497. if video_ext in exts and audio_ext in exts:
  1498. return True
  1499. # TODO: Check acodec/vcodec
  1500. return False
  1501. filename_real_ext = os.path.splitext(filename)[1][1:]
  1502. filename_wo_ext = (
  1503. os.path.splitext(filename)[0]
  1504. if filename_real_ext == info_dict['ext']
  1505. else filename)
  1506. requested_formats = info_dict['requested_formats']
  1507. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1508. info_dict['ext'] = 'mkv'
  1509. self.report_warning(
  1510. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1511. # Ensure filename always has a correct extension for successful merge
  1512. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1513. if os.path.exists(encodeFilename(filename)):
  1514. self.to_screen(
  1515. '[download] %s has already been downloaded and '
  1516. 'merged' % filename)
  1517. else:
  1518. for f in requested_formats:
  1519. new_info = dict(info_dict)
  1520. new_info.update(f)
  1521. fname = self.prepare_filename(new_info)
  1522. fname = prepend_extension(fname, 'f%s' % f['format_id'], new_info['ext'])
  1523. downloaded.append(fname)
  1524. partial_success = dl(fname, new_info)
  1525. success = success and partial_success
  1526. info_dict['__postprocessors'] = postprocessors
  1527. info_dict['__files_to_merge'] = downloaded
  1528. else:
  1529. # Just a single file
  1530. success = dl(filename, info_dict)
  1531. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1532. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1533. return
  1534. except (OSError, IOError) as err:
  1535. raise UnavailableVideoError(err)
  1536. except (ContentTooShortError, ) as err:
  1537. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1538. return
  1539. if success and filename != '-':
  1540. # Fixup content
  1541. fixup_policy = self.params.get('fixup')
  1542. if fixup_policy is None:
  1543. fixup_policy = 'detect_or_warn'
  1544. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1545. stretched_ratio = info_dict.get('stretched_ratio')
  1546. if stretched_ratio is not None and stretched_ratio != 1:
  1547. if fixup_policy == 'warn':
  1548. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1549. info_dict['id'], stretched_ratio))
  1550. elif fixup_policy == 'detect_or_warn':
  1551. stretched_pp = FFmpegFixupStretchedPP(self)
  1552. if stretched_pp.available:
  1553. info_dict.setdefault('__postprocessors', [])
  1554. info_dict['__postprocessors'].append(stretched_pp)
  1555. else:
  1556. self.report_warning(
  1557. '%s: Non-uniform pixel ratio (%s). %s'
  1558. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1559. else:
  1560. assert fixup_policy in ('ignore', 'never')
  1561. if (info_dict.get('requested_formats') is None and
  1562. info_dict.get('container') == 'm4a_dash'):
  1563. if fixup_policy == 'warn':
  1564. self.report_warning(
  1565. '%s: writing DASH m4a. '
  1566. 'Only some players support this container.'
  1567. % info_dict['id'])
  1568. elif fixup_policy == 'detect_or_warn':
  1569. fixup_pp = FFmpegFixupM4aPP(self)
  1570. if fixup_pp.available:
  1571. info_dict.setdefault('__postprocessors', [])
  1572. info_dict['__postprocessors'].append(fixup_pp)
  1573. else:
  1574. self.report_warning(
  1575. '%s: writing DASH m4a. '
  1576. 'Only some players support this container. %s'
  1577. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1578. else:
  1579. assert fixup_policy in ('ignore', 'never')
  1580. if (info_dict.get('protocol') == 'm3u8_native' or
  1581. info_dict.get('protocol') == 'm3u8' and
  1582. self.params.get('hls_prefer_native')):
  1583. if fixup_policy == 'warn':
  1584. self.report_warning('%s: malformated aac bitstream.' % (
  1585. info_dict['id']))
  1586. elif fixup_policy == 'detect_or_warn':
  1587. fixup_pp = FFmpegFixupM3u8PP(self)
  1588. if fixup_pp.available:
  1589. info_dict.setdefault('__postprocessors', [])
  1590. info_dict['__postprocessors'].append(fixup_pp)
  1591. else:
  1592. self.report_warning(
  1593. '%s: malformated aac bitstream. %s'
  1594. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1595. else:
  1596. assert fixup_policy in ('ignore', 'never')
  1597. try:
  1598. self.post_process(filename, info_dict)
  1599. except (PostProcessingError) as err:
  1600. self.report_error('postprocessing: %s' % str(err))
  1601. return
  1602. self.record_download_archive(info_dict)
  1603. def download(self, url_list):
  1604. """Download a given list of URLs."""
  1605. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1606. if (len(url_list) > 1 and
  1607. '%' not in outtmpl and
  1608. self.params.get('max_downloads') != 1):
  1609. raise SameFileError(outtmpl)
  1610. for url in url_list:
  1611. try:
  1612. # It also downloads the videos
  1613. res = self.extract_info(
  1614. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1615. except UnavailableVideoError:
  1616. self.report_error('unable to download video')
  1617. except MaxDownloadsReached:
  1618. self.to_screen('[info] Maximum number of downloaded files reached.')
  1619. raise
  1620. else:
  1621. if self.params.get('dump_single_json', False):
  1622. self.to_stdout(json.dumps(res))
  1623. return self._download_retcode
  1624. def download_with_info_file(self, info_filename):
  1625. with contextlib.closing(fileinput.FileInput(
  1626. [info_filename], mode='r',
  1627. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1628. # FileInput doesn't have a read method, we can't call json.load
  1629. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1630. try:
  1631. self.process_ie_result(info, download=True)
  1632. except DownloadError:
  1633. webpage_url = info.get('webpage_url')
  1634. if webpage_url is not None:
  1635. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1636. return self.download([webpage_url])
  1637. else:
  1638. raise
  1639. return self._download_retcode
  1640. @staticmethod
  1641. def filter_requested_info(info_dict):
  1642. return dict(
  1643. (k, v) for k, v in info_dict.items()
  1644. if k not in ['requested_formats', 'requested_subtitles'])
  1645. def post_process(self, filename, ie_info):
  1646. """Run all the postprocessors on the given file."""
  1647. info = dict(ie_info)
  1648. info['filepath'] = filename
  1649. pps_chain = []
  1650. if ie_info.get('__postprocessors') is not None:
  1651. pps_chain.extend(ie_info['__postprocessors'])
  1652. pps_chain.extend(self._pps)
  1653. for pp in pps_chain:
  1654. files_to_delete = []
  1655. try:
  1656. files_to_delete, info = pp.run(info)
  1657. except PostProcessingError as e:
  1658. self.report_error(e.msg)
  1659. if files_to_delete and not self.params.get('keepvideo', False):
  1660. for old_filename in files_to_delete:
  1661. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1662. try:
  1663. os.remove(encodeFilename(old_filename))
  1664. except (IOError, OSError):
  1665. self.report_warning('Unable to remove downloaded original file')
  1666. def _make_archive_id(self, info_dict):
  1667. # Future-proof against any change in case
  1668. # and backwards compatibility with prior versions
  1669. extractor = info_dict.get('extractor_key')
  1670. if extractor is None:
  1671. if 'id' in info_dict:
  1672. extractor = info_dict.get('ie_key') # key in a playlist
  1673. if extractor is None:
  1674. return None # Incomplete video information
  1675. return extractor.lower() + ' ' + info_dict['id']
  1676. def in_download_archive(self, info_dict):
  1677. fn = self.params.get('download_archive')
  1678. if fn is None:
  1679. return False
  1680. vid_id = self._make_archive_id(info_dict)
  1681. if vid_id is None:
  1682. return False # Incomplete video information
  1683. try:
  1684. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1685. for line in archive_file:
  1686. if line.strip() == vid_id:
  1687. return True
  1688. except IOError as ioe:
  1689. if ioe.errno != errno.ENOENT:
  1690. raise
  1691. return False
  1692. def record_download_archive(self, info_dict):
  1693. fn = self.params.get('download_archive')
  1694. if fn is None:
  1695. return
  1696. vid_id = self._make_archive_id(info_dict)
  1697. assert vid_id
  1698. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1699. archive_file.write(vid_id + '\n')
  1700. @staticmethod
  1701. def format_resolution(format, default='unknown'):
  1702. if format.get('vcodec') == 'none':
  1703. return 'audio only'
  1704. if format.get('resolution') is not None:
  1705. return format['resolution']
  1706. if format.get('height') is not None:
  1707. if format.get('width') is not None:
  1708. res = '%sx%s' % (format['width'], format['height'])
  1709. else:
  1710. res = '%sp' % format['height']
  1711. elif format.get('width') is not None:
  1712. res = '%dx?' % format['width']
  1713. else:
  1714. res = default
  1715. return res
  1716. def _format_note(self, fdict):
  1717. res = ''
  1718. if fdict.get('ext') in ['f4f', 'f4m']:
  1719. res += '(unsupported) '
  1720. if fdict.get('language'):
  1721. if res:
  1722. res += ' '
  1723. res += '[%s] ' % fdict['language']
  1724. if fdict.get('format_note') is not None:
  1725. res += fdict['format_note'] + ' '
  1726. if fdict.get('tbr') is not None:
  1727. res += '%4dk ' % fdict['tbr']
  1728. if fdict.get('container') is not None:
  1729. if res:
  1730. res += ', '
  1731. res += '%s container' % fdict['container']
  1732. if (fdict.get('vcodec') is not None and
  1733. fdict.get('vcodec') != 'none'):
  1734. if res:
  1735. res += ', '
  1736. res += fdict['vcodec']
  1737. if fdict.get('vbr') is not None:
  1738. res += '@'
  1739. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1740. res += 'video@'
  1741. if fdict.get('vbr') is not None:
  1742. res += '%4dk' % fdict['vbr']
  1743. if fdict.get('fps') is not None:
  1744. if res:
  1745. res += ', '
  1746. res += '%sfps' % fdict['fps']
  1747. if fdict.get('acodec') is not None:
  1748. if res:
  1749. res += ', '
  1750. if fdict['acodec'] == 'none':
  1751. res += 'video only'
  1752. else:
  1753. res += '%-5s' % fdict['acodec']
  1754. elif fdict.get('abr') is not None:
  1755. if res:
  1756. res += ', '
  1757. res += 'audio'
  1758. if fdict.get('abr') is not None:
  1759. res += '@%3dk' % fdict['abr']
  1760. if fdict.get('asr') is not None:
  1761. res += ' (%5dHz)' % fdict['asr']
  1762. if fdict.get('filesize') is not None:
  1763. if res:
  1764. res += ', '
  1765. res += format_bytes(fdict['filesize'])
  1766. elif fdict.get('filesize_approx') is not None:
  1767. if res:
  1768. res += ', '
  1769. res += '~' + format_bytes(fdict['filesize_approx'])
  1770. return res
  1771. def list_formats(self, info_dict):
  1772. formats = info_dict.get('formats', [info_dict])
  1773. table = [
  1774. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1775. for f in formats
  1776. if f.get('preference') is None or f['preference'] >= -1000]
  1777. if len(formats) > 1:
  1778. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1779. header_line = ['format code', 'extension', 'resolution', 'note']
  1780. self.to_screen(
  1781. '[info] Available formats for %s:\n%s' %
  1782. (info_dict['id'], render_table(header_line, table)))
  1783. def list_thumbnails(self, info_dict):
  1784. thumbnails = info_dict.get('thumbnails')
  1785. if not thumbnails:
  1786. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  1787. return
  1788. self.to_screen(
  1789. '[info] Thumbnails for %s:' % info_dict['id'])
  1790. self.to_screen(render_table(
  1791. ['ID', 'width', 'height', 'URL'],
  1792. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1793. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1794. if not subtitles:
  1795. self.to_screen('%s has no %s' % (video_id, name))
  1796. return
  1797. self.to_screen(
  1798. 'Available %s for %s:' % (name, video_id))
  1799. self.to_screen(render_table(
  1800. ['Language', 'formats'],
  1801. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  1802. for lang, formats in subtitles.items()]))
  1803. def urlopen(self, req):
  1804. """ Start an HTTP download """
  1805. if isinstance(req, compat_basestring):
  1806. req = sanitized_Request(req)
  1807. return self._opener.open(req, timeout=self._socket_timeout)
  1808. def print_debug_header(self):
  1809. if not self.params.get('verbose'):
  1810. return
  1811. if type('') is not compat_str:
  1812. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1813. self.report_warning(
  1814. 'Your Python is broken! Update to a newer and supported version')
  1815. stdout_encoding = getattr(
  1816. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1817. encoding_str = (
  1818. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1819. locale.getpreferredencoding(),
  1820. sys.getfilesystemencoding(),
  1821. stdout_encoding,
  1822. self.get_encoding()))
  1823. write_string(encoding_str, encoding=None)
  1824. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1825. if _LAZY_LOADER:
  1826. self._write_string('[debug] Lazy loading extractors enabled' + '\n')
  1827. try:
  1828. sp = subprocess.Popen(
  1829. ['git', 'rev-parse', '--short', 'HEAD'],
  1830. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1831. cwd=os.path.dirname(os.path.abspath(__file__)))
  1832. out, err = sp.communicate()
  1833. out = out.decode().strip()
  1834. if re.match('[0-9a-f]+', out):
  1835. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1836. except Exception:
  1837. try:
  1838. sys.exc_clear()
  1839. except Exception:
  1840. pass
  1841. self._write_string('[debug] Python version %s - %s\n' % (
  1842. platform.python_version(), platform_name()))
  1843. exe_versions = FFmpegPostProcessor.get_versions(self)
  1844. exe_versions['rtmpdump'] = rtmpdump_version()
  1845. exe_str = ', '.join(
  1846. '%s %s' % (exe, v)
  1847. for exe, v in sorted(exe_versions.items())
  1848. if v
  1849. )
  1850. if not exe_str:
  1851. exe_str = 'none'
  1852. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1853. proxy_map = {}
  1854. for handler in self._opener.handlers:
  1855. if hasattr(handler, 'proxies'):
  1856. proxy_map.update(handler.proxies)
  1857. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1858. if self.params.get('call_home', False):
  1859. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1860. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1861. latest_version = self.urlopen(
  1862. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1863. if version_tuple(latest_version) > version_tuple(__version__):
  1864. self.report_warning(
  1865. 'You are using an outdated version (newest version: %s)! '
  1866. 'See https://yt-dl.org/update if you need help updating.' %
  1867. latest_version)
  1868. def _setup_opener(self):
  1869. timeout_val = self.params.get('socket_timeout')
  1870. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1871. opts_cookiefile = self.params.get('cookiefile')
  1872. opts_proxy = self.params.get('proxy')
  1873. if opts_cookiefile is None:
  1874. self.cookiejar = compat_cookiejar.CookieJar()
  1875. else:
  1876. opts_cookiefile = compat_expanduser(opts_cookiefile)
  1877. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1878. opts_cookiefile)
  1879. if os.access(opts_cookiefile, os.R_OK):
  1880. self.cookiejar.load()
  1881. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  1882. if opts_proxy is not None:
  1883. if opts_proxy == '':
  1884. proxies = {}
  1885. else:
  1886. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1887. else:
  1888. proxies = compat_urllib_request.getproxies()
  1889. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1890. if 'http' in proxies and 'https' not in proxies:
  1891. proxies['https'] = proxies['http']
  1892. proxy_handler = PerRequestProxyHandler(proxies)
  1893. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1894. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1895. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1896. data_handler = compat_urllib_request_DataHandler()
  1897. # When passing our own FileHandler instance, build_opener won't add the
  1898. # default FileHandler and allows us to disable the file protocol, which
  1899. # can be used for malicious purposes (see
  1900. # https://github.com/rg3/youtube-dl/issues/8227)
  1901. file_handler = compat_urllib_request.FileHandler()
  1902. def file_open(*args, **kwargs):
  1903. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  1904. file_handler.file_open = file_open
  1905. opener = compat_urllib_request.build_opener(
  1906. proxy_handler, https_handler, cookie_processor, ydlh, data_handler, file_handler)
  1907. # Delete the default user-agent header, which would otherwise apply in
  1908. # cases where our custom HTTP handler doesn't come into play
  1909. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1910. opener.addheaders = []
  1911. self._opener = opener
  1912. def encode(self, s):
  1913. if isinstance(s, bytes):
  1914. return s # Already encoded
  1915. try:
  1916. return s.encode(self.get_encoding())
  1917. except UnicodeEncodeError as err:
  1918. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1919. raise
  1920. def get_encoding(self):
  1921. encoding = self.params.get('encoding')
  1922. if encoding is None:
  1923. encoding = preferredencoding()
  1924. return encoding
  1925. def _write_thumbnails(self, info_dict, filename):
  1926. if self.params.get('writethumbnail', False):
  1927. thumbnails = info_dict.get('thumbnails')
  1928. if thumbnails:
  1929. thumbnails = [thumbnails[-1]]
  1930. elif self.params.get('write_all_thumbnails', False):
  1931. thumbnails = info_dict.get('thumbnails')
  1932. else:
  1933. return
  1934. if not thumbnails:
  1935. # No thumbnails present, so return immediately
  1936. return
  1937. for t in thumbnails:
  1938. thumb_ext = determine_ext(t['url'], 'jpg')
  1939. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1940. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1941. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1942. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1943. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1944. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1945. else:
  1946. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1947. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1948. try:
  1949. uf = self.urlopen(t['url'])
  1950. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  1951. shutil.copyfileobj(uf, thumbf)
  1952. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1953. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1954. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1955. self.report_warning('Unable to download thumbnail "%s": %s' %
  1956. (t['url'], error_to_compat_str(err)))