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.

2109 lines
94 KiB

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