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.

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