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.

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