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.

2107 lines
94 KiB

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