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.

2048 lines
91 KiB

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