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.

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