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.

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