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.

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