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.

1139 lines
49 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
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import collections
  5. import errno
  6. import io
  7. import json
  8. import os
  9. import platform
  10. import re
  11. import shutil
  12. import subprocess
  13. import socket
  14. import sys
  15. import time
  16. import traceback
  17. if os.name == 'nt':
  18. import ctypes
  19. from .utils import (
  20. compat_cookiejar,
  21. compat_http_client,
  22. compat_str,
  23. compat_urllib_error,
  24. compat_urllib_request,
  25. ContentTooShortError,
  26. date_from_str,
  27. DateRange,
  28. determine_ext,
  29. DownloadError,
  30. encodeFilename,
  31. ExtractorError,
  32. format_bytes,
  33. formatSeconds,
  34. get_term_width,
  35. locked_file,
  36. make_HTTPS_handler,
  37. MaxDownloadsReached,
  38. PostProcessingError,
  39. platform_name,
  40. preferredencoding,
  41. SameFileError,
  42. sanitize_filename,
  43. subtitles_filename,
  44. takewhile_inclusive,
  45. UnavailableVideoError,
  46. url_basename,
  47. write_json_file,
  48. write_string,
  49. YoutubeDLHandler,
  50. )
  51. from .extractor import get_info_extractor, gen_extractors
  52. from .downloader import get_suitable_downloader
  53. from .version import __version__
  54. class YoutubeDL(object):
  55. """YoutubeDL class.
  56. YoutubeDL objects are the ones responsible of downloading the
  57. actual video file and writing it to disk if the user has requested
  58. it, among some other tasks. In most cases there should be one per
  59. program. As, given a video URL, the downloader doesn't know how to
  60. extract all the needed information, task that InfoExtractors do, it
  61. has to pass the URL to one of them.
  62. For this, YoutubeDL objects have a method that allows
  63. InfoExtractors to be registered in a given order. When it is passed
  64. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  65. finds that reports being able to handle it. The InfoExtractor extracts
  66. all the information about the video or videos the URL refers to, and
  67. YoutubeDL process the extracted information, possibly using a File
  68. Downloader to download the video.
  69. YoutubeDL objects accept a lot of parameters. In order not to saturate
  70. the object constructor with arguments, it receives a dictionary of
  71. options instead. These options are available through the params
  72. attribute for the InfoExtractors to use. The YoutubeDL also
  73. registers itself as the downloader in charge for the InfoExtractors
  74. that are added to it, so this is a "mutual registration".
  75. Available options:
  76. username: Username for authentication purposes.
  77. password: Password for authentication purposes.
  78. videopassword: Password for acces a video.
  79. usenetrc: Use netrc for authentication instead.
  80. verbose: Print additional info to stdout.
  81. quiet: Do not print messages to stdout.
  82. forceurl: Force printing final URL.
  83. forcetitle: Force printing title.
  84. forceid: Force printing ID.
  85. forcethumbnail: Force printing thumbnail URL.
  86. forcedescription: Force printing description.
  87. forcefilename: Force printing final filename.
  88. forceduration: Force printing duration.
  89. forcejson: Force printing info_dict as JSON.
  90. simulate: Do not download the video files.
  91. format: Video format code.
  92. format_limit: Highest quality format to try.
  93. outtmpl: Template for output names.
  94. restrictfilenames: Do not allow "&" and spaces in file names
  95. ignoreerrors: Do not stop on download errors.
  96. nooverwrites: Prevent overwriting files.
  97. playliststart: Playlist item to start at.
  98. playlistend: Playlist item to end at.
  99. matchtitle: Download only matching titles.
  100. rejecttitle: Reject downloads for matching titles.
  101. logger: Log messages to a logging.Logger instance.
  102. logtostderr: Log messages to stderr instead of stdout.
  103. writedescription: Write the video description to a .description file
  104. writeinfojson: Write the video description to a .info.json file
  105. writeannotations: Write the video annotations to a .annotations.xml file
  106. writethumbnail: Write the thumbnail image to a file
  107. writesubtitles: Write the video subtitles to a file
  108. writeautomaticsub: Write the automatic subtitles to a file
  109. allsubtitles: Downloads all the subtitles of the video
  110. (requires writesubtitles or writeautomaticsub)
  111. listsubtitles: Lists all available subtitles for the video
  112. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  113. subtitleslangs: List of languages of the subtitles to download
  114. keepvideo: Keep the video file after post-processing
  115. daterange: A DateRange object, download only if the upload_date is in the range.
  116. skip_download: Skip the actual download of the video file
  117. cachedir: Location of the cache files in the filesystem.
  118. None to disable filesystem cache.
  119. noplaylist: Download single video instead of a playlist if in doubt.
  120. age_limit: An integer representing the user's age in years.
  121. Unsuitable videos for the given age are skipped.
  122. min_views: An integer representing the minimum view count the video
  123. must have in order to not be skipped.
  124. Videos without view count information are always
  125. downloaded. None for no limit.
  126. max_views: An integer representing the maximum view count.
  127. Videos that are more popular than that are not
  128. downloaded.
  129. Videos without view count information are always
  130. downloaded. None for no limit.
  131. download_archive: File name of a file where all downloads are recorded.
  132. Videos already present in the file are not downloaded
  133. again.
  134. cookiefile: File name where cookies should be read from and dumped to.
  135. nocheckcertificate:Do not verify SSL certificates
  136. proxy: URL of the proxy server to use
  137. socket_timeout: Time to wait for unresponsive hosts, in seconds
  138. bidi_workaround: Work around buggy terminals without bidirectional text
  139. support, using fridibi
  140. The following parameters are not used by YoutubeDL itself, they are used by
  141. the FileDownloader:
  142. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  143. noresizebuffer, retries, continuedl, noprogress, consoletitle
  144. """
  145. params = None
  146. _ies = []
  147. _pps = []
  148. _download_retcode = None
  149. _num_downloads = None
  150. _screen_file = None
  151. def __init__(self, params=None):
  152. """Create a FileDownloader object with the given options."""
  153. self._ies = []
  154. self._ies_instances = {}
  155. self._pps = []
  156. self._progress_hooks = []
  157. self._download_retcode = 0
  158. self._num_downloads = 0
  159. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  160. self._err_file = sys.stderr
  161. self.params = {} if params is None else params
  162. if params.get('bidi_workaround', False):
  163. try:
  164. import pty
  165. master, slave = pty.openpty()
  166. width = get_term_width()
  167. if width is None:
  168. width_args = []
  169. else:
  170. width_args = ['-w', str(width)]
  171. sp_kwargs = dict(
  172. stdin=subprocess.PIPE,
  173. stdout=slave,
  174. stderr=self._err_file)
  175. try:
  176. self._output_process = subprocess.Popen(
  177. ['bidiv'] + width_args, **sp_kwargs
  178. )
  179. except OSError:
  180. self._output_process = subprocess.Popen(
  181. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  182. self._output_channel = os.fdopen(master, 'rb')
  183. except OSError as ose:
  184. if ose.errno == 2:
  185. self.report_warning(u'Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  186. else:
  187. raise
  188. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  189. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  190. and not params['restrictfilenames']):
  191. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  192. self.report_warning(
  193. u'Assuming --restrict-filenames since file system encoding '
  194. u'cannot encode all charactes. '
  195. u'Set the LC_ALL environment variable to fix this.')
  196. self.params['restrictfilenames'] = True
  197. if '%(stitle)s' in self.params.get('outtmpl', ''):
  198. self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  199. self._setup_opener()
  200. def add_info_extractor(self, ie):
  201. """Add an InfoExtractor object to the end of the list."""
  202. self._ies.append(ie)
  203. self._ies_instances[ie.ie_key()] = ie
  204. ie.set_downloader(self)
  205. def get_info_extractor(self, ie_key):
  206. """
  207. Get an instance of an IE with name ie_key, it will try to get one from
  208. the _ies list, if there's no instance it will create a new one and add
  209. it to the extractor list.
  210. """
  211. ie = self._ies_instances.get(ie_key)
  212. if ie is None:
  213. ie = get_info_extractor(ie_key)()
  214. self.add_info_extractor(ie)
  215. return ie
  216. def add_default_info_extractors(self):
  217. """
  218. Add the InfoExtractors returned by gen_extractors to the end of the list
  219. """
  220. for ie in gen_extractors():
  221. self.add_info_extractor(ie)
  222. def add_post_processor(self, pp):
  223. """Add a PostProcessor object to the end of the chain."""
  224. self._pps.append(pp)
  225. pp.set_downloader(self)
  226. def add_progress_hook(self, ph):
  227. """Add the progress hook (currently only for the file downloader)"""
  228. self._progress_hooks.append(ph)
  229. def _bidi_workaround(self, message):
  230. if not hasattr(self, '_output_channel'):
  231. return message
  232. assert hasattr(self, '_output_process')
  233. assert type(message) == type(u'')
  234. line_count = message.count(u'\n') + 1
  235. self._output_process.stdin.write((message + u'\n').encode('utf-8'))
  236. self._output_process.stdin.flush()
  237. res = u''.join(self._output_channel.readline().decode('utf-8')
  238. for _ in range(line_count))
  239. return res[:-len(u'\n')]
  240. def to_screen(self, message, skip_eol=False):
  241. """Print message to stdout if not in quiet mode."""
  242. return self.to_stdout(message, skip_eol, check_quiet=True)
  243. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  244. """Print message to stdout if not in quiet mode."""
  245. if self.params.get('logger'):
  246. self.params['logger'].debug(message)
  247. elif not check_quiet or not self.params.get('quiet', False):
  248. message = self._bidi_workaround(message)
  249. terminator = [u'\n', u''][skip_eol]
  250. output = message + terminator
  251. write_string(output, self._screen_file)
  252. def to_stderr(self, message):
  253. """Print message to stderr."""
  254. assert type(message) == type(u'')
  255. if self.params.get('logger'):
  256. self.params['logger'].error(message)
  257. else:
  258. message = self._bidi_workaround(message)
  259. output = message + u'\n'
  260. write_string(output, self._err_file)
  261. def to_console_title(self, message):
  262. if not self.params.get('consoletitle', False):
  263. return
  264. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  265. # c_wchar_p() might not be necessary if `message` is
  266. # already of type unicode()
  267. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  268. elif 'TERM' in os.environ:
  269. write_string(u'\033]0;%s\007' % message, self._screen_file)
  270. def save_console_title(self):
  271. if not self.params.get('consoletitle', False):
  272. return
  273. if 'TERM' in os.environ:
  274. # Save the title on stack
  275. write_string(u'\033[22;0t', self._screen_file)
  276. def restore_console_title(self):
  277. if not self.params.get('consoletitle', False):
  278. return
  279. if 'TERM' in os.environ:
  280. # Restore the title from stack
  281. write_string(u'\033[23;0t', self._screen_file)
  282. def __enter__(self):
  283. self.save_console_title()
  284. return self
  285. def __exit__(self, *args):
  286. self.restore_console_title()
  287. if self.params.get('cookiefile') is not None:
  288. self.cookiejar.save()
  289. def trouble(self, message=None, tb=None):
  290. """Determine action to take when a download problem appears.
  291. Depending on if the downloader has been configured to ignore
  292. download errors or not, this method may throw an exception or
  293. not when errors are found, after printing the message.
  294. tb, if given, is additional traceback information.
  295. """
  296. if message is not None:
  297. self.to_stderr(message)
  298. if self.params.get('verbose'):
  299. if tb is None:
  300. if sys.exc_info()[0]: # if .trouble has been called from an except block
  301. tb = u''
  302. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  303. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  304. tb += compat_str(traceback.format_exc())
  305. else:
  306. tb_data = traceback.format_list(traceback.extract_stack())
  307. tb = u''.join(tb_data)
  308. self.to_stderr(tb)
  309. if not self.params.get('ignoreerrors', False):
  310. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  311. exc_info = sys.exc_info()[1].exc_info
  312. else:
  313. exc_info = sys.exc_info()
  314. raise DownloadError(message, exc_info)
  315. self._download_retcode = 1
  316. def report_warning(self, message):
  317. '''
  318. Print the message to stderr, it will be prefixed with 'WARNING:'
  319. If stderr is a tty file the 'WARNING:' will be colored
  320. '''
  321. if self._err_file.isatty() and os.name != 'nt':
  322. _msg_header = u'\033[0;33mWARNING:\033[0m'
  323. else:
  324. _msg_header = u'WARNING:'
  325. warning_message = u'%s %s' % (_msg_header, message)
  326. self.to_stderr(warning_message)
  327. def report_error(self, message, tb=None):
  328. '''
  329. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  330. in red if stderr is a tty file.
  331. '''
  332. if self._err_file.isatty() and os.name != 'nt':
  333. _msg_header = u'\033[0;31mERROR:\033[0m'
  334. else:
  335. _msg_header = u'ERROR:'
  336. error_message = u'%s %s' % (_msg_header, message)
  337. self.trouble(error_message, tb)
  338. def report_file_already_downloaded(self, file_name):
  339. """Report file has already been fully downloaded."""
  340. try:
  341. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  342. except UnicodeEncodeError:
  343. self.to_screen(u'[download] The file has already been downloaded')
  344. def increment_downloads(self):
  345. """Increment the ordinal that assigns a number to each file."""
  346. self._num_downloads += 1
  347. def prepare_filename(self, info_dict):
  348. """Generate the output filename."""
  349. try:
  350. template_dict = dict(info_dict)
  351. template_dict['epoch'] = int(time.time())
  352. autonumber_size = self.params.get('autonumber_size')
  353. if autonumber_size is None:
  354. autonumber_size = 5
  355. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  356. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  357. if template_dict.get('playlist_index') is not None:
  358. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  359. sanitize = lambda k, v: sanitize_filename(
  360. compat_str(v),
  361. restricted=self.params.get('restrictfilenames'),
  362. is_id=(k == u'id'))
  363. template_dict = dict((k, sanitize(k, v))
  364. for k, v in template_dict.items()
  365. if v is not None)
  366. template_dict = collections.defaultdict(lambda: u'NA', template_dict)
  367. tmpl = os.path.expanduser(self.params['outtmpl'])
  368. filename = tmpl % template_dict
  369. return filename
  370. except ValueError as err:
  371. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  372. return None
  373. def _match_entry(self, info_dict):
  374. """ Returns None iff the file should be downloaded """
  375. video_title = info_dict.get('title', info_dict.get('id', u'video'))
  376. if 'title' in info_dict:
  377. # This can happen when we're just evaluating the playlist
  378. title = info_dict['title']
  379. matchtitle = self.params.get('matchtitle', False)
  380. if matchtitle:
  381. if not re.search(matchtitle, title, re.IGNORECASE):
  382. return u'"' + title + '" title did not match pattern "' + matchtitle + '"'
  383. rejecttitle = self.params.get('rejecttitle', False)
  384. if rejecttitle:
  385. if re.search(rejecttitle, title, re.IGNORECASE):
  386. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  387. date = info_dict.get('upload_date', None)
  388. if date is not None:
  389. dateRange = self.params.get('daterange', DateRange())
  390. if date not in dateRange:
  391. return u'%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  392. view_count = info_dict.get('view_count', None)
  393. if view_count is not None:
  394. min_views = self.params.get('min_views')
  395. if min_views is not None and view_count < min_views:
  396. return u'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  397. max_views = self.params.get('max_views')
  398. if max_views is not None and view_count > max_views:
  399. return u'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  400. age_limit = self.params.get('age_limit')
  401. if age_limit is not None:
  402. if age_limit < info_dict.get('age_limit', 0):
  403. return u'Skipping "' + title + '" because it is age restricted'
  404. if self.in_download_archive(info_dict):
  405. return u'%s has already been recorded in archive' % video_title
  406. return None
  407. @staticmethod
  408. def add_extra_info(info_dict, extra_info):
  409. '''Set the keys from extra_info in info dict if they are missing'''
  410. for key, value in extra_info.items():
  411. info_dict.setdefault(key, value)
  412. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  413. process=True):
  414. '''
  415. Returns a list with a dictionary for each video we find.
  416. If 'download', also downloads the videos.
  417. extra_info is a dict containing the extra values to add to each result
  418. '''
  419. if ie_key:
  420. ies = [self.get_info_extractor(ie_key)]
  421. else:
  422. ies = self._ies
  423. for ie in ies:
  424. if not ie.suitable(url):
  425. continue
  426. if not ie.working():
  427. self.report_warning(u'The program functionality for this site has been marked as broken, '
  428. u'and will probably not work.')
  429. try:
  430. ie_result = ie.extract(url)
  431. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  432. break
  433. if isinstance(ie_result, list):
  434. # Backwards compatibility: old IE result format
  435. ie_result = {
  436. '_type': 'compat_list',
  437. 'entries': ie_result,
  438. }
  439. self.add_extra_info(ie_result,
  440. {
  441. 'extractor': ie.IE_NAME,
  442. 'webpage_url': url,
  443. 'webpage_url_basename': url_basename(url),
  444. 'extractor_key': ie.ie_key(),
  445. })
  446. if process:
  447. return self.process_ie_result(ie_result, download, extra_info)
  448. else:
  449. return ie_result
  450. except ExtractorError as de: # An error we somewhat expected
  451. self.report_error(compat_str(de), de.format_traceback())
  452. break
  453. except Exception as e:
  454. if self.params.get('ignoreerrors', False):
  455. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  456. break
  457. else:
  458. raise
  459. else:
  460. self.report_error(u'no suitable InfoExtractor: %s' % url)
  461. def process_ie_result(self, ie_result, download=True, extra_info={}):
  462. """
  463. Take the result of the ie(may be modified) and resolve all unresolved
  464. references (URLs, playlist items).
  465. It will also download the videos if 'download'.
  466. Returns the resolved ie_result.
  467. """
  468. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  469. if result_type == 'video':
  470. self.add_extra_info(ie_result, extra_info)
  471. return self.process_video_result(ie_result, download=download)
  472. elif result_type == 'url':
  473. # We have to add extra_info to the results because it may be
  474. # contained in a playlist
  475. return self.extract_info(ie_result['url'],
  476. download,
  477. ie_key=ie_result.get('ie_key'),
  478. extra_info=extra_info)
  479. elif result_type == 'url_transparent':
  480. # Use the information from the embedding page
  481. info = self.extract_info(
  482. ie_result['url'], ie_key=ie_result.get('ie_key'),
  483. extra_info=extra_info, download=False, process=False)
  484. def make_result(embedded_info):
  485. new_result = ie_result.copy()
  486. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  487. 'entries', 'ie_key', 'duration',
  488. 'subtitles', 'annotations', 'format',
  489. 'thumbnail', 'thumbnails'):
  490. if f in new_result:
  491. del new_result[f]
  492. if f in embedded_info:
  493. new_result[f] = embedded_info[f]
  494. return new_result
  495. new_result = make_result(info)
  496. assert new_result.get('_type') != 'url_transparent'
  497. if new_result.get('_type') == 'compat_list':
  498. new_result['entries'] = [
  499. make_result(e) for e in new_result['entries']]
  500. return self.process_ie_result(
  501. new_result, download=download, extra_info=extra_info)
  502. elif result_type == 'playlist':
  503. # We process each entry in the playlist
  504. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  505. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  506. playlist_results = []
  507. n_all_entries = len(ie_result['entries'])
  508. playliststart = self.params.get('playliststart', 1) - 1
  509. playlistend = self.params.get('playlistend', None)
  510. # For backwards compatibility, interpret -1 as whole list
  511. if playlistend == -1:
  512. playlistend = None
  513. entries = ie_result['entries'][playliststart:playlistend]
  514. n_entries = len(entries)
  515. self.to_screen(
  516. u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  517. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  518. for i, entry in enumerate(entries, 1):
  519. self.to_screen(u'[download] Downloading video #%s of %s' % (i, n_entries))
  520. extra = {
  521. 'playlist': playlist,
  522. 'playlist_index': i + playliststart,
  523. 'extractor': ie_result['extractor'],
  524. 'webpage_url': ie_result['webpage_url'],
  525. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  526. 'extractor_key': ie_result['extractor_key'],
  527. }
  528. reason = self._match_entry(entry)
  529. if reason is not None:
  530. self.to_screen(u'[download] ' + reason)
  531. continue
  532. entry_result = self.process_ie_result(entry,
  533. download=download,
  534. extra_info=extra)
  535. playlist_results.append(entry_result)
  536. ie_result['entries'] = playlist_results
  537. return ie_result
  538. elif result_type == 'compat_list':
  539. def _fixup(r):
  540. self.add_extra_info(r,
  541. {
  542. 'extractor': ie_result['extractor'],
  543. 'webpage_url': ie_result['webpage_url'],
  544. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  545. 'extractor_key': ie_result['extractor_key'],
  546. })
  547. return r
  548. ie_result['entries'] = [
  549. self.process_ie_result(_fixup(r), download, extra_info)
  550. for r in ie_result['entries']
  551. ]
  552. return ie_result
  553. else:
  554. raise Exception('Invalid result type: %s' % result_type)
  555. def select_format(self, format_spec, available_formats):
  556. if format_spec == 'best' or format_spec is None:
  557. return available_formats[-1]
  558. elif format_spec == 'worst':
  559. return available_formats[0]
  560. else:
  561. extensions = [u'mp4', u'flv', u'webm', u'3gp']
  562. if format_spec in extensions:
  563. filter_f = lambda f: f['ext'] == format_spec
  564. else:
  565. filter_f = lambda f: f['format_id'] == format_spec
  566. matches = list(filter(filter_f, available_formats))
  567. if matches:
  568. return matches[-1]
  569. return None
  570. def process_video_result(self, info_dict, download=True):
  571. assert info_dict.get('_type', 'video') == 'video'
  572. if 'playlist' not in info_dict:
  573. # It isn't part of a playlist
  574. info_dict['playlist'] = None
  575. info_dict['playlist_index'] = None
  576. # This extractors handle format selection themselves
  577. if info_dict['extractor'] in [u'Youku']:
  578. if download:
  579. self.process_info(info_dict)
  580. return info_dict
  581. # We now pick which formats have to be downloaded
  582. if info_dict.get('formats') is None:
  583. # There's only one format available
  584. formats = [info_dict]
  585. else:
  586. formats = info_dict['formats']
  587. # We check that all the formats have the format and format_id fields
  588. for (i, format) in enumerate(formats):
  589. if format.get('format_id') is None:
  590. format['format_id'] = compat_str(i)
  591. if format.get('format') is None:
  592. format['format'] = u'{id} - {res}{note}'.format(
  593. id=format['format_id'],
  594. res=self.format_resolution(format),
  595. note=u' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  596. )
  597. # Automatically determine file extension if missing
  598. if 'ext' not in format:
  599. format['ext'] = determine_ext(format['url'])
  600. format_limit = self.params.get('format_limit', None)
  601. if format_limit:
  602. formats = list(takewhile_inclusive(
  603. lambda f: f['format_id'] != format_limit, formats
  604. ))
  605. # TODO Central sorting goes here
  606. if formats[0] is not info_dict:
  607. # only set the 'formats' fields if the original info_dict list them
  608. # otherwise we end up with a circular reference, the first (and unique)
  609. # element in the 'formats' field in info_dict is info_dict itself,
  610. # wich can't be exported to json
  611. info_dict['formats'] = formats
  612. if self.params.get('listformats', None):
  613. self.list_formats(info_dict)
  614. return
  615. req_format = self.params.get('format', 'best')
  616. if req_format is None:
  617. req_format = 'best'
  618. formats_to_download = []
  619. # The -1 is for supporting YoutubeIE
  620. if req_format in ('-1', 'all'):
  621. formats_to_download = formats
  622. else:
  623. # We can accept formats requestd in the format: 34/5/best, we pick
  624. # the first that is available, starting from left
  625. req_formats = req_format.split('/')
  626. for rf in req_formats:
  627. selected_format = self.select_format(rf, formats)
  628. if selected_format is not None:
  629. formats_to_download = [selected_format]
  630. break
  631. if not formats_to_download:
  632. raise ExtractorError(u'requested format not available',
  633. expected=True)
  634. if download:
  635. if len(formats_to_download) > 1:
  636. self.to_screen(u'[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  637. for format in formats_to_download:
  638. new_info = dict(info_dict)
  639. new_info.update(format)
  640. self.process_info(new_info)
  641. # We update the info dict with the best quality format (backwards compatibility)
  642. info_dict.update(formats_to_download[-1])
  643. return info_dict
  644. def process_info(self, info_dict):
  645. """Process a single resolved IE result."""
  646. assert info_dict.get('_type', 'video') == 'video'
  647. #We increment the download the download count here to match the previous behaviour.
  648. self.increment_downloads()
  649. info_dict['fulltitle'] = info_dict['title']
  650. if len(info_dict['title']) > 200:
  651. info_dict['title'] = info_dict['title'][:197] + u'...'
  652. # Keep for backwards compatibility
  653. info_dict['stitle'] = info_dict['title']
  654. if not 'format' in info_dict:
  655. info_dict['format'] = info_dict['ext']
  656. reason = self._match_entry(info_dict)
  657. if reason is not None:
  658. self.to_screen(u'[download] ' + reason)
  659. return
  660. max_downloads = self.params.get('max_downloads')
  661. if max_downloads is not None:
  662. if self._num_downloads > int(max_downloads):
  663. raise MaxDownloadsReached()
  664. filename = self.prepare_filename(info_dict)
  665. # Forced printings
  666. if self.params.get('forcetitle', False):
  667. self.to_stdout(info_dict['fulltitle'])
  668. if self.params.get('forceid', False):
  669. self.to_stdout(info_dict['id'])
  670. if self.params.get('forceurl', False):
  671. # For RTMP URLs, also include the playpath
  672. self.to_stdout(info_dict['url'] + info_dict.get('play_path', u''))
  673. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  674. self.to_stdout(info_dict['thumbnail'])
  675. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  676. self.to_stdout(info_dict['description'])
  677. if self.params.get('forcefilename', False) and filename is not None:
  678. self.to_stdout(filename)
  679. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  680. self.to_stdout(formatSeconds(info_dict['duration']))
  681. if self.params.get('forceformat', False):
  682. self.to_stdout(info_dict['format'])
  683. if self.params.get('forcejson', False):
  684. info_dict['_filename'] = filename
  685. self.to_stdout(json.dumps(info_dict))
  686. # Do nothing else if in simulate mode
  687. if self.params.get('simulate', False):
  688. return
  689. if filename is None:
  690. return
  691. try:
  692. dn = os.path.dirname(encodeFilename(filename))
  693. if dn != '' and not os.path.exists(dn):
  694. os.makedirs(dn)
  695. except (OSError, IOError) as err:
  696. self.report_error(u'unable to create directory ' + compat_str(err))
  697. return
  698. if self.params.get('writedescription', False):
  699. descfn = filename + u'.description'
  700. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  701. self.to_screen(u'[info] Video description is already present')
  702. else:
  703. try:
  704. self.to_screen(u'[info] Writing video description to: ' + descfn)
  705. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  706. descfile.write(info_dict['description'])
  707. except (KeyError, TypeError):
  708. self.report_warning(u'There\'s no description to write.')
  709. except (OSError, IOError):
  710. self.report_error(u'Cannot write description file ' + descfn)
  711. return
  712. if self.params.get('writeannotations', False):
  713. annofn = filename + u'.annotations.xml'
  714. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  715. self.to_screen(u'[info] Video annotations are already present')
  716. else:
  717. try:
  718. self.to_screen(u'[info] Writing video annotations to: ' + annofn)
  719. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  720. annofile.write(info_dict['annotations'])
  721. except (KeyError, TypeError):
  722. self.report_warning(u'There are no annotations to write.')
  723. except (OSError, IOError):
  724. self.report_error(u'Cannot write annotations file: ' + annofn)
  725. return
  726. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  727. self.params.get('writeautomaticsub')])
  728. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  729. # subtitles download errors are already managed as troubles in relevant IE
  730. # that way it will silently go on when used with unsupporting IE
  731. subtitles = info_dict['subtitles']
  732. sub_format = self.params.get('subtitlesformat', 'srt')
  733. for sub_lang in subtitles.keys():
  734. sub = subtitles[sub_lang]
  735. if sub is None:
  736. continue
  737. try:
  738. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  739. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  740. self.to_screen(u'[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  741. else:
  742. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  743. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  744. subfile.write(sub)
  745. except (OSError, IOError):
  746. self.report_error(u'Cannot write subtitles file ' + descfn)
  747. return
  748. if self.params.get('writeinfojson', False):
  749. infofn = os.path.splitext(filename)[0] + u'.info.json'
  750. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  751. self.to_screen(u'[info] Video description metadata is already present')
  752. else:
  753. self.to_screen(u'[info] Writing video description metadata as JSON to: ' + infofn)
  754. try:
  755. write_json_file(info_dict, encodeFilename(infofn))
  756. except (OSError, IOError):
  757. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  758. return
  759. if self.params.get('writethumbnail', False):
  760. if info_dict.get('thumbnail') is not None:
  761. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  762. thumb_filename = os.path.splitext(filename)[0] + u'.' + thumb_format
  763. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  764. self.to_screen(u'[%s] %s: Thumbnail is already present' %
  765. (info_dict['extractor'], info_dict['id']))
  766. else:
  767. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  768. (info_dict['extractor'], info_dict['id']))
  769. try:
  770. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  771. with open(thumb_filename, 'wb') as thumbf:
  772. shutil.copyfileobj(uf, thumbf)
  773. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  774. (info_dict['extractor'], info_dict['id'], thumb_filename))
  775. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  776. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  777. (info_dict['thumbnail'], compat_str(err)))
  778. if not self.params.get('skip_download', False):
  779. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  780. success = True
  781. else:
  782. try:
  783. fd = get_suitable_downloader(info_dict)(self, self.params)
  784. for ph in self._progress_hooks:
  785. fd.add_progress_hook(ph)
  786. success = fd.download(filename, info_dict)
  787. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  788. self.report_error(u'unable to download video data: %s' % str(err))
  789. return
  790. except (OSError, IOError) as err:
  791. raise UnavailableVideoError(err)
  792. except (ContentTooShortError, ) as err:
  793. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  794. return
  795. if success:
  796. try:
  797. self.post_process(filename, info_dict)
  798. except (PostProcessingError) as err:
  799. self.report_error(u'postprocessing: %s' % str(err))
  800. return
  801. self.record_download_archive(info_dict)
  802. def download(self, url_list):
  803. """Download a given list of URLs."""
  804. if (len(url_list) > 1 and
  805. '%' not in self.params['outtmpl']
  806. and self.params.get('max_downloads') != 1):
  807. raise SameFileError(self.params['outtmpl'])
  808. for url in url_list:
  809. try:
  810. #It also downloads the videos
  811. self.extract_info(url)
  812. except UnavailableVideoError:
  813. self.report_error(u'unable to download video')
  814. except MaxDownloadsReached:
  815. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  816. raise
  817. return self._download_retcode
  818. def download_with_info_file(self, info_filename):
  819. with io.open(info_filename, 'r', encoding='utf-8') as f:
  820. info = json.load(f)
  821. try:
  822. self.process_ie_result(info, download=True)
  823. except DownloadError:
  824. webpage_url = info.get('webpage_url')
  825. if webpage_url is not None:
  826. self.report_warning(u'The info failed to download, trying with "%s"' % webpage_url)
  827. return self.download([webpage_url])
  828. else:
  829. raise
  830. return self._download_retcode
  831. def post_process(self, filename, ie_info):
  832. """Run all the postprocessors on the given file."""
  833. info = dict(ie_info)
  834. info['filepath'] = filename
  835. keep_video = None
  836. for pp in self._pps:
  837. try:
  838. keep_video_wish, new_info = pp.run(info)
  839. if keep_video_wish is not None:
  840. if keep_video_wish:
  841. keep_video = keep_video_wish
  842. elif keep_video is None:
  843. # No clear decision yet, let IE decide
  844. keep_video = keep_video_wish
  845. except PostProcessingError as e:
  846. self.report_error(e.msg)
  847. if keep_video is False and not self.params.get('keepvideo', False):
  848. try:
  849. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  850. os.remove(encodeFilename(filename))
  851. except (IOError, OSError):
  852. self.report_warning(u'Unable to remove downloaded video file')
  853. def _make_archive_id(self, info_dict):
  854. # Future-proof against any change in case
  855. # and backwards compatibility with prior versions
  856. extractor = info_dict.get('extractor_key')
  857. if extractor is None:
  858. if 'id' in info_dict:
  859. extractor = info_dict.get('ie_key') # key in a playlist
  860. if extractor is None:
  861. return None # Incomplete video information
  862. return extractor.lower() + u' ' + info_dict['id']
  863. def in_download_archive(self, info_dict):
  864. fn = self.params.get('download_archive')
  865. if fn is None:
  866. return False
  867. vid_id = self._make_archive_id(info_dict)
  868. if vid_id is None:
  869. return False # Incomplete video information
  870. try:
  871. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  872. for line in archive_file:
  873. if line.strip() == vid_id:
  874. return True
  875. except IOError as ioe:
  876. if ioe.errno != errno.ENOENT:
  877. raise
  878. return False
  879. def record_download_archive(self, info_dict):
  880. fn = self.params.get('download_archive')
  881. if fn is None:
  882. return
  883. vid_id = self._make_archive_id(info_dict)
  884. assert vid_id
  885. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  886. archive_file.write(vid_id + u'\n')
  887. @staticmethod
  888. def format_resolution(format, default='unknown'):
  889. if format.get('vcodec') == 'none':
  890. return 'audio only'
  891. if format.get('resolution') is not None:
  892. return format['resolution']
  893. if format.get('height') is not None:
  894. if format.get('width') is not None:
  895. res = u'%sx%s' % (format['width'], format['height'])
  896. else:
  897. res = u'%sp' % format['height']
  898. elif format.get('width') is not None:
  899. res = u'?x%d' % format['width']
  900. else:
  901. res = default
  902. return res
  903. def list_formats(self, info_dict):
  904. def format_note(fdict):
  905. res = u''
  906. if f.get('ext') in ['f4f', 'f4m']:
  907. res += u'(unsupported) '
  908. if fdict.get('format_note') is not None:
  909. res += fdict['format_note'] + u' '
  910. if fdict.get('tbr') is not None:
  911. res += u'%4dk ' % fdict['tbr']
  912. if (fdict.get('vcodec') is not None and
  913. fdict.get('vcodec') != 'none'):
  914. res += u'%-5s@' % fdict['vcodec']
  915. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  916. res += u'video@'
  917. if fdict.get('vbr') is not None:
  918. res += u'%4dk' % fdict['vbr']
  919. if fdict.get('acodec') is not None:
  920. if res:
  921. res += u', '
  922. res += u'%-5s' % fdict['acodec']
  923. elif fdict.get('abr') is not None:
  924. if res:
  925. res += u', '
  926. res += 'audio'
  927. if fdict.get('abr') is not None:
  928. res += u'@%3dk' % fdict['abr']
  929. if fdict.get('filesize') is not None:
  930. if res:
  931. res += u', '
  932. res += format_bytes(fdict['filesize'])
  933. return res
  934. def line(format, idlen=20):
  935. return ((u'%-' + compat_str(idlen + 1) + u's%-10s%-12s%s') % (
  936. format['format_id'],
  937. format['ext'],
  938. self.format_resolution(format),
  939. format_note(format),
  940. ))
  941. formats = info_dict.get('formats', [info_dict])
  942. idlen = max(len(u'format code'),
  943. max(len(f['format_id']) for f in formats))
  944. formats_s = [line(f, idlen) for f in formats]
  945. if len(formats) > 1:
  946. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  947. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  948. header_line = line({
  949. 'format_id': u'format code', 'ext': u'extension',
  950. 'resolution': u'resolution', 'format_note': u'note'}, idlen=idlen)
  951. self.to_screen(u'[info] Available formats for %s:\n%s\n%s' %
  952. (info_dict['id'], header_line, u"\n".join(formats_s)))
  953. def urlopen(self, req):
  954. """ Start an HTTP download """
  955. return self._opener.open(req)
  956. def print_debug_header(self):
  957. if not self.params.get('verbose'):
  958. return
  959. write_string(u'[debug] youtube-dl version ' + __version__ + u'\n')
  960. try:
  961. sp = subprocess.Popen(
  962. ['git', 'rev-parse', '--short', 'HEAD'],
  963. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  964. cwd=os.path.dirname(os.path.abspath(__file__)))
  965. out, err = sp.communicate()
  966. out = out.decode().strip()
  967. if re.match('[0-9a-f]+', out):
  968. write_string(u'[debug] Git HEAD: ' + out + u'\n')
  969. except:
  970. try:
  971. sys.exc_clear()
  972. except:
  973. pass
  974. write_string(u'[debug] Python version %s - %s' %
  975. (platform.python_version(), platform_name()) + u'\n')
  976. proxy_map = {}
  977. for handler in self._opener.handlers:
  978. if hasattr(handler, 'proxies'):
  979. proxy_map.update(handler.proxies)
  980. write_string(u'[debug] Proxy map: ' + compat_str(proxy_map) + u'\n')
  981. def _setup_opener(self):
  982. timeout_val = self.params.get('socket_timeout')
  983. timeout = 600 if timeout_val is None else float(timeout_val)
  984. opts_cookiefile = self.params.get('cookiefile')
  985. opts_proxy = self.params.get('proxy')
  986. if opts_cookiefile is None:
  987. self.cookiejar = compat_cookiejar.CookieJar()
  988. else:
  989. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  990. opts_cookiefile)
  991. if os.access(opts_cookiefile, os.R_OK):
  992. self.cookiejar.load()
  993. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  994. self.cookiejar)
  995. if opts_proxy is not None:
  996. if opts_proxy == '':
  997. proxies = {}
  998. else:
  999. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1000. else:
  1001. proxies = compat_urllib_request.getproxies()
  1002. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1003. if 'http' in proxies and 'https' not in proxies:
  1004. proxies['https'] = proxies['http']
  1005. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1006. https_handler = make_HTTPS_handler(
  1007. self.params.get('nocheckcertificate', False))
  1008. opener = compat_urllib_request.build_opener(
  1009. https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  1010. # Delete the default user-agent header, which would otherwise apply in
  1011. # cases where our custom HTTP handler doesn't come into play
  1012. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1013. opener.addheaders = []
  1014. self._opener = opener
  1015. # TODO remove this global modification
  1016. compat_urllib_request.install_opener(opener)
  1017. socket.setdefaulttimeout(timeout)