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.

2065 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. }
  816. str_operator_rex = re.compile(r'''(?x)
  817. \s*(?P<key>ext|acodec|vcodec|container|protocol)
  818. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?
  819. \s*(?P<value>[a-zA-Z0-9_-]+)
  820. \s*$
  821. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  822. m = str_operator_rex.search(filter_spec)
  823. if m:
  824. comparison_value = m.group('value')
  825. op = STR_OPERATORS[m.group('op')]
  826. if not m:
  827. raise ValueError('Invalid filter specification %r' % filter_spec)
  828. def _filter(f):
  829. actual_value = f.get(m.group('key'))
  830. if actual_value is None:
  831. return m.group('none_inclusive')
  832. return op(actual_value, comparison_value)
  833. return _filter
  834. def build_format_selector(self, format_spec):
  835. def syntax_error(note, start):
  836. message = (
  837. 'Invalid format specification: '
  838. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  839. return SyntaxError(message)
  840. PICKFIRST = 'PICKFIRST'
  841. MERGE = 'MERGE'
  842. SINGLE = 'SINGLE'
  843. GROUP = 'GROUP'
  844. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  845. def _parse_filter(tokens):
  846. filter_parts = []
  847. for type, string, start, _, _ in tokens:
  848. if type == tokenize.OP and string == ']':
  849. return ''.join(filter_parts)
  850. else:
  851. filter_parts.append(string)
  852. def _remove_unused_ops(tokens):
  853. # Remove operators that we don't use and join them with the surrounding strings
  854. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  855. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  856. last_string, last_start, last_end, last_line = None, None, None, None
  857. for type, string, start, end, line in tokens:
  858. if type == tokenize.OP and string == '[':
  859. if last_string:
  860. yield tokenize.NAME, last_string, last_start, last_end, last_line
  861. last_string = None
  862. yield type, string, start, end, line
  863. # everything inside brackets will be handled by _parse_filter
  864. for type, string, start, end, line in tokens:
  865. yield type, string, start, end, line
  866. if type == tokenize.OP and string == ']':
  867. break
  868. elif type == tokenize.OP and string in ALLOWED_OPS:
  869. if last_string:
  870. yield tokenize.NAME, last_string, last_start, last_end, last_line
  871. last_string = None
  872. yield type, string, start, end, line
  873. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  874. if not last_string:
  875. last_string = string
  876. last_start = start
  877. last_end = end
  878. else:
  879. last_string += string
  880. if last_string:
  881. yield tokenize.NAME, last_string, last_start, last_end, last_line
  882. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  883. selectors = []
  884. current_selector = None
  885. for type, string, start, _, _ in tokens:
  886. # ENCODING is only defined in python 3.x
  887. if type == getattr(tokenize, 'ENCODING', None):
  888. continue
  889. elif type in [tokenize.NAME, tokenize.NUMBER]:
  890. current_selector = FormatSelector(SINGLE, string, [])
  891. elif type == tokenize.OP:
  892. if string == ')':
  893. if not inside_group:
  894. # ')' will be handled by the parentheses group
  895. tokens.restore_last_token()
  896. break
  897. elif inside_merge and string in ['/', ',']:
  898. tokens.restore_last_token()
  899. break
  900. elif inside_choice and string == ',':
  901. tokens.restore_last_token()
  902. break
  903. elif string == ',':
  904. if not current_selector:
  905. raise syntax_error('"," must follow a format selector', start)
  906. selectors.append(current_selector)
  907. current_selector = None
  908. elif string == '/':
  909. if not current_selector:
  910. raise syntax_error('"/" must follow a format selector', start)
  911. first_choice = current_selector
  912. second_choice = _parse_format_selection(tokens, inside_choice=True)
  913. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  914. elif string == '[':
  915. if not current_selector:
  916. current_selector = FormatSelector(SINGLE, 'best', [])
  917. format_filter = _parse_filter(tokens)
  918. current_selector.filters.append(format_filter)
  919. elif string == '(':
  920. if current_selector:
  921. raise syntax_error('Unexpected "("', start)
  922. group = _parse_format_selection(tokens, inside_group=True)
  923. current_selector = FormatSelector(GROUP, group, [])
  924. elif string == '+':
  925. video_selector = current_selector
  926. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  927. if not video_selector or not audio_selector:
  928. raise syntax_error('"+" must be between two format selectors', start)
  929. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  930. else:
  931. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  932. elif type == tokenize.ENDMARKER:
  933. break
  934. if current_selector:
  935. selectors.append(current_selector)
  936. return selectors
  937. def _build_selector_function(selector):
  938. if isinstance(selector, list):
  939. fs = [_build_selector_function(s) for s in selector]
  940. def selector_function(formats):
  941. for f in fs:
  942. for format in f(formats):
  943. yield format
  944. return selector_function
  945. elif selector.type == GROUP:
  946. selector_function = _build_selector_function(selector.selector)
  947. elif selector.type == PICKFIRST:
  948. fs = [_build_selector_function(s) for s in selector.selector]
  949. def selector_function(formats):
  950. for f in fs:
  951. picked_formats = list(f(formats))
  952. if picked_formats:
  953. return picked_formats
  954. return []
  955. elif selector.type == SINGLE:
  956. format_spec = selector.selector
  957. def selector_function(formats):
  958. formats = list(formats)
  959. if not formats:
  960. return
  961. if format_spec == 'all':
  962. for f in formats:
  963. yield f
  964. elif format_spec in ['best', 'worst', None]:
  965. format_idx = 0 if format_spec == 'worst' else -1
  966. audiovideo_formats = [
  967. f for f in formats
  968. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  969. if audiovideo_formats:
  970. yield audiovideo_formats[format_idx]
  971. # for audio only (soundcloud) or video only (imgur) urls, select the best/worst audio format
  972. elif (all(f.get('acodec') != 'none' for f in formats) or
  973. all(f.get('vcodec') != 'none' for f in formats)):
  974. yield formats[format_idx]
  975. elif format_spec == 'bestaudio':
  976. audio_formats = [
  977. f for f in formats
  978. if f.get('vcodec') == 'none']
  979. if audio_formats:
  980. yield audio_formats[-1]
  981. elif format_spec == 'worstaudio':
  982. audio_formats = [
  983. f for f in formats
  984. if f.get('vcodec') == 'none']
  985. if audio_formats:
  986. yield audio_formats[0]
  987. elif format_spec == 'bestvideo':
  988. video_formats = [
  989. f for f in formats
  990. if f.get('acodec') == 'none']
  991. if video_formats:
  992. yield video_formats[-1]
  993. elif format_spec == 'worstvideo':
  994. video_formats = [
  995. f for f in formats
  996. if f.get('acodec') == 'none']
  997. if video_formats:
  998. yield video_formats[0]
  999. else:
  1000. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1001. if format_spec in extensions:
  1002. filter_f = lambda f: f['ext'] == format_spec
  1003. else:
  1004. filter_f = lambda f: f['format_id'] == format_spec
  1005. matches = list(filter(filter_f, formats))
  1006. if matches:
  1007. yield matches[-1]
  1008. elif selector.type == MERGE:
  1009. def _merge(formats_info):
  1010. format_1, format_2 = [f['format_id'] for f in formats_info]
  1011. # The first format must contain the video and the
  1012. # second the audio
  1013. if formats_info[0].get('vcodec') == 'none':
  1014. self.report_error('The first format must '
  1015. 'contain the video, try using '
  1016. '"-f %s+%s"' % (format_2, format_1))
  1017. return
  1018. # Formats must be opposite (video+audio)
  1019. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1020. self.report_error(
  1021. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1022. % (format_1, format_2))
  1023. return
  1024. output_ext = (
  1025. formats_info[0]['ext']
  1026. if self.params.get('merge_output_format') is None
  1027. else self.params['merge_output_format'])
  1028. return {
  1029. 'requested_formats': formats_info,
  1030. 'format': '%s+%s' % (formats_info[0].get('format'),
  1031. formats_info[1].get('format')),
  1032. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1033. formats_info[1].get('format_id')),
  1034. 'width': formats_info[0].get('width'),
  1035. 'height': formats_info[0].get('height'),
  1036. 'resolution': formats_info[0].get('resolution'),
  1037. 'fps': formats_info[0].get('fps'),
  1038. 'vcodec': formats_info[0].get('vcodec'),
  1039. 'vbr': formats_info[0].get('vbr'),
  1040. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1041. 'acodec': formats_info[1].get('acodec'),
  1042. 'abr': formats_info[1].get('abr'),
  1043. 'ext': output_ext,
  1044. }
  1045. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1046. def selector_function(formats):
  1047. formats = list(formats)
  1048. for pair in itertools.product(video_selector(formats), audio_selector(formats)):
  1049. yield _merge(pair)
  1050. filters = [self._build_format_filter(f) for f in selector.filters]
  1051. def final_selector(formats):
  1052. for _filter in filters:
  1053. formats = list(filter(_filter, formats))
  1054. return selector_function(formats)
  1055. return final_selector
  1056. stream = io.BytesIO(format_spec.encode('utf-8'))
  1057. try:
  1058. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1059. except tokenize.TokenError:
  1060. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1061. class TokenIterator(object):
  1062. def __init__(self, tokens):
  1063. self.tokens = tokens
  1064. self.counter = 0
  1065. def __iter__(self):
  1066. return self
  1067. def __next__(self):
  1068. if self.counter >= len(self.tokens):
  1069. raise StopIteration()
  1070. value = self.tokens[self.counter]
  1071. self.counter += 1
  1072. return value
  1073. next = __next__
  1074. def restore_last_token(self):
  1075. self.counter -= 1
  1076. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1077. return _build_selector_function(parsed_selector)
  1078. def _calc_headers(self, info_dict):
  1079. res = std_headers.copy()
  1080. add_headers = info_dict.get('http_headers')
  1081. if add_headers:
  1082. res.update(add_headers)
  1083. cookies = self._calc_cookies(info_dict)
  1084. if cookies:
  1085. res['Cookie'] = cookies
  1086. return res
  1087. def _calc_cookies(self, info_dict):
  1088. pr = sanitized_Request(info_dict['url'])
  1089. self.cookiejar.add_cookie_header(pr)
  1090. return pr.get_header('Cookie')
  1091. def process_video_result(self, info_dict, download=True):
  1092. assert info_dict.get('_type', 'video') == 'video'
  1093. if 'id' not in info_dict:
  1094. raise ExtractorError('Missing "id" field in extractor result')
  1095. if 'title' not in info_dict:
  1096. raise ExtractorError('Missing "title" field in extractor result')
  1097. if 'playlist' not in info_dict:
  1098. # It isn't part of a playlist
  1099. info_dict['playlist'] = None
  1100. info_dict['playlist_index'] = None
  1101. thumbnails = info_dict.get('thumbnails')
  1102. if thumbnails is None:
  1103. thumbnail = info_dict.get('thumbnail')
  1104. if thumbnail:
  1105. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1106. if thumbnails:
  1107. thumbnails.sort(key=lambda t: (
  1108. t.get('preference'), t.get('width'), t.get('height'),
  1109. t.get('id'), t.get('url')))
  1110. for i, t in enumerate(thumbnails):
  1111. if t.get('width') and t.get('height'):
  1112. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1113. if t.get('id') is None:
  1114. t['id'] = '%d' % i
  1115. if thumbnails and 'thumbnail' not in info_dict:
  1116. info_dict['thumbnail'] = thumbnails[-1]['url']
  1117. if 'display_id' not in info_dict and 'id' in info_dict:
  1118. info_dict['display_id'] = info_dict['id']
  1119. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  1120. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1121. # see http://bugs.python.org/issue1646728)
  1122. try:
  1123. upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
  1124. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  1125. except (ValueError, OverflowError, OSError):
  1126. pass
  1127. # Auto generate title fields corresponding to the *_number fields when missing
  1128. # in order to always have clean titles. This is very common for TV series.
  1129. for field in ('chapter', 'season', 'episode'):
  1130. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1131. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1132. subtitles = info_dict.get('subtitles')
  1133. if subtitles:
  1134. for _, subtitle in subtitles.items():
  1135. for subtitle_format in subtitle:
  1136. if 'ext' not in subtitle_format:
  1137. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1138. if self.params.get('listsubtitles', False):
  1139. if 'automatic_captions' in info_dict:
  1140. self.list_subtitles(info_dict['id'], info_dict.get('automatic_captions'), 'automatic captions')
  1141. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1142. return
  1143. info_dict['requested_subtitles'] = self.process_subtitles(
  1144. info_dict['id'], subtitles,
  1145. info_dict.get('automatic_captions'))
  1146. # We now pick which formats have to be downloaded
  1147. if info_dict.get('formats') is None:
  1148. # There's only one format available
  1149. formats = [info_dict]
  1150. else:
  1151. formats = info_dict['formats']
  1152. if not formats:
  1153. raise ExtractorError('No video formats found!')
  1154. formats_dict = {}
  1155. # We check that all the formats have the format and format_id fields
  1156. for i, format in enumerate(formats):
  1157. if 'url' not in format:
  1158. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  1159. if format.get('format_id') is None:
  1160. format['format_id'] = compat_str(i)
  1161. format_id = format['format_id']
  1162. if format_id not in formats_dict:
  1163. formats_dict[format_id] = []
  1164. formats_dict[format_id].append(format)
  1165. # Make sure all formats have unique format_id
  1166. for format_id, ambiguous_formats in formats_dict.items():
  1167. if len(ambiguous_formats) > 1:
  1168. for i, format in enumerate(ambiguous_formats):
  1169. format['format_id'] = '%s-%d' % (format_id, i)
  1170. for i, format in enumerate(formats):
  1171. if format.get('format') is None:
  1172. format['format'] = '{id} - {res}{note}'.format(
  1173. id=format['format_id'],
  1174. res=self.format_resolution(format),
  1175. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1176. )
  1177. # Automatically determine file extension if missing
  1178. if 'ext' not in format:
  1179. format['ext'] = determine_ext(format['url']).lower()
  1180. # Add HTTP headers, so that external programs can use them from the
  1181. # json output
  1182. full_format_info = info_dict.copy()
  1183. full_format_info.update(format)
  1184. format['http_headers'] = self._calc_headers(full_format_info)
  1185. # TODO Central sorting goes here
  1186. if formats[0] is not info_dict:
  1187. # only set the 'formats' fields if the original info_dict list them
  1188. # otherwise we end up with a circular reference, the first (and unique)
  1189. # element in the 'formats' field in info_dict is info_dict itself,
  1190. # which can't be exported to json
  1191. info_dict['formats'] = formats
  1192. if self.params.get('listformats'):
  1193. self.list_formats(info_dict)
  1194. return
  1195. if self.params.get('list_thumbnails'):
  1196. self.list_thumbnails(info_dict)
  1197. return
  1198. req_format = self.params.get('format')
  1199. if req_format is None:
  1200. req_format_list = []
  1201. if (self.params.get('outtmpl', DEFAULT_OUTTMPL) != '-' and
  1202. info_dict['extractor'] in ['youtube', 'ted'] and
  1203. not info_dict.get('is_live')):
  1204. merger = FFmpegMergerPP(self)
  1205. if merger.available and merger.can_merge():
  1206. req_format_list.append('bestvideo+bestaudio')
  1207. req_format_list.append('best')
  1208. req_format = '/'.join(req_format_list)
  1209. format_selector = self.build_format_selector(req_format)
  1210. formats_to_download = list(format_selector(formats))
  1211. if not formats_to_download:
  1212. raise ExtractorError('requested format not available',
  1213. expected=True)
  1214. if download:
  1215. if len(formats_to_download) > 1:
  1216. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1217. for format in formats_to_download:
  1218. new_info = dict(info_dict)
  1219. new_info.update(format)
  1220. self.process_info(new_info)
  1221. # We update the info dict with the best quality format (backwards compatibility)
  1222. info_dict.update(formats_to_download[-1])
  1223. return info_dict
  1224. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1225. """Select the requested subtitles and their format"""
  1226. available_subs = {}
  1227. if normal_subtitles and self.params.get('writesubtitles'):
  1228. available_subs.update(normal_subtitles)
  1229. if automatic_captions and self.params.get('writeautomaticsub'):
  1230. for lang, cap_info in automatic_captions.items():
  1231. if lang not in available_subs:
  1232. available_subs[lang] = cap_info
  1233. if (not self.params.get('writesubtitles') and not
  1234. self.params.get('writeautomaticsub') or not
  1235. available_subs):
  1236. return None
  1237. if self.params.get('allsubtitles', False):
  1238. requested_langs = available_subs.keys()
  1239. else:
  1240. if self.params.get('subtitleslangs', False):
  1241. requested_langs = self.params.get('subtitleslangs')
  1242. elif 'en' in available_subs:
  1243. requested_langs = ['en']
  1244. else:
  1245. requested_langs = [list(available_subs.keys())[0]]
  1246. formats_query = self.params.get('subtitlesformat', 'best')
  1247. formats_preference = formats_query.split('/') if formats_query else []
  1248. subs = {}
  1249. for lang in requested_langs:
  1250. formats = available_subs.get(lang)
  1251. if formats is None:
  1252. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1253. continue
  1254. for ext in formats_preference:
  1255. if ext == 'best':
  1256. f = formats[-1]
  1257. break
  1258. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1259. if matches:
  1260. f = matches[-1]
  1261. break
  1262. else:
  1263. f = formats[-1]
  1264. self.report_warning(
  1265. 'No subtitle format found matching "%s" for language %s, '
  1266. 'using %s' % (formats_query, lang, f['ext']))
  1267. subs[lang] = f
  1268. return subs
  1269. def process_info(self, info_dict):
  1270. """Process a single resolved IE result."""
  1271. assert info_dict.get('_type', 'video') == 'video'
  1272. max_downloads = self.params.get('max_downloads')
  1273. if max_downloads is not None:
  1274. if self._num_downloads >= int(max_downloads):
  1275. raise MaxDownloadsReached()
  1276. info_dict['fulltitle'] = info_dict['title']
  1277. if len(info_dict['title']) > 200:
  1278. info_dict['title'] = info_dict['title'][:197] + '...'
  1279. if 'format' not in info_dict:
  1280. info_dict['format'] = info_dict['ext']
  1281. reason = self._match_entry(info_dict, incomplete=False)
  1282. if reason is not None:
  1283. self.to_screen('[download] ' + reason)
  1284. return
  1285. self._num_downloads += 1
  1286. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1287. # Forced printings
  1288. if self.params.get('forcetitle', False):
  1289. self.to_stdout(info_dict['fulltitle'])
  1290. if self.params.get('forceid', False):
  1291. self.to_stdout(info_dict['id'])
  1292. if self.params.get('forceurl', False):
  1293. if info_dict.get('requested_formats') is not None:
  1294. for f in info_dict['requested_formats']:
  1295. self.to_stdout(f['url'] + f.get('play_path', ''))
  1296. else:
  1297. # For RTMP URLs, also include the playpath
  1298. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1299. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1300. self.to_stdout(info_dict['thumbnail'])
  1301. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1302. self.to_stdout(info_dict['description'])
  1303. if self.params.get('forcefilename', False) and filename is not None:
  1304. self.to_stdout(filename)
  1305. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1306. self.to_stdout(formatSeconds(info_dict['duration']))
  1307. if self.params.get('forceformat', False):
  1308. self.to_stdout(info_dict['format'])
  1309. if self.params.get('forcejson', False):
  1310. self.to_stdout(json.dumps(info_dict))
  1311. # Do nothing else if in simulate mode
  1312. if self.params.get('simulate', False):
  1313. return
  1314. if filename is None:
  1315. return
  1316. try:
  1317. dn = os.path.dirname(sanitize_path(encodeFilename(filename)))
  1318. if dn and not os.path.exists(dn):
  1319. os.makedirs(dn)
  1320. except (OSError, IOError) as err:
  1321. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1322. return
  1323. if self.params.get('writedescription', False):
  1324. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1325. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1326. self.to_screen('[info] Video description is already present')
  1327. elif info_dict.get('description') is None:
  1328. self.report_warning('There\'s no description to write.')
  1329. else:
  1330. try:
  1331. self.to_screen('[info] Writing video description to: ' + descfn)
  1332. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1333. descfile.write(info_dict['description'])
  1334. except (OSError, IOError):
  1335. self.report_error('Cannot write description file ' + descfn)
  1336. return
  1337. if self.params.get('writeannotations', False):
  1338. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1339. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1340. self.to_screen('[info] Video annotations are already present')
  1341. else:
  1342. try:
  1343. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1344. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1345. annofile.write(info_dict['annotations'])
  1346. except (KeyError, TypeError):
  1347. self.report_warning('There are no annotations to write.')
  1348. except (OSError, IOError):
  1349. self.report_error('Cannot write annotations file: ' + annofn)
  1350. return
  1351. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1352. self.params.get('writeautomaticsub')])
  1353. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1354. # subtitles download errors are already managed as troubles in relevant IE
  1355. # that way it will silently go on when used with unsupporting IE
  1356. subtitles = info_dict['requested_subtitles']
  1357. ie = self.get_info_extractor(info_dict['extractor_key'])
  1358. for sub_lang, sub_info in subtitles.items():
  1359. sub_format = sub_info['ext']
  1360. if sub_info.get('data') is not None:
  1361. sub_data = sub_info['data']
  1362. else:
  1363. try:
  1364. sub_data = ie._download_webpage(
  1365. sub_info['url'], info_dict['id'], note=False)
  1366. except ExtractorError as err:
  1367. self.report_warning('Unable to download subtitle for "%s": %s' %
  1368. (sub_lang, error_to_compat_str(err.cause)))
  1369. continue
  1370. try:
  1371. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1372. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1373. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1374. else:
  1375. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1376. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1377. subfile.write(sub_data)
  1378. except (OSError, IOError):
  1379. self.report_error('Cannot write subtitles file ' + sub_filename)
  1380. return
  1381. if self.params.get('writeinfojson', False):
  1382. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1383. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1384. self.to_screen('[info] Video description metadata is already present')
  1385. else:
  1386. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1387. try:
  1388. write_json_file(self.filter_requested_info(info_dict), infofn)
  1389. except (OSError, IOError):
  1390. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1391. return
  1392. self._write_thumbnails(info_dict, filename)
  1393. if not self.params.get('skip_download', False):
  1394. try:
  1395. def dl(name, info):
  1396. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1397. for ph in self._progress_hooks:
  1398. fd.add_progress_hook(ph)
  1399. if self.params.get('verbose'):
  1400. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1401. return fd.download(name, info)
  1402. if info_dict.get('requested_formats') is not None:
  1403. downloaded = []
  1404. success = True
  1405. merger = FFmpegMergerPP(self)
  1406. if not merger.available:
  1407. postprocessors = []
  1408. self.report_warning('You have requested multiple '
  1409. 'formats but ffmpeg or avconv are not installed.'
  1410. ' The formats won\'t be merged.')
  1411. else:
  1412. postprocessors = [merger]
  1413. def compatible_formats(formats):
  1414. video, audio = formats
  1415. # Check extension
  1416. video_ext, audio_ext = audio.get('ext'), video.get('ext')
  1417. if video_ext and audio_ext:
  1418. COMPATIBLE_EXTS = (
  1419. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v'),
  1420. ('webm')
  1421. )
  1422. for exts in COMPATIBLE_EXTS:
  1423. if video_ext in exts and audio_ext in exts:
  1424. return True
  1425. # TODO: Check acodec/vcodec
  1426. return False
  1427. filename_real_ext = os.path.splitext(filename)[1][1:]
  1428. filename_wo_ext = (
  1429. os.path.splitext(filename)[0]
  1430. if filename_real_ext == info_dict['ext']
  1431. else filename)
  1432. requested_formats = info_dict['requested_formats']
  1433. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1434. info_dict['ext'] = 'mkv'
  1435. self.report_warning(
  1436. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1437. # Ensure filename always has a correct extension for successful merge
  1438. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1439. if os.path.exists(encodeFilename(filename)):
  1440. self.to_screen(
  1441. '[download] %s has already been downloaded and '
  1442. 'merged' % filename)
  1443. else:
  1444. for f in requested_formats:
  1445. new_info = dict(info_dict)
  1446. new_info.update(f)
  1447. fname = self.prepare_filename(new_info)
  1448. fname = prepend_extension(fname, 'f%s' % f['format_id'], new_info['ext'])
  1449. downloaded.append(fname)
  1450. partial_success = dl(fname, new_info)
  1451. success = success and partial_success
  1452. info_dict['__postprocessors'] = postprocessors
  1453. info_dict['__files_to_merge'] = downloaded
  1454. else:
  1455. # Just a single file
  1456. success = dl(filename, info_dict)
  1457. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1458. self.report_error('unable to download video data: %s' % str(err))
  1459. return
  1460. except (OSError, IOError) as err:
  1461. raise UnavailableVideoError(err)
  1462. except (ContentTooShortError, ) as err:
  1463. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1464. return
  1465. if success:
  1466. # Fixup content
  1467. fixup_policy = self.params.get('fixup')
  1468. if fixup_policy is None:
  1469. fixup_policy = 'detect_or_warn'
  1470. stretched_ratio = info_dict.get('stretched_ratio')
  1471. if stretched_ratio is not None and stretched_ratio != 1:
  1472. if fixup_policy == 'warn':
  1473. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1474. info_dict['id'], stretched_ratio))
  1475. elif fixup_policy == 'detect_or_warn':
  1476. stretched_pp = FFmpegFixupStretchedPP(self)
  1477. if stretched_pp.available:
  1478. info_dict.setdefault('__postprocessors', [])
  1479. info_dict['__postprocessors'].append(stretched_pp)
  1480. else:
  1481. self.report_warning(
  1482. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1483. info_dict['id'], stretched_ratio))
  1484. else:
  1485. assert fixup_policy in ('ignore', 'never')
  1486. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1487. if fixup_policy == 'warn':
  1488. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1489. info_dict['id']))
  1490. elif fixup_policy == 'detect_or_warn':
  1491. fixup_pp = FFmpegFixupM4aPP(self)
  1492. if fixup_pp.available:
  1493. info_dict.setdefault('__postprocessors', [])
  1494. info_dict['__postprocessors'].append(fixup_pp)
  1495. else:
  1496. self.report_warning(
  1497. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1498. info_dict['id']))
  1499. else:
  1500. assert fixup_policy in ('ignore', 'never')
  1501. try:
  1502. self.post_process(filename, info_dict)
  1503. except (PostProcessingError) as err:
  1504. self.report_error('postprocessing: %s' % str(err))
  1505. return
  1506. self.record_download_archive(info_dict)
  1507. def download(self, url_list):
  1508. """Download a given list of URLs."""
  1509. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1510. if (len(url_list) > 1 and
  1511. '%' not in outtmpl and
  1512. self.params.get('max_downloads') != 1):
  1513. raise SameFileError(outtmpl)
  1514. for url in url_list:
  1515. try:
  1516. # It also downloads the videos
  1517. res = self.extract_info(
  1518. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1519. except UnavailableVideoError:
  1520. self.report_error('unable to download video')
  1521. except MaxDownloadsReached:
  1522. self.to_screen('[info] Maximum number of downloaded files reached.')
  1523. raise
  1524. else:
  1525. if self.params.get('dump_single_json', False):
  1526. self.to_stdout(json.dumps(res))
  1527. return self._download_retcode
  1528. def download_with_info_file(self, info_filename):
  1529. with contextlib.closing(fileinput.FileInput(
  1530. [info_filename], mode='r',
  1531. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1532. # FileInput doesn't have a read method, we can't call json.load
  1533. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1534. try:
  1535. self.process_ie_result(info, download=True)
  1536. except DownloadError:
  1537. webpage_url = info.get('webpage_url')
  1538. if webpage_url is not None:
  1539. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1540. return self.download([webpage_url])
  1541. else:
  1542. raise
  1543. return self._download_retcode
  1544. @staticmethod
  1545. def filter_requested_info(info_dict):
  1546. return dict(
  1547. (k, v) for k, v in info_dict.items()
  1548. if k not in ['requested_formats', 'requested_subtitles'])
  1549. def post_process(self, filename, ie_info):
  1550. """Run all the postprocessors on the given file."""
  1551. info = dict(ie_info)
  1552. info['filepath'] = filename
  1553. pps_chain = []
  1554. if ie_info.get('__postprocessors') is not None:
  1555. pps_chain.extend(ie_info['__postprocessors'])
  1556. pps_chain.extend(self._pps)
  1557. for pp in pps_chain:
  1558. files_to_delete = []
  1559. try:
  1560. files_to_delete, info = pp.run(info)
  1561. except PostProcessingError as e:
  1562. self.report_error(e.msg)
  1563. if files_to_delete and not self.params.get('keepvideo', False):
  1564. for old_filename in files_to_delete:
  1565. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1566. try:
  1567. os.remove(encodeFilename(old_filename))
  1568. except (IOError, OSError):
  1569. self.report_warning('Unable to remove downloaded original file')
  1570. def _make_archive_id(self, info_dict):
  1571. # Future-proof against any change in case
  1572. # and backwards compatibility with prior versions
  1573. extractor = info_dict.get('extractor_key')
  1574. if extractor is None:
  1575. if 'id' in info_dict:
  1576. extractor = info_dict.get('ie_key') # key in a playlist
  1577. if extractor is None:
  1578. return None # Incomplete video information
  1579. return extractor.lower() + ' ' + info_dict['id']
  1580. def in_download_archive(self, info_dict):
  1581. fn = self.params.get('download_archive')
  1582. if fn is None:
  1583. return False
  1584. vid_id = self._make_archive_id(info_dict)
  1585. if vid_id is None:
  1586. return False # Incomplete video information
  1587. try:
  1588. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1589. for line in archive_file:
  1590. if line.strip() == vid_id:
  1591. return True
  1592. except IOError as ioe:
  1593. if ioe.errno != errno.ENOENT:
  1594. raise
  1595. return False
  1596. def record_download_archive(self, info_dict):
  1597. fn = self.params.get('download_archive')
  1598. if fn is None:
  1599. return
  1600. vid_id = self._make_archive_id(info_dict)
  1601. assert vid_id
  1602. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1603. archive_file.write(vid_id + '\n')
  1604. @staticmethod
  1605. def format_resolution(format, default='unknown'):
  1606. if format.get('vcodec') == 'none':
  1607. return 'audio only'
  1608. if format.get('resolution') is not None:
  1609. return format['resolution']
  1610. if format.get('height') is not None:
  1611. if format.get('width') is not None:
  1612. res = '%sx%s' % (format['width'], format['height'])
  1613. else:
  1614. res = '%sp' % format['height']
  1615. elif format.get('width') is not None:
  1616. res = '?x%d' % format['width']
  1617. else:
  1618. res = default
  1619. return res
  1620. def _format_note(self, fdict):
  1621. res = ''
  1622. if fdict.get('ext') in ['f4f', 'f4m']:
  1623. res += '(unsupported) '
  1624. if fdict.get('language'):
  1625. if res:
  1626. res += ' '
  1627. res += '[%s]' % fdict['language']
  1628. if fdict.get('format_note') is not None:
  1629. res += fdict['format_note'] + ' '
  1630. if fdict.get('tbr') is not None:
  1631. res += '%4dk ' % fdict['tbr']
  1632. if fdict.get('container') is not None:
  1633. if res:
  1634. res += ', '
  1635. res += '%s container' % fdict['container']
  1636. if (fdict.get('vcodec') is not None and
  1637. fdict.get('vcodec') != 'none'):
  1638. if res:
  1639. res += ', '
  1640. res += fdict['vcodec']
  1641. if fdict.get('vbr') is not None:
  1642. res += '@'
  1643. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1644. res += 'video@'
  1645. if fdict.get('vbr') is not None:
  1646. res += '%4dk' % fdict['vbr']
  1647. if fdict.get('fps') is not None:
  1648. res += ', %sfps' % fdict['fps']
  1649. if fdict.get('acodec') is not None:
  1650. if res:
  1651. res += ', '
  1652. if fdict['acodec'] == 'none':
  1653. res += 'video only'
  1654. else:
  1655. res += '%-5s' % fdict['acodec']
  1656. elif fdict.get('abr') is not None:
  1657. if res:
  1658. res += ', '
  1659. res += 'audio'
  1660. if fdict.get('abr') is not None:
  1661. res += '@%3dk' % fdict['abr']
  1662. if fdict.get('asr') is not None:
  1663. res += ' (%5dHz)' % fdict['asr']
  1664. if fdict.get('filesize') is not None:
  1665. if res:
  1666. res += ', '
  1667. res += format_bytes(fdict['filesize'])
  1668. elif fdict.get('filesize_approx') is not None:
  1669. if res:
  1670. res += ', '
  1671. res += '~' + format_bytes(fdict['filesize_approx'])
  1672. return res
  1673. def list_formats(self, info_dict):
  1674. formats = info_dict.get('formats', [info_dict])
  1675. table = [
  1676. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1677. for f in formats
  1678. if f.get('preference') is None or f['preference'] >= -1000]
  1679. if len(formats) > 1:
  1680. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1681. header_line = ['format code', 'extension', 'resolution', 'note']
  1682. self.to_screen(
  1683. '[info] Available formats for %s:\n%s' %
  1684. (info_dict['id'], render_table(header_line, table)))
  1685. def list_thumbnails(self, info_dict):
  1686. thumbnails = info_dict.get('thumbnails')
  1687. if not thumbnails:
  1688. tn_url = info_dict.get('thumbnail')
  1689. if tn_url:
  1690. thumbnails = [{'id': '0', 'url': tn_url}]
  1691. else:
  1692. self.to_screen(
  1693. '[info] No thumbnails present for %s' % info_dict['id'])
  1694. return
  1695. self.to_screen(
  1696. '[info] Thumbnails for %s:' % info_dict['id'])
  1697. self.to_screen(render_table(
  1698. ['ID', 'width', 'height', 'URL'],
  1699. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1700. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1701. if not subtitles:
  1702. self.to_screen('%s has no %s' % (video_id, name))
  1703. return
  1704. self.to_screen(
  1705. 'Available %s for %s:' % (name, video_id))
  1706. self.to_screen(render_table(
  1707. ['Language', 'formats'],
  1708. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  1709. for lang, formats in subtitles.items()]))
  1710. def urlopen(self, req):
  1711. """ Start an HTTP download """
  1712. if isinstance(req, compat_basestring):
  1713. req = sanitized_Request(req)
  1714. return self._opener.open(req, timeout=self._socket_timeout)
  1715. def print_debug_header(self):
  1716. if not self.params.get('verbose'):
  1717. return
  1718. if type('') is not compat_str:
  1719. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1720. self.report_warning(
  1721. 'Your Python is broken! Update to a newer and supported version')
  1722. stdout_encoding = getattr(
  1723. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1724. encoding_str = (
  1725. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1726. locale.getpreferredencoding(),
  1727. sys.getfilesystemencoding(),
  1728. stdout_encoding,
  1729. self.get_encoding()))
  1730. write_string(encoding_str, encoding=None)
  1731. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1732. try:
  1733. sp = subprocess.Popen(
  1734. ['git', 'rev-parse', '--short', 'HEAD'],
  1735. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1736. cwd=os.path.dirname(os.path.abspath(__file__)))
  1737. out, err = sp.communicate()
  1738. out = out.decode().strip()
  1739. if re.match('[0-9a-f]+', out):
  1740. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1741. except Exception:
  1742. try:
  1743. sys.exc_clear()
  1744. except Exception:
  1745. pass
  1746. self._write_string('[debug] Python version %s - %s\n' % (
  1747. platform.python_version(), platform_name()))
  1748. exe_versions = FFmpegPostProcessor.get_versions(self)
  1749. exe_versions['rtmpdump'] = rtmpdump_version()
  1750. exe_str = ', '.join(
  1751. '%s %s' % (exe, v)
  1752. for exe, v in sorted(exe_versions.items())
  1753. if v
  1754. )
  1755. if not exe_str:
  1756. exe_str = 'none'
  1757. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1758. proxy_map = {}
  1759. for handler in self._opener.handlers:
  1760. if hasattr(handler, 'proxies'):
  1761. proxy_map.update(handler.proxies)
  1762. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1763. if self.params.get('call_home', False):
  1764. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1765. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1766. latest_version = self.urlopen(
  1767. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1768. if version_tuple(latest_version) > version_tuple(__version__):
  1769. self.report_warning(
  1770. 'You are using an outdated version (newest version: %s)! '
  1771. 'See https://yt-dl.org/update if you need help updating.' %
  1772. latest_version)
  1773. def _setup_opener(self):
  1774. timeout_val = self.params.get('socket_timeout')
  1775. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1776. opts_cookiefile = self.params.get('cookiefile')
  1777. opts_proxy = self.params.get('proxy')
  1778. if opts_cookiefile is None:
  1779. self.cookiejar = compat_cookiejar.CookieJar()
  1780. else:
  1781. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1782. opts_cookiefile)
  1783. if os.access(opts_cookiefile, os.R_OK):
  1784. self.cookiejar.load()
  1785. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  1786. if opts_proxy is not None:
  1787. if opts_proxy == '':
  1788. proxies = {}
  1789. else:
  1790. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1791. else:
  1792. proxies = compat_urllib_request.getproxies()
  1793. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1794. if 'http' in proxies and 'https' not in proxies:
  1795. proxies['https'] = proxies['http']
  1796. proxy_handler = PerRequestProxyHandler(proxies)
  1797. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1798. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1799. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1800. data_handler = compat_urllib_request_DataHandler()
  1801. # When passing our own FileHandler instance, build_opener won't add the
  1802. # default FileHandler and allows us to disable the file protocol, which
  1803. # can be used for malicious purposes (see
  1804. # https://github.com/rg3/youtube-dl/issues/8227)
  1805. file_handler = compat_urllib_request.FileHandler()
  1806. def file_open(*args, **kwargs):
  1807. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  1808. file_handler.file_open = file_open
  1809. opener = compat_urllib_request.build_opener(
  1810. proxy_handler, https_handler, cookie_processor, ydlh, data_handler, file_handler)
  1811. # Delete the default user-agent header, which would otherwise apply in
  1812. # cases where our custom HTTP handler doesn't come into play
  1813. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1814. opener.addheaders = []
  1815. self._opener = opener
  1816. def encode(self, s):
  1817. if isinstance(s, bytes):
  1818. return s # Already encoded
  1819. try:
  1820. return s.encode(self.get_encoding())
  1821. except UnicodeEncodeError as err:
  1822. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1823. raise
  1824. def get_encoding(self):
  1825. encoding = self.params.get('encoding')
  1826. if encoding is None:
  1827. encoding = preferredencoding()
  1828. return encoding
  1829. def _write_thumbnails(self, info_dict, filename):
  1830. if self.params.get('writethumbnail', False):
  1831. thumbnails = info_dict.get('thumbnails')
  1832. if thumbnails:
  1833. thumbnails = [thumbnails[-1]]
  1834. elif self.params.get('write_all_thumbnails', False):
  1835. thumbnails = info_dict.get('thumbnails')
  1836. else:
  1837. return
  1838. if not thumbnails:
  1839. # No thumbnails present, so return immediately
  1840. return
  1841. for t in thumbnails:
  1842. thumb_ext = determine_ext(t['url'], 'jpg')
  1843. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1844. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1845. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1846. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1847. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1848. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1849. else:
  1850. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1851. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1852. try:
  1853. uf = self.urlopen(t['url'])
  1854. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  1855. shutil.copyfileobj(uf, thumbf)
  1856. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1857. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1858. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1859. self.report_warning('Unable to download thumbnail "%s": %s' %
  1860. (t['url'], error_to_compat_str(err)))