funimation.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_urllib_request
  6. from ..utils import (
  7. clean_html,
  8. determine_ext,
  9. encode_dict,
  10. sanitized_Request,
  11. ExtractorError,
  12. urlencode_postdata
  13. )
  14. class FunimationIE(InfoExtractor):
  15. _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/official/(?P<id>[^?]+)'
  16. _TEST = {
  17. 'url': 'http://www.funimation.com/shows/air/videos/official/breeze',
  18. 'info_dict': {
  19. 'id': '658',
  20. 'display_id': 'breeze',
  21. 'ext': 'mp4',
  22. 'title': 'Air - 1 - Breeze',
  23. 'description': 'md5:1769f43cd5fc130ace8fd87232207892',
  24. 'thumbnail': 're:https?://.*\.jpg',
  25. },
  26. }
  27. def _download_webpage(self, url_or_request, video_id, note='Downloading webpage'):
  28. HEADERS = {
  29. 'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
  30. }
  31. if isinstance(url_or_request, compat_urllib_request.Request):
  32. for header, value in HEADERS.items():
  33. url_or_request.add_header(header, value)
  34. else:
  35. url_or_request = sanitized_Request(url_or_request, headers=HEADERS)
  36. response = super(FunimationIE, self)._download_webpage(url_or_request, video_id, note)
  37. return response
  38. def _login(self):
  39. (username, password) = self._get_login_info()
  40. if username is None:
  41. return
  42. data = urlencode_postdata(encode_dict({
  43. 'email_field': username,
  44. 'password_field': password,
  45. }))
  46. login_request = sanitized_Request('http://www.funimation.com/login', data, headers={
  47. 'Content-Type': 'application/x-www-form-urlencoded'
  48. })
  49. login = self._download_webpage(
  50. login_request, None, 'Logging in as %s' % username)
  51. if re.search(r'<meta property="og:url" content="http://www.funimation.com/login"/>', login) is not None:
  52. raise ExtractorError('Unable to login, wrong username or password.', expected=True)
  53. def _real_initialize(self):
  54. self._login()
  55. def _real_extract(self, url):
  56. display_id = self._match_id(url)
  57. webpage = self._download_webpage(url, display_id)
  58. items = self._parse_json(
  59. self._search_regex(
  60. r'var\s+playersData\s*=\s*(\[.+?\]);\n',
  61. webpage, 'players data'),
  62. display_id)[0]['playlist'][0]['items']
  63. item = next(item for item in items if item.get('itemAK') == display_id)
  64. ERRORS_MAP = {
  65. 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
  66. 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
  67. 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
  68. 'ERROR_VIDEO_EXPIRED': 'videoExpired',
  69. 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
  70. 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
  71. 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
  72. 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
  73. 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
  74. 'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
  75. }
  76. error_messages = {}
  77. video_error_messages = self._search_regex(
  78. r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
  79. webpage, 'error messages', default=None)
  80. if video_error_messages:
  81. error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
  82. if error_messages_json:
  83. for _, error in error_messages_json.items():
  84. type_ = error.get('type')
  85. description = error.get('description')
  86. content = error.get('content')
  87. if type_ == 'text' and description and content:
  88. error_message = ERRORS_MAP.get(description)
  89. if error_message:
  90. error_messages[error_message] = content
  91. errors = []
  92. formats = []
  93. for video in item['videoSet']:
  94. auth_token = video.get('authToken')
  95. if not auth_token:
  96. continue
  97. funimation_id = video.get('FUNImationID') or video.get('videoId')
  98. if not auth_token.startswith('?'):
  99. auth_token = '?%s' % auth_token
  100. for quality in ('sd', 'hd', 'hd1080'):
  101. format_url = video.get('%sUrl' % quality)
  102. if not format_url:
  103. continue
  104. if not format_url.startswith(('http', '//')):
  105. errors.append(format_url)
  106. continue
  107. if determine_ext(format_url) == 'm3u8':
  108. m3u8_formats = self._extract_m3u8_formats(
  109. format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
  110. m3u8_id=funimation_id or 'hls', fatal=False)
  111. if m3u8_formats:
  112. formats.extend(m3u8_formats)
  113. else:
  114. formats.append({
  115. 'url': format_url + auth_token,
  116. })
  117. if not formats and errors:
  118. raise ExtractorError(
  119. '%s returned error: %s'
  120. % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
  121. expected=True)
  122. title = item['title']
  123. artist = item.get('artist')
  124. if artist:
  125. title = '%s - %s' % (artist, title)
  126. description = self._og_search_description(webpage) or item.get('description')
  127. thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
  128. video_id = item.get('itemId') or display_id
  129. return {
  130. 'id': video_id,
  131. 'display_id': display_id,
  132. 'title': title,
  133. 'description': description,
  134. 'thumbnail': thumbnail,
  135. 'formats': formats,
  136. }