選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

2420 行
109KB

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