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.

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