funimation.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. clean_html,
  7. determine_ext,
  8. encode_dict,
  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. _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(encode_dict({
  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 = self._download_webpage(
  59. login_request, None, 'Logging in as %s' % username)
  60. if re.search(r'<meta property="og:url" content="http://www.funimation.com/login"/>', login) is not None:
  61. raise ExtractorError('Unable to login, wrong username or password.', expected=True)
  62. def _real_initialize(self):
  63. self._login()
  64. def _real_extract(self, url):
  65. display_id = self._match_id(url)
  66. errors = []
  67. formats = []
  68. ERRORS_MAP = {
  69. 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
  70. 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
  71. 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
  72. 'ERROR_VIDEO_EXPIRED': 'videoExpired',
  73. 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
  74. 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
  75. 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
  76. 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
  77. 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
  78. 'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
  79. }
  80. USER_AGENTS = (
  81. # PC UA is served with m3u8 that provides some bonus lower quality formats
  82. ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
  83. # Mobile UA allows to extract direct links and also does not fail when
  84. # PC UA fails with hulu error (e.g.
  85. # http://www.funimation.com/shows/hacksign/videos/official/role-play)
  86. ('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'),
  87. )
  88. for kind, user_agent in USER_AGENTS:
  89. request = sanitized_Request(url)
  90. request.add_header('User-Agent', user_agent)
  91. webpage = self._download_webpage(
  92. request, display_id, 'Downloading %s webpage' % kind)
  93. playlist = self._parse_json(
  94. self._search_regex(
  95. r'var\s+playersData\s*=\s*(\[.+?\]);\n',
  96. webpage, 'players data'),
  97. display_id)[0]['playlist']
  98. items = next(item['items'] for item in playlist if item.get('items'))
  99. item = next(item for item in items if item.get('itemAK') == display_id)
  100. error_messages = {}
  101. video_error_messages = self._search_regex(
  102. r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
  103. webpage, 'error messages', default=None)
  104. if video_error_messages:
  105. error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
  106. if error_messages_json:
  107. for _, error in error_messages_json.items():
  108. type_ = error.get('type')
  109. description = error.get('description')
  110. content = error.get('content')
  111. if type_ == 'text' and description and content:
  112. error_message = ERRORS_MAP.get(description)
  113. if error_message:
  114. error_messages[error_message] = content
  115. for video in item.get('videoSet', []):
  116. auth_token = video.get('authToken')
  117. if not auth_token:
  118. continue
  119. funimation_id = video.get('FUNImationID') or video.get('videoId')
  120. preference = 1 if video.get('languageMode') == 'dub' else 0
  121. if not auth_token.startswith('?'):
  122. auth_token = '?%s' % auth_token
  123. for quality in ('sd', 'hd', 'hd1080'):
  124. format_url = video.get('%sUrl' % quality)
  125. if not format_url:
  126. continue
  127. if not format_url.startswith(('http', '//')):
  128. errors.append(format_url)
  129. continue
  130. if determine_ext(format_url) == 'm3u8':
  131. m3u8_formats = self._extract_m3u8_formats(
  132. format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
  133. preference=preference, m3u8_id=funimation_id or 'hls', fatal=False)
  134. if m3u8_formats:
  135. formats.extend(m3u8_formats)
  136. else:
  137. f = {
  138. 'url': format_url + auth_token,
  139. 'format_id': funimation_id,
  140. 'preference': preference,
  141. }
  142. mobj = re.search(r'(?P<height>\d+)-(?P<tbr>\d+)[Kk]', format_url)
  143. if mobj:
  144. f.update({
  145. 'height': int(mobj.group('height')),
  146. 'tbr': int(mobj.group('tbr')),
  147. })
  148. formats.append(f)
  149. if not formats and errors:
  150. raise ExtractorError(
  151. '%s returned error: %s'
  152. % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
  153. expected=True)
  154. self._sort_formats(formats)
  155. title = item['title']
  156. artist = item.get('artist')
  157. if artist:
  158. title = '%s - %s' % (artist, title)
  159. description = self._og_search_description(webpage) or item.get('description')
  160. thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
  161. video_id = item.get('itemId') or display_id
  162. return {
  163. 'id': video_id,
  164. 'display_id': display_id,
  165. 'title': title,
  166. 'description': description,
  167. 'thumbnail': thumbnail,
  168. 'formats': formats,
  169. }