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.

2357 lines
106 KiB

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