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.

2392 lines
107 KiB

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