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.

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