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.

2384 lines
107 KiB

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