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.

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