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.

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