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.

2074 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')
  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')
  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') or ie_result.get('id')
  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')
  682. # For backwards compatibility, interpret -1 as whole list
  683. if playlistend == -1:
  684. playlistend = None
  685. playlistitems_str = self.params.get('playlist_items')
  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. else:
  1166. # Sanitize format_id from characters used in format selector expression
  1167. format['format_id'] = re.sub('[\s,/+\[\]()]', '_', format['format_id'])
  1168. format_id = format['format_id']
  1169. if format_id not in formats_dict:
  1170. formats_dict[format_id] = []
  1171. formats_dict[format_id].append(format)
  1172. # Make sure all formats have unique format_id
  1173. for format_id, ambiguous_formats in formats_dict.items():
  1174. if len(ambiguous_formats) > 1:
  1175. for i, format in enumerate(ambiguous_formats):
  1176. format['format_id'] = '%s-%d' % (format_id, i)
  1177. for i, format in enumerate(formats):
  1178. if format.get('format') is None:
  1179. format['format'] = '{id} - {res}{note}'.format(
  1180. id=format['format_id'],
  1181. res=self.format_resolution(format),
  1182. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1183. )
  1184. # Automatically determine file extension if missing
  1185. if 'ext' not in format:
  1186. format['ext'] = determine_ext(format['url']).lower()
  1187. # Automatically determine protocol if missing (useful for format
  1188. # selection purposes)
  1189. if 'protocol' not in format:
  1190. format['protocol'] = determine_protocol(format)
  1191. # Add HTTP headers, so that external programs can use them from the
  1192. # json output
  1193. full_format_info = info_dict.copy()
  1194. full_format_info.update(format)
  1195. format['http_headers'] = self._calc_headers(full_format_info)
  1196. # TODO Central sorting goes here
  1197. if formats[0] is not info_dict:
  1198. # only set the 'formats' fields if the original info_dict list them
  1199. # otherwise we end up with a circular reference, the first (and unique)
  1200. # element in the 'formats' field in info_dict is info_dict itself,
  1201. # which can't be exported to json
  1202. info_dict['formats'] = formats
  1203. if self.params.get('listformats'):
  1204. self.list_formats(info_dict)
  1205. return
  1206. if self.params.get('list_thumbnails'):
  1207. self.list_thumbnails(info_dict)
  1208. return
  1209. req_format = self.params.get('format')
  1210. if req_format is None:
  1211. req_format_list = []
  1212. if (self.params.get('outtmpl', DEFAULT_OUTTMPL) != '-' and
  1213. not info_dict.get('is_live')):
  1214. merger = FFmpegMergerPP(self)
  1215. if merger.available and merger.can_merge():
  1216. req_format_list.append('bestvideo+bestaudio')
  1217. req_format_list.append('best')
  1218. req_format = '/'.join(req_format_list)
  1219. format_selector = self.build_format_selector(req_format)
  1220. formats_to_download = list(format_selector(formats))
  1221. if not formats_to_download:
  1222. raise ExtractorError('requested format not available',
  1223. expected=True)
  1224. if download:
  1225. if len(formats_to_download) > 1:
  1226. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1227. for format in formats_to_download:
  1228. new_info = dict(info_dict)
  1229. new_info.update(format)
  1230. self.process_info(new_info)
  1231. # We update the info dict with the best quality format (backwards compatibility)
  1232. info_dict.update(formats_to_download[-1])
  1233. return info_dict
  1234. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1235. """Select the requested subtitles and their format"""
  1236. available_subs = {}
  1237. if normal_subtitles and self.params.get('writesubtitles'):
  1238. available_subs.update(normal_subtitles)
  1239. if automatic_captions and self.params.get('writeautomaticsub'):
  1240. for lang, cap_info in automatic_captions.items():
  1241. if lang not in available_subs:
  1242. available_subs[lang] = cap_info
  1243. if (not self.params.get('writesubtitles') and not
  1244. self.params.get('writeautomaticsub') or not
  1245. available_subs):
  1246. return None
  1247. if self.params.get('allsubtitles', False):
  1248. requested_langs = available_subs.keys()
  1249. else:
  1250. if self.params.get('subtitleslangs', False):
  1251. requested_langs = self.params.get('subtitleslangs')
  1252. elif 'en' in available_subs:
  1253. requested_langs = ['en']
  1254. else:
  1255. requested_langs = [list(available_subs.keys())[0]]
  1256. formats_query = self.params.get('subtitlesformat', 'best')
  1257. formats_preference = formats_query.split('/') if formats_query else []
  1258. subs = {}
  1259. for lang in requested_langs:
  1260. formats = available_subs.get(lang)
  1261. if formats is None:
  1262. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1263. continue
  1264. for ext in formats_preference:
  1265. if ext == 'best':
  1266. f = formats[-1]
  1267. break
  1268. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1269. if matches:
  1270. f = matches[-1]
  1271. break
  1272. else:
  1273. f = formats[-1]
  1274. self.report_warning(
  1275. 'No subtitle format found matching "%s" for language %s, '
  1276. 'using %s' % (formats_query, lang, f['ext']))
  1277. subs[lang] = f
  1278. return subs
  1279. def process_info(self, info_dict):
  1280. """Process a single resolved IE result."""
  1281. assert info_dict.get('_type', 'video') == 'video'
  1282. max_downloads = self.params.get('max_downloads')
  1283. if max_downloads is not None:
  1284. if self._num_downloads >= int(max_downloads):
  1285. raise MaxDownloadsReached()
  1286. info_dict['fulltitle'] = info_dict['title']
  1287. if len(info_dict['title']) > 200:
  1288. info_dict['title'] = info_dict['title'][:197] + '...'
  1289. if 'format' not in info_dict:
  1290. info_dict['format'] = info_dict['ext']
  1291. reason = self._match_entry(info_dict, incomplete=False)
  1292. if reason is not None:
  1293. self.to_screen('[download] ' + reason)
  1294. return
  1295. self._num_downloads += 1
  1296. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1297. # Forced printings
  1298. if self.params.get('forcetitle', False):
  1299. self.to_stdout(info_dict['fulltitle'])
  1300. if self.params.get('forceid', False):
  1301. self.to_stdout(info_dict['id'])
  1302. if self.params.get('forceurl', False):
  1303. if info_dict.get('requested_formats') is not None:
  1304. for f in info_dict['requested_formats']:
  1305. self.to_stdout(f['url'] + f.get('play_path', ''))
  1306. else:
  1307. # For RTMP URLs, also include the playpath
  1308. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1309. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1310. self.to_stdout(info_dict['thumbnail'])
  1311. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1312. self.to_stdout(info_dict['description'])
  1313. if self.params.get('forcefilename', False) and filename is not None:
  1314. self.to_stdout(filename)
  1315. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1316. self.to_stdout(formatSeconds(info_dict['duration']))
  1317. if self.params.get('forceformat', False):
  1318. self.to_stdout(info_dict['format'])
  1319. if self.params.get('forcejson', False):
  1320. self.to_stdout(json.dumps(info_dict))
  1321. # Do nothing else if in simulate mode
  1322. if self.params.get('simulate', False):
  1323. return
  1324. if filename is None:
  1325. return
  1326. try:
  1327. dn = os.path.dirname(sanitize_path(encodeFilename(filename)))
  1328. if dn and not os.path.exists(dn):
  1329. os.makedirs(dn)
  1330. except (OSError, IOError) as err:
  1331. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1332. return
  1333. if self.params.get('writedescription', False):
  1334. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1335. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1336. self.to_screen('[info] Video description is already present')
  1337. elif info_dict.get('description') is None:
  1338. self.report_warning('There\'s no description to write.')
  1339. else:
  1340. try:
  1341. self.to_screen('[info] Writing video description to: ' + descfn)
  1342. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1343. descfile.write(info_dict['description'])
  1344. except (OSError, IOError):
  1345. self.report_error('Cannot write description file ' + descfn)
  1346. return
  1347. if self.params.get('writeannotations', False):
  1348. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1349. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1350. self.to_screen('[info] Video annotations are already present')
  1351. else:
  1352. try:
  1353. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1354. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1355. annofile.write(info_dict['annotations'])
  1356. except (KeyError, TypeError):
  1357. self.report_warning('There are no annotations to write.')
  1358. except (OSError, IOError):
  1359. self.report_error('Cannot write annotations file: ' + annofn)
  1360. return
  1361. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1362. self.params.get('writeautomaticsub')])
  1363. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1364. # subtitles download errors are already managed as troubles in relevant IE
  1365. # that way it will silently go on when used with unsupporting IE
  1366. subtitles = info_dict['requested_subtitles']
  1367. ie = self.get_info_extractor(info_dict['extractor_key'])
  1368. for sub_lang, sub_info in subtitles.items():
  1369. sub_format = sub_info['ext']
  1370. if sub_info.get('data') is not None:
  1371. sub_data = sub_info['data']
  1372. else:
  1373. try:
  1374. sub_data = ie._download_webpage(
  1375. sub_info['url'], info_dict['id'], note=False)
  1376. except ExtractorError as err:
  1377. self.report_warning('Unable to download subtitle for "%s": %s' %
  1378. (sub_lang, error_to_compat_str(err.cause)))
  1379. continue
  1380. try:
  1381. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1382. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1383. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1384. else:
  1385. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1386. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1387. subfile.write(sub_data)
  1388. except (OSError, IOError):
  1389. self.report_error('Cannot write subtitles file ' + sub_filename)
  1390. return
  1391. if self.params.get('writeinfojson', False):
  1392. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1393. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1394. self.to_screen('[info] Video description metadata is already present')
  1395. else:
  1396. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1397. try:
  1398. write_json_file(self.filter_requested_info(info_dict), infofn)
  1399. except (OSError, IOError):
  1400. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1401. return
  1402. self._write_thumbnails(info_dict, filename)
  1403. if not self.params.get('skip_download', False):
  1404. try:
  1405. def dl(name, info):
  1406. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1407. for ph in self._progress_hooks:
  1408. fd.add_progress_hook(ph)
  1409. if self.params.get('verbose'):
  1410. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1411. return fd.download(name, info)
  1412. if info_dict.get('requested_formats') is not None:
  1413. downloaded = []
  1414. success = True
  1415. merger = FFmpegMergerPP(self)
  1416. if not merger.available:
  1417. postprocessors = []
  1418. self.report_warning('You have requested multiple '
  1419. 'formats but ffmpeg or avconv are not installed.'
  1420. ' The formats won\'t be merged.')
  1421. else:
  1422. postprocessors = [merger]
  1423. def compatible_formats(formats):
  1424. video, audio = formats
  1425. # Check extension
  1426. video_ext, audio_ext = audio.get('ext'), video.get('ext')
  1427. if video_ext and audio_ext:
  1428. COMPATIBLE_EXTS = (
  1429. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v'),
  1430. ('webm')
  1431. )
  1432. for exts in COMPATIBLE_EXTS:
  1433. if video_ext in exts and audio_ext in exts:
  1434. return True
  1435. # TODO: Check acodec/vcodec
  1436. return False
  1437. filename_real_ext = os.path.splitext(filename)[1][1:]
  1438. filename_wo_ext = (
  1439. os.path.splitext(filename)[0]
  1440. if filename_real_ext == info_dict['ext']
  1441. else filename)
  1442. requested_formats = info_dict['requested_formats']
  1443. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1444. info_dict['ext'] = 'mkv'
  1445. self.report_warning(
  1446. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1447. # Ensure filename always has a correct extension for successful merge
  1448. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1449. if os.path.exists(encodeFilename(filename)):
  1450. self.to_screen(
  1451. '[download] %s has already been downloaded and '
  1452. 'merged' % filename)
  1453. else:
  1454. for f in requested_formats:
  1455. new_info = dict(info_dict)
  1456. new_info.update(f)
  1457. fname = self.prepare_filename(new_info)
  1458. fname = prepend_extension(fname, 'f%s' % f['format_id'], new_info['ext'])
  1459. downloaded.append(fname)
  1460. partial_success = dl(fname, new_info)
  1461. success = success and partial_success
  1462. info_dict['__postprocessors'] = postprocessors
  1463. info_dict['__files_to_merge'] = downloaded
  1464. else:
  1465. # Just a single file
  1466. success = dl(filename, info_dict)
  1467. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1468. self.report_error('unable to download video data: %s' % str(err))
  1469. return
  1470. except (OSError, IOError) as err:
  1471. raise UnavailableVideoError(err)
  1472. except (ContentTooShortError, ) as err:
  1473. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1474. return
  1475. if success and filename != '-':
  1476. # Fixup content
  1477. fixup_policy = self.params.get('fixup')
  1478. if fixup_policy is None:
  1479. fixup_policy = 'detect_or_warn'
  1480. stretched_ratio = info_dict.get('stretched_ratio')
  1481. if stretched_ratio is not None and stretched_ratio != 1:
  1482. if fixup_policy == 'warn':
  1483. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1484. info_dict['id'], stretched_ratio))
  1485. elif fixup_policy == 'detect_or_warn':
  1486. stretched_pp = FFmpegFixupStretchedPP(self)
  1487. if stretched_pp.available:
  1488. info_dict.setdefault('__postprocessors', [])
  1489. info_dict['__postprocessors'].append(stretched_pp)
  1490. else:
  1491. self.report_warning(
  1492. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1493. info_dict['id'], stretched_ratio))
  1494. else:
  1495. assert fixup_policy in ('ignore', 'never')
  1496. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1497. if fixup_policy == 'warn':
  1498. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1499. info_dict['id']))
  1500. elif fixup_policy == 'detect_or_warn':
  1501. fixup_pp = FFmpegFixupM4aPP(self)
  1502. if fixup_pp.available:
  1503. info_dict.setdefault('__postprocessors', [])
  1504. info_dict['__postprocessors'].append(fixup_pp)
  1505. else:
  1506. self.report_warning(
  1507. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1508. info_dict['id']))
  1509. else:
  1510. assert fixup_policy in ('ignore', 'never')
  1511. try:
  1512. self.post_process(filename, info_dict)
  1513. except (PostProcessingError) as err:
  1514. self.report_error('postprocessing: %s' % str(err))
  1515. return
  1516. self.record_download_archive(info_dict)
  1517. def download(self, url_list):
  1518. """Download a given list of URLs."""
  1519. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1520. if (len(url_list) > 1 and
  1521. '%' not in outtmpl and
  1522. self.params.get('max_downloads') != 1):
  1523. raise SameFileError(outtmpl)
  1524. for url in url_list:
  1525. try:
  1526. # It also downloads the videos
  1527. res = self.extract_info(
  1528. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1529. except UnavailableVideoError:
  1530. self.report_error('unable to download video')
  1531. except MaxDownloadsReached:
  1532. self.to_screen('[info] Maximum number of downloaded files reached.')
  1533. raise
  1534. else:
  1535. if self.params.get('dump_single_json', False):
  1536. self.to_stdout(json.dumps(res))
  1537. return self._download_retcode
  1538. def download_with_info_file(self, info_filename):
  1539. with contextlib.closing(fileinput.FileInput(
  1540. [info_filename], mode='r',
  1541. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1542. # FileInput doesn't have a read method, we can't call json.load
  1543. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1544. try:
  1545. self.process_ie_result(info, download=True)
  1546. except DownloadError:
  1547. webpage_url = info.get('webpage_url')
  1548. if webpage_url is not None:
  1549. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1550. return self.download([webpage_url])
  1551. else:
  1552. raise
  1553. return self._download_retcode
  1554. @staticmethod
  1555. def filter_requested_info(info_dict):
  1556. return dict(
  1557. (k, v) for k, v in info_dict.items()
  1558. if k not in ['requested_formats', 'requested_subtitles'])
  1559. def post_process(self, filename, ie_info):
  1560. """Run all the postprocessors on the given file."""
  1561. info = dict(ie_info)
  1562. info['filepath'] = filename
  1563. pps_chain = []
  1564. if ie_info.get('__postprocessors') is not None:
  1565. pps_chain.extend(ie_info['__postprocessors'])
  1566. pps_chain.extend(self._pps)
  1567. for pp in pps_chain:
  1568. files_to_delete = []
  1569. try:
  1570. files_to_delete, info = pp.run(info)
  1571. except PostProcessingError as e:
  1572. self.report_error(e.msg)
  1573. if files_to_delete and not self.params.get('keepvideo', False):
  1574. for old_filename in files_to_delete:
  1575. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1576. try:
  1577. os.remove(encodeFilename(old_filename))
  1578. except (IOError, OSError):
  1579. self.report_warning('Unable to remove downloaded original file')
  1580. def _make_archive_id(self, info_dict):
  1581. # Future-proof against any change in case
  1582. # and backwards compatibility with prior versions
  1583. extractor = info_dict.get('extractor_key')
  1584. if extractor is None:
  1585. if 'id' in info_dict:
  1586. extractor = info_dict.get('ie_key') # key in a playlist
  1587. if extractor is None:
  1588. return None # Incomplete video information
  1589. return extractor.lower() + ' ' + info_dict['id']
  1590. def in_download_archive(self, info_dict):
  1591. fn = self.params.get('download_archive')
  1592. if fn is None:
  1593. return False
  1594. vid_id = self._make_archive_id(info_dict)
  1595. if vid_id is None:
  1596. return False # Incomplete video information
  1597. try:
  1598. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1599. for line in archive_file:
  1600. if line.strip() == vid_id:
  1601. return True
  1602. except IOError as ioe:
  1603. if ioe.errno != errno.ENOENT:
  1604. raise
  1605. return False
  1606. def record_download_archive(self, info_dict):
  1607. fn = self.params.get('download_archive')
  1608. if fn is None:
  1609. return
  1610. vid_id = self._make_archive_id(info_dict)
  1611. assert vid_id
  1612. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1613. archive_file.write(vid_id + '\n')
  1614. @staticmethod
  1615. def format_resolution(format, default='unknown'):
  1616. if format.get('vcodec') == 'none':
  1617. return 'audio only'
  1618. if format.get('resolution') is not None:
  1619. return format['resolution']
  1620. if format.get('height') is not None:
  1621. if format.get('width') is not None:
  1622. res = '%sx%s' % (format['width'], format['height'])
  1623. else:
  1624. res = '%sp' % format['height']
  1625. elif format.get('width') is not None:
  1626. res = '%dx?' % format['width']
  1627. else:
  1628. res = default
  1629. return res
  1630. def _format_note(self, fdict):
  1631. res = ''
  1632. if fdict.get('ext') in ['f4f', 'f4m']:
  1633. res += '(unsupported) '
  1634. if fdict.get('language'):
  1635. if res:
  1636. res += ' '
  1637. res += '[%s]' % fdict['language']
  1638. if fdict.get('format_note') is not None:
  1639. res += fdict['format_note'] + ' '
  1640. if fdict.get('tbr') is not None:
  1641. res += '%4dk ' % fdict['tbr']
  1642. if fdict.get('container') is not None:
  1643. if res:
  1644. res += ', '
  1645. res += '%s container' % fdict['container']
  1646. if (fdict.get('vcodec') is not None and
  1647. fdict.get('vcodec') != 'none'):
  1648. if res:
  1649. res += ', '
  1650. res += fdict['vcodec']
  1651. if fdict.get('vbr') is not None:
  1652. res += '@'
  1653. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1654. res += 'video@'
  1655. if fdict.get('vbr') is not None:
  1656. res += '%4dk' % fdict['vbr']
  1657. if fdict.get('fps') is not None:
  1658. res += ', %sfps' % fdict['fps']
  1659. if fdict.get('acodec') is not None:
  1660. if res:
  1661. res += ', '
  1662. if fdict['acodec'] == 'none':
  1663. res += 'video only'
  1664. else:
  1665. res += '%-5s' % fdict['acodec']
  1666. elif fdict.get('abr') is not None:
  1667. if res:
  1668. res += ', '
  1669. res += 'audio'
  1670. if fdict.get('abr') is not None:
  1671. res += '@%3dk' % fdict['abr']
  1672. if fdict.get('asr') is not None:
  1673. res += ' (%5dHz)' % fdict['asr']
  1674. if fdict.get('filesize') is not None:
  1675. if res:
  1676. res += ', '
  1677. res += format_bytes(fdict['filesize'])
  1678. elif fdict.get('filesize_approx') is not None:
  1679. if res:
  1680. res += ', '
  1681. res += '~' + format_bytes(fdict['filesize_approx'])
  1682. return res
  1683. def list_formats(self, info_dict):
  1684. formats = info_dict.get('formats', [info_dict])
  1685. table = [
  1686. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1687. for f in formats
  1688. if f.get('preference') is None or f['preference'] >= -1000]
  1689. if len(formats) > 1:
  1690. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1691. header_line = ['format code', 'extension', 'resolution', 'note']
  1692. self.to_screen(
  1693. '[info] Available formats for %s:\n%s' %
  1694. (info_dict['id'], render_table(header_line, table)))
  1695. def list_thumbnails(self, info_dict):
  1696. thumbnails = info_dict.get('thumbnails')
  1697. if not thumbnails:
  1698. tn_url = info_dict.get('thumbnail')
  1699. if tn_url:
  1700. thumbnails = [{'id': '0', 'url': tn_url}]
  1701. else:
  1702. self.to_screen(
  1703. '[info] No thumbnails present for %s' % info_dict['id'])
  1704. return
  1705. self.to_screen(
  1706. '[info] Thumbnails for %s:' % info_dict['id'])
  1707. self.to_screen(render_table(
  1708. ['ID', 'width', 'height', 'URL'],
  1709. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1710. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1711. if not subtitles:
  1712. self.to_screen('%s has no %s' % (video_id, name))
  1713. return
  1714. self.to_screen(
  1715. 'Available %s for %s:' % (name, video_id))
  1716. self.to_screen(render_table(
  1717. ['Language', 'formats'],
  1718. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  1719. for lang, formats in subtitles.items()]))
  1720. def urlopen(self, req):
  1721. """ Start an HTTP download """
  1722. if isinstance(req, compat_basestring):
  1723. req = sanitized_Request(req)
  1724. return self._opener.open(req, timeout=self._socket_timeout)
  1725. def print_debug_header(self):
  1726. if not self.params.get('verbose'):
  1727. return
  1728. if type('') is not compat_str:
  1729. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1730. self.report_warning(
  1731. 'Your Python is broken! Update to a newer and supported version')
  1732. stdout_encoding = getattr(
  1733. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1734. encoding_str = (
  1735. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1736. locale.getpreferredencoding(),
  1737. sys.getfilesystemencoding(),
  1738. stdout_encoding,
  1739. self.get_encoding()))
  1740. write_string(encoding_str, encoding=None)
  1741. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1742. try:
  1743. sp = subprocess.Popen(
  1744. ['git', 'rev-parse', '--short', 'HEAD'],
  1745. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1746. cwd=os.path.dirname(os.path.abspath(__file__)))
  1747. out, err = sp.communicate()
  1748. out = out.decode().strip()
  1749. if re.match('[0-9a-f]+', out):
  1750. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1751. except Exception:
  1752. try:
  1753. sys.exc_clear()
  1754. except Exception:
  1755. pass
  1756. self._write_string('[debug] Python version %s - %s\n' % (
  1757. platform.python_version(), platform_name()))
  1758. exe_versions = FFmpegPostProcessor.get_versions(self)
  1759. exe_versions['rtmpdump'] = rtmpdump_version()
  1760. exe_str = ', '.join(
  1761. '%s %s' % (exe, v)
  1762. for exe, v in sorted(exe_versions.items())
  1763. if v
  1764. )
  1765. if not exe_str:
  1766. exe_str = 'none'
  1767. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1768. proxy_map = {}
  1769. for handler in self._opener.handlers:
  1770. if hasattr(handler, 'proxies'):
  1771. proxy_map.update(handler.proxies)
  1772. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1773. if self.params.get('call_home', False):
  1774. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1775. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1776. latest_version = self.urlopen(
  1777. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1778. if version_tuple(latest_version) > version_tuple(__version__):
  1779. self.report_warning(
  1780. 'You are using an outdated version (newest version: %s)! '
  1781. 'See https://yt-dl.org/update if you need help updating.' %
  1782. latest_version)
  1783. def _setup_opener(self):
  1784. timeout_val = self.params.get('socket_timeout')
  1785. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1786. opts_cookiefile = self.params.get('cookiefile')
  1787. opts_proxy = self.params.get('proxy')
  1788. if opts_cookiefile is None:
  1789. self.cookiejar = compat_cookiejar.CookieJar()
  1790. else:
  1791. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1792. opts_cookiefile)
  1793. if os.access(opts_cookiefile, os.R_OK):
  1794. self.cookiejar.load()
  1795. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  1796. if opts_proxy is not None:
  1797. if opts_proxy == '':
  1798. proxies = {}
  1799. else:
  1800. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1801. else:
  1802. proxies = compat_urllib_request.getproxies()
  1803. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1804. if 'http' in proxies and 'https' not in proxies:
  1805. proxies['https'] = proxies['http']
  1806. proxy_handler = PerRequestProxyHandler(proxies)
  1807. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1808. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1809. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1810. data_handler = compat_urllib_request_DataHandler()
  1811. # When passing our own FileHandler instance, build_opener won't add the
  1812. # default FileHandler and allows us to disable the file protocol, which
  1813. # can be used for malicious purposes (see
  1814. # https://github.com/rg3/youtube-dl/issues/8227)
  1815. file_handler = compat_urllib_request.FileHandler()
  1816. def file_open(*args, **kwargs):
  1817. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  1818. file_handler.file_open = file_open
  1819. opener = compat_urllib_request.build_opener(
  1820. proxy_handler, https_handler, cookie_processor, ydlh, data_handler, file_handler)
  1821. # Delete the default user-agent header, which would otherwise apply in
  1822. # cases where our custom HTTP handler doesn't come into play
  1823. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1824. opener.addheaders = []
  1825. self._opener = opener
  1826. def encode(self, s):
  1827. if isinstance(s, bytes):
  1828. return s # Already encoded
  1829. try:
  1830. return s.encode(self.get_encoding())
  1831. except UnicodeEncodeError as err:
  1832. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1833. raise
  1834. def get_encoding(self):
  1835. encoding = self.params.get('encoding')
  1836. if encoding is None:
  1837. encoding = preferredencoding()
  1838. return encoding
  1839. def _write_thumbnails(self, info_dict, filename):
  1840. if self.params.get('writethumbnail', False):
  1841. thumbnails = info_dict.get('thumbnails')
  1842. if thumbnails:
  1843. thumbnails = [thumbnails[-1]]
  1844. elif self.params.get('write_all_thumbnails', False):
  1845. thumbnails = info_dict.get('thumbnails')
  1846. else:
  1847. return
  1848. if not thumbnails:
  1849. # No thumbnails present, so return immediately
  1850. return
  1851. for t in thumbnails:
  1852. thumb_ext = determine_ext(t['url'], 'jpg')
  1853. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1854. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1855. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1856. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1857. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1858. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1859. else:
  1860. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1861. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1862. try:
  1863. uf = self.urlopen(t['url'])
  1864. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  1865. shutil.copyfileobj(uf, thumbf)
  1866. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1867. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1868. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1869. self.report_warning('Unable to download thumbnail "%s": %s' %
  1870. (t['url'], error_to_compat_str(err)))