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.

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