You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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