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.

1731 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. 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. 'ext': formats_info[0]['ext'],
  965. 'width': formats_info[0].get('width'),
  966. 'height': formats_info[0].get('height'),
  967. 'resolution': formats_info[0].get('resolution'),
  968. 'fps': formats_info[0].get('fps'),
  969. 'vcodec': formats_info[0].get('vcodec'),
  970. 'vbr': formats_info[0].get('vbr'),
  971. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  972. 'acodec': formats_info[1].get('acodec'),
  973. 'abr': formats_info[1].get('abr'),
  974. 'ext': output_ext,
  975. }
  976. else:
  977. selected_format = None
  978. else:
  979. selected_format = self.select_format(rf, formats)
  980. if selected_format is not None:
  981. formats_to_download.append(selected_format)
  982. break
  983. if not formats_to_download:
  984. raise ExtractorError('requested format not available',
  985. expected=True)
  986. if download:
  987. if len(formats_to_download) > 1:
  988. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  989. for format in formats_to_download:
  990. new_info = dict(info_dict)
  991. new_info.update(format)
  992. self.process_info(new_info)
  993. # We update the info dict with the best quality format (backwards compatibility)
  994. info_dict.update(formats_to_download[-1])
  995. return info_dict
  996. def process_info(self, info_dict):
  997. """Process a single resolved IE result."""
  998. assert info_dict.get('_type', 'video') == 'video'
  999. max_downloads = self.params.get('max_downloads')
  1000. if max_downloads is not None:
  1001. if self._num_downloads >= int(max_downloads):
  1002. raise MaxDownloadsReached()
  1003. info_dict['fulltitle'] = info_dict['title']
  1004. if len(info_dict['title']) > 200:
  1005. info_dict['title'] = info_dict['title'][:197] + '...'
  1006. # Keep for backwards compatibility
  1007. info_dict['stitle'] = info_dict['title']
  1008. if 'format' not in info_dict:
  1009. info_dict['format'] = info_dict['ext']
  1010. reason = self._match_entry(info_dict)
  1011. if reason is not None:
  1012. self.to_screen('[download] ' + reason)
  1013. return
  1014. self._num_downloads += 1
  1015. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1016. # Forced printings
  1017. if self.params.get('forcetitle', False):
  1018. self.to_stdout(info_dict['fulltitle'])
  1019. if self.params.get('forceid', False):
  1020. self.to_stdout(info_dict['id'])
  1021. if self.params.get('forceurl', False):
  1022. if info_dict.get('requested_formats') is not None:
  1023. for f in info_dict['requested_formats']:
  1024. self.to_stdout(f['url'] + f.get('play_path', ''))
  1025. else:
  1026. # For RTMP URLs, also include the playpath
  1027. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1028. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1029. self.to_stdout(info_dict['thumbnail'])
  1030. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1031. self.to_stdout(info_dict['description'])
  1032. if self.params.get('forcefilename', False) and filename is not None:
  1033. self.to_stdout(filename)
  1034. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1035. self.to_stdout(formatSeconds(info_dict['duration']))
  1036. if self.params.get('forceformat', False):
  1037. self.to_stdout(info_dict['format'])
  1038. if self.params.get('forcejson', False):
  1039. self.to_stdout(json.dumps(info_dict))
  1040. # Do nothing else if in simulate mode
  1041. if self.params.get('simulate', False):
  1042. return
  1043. if filename is None:
  1044. return
  1045. try:
  1046. dn = os.path.dirname(encodeFilename(filename))
  1047. if dn and not os.path.exists(dn):
  1048. os.makedirs(dn)
  1049. except (OSError, IOError) as err:
  1050. self.report_error('unable to create directory ' + compat_str(err))
  1051. return
  1052. if self.params.get('writedescription', False):
  1053. descfn = filename + '.description'
  1054. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1055. self.to_screen('[info] Video description is already present')
  1056. elif info_dict.get('description') is None:
  1057. self.report_warning('There\'s no description to write.')
  1058. else:
  1059. try:
  1060. self.to_screen('[info] Writing video description to: ' + descfn)
  1061. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1062. descfile.write(info_dict['description'])
  1063. except (OSError, IOError):
  1064. self.report_error('Cannot write description file ' + descfn)
  1065. return
  1066. if self.params.get('writeannotations', False):
  1067. annofn = filename + '.annotations.xml'
  1068. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1069. self.to_screen('[info] Video annotations are already present')
  1070. else:
  1071. try:
  1072. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1073. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1074. annofile.write(info_dict['annotations'])
  1075. except (KeyError, TypeError):
  1076. self.report_warning('There are no annotations to write.')
  1077. except (OSError, IOError):
  1078. self.report_error('Cannot write annotations file: ' + annofn)
  1079. return
  1080. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1081. self.params.get('writeautomaticsub')])
  1082. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  1083. # subtitles download errors are already managed as troubles in relevant IE
  1084. # that way it will silently go on when used with unsupporting IE
  1085. subtitles = info_dict['subtitles']
  1086. sub_format = self.params.get('subtitlesformat', 'srt')
  1087. for sub_lang in subtitles.keys():
  1088. sub = subtitles[sub_lang]
  1089. if sub is None:
  1090. continue
  1091. try:
  1092. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1093. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1094. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1095. else:
  1096. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1097. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1098. subfile.write(sub)
  1099. except (OSError, IOError):
  1100. self.report_error('Cannot write subtitles file ' + sub_filename)
  1101. return
  1102. if self.params.get('writeinfojson', False):
  1103. infofn = os.path.splitext(filename)[0] + '.info.json'
  1104. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1105. self.to_screen('[info] Video description metadata is already present')
  1106. else:
  1107. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1108. try:
  1109. write_json_file(info_dict, infofn)
  1110. except (OSError, IOError):
  1111. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1112. return
  1113. self._write_thumbnails(info_dict, filename)
  1114. if not self.params.get('skip_download', False):
  1115. try:
  1116. def dl(name, info):
  1117. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1118. for ph in self._progress_hooks:
  1119. fd.add_progress_hook(ph)
  1120. if self.params.get('verbose'):
  1121. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1122. return fd.download(name, info)
  1123. if info_dict.get('requested_formats') is not None:
  1124. downloaded = []
  1125. success = True
  1126. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1127. if not merger._executable:
  1128. postprocessors = []
  1129. self.report_warning('You have requested multiple '
  1130. 'formats but ffmpeg or avconv are not installed.'
  1131. ' The formats won\'t be merged')
  1132. else:
  1133. postprocessors = [merger]
  1134. for f in info_dict['requested_formats']:
  1135. new_info = dict(info_dict)
  1136. new_info.update(f)
  1137. fname = self.prepare_filename(new_info)
  1138. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1139. downloaded.append(fname)
  1140. partial_success = dl(fname, new_info)
  1141. success = success and partial_success
  1142. info_dict['__postprocessors'] = postprocessors
  1143. info_dict['__files_to_merge'] = downloaded
  1144. else:
  1145. # Just a single file
  1146. success = dl(filename, info_dict)
  1147. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1148. self.report_error('unable to download video data: %s' % str(err))
  1149. return
  1150. except (OSError, IOError) as err:
  1151. raise UnavailableVideoError(err)
  1152. except (ContentTooShortError, ) as err:
  1153. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1154. return
  1155. if success:
  1156. # Fixup content
  1157. fixup_policy = self.params.get('fixup')
  1158. if fixup_policy is None:
  1159. fixup_policy = 'detect_or_warn'
  1160. stretched_ratio = info_dict.get('stretched_ratio')
  1161. if stretched_ratio is not None and stretched_ratio != 1:
  1162. if fixup_policy == 'warn':
  1163. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1164. info_dict['id'], stretched_ratio))
  1165. elif fixup_policy == 'detect_or_warn':
  1166. stretched_pp = FFmpegFixupStretchedPP(self)
  1167. if stretched_pp.available:
  1168. info_dict.setdefault('__postprocessors', [])
  1169. info_dict['__postprocessors'].append(stretched_pp)
  1170. else:
  1171. self.report_warning(
  1172. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1173. info_dict['id'], stretched_ratio))
  1174. else:
  1175. assert fixup_policy in ('ignore', 'never')
  1176. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1177. if fixup_policy == 'warn':
  1178. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1179. info_dict['id']))
  1180. elif fixup_policy == 'detect_or_warn':
  1181. fixup_pp = FFmpegFixupM4aPP(self)
  1182. if fixup_pp.available:
  1183. info_dict.setdefault('__postprocessors', [])
  1184. info_dict['__postprocessors'].append(fixup_pp)
  1185. else:
  1186. self.report_warning(
  1187. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1188. info_dict['id']))
  1189. else:
  1190. assert fixup_policy in ('ignore', 'never')
  1191. try:
  1192. self.post_process(filename, info_dict)
  1193. except (PostProcessingError) as err:
  1194. self.report_error('postprocessing: %s' % str(err))
  1195. return
  1196. self.record_download_archive(info_dict)
  1197. def download(self, url_list):
  1198. """Download a given list of URLs."""
  1199. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1200. if (len(url_list) > 1 and
  1201. '%' not in outtmpl
  1202. and self.params.get('max_downloads') != 1):
  1203. raise SameFileError(outtmpl)
  1204. for url in url_list:
  1205. try:
  1206. # It also downloads the videos
  1207. res = self.extract_info(url)
  1208. except UnavailableVideoError:
  1209. self.report_error('unable to download video')
  1210. except MaxDownloadsReached:
  1211. self.to_screen('[info] Maximum number of downloaded files reached.')
  1212. raise
  1213. else:
  1214. if self.params.get('dump_single_json', False):
  1215. self.to_stdout(json.dumps(res))
  1216. return self._download_retcode
  1217. def download_with_info_file(self, info_filename):
  1218. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1219. info = json.load(f)
  1220. try:
  1221. self.process_ie_result(info, download=True)
  1222. except DownloadError:
  1223. webpage_url = info.get('webpage_url')
  1224. if webpage_url is not None:
  1225. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1226. return self.download([webpage_url])
  1227. else:
  1228. raise
  1229. return self._download_retcode
  1230. def post_process(self, filename, ie_info):
  1231. """Run all the postprocessors on the given file."""
  1232. info = dict(ie_info)
  1233. info['filepath'] = filename
  1234. pps_chain = []
  1235. if ie_info.get('__postprocessors') is not None:
  1236. pps_chain.extend(ie_info['__postprocessors'])
  1237. pps_chain.extend(self._pps)
  1238. for pp in pps_chain:
  1239. keep_video = None
  1240. old_filename = info['filepath']
  1241. try:
  1242. keep_video_wish, info = pp.run(info)
  1243. if keep_video_wish is not None:
  1244. if keep_video_wish:
  1245. keep_video = keep_video_wish
  1246. elif keep_video is None:
  1247. # No clear decision yet, let IE decide
  1248. keep_video = keep_video_wish
  1249. except PostProcessingError as e:
  1250. self.report_error(e.msg)
  1251. if keep_video is False and not self.params.get('keepvideo', False):
  1252. try:
  1253. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1254. os.remove(encodeFilename(old_filename))
  1255. except (IOError, OSError):
  1256. self.report_warning('Unable to remove downloaded video file')
  1257. def _make_archive_id(self, info_dict):
  1258. # Future-proof against any change in case
  1259. # and backwards compatibility with prior versions
  1260. extractor = info_dict.get('extractor_key')
  1261. if extractor is None:
  1262. if 'id' in info_dict:
  1263. extractor = info_dict.get('ie_key') # key in a playlist
  1264. if extractor is None:
  1265. return None # Incomplete video information
  1266. return extractor.lower() + ' ' + info_dict['id']
  1267. def in_download_archive(self, info_dict):
  1268. fn = self.params.get('download_archive')
  1269. if fn is None:
  1270. return False
  1271. vid_id = self._make_archive_id(info_dict)
  1272. if vid_id is None:
  1273. return False # Incomplete video information
  1274. try:
  1275. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1276. for line in archive_file:
  1277. if line.strip() == vid_id:
  1278. return True
  1279. except IOError as ioe:
  1280. if ioe.errno != errno.ENOENT:
  1281. raise
  1282. return False
  1283. def record_download_archive(self, info_dict):
  1284. fn = self.params.get('download_archive')
  1285. if fn is None:
  1286. return
  1287. vid_id = self._make_archive_id(info_dict)
  1288. assert vid_id
  1289. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1290. archive_file.write(vid_id + '\n')
  1291. @staticmethod
  1292. def format_resolution(format, default='unknown'):
  1293. if format.get('vcodec') == 'none':
  1294. return 'audio only'
  1295. if format.get('resolution') is not None:
  1296. return format['resolution']
  1297. if format.get('height') is not None:
  1298. if format.get('width') is not None:
  1299. res = '%sx%s' % (format['width'], format['height'])
  1300. else:
  1301. res = '%sp' % format['height']
  1302. elif format.get('width') is not None:
  1303. res = '?x%d' % format['width']
  1304. else:
  1305. res = default
  1306. return res
  1307. def _format_note(self, fdict):
  1308. res = ''
  1309. if fdict.get('ext') in ['f4f', 'f4m']:
  1310. res += '(unsupported) '
  1311. if fdict.get('format_note') is not None:
  1312. res += fdict['format_note'] + ' '
  1313. if fdict.get('tbr') is not None:
  1314. res += '%4dk ' % fdict['tbr']
  1315. if fdict.get('container') is not None:
  1316. if res:
  1317. res += ', '
  1318. res += '%s container' % fdict['container']
  1319. if (fdict.get('vcodec') is not None and
  1320. fdict.get('vcodec') != 'none'):
  1321. if res:
  1322. res += ', '
  1323. res += fdict['vcodec']
  1324. if fdict.get('vbr') is not None:
  1325. res += '@'
  1326. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1327. res += 'video@'
  1328. if fdict.get('vbr') is not None:
  1329. res += '%4dk' % fdict['vbr']
  1330. if fdict.get('fps') is not None:
  1331. res += ', %sfps' % fdict['fps']
  1332. if fdict.get('acodec') is not None:
  1333. if res:
  1334. res += ', '
  1335. if fdict['acodec'] == 'none':
  1336. res += 'video only'
  1337. else:
  1338. res += '%-5s' % fdict['acodec']
  1339. elif fdict.get('abr') is not None:
  1340. if res:
  1341. res += ', '
  1342. res += 'audio'
  1343. if fdict.get('abr') is not None:
  1344. res += '@%3dk' % fdict['abr']
  1345. if fdict.get('asr') is not None:
  1346. res += ' (%5dHz)' % fdict['asr']
  1347. if fdict.get('filesize') is not None:
  1348. if res:
  1349. res += ', '
  1350. res += format_bytes(fdict['filesize'])
  1351. elif fdict.get('filesize_approx') is not None:
  1352. if res:
  1353. res += ', '
  1354. res += '~' + format_bytes(fdict['filesize_approx'])
  1355. return res
  1356. def list_formats(self, info_dict):
  1357. def line(format, idlen=20):
  1358. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1359. format['format_id'],
  1360. format['ext'],
  1361. self.format_resolution(format),
  1362. self._format_note(format),
  1363. ))
  1364. formats = info_dict.get('formats', [info_dict])
  1365. idlen = max(len('format code'),
  1366. max(len(f['format_id']) for f in formats))
  1367. formats_s = [
  1368. line(f, idlen) for f in formats
  1369. if f.get('preference') is None or f['preference'] >= -1000]
  1370. if len(formats) > 1:
  1371. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1372. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1373. header_line = line({
  1374. 'format_id': 'format code', 'ext': 'extension',
  1375. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1376. self.to_screen(
  1377. '[info] Available formats for %s:\n%s\n%s' %
  1378. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1379. def list_thumbnails(self, info_dict):
  1380. thumbnails = info_dict.get('thumbnails')
  1381. if not thumbnails:
  1382. tn_url = info_dict.get('thumbnail')
  1383. if tn_url:
  1384. thumbnails = [{'id': '0', 'url': tn_url}]
  1385. else:
  1386. self.to_screen(
  1387. '[info] No thumbnails present for %s' % info_dict['id'])
  1388. return
  1389. self.to_screen(
  1390. '[info] Thumbnails for %s:' % info_dict['id'])
  1391. self.to_screen(render_table(
  1392. ['ID', 'width', 'height', 'URL'],
  1393. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1394. def urlopen(self, req):
  1395. """ Start an HTTP download """
  1396. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1397. # always respected by websites, some tend to give out URLs with non percent-encoded
  1398. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1399. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1400. # To work around aforementioned issue we will replace request's original URL with
  1401. # percent-encoded one
  1402. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1403. url = req if req_is_string else req.get_full_url()
  1404. url_escaped = escape_url(url)
  1405. # Substitute URL if any change after escaping
  1406. if url != url_escaped:
  1407. if req_is_string:
  1408. req = url_escaped
  1409. else:
  1410. req = compat_urllib_request.Request(
  1411. url_escaped, data=req.data, headers=req.headers,
  1412. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1413. return self._opener.open(req, timeout=self._socket_timeout)
  1414. def print_debug_header(self):
  1415. if not self.params.get('verbose'):
  1416. return
  1417. if type('') is not compat_str:
  1418. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1419. self.report_warning(
  1420. 'Your Python is broken! Update to a newer and supported version')
  1421. stdout_encoding = getattr(
  1422. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1423. encoding_str = (
  1424. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1425. locale.getpreferredencoding(),
  1426. sys.getfilesystemencoding(),
  1427. stdout_encoding,
  1428. self.get_encoding()))
  1429. write_string(encoding_str, encoding=None)
  1430. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1431. try:
  1432. sp = subprocess.Popen(
  1433. ['git', 'rev-parse', '--short', 'HEAD'],
  1434. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1435. cwd=os.path.dirname(os.path.abspath(__file__)))
  1436. out, err = sp.communicate()
  1437. out = out.decode().strip()
  1438. if re.match('[0-9a-f]+', out):
  1439. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1440. except:
  1441. try:
  1442. sys.exc_clear()
  1443. except:
  1444. pass
  1445. self._write_string('[debug] Python version %s - %s\n' % (
  1446. platform.python_version(), platform_name()))
  1447. exe_versions = FFmpegPostProcessor.get_versions()
  1448. exe_versions['rtmpdump'] = rtmpdump_version()
  1449. exe_str = ', '.join(
  1450. '%s %s' % (exe, v)
  1451. for exe, v in sorted(exe_versions.items())
  1452. if v
  1453. )
  1454. if not exe_str:
  1455. exe_str = 'none'
  1456. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1457. proxy_map = {}
  1458. for handler in self._opener.handlers:
  1459. if hasattr(handler, 'proxies'):
  1460. proxy_map.update(handler.proxies)
  1461. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1462. if self.params.get('call_home', False):
  1463. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1464. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1465. latest_version = self.urlopen(
  1466. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1467. if version_tuple(latest_version) > version_tuple(__version__):
  1468. self.report_warning(
  1469. 'You are using an outdated version (newest version: %s)! '
  1470. 'See https://yt-dl.org/update if you need help updating.' %
  1471. latest_version)
  1472. def _setup_opener(self):
  1473. timeout_val = self.params.get('socket_timeout')
  1474. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1475. opts_cookiefile = self.params.get('cookiefile')
  1476. opts_proxy = self.params.get('proxy')
  1477. if opts_cookiefile is None:
  1478. self.cookiejar = compat_cookiejar.CookieJar()
  1479. else:
  1480. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1481. opts_cookiefile)
  1482. if os.access(opts_cookiefile, os.R_OK):
  1483. self.cookiejar.load()
  1484. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1485. self.cookiejar)
  1486. if opts_proxy is not None:
  1487. if opts_proxy == '':
  1488. proxies = {}
  1489. else:
  1490. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1491. else:
  1492. proxies = compat_urllib_request.getproxies()
  1493. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1494. if 'http' in proxies and 'https' not in proxies:
  1495. proxies['https'] = proxies['http']
  1496. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1497. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1498. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1499. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1500. opener = compat_urllib_request.build_opener(
  1501. https_handler, proxy_handler, cookie_processor, ydlh)
  1502. # Delete the default user-agent header, which would otherwise apply in
  1503. # cases where our custom HTTP handler doesn't come into play
  1504. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1505. opener.addheaders = []
  1506. self._opener = opener
  1507. def encode(self, s):
  1508. if isinstance(s, bytes):
  1509. return s # Already encoded
  1510. try:
  1511. return s.encode(self.get_encoding())
  1512. except UnicodeEncodeError as err:
  1513. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1514. raise
  1515. def get_encoding(self):
  1516. encoding = self.params.get('encoding')
  1517. if encoding is None:
  1518. encoding = preferredencoding()
  1519. return encoding
  1520. def _write_thumbnails(self, info_dict, filename):
  1521. if self.params.get('writethumbnail', False):
  1522. thumbnails = info_dict.get('thumbnails')
  1523. if thumbnails:
  1524. thumbnails = [thumbnails[-1]]
  1525. elif self.params.get('write_all_thumbnails', False):
  1526. thumbnails = info_dict.get('thumbnails')
  1527. else:
  1528. return
  1529. if not thumbnails:
  1530. # No thumbnails present, so return immediately
  1531. return
  1532. for t in thumbnails:
  1533. thumb_ext = determine_ext(t['url'], 'jpg')
  1534. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1535. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1536. thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1537. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1538. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1539. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1540. else:
  1541. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1542. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1543. try:
  1544. uf = self.urlopen(t['url'])
  1545. with open(thumb_filename, 'wb') as thumbf:
  1546. shutil.copyfileobj(uf, thumbf)
  1547. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1548. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1549. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1550. self.report_warning('Unable to download thumbnail "%s": %s' %
  1551. (t['url'], compat_str(err)))