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.

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