funimation.py 7.9 KB

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