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.

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