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.

1746 lines
76 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
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 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 datetime
  6. import errno
  7. import io
  8. import itertools
  9. import json
  10. import locale
  11. import operator
  12. import os
  13. import platform
  14. import re
  15. import shutil
  16. import subprocess
  17. import socket
  18. import sys
  19. import time
  20. import traceback
  21. if os.name == 'nt':
  22. import ctypes
  23. from .compat import (
  24. compat_basestring,
  25. compat_cookiejar,
  26. compat_expanduser,
  27. compat_http_client,
  28. compat_kwargs,
  29. compat_str,
  30. compat_urllib_error,
  31. compat_urllib_request,
  32. )
  33. from .utils import (
  34. escape_url,
  35. ContentTooShortError,
  36. date_from_str,
  37. DateRange,
  38. DEFAULT_OUTTMPL,
  39. determine_ext,
  40. DownloadError,
  41. encodeFilename,
  42. ExtractorError,
  43. format_bytes,
  44. formatSeconds,
  45. get_term_width,
  46. locked_file,
  47. make_HTTPS_handler,
  48. MaxDownloadsReached,
  49. PagedList,
  50. parse_filesize,
  51. PostProcessingError,
  52. platform_name,
  53. preferredencoding,
  54. render_table,
  55. SameFileError,
  56. sanitize_filename,
  57. std_headers,
  58. subtitles_filename,
  59. takewhile_inclusive,
  60. UnavailableVideoError,
  61. url_basename,
  62. version_tuple,
  63. write_json_file,
  64. write_string,
  65. YoutubeDLHandler,
  66. prepend_extension,
  67. args_to_str,
  68. age_restricted,
  69. )
  70. from .cache import Cache
  71. from .extractor import get_info_extractor, gen_extractors
  72. from .downloader import get_suitable_downloader
  73. from .downloader.rtmp import rtmpdump_version
  74. from .postprocessor import (
  75. FFmpegFixupM4aPP,
  76. FFmpegFixupStretchedPP,
  77. FFmpegMergerPP,
  78. FFmpegPostProcessor,
  79. get_postprocessor,
  80. )
  81. from .version import __version__
  82. class YoutubeDL(object):
  83. """YoutubeDL class.
  84. YoutubeDL objects are the ones responsible of downloading the
  85. actual video file and writing it to disk if the user has requested
  86. it, among some other tasks. In most cases there should be one per
  87. program. As, given a video URL, the downloader doesn't know how to
  88. extract all the needed information, task that InfoExtractors do, it
  89. has to pass the URL to one of them.
  90. For this, YoutubeDL objects have a method that allows
  91. InfoExtractors to be registered in a given order. When it is passed
  92. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  93. finds that reports being able to handle it. The InfoExtractor extracts
  94. all the information about the video or videos the URL refers to, and
  95. YoutubeDL process the extracted information, possibly using a File
  96. Downloader to download the video.
  97. YoutubeDL objects accept a lot of parameters. In order not to saturate
  98. the object constructor with arguments, it receives a dictionary of
  99. options instead. These options are available through the params
  100. attribute for the InfoExtractors to use. The YoutubeDL also
  101. registers itself as the downloader in charge for the InfoExtractors
  102. that are added to it, so this is a "mutual registration".
  103. Available options:
  104. username: Username for authentication purposes.
  105. password: Password for authentication purposes.
  106. videopassword: Password for acces a video.
  107. usenetrc: Use netrc for authentication instead.
  108. verbose: Print additional info to stdout.
  109. quiet: Do not print messages to stdout.
  110. no_warnings: Do not print out anything for warnings.
  111. forceurl: Force printing final URL.
  112. forcetitle: Force printing title.
  113. forceid: Force printing ID.
  114. forcethumbnail: Force printing thumbnail URL.
  115. forcedescription: Force printing description.
  116. forcefilename: Force printing final filename.
  117. forceduration: Force printing duration.
  118. forcejson: Force printing info_dict as JSON.
  119. dump_single_json: Force printing the info_dict of the whole playlist
  120. (or video) as a single JSON line.
  121. simulate: Do not download the video files.
  122. format: Video format code. See options.py for more information.
  123. format_limit: Highest quality format to try.
  124. outtmpl: Template for output names.
  125. restrictfilenames: Do not allow "&" and spaces in file names
  126. ignoreerrors: Do not stop on download errors.
  127. nooverwrites: Prevent overwriting files.
  128. playliststart: Playlist item to start at.
  129. playlistend: Playlist item to end at.
  130. playlist_items: Specific indices of playlist to download.
  131. playlistreverse: Download playlist items in reverse order.
  132. matchtitle: Download only matching titles.
  133. rejecttitle: Reject downloads for matching titles.
  134. logger: Log messages to a logging.Logger instance.
  135. logtostderr: Log messages to stderr instead of stdout.
  136. writedescription: Write the video description to a .description file
  137. writeinfojson: Write the video description to a .info.json file
  138. writeannotations: Write the video annotations to a .annotations.xml file
  139. writethumbnail: Write the thumbnail image to a file
  140. write_all_thumbnails: Write all thumbnail formats to files
  141. writesubtitles: Write the video subtitles to a file
  142. writeautomaticsub: Write the automatic subtitles to a file
  143. allsubtitles: Downloads all the subtitles of the video
  144. (requires writesubtitles or writeautomaticsub)
  145. listsubtitles: Lists all available subtitles for the video
  146. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  147. subtitleslangs: List of languages of the subtitles to download
  148. keepvideo: Keep the video file after post-processing
  149. daterange: A DateRange object, download only if the upload_date is in the range.
  150. skip_download: Skip the actual download of the video file
  151. cachedir: Location of the cache files in the filesystem.
  152. False to disable filesystem cache.
  153. noplaylist: Download single video instead of a playlist if in doubt.
  154. age_limit: An integer representing the user's age in years.
  155. Unsuitable videos for the given age are skipped.
  156. min_views: An integer representing the minimum view count the video
  157. must have in order to not be skipped.
  158. Videos without view count information are always
  159. downloaded. None for no limit.
  160. max_views: An integer representing the maximum view count.
  161. Videos that are more popular than that are not
  162. downloaded.
  163. Videos without view count information are always
  164. downloaded. None for no limit.
  165. download_archive: File name of a file where all downloads are recorded.
  166. Videos already present in the file are not downloaded
  167. again.
  168. cookiefile: File name where cookies should be read from and dumped to.
  169. nocheckcertificate:Do not verify SSL certificates
  170. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  171. At the moment, this is only supported by YouTube.
  172. proxy: URL of the proxy server to use
  173. socket_timeout: Time to wait for unresponsive hosts, in seconds
  174. bidi_workaround: Work around buggy terminals without bidirectional text
  175. support, using fridibi
  176. debug_printtraffic:Print out sent and received HTTP traffic
  177. include_ads: Download ads as well
  178. default_search: Prepend this string if an input url is not valid.
  179. 'auto' for elaborate guessing
  180. encoding: Use this encoding instead of the system-specified.
  181. extract_flat: Do not resolve URLs, return the immediate result.
  182. Pass in 'in_playlist' to only show this behavior for
  183. playlist items.
  184. postprocessors: A list of dictionaries, each with an entry
  185. * key: The name of the postprocessor. See
  186. youtube_dl/postprocessor/__init__.py for a list.
  187. as well as any further keyword arguments for the
  188. postprocessor.
  189. progress_hooks: A list of functions that get called on download
  190. progress, with a dictionary with the entries
  191. * status: One of "downloading", "error", or "finished".
  192. Check this first and ignore unknown values.
  193. If status is one of "downloading", or "finished", the
  194. following properties may also be present:
  195. * filename: The final filename (always present)
  196. * tmpfilename: The filename we're currently writing to
  197. * downloaded_bytes: Bytes on disk
  198. * total_bytes: Size of the whole file, None if unknown
  199. * total_bytes_estimate: Guess of the eventual file size,
  200. None if unavailable.
  201. * elapsed: The number of seconds since download started.
  202. * eta: The estimated time in seconds, None if unknown
  203. * speed: The download speed in bytes/second, None if
  204. unknown
  205. * fragment_index: The counter of the currently
  206. downloaded video fragment.
  207. * fragment_count: The number of fragments (= individual
  208. files that will be merged)
  209. Progress hooks are guaranteed to be called at least once
  210. (with status "finished") if the download is successful.
  211. merge_output_format: Extension to use when merging formats.
  212. fixup: Automatically correct known faults of the file.
  213. One of:
  214. - "never": do nothing
  215. - "warn": only emit a warning
  216. - "detect_or_warn": check whether we can do anything
  217. about it, warn otherwise (default)
  218. source_address: (Experimental) Client-side IP address to bind to.
  219. call_home: Boolean, true iff we are allowed to contact the
  220. youtube-dl servers for debugging.
  221. sleep_interval: Number of seconds to sleep before each download.
  222. listformats: Print an overview of available video formats and exit.
  223. list_thumbnails: Print a table of all thumbnails and exit.
  224. match_filter: A function that gets called with the info_dict of
  225. every video.
  226. If it returns a message, the video is ignored.
  227. If it returns None, the video is downloaded.
  228. match_filter_func in utils.py is one example for this.
  229. no_color: Do not emit color codes in output.
  230. The following options determine which downloader is picked:
  231. external_downloader: Executable of the external downloader to call.
  232. None or unset for standard (built-in) downloader.
  233. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv.
  234. The following parameters are not used by YoutubeDL itself, they are used by
  235. the FileDownloader:
  236. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  237. noresizebuffer, retries, continuedl, noprogress, consoletitle,
  238. xattr_set_filesize.
  239. The following options are used by the post processors:
  240. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  241. otherwise prefer avconv.
  242. exec_cmd: Arbitrary command to run after downloading
  243. """
  244. params = None
  245. _ies = []
  246. _pps = []
  247. _download_retcode = None
  248. _num_downloads = None
  249. _screen_file = None
  250. def __init__(self, params=None, auto_init=True):
  251. """Create a FileDownloader object with the given options."""
  252. if params is None:
  253. params = {}
  254. self._ies = []
  255. self._ies_instances = {}
  256. self._pps = []
  257. self._progress_hooks = []
  258. self._download_retcode = 0
  259. self._num_downloads = 0
  260. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  261. self._err_file = sys.stderr
  262. self.params = params
  263. self.cache = Cache(self)
  264. if params.get('bidi_workaround', False):
  265. try:
  266. import pty
  267. master, slave = pty.openpty()
  268. width = get_term_width()
  269. if width is None:
  270. width_args = []
  271. else:
  272. width_args = ['-w', str(width)]
  273. sp_kwargs = dict(
  274. stdin=subprocess.PIPE,
  275. stdout=slave,
  276. stderr=self._err_file)
  277. try:
  278. self._output_process = subprocess.Popen(
  279. ['bidiv'] + width_args, **sp_kwargs
  280. )
  281. except OSError:
  282. self._output_process = subprocess.Popen(
  283. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  284. self._output_channel = os.fdopen(master, 'rb')
  285. except OSError as ose:
  286. if ose.errno == 2:
  287. 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.')
  288. else:
  289. raise
  290. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  291. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968'] and
  292. not params.get('restrictfilenames', False)):
  293. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  294. self.report_warning(
  295. 'Assuming --restrict-filenames since file system encoding '
  296. 'cannot encode all characters. '
  297. 'Set the LC_ALL environment variable to fix this.')
  298. self.params['restrictfilenames'] = True
  299. if '%(stitle)s' in self.params.get('outtmpl', ''):
  300. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  301. self._setup_opener()
  302. if auto_init:
  303. self.print_debug_header()
  304. self.add_default_info_extractors()
  305. for pp_def_raw in self.params.get('postprocessors', []):
  306. pp_class = get_postprocessor(pp_def_raw['key'])
  307. pp_def = dict(pp_def_raw)
  308. del pp_def['key']
  309. pp = pp_class(self, **compat_kwargs(pp_def))
  310. self.add_post_processor(pp)
  311. for ph in self.params.get('progress_hooks', []):
  312. self.add_progress_hook(ph)
  313. def warn_if_short_id(self, argv):
  314. # short YouTube ID starting with dash?
  315. idxs = [
  316. i for i, a in enumerate(argv)
  317. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  318. if idxs:
  319. correct_argv = (
  320. ['youtube-dl'] +
  321. [a for i, a in enumerate(argv) if i not in idxs] +
  322. ['--'] + [argv[i] for i in idxs]
  323. )
  324. self.report_warning(
  325. 'Long argument string detected. '
  326. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  327. args_to_str(correct_argv))
  328. def add_info_extractor(self, ie):
  329. """Add an InfoExtractor object to the end of the list."""
  330. self._ies.append(ie)
  331. self._ies_instances[ie.ie_key()] = ie
  332. ie.set_downloader(self)
  333. def get_info_extractor(self, ie_key):
  334. """
  335. Get an instance of an IE with name ie_key, it will try to get one from
  336. the _ies list, if there's no instance it will create a new one and add
  337. it to the extractor list.
  338. """
  339. ie = self._ies_instances.get(ie_key)
  340. if ie is None:
  341. ie = get_info_extractor(ie_key)()
  342. self.add_info_extractor(ie)
  343. return ie
  344. def add_default_info_extractors(self):
  345. """
  346. Add the InfoExtractors returned by gen_extractors to the end of the list
  347. """
  348. for ie in gen_extractors():
  349. self.add_info_extractor(ie)
  350. def add_post_processor(self, pp):
  351. """Add a PostProcessor object to the end of the chain."""
  352. self._pps.append(pp)
  353. pp.set_downloader(self)
  354. def add_progress_hook(self, ph):
  355. """Add the progress hook (currently only for the file downloader)"""
  356. self._progress_hooks.append(ph)
  357. def _bidi_workaround(self, message):
  358. if not hasattr(self, '_output_channel'):
  359. return message
  360. assert hasattr(self, '_output_process')
  361. assert isinstance(message, compat_str)
  362. line_count = message.count('\n') + 1
  363. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  364. self._output_process.stdin.flush()
  365. res = ''.join(self._output_channel.readline().decode('utf-8')
  366. for _ in range(line_count))
  367. return res[:-len('\n')]
  368. def to_screen(self, message, skip_eol=False):
  369. """Print message to stdout if not in quiet mode."""
  370. return self.to_stdout(message, skip_eol, check_quiet=True)
  371. def _write_string(self, s, out=None):
  372. write_string(s, out=out, encoding=self.params.get('encoding'))
  373. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  374. """Print message to stdout if not in quiet mode."""
  375. if self.params.get('logger'):
  376. self.params['logger'].debug(message)
  377. elif not check_quiet or not self.params.get('quiet', False):
  378. message = self._bidi_workaround(message)
  379. terminator = ['\n', ''][skip_eol]
  380. output = message + terminator
  381. self._write_string(output, self._screen_file)
  382. def to_stderr(self, message):
  383. """Print message to stderr."""
  384. assert isinstance(message, compat_str)
  385. if self.params.get('logger'):
  386. self.params['logger'].error(message)
  387. else:
  388. message = self._bidi_workaround(message)
  389. output = message + '\n'
  390. self._write_string(output, self._err_file)
  391. def to_console_title(self, message):
  392. if not self.params.get('consoletitle', False):
  393. return
  394. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  395. # c_wchar_p() might not be necessary if `message` is
  396. # already of type unicode()
  397. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  398. elif 'TERM' in os.environ:
  399. self._write_string('\033]0;%s\007' % message, self._screen_file)
  400. def save_console_title(self):
  401. if not self.params.get('consoletitle', False):
  402. return
  403. if 'TERM' in os.environ:
  404. # Save the title on stack
  405. self._write_string('\033[22;0t', self._screen_file)
  406. def restore_console_title(self):
  407. if not self.params.get('consoletitle', False):
  408. return
  409. if 'TERM' in os.environ:
  410. # Restore the title from stack
  411. self._write_string('\033[23;0t', self._screen_file)
  412. def __enter__(self):
  413. self.save_console_title()
  414. return self
  415. def __exit__(self, *args):
  416. self.restore_console_title()
  417. if self.params.get('cookiefile') is not None:
  418. self.cookiejar.save()
  419. def trouble(self, message=None, tb=None):
  420. """Determine action to take when a download problem appears.
  421. Depending on if the downloader has been configured to ignore
  422. download errors or not, this method may throw an exception or
  423. not when errors are found, after printing the message.
  424. tb, if given, is additional traceback information.
  425. """
  426. if message is not None:
  427. self.to_stderr(message)
  428. if self.params.get('verbose'):
  429. if tb is None:
  430. if sys.exc_info()[0]: # if .trouble has been called from an except block
  431. tb = ''
  432. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  433. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  434. tb += compat_str(traceback.format_exc())
  435. else:
  436. tb_data = traceback.format_list(traceback.extract_stack())
  437. tb = ''.join(tb_data)
  438. self.to_stderr(tb)
  439. if not self.params.get('ignoreerrors', False):
  440. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  441. exc_info = sys.exc_info()[1].exc_info
  442. else:
  443. exc_info = sys.exc_info()
  444. raise DownloadError(message, exc_info)
  445. self._download_retcode = 1
  446. def report_warning(self, message):
  447. '''
  448. Print the message to stderr, it will be prefixed with 'WARNING:'
  449. If stderr is a tty file the 'WARNING:' will be colored
  450. '''
  451. if self.params.get('logger') is not None:
  452. self.params['logger'].warning(message)
  453. else:
  454. if self.params.get('no_warnings'):
  455. return
  456. if not self.params.get('no_color') and self._err_file.isatty() and os.name != 'nt':
  457. _msg_header = '\033[0;33mWARNING:\033[0m'
  458. else:
  459. _msg_header = 'WARNING:'
  460. warning_message = '%s %s' % (_msg_header, message)
  461. self.to_stderr(warning_message)
  462. def report_error(self, message, tb=None):
  463. '''
  464. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  465. in red if stderr is a tty file.
  466. '''
  467. if not self.params.get('no_color') and self._err_file.isatty() and os.name != 'nt':
  468. _msg_header = '\033[0;31mERROR:\033[0m'
  469. else:
  470. _msg_header = 'ERROR:'
  471. error_message = '%s %s' % (_msg_header, message)
  472. self.trouble(error_message, tb)
  473. def report_file_already_downloaded(self, file_name):
  474. """Report file has already been fully downloaded."""
  475. try:
  476. self.to_screen('[download] %s has already been downloaded' % file_name)
  477. except UnicodeEncodeError:
  478. self.to_screen('[download] The file has already been downloaded')
  479. def prepare_filename(self, info_dict):
  480. """Generate the output filename."""
  481. try:
  482. template_dict = dict(info_dict)
  483. template_dict['epoch'] = int(time.time())
  484. autonumber_size = self.params.get('autonumber_size')
  485. if autonumber_size is None:
  486. autonumber_size = 5
  487. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  488. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  489. if template_dict.get('playlist_index') is not None:
  490. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  491. if template_dict.get('resolution') is None:
  492. if template_dict.get('width') and template_dict.get('height'):
  493. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  494. elif template_dict.get('height'):
  495. template_dict['resolution'] = '%sp' % template_dict['height']
  496. elif template_dict.get('width'):
  497. template_dict['resolution'] = '?x%d' % template_dict['width']
  498. sanitize = lambda k, v: sanitize_filename(
  499. compat_str(v),
  500. restricted=self.params.get('restrictfilenames'),
  501. is_id=(k == 'id'))
  502. template_dict = dict((k, sanitize(k, v))
  503. for k, v in template_dict.items()
  504. if v is not None)
  505. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  506. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  507. tmpl = compat_expanduser(outtmpl)
  508. filename = tmpl % template_dict
  509. # Temporary fix for #4787
  510. # 'Treat' all problem characters by passing filename through preferredencoding
  511. # to workaround encoding issues with subprocess on python2 @ Windows
  512. if sys.version_info < (3, 0) and sys.platform == 'win32':
  513. filename = encodeFilename(filename, True).decode(preferredencoding())
  514. return filename
  515. except ValueError as err:
  516. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  517. return None
  518. def _match_entry(self, info_dict, incomplete):
  519. """ Returns None iff the file should be downloaded """
  520. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  521. if 'title' in info_dict:
  522. # This can happen when we're just evaluating the playlist
  523. title = info_dict['title']
  524. matchtitle = self.params.get('matchtitle', False)
  525. if matchtitle:
  526. if not re.search(matchtitle, title, re.IGNORECASE):
  527. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  528. rejecttitle = self.params.get('rejecttitle', False)
  529. if rejecttitle:
  530. if re.search(rejecttitle, title, re.IGNORECASE):
  531. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  532. date = info_dict.get('upload_date', None)
  533. if date is not None:
  534. dateRange = self.params.get('daterange', DateRange())
  535. if date not in dateRange:
  536. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  537. view_count = info_dict.get('view_count', None)
  538. if view_count is not None:
  539. min_views = self.params.get('min_views')
  540. if min_views is not None and view_count < min_views:
  541. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  542. max_views = self.params.get('max_views')
  543. if max_views is not None and view_count > max_views:
  544. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  545. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  546. return 'Skipping "%s" because it is age restricted' % video_title
  547. if self.in_download_archive(info_dict):
  548. return '%s has already been recorded in archive' % video_title
  549. if not incomplete:
  550. match_filter = self.params.get('match_filter')
  551. if match_filter is not None:
  552. ret = match_filter(info_dict)
  553. if ret is not None:
  554. return ret
  555. return None
  556. @staticmethod
  557. def add_extra_info(info_dict, extra_info):
  558. '''Set the keys from extra_info in info dict if they are missing'''
  559. for key, value in extra_info.items():
  560. info_dict.setdefault(key, value)
  561. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  562. process=True):
  563. '''
  564. Returns a list with a dictionary for each video we find.
  565. If 'download', also downloads the videos.
  566. extra_info is a dict containing the extra values to add to each result
  567. '''
  568. if ie_key:
  569. ies = [self.get_info_extractor(ie_key)]
  570. else:
  571. ies = self._ies
  572. for ie in ies:
  573. if not ie.suitable(url):
  574. continue
  575. if not ie.working():
  576. self.report_warning('The program functionality for this site has been marked as broken, '
  577. 'and will probably not work.')
  578. try:
  579. ie_result = ie.extract(url)
  580. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  581. break
  582. if isinstance(ie_result, list):
  583. # Backwards compatibility: old IE result format
  584. ie_result = {
  585. '_type': 'compat_list',
  586. 'entries': ie_result,
  587. }
  588. self.add_default_extra_info(ie_result, ie, url)
  589. if process:
  590. return self.process_ie_result(ie_result, download, extra_info)
  591. else:
  592. return ie_result
  593. except ExtractorError as de: # An error we somewhat expected
  594. self.report_error(compat_str(de), de.format_traceback())
  595. break
  596. except MaxDownloadsReached:
  597. raise
  598. except Exception as e:
  599. if self.params.get('ignoreerrors', False):
  600. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  601. break
  602. else:
  603. raise
  604. else:
  605. self.report_error('no suitable InfoExtractor for URL %s' % url)
  606. def add_default_extra_info(self, ie_result, ie, url):
  607. self.add_extra_info(ie_result, {
  608. 'extractor': ie.IE_NAME,
  609. 'webpage_url': url,
  610. 'webpage_url_basename': url_basename(url),
  611. 'extractor_key': ie.ie_key(),
  612. })
  613. def process_ie_result(self, ie_result, download=True, extra_info={}):
  614. """
  615. Take the result of the ie(may be modified) and resolve all unresolved
  616. references (URLs, playlist items).
  617. It will also download the videos if 'download'.
  618. Returns the resolved ie_result.
  619. """
  620. result_type = ie_result.get('_type', 'video')
  621. if result_type in ('url', 'url_transparent'):
  622. extract_flat = self.params.get('extract_flat', False)
  623. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  624. extract_flat is True):
  625. if self.params.get('forcejson', False):
  626. self.to_stdout(json.dumps(ie_result))
  627. return ie_result
  628. if result_type == 'video':
  629. self.add_extra_info(ie_result, extra_info)
  630. return self.process_video_result(ie_result, download=download)
  631. elif result_type == 'url':
  632. # We have to add extra_info to the results because it may be
  633. # contained in a playlist
  634. return self.extract_info(ie_result['url'],
  635. download,
  636. ie_key=ie_result.get('ie_key'),
  637. extra_info=extra_info)
  638. elif result_type == 'url_transparent':
  639. # Use the information from the embedding page
  640. info = self.extract_info(
  641. ie_result['url'], ie_key=ie_result.get('ie_key'),
  642. extra_info=extra_info, download=False, process=False)
  643. force_properties = dict(
  644. (k, v) for k, v in ie_result.items() if v is not None)
  645. for f in ('_type', 'url'):
  646. if f in force_properties:
  647. del force_properties[f]
  648. new_result = info.copy()
  649. new_result.update(force_properties)
  650. assert new_result.get('_type') != 'url_transparent'
  651. return self.process_ie_result(
  652. new_result, download=download, extra_info=extra_info)
  653. elif result_type == 'playlist' or result_type == 'multi_video':
  654. # We process each entry in the playlist
  655. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  656. self.to_screen('[download] Downloading playlist: %s' % playlist)
  657. playlist_results = []
  658. playliststart = self.params.get('playliststart', 1) - 1
  659. playlistend = self.params.get('playlistend', None)
  660. # For backwards compatibility, interpret -1 as whole list
  661. if playlistend == -1:
  662. playlistend = None
  663. playlistitems_str = self.params.get('playlist_items', None)
  664. playlistitems = None
  665. if playlistitems_str is not None:
  666. def iter_playlistitems(format):
  667. for string_segment in format.split(','):
  668. if '-' in string_segment:
  669. start, end = string_segment.split('-')
  670. for item in range(int(start), int(end) + 1):
  671. yield int(item)
  672. else:
  673. yield int(string_segment)
  674. playlistitems = iter_playlistitems(playlistitems_str)
  675. ie_entries = ie_result['entries']
  676. if isinstance(ie_entries, list):
  677. n_all_entries = len(ie_entries)
  678. if playlistitems:
  679. entries = [ie_entries[i - 1] for i in playlistitems]
  680. else:
  681. entries = ie_entries[playliststart:playlistend]
  682. n_entries = len(entries)
  683. self.to_screen(
  684. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  685. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  686. elif isinstance(ie_entries, PagedList):
  687. if playlistitems:
  688. entries = []
  689. for item in playlistitems:
  690. entries.extend(ie_entries.getslice(
  691. item - 1, item
  692. ))
  693. else:
  694. entries = ie_entries.getslice(
  695. playliststart, playlistend)
  696. n_entries = len(entries)
  697. self.to_screen(
  698. "[%s] playlist %s: Downloading %d videos" %
  699. (ie_result['extractor'], playlist, n_entries))
  700. else: # iterable
  701. if playlistitems:
  702. entry_list = list(ie_entries)
  703. entries = [entry_list[i - 1] for i in playlistitems]
  704. else:
  705. entries = list(itertools.islice(
  706. ie_entries, playliststart, playlistend))
  707. n_entries = len(entries)
  708. self.to_screen(
  709. "[%s] playlist %s: Downloading %d videos" %
  710. (ie_result['extractor'], playlist, n_entries))
  711. if self.params.get('playlistreverse', False):
  712. entries = entries[::-1]
  713. for i, entry in enumerate(entries, 1):
  714. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  715. extra = {
  716. 'n_entries': n_entries,
  717. 'playlist': playlist,
  718. 'playlist_id': ie_result.get('id'),
  719. 'playlist_title': ie_result.get('title'),
  720. 'playlist_index': i + playliststart,
  721. 'extractor': ie_result['extractor'],
  722. 'webpage_url': ie_result['webpage_url'],
  723. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  724. 'extractor_key': ie_result['extractor_key'],
  725. }
  726. reason = self._match_entry(entry, incomplete=True)
  727. if reason is not None:
  728. self.to_screen('[download] ' + reason)
  729. continue
  730. entry_result = self.process_ie_result(entry,
  731. download=download,
  732. extra_info=extra)
  733. playlist_results.append(entry_result)
  734. ie_result['entries'] = playlist_results
  735. return ie_result
  736. elif result_type == 'compat_list':
  737. self.report_warning(
  738. 'Extractor %s returned a compat_list result. '
  739. 'It needs to be updated.' % ie_result.get('extractor'))
  740. def _fixup(r):
  741. self.add_extra_info(
  742. r,
  743. {
  744. 'extractor': ie_result['extractor'],
  745. 'webpage_url': ie_result['webpage_url'],
  746. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  747. 'extractor_key': ie_result['extractor_key'],
  748. }
  749. )
  750. return r
  751. ie_result['entries'] = [
  752. self.process_ie_result(_fixup(r), download, extra_info)
  753. for r in ie_result['entries']
  754. ]
  755. return ie_result
  756. else:
  757. raise Exception('Invalid result type: %s' % result_type)
  758. def _apply_format_filter(self, format_spec, available_formats):
  759. " Returns a tuple of the remaining format_spec and filtered formats "
  760. OPERATORS = {
  761. '<': operator.lt,
  762. '<=': operator.le,
  763. '>': operator.gt,
  764. '>=': operator.ge,
  765. '=': operator.eq,
  766. '!=': operator.ne,
  767. }
  768. operator_rex = re.compile(r'''(?x)\s*\[
  769. (?P<key>width|height|tbr|abr|vbr|asr|filesize|fps)
  770. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  771. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  772. \]$
  773. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  774. m = operator_rex.search(format_spec)
  775. if m:
  776. try:
  777. comparison_value = int(m.group('value'))
  778. except ValueError:
  779. comparison_value = parse_filesize(m.group('value'))
  780. if comparison_value is None:
  781. comparison_value = parse_filesize(m.group('value') + 'B')
  782. if comparison_value is None:
  783. raise ValueError(
  784. 'Invalid value %r in format specification %r' % (
  785. m.group('value'), format_spec))
  786. op = OPERATORS[m.group('op')]
  787. if not m:
  788. STR_OPERATORS = {
  789. '=': operator.eq,
  790. '!=': operator.ne,
  791. }
  792. str_operator_rex = re.compile(r'''(?x)\s*\[
  793. \s*(?P<key>ext|acodec|vcodec|container|protocol)
  794. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?
  795. \s*(?P<value>[a-zA-Z0-9_-]+)
  796. \s*\]$
  797. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  798. m = str_operator_rex.search(format_spec)
  799. if m:
  800. comparison_value = m.group('value')
  801. op = STR_OPERATORS[m.group('op')]
  802. if not m:
  803. raise ValueError('Invalid format specification %r' % format_spec)
  804. def _filter(f):
  805. actual_value = f.get(m.group('key'))
  806. if actual_value is None:
  807. return m.group('none_inclusive')
  808. return op(actual_value, comparison_value)
  809. new_formats = [f for f in available_formats if _filter(f)]
  810. new_format_spec = format_spec[:-len(m.group(0))]
  811. if not new_format_spec:
  812. new_format_spec = 'best'
  813. return (new_format_spec, new_formats)
  814. def select_format(self, format_spec, available_formats):
  815. while format_spec.endswith(']'):
  816. format_spec, available_formats = self._apply_format_filter(
  817. format_spec, available_formats)
  818. if not available_formats:
  819. return None
  820. if format_spec == 'best' or format_spec is None:
  821. return available_formats[-1]
  822. elif format_spec == 'worst':
  823. return available_formats[0]
  824. elif format_spec == 'bestaudio':
  825. audio_formats = [
  826. f for f in available_formats
  827. if f.get('vcodec') == 'none']
  828. if audio_formats:
  829. return audio_formats[-1]
  830. elif format_spec == 'worstaudio':
  831. audio_formats = [
  832. f for f in available_formats
  833. if f.get('vcodec') == 'none']
  834. if audio_formats:
  835. return audio_formats[0]
  836. elif format_spec == 'bestvideo':
  837. video_formats = [
  838. f for f in available_formats
  839. if f.get('acodec') == 'none']
  840. if video_formats:
  841. return video_formats[-1]
  842. elif format_spec == 'worstvideo':
  843. video_formats = [
  844. f for f in available_formats
  845. if f.get('acodec') == 'none']
  846. if video_formats:
  847. return video_formats[0]
  848. else:
  849. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  850. if format_spec in extensions:
  851. filter_f = lambda f: f['ext'] == format_spec
  852. else:
  853. filter_f = lambda f: f['format_id'] == format_spec
  854. matches = list(filter(filter_f, available_formats))
  855. if matches:
  856. return matches[-1]
  857. return None
  858. def _calc_headers(self, info_dict):
  859. res = std_headers.copy()
  860. add_headers = info_dict.get('http_headers')
  861. if add_headers:
  862. res.update(add_headers)
  863. cookies = self._calc_cookies(info_dict)
  864. if cookies:
  865. res['Cookie'] = cookies
  866. return res
  867. def _calc_cookies(self, info_dict):
  868. pr = compat_urllib_request.Request(info_dict['url'])
  869. self.cookiejar.add_cookie_header(pr)
  870. return pr.get_header('Cookie')
  871. def process_video_result(self, info_dict, download=True):
  872. assert info_dict.get('_type', 'video') == 'video'
  873. if 'id' not in info_dict:
  874. raise ExtractorError('Missing "id" field in extractor result')
  875. if 'title' not in info_dict:
  876. raise ExtractorError('Missing "title" field in extractor result')
  877. if 'playlist' not in info_dict:
  878. # It isn't part of a playlist
  879. info_dict['playlist'] = None
  880. info_dict['playlist_index'] = None
  881. thumbnails = info_dict.get('thumbnails')
  882. if thumbnails is None:
  883. thumbnail = info_dict.get('thumbnail')
  884. if thumbnail:
  885. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  886. if thumbnails:
  887. thumbnails.sort(key=lambda t: (
  888. t.get('preference'), t.get('width'), t.get('height'),
  889. t.get('id'), t.get('url')))
  890. for i, t in enumerate(thumbnails):
  891. if 'width' in t and 'height' in t:
  892. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  893. if t.get('id') is None:
  894. t['id'] = '%d' % i
  895. if thumbnails and 'thumbnail' not in info_dict:
  896. info_dict['thumbnail'] = thumbnails[-1]['url']
  897. if 'display_id' not in info_dict and 'id' in info_dict:
  898. info_dict['display_id'] = info_dict['id']
  899. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  900. # Working around negative timestamps in Windows
  901. # (see http://bugs.python.org/issue1646728)
  902. if info_dict['timestamp'] < 0 and os.name == 'nt':
  903. info_dict['timestamp'] = 0
  904. upload_date = datetime.datetime.utcfromtimestamp(
  905. info_dict['timestamp'])
  906. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  907. # This extractors handle format selection themselves
  908. if info_dict['extractor'] in ['Youku']:
  909. if download:
  910. self.process_info(info_dict)
  911. return info_dict
  912. # We now pick which formats have to be downloaded
  913. if info_dict.get('formats') is None:
  914. # There's only one format available
  915. formats = [info_dict]
  916. else:
  917. formats = info_dict['formats']
  918. if not formats:
  919. raise ExtractorError('No video formats found!')
  920. # We check that all the formats have the format and format_id fields
  921. for i, format in enumerate(formats):
  922. if 'url' not in format:
  923. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  924. if format.get('format_id') is None:
  925. format['format_id'] = compat_str(i)
  926. if format.get('format') is None:
  927. format['format'] = '{id} - {res}{note}'.format(
  928. id=format['format_id'],
  929. res=self.format_resolution(format),
  930. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  931. )
  932. # Automatically determine file extension if missing
  933. if 'ext' not in format:
  934. format['ext'] = determine_ext(format['url']).lower()
  935. # Add HTTP headers, so that external programs can use them from the
  936. # json output
  937. full_format_info = info_dict.copy()
  938. full_format_info.update(format)
  939. format['http_headers'] = self._calc_headers(full_format_info)
  940. format_limit = self.params.get('format_limit', None)
  941. if format_limit:
  942. formats = list(takewhile_inclusive(
  943. lambda f: f['format_id'] != format_limit, formats
  944. ))
  945. # TODO Central sorting goes here
  946. if formats[0] is not info_dict:
  947. # only set the 'formats' fields if the original info_dict list them
  948. # otherwise we end up with a circular reference, the first (and unique)
  949. # element in the 'formats' field in info_dict is info_dict itself,
  950. # wich can't be exported to json
  951. info_dict['formats'] = formats
  952. if self.params.get('listformats'):
  953. self.list_formats(info_dict)
  954. return
  955. if self.params.get('list_thumbnails'):
  956. self.list_thumbnails(info_dict)
  957. return
  958. req_format = self.params.get('format')
  959. if req_format is None:
  960. req_format = 'best'
  961. formats_to_download = []
  962. # The -1 is for supporting YoutubeIE
  963. if req_format in ('-1', 'all'):
  964. formats_to_download = formats
  965. else:
  966. for rfstr in req_format.split(','):
  967. # We can accept formats requested in the format: 34/5/best, we pick
  968. # the first that is available, starting from left
  969. req_formats = rfstr.split('/')
  970. for rf in req_formats:
  971. if re.match(r'.+?\+.+?', rf) is not None:
  972. # Two formats have been requested like '137+139'
  973. format_1, format_2 = rf.split('+')
  974. formats_info = (self.select_format(format_1, formats),
  975. self.select_format(format_2, formats))
  976. if all(formats_info):
  977. # The first format must contain the video and the
  978. # second the audio
  979. if formats_info[0].get('vcodec') == 'none':
  980. self.report_error('The first format must '
  981. 'contain the video, try using '
  982. '"-f %s+%s"' % (format_2, format_1))
  983. return
  984. output_ext = (
  985. formats_info[0]['ext']
  986. if self.params.get('merge_output_format') is None
  987. else self.params['merge_output_format'])
  988. selected_format = {
  989. 'requested_formats': formats_info,
  990. 'format': '%s+%s' % (formats_info[0].get('format'),
  991. formats_info[1].get('format')),
  992. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  993. formats_info[1].get('format_id')),
  994. 'width': formats_info[0].get('width'),
  995. 'height': formats_info[0].get('height'),
  996. 'resolution': formats_info[0].get('resolution'),
  997. 'fps': formats_info[0].get('fps'),
  998. 'vcodec': formats_info[0].get('vcodec'),
  999. 'vbr': formats_info[0].get('vbr'),
  1000. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1001. 'acodec': formats_info[1].get('acodec'),
  1002. 'abr': formats_info[1].get('abr'),
  1003. 'ext': output_ext,
  1004. }
  1005. else:
  1006. selected_format = None
  1007. else:
  1008. selected_format = self.select_format(rf, formats)
  1009. if selected_format is not None:
  1010. formats_to_download.append(selected_format)
  1011. break
  1012. if not formats_to_download:
  1013. raise ExtractorError('requested format not available',
  1014. expected=True)
  1015. if download:
  1016. if len(formats_to_download) > 1:
  1017. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1018. for format in formats_to_download:
  1019. new_info = dict(info_dict)
  1020. new_info.update(format)
  1021. self.process_info(new_info)
  1022. # We update the info dict with the best quality format (backwards compatibility)
  1023. info_dict.update(formats_to_download[-1])
  1024. return info_dict
  1025. def process_info(self, info_dict):
  1026. """Process a single resolved IE result."""
  1027. assert info_dict.get('_type', 'video') == 'video'
  1028. max_downloads = self.params.get('max_downloads')
  1029. if max_downloads is not None:
  1030. if self._num_downloads >= int(max_downloads):
  1031. raise MaxDownloadsReached()
  1032. info_dict['fulltitle'] = info_dict['title']
  1033. if len(info_dict['title']) > 200:
  1034. info_dict['title'] = info_dict['title'][:197] + '...'
  1035. # Keep for backwards compatibility
  1036. info_dict['stitle'] = info_dict['title']
  1037. if 'format' not in info_dict:
  1038. info_dict['format'] = info_dict['ext']
  1039. reason = self._match_entry(info_dict, incomplete=False)
  1040. if reason is not None:
  1041. self.to_screen('[download] ' + reason)
  1042. return
  1043. self._num_downloads += 1
  1044. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1045. # Forced printings
  1046. if self.params.get('forcetitle', False):
  1047. self.to_stdout(info_dict['fulltitle'])
  1048. if self.params.get('forceid', False):
  1049. self.to_stdout(info_dict['id'])
  1050. if self.params.get('forceurl', False):
  1051. if info_dict.get('requested_formats') is not None:
  1052. for f in info_dict['requested_formats']:
  1053. self.to_stdout(f['url'] + f.get('play_path', ''))
  1054. else:
  1055. # For RTMP URLs, also include the playpath
  1056. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1057. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1058. self.to_stdout(info_dict['thumbnail'])
  1059. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1060. self.to_stdout(info_dict['description'])
  1061. if self.params.get('forcefilename', False) and filename is not None:
  1062. self.to_stdout(filename)
  1063. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1064. self.to_stdout(formatSeconds(info_dict['duration']))
  1065. if self.params.get('forceformat', False):
  1066. self.to_stdout(info_dict['format'])
  1067. if self.params.get('forcejson', False):
  1068. self.to_stdout(json.dumps(info_dict))
  1069. # Do nothing else if in simulate mode
  1070. if self.params.get('simulate', False):
  1071. return
  1072. if filename is None:
  1073. return
  1074. try:
  1075. dn = os.path.dirname(encodeFilename(filename))
  1076. if dn and not os.path.exists(dn):
  1077. os.makedirs(dn)
  1078. except (OSError, IOError) as err:
  1079. self.report_error('unable to create directory ' + compat_str(err))
  1080. return
  1081. if self.params.get('writedescription', False):
  1082. descfn = filename + '.description'
  1083. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1084. self.to_screen('[info] Video description is already present')
  1085. elif info_dict.get('description') is None:
  1086. self.report_warning('There\'s no description to write.')
  1087. else:
  1088. try:
  1089. self.to_screen('[info] Writing video description to: ' + descfn)
  1090. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1091. descfile.write(info_dict['description'])
  1092. except (OSError, IOError):
  1093. self.report_error('Cannot write description file ' + descfn)
  1094. return
  1095. if self.params.get('writeannotations', False):
  1096. annofn = filename + '.annotations.xml'
  1097. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1098. self.to_screen('[info] Video annotations are already present')
  1099. else:
  1100. try:
  1101. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1102. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1103. annofile.write(info_dict['annotations'])
  1104. except (KeyError, TypeError):
  1105. self.report_warning('There are no annotations to write.')
  1106. except (OSError, IOError):
  1107. self.report_error('Cannot write annotations file: ' + annofn)
  1108. return
  1109. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1110. self.params.get('writeautomaticsub')])
  1111. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  1112. # subtitles download errors are already managed as troubles in relevant IE
  1113. # that way it will silently go on when used with unsupporting IE
  1114. subtitles = info_dict['subtitles']
  1115. sub_format = self.params.get('subtitlesformat', 'srt')
  1116. for sub_lang in subtitles.keys():
  1117. sub = subtitles[sub_lang]
  1118. if sub is None:
  1119. continue
  1120. try:
  1121. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1122. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1123. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1124. else:
  1125. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1126. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1127. subfile.write(sub)
  1128. except (OSError, IOError):
  1129. self.report_error('Cannot write subtitles file ' + sub_filename)
  1130. return
  1131. if self.params.get('writeinfojson', False):
  1132. infofn = os.path.splitext(filename)[0] + '.info.json'
  1133. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1134. self.to_screen('[info] Video description metadata is already present')
  1135. else:
  1136. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1137. try:
  1138. write_json_file(info_dict, infofn)
  1139. except (OSError, IOError):
  1140. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1141. return
  1142. self._write_thumbnails(info_dict, filename)
  1143. if not self.params.get('skip_download', False):
  1144. try:
  1145. def dl(name, info):
  1146. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1147. for ph in self._progress_hooks:
  1148. fd.add_progress_hook(ph)
  1149. if self.params.get('verbose'):
  1150. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1151. return fd.download(name, info)
  1152. if info_dict.get('requested_formats') is not None:
  1153. downloaded = []
  1154. success = True
  1155. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1156. if not merger.available:
  1157. postprocessors = []
  1158. self.report_warning('You have requested multiple '
  1159. 'formats but ffmpeg or avconv are not installed.'
  1160. ' The formats won\'t be merged')
  1161. else:
  1162. postprocessors = [merger]
  1163. for f in info_dict['requested_formats']:
  1164. new_info = dict(info_dict)
  1165. new_info.update(f)
  1166. fname = self.prepare_filename(new_info)
  1167. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1168. downloaded.append(fname)
  1169. partial_success = dl(fname, new_info)
  1170. success = success and partial_success
  1171. info_dict['__postprocessors'] = postprocessors
  1172. info_dict['__files_to_merge'] = downloaded
  1173. else:
  1174. # Just a single file
  1175. success = dl(filename, info_dict)
  1176. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1177. self.report_error('unable to download video data: %s' % str(err))
  1178. return
  1179. except (OSError, IOError) as err:
  1180. raise UnavailableVideoError(err)
  1181. except (ContentTooShortError, ) as err:
  1182. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1183. return
  1184. if success:
  1185. # Fixup content
  1186. fixup_policy = self.params.get('fixup')
  1187. if fixup_policy is None:
  1188. fixup_policy = 'detect_or_warn'
  1189. stretched_ratio = info_dict.get('stretched_ratio')
  1190. if stretched_ratio is not None and stretched_ratio != 1:
  1191. if fixup_policy == 'warn':
  1192. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1193. info_dict['id'], stretched_ratio))
  1194. elif fixup_policy == 'detect_or_warn':
  1195. stretched_pp = FFmpegFixupStretchedPP(self)
  1196. if stretched_pp.available:
  1197. info_dict.setdefault('__postprocessors', [])
  1198. info_dict['__postprocessors'].append(stretched_pp)
  1199. else:
  1200. self.report_warning(
  1201. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1202. info_dict['id'], stretched_ratio))
  1203. else:
  1204. assert fixup_policy in ('ignore', 'never')
  1205. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1206. if fixup_policy == 'warn':
  1207. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1208. info_dict['id']))
  1209. elif fixup_policy == 'detect_or_warn':
  1210. fixup_pp = FFmpegFixupM4aPP(self)
  1211. if fixup_pp.available:
  1212. info_dict.setdefault('__postprocessors', [])
  1213. info_dict['__postprocessors'].append(fixup_pp)
  1214. else:
  1215. self.report_warning(
  1216. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1217. info_dict['id']))
  1218. else:
  1219. assert fixup_policy in ('ignore', 'never')
  1220. try:
  1221. self.post_process(filename, info_dict)
  1222. except (PostProcessingError) as err:
  1223. self.report_error('postprocessing: %s' % str(err))
  1224. return
  1225. self.record_download_archive(info_dict)
  1226. def download(self, url_list):
  1227. """Download a given list of URLs."""
  1228. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1229. if (len(url_list) > 1 and
  1230. '%' not in outtmpl and
  1231. self.params.get('max_downloads') != 1):
  1232. raise SameFileError(outtmpl)
  1233. for url in url_list:
  1234. try:
  1235. # It also downloads the videos
  1236. res = self.extract_info(url)
  1237. except UnavailableVideoError:
  1238. self.report_error('unable to download video')
  1239. except MaxDownloadsReached:
  1240. self.to_screen('[info] Maximum number of downloaded files reached.')
  1241. raise
  1242. else:
  1243. if self.params.get('dump_single_json', False):
  1244. self.to_stdout(json.dumps(res))
  1245. return self._download_retcode
  1246. def download_with_info_file(self, info_filename):
  1247. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1248. info = json.load(f)
  1249. try:
  1250. self.process_ie_result(info, download=True)
  1251. except DownloadError:
  1252. webpage_url = info.get('webpage_url')
  1253. if webpage_url is not None:
  1254. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1255. return self.download([webpage_url])
  1256. else:
  1257. raise
  1258. return self._download_retcode
  1259. def post_process(self, filename, ie_info):
  1260. """Run all the postprocessors on the given file."""
  1261. info = dict(ie_info)
  1262. info['filepath'] = filename
  1263. pps_chain = []
  1264. if ie_info.get('__postprocessors') is not None:
  1265. pps_chain.extend(ie_info['__postprocessors'])
  1266. pps_chain.extend(self._pps)
  1267. for pp in pps_chain:
  1268. keep_video = None
  1269. old_filename = info['filepath']
  1270. try:
  1271. keep_video_wish, info = pp.run(info)
  1272. if keep_video_wish is not None:
  1273. if keep_video_wish:
  1274. keep_video = keep_video_wish
  1275. elif keep_video is None:
  1276. # No clear decision yet, let IE decide
  1277. keep_video = keep_video_wish
  1278. except PostProcessingError as e:
  1279. self.report_error(e.msg)
  1280. if keep_video is False and not self.params.get('keepvideo', False):
  1281. try:
  1282. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1283. os.remove(encodeFilename(old_filename))
  1284. except (IOError, OSError):
  1285. self.report_warning('Unable to remove downloaded video file')
  1286. def _make_archive_id(self, info_dict):
  1287. # Future-proof against any change in case
  1288. # and backwards compatibility with prior versions
  1289. extractor = info_dict.get('extractor_key')
  1290. if extractor is None:
  1291. if 'id' in info_dict:
  1292. extractor = info_dict.get('ie_key') # key in a playlist
  1293. if extractor is None:
  1294. return None # Incomplete video information
  1295. return extractor.lower() + ' ' + info_dict['id']
  1296. def in_download_archive(self, info_dict):
  1297. fn = self.params.get('download_archive')
  1298. if fn is None:
  1299. return False
  1300. vid_id = self._make_archive_id(info_dict)
  1301. if vid_id is None:
  1302. return False # Incomplete video information
  1303. try:
  1304. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1305. for line in archive_file:
  1306. if line.strip() == vid_id:
  1307. return True
  1308. except IOError as ioe:
  1309. if ioe.errno != errno.ENOENT:
  1310. raise
  1311. return False
  1312. def record_download_archive(self, info_dict):
  1313. fn = self.params.get('download_archive')
  1314. if fn is None:
  1315. return
  1316. vid_id = self._make_archive_id(info_dict)
  1317. assert vid_id
  1318. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1319. archive_file.write(vid_id + '\n')
  1320. @staticmethod
  1321. def format_resolution(format, default='unknown'):
  1322. if format.get('vcodec') == 'none':
  1323. return 'audio only'
  1324. if format.get('resolution') is not None:
  1325. return format['resolution']
  1326. if format.get('height') is not None:
  1327. if format.get('width') is not None:
  1328. res = '%sx%s' % (format['width'], format['height'])
  1329. else:
  1330. res = '%sp' % format['height']
  1331. elif format.get('width') is not None:
  1332. res = '?x%d' % format['width']
  1333. else:
  1334. res = default
  1335. return res
  1336. def _format_note(self, fdict):
  1337. res = ''
  1338. if fdict.get('ext') in ['f4f', 'f4m']:
  1339. res += '(unsupported) '
  1340. if fdict.get('format_note') is not None:
  1341. res += fdict['format_note'] + ' '
  1342. if fdict.get('tbr') is not None:
  1343. res += '%4dk ' % fdict['tbr']
  1344. if fdict.get('container') is not None:
  1345. if res:
  1346. res += ', '
  1347. res += '%s container' % fdict['container']
  1348. if (fdict.get('vcodec') is not None and
  1349. fdict.get('vcodec') != 'none'):
  1350. if res:
  1351. res += ', '
  1352. res += fdict['vcodec']
  1353. if fdict.get('vbr') is not None:
  1354. res += '@'
  1355. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1356. res += 'video@'
  1357. if fdict.get('vbr') is not None:
  1358. res += '%4dk' % fdict['vbr']
  1359. if fdict.get('fps') is not None:
  1360. res += ', %sfps' % fdict['fps']
  1361. if fdict.get('acodec') is not None:
  1362. if res:
  1363. res += ', '
  1364. if fdict['acodec'] == 'none':
  1365. res += 'video only'
  1366. else:
  1367. res += '%-5s' % fdict['acodec']
  1368. elif fdict.get('abr') is not None:
  1369. if res:
  1370. res += ', '
  1371. res += 'audio'
  1372. if fdict.get('abr') is not None:
  1373. res += '@%3dk' % fdict['abr']
  1374. if fdict.get('asr') is not None:
  1375. res += ' (%5dHz)' % fdict['asr']
  1376. if fdict.get('filesize') is not None:
  1377. if res:
  1378. res += ', '
  1379. res += format_bytes(fdict['filesize'])
  1380. elif fdict.get('filesize_approx') is not None:
  1381. if res:
  1382. res += ', '
  1383. res += '~' + format_bytes(fdict['filesize_approx'])
  1384. return res
  1385. def list_formats(self, info_dict):
  1386. formats = info_dict.get('formats', [info_dict])
  1387. table = [
  1388. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1389. for f in formats
  1390. if f.get('preference') is None or f['preference'] >= -1000]
  1391. if len(formats) > 1:
  1392. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1393. header_line = ['format code', 'extension', 'resolution', 'note']
  1394. self.to_screen(
  1395. '[info] Available formats for %s:\n%s' %
  1396. (info_dict['id'], render_table(header_line, table)))
  1397. def list_thumbnails(self, info_dict):
  1398. thumbnails = info_dict.get('thumbnails')
  1399. if not thumbnails:
  1400. tn_url = info_dict.get('thumbnail')
  1401. if tn_url:
  1402. thumbnails = [{'id': '0', 'url': tn_url}]
  1403. else:
  1404. self.to_screen(
  1405. '[info] No thumbnails present for %s' % info_dict['id'])
  1406. return
  1407. self.to_screen(
  1408. '[info] Thumbnails for %s:' % info_dict['id'])
  1409. self.to_screen(render_table(
  1410. ['ID', 'width', 'height', 'URL'],
  1411. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1412. def urlopen(self, req):
  1413. """ Start an HTTP download """
  1414. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1415. # always respected by websites, some tend to give out URLs with non percent-encoded
  1416. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1417. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1418. # To work around aforementioned issue we will replace request's original URL with
  1419. # percent-encoded one
  1420. req_is_string = isinstance(req, compat_basestring)
  1421. url = req if req_is_string else req.get_full_url()
  1422. url_escaped = escape_url(url)
  1423. # Substitute URL if any change after escaping
  1424. if url != url_escaped:
  1425. if req_is_string:
  1426. req = url_escaped
  1427. else:
  1428. req = compat_urllib_request.Request(
  1429. url_escaped, data=req.data, headers=req.headers,
  1430. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1431. return self._opener.open(req, timeout=self._socket_timeout)
  1432. def print_debug_header(self):
  1433. if not self.params.get('verbose'):
  1434. return
  1435. if type('') is not compat_str:
  1436. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1437. self.report_warning(
  1438. 'Your Python is broken! Update to a newer and supported version')
  1439. stdout_encoding = getattr(
  1440. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1441. encoding_str = (
  1442. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1443. locale.getpreferredencoding(),
  1444. sys.getfilesystemencoding(),
  1445. stdout_encoding,
  1446. self.get_encoding()))
  1447. write_string(encoding_str, encoding=None)
  1448. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1449. try:
  1450. sp = subprocess.Popen(
  1451. ['git', 'rev-parse', '--short', 'HEAD'],
  1452. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1453. cwd=os.path.dirname(os.path.abspath(__file__)))
  1454. out, err = sp.communicate()
  1455. out = out.decode().strip()
  1456. if re.match('[0-9a-f]+', out):
  1457. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1458. except:
  1459. try:
  1460. sys.exc_clear()
  1461. except:
  1462. pass
  1463. self._write_string('[debug] Python version %s - %s\n' % (
  1464. platform.python_version(), platform_name()))
  1465. exe_versions = FFmpegPostProcessor.get_versions(self)
  1466. exe_versions['rtmpdump'] = rtmpdump_version()
  1467. exe_str = ', '.join(
  1468. '%s %s' % (exe, v)
  1469. for exe, v in sorted(exe_versions.items())
  1470. if v
  1471. )
  1472. if not exe_str:
  1473. exe_str = 'none'
  1474. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1475. proxy_map = {}
  1476. for handler in self._opener.handlers:
  1477. if hasattr(handler, 'proxies'):
  1478. proxy_map.update(handler.proxies)
  1479. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1480. if self.params.get('call_home', False):
  1481. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1482. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1483. latest_version = self.urlopen(
  1484. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1485. if version_tuple(latest_version) > version_tuple(__version__):
  1486. self.report_warning(
  1487. 'You are using an outdated version (newest version: %s)! '
  1488. 'See https://yt-dl.org/update if you need help updating.' %
  1489. latest_version)
  1490. def _setup_opener(self):
  1491. timeout_val = self.params.get('socket_timeout')
  1492. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1493. opts_cookiefile = self.params.get('cookiefile')
  1494. opts_proxy = self.params.get('proxy')
  1495. if opts_cookiefile is None:
  1496. self.cookiejar = compat_cookiejar.CookieJar()
  1497. else:
  1498. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1499. opts_cookiefile)
  1500. if os.access(opts_cookiefile, os.R_OK):
  1501. self.cookiejar.load()
  1502. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1503. self.cookiejar)
  1504. if opts_proxy is not None:
  1505. if opts_proxy == '':
  1506. proxies = {}
  1507. else:
  1508. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1509. else:
  1510. proxies = compat_urllib_request.getproxies()
  1511. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1512. if 'http' in proxies and 'https' not in proxies:
  1513. proxies['https'] = proxies['http']
  1514. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1515. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1516. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1517. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1518. opener = compat_urllib_request.build_opener(
  1519. https_handler, proxy_handler, cookie_processor, ydlh)
  1520. # Delete the default user-agent header, which would otherwise apply in
  1521. # cases where our custom HTTP handler doesn't come into play
  1522. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1523. opener.addheaders = []
  1524. self._opener = opener
  1525. def encode(self, s):
  1526. if isinstance(s, bytes):
  1527. return s # Already encoded
  1528. try:
  1529. return s.encode(self.get_encoding())
  1530. except UnicodeEncodeError as err:
  1531. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1532. raise
  1533. def get_encoding(self):
  1534. encoding = self.params.get('encoding')
  1535. if encoding is None:
  1536. encoding = preferredencoding()
  1537. return encoding
  1538. def _write_thumbnails(self, info_dict, filename):
  1539. if self.params.get('writethumbnail', False):
  1540. thumbnails = info_dict.get('thumbnails')
  1541. if thumbnails:
  1542. thumbnails = [thumbnails[-1]]
  1543. elif self.params.get('write_all_thumbnails', False):
  1544. thumbnails = info_dict.get('thumbnails')
  1545. else:
  1546. return
  1547. if not thumbnails:
  1548. # No thumbnails present, so return immediately
  1549. return
  1550. for t in thumbnails:
  1551. thumb_ext = determine_ext(t['url'], 'jpg')
  1552. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1553. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1554. thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1555. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1556. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1557. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1558. else:
  1559. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1560. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1561. try:
  1562. uf = self.urlopen(t['url'])
  1563. with open(thumb_filename, 'wb') as thumbf:
  1564. shutil.copyfileobj(uf, thumbf)
  1565. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1566. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1567. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1568. self.report_warning('Unable to download thumbnail "%s": %s' %
  1569. (t['url'], compat_str(err)))