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.

75 lines
2.8 KiB

  1. import socket
  2. from .common import InfoExtractor
  3. from ..utils import (
  4. compat_http_client,
  5. compat_urllib_error,
  6. compat_urllib_request,
  7. compat_str,
  8. )
  9. class SubtitlesIE(InfoExtractor):
  10. def _list_available_subtitles(self, video_id):
  11. """ outputs the available subtitles for the video """
  12. sub_lang_list = self._get_available_subtitles(video_id)
  13. sub_lang = ",".join(list(sub_lang_list.keys()))
  14. self.to_screen(u'%s: Available subtitles for video: %s' %
  15. (video_id, sub_lang))
  16. def _extract_subtitles(self, video_id):
  17. """ returns {sub_lang: sub} or {} if subtitles not found """
  18. sub_lang_list = self._get_available_subtitles(video_id)
  19. if not sub_lang_list: # error, it didn't get the available subtitles
  20. return {}
  21. if self._downloader.params.get('writesubtitles', False):
  22. if self._downloader.params.get('subtitleslang', False):
  23. sub_lang = self._downloader.params.get('subtitleslang')
  24. elif 'en' in sub_lang_list:
  25. sub_lang = 'en'
  26. else:
  27. sub_lang = list(sub_lang_list.keys())[0]
  28. if not sub_lang in sub_lang_list:
  29. self._downloader.report_warning(u'no closed captions found in the specified language "%s"' % sub_lang)
  30. return {}
  31. sub_lang_list = {sub_lang: sub_lang_list[sub_lang]}
  32. subtitles = {}
  33. for sub_lang, url in sub_lang_list.iteritems():
  34. subtitle = self._request_subtitle_url(sub_lang, url)
  35. if subtitle:
  36. subtitles[sub_lang] = subtitle
  37. return subtitles
  38. def _request_subtitle_url(self, sub_lang, url):
  39. """ makes the http request for the subtitle """
  40. try:
  41. sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
  42. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  43. self._downloader.report_warning(u'unable to download video subtitles for %s: %s' % (sub_lang, compat_str(err)))
  44. return
  45. if not sub:
  46. self._downloader.report_warning(u'Did not fetch video subtitles')
  47. return
  48. return sub
  49. def _get_available_subtitles(self, video_id):
  50. """ returns {sub_lang: url} or {} if not available """
  51. """ Must be redefined by the subclasses """
  52. pass
  53. def _request_automatic_caption(self, video_id, webpage):
  54. """ returns {sub_lang: sub} or {} if not available """
  55. """ Must be redefined by the subclasses """
  56. pass
  57. class NoAutoSubtitlesIE(SubtitlesIE):
  58. """ A subtitle class for the servers that don't support auto-captions"""
  59. def _request_automatic_caption(self, video_id, webpage):
  60. self._downloader.report_warning(u'Automatic Captions not supported by this server')
  61. return {}