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.

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