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.

2401 lines
108 KiB

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