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.

2363 lines
106 KiB

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