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.

1448 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. def make_result(embedded_info):
  562. new_result = ie_result.copy()
  563. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  564. 'entries', 'ie_key', 'duration',
  565. 'subtitles', 'annotations', 'format',
  566. 'thumbnail', 'thumbnails'):
  567. if f in new_result:
  568. del new_result[f]
  569. if f in embedded_info:
  570. new_result[f] = embedded_info[f]
  571. return new_result
  572. new_result = make_result(info)
  573. assert new_result.get('_type') != 'url_transparent'
  574. if new_result.get('_type') == 'compat_list':
  575. new_result['entries'] = [
  576. make_result(e) for e in new_result['entries']]
  577. return self.process_ie_result(
  578. new_result, download=download, extra_info=extra_info)
  579. elif result_type == 'playlist' or result_type == 'multi_video':
  580. # We process each entry in the playlist
  581. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  582. self.to_screen('[download] Downloading playlist: %s' % playlist)
  583. playlist_results = []
  584. playliststart = self.params.get('playliststart', 1) - 1
  585. playlistend = self.params.get('playlistend', None)
  586. # For backwards compatibility, interpret -1 as whole list
  587. if playlistend == -1:
  588. playlistend = None
  589. ie_entries = ie_result['entries']
  590. if isinstance(ie_entries, list):
  591. n_all_entries = len(ie_entries)
  592. entries = ie_entries[playliststart:playlistend]
  593. n_entries = len(entries)
  594. self.to_screen(
  595. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  596. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  597. elif isinstance(ie_entries, PagedList):
  598. entries = ie_entries.getslice(
  599. playliststart, playlistend)
  600. n_entries = len(entries)
  601. self.to_screen(
  602. "[%s] playlist %s: Downloading %d videos" %
  603. (ie_result['extractor'], playlist, n_entries))
  604. else: # iterable
  605. entries = list(itertools.islice(
  606. ie_entries, playliststart, playlistend))
  607. n_entries = len(entries)
  608. self.to_screen(
  609. "[%s] playlist %s: Downloading %d videos" %
  610. (ie_result['extractor'], playlist, n_entries))
  611. for i, entry in enumerate(entries, 1):
  612. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  613. extra = {
  614. 'n_entries': n_entries,
  615. 'playlist': playlist,
  616. 'playlist_id': ie_result.get('id'),
  617. 'playlist_title': ie_result.get('title'),
  618. 'playlist_index': i + playliststart,
  619. 'extractor': ie_result['extractor'],
  620. 'webpage_url': ie_result['webpage_url'],
  621. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  622. 'extractor_key': ie_result['extractor_key'],
  623. }
  624. reason = self._match_entry(entry)
  625. if reason is not None:
  626. self.to_screen('[download] ' + reason)
  627. continue
  628. entry_result = self.process_ie_result(entry,
  629. download=download,
  630. extra_info=extra)
  631. playlist_results.append(entry_result)
  632. ie_result['entries'] = playlist_results
  633. return ie_result
  634. elif result_type == 'compat_list':
  635. self.report_warning(
  636. 'Extractor %s returned a compat_list result. '
  637. 'It needs to be updated.' % ie_result.get('extractor'))
  638. def _fixup(r):
  639. self.add_extra_info(
  640. r,
  641. {
  642. 'extractor': ie_result['extractor'],
  643. 'webpage_url': ie_result['webpage_url'],
  644. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  645. 'extractor_key': ie_result['extractor_key'],
  646. }
  647. )
  648. return r
  649. ie_result['entries'] = [
  650. self.process_ie_result(_fixup(r), download, extra_info)
  651. for r in ie_result['entries']
  652. ]
  653. return ie_result
  654. else:
  655. raise Exception('Invalid result type: %s' % result_type)
  656. def select_format(self, format_spec, available_formats):
  657. if format_spec == 'best' or format_spec is None:
  658. return available_formats[-1]
  659. elif format_spec == 'worst':
  660. return available_formats[0]
  661. elif format_spec == 'bestaudio':
  662. audio_formats = [
  663. f for f in available_formats
  664. if f.get('vcodec') == 'none']
  665. if audio_formats:
  666. return audio_formats[-1]
  667. elif format_spec == 'worstaudio':
  668. audio_formats = [
  669. f for f in available_formats
  670. if f.get('vcodec') == 'none']
  671. if audio_formats:
  672. return audio_formats[0]
  673. elif format_spec == 'bestvideo':
  674. video_formats = [
  675. f for f in available_formats
  676. if f.get('acodec') == 'none']
  677. if video_formats:
  678. return video_formats[-1]
  679. elif format_spec == 'worstvideo':
  680. video_formats = [
  681. f for f in available_formats
  682. if f.get('acodec') == 'none']
  683. if video_formats:
  684. return video_formats[0]
  685. else:
  686. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a']
  687. if format_spec in extensions:
  688. filter_f = lambda f: f['ext'] == format_spec
  689. else:
  690. filter_f = lambda f: f['format_id'] == format_spec
  691. matches = list(filter(filter_f, available_formats))
  692. if matches:
  693. return matches[-1]
  694. return None
  695. def process_video_result(self, info_dict, download=True):
  696. assert info_dict.get('_type', 'video') == 'video'
  697. if 'id' not in info_dict:
  698. raise ExtractorError('Missing "id" field in extractor result')
  699. if 'title' not in info_dict:
  700. raise ExtractorError('Missing "title" field in extractor result')
  701. if 'playlist' not in info_dict:
  702. # It isn't part of a playlist
  703. info_dict['playlist'] = None
  704. info_dict['playlist_index'] = None
  705. thumbnails = info_dict.get('thumbnails')
  706. if thumbnails:
  707. thumbnails.sort(key=lambda t: (
  708. t.get('width'), t.get('height'), t.get('url')))
  709. for t in thumbnails:
  710. if 'width' in t and 'height' in t:
  711. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  712. if thumbnails and 'thumbnail' not in info_dict:
  713. info_dict['thumbnail'] = thumbnails[-1]['url']
  714. if 'display_id' not in info_dict and 'id' in info_dict:
  715. info_dict['display_id'] = info_dict['id']
  716. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  717. # Working around negative timestamps in Windows
  718. # (see http://bugs.python.org/issue1646728)
  719. if info_dict['timestamp'] < 0 and os.name == 'nt':
  720. info_dict['timestamp'] = 0
  721. upload_date = datetime.datetime.utcfromtimestamp(
  722. info_dict['timestamp'])
  723. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  724. # This extractors handle format selection themselves
  725. if info_dict['extractor'] in ['Youku']:
  726. if download:
  727. self.process_info(info_dict)
  728. return info_dict
  729. # We now pick which formats have to be downloaded
  730. if info_dict.get('formats') is None:
  731. # There's only one format available
  732. formats = [info_dict]
  733. else:
  734. formats = info_dict['formats']
  735. if not formats:
  736. raise ExtractorError('No video formats found!')
  737. # We check that all the formats have the format and format_id fields
  738. for i, format in enumerate(formats):
  739. if 'url' not in format:
  740. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  741. if format.get('format_id') is None:
  742. format['format_id'] = compat_str(i)
  743. if format.get('format') is None:
  744. format['format'] = '{id} - {res}{note}'.format(
  745. id=format['format_id'],
  746. res=self.format_resolution(format),
  747. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  748. )
  749. # Automatically determine file extension if missing
  750. if 'ext' not in format:
  751. format['ext'] = determine_ext(format['url']).lower()
  752. format_limit = self.params.get('format_limit', None)
  753. if format_limit:
  754. formats = list(takewhile_inclusive(
  755. lambda f: f['format_id'] != format_limit, formats
  756. ))
  757. # TODO Central sorting goes here
  758. if formats[0] is not info_dict:
  759. # only set the 'formats' fields if the original info_dict list them
  760. # otherwise we end up with a circular reference, the first (and unique)
  761. # element in the 'formats' field in info_dict is info_dict itself,
  762. # wich can't be exported to json
  763. info_dict['formats'] = formats
  764. if self.params.get('listformats', None):
  765. self.list_formats(info_dict)
  766. return
  767. req_format = self.params.get('format')
  768. if req_format is None:
  769. req_format = 'best'
  770. formats_to_download = []
  771. # The -1 is for supporting YoutubeIE
  772. if req_format in ('-1', 'all'):
  773. formats_to_download = formats
  774. else:
  775. for rfstr in req_format.split(','):
  776. # We can accept formats requested in the format: 34/5/best, we pick
  777. # the first that is available, starting from left
  778. req_formats = rfstr.split('/')
  779. for rf in req_formats:
  780. if re.match(r'.+?\+.+?', rf) is not None:
  781. # Two formats have been requested like '137+139'
  782. format_1, format_2 = rf.split('+')
  783. formats_info = (self.select_format(format_1, formats),
  784. self.select_format(format_2, formats))
  785. if all(formats_info):
  786. # The first format must contain the video and the
  787. # second the audio
  788. if formats_info[0].get('vcodec') == 'none':
  789. self.report_error('The first format must '
  790. 'contain the video, try using '
  791. '"-f %s+%s"' % (format_2, format_1))
  792. return
  793. selected_format = {
  794. 'requested_formats': formats_info,
  795. 'format': rf,
  796. 'ext': formats_info[0]['ext'],
  797. }
  798. else:
  799. selected_format = None
  800. else:
  801. selected_format = self.select_format(rf, formats)
  802. if selected_format is not None:
  803. formats_to_download.append(selected_format)
  804. break
  805. if not formats_to_download:
  806. raise ExtractorError('requested format not available',
  807. expected=True)
  808. if download:
  809. if len(formats_to_download) > 1:
  810. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  811. for format in formats_to_download:
  812. new_info = dict(info_dict)
  813. new_info.update(format)
  814. self.process_info(new_info)
  815. # We update the info dict with the best quality format (backwards compatibility)
  816. info_dict.update(formats_to_download[-1])
  817. return info_dict
  818. def process_info(self, info_dict):
  819. """Process a single resolved IE result."""
  820. assert info_dict.get('_type', 'video') == 'video'
  821. max_downloads = self.params.get('max_downloads')
  822. if max_downloads is not None:
  823. if self._num_downloads >= int(max_downloads):
  824. raise MaxDownloadsReached()
  825. info_dict['fulltitle'] = info_dict['title']
  826. if len(info_dict['title']) > 200:
  827. info_dict['title'] = info_dict['title'][:197] + '...'
  828. # Keep for backwards compatibility
  829. info_dict['stitle'] = info_dict['title']
  830. if 'format' not in info_dict:
  831. info_dict['format'] = info_dict['ext']
  832. reason = self._match_entry(info_dict)
  833. if reason is not None:
  834. self.to_screen('[download] ' + reason)
  835. return
  836. self._num_downloads += 1
  837. filename = self.prepare_filename(info_dict)
  838. # Forced printings
  839. if self.params.get('forcetitle', False):
  840. self.to_stdout(info_dict['fulltitle'])
  841. if self.params.get('forceid', False):
  842. self.to_stdout(info_dict['id'])
  843. if self.params.get('forceurl', False):
  844. if info_dict.get('requested_formats') is not None:
  845. for f in info_dict['requested_formats']:
  846. self.to_stdout(f['url'] + f.get('play_path', ''))
  847. else:
  848. # For RTMP URLs, also include the playpath
  849. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  850. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  851. self.to_stdout(info_dict['thumbnail'])
  852. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  853. self.to_stdout(info_dict['description'])
  854. if self.params.get('forcefilename', False) and filename is not None:
  855. self.to_stdout(filename)
  856. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  857. self.to_stdout(formatSeconds(info_dict['duration']))
  858. if self.params.get('forceformat', False):
  859. self.to_stdout(info_dict['format'])
  860. if self.params.get('forcejson', False):
  861. info_dict['_filename'] = filename
  862. self.to_stdout(json.dumps(info_dict))
  863. if self.params.get('dump_single_json', False):
  864. info_dict['_filename'] = filename
  865. # Do nothing else if in simulate mode
  866. if self.params.get('simulate', False):
  867. return
  868. if filename is None:
  869. return
  870. try:
  871. dn = os.path.dirname(encodeFilename(filename))
  872. if dn and not os.path.exists(dn):
  873. os.makedirs(dn)
  874. except (OSError, IOError) as err:
  875. self.report_error('unable to create directory ' + compat_str(err))
  876. return
  877. if self.params.get('writedescription', False):
  878. descfn = filename + '.description'
  879. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  880. self.to_screen('[info] Video description is already present')
  881. else:
  882. try:
  883. self.to_screen('[info] Writing video description to: ' + descfn)
  884. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  885. descfile.write(info_dict['description'])
  886. except (KeyError, TypeError):
  887. self.report_warning('There\'s no description to write.')
  888. except (OSError, IOError):
  889. self.report_error('Cannot write description file ' + descfn)
  890. return
  891. if self.params.get('writeannotations', False):
  892. annofn = filename + '.annotations.xml'
  893. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  894. self.to_screen('[info] Video annotations are already present')
  895. else:
  896. try:
  897. self.to_screen('[info] Writing video annotations to: ' + annofn)
  898. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  899. annofile.write(info_dict['annotations'])
  900. except (KeyError, TypeError):
  901. self.report_warning('There are no annotations to write.')
  902. except (OSError, IOError):
  903. self.report_error('Cannot write annotations file: ' + annofn)
  904. return
  905. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  906. self.params.get('writeautomaticsub')])
  907. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  908. # subtitles download errors are already managed as troubles in relevant IE
  909. # that way it will silently go on when used with unsupporting IE
  910. subtitles = info_dict['subtitles']
  911. sub_format = self.params.get('subtitlesformat', 'srt')
  912. for sub_lang in subtitles.keys():
  913. sub = subtitles[sub_lang]
  914. if sub is None:
  915. continue
  916. try:
  917. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  918. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  919. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  920. else:
  921. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  922. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  923. subfile.write(sub)
  924. except (OSError, IOError):
  925. self.report_error('Cannot write subtitles file ' + sub_filename)
  926. return
  927. if self.params.get('writeinfojson', False):
  928. infofn = os.path.splitext(filename)[0] + '.info.json'
  929. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  930. self.to_screen('[info] Video description metadata is already present')
  931. else:
  932. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  933. try:
  934. write_json_file(info_dict, infofn)
  935. except (OSError, IOError):
  936. self.report_error('Cannot write metadata to JSON file ' + infofn)
  937. return
  938. if self.params.get('writethumbnail', False):
  939. if info_dict.get('thumbnail') is not None:
  940. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  941. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  942. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  943. self.to_screen('[%s] %s: Thumbnail is already present' %
  944. (info_dict['extractor'], info_dict['id']))
  945. else:
  946. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  947. (info_dict['extractor'], info_dict['id']))
  948. try:
  949. uf = self.urlopen(info_dict['thumbnail'])
  950. with open(thumb_filename, 'wb') as thumbf:
  951. shutil.copyfileobj(uf, thumbf)
  952. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  953. (info_dict['extractor'], info_dict['id'], thumb_filename))
  954. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  955. self.report_warning('Unable to download thumbnail "%s": %s' %
  956. (info_dict['thumbnail'], compat_str(err)))
  957. if not self.params.get('skip_download', False):
  958. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  959. success = True
  960. else:
  961. try:
  962. def dl(name, info):
  963. fd = get_suitable_downloader(info)(self, self.params)
  964. for ph in self._progress_hooks:
  965. fd.add_progress_hook(ph)
  966. if self.params.get('verbose'):
  967. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  968. return fd.download(name, info)
  969. if info_dict.get('requested_formats') is not None:
  970. downloaded = []
  971. success = True
  972. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  973. if not merger._executable:
  974. postprocessors = []
  975. self.report_warning('You have requested multiple '
  976. 'formats but ffmpeg or avconv are not installed.'
  977. ' The formats won\'t be merged')
  978. else:
  979. postprocessors = [merger]
  980. for f in info_dict['requested_formats']:
  981. new_info = dict(info_dict)
  982. new_info.update(f)
  983. fname = self.prepare_filename(new_info)
  984. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  985. downloaded.append(fname)
  986. partial_success = dl(fname, new_info)
  987. success = success and partial_success
  988. info_dict['__postprocessors'] = postprocessors
  989. info_dict['__files_to_merge'] = downloaded
  990. else:
  991. # Just a single file
  992. success = dl(filename, info_dict)
  993. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  994. self.report_error('unable to download video data: %s' % str(err))
  995. return
  996. except (OSError, IOError) as err:
  997. raise UnavailableVideoError(err)
  998. except (ContentTooShortError, ) as err:
  999. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1000. return
  1001. if success:
  1002. try:
  1003. self.post_process(filename, info_dict)
  1004. except (PostProcessingError) as err:
  1005. self.report_error('postprocessing: %s' % str(err))
  1006. return
  1007. self.record_download_archive(info_dict)
  1008. def download(self, url_list):
  1009. """Download a given list of URLs."""
  1010. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1011. if (len(url_list) > 1 and
  1012. '%' not in outtmpl
  1013. and self.params.get('max_downloads') != 1):
  1014. raise SameFileError(outtmpl)
  1015. for url in url_list:
  1016. try:
  1017. # It also downloads the videos
  1018. res = self.extract_info(url)
  1019. except UnavailableVideoError:
  1020. self.report_error('unable to download video')
  1021. except MaxDownloadsReached:
  1022. self.to_screen('[info] Maximum number of downloaded files reached.')
  1023. raise
  1024. else:
  1025. if self.params.get('dump_single_json', False):
  1026. self.to_stdout(json.dumps(res))
  1027. return self._download_retcode
  1028. def download_with_info_file(self, info_filename):
  1029. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1030. info = json.load(f)
  1031. try:
  1032. self.process_ie_result(info, download=True)
  1033. except DownloadError:
  1034. webpage_url = info.get('webpage_url')
  1035. if webpage_url is not None:
  1036. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1037. return self.download([webpage_url])
  1038. else:
  1039. raise
  1040. return self._download_retcode
  1041. def post_process(self, filename, ie_info):
  1042. """Run all the postprocessors on the given file."""
  1043. info = dict(ie_info)
  1044. info['filepath'] = filename
  1045. keep_video = None
  1046. pps_chain = []
  1047. if ie_info.get('__postprocessors') is not None:
  1048. pps_chain.extend(ie_info['__postprocessors'])
  1049. pps_chain.extend(self._pps)
  1050. for pp in pps_chain:
  1051. try:
  1052. keep_video_wish, new_info = pp.run(info)
  1053. if keep_video_wish is not None:
  1054. if keep_video_wish:
  1055. keep_video = keep_video_wish
  1056. elif keep_video is None:
  1057. # No clear decision yet, let IE decide
  1058. keep_video = keep_video_wish
  1059. except PostProcessingError as e:
  1060. self.report_error(e.msg)
  1061. if keep_video is False and not self.params.get('keepvideo', False):
  1062. try:
  1063. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  1064. os.remove(encodeFilename(filename))
  1065. except (IOError, OSError):
  1066. self.report_warning('Unable to remove downloaded video file')
  1067. def _make_archive_id(self, info_dict):
  1068. # Future-proof against any change in case
  1069. # and backwards compatibility with prior versions
  1070. extractor = info_dict.get('extractor_key')
  1071. if extractor is None:
  1072. if 'id' in info_dict:
  1073. extractor = info_dict.get('ie_key') # key in a playlist
  1074. if extractor is None:
  1075. return None # Incomplete video information
  1076. return extractor.lower() + ' ' + info_dict['id']
  1077. def in_download_archive(self, info_dict):
  1078. fn = self.params.get('download_archive')
  1079. if fn is None:
  1080. return False
  1081. vid_id = self._make_archive_id(info_dict)
  1082. if vid_id is None:
  1083. return False # Incomplete video information
  1084. try:
  1085. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1086. for line in archive_file:
  1087. if line.strip() == vid_id:
  1088. return True
  1089. except IOError as ioe:
  1090. if ioe.errno != errno.ENOENT:
  1091. raise
  1092. return False
  1093. def record_download_archive(self, info_dict):
  1094. fn = self.params.get('download_archive')
  1095. if fn is None:
  1096. return
  1097. vid_id = self._make_archive_id(info_dict)
  1098. assert vid_id
  1099. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1100. archive_file.write(vid_id + '\n')
  1101. @staticmethod
  1102. def format_resolution(format, default='unknown'):
  1103. if format.get('vcodec') == 'none':
  1104. return 'audio only'
  1105. if format.get('resolution') is not None:
  1106. return format['resolution']
  1107. if format.get('height') is not None:
  1108. if format.get('width') is not None:
  1109. res = '%sx%s' % (format['width'], format['height'])
  1110. else:
  1111. res = '%sp' % format['height']
  1112. elif format.get('width') is not None:
  1113. res = '?x%d' % format['width']
  1114. else:
  1115. res = default
  1116. return res
  1117. def _format_note(self, fdict):
  1118. res = ''
  1119. if fdict.get('ext') in ['f4f', 'f4m']:
  1120. res += '(unsupported) '
  1121. if fdict.get('format_note') is not None:
  1122. res += fdict['format_note'] + ' '
  1123. if fdict.get('tbr') is not None:
  1124. res += '%4dk ' % fdict['tbr']
  1125. if fdict.get('container') is not None:
  1126. if res:
  1127. res += ', '
  1128. res += '%s container' % fdict['container']
  1129. if (fdict.get('vcodec') is not None and
  1130. fdict.get('vcodec') != 'none'):
  1131. if res:
  1132. res += ', '
  1133. res += fdict['vcodec']
  1134. if fdict.get('vbr') is not None:
  1135. res += '@'
  1136. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1137. res += 'video@'
  1138. if fdict.get('vbr') is not None:
  1139. res += '%4dk' % fdict['vbr']
  1140. if fdict.get('fps') is not None:
  1141. res += ', %sfps' % fdict['fps']
  1142. if fdict.get('acodec') is not None:
  1143. if res:
  1144. res += ', '
  1145. if fdict['acodec'] == 'none':
  1146. res += 'video only'
  1147. else:
  1148. res += '%-5s' % fdict['acodec']
  1149. elif fdict.get('abr') is not None:
  1150. if res:
  1151. res += ', '
  1152. res += 'audio'
  1153. if fdict.get('abr') is not None:
  1154. res += '@%3dk' % fdict['abr']
  1155. if fdict.get('asr') is not None:
  1156. res += ' (%5dHz)' % fdict['asr']
  1157. if fdict.get('filesize') is not None:
  1158. if res:
  1159. res += ', '
  1160. res += format_bytes(fdict['filesize'])
  1161. elif fdict.get('filesize_approx') is not None:
  1162. if res:
  1163. res += ', '
  1164. res += '~' + format_bytes(fdict['filesize_approx'])
  1165. return res
  1166. def list_formats(self, info_dict):
  1167. def line(format, idlen=20):
  1168. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1169. format['format_id'],
  1170. format['ext'],
  1171. self.format_resolution(format),
  1172. self._format_note(format),
  1173. ))
  1174. formats = info_dict.get('formats', [info_dict])
  1175. idlen = max(len('format code'),
  1176. max(len(f['format_id']) for f in formats))
  1177. formats_s = [line(f, idlen) for f in formats]
  1178. if len(formats) > 1:
  1179. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1180. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1181. header_line = line({
  1182. 'format_id': 'format code', 'ext': 'extension',
  1183. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1184. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1185. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1186. def urlopen(self, req):
  1187. """ Start an HTTP download """
  1188. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1189. # always respected by websites, some tend to give out URLs with non percent-encoded
  1190. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1191. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1192. # To work around aforementioned issue we will replace request's original URL with
  1193. # percent-encoded one
  1194. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1195. url = req if req_is_string else req.get_full_url()
  1196. url_escaped = escape_url(url)
  1197. # Substitute URL if any change after escaping
  1198. if url != url_escaped:
  1199. if req_is_string:
  1200. req = url_escaped
  1201. else:
  1202. req = compat_urllib_request.Request(
  1203. url_escaped, data=req.data, headers=req.headers,
  1204. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1205. return self._opener.open(req, timeout=self._socket_timeout)
  1206. def print_debug_header(self):
  1207. if not self.params.get('verbose'):
  1208. return
  1209. if type('') is not compat_str:
  1210. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1211. self.report_warning(
  1212. 'Your Python is broken! Update to a newer and supported version')
  1213. stdout_encoding = getattr(
  1214. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1215. encoding_str = (
  1216. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1217. locale.getpreferredencoding(),
  1218. sys.getfilesystemencoding(),
  1219. stdout_encoding,
  1220. self.get_encoding()))
  1221. write_string(encoding_str, encoding=None)
  1222. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1223. try:
  1224. sp = subprocess.Popen(
  1225. ['git', 'rev-parse', '--short', 'HEAD'],
  1226. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1227. cwd=os.path.dirname(os.path.abspath(__file__)))
  1228. out, err = sp.communicate()
  1229. out = out.decode().strip()
  1230. if re.match('[0-9a-f]+', out):
  1231. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1232. except:
  1233. try:
  1234. sys.exc_clear()
  1235. except:
  1236. pass
  1237. self._write_string('[debug] Python version %s - %s\n' % (
  1238. platform.python_version(), platform_name()))
  1239. exe_versions = FFmpegPostProcessor.get_versions()
  1240. exe_versions['rtmpdump'] = rtmpdump_version()
  1241. exe_str = ', '.join(
  1242. '%s %s' % (exe, v)
  1243. for exe, v in sorted(exe_versions.items())
  1244. if v
  1245. )
  1246. if not exe_str:
  1247. exe_str = 'none'
  1248. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1249. proxy_map = {}
  1250. for handler in self._opener.handlers:
  1251. if hasattr(handler, 'proxies'):
  1252. proxy_map.update(handler.proxies)
  1253. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1254. def _setup_opener(self):
  1255. timeout_val = self.params.get('socket_timeout')
  1256. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1257. opts_cookiefile = self.params.get('cookiefile')
  1258. opts_proxy = self.params.get('proxy')
  1259. if opts_cookiefile is None:
  1260. self.cookiejar = compat_cookiejar.CookieJar()
  1261. else:
  1262. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1263. opts_cookiefile)
  1264. if os.access(opts_cookiefile, os.R_OK):
  1265. self.cookiejar.load()
  1266. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1267. self.cookiejar)
  1268. if opts_proxy is not None:
  1269. if opts_proxy == '':
  1270. proxies = {}
  1271. else:
  1272. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1273. else:
  1274. proxies = compat_urllib_request.getproxies()
  1275. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1276. if 'http' in proxies and 'https' not in proxies:
  1277. proxies['https'] = proxies['http']
  1278. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1279. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1280. https_handler = make_HTTPS_handler(
  1281. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1282. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1283. opener = compat_urllib_request.build_opener(
  1284. https_handler, proxy_handler, cookie_processor, ydlh)
  1285. # Delete the default user-agent header, which would otherwise apply in
  1286. # cases where our custom HTTP handler doesn't come into play
  1287. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1288. opener.addheaders = []
  1289. self._opener = opener
  1290. def encode(self, s):
  1291. if isinstance(s, bytes):
  1292. return s # Already encoded
  1293. try:
  1294. return s.encode(self.get_encoding())
  1295. except UnicodeEncodeError as err:
  1296. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1297. raise
  1298. def get_encoding(self):
  1299. encoding = self.params.get('encoding')
  1300. if encoding is None:
  1301. encoding = preferredencoding()
  1302. return encoding