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.

2407 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. if self.params.get('forcejson', False):
  775. self.to_stdout(json.dumps(ie_result))
  776. return ie_result
  777. if result_type == 'video':
  778. self.add_extra_info(ie_result, extra_info)
  779. return self.process_video_result(ie_result, download=download)
  780. elif result_type == 'url':
  781. # We have to add extra_info to the results because it may be
  782. # contained in a playlist
  783. return self.extract_info(ie_result['url'],
  784. download,
  785. ie_key=ie_result.get('ie_key'),
  786. extra_info=extra_info)
  787. elif result_type == 'url_transparent':
  788. # Use the information from the embedding page
  789. info = self.extract_info(
  790. ie_result['url'], ie_key=ie_result.get('ie_key'),
  791. extra_info=extra_info, download=False, process=False)
  792. # extract_info may return None when ignoreerrors is enabled and
  793. # extraction failed with an error, don't crash and return early
  794. # in this case
  795. if not info:
  796. return info
  797. force_properties = dict(
  798. (k, v) for k, v in ie_result.items() if v is not None)
  799. for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
  800. if f in force_properties:
  801. del force_properties[f]
  802. new_result = info.copy()
  803. new_result.update(force_properties)
  804. # Extracted info may not be a video result (i.e.
  805. # info.get('_type', 'video') != video) but rather an url or
  806. # url_transparent. In such cases outer metadata (from ie_result)
  807. # should be propagated to inner one (info). For this to happen
  808. # _type of info should be overridden with url_transparent. This
  809. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  810. if new_result.get('_type') == 'url':
  811. new_result['_type'] = 'url_transparent'
  812. return self.process_ie_result(
  813. new_result, download=download, extra_info=extra_info)
  814. elif result_type in ('playlist', 'multi_video'):
  815. # We process each entry in the playlist
  816. playlist = ie_result.get('title') or ie_result.get('id')
  817. self.to_screen('[download] Downloading playlist: %s' % playlist)
  818. playlist_results = []
  819. playliststart = self.params.get('playliststart', 1) - 1
  820. playlistend = self.params.get('playlistend')
  821. # For backwards compatibility, interpret -1 as whole list
  822. if playlistend == -1:
  823. playlistend = None
  824. playlistitems_str = self.params.get('playlist_items')
  825. playlistitems = None
  826. if playlistitems_str is not None:
  827. def iter_playlistitems(format):
  828. for string_segment in format.split(','):
  829. if '-' in string_segment:
  830. start, end = string_segment.split('-')
  831. for item in range(int(start), int(end) + 1):
  832. yield int(item)
  833. else:
  834. yield int(string_segment)
  835. playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
  836. ie_entries = ie_result['entries']
  837. def make_playlistitems_entries(list_ie_entries):
  838. num_entries = len(list_ie_entries)
  839. return [
  840. list_ie_entries[i - 1] for i in playlistitems
  841. if -num_entries <= i - 1 < num_entries]
  842. def report_download(num_entries):
  843. self.to_screen(
  844. '[%s] playlist %s: Downloading %d videos' %
  845. (ie_result['extractor'], playlist, num_entries))
  846. if isinstance(ie_entries, list):
  847. n_all_entries = len(ie_entries)
  848. if playlistitems:
  849. entries = make_playlistitems_entries(ie_entries)
  850. else:
  851. entries = ie_entries[playliststart:playlistend]
  852. n_entries = len(entries)
  853. self.to_screen(
  854. '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
  855. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  856. elif isinstance(ie_entries, PagedList):
  857. if playlistitems:
  858. entries = []
  859. for item in playlistitems:
  860. entries.extend(ie_entries.getslice(
  861. item - 1, item
  862. ))
  863. else:
  864. entries = ie_entries.getslice(
  865. playliststart, playlistend)
  866. n_entries = len(entries)
  867. report_download(n_entries)
  868. else: # iterable
  869. if playlistitems:
  870. entries = make_playlistitems_entries(list(itertools.islice(
  871. ie_entries, 0, max(playlistitems))))
  872. else:
  873. entries = list(itertools.islice(
  874. ie_entries, playliststart, playlistend))
  875. n_entries = len(entries)
  876. report_download(n_entries)
  877. if self.params.get('playlistreverse', False):
  878. entries = entries[::-1]
  879. if self.params.get('playlistrandom', False):
  880. random.shuffle(entries)
  881. x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
  882. for i, entry in enumerate(entries, 1):
  883. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  884. # This __x_forwarded_for_ip thing is a bit ugly but requires
  885. # minimal changes
  886. if x_forwarded_for:
  887. entry['__x_forwarded_for_ip'] = x_forwarded_for
  888. extra = {
  889. 'n_entries': n_entries,
  890. 'playlist': playlist,
  891. 'playlist_id': ie_result.get('id'),
  892. 'playlist_title': ie_result.get('title'),
  893. 'playlist_uploader': ie_result.get('uploader'),
  894. 'playlist_uploader_id': ie_result.get('uploader_id'),
  895. 'playlist_index': i + playliststart,
  896. 'extractor': ie_result['extractor'],
  897. 'webpage_url': ie_result['webpage_url'],
  898. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  899. 'extractor_key': ie_result['extractor_key'],
  900. }
  901. reason = self._match_entry(entry, incomplete=True)
  902. if reason is not None:
  903. self.to_screen('[download] ' + reason)
  904. continue
  905. entry_result = self.process_ie_result(entry,
  906. download=download,
  907. extra_info=extra)
  908. playlist_results.append(entry_result)
  909. ie_result['entries'] = playlist_results
  910. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  911. return ie_result
  912. elif result_type == 'compat_list':
  913. self.report_warning(
  914. 'Extractor %s returned a compat_list result. '
  915. 'It needs to be updated.' % ie_result.get('extractor'))
  916. def _fixup(r):
  917. self.add_extra_info(
  918. r,
  919. {
  920. 'extractor': ie_result['extractor'],
  921. 'webpage_url': ie_result['webpage_url'],
  922. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  923. 'extractor_key': ie_result['extractor_key'],
  924. }
  925. )
  926. return r
  927. ie_result['entries'] = [
  928. self.process_ie_result(_fixup(r), download, extra_info)
  929. for r in ie_result['entries']
  930. ]
  931. return ie_result
  932. else:
  933. raise Exception('Invalid result type: %s' % result_type)
  934. def _build_format_filter(self, filter_spec):
  935. " Returns a function to filter the formats according to the filter_spec "
  936. OPERATORS = {
  937. '<': operator.lt,
  938. '<=': operator.le,
  939. '>': operator.gt,
  940. '>=': operator.ge,
  941. '=': operator.eq,
  942. '!=': operator.ne,
  943. }
  944. operator_rex = re.compile(r'''(?x)\s*
  945. (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
  946. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  947. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  948. $
  949. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  950. m = operator_rex.search(filter_spec)
  951. if m:
  952. try:
  953. comparison_value = int(m.group('value'))
  954. except ValueError:
  955. comparison_value = parse_filesize(m.group('value'))
  956. if comparison_value is None:
  957. comparison_value = parse_filesize(m.group('value') + 'B')
  958. if comparison_value is None:
  959. raise ValueError(
  960. 'Invalid value %r in format specification %r' % (
  961. m.group('value'), filter_spec))
  962. op = OPERATORS[m.group('op')]
  963. if not m:
  964. STR_OPERATORS = {
  965. '=': operator.eq,
  966. '^=': lambda attr, value: attr.startswith(value),
  967. '$=': lambda attr, value: attr.endswith(value),
  968. '*=': lambda attr, value: value in attr,
  969. }
  970. str_operator_rex = re.compile(r'''(?x)
  971. \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id)
  972. \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
  973. \s*(?P<value>[a-zA-Z0-9._-]+)
  974. \s*$
  975. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  976. m = str_operator_rex.search(filter_spec)
  977. if m:
  978. comparison_value = m.group('value')
  979. str_op = STR_OPERATORS[m.group('op')]
  980. if m.group('negation'):
  981. op = lambda attr, value: not str_op(attr, value)
  982. else:
  983. op = str_op
  984. if not m:
  985. raise ValueError('Invalid filter specification %r' % filter_spec)
  986. def _filter(f):
  987. actual_value = f.get(m.group('key'))
  988. if actual_value is None:
  989. return m.group('none_inclusive')
  990. return op(actual_value, comparison_value)
  991. return _filter
  992. def _default_format_spec(self, info_dict, download=True):
  993. def can_merge():
  994. merger = FFmpegMergerPP(self)
  995. return merger.available and merger.can_merge()
  996. def prefer_best():
  997. if self.params.get('simulate', False):
  998. return False
  999. if not download:
  1000. return False
  1001. if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
  1002. return True
  1003. if info_dict.get('is_live'):
  1004. return True
  1005. if not can_merge():
  1006. return True
  1007. return False
  1008. req_format_list = ['bestvideo+bestaudio', 'best']
  1009. if prefer_best():
  1010. req_format_list.reverse()
  1011. return '/'.join(req_format_list)
  1012. def build_format_selector(self, format_spec):
  1013. def syntax_error(note, start):
  1014. message = (
  1015. 'Invalid format specification: '
  1016. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  1017. return SyntaxError(message)
  1018. PICKFIRST = 'PICKFIRST'
  1019. MERGE = 'MERGE'
  1020. SINGLE = 'SINGLE'
  1021. GROUP = 'GROUP'
  1022. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  1023. def _parse_filter(tokens):
  1024. filter_parts = []
  1025. for type, string, start, _, _ in tokens:
  1026. if type == tokenize.OP and string == ']':
  1027. return ''.join(filter_parts)
  1028. else:
  1029. filter_parts.append(string)
  1030. def _remove_unused_ops(tokens):
  1031. # Remove operators that we don't use and join them with the surrounding strings
  1032. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  1033. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  1034. last_string, last_start, last_end, last_line = None, None, None, None
  1035. for type, string, start, end, line in tokens:
  1036. if type == tokenize.OP and string == '[':
  1037. if last_string:
  1038. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1039. last_string = None
  1040. yield type, string, start, end, line
  1041. # everything inside brackets will be handled by _parse_filter
  1042. for type, string, start, end, line in tokens:
  1043. yield type, string, start, end, line
  1044. if type == tokenize.OP and string == ']':
  1045. break
  1046. elif type == tokenize.OP and string in ALLOWED_OPS:
  1047. if last_string:
  1048. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1049. last_string = None
  1050. yield type, string, start, end, line
  1051. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  1052. if not last_string:
  1053. last_string = string
  1054. last_start = start
  1055. last_end = end
  1056. else:
  1057. last_string += string
  1058. if last_string:
  1059. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1060. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  1061. selectors = []
  1062. current_selector = None
  1063. for type, string, start, _, _ in tokens:
  1064. # ENCODING is only defined in python 3.x
  1065. if type == getattr(tokenize, 'ENCODING', None):
  1066. continue
  1067. elif type in [tokenize.NAME, tokenize.NUMBER]:
  1068. current_selector = FormatSelector(SINGLE, string, [])
  1069. elif type == tokenize.OP:
  1070. if string == ')':
  1071. if not inside_group:
  1072. # ')' will be handled by the parentheses group
  1073. tokens.restore_last_token()
  1074. break
  1075. elif inside_merge and string in ['/', ',']:
  1076. tokens.restore_last_token()
  1077. break
  1078. elif inside_choice and string == ',':
  1079. tokens.restore_last_token()
  1080. break
  1081. elif string == ',':
  1082. if not current_selector:
  1083. raise syntax_error('"," must follow a format selector', start)
  1084. selectors.append(current_selector)
  1085. current_selector = None
  1086. elif string == '/':
  1087. if not current_selector:
  1088. raise syntax_error('"/" must follow a format selector', start)
  1089. first_choice = current_selector
  1090. second_choice = _parse_format_selection(tokens, inside_choice=True)
  1091. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  1092. elif string == '[':
  1093. if not current_selector:
  1094. current_selector = FormatSelector(SINGLE, 'best', [])
  1095. format_filter = _parse_filter(tokens)
  1096. current_selector.filters.append(format_filter)
  1097. elif string == '(':
  1098. if current_selector:
  1099. raise syntax_error('Unexpected "("', start)
  1100. group = _parse_format_selection(tokens, inside_group=True)
  1101. current_selector = FormatSelector(GROUP, group, [])
  1102. elif string == '+':
  1103. video_selector = current_selector
  1104. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  1105. if not video_selector or not audio_selector:
  1106. raise syntax_error('"+" must be between two format selectors', start)
  1107. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  1108. else:
  1109. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  1110. elif type == tokenize.ENDMARKER:
  1111. break
  1112. if current_selector:
  1113. selectors.append(current_selector)
  1114. return selectors
  1115. def _build_selector_function(selector):
  1116. if isinstance(selector, list):
  1117. fs = [_build_selector_function(s) for s in selector]
  1118. def selector_function(ctx):
  1119. for f in fs:
  1120. for format in f(ctx):
  1121. yield format
  1122. return selector_function
  1123. elif selector.type == GROUP:
  1124. selector_function = _build_selector_function(selector.selector)
  1125. elif selector.type == PICKFIRST:
  1126. fs = [_build_selector_function(s) for s in selector.selector]
  1127. def selector_function(ctx):
  1128. for f in fs:
  1129. picked_formats = list(f(ctx))
  1130. if picked_formats:
  1131. return picked_formats
  1132. return []
  1133. elif selector.type == SINGLE:
  1134. format_spec = selector.selector
  1135. def selector_function(ctx):
  1136. formats = list(ctx['formats'])
  1137. if not formats:
  1138. return
  1139. if format_spec == 'all':
  1140. for f in formats:
  1141. yield f
  1142. elif format_spec in ['best', 'worst', None]:
  1143. format_idx = 0 if format_spec == 'worst' else -1
  1144. audiovideo_formats = [
  1145. f for f in formats
  1146. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  1147. if audiovideo_formats:
  1148. yield audiovideo_formats[format_idx]
  1149. # for extractors with incomplete formats (audio only (soundcloud)
  1150. # or video only (imgur)) we will fallback to best/worst
  1151. # {video,audio}-only format
  1152. elif ctx['incomplete_formats']:
  1153. yield formats[format_idx]
  1154. elif format_spec == 'bestaudio':
  1155. audio_formats = [
  1156. f for f in formats
  1157. if f.get('vcodec') == 'none']
  1158. if audio_formats:
  1159. yield audio_formats[-1]
  1160. elif format_spec == 'worstaudio':
  1161. audio_formats = [
  1162. f for f in formats
  1163. if f.get('vcodec') == 'none']
  1164. if audio_formats:
  1165. yield audio_formats[0]
  1166. elif format_spec == 'bestvideo':
  1167. video_formats = [
  1168. f for f in formats
  1169. if f.get('acodec') == 'none']
  1170. if video_formats:
  1171. yield video_formats[-1]
  1172. elif format_spec == 'worstvideo':
  1173. video_formats = [
  1174. f for f in formats
  1175. if f.get('acodec') == 'none']
  1176. if video_formats:
  1177. yield video_formats[0]
  1178. else:
  1179. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1180. if format_spec in extensions:
  1181. filter_f = lambda f: f['ext'] == format_spec
  1182. else:
  1183. filter_f = lambda f: f['format_id'] == format_spec
  1184. matches = list(filter(filter_f, formats))
  1185. if matches:
  1186. yield matches[-1]
  1187. elif selector.type == MERGE:
  1188. def _merge(formats_info):
  1189. format_1, format_2 = [f['format_id'] for f in formats_info]
  1190. # The first format must contain the video and the
  1191. # second the audio
  1192. if formats_info[0].get('vcodec') == 'none':
  1193. self.report_error('The first format must '
  1194. 'contain the video, try using '
  1195. '"-f %s+%s"' % (format_2, format_1))
  1196. return
  1197. # Formats must be opposite (video+audio)
  1198. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1199. self.report_error(
  1200. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1201. % (format_1, format_2))
  1202. return
  1203. output_ext = (
  1204. formats_info[0]['ext']
  1205. if self.params.get('merge_output_format') is None
  1206. else self.params['merge_output_format'])
  1207. return {
  1208. 'requested_formats': formats_info,
  1209. 'format': '%s+%s' % (formats_info[0].get('format'),
  1210. formats_info[1].get('format')),
  1211. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1212. formats_info[1].get('format_id')),
  1213. 'width': formats_info[0].get('width'),
  1214. 'height': formats_info[0].get('height'),
  1215. 'resolution': formats_info[0].get('resolution'),
  1216. 'fps': formats_info[0].get('fps'),
  1217. 'vcodec': formats_info[0].get('vcodec'),
  1218. 'vbr': formats_info[0].get('vbr'),
  1219. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1220. 'acodec': formats_info[1].get('acodec'),
  1221. 'abr': formats_info[1].get('abr'),
  1222. 'ext': output_ext,
  1223. }
  1224. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1225. def selector_function(ctx):
  1226. for pair in itertools.product(
  1227. video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
  1228. yield _merge(pair)
  1229. filters = [self._build_format_filter(f) for f in selector.filters]
  1230. def final_selector(ctx):
  1231. ctx_copy = copy.deepcopy(ctx)
  1232. for _filter in filters:
  1233. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  1234. return selector_function(ctx_copy)
  1235. return final_selector
  1236. stream = io.BytesIO(format_spec.encode('utf-8'))
  1237. try:
  1238. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1239. except tokenize.TokenError:
  1240. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1241. class TokenIterator(object):
  1242. def __init__(self, tokens):
  1243. self.tokens = tokens
  1244. self.counter = 0
  1245. def __iter__(self):
  1246. return self
  1247. def __next__(self):
  1248. if self.counter >= len(self.tokens):
  1249. raise StopIteration()
  1250. value = self.tokens[self.counter]
  1251. self.counter += 1
  1252. return value
  1253. next = __next__
  1254. def restore_last_token(self):
  1255. self.counter -= 1
  1256. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1257. return _build_selector_function(parsed_selector)
  1258. def _calc_headers(self, info_dict):
  1259. res = std_headers.copy()
  1260. add_headers = info_dict.get('http_headers')
  1261. if add_headers:
  1262. res.update(add_headers)
  1263. cookies = self._calc_cookies(info_dict)
  1264. if cookies:
  1265. res['Cookie'] = cookies
  1266. if 'X-Forwarded-For' not in res:
  1267. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  1268. if x_forwarded_for_ip:
  1269. res['X-Forwarded-For'] = x_forwarded_for_ip
  1270. return res
  1271. def _calc_cookies(self, info_dict):
  1272. pr = sanitized_Request(info_dict['url'])
  1273. self.cookiejar.add_cookie_header(pr)
  1274. return pr.get_header('Cookie')
  1275. def process_video_result(self, info_dict, download=True):
  1276. assert info_dict.get('_type', 'video') == 'video'
  1277. if 'id' not in info_dict:
  1278. raise ExtractorError('Missing "id" field in extractor result')
  1279. if 'title' not in info_dict:
  1280. raise ExtractorError('Missing "title" field in extractor result')
  1281. def report_force_conversion(field, field_not, conversion):
  1282. self.report_warning(
  1283. '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
  1284. % (field, field_not, conversion))
  1285. def sanitize_string_field(info, string_field):
  1286. field = info.get(string_field)
  1287. if field is None or isinstance(field, compat_str):
  1288. return
  1289. report_force_conversion(string_field, 'a string', 'string')
  1290. info[string_field] = compat_str(field)
  1291. def sanitize_numeric_fields(info):
  1292. for numeric_field in self._NUMERIC_FIELDS:
  1293. field = info.get(numeric_field)
  1294. if field is None or isinstance(field, compat_numeric_types):
  1295. continue
  1296. report_force_conversion(numeric_field, 'numeric', 'int')
  1297. info[numeric_field] = int_or_none(field)
  1298. sanitize_string_field(info_dict, 'id')
  1299. sanitize_numeric_fields(info_dict)
  1300. if 'playlist' not in info_dict:
  1301. # It isn't part of a playlist
  1302. info_dict['playlist'] = None
  1303. info_dict['playlist_index'] = None
  1304. thumbnails = info_dict.get('thumbnails')
  1305. if thumbnails is None:
  1306. thumbnail = info_dict.get('thumbnail')
  1307. if thumbnail:
  1308. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1309. if thumbnails:
  1310. thumbnails.sort(key=lambda t: (
  1311. t.get('preference') if t.get('preference') is not None else -1,
  1312. t.get('width') if t.get('width') is not None else -1,
  1313. t.get('height') if t.get('height') is not None else -1,
  1314. t.get('id') if t.get('id') is not None else '', t.get('url')))
  1315. for i, t in enumerate(thumbnails):
  1316. t['url'] = sanitize_url(t['url'])
  1317. if t.get('width') and t.get('height'):
  1318. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1319. if t.get('id') is None:
  1320. t['id'] = '%d' % i
  1321. if self.params.get('list_thumbnails'):
  1322. self.list_thumbnails(info_dict)
  1323. return
  1324. thumbnail = info_dict.get('thumbnail')
  1325. if thumbnail:
  1326. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1327. elif thumbnails:
  1328. info_dict['thumbnail'] = thumbnails[-1]['url']
  1329. if 'display_id' not in info_dict and 'id' in info_dict:
  1330. info_dict['display_id'] = info_dict['id']
  1331. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  1332. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1333. # see http://bugs.python.org/issue1646728)
  1334. try:
  1335. upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
  1336. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  1337. except (ValueError, OverflowError, OSError):
  1338. pass
  1339. # Auto generate title fields corresponding to the *_number fields when missing
  1340. # in order to always have clean titles. This is very common for TV series.
  1341. for field in ('chapter', 'season', 'episode'):
  1342. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1343. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1344. for cc_kind in ('subtitles', 'automatic_captions'):
  1345. cc = info_dict.get(cc_kind)
  1346. if cc:
  1347. for _, subtitle in cc.items():
  1348. for subtitle_format in subtitle:
  1349. if subtitle_format.get('url'):
  1350. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1351. if subtitle_format.get('ext') is None:
  1352. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1353. automatic_captions = info_dict.get('automatic_captions')
  1354. subtitles = info_dict.get('subtitles')
  1355. if self.params.get('listsubtitles', False):
  1356. if 'automatic_captions' in info_dict:
  1357. self.list_subtitles(
  1358. info_dict['id'], automatic_captions, 'automatic captions')
  1359. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1360. return
  1361. info_dict['requested_subtitles'] = self.process_subtitles(
  1362. info_dict['id'], subtitles, automatic_captions)
  1363. # We now pick which formats have to be downloaded
  1364. if info_dict.get('formats') is None:
  1365. # There's only one format available
  1366. formats = [info_dict]
  1367. else:
  1368. formats = info_dict['formats']
  1369. if not formats:
  1370. raise ExtractorError('No video formats found!')
  1371. def is_wellformed(f):
  1372. url = f.get('url')
  1373. if not url:
  1374. self.report_warning(
  1375. '"url" field is missing or empty - skipping format, '
  1376. 'there is an error in extractor')
  1377. return False
  1378. if isinstance(url, bytes):
  1379. sanitize_string_field(f, 'url')
  1380. return True
  1381. # Filter out malformed formats for better extraction robustness
  1382. formats = list(filter(is_wellformed, formats))
  1383. formats_dict = {}
  1384. # We check that all the formats have the format and format_id fields
  1385. for i, format in enumerate(formats):
  1386. sanitize_string_field(format, 'format_id')
  1387. sanitize_numeric_fields(format)
  1388. format['url'] = sanitize_url(format['url'])
  1389. if not format.get('format_id'):
  1390. format['format_id'] = compat_str(i)
  1391. else:
  1392. # Sanitize format_id from characters used in format selector expression
  1393. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  1394. format_id = format['format_id']
  1395. if format_id not in formats_dict:
  1396. formats_dict[format_id] = []
  1397. formats_dict[format_id].append(format)
  1398. # Make sure all formats have unique format_id
  1399. for format_id, ambiguous_formats in formats_dict.items():
  1400. if len(ambiguous_formats) > 1:
  1401. for i, format in enumerate(ambiguous_formats):
  1402. format['format_id'] = '%s-%d' % (format_id, i)
  1403. for i, format in enumerate(formats):
  1404. if format.get('format') is None:
  1405. format['format'] = '{id} - {res}{note}'.format(
  1406. id=format['format_id'],
  1407. res=self.format_resolution(format),
  1408. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1409. )
  1410. # Automatically determine file extension if missing
  1411. if format.get('ext') is None:
  1412. format['ext'] = determine_ext(format['url']).lower()
  1413. # Automatically determine protocol if missing (useful for format
  1414. # selection purposes)
  1415. if format.get('protocol') is None:
  1416. format['protocol'] = determine_protocol(format)
  1417. # Add HTTP headers, so that external programs can use them from the
  1418. # json output
  1419. full_format_info = info_dict.copy()
  1420. full_format_info.update(format)
  1421. format['http_headers'] = self._calc_headers(full_format_info)
  1422. # Remove private housekeeping stuff
  1423. if '__x_forwarded_for_ip' in info_dict:
  1424. del info_dict['__x_forwarded_for_ip']
  1425. # TODO Central sorting goes here
  1426. if formats[0] is not info_dict:
  1427. # only set the 'formats' fields if the original info_dict list them
  1428. # otherwise we end up with a circular reference, the first (and unique)
  1429. # element in the 'formats' field in info_dict is info_dict itself,
  1430. # which can't be exported to json
  1431. info_dict['formats'] = formats
  1432. if self.params.get('listformats'):
  1433. self.list_formats(info_dict)
  1434. return
  1435. req_format = self.params.get('format')
  1436. if req_format is None:
  1437. req_format = self._default_format_spec(info_dict, download=download)
  1438. if self.params.get('verbose'):
  1439. self.to_stdout('[debug] Default format spec: %s' % req_format)
  1440. format_selector = self.build_format_selector(req_format)
  1441. # While in format selection we may need to have an access to the original
  1442. # format set in order to calculate some metrics or do some processing.
  1443. # For now we need to be able to guess whether original formats provided
  1444. # by extractor are incomplete or not (i.e. whether extractor provides only
  1445. # video-only or audio-only formats) for proper formats selection for
  1446. # extractors with such incomplete formats (see
  1447. # https://github.com/ytdl-org/youtube-dl/pull/5556).
  1448. # Since formats may be filtered during format selection and may not match
  1449. # the original formats the results may be incorrect. Thus original formats
  1450. # or pre-calculated metrics should be passed to format selection routines
  1451. # as well.
  1452. # We will pass a context object containing all necessary additional data
  1453. # instead of just formats.
  1454. # This fixes incorrect format selection issue (see
  1455. # https://github.com/ytdl-org/youtube-dl/issues/10083).
  1456. incomplete_formats = (
  1457. # All formats are video-only or
  1458. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
  1459. # all formats are audio-only
  1460. or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
  1461. ctx = {
  1462. 'formats': formats,
  1463. 'incomplete_formats': incomplete_formats,
  1464. }
  1465. formats_to_download = list(format_selector(ctx))
  1466. if not formats_to_download:
  1467. raise ExtractorError('requested format not available',
  1468. expected=True)
  1469. if download:
  1470. if len(formats_to_download) > 1:
  1471. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1472. for format in formats_to_download:
  1473. new_info = dict(info_dict)
  1474. new_info.update(format)
  1475. self.process_info(new_info)
  1476. # We update the info dict with the best quality format (backwards compatibility)
  1477. info_dict.update(formats_to_download[-1])
  1478. return info_dict
  1479. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1480. """Select the requested subtitles and their format"""
  1481. available_subs = {}
  1482. if normal_subtitles and self.params.get('writesubtitles'):
  1483. available_subs.update(normal_subtitles)
  1484. if automatic_captions and self.params.get('writeautomaticsub'):
  1485. for lang, cap_info in automatic_captions.items():
  1486. if lang not in available_subs:
  1487. available_subs[lang] = cap_info
  1488. if (not self.params.get('writesubtitles') and not
  1489. self.params.get('writeautomaticsub') or not
  1490. available_subs):
  1491. return None
  1492. if self.params.get('allsubtitles', False):
  1493. requested_langs = available_subs.keys()
  1494. else:
  1495. if self.params.get('subtitleslangs', False):
  1496. requested_langs = self.params.get('subtitleslangs')
  1497. elif 'en' in available_subs:
  1498. requested_langs = ['en']
  1499. else:
  1500. requested_langs = [list(available_subs.keys())[0]]
  1501. formats_query = self.params.get('subtitlesformat', 'best')
  1502. formats_preference = formats_query.split('/') if formats_query else []
  1503. subs = {}
  1504. for lang in requested_langs:
  1505. formats = available_subs.get(lang)
  1506. if formats is None:
  1507. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1508. continue
  1509. for ext in formats_preference:
  1510. if ext == 'best':
  1511. f = formats[-1]
  1512. break
  1513. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1514. if matches:
  1515. f = matches[-1]
  1516. break
  1517. else:
  1518. f = formats[-1]
  1519. self.report_warning(
  1520. 'No subtitle format found matching "%s" for language %s, '
  1521. 'using %s' % (formats_query, lang, f['ext']))
  1522. subs[lang] = f
  1523. return subs
  1524. def process_info(self, info_dict):
  1525. """Process a single resolved IE result."""
  1526. assert info_dict.get('_type', 'video') == 'video'
  1527. max_downloads = self.params.get('max_downloads')
  1528. if max_downloads is not None:
  1529. if self._num_downloads >= int(max_downloads):
  1530. raise MaxDownloadsReached()
  1531. info_dict['fulltitle'] = info_dict['title']
  1532. if len(info_dict['title']) > 200:
  1533. info_dict['title'] = info_dict['title'][:197] + '...'
  1534. if 'format' not in info_dict:
  1535. info_dict['format'] = info_dict['ext']
  1536. reason = self._match_entry(info_dict, incomplete=False)
  1537. if reason is not None:
  1538. self.to_screen('[download] ' + reason)
  1539. return
  1540. self._num_downloads += 1
  1541. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1542. # Forced printings
  1543. if self.params.get('forcetitle', False):
  1544. self.to_stdout(info_dict['fulltitle'])
  1545. if self.params.get('forceid', False):
  1546. self.to_stdout(info_dict['id'])
  1547. if self.params.get('forceurl', False):
  1548. if info_dict.get('requested_formats') is not None:
  1549. for f in info_dict['requested_formats']:
  1550. self.to_stdout(f['url'] + f.get('play_path', ''))
  1551. else:
  1552. # For RTMP URLs, also include the playpath
  1553. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1554. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1555. self.to_stdout(info_dict['thumbnail'])
  1556. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1557. self.to_stdout(info_dict['description'])
  1558. if self.params.get('forcefilename', False) and filename is not None:
  1559. self.to_stdout(filename)
  1560. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1561. self.to_stdout(formatSeconds(info_dict['duration']))
  1562. if self.params.get('forceformat', False):
  1563. self.to_stdout(info_dict['format'])
  1564. if self.params.get('forcejson', False):
  1565. self.to_stdout(json.dumps(info_dict))
  1566. # Do nothing else if in simulate mode
  1567. if self.params.get('simulate', False):
  1568. return
  1569. if filename is None:
  1570. return
  1571. def ensure_dir_exists(path):
  1572. try:
  1573. dn = os.path.dirname(path)
  1574. if dn and not os.path.exists(dn):
  1575. os.makedirs(dn)
  1576. return True
  1577. except (OSError, IOError) as err:
  1578. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1579. return False
  1580. if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
  1581. return
  1582. if self.params.get('writedescription', False):
  1583. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1584. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1585. self.to_screen('[info] Video description is already present')
  1586. elif info_dict.get('description') is None:
  1587. self.report_warning('There\'s no description to write.')
  1588. else:
  1589. try:
  1590. self.to_screen('[info] Writing video description to: ' + descfn)
  1591. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1592. descfile.write(info_dict['description'])
  1593. except (OSError, IOError):
  1594. self.report_error('Cannot write description file ' + descfn)
  1595. return
  1596. if self.params.get('writeannotations', False):
  1597. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1598. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1599. self.to_screen('[info] Video annotations are already present')
  1600. else:
  1601. try:
  1602. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1603. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1604. annofile.write(info_dict['annotations'])
  1605. except (KeyError, TypeError):
  1606. self.report_warning('There are no annotations to write.')
  1607. except (OSError, IOError):
  1608. self.report_error('Cannot write annotations file: ' + annofn)
  1609. return
  1610. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1611. self.params.get('writeautomaticsub')])
  1612. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1613. # subtitles download errors are already managed as troubles in relevant IE
  1614. # that way it will silently go on when used with unsupporting IE
  1615. subtitles = info_dict['requested_subtitles']
  1616. ie = self.get_info_extractor(info_dict['extractor_key'])
  1617. for sub_lang, sub_info in subtitles.items():
  1618. sub_format = sub_info['ext']
  1619. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1620. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1621. self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
  1622. else:
  1623. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1624. if sub_info.get('data') is not None:
  1625. try:
  1626. # Use newline='' to prevent conversion of newline characters
  1627. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  1628. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
  1629. subfile.write(sub_info['data'])
  1630. except (OSError, IOError):
  1631. self.report_error('Cannot write subtitles file ' + sub_filename)
  1632. return
  1633. else:
  1634. try:
  1635. sub_data = ie._request_webpage(
  1636. sub_info['url'], info_dict['id'], note=False).read()
  1637. with io.open(encodeFilename(sub_filename), 'wb') as subfile:
  1638. subfile.write(sub_data)
  1639. except (ExtractorError, IOError, OSError, ValueError) as err:
  1640. self.report_warning('Unable to download subtitle for "%s": %s' %
  1641. (sub_lang, error_to_compat_str(err)))
  1642. continue
  1643. if self.params.get('writeinfojson', False):
  1644. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1645. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1646. self.to_screen('[info] Video description metadata is already present')
  1647. else:
  1648. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1649. try:
  1650. write_json_file(self.filter_requested_info(info_dict), infofn)
  1651. except (OSError, IOError):
  1652. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1653. return
  1654. self._write_thumbnails(info_dict, filename)
  1655. if not self.params.get('skip_download', False):
  1656. try:
  1657. def dl(name, info):
  1658. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1659. for ph in self._progress_hooks:
  1660. fd.add_progress_hook(ph)
  1661. if self.params.get('verbose'):
  1662. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1663. return fd.download(name, info)
  1664. if info_dict.get('requested_formats') is not None:
  1665. downloaded = []
  1666. success = True
  1667. merger = FFmpegMergerPP(self)
  1668. if not merger.available:
  1669. postprocessors = []
  1670. self.report_warning('You have requested multiple '
  1671. 'formats but ffmpeg or avconv are not installed.'
  1672. ' The formats won\'t be merged.')
  1673. else:
  1674. postprocessors = [merger]
  1675. def compatible_formats(formats):
  1676. video, audio = formats
  1677. # Check extension
  1678. video_ext, audio_ext = video.get('ext'), audio.get('ext')
  1679. if video_ext and audio_ext:
  1680. COMPATIBLE_EXTS = (
  1681. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
  1682. ('webm')
  1683. )
  1684. for exts in COMPATIBLE_EXTS:
  1685. if video_ext in exts and audio_ext in exts:
  1686. return True
  1687. # TODO: Check acodec/vcodec
  1688. return False
  1689. filename_real_ext = os.path.splitext(filename)[1][1:]
  1690. filename_wo_ext = (
  1691. os.path.splitext(filename)[0]
  1692. if filename_real_ext == info_dict['ext']
  1693. else filename)
  1694. requested_formats = info_dict['requested_formats']
  1695. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1696. info_dict['ext'] = 'mkv'
  1697. self.report_warning(
  1698. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1699. # Ensure filename always has a correct extension for successful merge
  1700. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1701. if os.path.exists(encodeFilename(filename)):
  1702. self.to_screen(
  1703. '[download] %s has already been downloaded and '
  1704. 'merged' % filename)
  1705. else:
  1706. for f in requested_formats:
  1707. new_info = dict(info_dict)
  1708. new_info.update(f)
  1709. fname = prepend_extension(
  1710. self.prepare_filename(new_info),
  1711. 'f%s' % f['format_id'], new_info['ext'])
  1712. if not ensure_dir_exists(fname):
  1713. return
  1714. downloaded.append(fname)
  1715. partial_success = dl(fname, new_info)
  1716. success = success and partial_success
  1717. info_dict['__postprocessors'] = postprocessors
  1718. info_dict['__files_to_merge'] = downloaded
  1719. else:
  1720. # Just a single file
  1721. success = dl(filename, info_dict)
  1722. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1723. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1724. return
  1725. except (OSError, IOError) as err:
  1726. raise UnavailableVideoError(err)
  1727. except (ContentTooShortError, ) as err:
  1728. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1729. return
  1730. if success and filename != '-':
  1731. # Fixup content
  1732. fixup_policy = self.params.get('fixup')
  1733. if fixup_policy is None:
  1734. fixup_policy = 'detect_or_warn'
  1735. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1736. stretched_ratio = info_dict.get('stretched_ratio')
  1737. if stretched_ratio is not None and stretched_ratio != 1:
  1738. if fixup_policy == 'warn':
  1739. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1740. info_dict['id'], stretched_ratio))
  1741. elif fixup_policy == 'detect_or_warn':
  1742. stretched_pp = FFmpegFixupStretchedPP(self)
  1743. if stretched_pp.available:
  1744. info_dict.setdefault('__postprocessors', [])
  1745. info_dict['__postprocessors'].append(stretched_pp)
  1746. else:
  1747. self.report_warning(
  1748. '%s: Non-uniform pixel ratio (%s). %s'
  1749. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1750. else:
  1751. assert fixup_policy in ('ignore', 'never')
  1752. if (info_dict.get('requested_formats') is None
  1753. and info_dict.get('container') == 'm4a_dash'):
  1754. if fixup_policy == 'warn':
  1755. self.report_warning(
  1756. '%s: writing DASH m4a. '
  1757. 'Only some players support this container.'
  1758. % info_dict['id'])
  1759. elif fixup_policy == 'detect_or_warn':
  1760. fixup_pp = FFmpegFixupM4aPP(self)
  1761. if fixup_pp.available:
  1762. info_dict.setdefault('__postprocessors', [])
  1763. info_dict['__postprocessors'].append(fixup_pp)
  1764. else:
  1765. self.report_warning(
  1766. '%s: writing DASH m4a. '
  1767. 'Only some players support this container. %s'
  1768. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1769. else:
  1770. assert fixup_policy in ('ignore', 'never')
  1771. if (info_dict.get('protocol') == 'm3u8_native'
  1772. or info_dict.get('protocol') == 'm3u8'
  1773. and self.params.get('hls_prefer_native')):
  1774. if fixup_policy == 'warn':
  1775. self.report_warning('%s: malformed AAC bitstream detected.' % (
  1776. info_dict['id']))
  1777. elif fixup_policy == 'detect_or_warn':
  1778. fixup_pp = FFmpegFixupM3u8PP(self)
  1779. if fixup_pp.available:
  1780. info_dict.setdefault('__postprocessors', [])
  1781. info_dict['__postprocessors'].append(fixup_pp)
  1782. else:
  1783. self.report_warning(
  1784. '%s: malformed AAC bitstream detected. %s'
  1785. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1786. else:
  1787. assert fixup_policy in ('ignore', 'never')
  1788. try:
  1789. self.post_process(filename, info_dict)
  1790. except (PostProcessingError) as err:
  1791. self.report_error('postprocessing: %s' % str(err))
  1792. return
  1793. self.record_download_archive(info_dict)
  1794. def download(self, url_list):
  1795. """Download a given list of URLs."""
  1796. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1797. if (len(url_list) > 1
  1798. and outtmpl != '-'
  1799. and '%' not in outtmpl
  1800. and self.params.get('max_downloads') != 1):
  1801. raise SameFileError(outtmpl)
  1802. for url in url_list:
  1803. try:
  1804. # It also downloads the videos
  1805. res = self.extract_info(
  1806. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1807. except UnavailableVideoError:
  1808. self.report_error('unable to download video')
  1809. except MaxDownloadsReached:
  1810. self.to_screen('[info] Maximum number of downloaded files reached.')
  1811. raise
  1812. else:
  1813. if self.params.get('dump_single_json', False):
  1814. self.to_stdout(json.dumps(res))
  1815. return self._download_retcode
  1816. def download_with_info_file(self, info_filename):
  1817. with contextlib.closing(fileinput.FileInput(
  1818. [info_filename], mode='r',
  1819. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1820. # FileInput doesn't have a read method, we can't call json.load
  1821. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1822. try:
  1823. self.process_ie_result(info, download=True)
  1824. except DownloadError:
  1825. webpage_url = info.get('webpage_url')
  1826. if webpage_url is not None:
  1827. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1828. return self.download([webpage_url])
  1829. else:
  1830. raise
  1831. return self._download_retcode
  1832. @staticmethod
  1833. def filter_requested_info(info_dict):
  1834. return dict(
  1835. (k, v) for k, v in info_dict.items()
  1836. if k not in ['requested_formats', 'requested_subtitles'])
  1837. def post_process(self, filename, ie_info):
  1838. """Run all the postprocessors on the given file."""
  1839. info = dict(ie_info)
  1840. info['filepath'] = filename
  1841. pps_chain = []
  1842. if ie_info.get('__postprocessors') is not None:
  1843. pps_chain.extend(ie_info['__postprocessors'])
  1844. pps_chain.extend(self._pps)
  1845. for pp in pps_chain:
  1846. files_to_delete = []
  1847. try:
  1848. files_to_delete, info = pp.run(info)
  1849. except PostProcessingError as e:
  1850. self.report_error(e.msg)
  1851. if files_to_delete and not self.params.get('keepvideo', False):
  1852. for old_filename in files_to_delete:
  1853. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1854. try:
  1855. os.remove(encodeFilename(old_filename))
  1856. except (IOError, OSError):
  1857. self.report_warning('Unable to remove downloaded original file')
  1858. def _make_archive_id(self, info_dict):
  1859. video_id = info_dict.get('id')
  1860. if not video_id:
  1861. return
  1862. # Future-proof against any change in case
  1863. # and backwards compatibility with prior versions
  1864. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  1865. if extractor is None:
  1866. url = str_or_none(info_dict.get('url'))
  1867. if not url:
  1868. return
  1869. # Try to find matching extractor for the URL and take its ie_key
  1870. for ie in self._ies:
  1871. if ie.suitable(url):
  1872. extractor = ie.ie_key()
  1873. break
  1874. else:
  1875. return
  1876. return extractor.lower() + ' ' + video_id
  1877. def in_download_archive(self, info_dict):
  1878. fn = self.params.get('download_archive')
  1879. if fn is None:
  1880. return False
  1881. vid_id = self._make_archive_id(info_dict)
  1882. if not vid_id:
  1883. return False # Incomplete video information
  1884. try:
  1885. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1886. for line in archive_file:
  1887. if line.strip() == vid_id:
  1888. return True
  1889. except IOError as ioe:
  1890. if ioe.errno != errno.ENOENT:
  1891. raise
  1892. return False
  1893. def record_download_archive(self, info_dict):
  1894. fn = self.params.get('download_archive')
  1895. if fn is None:
  1896. return
  1897. vid_id = self._make_archive_id(info_dict)
  1898. assert vid_id
  1899. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1900. archive_file.write(vid_id + '\n')
  1901. @staticmethod
  1902. def format_resolution(format, default='unknown'):
  1903. if format.get('vcodec') == 'none':
  1904. return 'audio only'
  1905. if format.get('resolution') is not None:
  1906. return format['resolution']
  1907. if format.get('height') is not None:
  1908. if format.get('width') is not None:
  1909. res = '%sx%s' % (format['width'], format['height'])
  1910. else:
  1911. res = '%sp' % format['height']
  1912. elif format.get('width') is not None:
  1913. res = '%dx?' % format['width']
  1914. else:
  1915. res = default
  1916. return res
  1917. def _format_note(self, fdict):
  1918. res = ''
  1919. if fdict.get('ext') in ['f4f', 'f4m']:
  1920. res += '(unsupported) '
  1921. if fdict.get('language'):
  1922. if res:
  1923. res += ' '
  1924. res += '[%s] ' % fdict['language']
  1925. if fdict.get('format_note') is not None:
  1926. res += fdict['format_note'] + ' '
  1927. if fdict.get('tbr') is not None:
  1928. res += '%4dk ' % fdict['tbr']
  1929. if fdict.get('container') is not None:
  1930. if res:
  1931. res += ', '
  1932. res += '%s container' % fdict['container']
  1933. if (fdict.get('vcodec') is not None
  1934. and fdict.get('vcodec') != 'none'):
  1935. if res:
  1936. res += ', '
  1937. res += fdict['vcodec']
  1938. if fdict.get('vbr') is not None:
  1939. res += '@'
  1940. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1941. res += 'video@'
  1942. if fdict.get('vbr') is not None:
  1943. res += '%4dk' % fdict['vbr']
  1944. if fdict.get('fps') is not None:
  1945. if res:
  1946. res += ', '
  1947. res += '%sfps' % fdict['fps']
  1948. if fdict.get('acodec') is not None:
  1949. if res:
  1950. res += ', '
  1951. if fdict['acodec'] == 'none':
  1952. res += 'video only'
  1953. else:
  1954. res += '%-5s' % fdict['acodec']
  1955. elif fdict.get('abr') is not None:
  1956. if res:
  1957. res += ', '
  1958. res += 'audio'
  1959. if fdict.get('abr') is not None:
  1960. res += '@%3dk' % fdict['abr']
  1961. if fdict.get('asr') is not None:
  1962. res += ' (%5dHz)' % fdict['asr']
  1963. if fdict.get('filesize') is not None:
  1964. if res:
  1965. res += ', '
  1966. res += format_bytes(fdict['filesize'])
  1967. elif fdict.get('filesize_approx') is not None:
  1968. if res:
  1969. res += ', '
  1970. res += '~' + format_bytes(fdict['filesize_approx'])
  1971. return res
  1972. def list_formats(self, info_dict):
  1973. formats = info_dict.get('formats', [info_dict])
  1974. table = [
  1975. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1976. for f in formats
  1977. if f.get('preference') is None or f['preference'] >= -1000]
  1978. if len(formats) > 1:
  1979. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1980. header_line = ['format code', 'extension', 'resolution', 'note']
  1981. self.to_screen(
  1982. '[info] Available formats for %s:\n%s' %
  1983. (info_dict['id'], render_table(header_line, table)))
  1984. def list_thumbnails(self, info_dict):
  1985. thumbnails = info_dict.get('thumbnails')
  1986. if not thumbnails:
  1987. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  1988. return
  1989. self.to_screen(
  1990. '[info] Thumbnails for %s:' % info_dict['id'])
  1991. self.to_screen(render_table(
  1992. ['ID', 'width', 'height', 'URL'],
  1993. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1994. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1995. if not subtitles:
  1996. self.to_screen('%s has no %s' % (video_id, name))
  1997. return
  1998. self.to_screen(
  1999. 'Available %s for %s:' % (name, video_id))
  2000. self.to_screen(render_table(
  2001. ['Language', 'formats'],
  2002. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  2003. for lang, formats in subtitles.items()]))
  2004. def urlopen(self, req):
  2005. """ Start an HTTP download """
  2006. if isinstance(req, compat_basestring):
  2007. req = sanitized_Request(req)
  2008. return self._opener.open(req, timeout=self._socket_timeout)
  2009. def print_debug_header(self):
  2010. if not self.params.get('verbose'):
  2011. return
  2012. if type('') is not compat_str:
  2013. # Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
  2014. self.report_warning(
  2015. 'Your Python is broken! Update to a newer and supported version')
  2016. stdout_encoding = getattr(
  2017. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  2018. encoding_str = (
  2019. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  2020. locale.getpreferredencoding(),
  2021. sys.getfilesystemencoding(),
  2022. stdout_encoding,
  2023. self.get_encoding()))
  2024. write_string(encoding_str, encoding=None)
  2025. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  2026. if _LAZY_LOADER:
  2027. self._write_string('[debug] Lazy loading extractors enabled' + '\n')
  2028. try:
  2029. sp = subprocess.Popen(
  2030. ['git', 'rev-parse', '--short', 'HEAD'],
  2031. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2032. cwd=os.path.dirname(os.path.abspath(__file__)))
  2033. out, err = sp.communicate()
  2034. out = out.decode().strip()
  2035. if re.match('[0-9a-f]+', out):
  2036. self._write_string('[debug] Git HEAD: ' + out + '\n')
  2037. except Exception:
  2038. try:
  2039. sys.exc_clear()
  2040. except Exception:
  2041. pass
  2042. def python_implementation():
  2043. impl_name = platform.python_implementation()
  2044. if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
  2045. return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
  2046. return impl_name
  2047. self._write_string('[debug] Python version %s (%s) - %s\n' % (
  2048. platform.python_version(), python_implementation(),
  2049. platform_name()))
  2050. exe_versions = FFmpegPostProcessor.get_versions(self)
  2051. exe_versions['rtmpdump'] = rtmpdump_version()
  2052. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  2053. exe_str = ', '.join(
  2054. '%s %s' % (exe, v)
  2055. for exe, v in sorted(exe_versions.items())
  2056. if v
  2057. )
  2058. if not exe_str:
  2059. exe_str = 'none'
  2060. self._write_string('[debug] exe versions: %s\n' % exe_str)
  2061. proxy_map = {}
  2062. for handler in self._opener.handlers:
  2063. if hasattr(handler, 'proxies'):
  2064. proxy_map.update(handler.proxies)
  2065. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  2066. if self.params.get('call_home', False):
  2067. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  2068. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  2069. latest_version = self.urlopen(
  2070. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  2071. if version_tuple(latest_version) > version_tuple(__version__):
  2072. self.report_warning(
  2073. 'You are using an outdated version (newest version: %s)! '
  2074. 'See https://yt-dl.org/update if you need help updating.' %
  2075. latest_version)
  2076. def _setup_opener(self):
  2077. timeout_val = self.params.get('socket_timeout')
  2078. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  2079. opts_cookiefile = self.params.get('cookiefile')
  2080. opts_proxy = self.params.get('proxy')
  2081. if opts_cookiefile is None:
  2082. self.cookiejar = compat_cookiejar.CookieJar()
  2083. else:
  2084. opts_cookiefile = expand_path(opts_cookiefile)
  2085. self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
  2086. if os.access(opts_cookiefile, os.R_OK):
  2087. self.cookiejar.load(ignore_discard=True, ignore_expires=True)
  2088. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  2089. if opts_proxy is not None:
  2090. if opts_proxy == '':
  2091. proxies = {}
  2092. else:
  2093. proxies = {'http': opts_proxy, 'https': opts_proxy}
  2094. else:
  2095. proxies = compat_urllib_request.getproxies()
  2096. # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
  2097. if 'http' in proxies and 'https' not in proxies:
  2098. proxies['https'] = proxies['http']
  2099. proxy_handler = PerRequestProxyHandler(proxies)
  2100. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  2101. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  2102. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  2103. data_handler = compat_urllib_request_DataHandler()
  2104. # When passing our own FileHandler instance, build_opener won't add the
  2105. # default FileHandler and allows us to disable the file protocol, which
  2106. # can be used for malicious purposes (see
  2107. # https://github.com/ytdl-org/youtube-dl/issues/8227)
  2108. file_handler = compat_urllib_request.FileHandler()
  2109. def file_open(*args, **kwargs):
  2110. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  2111. file_handler.file_open = file_open
  2112. opener = compat_urllib_request.build_opener(
  2113. proxy_handler, https_handler, cookie_processor, ydlh, data_handler, file_handler)
  2114. # Delete the default user-agent header, which would otherwise apply in
  2115. # cases where our custom HTTP handler doesn't come into play
  2116. # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
  2117. opener.addheaders = []
  2118. self._opener = opener
  2119. def encode(self, s):
  2120. if isinstance(s, bytes):
  2121. return s # Already encoded
  2122. try:
  2123. return s.encode(self.get_encoding())
  2124. except UnicodeEncodeError as err:
  2125. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  2126. raise
  2127. def get_encoding(self):
  2128. encoding = self.params.get('encoding')
  2129. if encoding is None:
  2130. encoding = preferredencoding()
  2131. return encoding
  2132. def _write_thumbnails(self, info_dict, filename):
  2133. if self.params.get('writethumbnail', False):
  2134. thumbnails = info_dict.get('thumbnails')
  2135. if thumbnails:
  2136. thumbnails = [thumbnails[-1]]
  2137. elif self.params.get('write_all_thumbnails', False):
  2138. thumbnails = info_dict.get('thumbnails')
  2139. else:
  2140. return
  2141. if not thumbnails:
  2142. # No thumbnails present, so return immediately
  2143. return
  2144. for t in thumbnails:
  2145. thumb_ext = determine_ext(t['url'], 'jpg')
  2146. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  2147. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  2148. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  2149. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  2150. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  2151. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2152. else:
  2153. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  2154. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2155. try:
  2156. uf = self.urlopen(t['url'])
  2157. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  2158. shutil.copyfileobj(uf, thumbf)
  2159. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  2160. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  2161. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2162. self.report_warning('Unable to download thumbnail "%s": %s' %
  2163. (t['url'], error_to_compat_str(err)))