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.

1444 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. # For RTMP URLs, also include the playpath
  845. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  846. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  847. self.to_stdout(info_dict['thumbnail'])
  848. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  849. self.to_stdout(info_dict['description'])
  850. if self.params.get('forcefilename', False) and filename is not None:
  851. self.to_stdout(filename)
  852. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  853. self.to_stdout(formatSeconds(info_dict['duration']))
  854. if self.params.get('forceformat', False):
  855. self.to_stdout(info_dict['format'])
  856. if self.params.get('forcejson', False):
  857. info_dict['_filename'] = filename
  858. self.to_stdout(json.dumps(info_dict))
  859. if self.params.get('dump_single_json', False):
  860. info_dict['_filename'] = filename
  861. # Do nothing else if in simulate mode
  862. if self.params.get('simulate', False):
  863. return
  864. if filename is None:
  865. return
  866. try:
  867. dn = os.path.dirname(encodeFilename(filename))
  868. if dn and not os.path.exists(dn):
  869. os.makedirs(dn)
  870. except (OSError, IOError) as err:
  871. self.report_error('unable to create directory ' + compat_str(err))
  872. return
  873. if self.params.get('writedescription', False):
  874. descfn = filename + '.description'
  875. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  876. self.to_screen('[info] Video description is already present')
  877. else:
  878. try:
  879. self.to_screen('[info] Writing video description to: ' + descfn)
  880. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  881. descfile.write(info_dict['description'])
  882. except (KeyError, TypeError):
  883. self.report_warning('There\'s no description to write.')
  884. except (OSError, IOError):
  885. self.report_error('Cannot write description file ' + descfn)
  886. return
  887. if self.params.get('writeannotations', False):
  888. annofn = filename + '.annotations.xml'
  889. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  890. self.to_screen('[info] Video annotations are already present')
  891. else:
  892. try:
  893. self.to_screen('[info] Writing video annotations to: ' + annofn)
  894. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  895. annofile.write(info_dict['annotations'])
  896. except (KeyError, TypeError):
  897. self.report_warning('There are no annotations to write.')
  898. except (OSError, IOError):
  899. self.report_error('Cannot write annotations file: ' + annofn)
  900. return
  901. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  902. self.params.get('writeautomaticsub')])
  903. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  904. # subtitles download errors are already managed as troubles in relevant IE
  905. # that way it will silently go on when used with unsupporting IE
  906. subtitles = info_dict['subtitles']
  907. sub_format = self.params.get('subtitlesformat', 'srt')
  908. for sub_lang in subtitles.keys():
  909. sub = subtitles[sub_lang]
  910. if sub is None:
  911. continue
  912. try:
  913. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  914. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  915. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  916. else:
  917. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  918. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  919. subfile.write(sub)
  920. except (OSError, IOError):
  921. self.report_error('Cannot write subtitles file ' + sub_filename)
  922. return
  923. if self.params.get('writeinfojson', False):
  924. infofn = os.path.splitext(filename)[0] + '.info.json'
  925. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  926. self.to_screen('[info] Video description metadata is already present')
  927. else:
  928. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  929. try:
  930. write_json_file(info_dict, infofn)
  931. except (OSError, IOError):
  932. self.report_error('Cannot write metadata to JSON file ' + infofn)
  933. return
  934. if self.params.get('writethumbnail', False):
  935. if info_dict.get('thumbnail') is not None:
  936. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  937. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  938. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  939. self.to_screen('[%s] %s: Thumbnail is already present' %
  940. (info_dict['extractor'], info_dict['id']))
  941. else:
  942. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  943. (info_dict['extractor'], info_dict['id']))
  944. try:
  945. uf = self.urlopen(info_dict['thumbnail'])
  946. with open(thumb_filename, 'wb') as thumbf:
  947. shutil.copyfileobj(uf, thumbf)
  948. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  949. (info_dict['extractor'], info_dict['id'], thumb_filename))
  950. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  951. self.report_warning('Unable to download thumbnail "%s": %s' %
  952. (info_dict['thumbnail'], compat_str(err)))
  953. if not self.params.get('skip_download', False):
  954. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  955. success = True
  956. else:
  957. try:
  958. def dl(name, info):
  959. fd = get_suitable_downloader(info)(self, self.params)
  960. for ph in self._progress_hooks:
  961. fd.add_progress_hook(ph)
  962. if self.params.get('verbose'):
  963. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  964. return fd.download(name, info)
  965. if info_dict.get('requested_formats') is not None:
  966. downloaded = []
  967. success = True
  968. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  969. if not merger._executable:
  970. postprocessors = []
  971. self.report_warning('You have requested multiple '
  972. 'formats but ffmpeg or avconv are not installed.'
  973. ' The formats won\'t be merged')
  974. else:
  975. postprocessors = [merger]
  976. for f in info_dict['requested_formats']:
  977. new_info = dict(info_dict)
  978. new_info.update(f)
  979. fname = self.prepare_filename(new_info)
  980. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  981. downloaded.append(fname)
  982. partial_success = dl(fname, new_info)
  983. success = success and partial_success
  984. info_dict['__postprocessors'] = postprocessors
  985. info_dict['__files_to_merge'] = downloaded
  986. else:
  987. # Just a single file
  988. success = dl(filename, info_dict)
  989. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  990. self.report_error('unable to download video data: %s' % str(err))
  991. return
  992. except (OSError, IOError) as err:
  993. raise UnavailableVideoError(err)
  994. except (ContentTooShortError, ) as err:
  995. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  996. return
  997. if success:
  998. try:
  999. self.post_process(filename, info_dict)
  1000. except (PostProcessingError) as err:
  1001. self.report_error('postprocessing: %s' % str(err))
  1002. return
  1003. self.record_download_archive(info_dict)
  1004. def download(self, url_list):
  1005. """Download a given list of URLs."""
  1006. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1007. if (len(url_list) > 1 and
  1008. '%' not in outtmpl
  1009. and self.params.get('max_downloads') != 1):
  1010. raise SameFileError(outtmpl)
  1011. for url in url_list:
  1012. try:
  1013. # It also downloads the videos
  1014. res = self.extract_info(url)
  1015. except UnavailableVideoError:
  1016. self.report_error('unable to download video')
  1017. except MaxDownloadsReached:
  1018. self.to_screen('[info] Maximum number of downloaded files reached.')
  1019. raise
  1020. else:
  1021. if self.params.get('dump_single_json', False):
  1022. self.to_stdout(json.dumps(res))
  1023. return self._download_retcode
  1024. def download_with_info_file(self, info_filename):
  1025. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1026. info = json.load(f)
  1027. try:
  1028. self.process_ie_result(info, download=True)
  1029. except DownloadError:
  1030. webpage_url = info.get('webpage_url')
  1031. if webpage_url is not None:
  1032. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1033. return self.download([webpage_url])
  1034. else:
  1035. raise
  1036. return self._download_retcode
  1037. def post_process(self, filename, ie_info):
  1038. """Run all the postprocessors on the given file."""
  1039. info = dict(ie_info)
  1040. info['filepath'] = filename
  1041. keep_video = None
  1042. pps_chain = []
  1043. if ie_info.get('__postprocessors') is not None:
  1044. pps_chain.extend(ie_info['__postprocessors'])
  1045. pps_chain.extend(self._pps)
  1046. for pp in pps_chain:
  1047. try:
  1048. keep_video_wish, new_info = pp.run(info)
  1049. if keep_video_wish is not None:
  1050. if keep_video_wish:
  1051. keep_video = keep_video_wish
  1052. elif keep_video is None:
  1053. # No clear decision yet, let IE decide
  1054. keep_video = keep_video_wish
  1055. except PostProcessingError as e:
  1056. self.report_error(e.msg)
  1057. if keep_video is False and not self.params.get('keepvideo', False):
  1058. try:
  1059. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  1060. os.remove(encodeFilename(filename))
  1061. except (IOError, OSError):
  1062. self.report_warning('Unable to remove downloaded video file')
  1063. def _make_archive_id(self, info_dict):
  1064. # Future-proof against any change in case
  1065. # and backwards compatibility with prior versions
  1066. extractor = info_dict.get('extractor_key')
  1067. if extractor is None:
  1068. if 'id' in info_dict:
  1069. extractor = info_dict.get('ie_key') # key in a playlist
  1070. if extractor is None:
  1071. return None # Incomplete video information
  1072. return extractor.lower() + ' ' + info_dict['id']
  1073. def in_download_archive(self, info_dict):
  1074. fn = self.params.get('download_archive')
  1075. if fn is None:
  1076. return False
  1077. vid_id = self._make_archive_id(info_dict)
  1078. if vid_id is None:
  1079. return False # Incomplete video information
  1080. try:
  1081. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1082. for line in archive_file:
  1083. if line.strip() == vid_id:
  1084. return True
  1085. except IOError as ioe:
  1086. if ioe.errno != errno.ENOENT:
  1087. raise
  1088. return False
  1089. def record_download_archive(self, info_dict):
  1090. fn = self.params.get('download_archive')
  1091. if fn is None:
  1092. return
  1093. vid_id = self._make_archive_id(info_dict)
  1094. assert vid_id
  1095. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1096. archive_file.write(vid_id + '\n')
  1097. @staticmethod
  1098. def format_resolution(format, default='unknown'):
  1099. if format.get('vcodec') == 'none':
  1100. return 'audio only'
  1101. if format.get('resolution') is not None:
  1102. return format['resolution']
  1103. if format.get('height') is not None:
  1104. if format.get('width') is not None:
  1105. res = '%sx%s' % (format['width'], format['height'])
  1106. else:
  1107. res = '%sp' % format['height']
  1108. elif format.get('width') is not None:
  1109. res = '?x%d' % format['width']
  1110. else:
  1111. res = default
  1112. return res
  1113. def _format_note(self, fdict):
  1114. res = ''
  1115. if fdict.get('ext') in ['f4f', 'f4m']:
  1116. res += '(unsupported) '
  1117. if fdict.get('format_note') is not None:
  1118. res += fdict['format_note'] + ' '
  1119. if fdict.get('tbr') is not None:
  1120. res += '%4dk ' % fdict['tbr']
  1121. if fdict.get('container') is not None:
  1122. if res:
  1123. res += ', '
  1124. res += '%s container' % fdict['container']
  1125. if (fdict.get('vcodec') is not None and
  1126. fdict.get('vcodec') != 'none'):
  1127. if res:
  1128. res += ', '
  1129. res += fdict['vcodec']
  1130. if fdict.get('vbr') is not None:
  1131. res += '@'
  1132. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1133. res += 'video@'
  1134. if fdict.get('vbr') is not None:
  1135. res += '%4dk' % fdict['vbr']
  1136. if fdict.get('fps') is not None:
  1137. res += ', %sfps' % fdict['fps']
  1138. if fdict.get('acodec') is not None:
  1139. if res:
  1140. res += ', '
  1141. if fdict['acodec'] == 'none':
  1142. res += 'video only'
  1143. else:
  1144. res += '%-5s' % fdict['acodec']
  1145. elif fdict.get('abr') is not None:
  1146. if res:
  1147. res += ', '
  1148. res += 'audio'
  1149. if fdict.get('abr') is not None:
  1150. res += '@%3dk' % fdict['abr']
  1151. if fdict.get('asr') is not None:
  1152. res += ' (%5dHz)' % fdict['asr']
  1153. if fdict.get('filesize') is not None:
  1154. if res:
  1155. res += ', '
  1156. res += format_bytes(fdict['filesize'])
  1157. elif fdict.get('filesize_approx') is not None:
  1158. if res:
  1159. res += ', '
  1160. res += '~' + format_bytes(fdict['filesize_approx'])
  1161. return res
  1162. def list_formats(self, info_dict):
  1163. def line(format, idlen=20):
  1164. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1165. format['format_id'],
  1166. format['ext'],
  1167. self.format_resolution(format),
  1168. self._format_note(format),
  1169. ))
  1170. formats = info_dict.get('formats', [info_dict])
  1171. idlen = max(len('format code'),
  1172. max(len(f['format_id']) for f in formats))
  1173. formats_s = [line(f, idlen) for f in formats]
  1174. if len(formats) > 1:
  1175. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1176. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1177. header_line = line({
  1178. 'format_id': 'format code', 'ext': 'extension',
  1179. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1180. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1181. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1182. def urlopen(self, req):
  1183. """ Start an HTTP download """
  1184. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1185. # always respected by websites, some tend to give out URLs with non percent-encoded
  1186. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1187. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1188. # To work around aforementioned issue we will replace request's original URL with
  1189. # percent-encoded one
  1190. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1191. url = req if req_is_string else req.get_full_url()
  1192. url_escaped = escape_url(url)
  1193. # Substitute URL if any change after escaping
  1194. if url != url_escaped:
  1195. if req_is_string:
  1196. req = url_escaped
  1197. else:
  1198. req = compat_urllib_request.Request(
  1199. url_escaped, data=req.data, headers=req.headers,
  1200. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1201. return self._opener.open(req, timeout=self._socket_timeout)
  1202. def print_debug_header(self):
  1203. if not self.params.get('verbose'):
  1204. return
  1205. if type('') is not compat_str:
  1206. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1207. self.report_warning(
  1208. 'Your Python is broken! Update to a newer and supported version')
  1209. stdout_encoding = getattr(
  1210. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1211. encoding_str = (
  1212. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1213. locale.getpreferredencoding(),
  1214. sys.getfilesystemencoding(),
  1215. stdout_encoding,
  1216. self.get_encoding()))
  1217. write_string(encoding_str, encoding=None)
  1218. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1219. try:
  1220. sp = subprocess.Popen(
  1221. ['git', 'rev-parse', '--short', 'HEAD'],
  1222. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1223. cwd=os.path.dirname(os.path.abspath(__file__)))
  1224. out, err = sp.communicate()
  1225. out = out.decode().strip()
  1226. if re.match('[0-9a-f]+', out):
  1227. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1228. except:
  1229. try:
  1230. sys.exc_clear()
  1231. except:
  1232. pass
  1233. self._write_string('[debug] Python version %s - %s\n' % (
  1234. platform.python_version(), platform_name()))
  1235. exe_versions = FFmpegPostProcessor.get_versions()
  1236. exe_versions['rtmpdump'] = rtmpdump_version()
  1237. exe_str = ', '.join(
  1238. '%s %s' % (exe, v)
  1239. for exe, v in sorted(exe_versions.items())
  1240. if v
  1241. )
  1242. if not exe_str:
  1243. exe_str = 'none'
  1244. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1245. proxy_map = {}
  1246. for handler in self._opener.handlers:
  1247. if hasattr(handler, 'proxies'):
  1248. proxy_map.update(handler.proxies)
  1249. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1250. def _setup_opener(self):
  1251. timeout_val = self.params.get('socket_timeout')
  1252. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1253. opts_cookiefile = self.params.get('cookiefile')
  1254. opts_proxy = self.params.get('proxy')
  1255. if opts_cookiefile is None:
  1256. self.cookiejar = compat_cookiejar.CookieJar()
  1257. else:
  1258. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1259. opts_cookiefile)
  1260. if os.access(opts_cookiefile, os.R_OK):
  1261. self.cookiejar.load()
  1262. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1263. self.cookiejar)
  1264. if opts_proxy is not None:
  1265. if opts_proxy == '':
  1266. proxies = {}
  1267. else:
  1268. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1269. else:
  1270. proxies = compat_urllib_request.getproxies()
  1271. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1272. if 'http' in proxies and 'https' not in proxies:
  1273. proxies['https'] = proxies['http']
  1274. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1275. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1276. https_handler = make_HTTPS_handler(
  1277. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1278. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1279. opener = compat_urllib_request.build_opener(
  1280. https_handler, proxy_handler, cookie_processor, ydlh)
  1281. # Delete the default user-agent header, which would otherwise apply in
  1282. # cases where our custom HTTP handler doesn't come into play
  1283. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1284. opener.addheaders = []
  1285. self._opener = opener
  1286. def encode(self, s):
  1287. if isinstance(s, bytes):
  1288. return s # Already encoded
  1289. try:
  1290. return s.encode(self.get_encoding())
  1291. except UnicodeEncodeError as err:
  1292. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1293. raise
  1294. def get_encoding(self):
  1295. encoding = self.params.get('encoding')
  1296. if encoding is None:
  1297. encoding = preferredencoding()
  1298. return encoding