funimation.py 7.6 KB

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