You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2301 lines
104 KiB

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