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.

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