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.

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