funimation.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import random
  2. import re
  3. import string
  4. from .common import InfoExtractor
  5. from ..networking.exceptions import HTTPError
  6. from ..utils import (
  7. ExtractorError,
  8. determine_ext,
  9. int_or_none,
  10. join_nonempty,
  11. js_to_json,
  12. make_archive_id,
  13. orderedSet,
  14. qualities,
  15. str_or_none,
  16. traverse_obj,
  17. try_get,
  18. urlencode_postdata,
  19. )
  20. class FunimationBaseIE(InfoExtractor):
  21. _NETRC_MACHINE = 'funimation'
  22. _REGION = None
  23. _TOKEN = None
  24. def _get_region(self):
  25. region_cookie = self._get_cookies('https://www.funimation.com').get('region')
  26. region = region_cookie.value if region_cookie else self.get_param('geo_bypass_country')
  27. return region or traverse_obj(
  28. self._download_json(
  29. 'https://geo-service.prd.funimationsvc.com/geo/v1/region/check', None, fatal=False,
  30. note='Checking geo-location', errnote='Unable to fetch geo-location information'),
  31. 'region') or 'US'
  32. def _perform_login(self, username, password):
  33. if self._TOKEN:
  34. return
  35. try:
  36. data = self._download_json(
  37. 'https://prod-api-funimationnow.dadcdigital.com/api/auth/login/',
  38. None, 'Logging in', data=urlencode_postdata({
  39. 'username': username,
  40. 'password': password,
  41. }))
  42. FunimationBaseIE._TOKEN = data['token']
  43. except ExtractorError as e:
  44. if isinstance(e.cause, HTTPError) and e.cause.status == 401:
  45. error = self._parse_json(e.cause.response.read().decode(), None)['error']
  46. raise ExtractorError(error, expected=True)
  47. raise
  48. class FunimationPageIE(FunimationBaseIE):
  49. IE_NAME = 'funimation:page'
  50. _VALID_URL = r'https?://(?:www\.)?funimation(?:\.com|now\.uk)/(?:(?P<lang>[^/]+)/)?(?:shows|v)/(?P<show>[^/]+)/(?P<episode>[^/?#&]+)'
  51. _TESTS = [{
  52. 'url': 'https://www.funimation.com/shows/attack-on-titan-junior-high/broadcast-dub-preview/',
  53. 'info_dict': {
  54. 'id': '210050',
  55. 'ext': 'mp4',
  56. 'title': 'Broadcast Dub Preview',
  57. # Other metadata is tested in FunimationIE
  58. },
  59. 'params': {
  60. 'skip_download': 'm3u8',
  61. },
  62. 'add_ie': ['Funimation'],
  63. }, {
  64. # Not available in US
  65. 'url': 'https://www.funimation.com/shows/hacksign/role-play/',
  66. 'only_matching': True,
  67. }, {
  68. # with lang code
  69. 'url': 'https://www.funimation.com/en/shows/hacksign/role-play/',
  70. 'only_matching': True,
  71. }, {
  72. 'url': 'https://www.funimationnow.uk/shows/puzzle-dragons-x/drop-impact/simulcast/',
  73. 'only_matching': True,
  74. }, {
  75. 'url': 'https://www.funimation.com/v/a-certain-scientific-railgun/super-powered-level-5',
  76. 'only_matching': True,
  77. }]
  78. def _real_initialize(self):
  79. if not self._REGION:
  80. FunimationBaseIE._REGION = self._get_region()
  81. def _real_extract(self, url):
  82. locale, show, episode = self._match_valid_url(url).group('lang', 'show', 'episode')
  83. video_id = traverse_obj(self._download_json(
  84. f'https://title-api.prd.funimationsvc.com/v1/shows/{show}/episodes/{episode}',
  85. f'{show}_{episode}', query={
  86. 'deviceType': 'web',
  87. 'region': self._REGION,
  88. 'locale': locale or 'en',
  89. }), ('videoList', ..., 'id'), get_all=False)
  90. return self.url_result(f'https://www.funimation.com/player/{video_id}', FunimationIE.ie_key(), video_id)
  91. class FunimationIE(FunimationBaseIE):
  92. _VALID_URL = r'https?://(?:www\.)?funimation\.com/player/(?P<id>\d+)'
  93. _TESTS = [{
  94. 'url': 'https://www.funimation.com/player/210051',
  95. 'info_dict': {
  96. 'id': '210050',
  97. 'display_id': 'broadcast-dub-preview',
  98. 'ext': 'mp4',
  99. 'title': 'Broadcast Dub Preview',
  100. 'thumbnail': r're:https?://.*\.(?:jpg|png)',
  101. 'episode': 'Broadcast Dub Preview',
  102. 'episode_id': '210050',
  103. 'season': 'Extras',
  104. 'season_id': '166038',
  105. 'season_number': 99,
  106. 'series': 'Attack on Titan: Junior High',
  107. 'description': '',
  108. 'duration': 155,
  109. },
  110. 'params': {
  111. 'skip_download': 'm3u8',
  112. },
  113. }, {
  114. 'note': 'player_id should be extracted with the relevent compat-opt',
  115. 'url': 'https://www.funimation.com/player/210051',
  116. 'info_dict': {
  117. 'id': '210051',
  118. 'display_id': 'broadcast-dub-preview',
  119. 'ext': 'mp4',
  120. 'title': 'Broadcast Dub Preview',
  121. 'thumbnail': r're:https?://.*\.(?:jpg|png)',
  122. 'episode': 'Broadcast Dub Preview',
  123. 'episode_id': '210050',
  124. 'season': 'Extras',
  125. 'season_id': '166038',
  126. 'season_number': 99,
  127. 'series': 'Attack on Titan: Junior High',
  128. 'description': '',
  129. 'duration': 155,
  130. },
  131. 'params': {
  132. 'skip_download': 'm3u8',
  133. 'compat_opts': ['seperate-video-versions'],
  134. },
  135. }]
  136. @staticmethod
  137. def _get_experiences(episode):
  138. for lang, lang_data in episode.get('languages', {}).items():
  139. for video_data in lang_data.values():
  140. for version, f in video_data.items():
  141. yield lang, version.title(), f
  142. def _get_episode(self, webpage, experience_id=None, episode_id=None, fatal=True):
  143. """ Extract the episode, season and show objects given either episode/experience id """
  144. show = self._parse_json(
  145. self._search_regex(
  146. r'show\s*=\s*({.+?})\s*;', webpage, 'show data', fatal=fatal),
  147. experience_id, transform_source=js_to_json, fatal=fatal) or []
  148. for season in show.get('seasons', []):
  149. for episode in season.get('episodes', []):
  150. if episode_id is not None:
  151. if str(episode.get('episodePk')) == episode_id:
  152. return episode, season, show
  153. continue
  154. for _, _, f in self._get_experiences(episode):
  155. if f.get('experienceId') == experience_id:
  156. return episode, season, show
  157. if fatal:
  158. raise ExtractorError('Unable to find episode information')
  159. else:
  160. self.report_warning('Unable to find episode information')
  161. return {}, {}, {}
  162. def _real_extract(self, url):
  163. initial_experience_id = self._match_id(url)
  164. webpage = self._download_webpage(
  165. url, initial_experience_id, note=f'Downloading player webpage for {initial_experience_id}')
  166. episode, season, show = self._get_episode(webpage, experience_id=int(initial_experience_id))
  167. episode_id = str(episode['episodePk'])
  168. display_id = episode.get('slug') or episode_id
  169. formats, subtitles, thumbnails, duration = [], {}, [], 0
  170. requested_languages, requested_versions = self._configuration_arg('language'), self._configuration_arg('version')
  171. language_preference = qualities((requested_languages or [''])[::-1])
  172. source_preference = qualities((requested_versions or ['uncut', 'simulcast'])[::-1])
  173. only_initial_experience = 'seperate-video-versions' in self.get_param('compat_opts', [])
  174. for lang, version, fmt in self._get_experiences(episode):
  175. experience_id = str(fmt['experienceId'])
  176. if (only_initial_experience and experience_id != initial_experience_id
  177. or requested_languages and lang.lower() not in requested_languages
  178. or requested_versions and version.lower() not in requested_versions):
  179. continue
  180. thumbnails.append({'url': fmt.get('poster')})
  181. duration = max(duration, fmt.get('duration', 0))
  182. format_name = f'{version} {lang} ({experience_id})'
  183. self.extract_subtitles(
  184. subtitles, experience_id, display_id=display_id, format_name=format_name,
  185. episode=episode if experience_id == initial_experience_id else episode_id)
  186. headers = {}
  187. if self._TOKEN:
  188. headers['Authorization'] = f'Token {self._TOKEN}'
  189. page = self._download_json(
  190. f'https://www.funimation.com/api/showexperience/{experience_id}/',
  191. display_id, headers=headers, expected_status=403, query={
  192. 'pinst_id': ''.join(random.choices(string.digits + string.ascii_letters, k=8)),
  193. }, note=f'Downloading {format_name} JSON')
  194. sources = page.get('items') or []
  195. if not sources:
  196. error = try_get(page, lambda x: x['errors'][0], dict)
  197. if error:
  198. self.report_warning('{} said: Error {} - {}'.format(
  199. self.IE_NAME, error.get('code'), error.get('detail') or error.get('title')))
  200. else:
  201. self.report_warning('No sources found for format')
  202. current_formats = []
  203. for source in sources:
  204. source_url = source.get('src')
  205. source_type = source.get('videoType') or determine_ext(source_url)
  206. if source_type == 'm3u8':
  207. current_formats.extend(self._extract_m3u8_formats(
  208. source_url, display_id, 'mp4', m3u8_id='{}-{}'.format(experience_id, 'hls'), fatal=False,
  209. note=f'Downloading {format_name} m3u8 information'))
  210. else:
  211. current_formats.append({
  212. 'format_id': f'{experience_id}-{source_type}',
  213. 'url': source_url,
  214. })
  215. for f in current_formats:
  216. # TODO: Convert language to code
  217. f.update({
  218. 'language': lang,
  219. 'format_note': version,
  220. 'source_preference': source_preference(version.lower()),
  221. 'language_preference': language_preference(lang.lower()),
  222. })
  223. formats.extend(current_formats)
  224. if not formats and (requested_languages or requested_versions):
  225. self.raise_no_formats(
  226. 'There are no video formats matching the requested languages/versions', expected=True, video_id=display_id)
  227. self._remove_duplicate_formats(formats)
  228. return {
  229. 'id': episode_id,
  230. '_old_archive_ids': [make_archive_id(self, initial_experience_id)],
  231. 'display_id': display_id,
  232. 'duration': duration,
  233. 'title': episode['episodeTitle'],
  234. 'description': episode.get('episodeSummary'),
  235. 'episode': episode.get('episodeTitle'),
  236. 'episode_number': int_or_none(episode.get('episodeId')),
  237. 'episode_id': episode_id,
  238. 'season': season.get('seasonTitle'),
  239. 'season_number': int_or_none(season.get('seasonId')),
  240. 'season_id': str_or_none(season.get('seasonPk')),
  241. 'series': show.get('showTitle'),
  242. 'formats': formats,
  243. 'thumbnails': thumbnails,
  244. 'subtitles': subtitles,
  245. '_format_sort_fields': ('lang', 'source'),
  246. }
  247. def _get_subtitles(self, subtitles, experience_id, episode, display_id, format_name):
  248. if isinstance(episode, str):
  249. webpage = self._download_webpage(
  250. f'https://www.funimation.com/player/{experience_id}/', display_id,
  251. fatal=False, note=f'Downloading player webpage for {format_name}')
  252. episode, _, _ = self._get_episode(webpage, episode_id=episode, fatal=False)
  253. for _, version, f in self._get_experiences(episode):
  254. for source in f.get('sources'):
  255. for text_track in source.get('textTracks'):
  256. if not text_track.get('src'):
  257. continue
  258. sub_type = text_track.get('type').upper()
  259. sub_type = sub_type if sub_type != 'FULL' else None
  260. current_sub = {
  261. 'url': text_track['src'],
  262. 'name': join_nonempty(version, text_track.get('label'), sub_type, delim=' '),
  263. }
  264. lang = join_nonempty(text_track.get('language', 'und'),
  265. version if version != 'Simulcast' else None,
  266. sub_type, delim='_')
  267. if current_sub not in subtitles.get(lang, []):
  268. subtitles.setdefault(lang, []).append(current_sub)
  269. return subtitles
  270. class FunimationShowIE(FunimationBaseIE):
  271. IE_NAME = 'funimation:show'
  272. _VALID_URL = r'(?P<url>https?://(?:www\.)?funimation(?:\.com|now\.uk)/(?P<locale>[^/]+)?/?shows/(?P<id>[^/?#&]+))/?(?:[?#]|$)'
  273. _TESTS = [{
  274. 'url': 'https://www.funimation.com/en/shows/sk8-the-infinity',
  275. 'info_dict': {
  276. 'id': '1315000',
  277. 'title': 'SK8 the Infinity',
  278. },
  279. 'playlist_count': 13,
  280. 'params': {
  281. 'skip_download': True,
  282. },
  283. }, {
  284. # without lang code
  285. 'url': 'https://www.funimation.com/shows/ouran-high-school-host-club/',
  286. 'info_dict': {
  287. 'id': '39643',
  288. 'title': 'Ouran High School Host Club',
  289. },
  290. 'playlist_count': 26,
  291. 'params': {
  292. 'skip_download': True,
  293. },
  294. }]
  295. def _real_initialize(self):
  296. if not self._REGION:
  297. FunimationBaseIE._REGION = self._get_region()
  298. def _real_extract(self, url):
  299. base_url, locale, display_id = self._match_valid_url(url).groups()
  300. show_info = self._download_json(
  301. 'https://title-api.prd.funimationsvc.com/v2/shows/{}?region={}&deviceType=web&locale={}'.format(
  302. display_id, self._REGION, locale or 'en'), display_id)
  303. items_info = self._download_json(
  304. 'https://prod-api-funimationnow.dadcdigital.com/api/funimation/episodes/?limit=99999&title_id={}'.format(
  305. show_info.get('id')), display_id)
  306. vod_items = traverse_obj(items_info, ('items', ..., lambda k, _: re.match(r'(?i)mostRecent[AS]vod', k), 'item'))
  307. return {
  308. '_type': 'playlist',
  309. 'id': str_or_none(show_info['id']),
  310. 'title': show_info['name'],
  311. 'entries': orderedSet(
  312. self.url_result(
  313. '{}/{}'.format(base_url, vod_item.get('episodeSlug')), FunimationPageIE.ie_key(),
  314. vod_item.get('episodeId'), vod_item.get('episodeName'))
  315. for vod_item in sorted(vod_items, key=lambda x: x.get('episodeOrder', -1))),
  316. }