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.

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