funimation.py 7.4 KB

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