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