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.

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