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.

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