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.

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