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.

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