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.

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