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.

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