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.

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