funimation.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. determine_ext,
  10. int_or_none,
  11. js_to_json,
  12. sanitized_Request,
  13. ExtractorError,
  14. urlencode_postdata
  15. )
  16. class FunimationIE(InfoExtractor):
  17. _VALID_URL = r'https?://(?:www\.)?funimation(?:\.com|now\.uk)/shows/[^/]+/(?P<id>[^/?#&]+)'
  18. _NETRC_MACHINE = 'funimation'
  19. _TOKEN = None
  20. _TESTS = [{
  21. 'url': 'https://www.funimation.com/shows/hacksign/role-play/',
  22. 'info_dict': {
  23. 'id': '91144',
  24. 'display_id': 'role-play',
  25. 'ext': 'mp4',
  26. 'title': '.hack//SIGN - Role Play',
  27. 'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd',
  28. 'thumbnail': r're:https?://.*\.jpg',
  29. },
  30. 'params': {
  31. # m3u8 download
  32. 'skip_download': True,
  33. },
  34. }, {
  35. 'url': 'https://www.funimation.com/shows/attack-on-titan-junior-high/broadcast-dub-preview/',
  36. 'info_dict': {
  37. 'id': '9635',
  38. 'display_id': 'broadcast-dub-preview',
  39. 'ext': 'mp4',
  40. 'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
  41. 'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
  42. 'thumbnail': r're:https?://.*\.(?:jpg|png)',
  43. },
  44. 'skip': 'Access without user interaction is forbidden by CloudFlare',
  45. }, {
  46. 'url': 'https://www.funimationnow.uk/shows/puzzle-dragons-x/drop-impact/simulcast/',
  47. 'only_matching': True,
  48. }]
  49. _LOGIN_URL = 'http://www.funimation.com/login'
  50. def _extract_cloudflare_session_ua(self, url):
  51. ci_session_cookie = self._get_cookies(url).get('ci_session')
  52. if ci_session_cookie:
  53. ci_session = compat_urllib_parse_unquote_plus(ci_session_cookie.value)
  54. # ci_session is a string serialized by PHP function serialize()
  55. # This case is simple enough to use regular expressions only
  56. return self._search_regex(
  57. r'"user_agent";s:\d+:"([^"]+)"', ci_session, 'user agent',
  58. default=None)
  59. def _login(self):
  60. (username, password) = self._get_login_info()
  61. if username is None:
  62. return
  63. try:
  64. data = self._download_json(
  65. 'https://prod-api-funimationnow.dadcdigital.com/api/auth/login/',
  66. None, 'Logging in as %s' % username, data=urlencode_postdata({
  67. 'username': username,
  68. 'password': password,
  69. }))
  70. self._TOKEN = data['token']
  71. except ExtractorError as e:
  72. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  73. error = self._parse_json(e.cause.read().decode(), None)['error']
  74. raise ExtractorError(error, expected=True)
  75. raise
  76. def _real_initialize(self):
  77. self._login()
  78. def _real_extract(self, url):
  79. display_id = self._match_id(url)
  80. webpage = self._download_webpage(url, display_id)
  81. def _search_kane(name):
  82. return self._search_regex(
  83. r"KANE_customdimensions\.%s\s*=\s*'([^']+)';" % name,
  84. webpage, name, default=None)
  85. title_data = self._parse_json(self._search_regex(
  86. r'TITLE_DATA\s*=\s*({[^}]+})',
  87. webpage, 'title data', default=''),
  88. display_id, js_to_json, fatal=False) or {}
  89. video_id = title_data.get('id') or self._search_regex([
  90. r"KANE_customdimensions.videoID\s*=\s*'(\d+)';",
  91. r'<iframe[^>]+src="/player/(\d+)"',
  92. ], webpage, 'video_id', default=None)
  93. if not video_id:
  94. player_url = self._html_search_meta([
  95. 'al:web:url',
  96. 'og:video:url',
  97. 'og:video:secure_url',
  98. ], webpage, fatal=True)
  99. video_id = self._search_regex(r'/player/(\d+)', player_url, 'video id')
  100. title = episode = title_data.get('title') or _search_kane('videoTitle') or self._og_search_title(webpage)
  101. series = _search_kane('showName')
  102. if series:
  103. title = '%s - %s' % (series, title)
  104. description = self._html_search_meta(['description', 'og:description'], webpage, fatal=True)
  105. try:
  106. headers = {}
  107. if self._TOKEN:
  108. headers['Authorization'] = 'Token %s' % self._TOKEN
  109. sources = self._download_json(
  110. 'https://prod-api-funimationnow.dadcdigital.com/api/source/catalog/video/%s/signed/' % video_id,
  111. video_id, headers=headers)['items']
  112. except ExtractorError as e:
  113. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  114. error = self._parse_json(e.cause.read(), video_id)['errors'][0]
  115. raise ExtractorError('%s said: %s' % (
  116. self.IE_NAME, error.get('detail') or error.get('title')), expected=True)
  117. raise
  118. formats = []
  119. for source in sources:
  120. source_url = source.get('src')
  121. if not source_url:
  122. continue
  123. source_type = source.get('videoType') or determine_ext(source_url)
  124. if source_type == 'm3u8':
  125. formats.extend(self._extract_m3u8_formats(
  126. source_url, video_id, 'mp4',
  127. m3u8_id='hls', fatal=False))
  128. else:
  129. formats.append({
  130. 'format_id': source_type,
  131. 'url': source_url,
  132. })
  133. self._sort_formats(formats)
  134. return {
  135. 'id': video_id,
  136. 'display_id': display_id,
  137. 'title': title,
  138. 'description': description,
  139. 'thumbnail': self._og_search_thumbnail(webpage),
  140. 'series': series,
  141. 'season_number': int_or_none(title_data.get('seasonNum') or _search_kane('season')),
  142. 'episode_number': int_or_none(title_data.get('episodeNum')),
  143. 'episode': episode,
  144. 'season_id': title_data.get('seriesId'),
  145. 'formats': formats,
  146. }