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.

232 lines
10 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_HTTPError,
  6. compat_urllib_parse_unquote_plus,
  7. )
  8. from ..utils import (
  9. clean_html,
  10. determine_ext,
  11. int_or_none,
  12. sanitized_Request,
  13. ExtractorError,
  14. urlencode_postdata
  15. )
  16. class FunimationIE(InfoExtractor):
  17. _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/(?:official|promotional)/(?P<id>[^/?#&]+)'
  18. _NETRC_MACHINE = 'funimation'
  19. _TESTS = [{
  20. 'url': 'http://www.funimation.com/shows/air/videos/official/breeze',
  21. 'info_dict': {
  22. 'id': '658',
  23. 'display_id': 'breeze',
  24. 'ext': 'mp4',
  25. 'title': 'Air - 1 - Breeze',
  26. 'description': 'md5:1769f43cd5fc130ace8fd87232207892',
  27. 'thumbnail': 're:https?://.*\.jpg',
  28. },
  29. 'skip': 'Access without user interaction is forbidden by CloudFlare, and video removed',
  30. }, {
  31. 'url': 'http://www.funimation.com/shows/hacksign/videos/official/role-play',
  32. 'info_dict': {
  33. 'id': '31128',
  34. 'display_id': 'role-play',
  35. 'ext': 'mp4',
  36. 'title': '.hack//SIGN - 1 - Role Play',
  37. 'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd',
  38. 'thumbnail': 're:https?://.*\.jpg',
  39. },
  40. 'skip': 'Access without user interaction is forbidden by CloudFlare',
  41. }, {
  42. 'url': 'http://www.funimation.com/shows/attack-on-titan-junior-high/videos/promotional/broadcast-dub-preview',
  43. 'info_dict': {
  44. 'id': '9635',
  45. 'display_id': 'broadcast-dub-preview',
  46. 'ext': 'mp4',
  47. 'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
  48. 'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
  49. 'thumbnail': 're:https?://.*\.(?:jpg|png)',
  50. },
  51. 'skip': 'Access without user interaction is forbidden by CloudFlare',
  52. }]
  53. _LOGIN_URL = 'http://www.funimation.com/login'
  54. def _download_webpage(self, *args, **kwargs):
  55. try:
  56. return super(FunimationIE, self)._download_webpage(*args, **kwargs)
  57. except ExtractorError as ee:
  58. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  59. response = ee.cause.read()
  60. if b'>Please complete the security check to access<' in response:
  61. raise ExtractorError(
  62. 'Access to funimation.com is blocked by CloudFlare. '
  63. 'Please browse to http://www.funimation.com/, solve '
  64. 'the reCAPTCHA, export browser cookies to a text file,'
  65. ' and then try again with --cookies YOUR_COOKIE_FILE.',
  66. expected=True)
  67. raise
  68. def _extract_cloudflare_session_ua(self, url):
  69. ci_session_cookie = self._get_cookies(url).get('ci_session')
  70. if ci_session_cookie:
  71. ci_session = compat_urllib_parse_unquote_plus(ci_session_cookie.value)
  72. # ci_session is a string serialized by PHP function serialize()
  73. # This case is simple enough to use regular expressions only
  74. return self._search_regex(
  75. r'"user_agent";s:\d+:"([^"]+)"', ci_session, 'user agent',
  76. default=None)
  77. def _login(self):
  78. (username, password) = self._get_login_info()
  79. if username is None:
  80. return
  81. data = urlencode_postdata({
  82. 'email_field': username,
  83. 'password_field': password,
  84. })
  85. user_agent = self._extract_cloudflare_session_ua(self._LOGIN_URL)
  86. if not user_agent:
  87. user_agent = 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'
  88. login_request = sanitized_Request(self._LOGIN_URL, data, headers={
  89. 'User-Agent': user_agent,
  90. 'Content-Type': 'application/x-www-form-urlencoded'
  91. })
  92. login_page = self._download_webpage(
  93. login_request, None, 'Logging in as %s' % username)
  94. if any(p in login_page for p in ('funimation.com/logout', '>Log Out<')):
  95. return
  96. error = self._html_search_regex(
  97. r'(?s)<div[^>]+id=["\']errorMessages["\'][^>]*>(.+?)</div>',
  98. login_page, 'error messages', default=None)
  99. if error:
  100. raise ExtractorError('Unable to login: %s' % error, expected=True)
  101. raise ExtractorError('Unable to log in')
  102. def _real_initialize(self):
  103. self._login()
  104. def _real_extract(self, url):
  105. display_id = self._match_id(url)
  106. errors = []
  107. formats = []
  108. ERRORS_MAP = {
  109. 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
  110. 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
  111. 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
  112. 'ERROR_VIDEO_EXPIRED': 'videoExpired',
  113. 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
  114. 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
  115. 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
  116. 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
  117. 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
  118. 'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
  119. }
  120. USER_AGENTS = (
  121. # PC UA is served with m3u8 that provides some bonus lower quality formats
  122. ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
  123. # Mobile UA allows to extract direct links and also does not fail when
  124. # PC UA fails with hulu error (e.g.
  125. # http://www.funimation.com/shows/hacksign/videos/official/role-play)
  126. ('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'),
  127. )
  128. user_agent = self._extract_cloudflare_session_ua(url)
  129. if user_agent:
  130. USER_AGENTS = ((None, user_agent),)
  131. for kind, user_agent in USER_AGENTS:
  132. request = sanitized_Request(url)
  133. request.add_header('User-Agent', user_agent)
  134. webpage = self._download_webpage(
  135. request, display_id,
  136. 'Downloading %s webpage' % kind if kind else 'Downloading webpage')
  137. playlist = self._parse_json(
  138. self._search_regex(
  139. r'var\s+playersData\s*=\s*(\[.+?\]);\n',
  140. webpage, 'players data'),
  141. display_id)[0]['playlist']
  142. items = next(item['items'] for item in playlist if item.get('items'))
  143. item = next(item for item in items if item.get('itemAK') == display_id)
  144. error_messages = {}
  145. video_error_messages = self._search_regex(
  146. r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
  147. webpage, 'error messages', default=None)
  148. if video_error_messages:
  149. error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
  150. if error_messages_json:
  151. for _, error in error_messages_json.items():
  152. type_ = error.get('type')
  153. description = error.get('description')
  154. content = error.get('content')
  155. if type_ == 'text' and description and content:
  156. error_message = ERRORS_MAP.get(description)
  157. if error_message:
  158. error_messages[error_message] = content
  159. for video in item.get('videoSet', []):
  160. auth_token = video.get('authToken')
  161. if not auth_token:
  162. continue
  163. funimation_id = video.get('FUNImationID') or video.get('videoId')
  164. preference = 1 if video.get('languageMode') == 'dub' else 0
  165. if not auth_token.startswith('?'):
  166. auth_token = '?%s' % auth_token
  167. for quality, height in (('sd', 480), ('hd', 720), ('hd1080', 1080)):
  168. format_url = video.get('%sUrl' % quality)
  169. if not format_url:
  170. continue
  171. if not format_url.startswith(('http', '//')):
  172. errors.append(format_url)
  173. continue
  174. if determine_ext(format_url) == 'm3u8':
  175. formats.extend(self._extract_m3u8_formats(
  176. format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
  177. preference=preference, m3u8_id='%s-hls' % funimation_id, fatal=False))
  178. else:
  179. tbr = int_or_none(self._search_regex(
  180. r'-(\d+)[Kk]', format_url, 'tbr', default=None))
  181. formats.append({
  182. 'url': format_url + auth_token,
  183. 'format_id': '%s-http-%dp' % (funimation_id, height),
  184. 'height': height,
  185. 'tbr': tbr,
  186. 'preference': preference,
  187. })
  188. if not formats and errors:
  189. raise ExtractorError(
  190. '%s returned error: %s'
  191. % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
  192. expected=True)
  193. self._sort_formats(formats)
  194. title = item['title']
  195. artist = item.get('artist')
  196. if artist:
  197. title = '%s - %s' % (artist, title)
  198. description = self._og_search_description(webpage) or item.get('description')
  199. thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
  200. video_id = item.get('itemId') or display_id
  201. return {
  202. 'id': video_id,
  203. 'display_id': display_id,
  204. 'title': title,
  205. 'description': description,
  206. 'thumbnail': thumbnail,
  207. 'formats': formats,
  208. }