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.

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