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.

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