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.

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