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.

193 lines
8.1 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. clean_html,
  6. determine_ext,
  7. encode_dict,
  8. int_or_none,
  9. sanitized_Request,
  10. ExtractorError,
  11. urlencode_postdata
  12. )
  13. class FunimationIE(InfoExtractor):
  14. _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/(?:official|promotional)/(?P<id>[^/?#&]+)'
  15. _NETRC_MACHINE = 'funimation'
  16. _TESTS = [{
  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. 'url': 'http://www.funimation.com/shows/hacksign/videos/official/role-play',
  28. 'info_dict': {
  29. 'id': '31128',
  30. 'display_id': 'role-play',
  31. 'ext': 'mp4',
  32. 'title': '.hack//SIGN - 1 - Role Play',
  33. 'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd',
  34. 'thumbnail': 're:https?://.*\.jpg',
  35. },
  36. }, {
  37. 'url': 'http://www.funimation.com/shows/attack-on-titan-junior-high/videos/promotional/broadcast-dub-preview',
  38. 'info_dict': {
  39. 'id': '9635',
  40. 'display_id': 'broadcast-dub-preview',
  41. 'ext': 'mp4',
  42. 'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
  43. 'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
  44. 'thumbnail': 're:https?://.*\.(?:jpg|png)',
  45. },
  46. }]
  47. def _login(self):
  48. (username, password) = self._get_login_info()
  49. if username is None:
  50. return
  51. data = urlencode_postdata(encode_dict({
  52. 'email_field': username,
  53. 'password_field': password,
  54. }))
  55. login_request = sanitized_Request('http://www.funimation.com/login', data, headers={
  56. 'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
  57. 'Content-Type': 'application/x-www-form-urlencoded'
  58. })
  59. login_page = self._download_webpage(
  60. login_request, None, 'Logging in as %s' % username)
  61. if any(p in login_page for p in ('funimation.com/logout', '>Log Out<')):
  62. return
  63. error = self._html_search_regex(
  64. r'(?s)<div[^>]+id=["\']errorMessages["\'][^>]*>(.+?)</div>',
  65. login_page, 'error messages', default=None)
  66. if error:
  67. raise ExtractorError('Unable to login: %s' % error, expected=True)
  68. raise ExtractorError('Unable to log in')
  69. def _real_initialize(self):
  70. self._login()
  71. def _real_extract(self, url):
  72. display_id = self._match_id(url)
  73. errors = []
  74. formats = []
  75. ERRORS_MAP = {
  76. 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
  77. 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
  78. 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
  79. 'ERROR_VIDEO_EXPIRED': 'videoExpired',
  80. 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
  81. 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
  82. 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
  83. 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
  84. 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
  85. 'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
  86. }
  87. USER_AGENTS = (
  88. # PC UA is served with m3u8 that provides some bonus lower quality formats
  89. ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
  90. # Mobile UA allows to extract direct links and also does not fail when
  91. # PC UA fails with hulu error (e.g.
  92. # http://www.funimation.com/shows/hacksign/videos/official/role-play)
  93. ('mobile', 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36'),
  94. )
  95. for kind, user_agent in USER_AGENTS:
  96. request = sanitized_Request(url)
  97. request.add_header('User-Agent', user_agent)
  98. webpage = self._download_webpage(
  99. request, display_id, 'Downloading %s webpage' % kind)
  100. playlist = self._parse_json(
  101. self._search_regex(
  102. r'var\s+playersData\s*=\s*(\[.+?\]);\n',
  103. webpage, 'players data'),
  104. display_id)[0]['playlist']
  105. items = next(item['items'] for item in playlist if item.get('items'))
  106. item = next(item for item in items if item.get('itemAK') == display_id)
  107. error_messages = {}
  108. video_error_messages = self._search_regex(
  109. r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
  110. webpage, 'error messages', default=None)
  111. if video_error_messages:
  112. error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
  113. if error_messages_json:
  114. for _, error in error_messages_json.items():
  115. type_ = error.get('type')
  116. description = error.get('description')
  117. content = error.get('content')
  118. if type_ == 'text' and description and content:
  119. error_message = ERRORS_MAP.get(description)
  120. if error_message:
  121. error_messages[error_message] = content
  122. for video in item.get('videoSet', []):
  123. auth_token = video.get('authToken')
  124. if not auth_token:
  125. continue
  126. funimation_id = video.get('FUNImationID') or video.get('videoId')
  127. preference = 1 if video.get('languageMode') == 'dub' else 0
  128. if not auth_token.startswith('?'):
  129. auth_token = '?%s' % auth_token
  130. for quality, height in (('sd', 480), ('hd', 720), ('hd1080', 1080)):
  131. format_url = video.get('%sUrl' % quality)
  132. if not format_url:
  133. continue
  134. if not format_url.startswith(('http', '//')):
  135. errors.append(format_url)
  136. continue
  137. if determine_ext(format_url) == 'm3u8':
  138. m3u8_formats = self._extract_m3u8_formats(
  139. format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
  140. preference=preference, m3u8_id='%s-hls' % funimation_id, fatal=False)
  141. if m3u8_formats:
  142. formats.extend(m3u8_formats)
  143. else:
  144. tbr = int_or_none(self._search_regex(
  145. r'-(\d+)[Kk]', format_url, 'tbr', default=None))
  146. formats.append({
  147. 'url': format_url + auth_token,
  148. 'format_id': '%s-http-%dp' % (funimation_id, height),
  149. 'height': height,
  150. 'tbr': tbr,
  151. 'preference': preference,
  152. })
  153. if not formats and errors:
  154. raise ExtractorError(
  155. '%s returned error: %s'
  156. % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
  157. expected=True)
  158. self._sort_formats(formats)
  159. title = item['title']
  160. artist = item.get('artist')
  161. if artist:
  162. title = '%s - %s' % (artist, title)
  163. description = self._og_search_description(webpage) or item.get('description')
  164. thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
  165. video_id = item.get('itemId') or display_id
  166. return {
  167. 'id': video_id,
  168. 'display_id': display_id,
  169. 'title': title,
  170. 'description': description,
  171. 'thumbnail': thumbnail,
  172. 'formats': formats,
  173. }