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.

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