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.

2018 lines
90 KiB

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