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. source_address: (Experimental) Client-side IP address to bind to.
  201. The following parameters are not used by YoutubeDL itself, they are used by
  202. the FileDownloader:
  203. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  204. noresizebuffer, retries, continuedl, noprogress, consoletitle
  205. The following options are used by the post processors:
  206. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  207. otherwise prefer avconv.
  208. exec_cmd: Arbitrary command to run after downloading
  209. """
  210. params = None
  211. _ies = []
  212. _pps = []
  213. _download_retcode = None
  214. _num_downloads = None
  215. _screen_file = None
  216. def __init__(self, params=None, auto_init=True):
  217. """Create a FileDownloader object with the given options."""
  218. if params is None:
  219. params = {}
  220. self._ies = []
  221. self._ies_instances = {}
  222. self._pps = []
  223. self._progress_hooks = []
  224. self._download_retcode = 0
  225. self._num_downloads = 0
  226. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  227. self._err_file = sys.stderr
  228. self.params = params
  229. self.cache = Cache(self)
  230. if params.get('bidi_workaround', False):
  231. try:
  232. import pty
  233. master, slave = pty.openpty()
  234. width = get_term_width()
  235. if width is None:
  236. width_args = []
  237. else:
  238. width_args = ['-w', str(width)]
  239. sp_kwargs = dict(
  240. stdin=subprocess.PIPE,
  241. stdout=slave,
  242. stderr=self._err_file)
  243. try:
  244. self._output_process = subprocess.Popen(
  245. ['bidiv'] + width_args, **sp_kwargs
  246. )
  247. except OSError:
  248. self._output_process = subprocess.Popen(
  249. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  250. self._output_channel = os.fdopen(master, 'rb')
  251. except OSError as ose:
  252. if ose.errno == 2:
  253. 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.')
  254. else:
  255. raise
  256. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  257. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  258. and not params.get('restrictfilenames', False)):
  259. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  260. self.report_warning(
  261. 'Assuming --restrict-filenames since file system encoding '
  262. 'cannot encode all characters. '
  263. 'Set the LC_ALL environment variable to fix this.')
  264. self.params['restrictfilenames'] = True
  265. if '%(stitle)s' in self.params.get('outtmpl', ''):
  266. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  267. self._setup_opener()
  268. if auto_init:
  269. self.print_debug_header()
  270. self.add_default_info_extractors()
  271. for pp_def_raw in self.params.get('postprocessors', []):
  272. pp_class = get_postprocessor(pp_def_raw['key'])
  273. pp_def = dict(pp_def_raw)
  274. del pp_def['key']
  275. pp = pp_class(self, **compat_kwargs(pp_def))
  276. self.add_post_processor(pp)
  277. for ph in self.params.get('progress_hooks', []):
  278. self.add_progress_hook(ph)
  279. def warn_if_short_id(self, argv):
  280. # short YouTube ID starting with dash?
  281. idxs = [
  282. i for i, a in enumerate(argv)
  283. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  284. if idxs:
  285. correct_argv = (
  286. ['youtube-dl'] +
  287. [a for i, a in enumerate(argv) if i not in idxs] +
  288. ['--'] + [argv[i] for i in idxs]
  289. )
  290. self.report_warning(
  291. 'Long argument string detected. '
  292. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  293. args_to_str(correct_argv))
  294. def add_info_extractor(self, ie):
  295. """Add an InfoExtractor object to the end of the list."""
  296. self._ies.append(ie)
  297. self._ies_instances[ie.ie_key()] = ie
  298. ie.set_downloader(self)
  299. def get_info_extractor(self, ie_key):
  300. """
  301. Get an instance of an IE with name ie_key, it will try to get one from
  302. the _ies list, if there's no instance it will create a new one and add
  303. it to the extractor list.
  304. """
  305. ie = self._ies_instances.get(ie_key)
  306. if ie is None:
  307. ie = get_info_extractor(ie_key)()
  308. self.add_info_extractor(ie)
  309. return ie
  310. def add_default_info_extractors(self):
  311. """
  312. Add the InfoExtractors returned by gen_extractors to the end of the list
  313. """
  314. for ie in gen_extractors():
  315. self.add_info_extractor(ie)
  316. def add_post_processor(self, pp):
  317. """Add a PostProcessor object to the end of the chain."""
  318. self._pps.append(pp)
  319. pp.set_downloader(self)
  320. def add_progress_hook(self, ph):
  321. """Add the progress hook (currently only for the file downloader)"""
  322. self._progress_hooks.append(ph)
  323. def _bidi_workaround(self, message):
  324. if not hasattr(self, '_output_channel'):
  325. return message
  326. assert hasattr(self, '_output_process')
  327. assert isinstance(message, compat_str)
  328. line_count = message.count('\n') + 1
  329. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  330. self._output_process.stdin.flush()
  331. res = ''.join(self._output_channel.readline().decode('utf-8')
  332. for _ in range(line_count))
  333. return res[:-len('\n')]
  334. def to_screen(self, message, skip_eol=False):
  335. """Print message to stdout if not in quiet mode."""
  336. return self.to_stdout(message, skip_eol, check_quiet=True)
  337. def _write_string(self, s, out=None):
  338. write_string(s, out=out, encoding=self.params.get('encoding'))
  339. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  340. """Print message to stdout if not in quiet mode."""
  341. if self.params.get('logger'):
  342. self.params['logger'].debug(message)
  343. elif not check_quiet or not self.params.get('quiet', False):
  344. message = self._bidi_workaround(message)
  345. terminator = ['\n', ''][skip_eol]
  346. output = message + terminator
  347. self._write_string(output, self._screen_file)
  348. def to_stderr(self, message):
  349. """Print message to stderr."""
  350. assert isinstance(message, compat_str)
  351. if self.params.get('logger'):
  352. self.params['logger'].error(message)
  353. else:
  354. message = self._bidi_workaround(message)
  355. output = message + '\n'
  356. self._write_string(output, self._err_file)
  357. def to_console_title(self, message):
  358. if not self.params.get('consoletitle', False):
  359. return
  360. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  361. # c_wchar_p() might not be necessary if `message` is
  362. # already of type unicode()
  363. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  364. elif 'TERM' in os.environ:
  365. self._write_string('\033]0;%s\007' % message, self._screen_file)
  366. def save_console_title(self):
  367. if not self.params.get('consoletitle', False):
  368. return
  369. if 'TERM' in os.environ:
  370. # Save the title on stack
  371. self._write_string('\033[22;0t', self._screen_file)
  372. def restore_console_title(self):
  373. if not self.params.get('consoletitle', False):
  374. return
  375. if 'TERM' in os.environ:
  376. # Restore the title from stack
  377. self._write_string('\033[23;0t', self._screen_file)
  378. def __enter__(self):
  379. self.save_console_title()
  380. return self
  381. def __exit__(self, *args):
  382. self.restore_console_title()
  383. if self.params.get('cookiefile') is not None:
  384. self.cookiejar.save()
  385. def trouble(self, message=None, tb=None):
  386. """Determine action to take when a download problem appears.
  387. Depending on if the downloader has been configured to ignore
  388. download errors or not, this method may throw an exception or
  389. not when errors are found, after printing the message.
  390. tb, if given, is additional traceback information.
  391. """
  392. if message is not None:
  393. self.to_stderr(message)
  394. if self.params.get('verbose'):
  395. if tb is None:
  396. if sys.exc_info()[0]: # if .trouble has been called from an except block
  397. tb = ''
  398. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  399. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  400. tb += compat_str(traceback.format_exc())
  401. else:
  402. tb_data = traceback.format_list(traceback.extract_stack())
  403. tb = ''.join(tb_data)
  404. self.to_stderr(tb)
  405. if not self.params.get('ignoreerrors', False):
  406. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  407. exc_info = sys.exc_info()[1].exc_info
  408. else:
  409. exc_info = sys.exc_info()
  410. raise DownloadError(message, exc_info)
  411. self._download_retcode = 1
  412. def report_warning(self, message):
  413. '''
  414. Print the message to stderr, it will be prefixed with 'WARNING:'
  415. If stderr is a tty file the 'WARNING:' will be colored
  416. '''
  417. if self.params.get('logger') is not None:
  418. self.params['logger'].warning(message)
  419. else:
  420. if self.params.get('no_warnings'):
  421. return
  422. if self._err_file.isatty() and os.name != 'nt':
  423. _msg_header = '\033[0;33mWARNING:\033[0m'
  424. else:
  425. _msg_header = 'WARNING:'
  426. warning_message = '%s %s' % (_msg_header, message)
  427. self.to_stderr(warning_message)
  428. def report_error(self, message, tb=None):
  429. '''
  430. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  431. in red if stderr is a tty file.
  432. '''
  433. if self._err_file.isatty() and os.name != 'nt':
  434. _msg_header = '\033[0;31mERROR:\033[0m'
  435. else:
  436. _msg_header = 'ERROR:'
  437. error_message = '%s %s' % (_msg_header, message)
  438. self.trouble(error_message, tb)
  439. def report_file_already_downloaded(self, file_name):
  440. """Report file has already been fully downloaded."""
  441. try:
  442. self.to_screen('[download] %s has already been downloaded' % file_name)
  443. except UnicodeEncodeError:
  444. self.to_screen('[download] The file has already been downloaded')
  445. def prepare_filename(self, info_dict):
  446. """Generate the output filename."""
  447. try:
  448. template_dict = dict(info_dict)
  449. template_dict['epoch'] = int(time.time())
  450. autonumber_size = self.params.get('autonumber_size')
  451. if autonumber_size is None:
  452. autonumber_size = 5
  453. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  454. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  455. if template_dict.get('playlist_index') is not None:
  456. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  457. if template_dict.get('resolution') is None:
  458. if template_dict.get('width') and template_dict.get('height'):
  459. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  460. elif template_dict.get('height'):
  461. template_dict['resolution'] = '%sp' % template_dict['height']
  462. elif template_dict.get('width'):
  463. template_dict['resolution'] = '?x%d' % template_dict['width']
  464. sanitize = lambda k, v: sanitize_filename(
  465. compat_str(v),
  466. restricted=self.params.get('restrictfilenames'),
  467. is_id=(k == 'id'))
  468. template_dict = dict((k, sanitize(k, v))
  469. for k, v in template_dict.items()
  470. if v is not None)
  471. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  472. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  473. tmpl = compat_expanduser(outtmpl)
  474. filename = tmpl % template_dict
  475. return filename
  476. except ValueError as err:
  477. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  478. return None
  479. def _match_entry(self, info_dict):
  480. """ Returns None iff the file should be downloaded """
  481. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  482. if 'title' in info_dict:
  483. # This can happen when we're just evaluating the playlist
  484. title = info_dict['title']
  485. matchtitle = self.params.get('matchtitle', False)
  486. if matchtitle:
  487. if not re.search(matchtitle, title, re.IGNORECASE):
  488. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  489. rejecttitle = self.params.get('rejecttitle', False)
  490. if rejecttitle:
  491. if re.search(rejecttitle, title, re.IGNORECASE):
  492. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  493. date = info_dict.get('upload_date', None)
  494. if date is not None:
  495. dateRange = self.params.get('daterange', DateRange())
  496. if date not in dateRange:
  497. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  498. view_count = info_dict.get('view_count', None)
  499. if view_count is not None:
  500. min_views = self.params.get('min_views')
  501. if min_views is not None and view_count < min_views:
  502. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  503. max_views = self.params.get('max_views')
  504. if max_views is not None and view_count > max_views:
  505. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  506. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  507. return 'Skipping "%s" because it is age restricted' % title
  508. if self.in_download_archive(info_dict):
  509. return '%s has already been recorded in archive' % video_title
  510. return None
  511. @staticmethod
  512. def add_extra_info(info_dict, extra_info):
  513. '''Set the keys from extra_info in info dict if they are missing'''
  514. for key, value in extra_info.items():
  515. info_dict.setdefault(key, value)
  516. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  517. process=True):
  518. '''
  519. Returns a list with a dictionary for each video we find.
  520. If 'download', also downloads the videos.
  521. extra_info is a dict containing the extra values to add to each result
  522. '''
  523. if ie_key:
  524. ies = [self.get_info_extractor(ie_key)]
  525. else:
  526. ies = self._ies
  527. for ie in ies:
  528. if not ie.suitable(url):
  529. continue
  530. if not ie.working():
  531. self.report_warning('The program functionality for this site has been marked as broken, '
  532. 'and will probably not work.')
  533. try:
  534. ie_result = ie.extract(url)
  535. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  536. break
  537. if isinstance(ie_result, list):
  538. # Backwards compatibility: old IE result format
  539. ie_result = {
  540. '_type': 'compat_list',
  541. 'entries': ie_result,
  542. }
  543. self.add_default_extra_info(ie_result, ie, url)
  544. if process:
  545. return self.process_ie_result(ie_result, download, extra_info)
  546. else:
  547. return ie_result
  548. except ExtractorError as de: # An error we somewhat expected
  549. self.report_error(compat_str(de), de.format_traceback())
  550. break
  551. except MaxDownloadsReached:
  552. raise
  553. except Exception as e:
  554. if self.params.get('ignoreerrors', False):
  555. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  556. break
  557. else:
  558. raise
  559. else:
  560. self.report_error('no suitable InfoExtractor for URL %s' % url)
  561. def add_default_extra_info(self, ie_result, ie, url):
  562. self.add_extra_info(ie_result, {
  563. 'extractor': ie.IE_NAME,
  564. 'webpage_url': url,
  565. 'webpage_url_basename': url_basename(url),
  566. 'extractor_key': ie.ie_key(),
  567. })
  568. def process_ie_result(self, ie_result, download=True, extra_info={}):
  569. """
  570. Take the result of the ie(may be modified) and resolve all unresolved
  571. references (URLs, playlist items).
  572. It will also download the videos if 'download'.
  573. Returns the resolved ie_result.
  574. """
  575. result_type = ie_result.get('_type', 'video')
  576. if result_type in ('url', 'url_transparent'):
  577. extract_flat = self.params.get('extract_flat', False)
  578. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  579. extract_flat is True):
  580. if self.params.get('forcejson', False):
  581. self.to_stdout(json.dumps(ie_result))
  582. return ie_result
  583. if result_type == 'video':
  584. self.add_extra_info(ie_result, extra_info)
  585. return self.process_video_result(ie_result, download=download)
  586. elif result_type == 'url':
  587. # We have to add extra_info to the results because it may be
  588. # contained in a playlist
  589. return self.extract_info(ie_result['url'],
  590. download,
  591. ie_key=ie_result.get('ie_key'),
  592. extra_info=extra_info)
  593. elif result_type == 'url_transparent':
  594. # Use the information from the embedding page
  595. info = self.extract_info(
  596. ie_result['url'], ie_key=ie_result.get('ie_key'),
  597. extra_info=extra_info, download=False, process=False)
  598. force_properties = dict(
  599. (k, v) for k, v in ie_result.items() if v is not None)
  600. for f in ('_type', 'url'):
  601. if f in force_properties:
  602. del force_properties[f]
  603. new_result = info.copy()
  604. new_result.update(force_properties)
  605. assert new_result.get('_type') != 'url_transparent'
  606. return self.process_ie_result(
  607. new_result, download=download, extra_info=extra_info)
  608. elif result_type == 'playlist' or result_type == 'multi_video':
  609. # We process each entry in the playlist
  610. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  611. self.to_screen('[download] Downloading playlist: %s' % playlist)
  612. playlist_results = []
  613. playliststart = self.params.get('playliststart', 1) - 1
  614. playlistend = self.params.get('playlistend', None)
  615. # For backwards compatibility, interpret -1 as whole list
  616. if playlistend == -1:
  617. playlistend = None
  618. ie_entries = ie_result['entries']
  619. if isinstance(ie_entries, list):
  620. n_all_entries = len(ie_entries)
  621. entries = ie_entries[playliststart:playlistend]
  622. n_entries = len(entries)
  623. self.to_screen(
  624. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  625. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  626. elif isinstance(ie_entries, PagedList):
  627. entries = ie_entries.getslice(
  628. playliststart, playlistend)
  629. n_entries = len(entries)
  630. self.to_screen(
  631. "[%s] playlist %s: Downloading %d videos" %
  632. (ie_result['extractor'], playlist, n_entries))
  633. else: # iterable
  634. entries = list(itertools.islice(
  635. ie_entries, playliststart, playlistend))
  636. n_entries = len(entries)
  637. self.to_screen(
  638. "[%s] playlist %s: Downloading %d videos" %
  639. (ie_result['extractor'], playlist, n_entries))
  640. if self.params.get('playlistreverse', False):
  641. entries = entries[::-1]
  642. for i, entry in enumerate(entries, 1):
  643. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  644. extra = {
  645. 'n_entries': n_entries,
  646. 'playlist': playlist,
  647. 'playlist_id': ie_result.get('id'),
  648. 'playlist_title': ie_result.get('title'),
  649. 'playlist_index': i + playliststart,
  650. 'extractor': ie_result['extractor'],
  651. 'webpage_url': ie_result['webpage_url'],
  652. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  653. 'extractor_key': ie_result['extractor_key'],
  654. }
  655. reason = self._match_entry(entry)
  656. if reason is not None:
  657. self.to_screen('[download] ' + reason)
  658. continue
  659. entry_result = self.process_ie_result(entry,
  660. download=download,
  661. extra_info=extra)
  662. playlist_results.append(entry_result)
  663. ie_result['entries'] = playlist_results
  664. return ie_result
  665. elif result_type == 'compat_list':
  666. self.report_warning(
  667. 'Extractor %s returned a compat_list result. '
  668. 'It needs to be updated.' % ie_result.get('extractor'))
  669. def _fixup(r):
  670. self.add_extra_info(
  671. r,
  672. {
  673. 'extractor': ie_result['extractor'],
  674. 'webpage_url': ie_result['webpage_url'],
  675. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  676. 'extractor_key': ie_result['extractor_key'],
  677. }
  678. )
  679. return r
  680. ie_result['entries'] = [
  681. self.process_ie_result(_fixup(r), download, extra_info)
  682. for r in ie_result['entries']
  683. ]
  684. return ie_result
  685. else:
  686. raise Exception('Invalid result type: %s' % result_type)
  687. def select_format(self, format_spec, available_formats):
  688. if format_spec == 'best' or format_spec is None:
  689. return available_formats[-1]
  690. elif format_spec == 'worst':
  691. return available_formats[0]
  692. elif format_spec == 'bestaudio':
  693. audio_formats = [
  694. f for f in available_formats
  695. if f.get('vcodec') == 'none']
  696. if audio_formats:
  697. return audio_formats[-1]
  698. elif format_spec == 'worstaudio':
  699. audio_formats = [
  700. f for f in available_formats
  701. if f.get('vcodec') == 'none']
  702. if audio_formats:
  703. return audio_formats[0]
  704. elif format_spec == 'bestvideo':
  705. video_formats = [
  706. f for f in available_formats
  707. if f.get('acodec') == 'none']
  708. if video_formats:
  709. return video_formats[-1]
  710. elif format_spec == 'worstvideo':
  711. video_formats = [
  712. f for f in available_formats
  713. if f.get('acodec') == 'none']
  714. if video_formats:
  715. return video_formats[0]
  716. else:
  717. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  718. if format_spec in extensions:
  719. filter_f = lambda f: f['ext'] == format_spec
  720. else:
  721. filter_f = lambda f: f['format_id'] == format_spec
  722. matches = list(filter(filter_f, available_formats))
  723. if matches:
  724. return matches[-1]
  725. return None
  726. def process_video_result(self, info_dict, download=True):
  727. assert info_dict.get('_type', 'video') == 'video'
  728. if 'id' not in info_dict:
  729. raise ExtractorError('Missing "id" field in extractor result')
  730. if 'title' not in info_dict:
  731. raise ExtractorError('Missing "title" field in extractor result')
  732. if 'playlist' not in info_dict:
  733. # It isn't part of a playlist
  734. info_dict['playlist'] = None
  735. info_dict['playlist_index'] = None
  736. thumbnails = info_dict.get('thumbnails')
  737. if thumbnails:
  738. thumbnails.sort(key=lambda t: (
  739. t.get('width'), t.get('height'), t.get('url')))
  740. for t in thumbnails:
  741. if 'width' in t and 'height' in t:
  742. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  743. if thumbnails and 'thumbnail' not in info_dict:
  744. info_dict['thumbnail'] = thumbnails[-1]['url']
  745. if 'display_id' not in info_dict and 'id' in info_dict:
  746. info_dict['display_id'] = info_dict['id']
  747. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  748. # Working around negative timestamps in Windows
  749. # (see http://bugs.python.org/issue1646728)
  750. if info_dict['timestamp'] < 0 and os.name == 'nt':
  751. info_dict['timestamp'] = 0
  752. upload_date = datetime.datetime.utcfromtimestamp(
  753. info_dict['timestamp'])
  754. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  755. # This extractors handle format selection themselves
  756. if info_dict['extractor'] in ['Youku']:
  757. if download:
  758. self.process_info(info_dict)
  759. return info_dict
  760. # We now pick which formats have to be downloaded
  761. if info_dict.get('formats') is None:
  762. # There's only one format available
  763. formats = [info_dict]
  764. else:
  765. formats = info_dict['formats']
  766. if not formats:
  767. raise ExtractorError('No video formats found!')
  768. # We check that all the formats have the format and format_id fields
  769. for i, format in enumerate(formats):
  770. if 'url' not in format:
  771. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  772. if format.get('format_id') is None:
  773. format['format_id'] = compat_str(i)
  774. if format.get('format') is None:
  775. format['format'] = '{id} - {res}{note}'.format(
  776. id=format['format_id'],
  777. res=self.format_resolution(format),
  778. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  779. )
  780. # Automatically determine file extension if missing
  781. if 'ext' not in format:
  782. format['ext'] = determine_ext(format['url']).lower()
  783. format_limit = self.params.get('format_limit', None)
  784. if format_limit:
  785. formats = list(takewhile_inclusive(
  786. lambda f: f['format_id'] != format_limit, formats
  787. ))
  788. # TODO Central sorting goes here
  789. if formats[0] is not info_dict:
  790. # only set the 'formats' fields if the original info_dict list them
  791. # otherwise we end up with a circular reference, the first (and unique)
  792. # element in the 'formats' field in info_dict is info_dict itself,
  793. # wich can't be exported to json
  794. info_dict['formats'] = formats
  795. if self.params.get('listformats', None):
  796. self.list_formats(info_dict)
  797. return
  798. req_format = self.params.get('format')
  799. if req_format is None:
  800. req_format = 'best'
  801. formats_to_download = []
  802. # The -1 is for supporting YoutubeIE
  803. if req_format in ('-1', 'all'):
  804. formats_to_download = formats
  805. else:
  806. for rfstr in req_format.split(','):
  807. # We can accept formats requested in the format: 34/5/best, we pick
  808. # the first that is available, starting from left
  809. req_formats = rfstr.split('/')
  810. for rf in req_formats:
  811. if re.match(r'.+?\+.+?', rf) is not None:
  812. # Two formats have been requested like '137+139'
  813. format_1, format_2 = rf.split('+')
  814. formats_info = (self.select_format(format_1, formats),
  815. self.select_format(format_2, formats))
  816. if all(formats_info):
  817. # The first format must contain the video and the
  818. # second the audio
  819. if formats_info[0].get('vcodec') == 'none':
  820. self.report_error('The first format must '
  821. 'contain the video, try using '
  822. '"-f %s+%s"' % (format_2, format_1))
  823. return
  824. output_ext = (
  825. formats_info[0]['ext']
  826. if self.params.get('merge_output_format') is None
  827. else self.params['merge_output_format'])
  828. selected_format = {
  829. 'requested_formats': formats_info,
  830. 'format': rf,
  831. 'ext': formats_info[0]['ext'],
  832. 'width': formats_info[0].get('width'),
  833. 'height': formats_info[0].get('height'),
  834. 'resolution': formats_info[0].get('resolution'),
  835. 'fps': formats_info[0].get('fps'),
  836. 'vcodec': formats_info[0].get('vcodec'),
  837. 'vbr': formats_info[0].get('vbr'),
  838. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  839. 'acodec': formats_info[1].get('acodec'),
  840. 'abr': formats_info[1].get('abr'),
  841. 'ext': output_ext,
  842. }
  843. else:
  844. selected_format = None
  845. else:
  846. selected_format = self.select_format(rf, formats)
  847. if selected_format is not None:
  848. formats_to_download.append(selected_format)
  849. break
  850. if not formats_to_download:
  851. raise ExtractorError('requested format not available',
  852. expected=True)
  853. if download:
  854. if len(formats_to_download) > 1:
  855. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  856. for format in formats_to_download:
  857. new_info = dict(info_dict)
  858. new_info.update(format)
  859. self.process_info(new_info)
  860. # We update the info dict with the best quality format (backwards compatibility)
  861. info_dict.update(formats_to_download[-1])
  862. return info_dict
  863. def process_info(self, info_dict):
  864. """Process a single resolved IE result."""
  865. assert info_dict.get('_type', 'video') == 'video'
  866. max_downloads = self.params.get('max_downloads')
  867. if max_downloads is not None:
  868. if self._num_downloads >= int(max_downloads):
  869. raise MaxDownloadsReached()
  870. info_dict['fulltitle'] = info_dict['title']
  871. if len(info_dict['title']) > 200:
  872. info_dict['title'] = info_dict['title'][:197] + '...'
  873. # Keep for backwards compatibility
  874. info_dict['stitle'] = info_dict['title']
  875. if 'format' not in info_dict:
  876. info_dict['format'] = info_dict['ext']
  877. reason = self._match_entry(info_dict)
  878. if reason is not None:
  879. self.to_screen('[download] ' + reason)
  880. return
  881. self._num_downloads += 1
  882. filename = self.prepare_filename(info_dict)
  883. # Forced printings
  884. if self.params.get('forcetitle', False):
  885. self.to_stdout(info_dict['fulltitle'])
  886. if self.params.get('forceid', False):
  887. self.to_stdout(info_dict['id'])
  888. if self.params.get('forceurl', False):
  889. if info_dict.get('requested_formats') is not None:
  890. for f in info_dict['requested_formats']:
  891. self.to_stdout(f['url'] + f.get('play_path', ''))
  892. else:
  893. # For RTMP URLs, also include the playpath
  894. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  895. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  896. self.to_stdout(info_dict['thumbnail'])
  897. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  898. self.to_stdout(info_dict['description'])
  899. if self.params.get('forcefilename', False) and filename is not None:
  900. self.to_stdout(filename)
  901. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  902. self.to_stdout(formatSeconds(info_dict['duration']))
  903. if self.params.get('forceformat', False):
  904. self.to_stdout(info_dict['format'])
  905. if self.params.get('forcejson', False):
  906. info_dict['_filename'] = filename
  907. self.to_stdout(json.dumps(info_dict))
  908. if self.params.get('dump_single_json', False):
  909. info_dict['_filename'] = filename
  910. # Do nothing else if in simulate mode
  911. if self.params.get('simulate', False):
  912. return
  913. if filename is None:
  914. return
  915. try:
  916. dn = os.path.dirname(encodeFilename(filename))
  917. if dn and not os.path.exists(dn):
  918. os.makedirs(dn)
  919. except (OSError, IOError) as err:
  920. self.report_error('unable to create directory ' + compat_str(err))
  921. return
  922. if self.params.get('writedescription', False):
  923. descfn = filename + '.description'
  924. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  925. self.to_screen('[info] Video description is already present')
  926. elif info_dict.get('description') is None:
  927. self.report_warning('There\'s no description to write.')
  928. else:
  929. try:
  930. self.to_screen('[info] Writing video description to: ' + descfn)
  931. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  932. descfile.write(info_dict['description'])
  933. except (OSError, IOError):
  934. self.report_error('Cannot write description file ' + descfn)
  935. return
  936. if self.params.get('writeannotations', False):
  937. annofn = filename + '.annotations.xml'
  938. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  939. self.to_screen('[info] Video annotations are already present')
  940. else:
  941. try:
  942. self.to_screen('[info] Writing video annotations to: ' + annofn)
  943. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  944. annofile.write(info_dict['annotations'])
  945. except (KeyError, TypeError):
  946. self.report_warning('There are no annotations to write.')
  947. except (OSError, IOError):
  948. self.report_error('Cannot write annotations file: ' + annofn)
  949. return
  950. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  951. self.params.get('writeautomaticsub')])
  952. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  953. # subtitles download errors are already managed as troubles in relevant IE
  954. # that way it will silently go on when used with unsupporting IE
  955. subtitles = info_dict['subtitles']
  956. sub_format = self.params.get('subtitlesformat', 'srt')
  957. for sub_lang in subtitles.keys():
  958. sub = subtitles[sub_lang]
  959. if sub is None:
  960. continue
  961. try:
  962. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  963. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  964. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  965. else:
  966. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  967. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  968. subfile.write(sub)
  969. except (OSError, IOError):
  970. self.report_error('Cannot write subtitles file ' + sub_filename)
  971. return
  972. if self.params.get('writeinfojson', False):
  973. infofn = os.path.splitext(filename)[0] + '.info.json'
  974. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  975. self.to_screen('[info] Video description metadata is already present')
  976. else:
  977. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  978. try:
  979. write_json_file(info_dict, infofn)
  980. except (OSError, IOError):
  981. self.report_error('Cannot write metadata to JSON file ' + infofn)
  982. return
  983. if self.params.get('writethumbnail', False):
  984. if info_dict.get('thumbnail') is not None:
  985. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  986. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  987. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  988. self.to_screen('[%s] %s: Thumbnail is already present' %
  989. (info_dict['extractor'], info_dict['id']))
  990. else:
  991. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  992. (info_dict['extractor'], info_dict['id']))
  993. try:
  994. uf = self.urlopen(info_dict['thumbnail'])
  995. with open(thumb_filename, 'wb') as thumbf:
  996. shutil.copyfileobj(uf, thumbf)
  997. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  998. (info_dict['extractor'], info_dict['id'], thumb_filename))
  999. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1000. self.report_warning('Unable to download thumbnail "%s": %s' %
  1001. (info_dict['thumbnail'], compat_str(err)))
  1002. if not self.params.get('skip_download', False):
  1003. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  1004. success = True
  1005. else:
  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. keep_video = None
  1111. pps_chain = []
  1112. if ie_info.get('__postprocessors') is not None:
  1113. pps_chain.extend(ie_info['__postprocessors'])
  1114. pps_chain.extend(self._pps)
  1115. for pp in pps_chain:
  1116. try:
  1117. keep_video_wish, new_info = pp.run(info)
  1118. if keep_video_wish is not None:
  1119. if keep_video_wish:
  1120. keep_video = keep_video_wish
  1121. elif keep_video is None:
  1122. # No clear decision yet, let IE decide
  1123. keep_video = keep_video_wish
  1124. except PostProcessingError as e:
  1125. self.report_error(e.msg)
  1126. if keep_video is False and not self.params.get('keepvideo', False):
  1127. try:
  1128. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  1129. os.remove(encodeFilename(filename))
  1130. except (IOError, OSError):
  1131. self.report_warning('Unable to remove downloaded video file')
  1132. def _make_archive_id(self, info_dict):
  1133. # Future-proof against any change in case
  1134. # and backwards compatibility with prior versions
  1135. extractor = info_dict.get('extractor_key')
  1136. if extractor is None:
  1137. if 'id' in info_dict:
  1138. extractor = info_dict.get('ie_key') # key in a playlist
  1139. if extractor is None:
  1140. return None # Incomplete video information
  1141. return extractor.lower() + ' ' + info_dict['id']
  1142. def in_download_archive(self, info_dict):
  1143. fn = self.params.get('download_archive')
  1144. if fn is None:
  1145. return False
  1146. vid_id = self._make_archive_id(info_dict)
  1147. if vid_id is None:
  1148. return False # Incomplete video information
  1149. try:
  1150. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1151. for line in archive_file:
  1152. if line.strip() == vid_id:
  1153. return True
  1154. except IOError as ioe:
  1155. if ioe.errno != errno.ENOENT:
  1156. raise
  1157. return False
  1158. def record_download_archive(self, info_dict):
  1159. fn = self.params.get('download_archive')
  1160. if fn is None:
  1161. return
  1162. vid_id = self._make_archive_id(info_dict)
  1163. assert vid_id
  1164. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1165. archive_file.write(vid_id + '\n')
  1166. @staticmethod
  1167. def format_resolution(format, default='unknown'):
  1168. if format.get('vcodec') == 'none':
  1169. return 'audio only'
  1170. if format.get('resolution') is not None:
  1171. return format['resolution']
  1172. if format.get('height') is not None:
  1173. if format.get('width') is not None:
  1174. res = '%sx%s' % (format['width'], format['height'])
  1175. else:
  1176. res = '%sp' % format['height']
  1177. elif format.get('width') is not None:
  1178. res = '?x%d' % format['width']
  1179. else:
  1180. res = default
  1181. return res
  1182. def _format_note(self, fdict):
  1183. res = ''
  1184. if fdict.get('ext') in ['f4f', 'f4m']:
  1185. res += '(unsupported) '
  1186. if fdict.get('format_note') is not None:
  1187. res += fdict['format_note'] + ' '
  1188. if fdict.get('tbr') is not None:
  1189. res += '%4dk ' % fdict['tbr']
  1190. if fdict.get('container') is not None:
  1191. if res:
  1192. res += ', '
  1193. res += '%s container' % fdict['container']
  1194. if (fdict.get('vcodec') is not None and
  1195. fdict.get('vcodec') != 'none'):
  1196. if res:
  1197. res += ', '
  1198. res += fdict['vcodec']
  1199. if fdict.get('vbr') is not None:
  1200. res += '@'
  1201. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1202. res += 'video@'
  1203. if fdict.get('vbr') is not None:
  1204. res += '%4dk' % fdict['vbr']
  1205. if fdict.get('fps') is not None:
  1206. res += ', %sfps' % fdict['fps']
  1207. if fdict.get('acodec') is not None:
  1208. if res:
  1209. res += ', '
  1210. if fdict['acodec'] == 'none':
  1211. res += 'video only'
  1212. else:
  1213. res += '%-5s' % fdict['acodec']
  1214. elif fdict.get('abr') is not None:
  1215. if res:
  1216. res += ', '
  1217. res += 'audio'
  1218. if fdict.get('abr') is not None:
  1219. res += '@%3dk' % fdict['abr']
  1220. if fdict.get('asr') is not None:
  1221. res += ' (%5dHz)' % fdict['asr']
  1222. if fdict.get('filesize') is not None:
  1223. if res:
  1224. res += ', '
  1225. res += format_bytes(fdict['filesize'])
  1226. elif fdict.get('filesize_approx') is not None:
  1227. if res:
  1228. res += ', '
  1229. res += '~' + format_bytes(fdict['filesize_approx'])
  1230. return res
  1231. def list_formats(self, info_dict):
  1232. def line(format, idlen=20):
  1233. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1234. format['format_id'],
  1235. format['ext'],
  1236. self.format_resolution(format),
  1237. self._format_note(format),
  1238. ))
  1239. formats = info_dict.get('formats', [info_dict])
  1240. idlen = max(len('format code'),
  1241. max(len(f['format_id']) for f in formats))
  1242. formats_s = [
  1243. line(f, idlen) for f in formats
  1244. if f.get('preference') is None or f['preference'] >= -1000]
  1245. if len(formats) > 1:
  1246. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1247. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1248. header_line = line({
  1249. 'format_id': 'format code', 'ext': 'extension',
  1250. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1251. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1252. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1253. def urlopen(self, req):
  1254. """ Start an HTTP download """
  1255. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1256. # always respected by websites, some tend to give out URLs with non percent-encoded
  1257. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1258. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1259. # To work around aforementioned issue we will replace request's original URL with
  1260. # percent-encoded one
  1261. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1262. url = req if req_is_string else req.get_full_url()
  1263. url_escaped = escape_url(url)
  1264. # Substitute URL if any change after escaping
  1265. if url != url_escaped:
  1266. if req_is_string:
  1267. req = url_escaped
  1268. else:
  1269. req = compat_urllib_request.Request(
  1270. url_escaped, data=req.data, headers=req.headers,
  1271. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1272. return self._opener.open(req, timeout=self._socket_timeout)
  1273. def print_debug_header(self):
  1274. if not self.params.get('verbose'):
  1275. return
  1276. if type('') is not compat_str:
  1277. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1278. self.report_warning(
  1279. 'Your Python is broken! Update to a newer and supported version')
  1280. stdout_encoding = getattr(
  1281. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1282. encoding_str = (
  1283. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1284. locale.getpreferredencoding(),
  1285. sys.getfilesystemencoding(),
  1286. stdout_encoding,
  1287. self.get_encoding()))
  1288. write_string(encoding_str, encoding=None)
  1289. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1290. try:
  1291. sp = subprocess.Popen(
  1292. ['git', 'rev-parse', '--short', 'HEAD'],
  1293. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1294. cwd=os.path.dirname(os.path.abspath(__file__)))
  1295. out, err = sp.communicate()
  1296. out = out.decode().strip()
  1297. if re.match('[0-9a-f]+', out):
  1298. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1299. except:
  1300. try:
  1301. sys.exc_clear()
  1302. except:
  1303. pass
  1304. self._write_string('[debug] Python version %s - %s\n' % (
  1305. platform.python_version(), platform_name()))
  1306. exe_versions = FFmpegPostProcessor.get_versions()
  1307. exe_versions['rtmpdump'] = rtmpdump_version()
  1308. exe_str = ', '.join(
  1309. '%s %s' % (exe, v)
  1310. for exe, v in sorted(exe_versions.items())
  1311. if v
  1312. )
  1313. if not exe_str:
  1314. exe_str = 'none'
  1315. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1316. proxy_map = {}
  1317. for handler in self._opener.handlers:
  1318. if hasattr(handler, 'proxies'):
  1319. proxy_map.update(handler.proxies)
  1320. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1321. def _setup_opener(self):
  1322. timeout_val = self.params.get('socket_timeout')
  1323. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1324. opts_cookiefile = self.params.get('cookiefile')
  1325. opts_proxy = self.params.get('proxy')
  1326. if opts_cookiefile is None:
  1327. self.cookiejar = compat_cookiejar.CookieJar()
  1328. else:
  1329. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1330. opts_cookiefile)
  1331. if os.access(opts_cookiefile, os.R_OK):
  1332. self.cookiejar.load()
  1333. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1334. self.cookiejar)
  1335. if opts_proxy is not None:
  1336. if opts_proxy == '':
  1337. proxies = {}
  1338. else:
  1339. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1340. else:
  1341. proxies = compat_urllib_request.getproxies()
  1342. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1343. if 'http' in proxies and 'https' not in proxies:
  1344. proxies['https'] = proxies['http']
  1345. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1346. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1347. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1348. ydlh = YoutubeDLHandler(self.params, 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