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.

2173 lines
98 KiB

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