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.

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