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.

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