funimation.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_urllib_request
  6. from ..utils import (
  7. clean_html,
  8. determine_ext,
  9. encode_dict,
  10. sanitized_Request,
  11. ExtractorError,
  12. urlencode_postdata
  13. )
  14. class FunimationIE(InfoExtractor):
  15. _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/official/(?P<id>[^?]+)'
  16. _TEST = {
  17. 'url': 'http://www.funimation.com/shows/air/videos/official/breeze',
  18. 'info_dict': {
  19. 'id': 'AIRENG0001',
  20. 'title': 'Air - 1 - Breeze ',
  21. 'ext': 'mp4',
  22. 'thumbnail': 'http://www.funimation.com/admin/uploads/default/recap_thumbnails/7555590/home_spotlight/AIR0001.jpg',
  23. 'description': 'Travelling puppeteer Yukito arrives in a small town where he hopes to earn money through the magic of his puppets. When a young girl named Misuzu lures him to her home with the promise of food, his life changes forever. ',
  24. }
  25. }
  26. def _download_webpage(self, url_or_request, video_id, note='Downloading webpage'):
  27. HEADERS = {
  28. 'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
  29. }
  30. if isinstance(url_or_request, compat_urllib_request.Request):
  31. for header, value in HEADERS.items():
  32. url_or_request.add_header(header, value)
  33. else:
  34. url_or_request = sanitized_Request(url_or_request, headers=HEADERS)
  35. response = super(FunimationIE, self)._download_webpage(url_or_request, video_id, note)
  36. return response
  37. def _login(self):
  38. (username, password) = self._get_login_info()
  39. if username is None:
  40. return
  41. data = urlencode_postdata(encode_dict({
  42. 'email_field': username,
  43. 'password_field': password,
  44. }))
  45. login_request = sanitized_Request('http://www.funimation.com/login', data, headers={
  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. webpage = self._download_webpage(url, display_id)
  57. items = self._parse_json(
  58. self._search_regex(
  59. r'var\s+playersData\s*=\s*(\[.+?\]);\n',
  60. webpage, 'players data'),
  61. display_id)[0]['playlist'][0]['items']
  62. item = next(item for item in items if item.get('itemAK') == display_id)
  63. ERRORS_MAP = {
  64. 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
  65. 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
  66. 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
  67. 'ERROR_VIDEO_EXPIRED': 'videoExpired',
  68. 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
  69. 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
  70. 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
  71. 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
  72. 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
  73. 'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
  74. }
  75. error_messages = {}
  76. video_error_messages = self._search_regex(
  77. r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
  78. webpage, 'error messages', default=None)
  79. if video_error_messages:
  80. error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
  81. if error_messages_json:
  82. for _, error in error_messages_json.items():
  83. type_ = error.get('type')
  84. description = error.get('description')
  85. content = error.get('content')
  86. if type_ == 'text' and description and content:
  87. error_message = ERRORS_MAP.get(description)
  88. if error_message:
  89. error_messages[error_message] = content
  90. errors = []
  91. formats = []
  92. for video in item['videoSet']:
  93. auth_token = video.get('authToken')
  94. if not auth_token:
  95. continue
  96. funimation_id = video.get('FUNImationID') or video.get('videoId')
  97. if not auth_token.startswith('?'):
  98. auth_token = '?%s' % auth_token
  99. for quality in ('sd', 'hd', 'hd1080'):
  100. format_url = video.get('%sUrl' % quality)
  101. if not format_url:
  102. continue
  103. if not format_url.startswith(('http', '//')):
  104. errors.append(format_url)
  105. continue
  106. if determine_ext(format_url) == 'm3u8':
  107. m3u8_formats = self._extract_m3u8_formats(
  108. format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
  109. m3u8_id=funimation_id or 'hls', fatal=False)
  110. if m3u8_formats:
  111. formats.extend(m3u8_formats)
  112. else:
  113. formats.append({
  114. 'url': format_url + auth_token,
  115. })
  116. if not formats and errors:
  117. raise ExtractorError(
  118. '%s returned error: %s'
  119. % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
  120. expected=True)
  121. title = item['title']
  122. artist = item.get('artist')
  123. if artist:
  124. title = '%s - %s' % (artist, title)
  125. description = self._og_search_description(webpage) or item.get('description')
  126. thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
  127. video_id = item.get('itemId') or display_id
  128. return {
  129. 'id': video_id,
  130. 'display_id': display_id,
  131. 'title': title,
  132. 'description': description,
  133. 'thumbnail': thumbnail,
  134. 'formats': formats,
  135. }