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.

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