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.

1533 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: Boolean, true iff we are allowed to contact the
  203. 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. try:
  1007. def dl(name, info):
  1008. fd = get_suitable_downloader(info)(self, self.params)
  1009. for ph in self._progress_hooks:
  1010. fd.add_progress_hook(ph)
  1011. if self.params.get('verbose'):
  1012. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1013. return fd.download(name, info)
  1014. if info_dict.get('requested_formats') is not None:
  1015. downloaded = []
  1016. success = True
  1017. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1018. if not merger._executable:
  1019. postprocessors = []
  1020. self.report_warning('You have requested multiple '
  1021. 'formats but ffmpeg or avconv are not installed.'
  1022. ' The formats won\'t be merged')
  1023. else:
  1024. postprocessors = [merger]
  1025. for f in info_dict['requested_formats']:
  1026. new_info = dict(info_dict)
  1027. new_info.update(f)
  1028. fname = self.prepare_filename(new_info)
  1029. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1030. downloaded.append(fname)
  1031. partial_success = dl(fname, new_info)
  1032. success = success and partial_success
  1033. info_dict['__postprocessors'] = postprocessors
  1034. info_dict['__files_to_merge'] = downloaded
  1035. else:
  1036. # Just a single file
  1037. success = dl(filename, info_dict)
  1038. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1039. self.report_error('unable to download video data: %s' % str(err))
  1040. return
  1041. except (OSError, IOError) as err:
  1042. raise UnavailableVideoError(err)
  1043. except (ContentTooShortError, ) as err:
  1044. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1045. return
  1046. if success:
  1047. # Fixup content
  1048. stretched_ratio = info_dict.get('stretched_ratio')
  1049. if stretched_ratio is not None and stretched_ratio != 1:
  1050. fixup_policy = self.params.get('fixup')
  1051. if fixup_policy is None:
  1052. fixup_policy = 'detect_or_warn'
  1053. if fixup_policy == 'warn':
  1054. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1055. info_dict['id'], stretched_ratio))
  1056. elif fixup_policy == 'detect_or_warn':
  1057. stretched_pp = FFmpegFixupStretchedPP(self)
  1058. if stretched_pp.available:
  1059. info_dict.setdefault('__postprocessors', [])
  1060. info_dict['__postprocessors'].append(stretched_pp)
  1061. else:
  1062. self.report_warning(
  1063. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1064. info_dict['id'], stretched_ratio))
  1065. else:
  1066. assert fixup_policy == 'ignore'
  1067. try:
  1068. self.post_process(filename, info_dict)
  1069. except (PostProcessingError) as err:
  1070. self.report_error('postprocessing: %s' % str(err))
  1071. return
  1072. self.record_download_archive(info_dict)
  1073. def download(self, url_list):
  1074. """Download a given list of URLs."""
  1075. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1076. if (len(url_list) > 1 and
  1077. '%' not in outtmpl
  1078. and self.params.get('max_downloads') != 1):
  1079. raise SameFileError(outtmpl)
  1080. for url in url_list:
  1081. try:
  1082. # It also downloads the videos
  1083. res = self.extract_info(url)
  1084. except UnavailableVideoError:
  1085. self.report_error('unable to download video')
  1086. except MaxDownloadsReached:
  1087. self.to_screen('[info] Maximum number of downloaded files reached.')
  1088. raise
  1089. else:
  1090. if self.params.get('dump_single_json', False):
  1091. self.to_stdout(json.dumps(res))
  1092. return self._download_retcode
  1093. def download_with_info_file(self, info_filename):
  1094. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1095. info = json.load(f)
  1096. try:
  1097. self.process_ie_result(info, download=True)
  1098. except DownloadError:
  1099. webpage_url = info.get('webpage_url')
  1100. if webpage_url is not None:
  1101. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1102. return self.download([webpage_url])
  1103. else:
  1104. raise
  1105. return self._download_retcode
  1106. def post_process(self, filename, ie_info):
  1107. """Run all the postprocessors on the given file."""
  1108. info = dict(ie_info)
  1109. info['filepath'] = filename
  1110. pps_chain = []
  1111. if ie_info.get('__postprocessors') is not None:
  1112. pps_chain.extend(ie_info['__postprocessors'])
  1113. pps_chain.extend(self._pps)
  1114. for pp in pps_chain:
  1115. keep_video = None
  1116. old_filename = info['filepath']
  1117. try:
  1118. keep_video_wish, info = pp.run(info)
  1119. if keep_video_wish is not None:
  1120. if keep_video_wish:
  1121. keep_video = keep_video_wish
  1122. elif keep_video is None:
  1123. # No clear decision yet, let IE decide
  1124. keep_video = keep_video_wish
  1125. except PostProcessingError as e:
  1126. self.report_error(e.msg)
  1127. if keep_video is False and not self.params.get('keepvideo', False):
  1128. try:
  1129. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1130. os.remove(encodeFilename(old_filename))
  1131. except (IOError, OSError):
  1132. self.report_warning('Unable to remove downloaded video file')
  1133. def _make_archive_id(self, info_dict):
  1134. # Future-proof against any change in case
  1135. # and backwards compatibility with prior versions
  1136. extractor = info_dict.get('extractor_key')
  1137. if extractor is None:
  1138. if 'id' in info_dict:
  1139. extractor = info_dict.get('ie_key') # key in a playlist
  1140. if extractor is None:
  1141. return None # Incomplete video information
  1142. return extractor.lower() + ' ' + info_dict['id']
  1143. def in_download_archive(self, info_dict):
  1144. fn = self.params.get('download_archive')
  1145. if fn is None:
  1146. return False
  1147. vid_id = self._make_archive_id(info_dict)
  1148. if vid_id is None:
  1149. return False # Incomplete video information
  1150. try:
  1151. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1152. for line in archive_file:
  1153. if line.strip() == vid_id:
  1154. return True
  1155. except IOError as ioe:
  1156. if ioe.errno != errno.ENOENT:
  1157. raise
  1158. return False
  1159. def record_download_archive(self, info_dict):
  1160. fn = self.params.get('download_archive')
  1161. if fn is None:
  1162. return
  1163. vid_id = self._make_archive_id(info_dict)
  1164. assert vid_id
  1165. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1166. archive_file.write(vid_id + '\n')
  1167. @staticmethod
  1168. def format_resolution(format, default='unknown'):
  1169. if format.get('vcodec') == 'none':
  1170. return 'audio only'
  1171. if format.get('resolution') is not None:
  1172. return format['resolution']
  1173. if format.get('height') is not None:
  1174. if format.get('width') is not None:
  1175. res = '%sx%s' % (format['width'], format['height'])
  1176. else:
  1177. res = '%sp' % format['height']
  1178. elif format.get('width') is not None:
  1179. res = '?x%d' % format['width']
  1180. else:
  1181. res = default
  1182. return res
  1183. def _format_note(self, fdict):
  1184. res = ''
  1185. if fdict.get('ext') in ['f4f', 'f4m']:
  1186. res += '(unsupported) '
  1187. if fdict.get('format_note') is not None:
  1188. res += fdict['format_note'] + ' '
  1189. if fdict.get('tbr') is not None:
  1190. res += '%4dk ' % fdict['tbr']
  1191. if fdict.get('container') is not None:
  1192. if res:
  1193. res += ', '
  1194. res += '%s container' % fdict['container']
  1195. if (fdict.get('vcodec') is not None and
  1196. fdict.get('vcodec') != 'none'):
  1197. if res:
  1198. res += ', '
  1199. res += fdict['vcodec']
  1200. if fdict.get('vbr') is not None:
  1201. res += '@'
  1202. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1203. res += 'video@'
  1204. if fdict.get('vbr') is not None:
  1205. res += '%4dk' % fdict['vbr']
  1206. if fdict.get('fps') is not None:
  1207. res += ', %sfps' % fdict['fps']
  1208. if fdict.get('acodec') is not None:
  1209. if res:
  1210. res += ', '
  1211. if fdict['acodec'] == 'none':
  1212. res += 'video only'
  1213. else:
  1214. res += '%-5s' % fdict['acodec']
  1215. elif fdict.get('abr') is not None:
  1216. if res:
  1217. res += ', '
  1218. res += 'audio'
  1219. if fdict.get('abr') is not None:
  1220. res += '@%3dk' % fdict['abr']
  1221. if fdict.get('asr') is not None:
  1222. res += ' (%5dHz)' % fdict['asr']
  1223. if fdict.get('filesize') is not None:
  1224. if res:
  1225. res += ', '
  1226. res += format_bytes(fdict['filesize'])
  1227. elif fdict.get('filesize_approx') is not None:
  1228. if res:
  1229. res += ', '
  1230. res += '~' + format_bytes(fdict['filesize_approx'])
  1231. return res
  1232. def list_formats(self, info_dict):
  1233. def line(format, idlen=20):
  1234. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1235. format['format_id'],
  1236. format['ext'],
  1237. self.format_resolution(format),
  1238. self._format_note(format),
  1239. ))
  1240. formats = info_dict.get('formats', [info_dict])
  1241. idlen = max(len('format code'),
  1242. max(len(f['format_id']) for f in formats))
  1243. formats_s = [
  1244. line(f, idlen) for f in formats
  1245. if f.get('preference') is None or f['preference'] >= -1000]
  1246. if len(formats) > 1:
  1247. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1248. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1249. header_line = line({
  1250. 'format_id': 'format code', 'ext': 'extension',
  1251. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1252. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1253. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1254. def urlopen(self, req):
  1255. """ Start an HTTP download """
  1256. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1257. # always respected by websites, some tend to give out URLs with non percent-encoded
  1258. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1259. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1260. # To work around aforementioned issue we will replace request's original URL with
  1261. # percent-encoded one
  1262. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1263. url = req if req_is_string else req.get_full_url()
  1264. url_escaped = escape_url(url)
  1265. # Substitute URL if any change after escaping
  1266. if url != url_escaped:
  1267. if req_is_string:
  1268. req = url_escaped
  1269. else:
  1270. req = compat_urllib_request.Request(
  1271. url_escaped, data=req.data, headers=req.headers,
  1272. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1273. return self._opener.open(req, timeout=self._socket_timeout)
  1274. def print_debug_header(self):
  1275. if not self.params.get('verbose'):
  1276. return
  1277. if type('') is not compat_str:
  1278. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1279. self.report_warning(
  1280. 'Your Python is broken! Update to a newer and supported version')
  1281. stdout_encoding = getattr(
  1282. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1283. encoding_str = (
  1284. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1285. locale.getpreferredencoding(),
  1286. sys.getfilesystemencoding(),
  1287. stdout_encoding,
  1288. self.get_encoding()))
  1289. write_string(encoding_str, encoding=None)
  1290. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1291. try:
  1292. sp = subprocess.Popen(
  1293. ['git', 'rev-parse', '--short', 'HEAD'],
  1294. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1295. cwd=os.path.dirname(os.path.abspath(__file__)))
  1296. out, err = sp.communicate()
  1297. out = out.decode().strip()
  1298. if re.match('[0-9a-f]+', out):
  1299. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1300. except:
  1301. try:
  1302. sys.exc_clear()
  1303. except:
  1304. pass
  1305. self._write_string('[debug] Python version %s - %s\n' % (
  1306. platform.python_version(), platform_name()))
  1307. exe_versions = FFmpegPostProcessor.get_versions()
  1308. exe_versions['rtmpdump'] = rtmpdump_version()
  1309. exe_str = ', '.join(
  1310. '%s %s' % (exe, v)
  1311. for exe, v in sorted(exe_versions.items())
  1312. if v
  1313. )
  1314. if not exe_str:
  1315. exe_str = 'none'
  1316. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1317. proxy_map = {}
  1318. for handler in self._opener.handlers:
  1319. if hasattr(handler, 'proxies'):
  1320. proxy_map.update(handler.proxies)
  1321. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1322. if self.params.get('call_home', False):
  1323. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1324. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1325. latest_version = self.urlopen(
  1326. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1327. if version_tuple(latest_version) > version_tuple(__version__):
  1328. self.report_warning(
  1329. 'You are using an outdated version (newest version: %s)! '
  1330. 'See https://yt-dl.org/update if you need help updating.' %
  1331. latest_version)
  1332. def _setup_opener(self):
  1333. timeout_val = self.params.get('socket_timeout')
  1334. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1335. opts_cookiefile = self.params.get('cookiefile')
  1336. opts_proxy = self.params.get('proxy')
  1337. if opts_cookiefile is None:
  1338. self.cookiejar = compat_cookiejar.CookieJar()
  1339. else:
  1340. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1341. opts_cookiefile)
  1342. if os.access(opts_cookiefile, os.R_OK):
  1343. self.cookiejar.load()
  1344. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1345. self.cookiejar)
  1346. if opts_proxy is not None:
  1347. if opts_proxy == '':
  1348. proxies = {}
  1349. else:
  1350. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1351. else:
  1352. proxies = compat_urllib_request.getproxies()
  1353. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1354. if 'http' in proxies and 'https' not in proxies:
  1355. proxies['https'] = proxies['http']
  1356. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1357. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1358. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1359. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1360. opener = compat_urllib_request.build_opener(
  1361. https_handler, proxy_handler, cookie_processor, ydlh)
  1362. # Delete the default user-agent header, which would otherwise apply in
  1363. # cases where our custom HTTP handler doesn't come into play
  1364. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1365. opener.addheaders = []
  1366. self._opener = opener
  1367. def encode(self, s):
  1368. if isinstance(s, bytes):
  1369. return s # Already encoded
  1370. try:
  1371. return s.encode(self.get_encoding())
  1372. except UnicodeEncodeError as err:
  1373. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1374. raise
  1375. def get_encoding(self):
  1376. encoding = self.params.get('encoding')
  1377. if encoding is None:
  1378. encoding = preferredencoding()
  1379. return encoding