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.

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