crunchyroll.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import base64
  2. import uuid
  3. from .common import InfoExtractor
  4. from ..networking import Request
  5. from ..networking.exceptions import HTTPError
  6. from ..utils import (
  7. ExtractorError,
  8. float_or_none,
  9. format_field,
  10. int_or_none,
  11. jwt_decode_hs256,
  12. parse_age_limit,
  13. parse_count,
  14. parse_iso8601,
  15. qualities,
  16. time_seconds,
  17. traverse_obj,
  18. url_or_none,
  19. urlencode_postdata,
  20. )
  21. class CrunchyrollBaseIE(InfoExtractor):
  22. _BASE_URL = 'https://www.crunchyroll.com'
  23. _API_BASE = 'https://api.crunchyroll.com'
  24. _NETRC_MACHINE = 'crunchyroll'
  25. _SWITCH_USER_AGENT = 'Crunchyroll/1.8.0 Nintendo Switch/12.3.12.0 UE4/4.27'
  26. _REFRESH_TOKEN = None
  27. _AUTH_HEADERS = None
  28. _AUTH_EXPIRY = None
  29. _API_ENDPOINT = None
  30. _BASIC_AUTH = 'Basic ' + base64.b64encode(':'.join((
  31. 't-kdgp2h8c3jub8fn0fq',
  32. 'yfLDfMfrYvKXh4JXS1LEI2cCqu1v5Wan',
  33. )).encode()).decode()
  34. _IS_PREMIUM = None
  35. _LOCALE_LOOKUP = {
  36. 'ar': 'ar-SA',
  37. 'de': 'de-DE',
  38. '': 'en-US',
  39. 'es': 'es-419',
  40. 'es-es': 'es-ES',
  41. 'fr': 'fr-FR',
  42. 'it': 'it-IT',
  43. 'pt-br': 'pt-BR',
  44. 'pt-pt': 'pt-PT',
  45. 'ru': 'ru-RU',
  46. 'hi': 'hi-IN',
  47. }
  48. def _set_auth_info(self, response):
  49. CrunchyrollBaseIE._IS_PREMIUM = 'cr_premium' in traverse_obj(response, ('access_token', {jwt_decode_hs256}, 'benefits', ...))
  50. CrunchyrollBaseIE._AUTH_HEADERS = {'Authorization': response['token_type'] + ' ' + response['access_token']}
  51. CrunchyrollBaseIE._AUTH_EXPIRY = time_seconds(seconds=traverse_obj(response, ('expires_in', {float_or_none}), default=300) - 10)
  52. def _request_token(self, headers, data, note='Requesting token', errnote='Failed to request token'):
  53. try:
  54. return self._download_json(
  55. f'{self._BASE_URL}/auth/v1/token', None, note=note, errnote=errnote,
  56. headers=headers, data=urlencode_postdata(data), impersonate=True)
  57. except ExtractorError as error:
  58. if not isinstance(error.cause, HTTPError) or error.cause.status != 403:
  59. raise
  60. if target := error.cause.response.extensions.get('impersonate'):
  61. raise ExtractorError(f'Got HTTP Error 403 when using impersonate target "{target}"')
  62. raise ExtractorError(
  63. 'Request blocked by Cloudflare. '
  64. 'Install the required impersonation dependency if possible, '
  65. 'or else navigate to Crunchyroll in your browser, '
  66. 'then pass the fresh cookies (with --cookies-from-browser or --cookies) '
  67. 'and your browser\'s User-Agent (with --user-agent)', expected=True)
  68. def _perform_login(self, username, password):
  69. if not CrunchyrollBaseIE._REFRESH_TOKEN:
  70. CrunchyrollBaseIE._REFRESH_TOKEN = self.cache.load(self._NETRC_MACHINE, username)
  71. if CrunchyrollBaseIE._REFRESH_TOKEN:
  72. return
  73. try:
  74. login_response = self._request_token(
  75. headers={'Authorization': self._BASIC_AUTH}, data={
  76. 'username': username,
  77. 'password': password,
  78. 'grant_type': 'password',
  79. 'scope': 'offline_access',
  80. }, note='Logging in', errnote='Failed to log in')
  81. except ExtractorError as error:
  82. if isinstance(error.cause, HTTPError) and error.cause.status == 401:
  83. raise ExtractorError('Invalid username and/or password', expected=True)
  84. raise
  85. CrunchyrollBaseIE._REFRESH_TOKEN = login_response['refresh_token']
  86. self.cache.store(self._NETRC_MACHINE, username, CrunchyrollBaseIE._REFRESH_TOKEN)
  87. self._set_auth_info(login_response)
  88. def _update_auth(self):
  89. if CrunchyrollBaseIE._AUTH_HEADERS and CrunchyrollBaseIE._AUTH_EXPIRY > time_seconds():
  90. return
  91. auth_headers = {'Authorization': self._BASIC_AUTH}
  92. if CrunchyrollBaseIE._REFRESH_TOKEN:
  93. data = {
  94. 'refresh_token': CrunchyrollBaseIE._REFRESH_TOKEN,
  95. 'grant_type': 'refresh_token',
  96. 'scope': 'offline_access',
  97. }
  98. else:
  99. data = {'grant_type': 'client_id'}
  100. auth_headers['ETP-Anonymous-ID'] = uuid.uuid4()
  101. try:
  102. auth_response = self._request_token(auth_headers, data)
  103. except ExtractorError as error:
  104. username, password = self._get_login_info()
  105. if not username or not isinstance(error.cause, HTTPError) or error.cause.status != 400:
  106. raise
  107. self.to_screen('Refresh token has expired. Re-logging in')
  108. CrunchyrollBaseIE._REFRESH_TOKEN = None
  109. self.cache.store(self._NETRC_MACHINE, username, None)
  110. self._perform_login(username, password)
  111. return
  112. self._set_auth_info(auth_response)
  113. def _locale_from_language(self, language):
  114. config_locale = self._configuration_arg('metadata', ie_key=CrunchyrollBetaIE, casesense=True)
  115. return config_locale[0] if config_locale else self._LOCALE_LOOKUP.get(language)
  116. def _call_base_api(self, endpoint, internal_id, lang, note=None, query={}):
  117. self._update_auth()
  118. if not endpoint.startswith('/'):
  119. endpoint = f'/{endpoint}'
  120. query = query.copy()
  121. locale = self._locale_from_language(lang)
  122. if locale:
  123. query['locale'] = locale
  124. return self._download_json(
  125. f'{self._BASE_URL}{endpoint}', internal_id, note or f'Calling API: {endpoint}',
  126. headers=CrunchyrollBaseIE._AUTH_HEADERS, query=query)
  127. def _call_api(self, path, internal_id, lang, note='api', query={}):
  128. if not path.startswith(f'/content/v2/{self._API_ENDPOINT}/'):
  129. path = f'/content/v2/{self._API_ENDPOINT}/{path}'
  130. try:
  131. result = self._call_base_api(
  132. path, internal_id, lang, f'Downloading {note} JSON ({self._API_ENDPOINT})', query=query)
  133. except ExtractorError as error:
  134. if isinstance(error.cause, HTTPError) and error.cause.status == 404:
  135. return None
  136. raise
  137. if not result:
  138. raise ExtractorError(f'Unexpected response when downloading {note} JSON')
  139. return result
  140. def _extract_chapters(self, internal_id):
  141. # if no skip events are available, a 403 xml error is returned
  142. skip_events = self._download_json(
  143. f'https://static.crunchyroll.com/skip-events/production/{internal_id}.json',
  144. internal_id, note='Downloading chapter info', fatal=False, errnote=False)
  145. if not skip_events:
  146. return None
  147. chapters = []
  148. for event in ('recap', 'intro', 'credits', 'preview'):
  149. start = traverse_obj(skip_events, (event, 'start', {float_or_none}))
  150. end = traverse_obj(skip_events, (event, 'end', {float_or_none}))
  151. # some chapters have no start and/or ending time, they will just be ignored
  152. if start is None or end is None:
  153. continue
  154. chapters.append({'title': event.capitalize(), 'start_time': start, 'end_time': end})
  155. return chapters
  156. def _extract_stream(self, identifier, display_id=None):
  157. if not display_id:
  158. display_id = identifier
  159. self._update_auth()
  160. headers = {**CrunchyrollBaseIE._AUTH_HEADERS, 'User-Agent': self._SWITCH_USER_AGENT}
  161. try:
  162. stream_response = self._download_json(
  163. f'https://cr-play-service.prd.crunchyrollsvc.com/v1/{identifier}/console/switch/play',
  164. display_id, note='Downloading stream info', errnote='Failed to download stream info', headers=headers)
  165. except ExtractorError as error:
  166. if self.get_param('ignore_no_formats_error'):
  167. self.report_warning(error.orig_msg)
  168. return [], {}
  169. elif isinstance(error.cause, HTTPError) and error.cause.status == 420:
  170. raise ExtractorError(
  171. 'You have reached the rate-limit for active streams; try again later', expected=True)
  172. raise
  173. available_formats = {'': ('', '', stream_response['url'])}
  174. for hardsub_lang, stream in traverse_obj(stream_response, ('hardSubs', {dict.items}, lambda _, v: v[1]['url'])):
  175. available_formats[hardsub_lang] = (f'hardsub-{hardsub_lang}', hardsub_lang, stream['url'])
  176. requested_hardsubs = [('' if val == 'none' else val) for val in (self._configuration_arg('hardsub') or ['none'])]
  177. hardsub_langs = [lang for lang in available_formats if lang]
  178. if hardsub_langs and 'all' not in requested_hardsubs:
  179. full_format_langs = set(requested_hardsubs)
  180. self.to_screen(f'Available hardsub languages: {", ".join(hardsub_langs)}')
  181. self.to_screen(
  182. 'To extract formats of a hardsub language, use '
  183. '"--extractor-args crunchyrollbeta:hardsub=<language_code or all>". '
  184. 'See https://github.com/yt-dlp/yt-dlp#crunchyrollbeta-crunchyroll for more info',
  185. only_once=True)
  186. else:
  187. full_format_langs = set(map(str.lower, available_formats))
  188. audio_locale = traverse_obj(stream_response, ('audioLocale', {str}))
  189. hardsub_preference = qualities(requested_hardsubs[::-1])
  190. formats, subtitles = [], {}
  191. for format_id, hardsub_lang, stream_url in available_formats.values():
  192. if hardsub_lang.lower() in full_format_langs:
  193. adaptive_formats, dash_subs = self._extract_mpd_formats_and_subtitles(
  194. stream_url, display_id, mpd_id=format_id, headers=CrunchyrollBaseIE._AUTH_HEADERS,
  195. fatal=False, note=f'Downloading {f"{format_id} " if hardsub_lang else ""}MPD manifest')
  196. self._merge_subtitles(dash_subs, target=subtitles)
  197. else:
  198. continue # XXX: Update this if meta mpd formats work; will be tricky with token invalidation
  199. for f in adaptive_formats:
  200. if f.get('acodec') != 'none':
  201. f['language'] = audio_locale
  202. f['quality'] = hardsub_preference(hardsub_lang.lower())
  203. formats.extend(adaptive_formats)
  204. for locale, subtitle in traverse_obj(stream_response, (('subtitles', 'captions'), {dict.items}, ...)):
  205. subtitles.setdefault(locale, []).append(traverse_obj(subtitle, {'url': 'url', 'ext': 'format'}))
  206. # Invalidate stream token to avoid rate-limit
  207. error_msg = 'Unable to invalidate stream token; you may experience rate-limiting'
  208. if stream_token := stream_response.get('token'):
  209. self._request_webpage(Request(
  210. f'https://cr-play-service.prd.crunchyrollsvc.com/v1/token/{identifier}/{stream_token}/inactive',
  211. headers=headers, method='PATCH'), display_id, 'Invalidating stream token', error_msg, fatal=False)
  212. else:
  213. self.report_warning(error_msg)
  214. return formats, subtitles
  215. class CrunchyrollCmsBaseIE(CrunchyrollBaseIE):
  216. _API_ENDPOINT = 'cms'
  217. _CMS_EXPIRY = None
  218. def _call_cms_api_signed(self, path, internal_id, lang, note='api'):
  219. if not CrunchyrollCmsBaseIE._CMS_EXPIRY or CrunchyrollCmsBaseIE._CMS_EXPIRY <= time_seconds():
  220. response = self._call_base_api('index/v2', None, lang, 'Retrieving signed policy')['cms_web']
  221. CrunchyrollCmsBaseIE._CMS_QUERY = {
  222. 'Policy': response['policy'],
  223. 'Signature': response['signature'],
  224. 'Key-Pair-Id': response['key_pair_id'],
  225. }
  226. CrunchyrollCmsBaseIE._CMS_BUCKET = response['bucket']
  227. CrunchyrollCmsBaseIE._CMS_EXPIRY = parse_iso8601(response['expires']) - 10
  228. if not path.startswith('/cms/v2'):
  229. path = f'/cms/v2{CrunchyrollCmsBaseIE._CMS_BUCKET}/{path}'
  230. return self._call_base_api(
  231. path, internal_id, lang, f'Downloading {note} JSON (signed cms)', query=CrunchyrollCmsBaseIE._CMS_QUERY)
  232. class CrunchyrollBetaIE(CrunchyrollCmsBaseIE):
  233. IE_NAME = 'crunchyroll'
  234. _VALID_URL = r'''(?x)
  235. https?://(?:beta\.|www\.)?crunchyroll\.com/
  236. (?:(?P<lang>\w{2}(?:-\w{2})?)/)?
  237. watch/(?!concert|musicvideo)(?P<id>\w+)'''
  238. _TESTS = [{
  239. # Premium only
  240. 'url': 'https://www.crunchyroll.com/watch/GY2P1Q98Y/to-the-future',
  241. 'info_dict': {
  242. 'id': 'GY2P1Q98Y',
  243. 'ext': 'mp4',
  244. 'duration': 1380.241,
  245. 'timestamp': 1459632600,
  246. 'description': 'md5:a022fbec4fbb023d43631032c91ed64b',
  247. 'title': 'World Trigger Episode 73 – To the Future',
  248. 'upload_date': '20160402',
  249. 'series': 'World Trigger',
  250. 'series_id': 'GR757DMKY',
  251. 'season': 'World Trigger',
  252. 'season_id': 'GR9P39NJ6',
  253. 'season_number': 1,
  254. 'episode': 'To the Future',
  255. 'episode_number': 73,
  256. 'thumbnail': r're:^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  257. 'chapters': 'count:2',
  258. 'age_limit': 14,
  259. 'like_count': int,
  260. 'dislike_count': int,
  261. },
  262. 'params': {
  263. 'skip_download': 'm3u8',
  264. 'extractor_args': {'crunchyrollbeta': {'hardsub': ['de-DE']}},
  265. 'format': 'bv[format_id~=hardsub]',
  266. },
  267. }, {
  268. # Premium only
  269. 'url': 'https://www.crunchyroll.com/watch/GYE5WKQGR',
  270. 'info_dict': {
  271. 'id': 'GYE5WKQGR',
  272. 'ext': 'mp4',
  273. 'duration': 366.459,
  274. 'timestamp': 1476788400,
  275. 'description': 'md5:74b67283ffddd75f6e224ca7dc031e76',
  276. 'title': 'SHELTER – Porter Robinson presents Shelter the Animation',
  277. 'upload_date': '20161018',
  278. 'series': 'SHELTER',
  279. 'series_id': 'GYGG09WWY',
  280. 'season': 'SHELTER',
  281. 'season_id': 'GR09MGK4R',
  282. 'season_number': 1,
  283. 'episode': 'Porter Robinson presents Shelter the Animation',
  284. 'episode_number': 0,
  285. 'thumbnail': r're:^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  286. 'age_limit': 14,
  287. 'like_count': int,
  288. 'dislike_count': int,
  289. },
  290. 'params': {'skip_download': True},
  291. }, {
  292. 'url': 'https://www.crunchyroll.com/watch/GJWU2VKK3/cherry-blossom-meeting-and-a-coming-blizzard',
  293. 'info_dict': {
  294. 'id': 'GJWU2VKK3',
  295. 'ext': 'mp4',
  296. 'duration': 1420.054,
  297. 'description': 'md5:2d1c67c0ec6ae514d9c30b0b99a625cd',
  298. 'title': 'The Ice Guy and His Cool Female Colleague Episode 1 – Cherry Blossom Meeting and a Coming Blizzard',
  299. 'series': 'The Ice Guy and His Cool Female Colleague',
  300. 'series_id': 'GW4HM75NP',
  301. 'season': 'The Ice Guy and His Cool Female Colleague',
  302. 'season_id': 'GY9PC21VE',
  303. 'season_number': 1,
  304. 'episode': 'Cherry Blossom Meeting and a Coming Blizzard',
  305. 'episode_number': 1,
  306. 'chapters': 'count:2',
  307. 'thumbnail': r're:^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  308. 'timestamp': 1672839000,
  309. 'upload_date': '20230104',
  310. 'age_limit': 14,
  311. 'like_count': int,
  312. 'dislike_count': int,
  313. },
  314. 'params': {'skip_download': 'm3u8'},
  315. }, {
  316. 'url': 'https://www.crunchyroll.com/watch/GM8F313NQ',
  317. 'info_dict': {
  318. 'id': 'GM8F313NQ',
  319. 'ext': 'mp4',
  320. 'title': 'Garakowa -Restore the World-',
  321. 'description': 'md5:8d2f8b6b9dd77d87810882e7d2ee5608',
  322. 'duration': 3996.104,
  323. 'age_limit': 13,
  324. 'thumbnail': r're:^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  325. },
  326. 'params': {'skip_download': 'm3u8'},
  327. 'skip': 'no longer exists',
  328. }, {
  329. 'url': 'https://www.crunchyroll.com/watch/G62PEZ2E6',
  330. 'info_dict': {
  331. 'id': 'G62PEZ2E6',
  332. 'description': 'md5:8d2f8b6b9dd77d87810882e7d2ee5608',
  333. 'age_limit': 13,
  334. 'duration': 65.138,
  335. 'title': 'Garakowa -Restore the World-',
  336. },
  337. 'playlist_mincount': 5,
  338. }, {
  339. 'url': 'https://www.crunchyroll.com/de/watch/GY2P1Q98Y',
  340. 'only_matching': True,
  341. }, {
  342. 'url': 'https://beta.crunchyroll.com/pt-br/watch/G8WUN8VKP/the-ruler-of-conspiracy',
  343. 'only_matching': True,
  344. }]
  345. # We want to support lazy playlist filtering and movie listings cannot be inside a playlist
  346. _RETURN_TYPE = 'video'
  347. def _real_extract(self, url):
  348. lang, internal_id = self._match_valid_url(url).group('lang', 'id')
  349. # We need to use unsigned API call to allow ratings query string
  350. response = traverse_obj(self._call_api(
  351. f'objects/{internal_id}', internal_id, lang, 'object info', {'ratings': 'true'}), ('data', 0, {dict}))
  352. if not response:
  353. raise ExtractorError(f'No video with id {internal_id} could be found (possibly region locked?)', expected=True)
  354. object_type = response.get('type')
  355. if object_type == 'episode':
  356. result = self._transform_episode_response(response)
  357. elif object_type == 'movie':
  358. result = self._transform_movie_response(response)
  359. elif object_type == 'movie_listing':
  360. first_movie_id = traverse_obj(response, ('movie_listing_metadata', 'first_movie_id'))
  361. if not self._yes_playlist(internal_id, first_movie_id):
  362. return self.url_result(f'{self._BASE_URL}/{lang}watch/{first_movie_id}', CrunchyrollBetaIE, first_movie_id)
  363. def entries():
  364. movies = self._call_api(f'movie_listings/{internal_id}/movies', internal_id, lang, 'movie list')
  365. for movie_response in traverse_obj(movies, ('data', ...)):
  366. yield self.url_result(
  367. f'{self._BASE_URL}/{lang}watch/{movie_response["id"]}',
  368. CrunchyrollBetaIE, **self._transform_movie_response(movie_response))
  369. return self.playlist_result(entries(), **self._transform_movie_response(response))
  370. else:
  371. raise ExtractorError(f'Unknown object type {object_type}')
  372. if not self._IS_PREMIUM and traverse_obj(response, (f'{object_type}_metadata', 'is_premium_only')):
  373. message = f'This {object_type} is for premium members only'
  374. if CrunchyrollBaseIE._REFRESH_TOKEN:
  375. self.raise_no_formats(message, expected=True, video_id=internal_id)
  376. else:
  377. self.raise_login_required(message, method='password', metadata_available=True)
  378. else:
  379. result['formats'], result['subtitles'] = self._extract_stream(internal_id)
  380. result['chapters'] = self._extract_chapters(internal_id)
  381. def calculate_count(item):
  382. return parse_count(''.join((item['displayed'], item.get('unit') or '')))
  383. result.update(traverse_obj(response, ('rating', {
  384. 'like_count': ('up', {calculate_count}),
  385. 'dislike_count': ('down', {calculate_count}),
  386. })))
  387. return result
  388. @staticmethod
  389. def _transform_episode_response(data):
  390. metadata = traverse_obj(data, (('episode_metadata', None), {dict}), get_all=False) or {}
  391. return {
  392. 'id': data['id'],
  393. 'title': ' \u2013 '.join((
  394. ('{}{}'.format(
  395. format_field(metadata, 'season_title'),
  396. format_field(metadata, 'episode', ' Episode %s'))),
  397. format_field(data, 'title'))),
  398. **traverse_obj(data, {
  399. 'episode': ('title', {str}),
  400. 'description': ('description', {str}, {lambda x: x.replace(r'\r\n', '\n')}),
  401. 'thumbnails': ('images', 'thumbnail', ..., ..., {
  402. 'url': ('source', {url_or_none}),
  403. 'width': ('width', {int_or_none}),
  404. 'height': ('height', {int_or_none}),
  405. }),
  406. }),
  407. **traverse_obj(metadata, {
  408. 'duration': ('duration_ms', {lambda x: float_or_none(x, 1000)}),
  409. 'timestamp': ('upload_date', {parse_iso8601}),
  410. 'series': ('series_title', {str}),
  411. 'series_id': ('series_id', {str}),
  412. 'season': ('season_title', {str}),
  413. 'season_id': ('season_id', {str}),
  414. 'season_number': ('season_number', ({int}, {float_or_none})),
  415. 'episode_number': ('sequence_number', ({int}, {float_or_none})),
  416. 'age_limit': ('maturity_ratings', -1, {parse_age_limit}),
  417. 'language': ('audio_locale', {str}),
  418. }, get_all=False),
  419. }
  420. @staticmethod
  421. def _transform_movie_response(data):
  422. metadata = traverse_obj(data, (('movie_metadata', 'movie_listing_metadata', None), {dict}), get_all=False) or {}
  423. return {
  424. 'id': data['id'],
  425. **traverse_obj(data, {
  426. 'title': ('title', {str}),
  427. 'description': ('description', {str}, {lambda x: x.replace(r'\r\n', '\n')}),
  428. 'thumbnails': ('images', 'thumbnail', ..., ..., {
  429. 'url': ('source', {url_or_none}),
  430. 'width': ('width', {int_or_none}),
  431. 'height': ('height', {int_or_none}),
  432. }),
  433. }),
  434. **traverse_obj(metadata, {
  435. 'duration': ('duration_ms', {lambda x: float_or_none(x, 1000)}),
  436. 'age_limit': ('maturity_ratings', -1, {parse_age_limit}),
  437. }),
  438. }
  439. class CrunchyrollBetaShowIE(CrunchyrollCmsBaseIE):
  440. IE_NAME = 'crunchyroll:playlist'
  441. _VALID_URL = r'''(?x)
  442. https?://(?:beta\.|www\.)?crunchyroll\.com/
  443. (?P<lang>(?:\w{2}(?:-\w{2})?/)?)
  444. series/(?P<id>\w+)'''
  445. _TESTS = [{
  446. 'url': 'https://www.crunchyroll.com/series/GY19NQ2QR/Girl-Friend-BETA',
  447. 'info_dict': {
  448. 'id': 'GY19NQ2QR',
  449. 'title': 'Girl Friend BETA',
  450. 'description': 'md5:99c1b22ee30a74b536a8277ced8eb750',
  451. # XXX: `thumbnail` does not get set from `thumbnails` in playlist
  452. # 'thumbnail': r're:^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  453. 'age_limit': 14,
  454. },
  455. 'playlist_mincount': 10,
  456. }, {
  457. 'url': 'https://beta.crunchyroll.com/it/series/GY19NQ2QR',
  458. 'only_matching': True,
  459. }]
  460. def _real_extract(self, url):
  461. lang, internal_id = self._match_valid_url(url).group('lang', 'id')
  462. def entries():
  463. seasons_response = self._call_cms_api_signed(f'seasons?series_id={internal_id}', internal_id, lang, 'seasons')
  464. for season in traverse_obj(seasons_response, ('items', ..., {dict})):
  465. episodes_response = self._call_cms_api_signed(
  466. f'episodes?season_id={season["id"]}', season['id'], lang, 'episode list')
  467. for episode_response in traverse_obj(episodes_response, ('items', ..., {dict})):
  468. yield self.url_result(
  469. f'{self._BASE_URL}/{lang}watch/{episode_response["id"]}',
  470. CrunchyrollBetaIE, **CrunchyrollBetaIE._transform_episode_response(episode_response))
  471. return self.playlist_result(
  472. entries(), internal_id,
  473. **traverse_obj(self._call_api(f'series/{internal_id}', internal_id, lang, 'series'), ('data', 0, {
  474. 'title': ('title', {str}),
  475. 'description': ('description', {lambda x: x.replace(r'\r\n', '\n')}),
  476. 'age_limit': ('maturity_ratings', -1, {parse_age_limit}),
  477. 'thumbnails': ('images', ..., ..., ..., {
  478. 'url': ('source', {url_or_none}),
  479. 'width': ('width', {int_or_none}),
  480. 'height': ('height', {int_or_none}),
  481. }),
  482. })))
  483. class CrunchyrollMusicIE(CrunchyrollBaseIE):
  484. IE_NAME = 'crunchyroll:music'
  485. _VALID_URL = r'''(?x)
  486. https?://(?:www\.)?crunchyroll\.com/
  487. (?P<lang>(?:\w{2}(?:-\w{2})?/)?)
  488. watch/(?P<type>concert|musicvideo)/(?P<id>\w+)'''
  489. _TESTS = [{
  490. 'url': 'https://www.crunchyroll.com/de/watch/musicvideo/MV5B02C79',
  491. 'info_dict': {
  492. 'ext': 'mp4',
  493. 'id': 'MV5B02C79',
  494. 'display_id': 'egaono-hana',
  495. 'title': 'Egaono Hana',
  496. 'track': 'Egaono Hana',
  497. 'artists': ['Goose house'],
  498. 'thumbnail': r're:(?i)^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  499. 'genres': ['J-Pop'],
  500. },
  501. 'params': {'skip_download': 'm3u8'},
  502. }, {
  503. 'url': 'https://www.crunchyroll.com/watch/musicvideo/MV88BB7F2C',
  504. 'info_dict': {
  505. 'ext': 'mp4',
  506. 'id': 'MV88BB7F2C',
  507. 'display_id': 'crossing-field',
  508. 'title': 'Crossing Field',
  509. 'track': 'Crossing Field',
  510. 'artists': ['LiSA'],
  511. 'thumbnail': r're:(?i)^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  512. 'genres': ['Anime'],
  513. },
  514. 'params': {'skip_download': 'm3u8'},
  515. 'skip': 'no longer exists',
  516. }, {
  517. 'url': 'https://www.crunchyroll.com/watch/concert/MC2E2AC135',
  518. 'info_dict': {
  519. 'ext': 'mp4',
  520. 'id': 'MC2E2AC135',
  521. 'display_id': 'live-is-smile-always-364joker-at-yokohama-arena',
  522. 'title': 'LiVE is Smile Always-364+JOKER- at YOKOHAMA ARENA',
  523. 'track': 'LiVE is Smile Always-364+JOKER- at YOKOHAMA ARENA',
  524. 'artists': ['LiSA'],
  525. 'thumbnail': r're:(?i)^https://www.crunchyroll.com/imgsrv/.*\.jpeg?$',
  526. 'description': 'md5:747444e7e6300907b7a43f0a0503072e',
  527. 'genres': ['J-Pop'],
  528. },
  529. 'params': {'skip_download': 'm3u8'},
  530. }, {
  531. 'url': 'https://www.crunchyroll.com/de/watch/musicvideo/MV5B02C79/egaono-hana',
  532. 'only_matching': True,
  533. }, {
  534. 'url': 'https://www.crunchyroll.com/watch/concert/MC2E2AC135/live-is-smile-always-364joker-at-yokohama-arena',
  535. 'only_matching': True,
  536. }, {
  537. 'url': 'https://www.crunchyroll.com/watch/musicvideo/MV88BB7F2C/crossing-field',
  538. 'only_matching': True,
  539. }]
  540. _API_ENDPOINT = 'music'
  541. def _real_extract(self, url):
  542. lang, internal_id, object_type = self._match_valid_url(url).group('lang', 'id', 'type')
  543. path, name = {
  544. 'concert': ('concerts', 'concert info'),
  545. 'musicvideo': ('music_videos', 'music video info'),
  546. }[object_type]
  547. response = traverse_obj(self._call_api(f'{path}/{internal_id}', internal_id, lang, name), ('data', 0, {dict}))
  548. if not response:
  549. raise ExtractorError(f'No video with id {internal_id} could be found (possibly region locked?)', expected=True)
  550. result = self._transform_music_response(response)
  551. if not self._IS_PREMIUM and response.get('isPremiumOnly'):
  552. message = f'This {response.get("type") or "media"} is for premium members only'
  553. if CrunchyrollBaseIE._REFRESH_TOKEN:
  554. self.raise_no_formats(message, expected=True, video_id=internal_id)
  555. else:
  556. self.raise_login_required(message, method='password', metadata_available=True)
  557. else:
  558. result['formats'], _ = self._extract_stream(f'music/{internal_id}', internal_id)
  559. return result
  560. @staticmethod
  561. def _transform_music_response(data):
  562. return {
  563. 'id': data['id'],
  564. **traverse_obj(data, {
  565. 'display_id': 'slug',
  566. 'title': 'title',
  567. 'track': 'title',
  568. 'artists': ('artist', 'name', all),
  569. 'description': ('description', {str}, {lambda x: x.replace(r'\r\n', '\n') or None}),
  570. 'thumbnails': ('images', ..., ..., {
  571. 'url': ('source', {url_or_none}),
  572. 'width': ('width', {int_or_none}),
  573. 'height': ('height', {int_or_none}),
  574. }),
  575. 'genres': ('genres', ..., 'displayValue'),
  576. 'age_limit': ('maturity_ratings', -1, {parse_age_limit}),
  577. }),
  578. }
  579. class CrunchyrollArtistIE(CrunchyrollBaseIE):
  580. IE_NAME = 'crunchyroll:artist'
  581. _VALID_URL = r'''(?x)
  582. https?://(?:www\.)?crunchyroll\.com/
  583. (?P<lang>(?:\w{2}(?:-\w{2})?/)?)
  584. artist/(?P<id>\w{10})'''
  585. _TESTS = [{
  586. 'url': 'https://www.crunchyroll.com/artist/MA179CB50D',
  587. 'info_dict': {
  588. 'id': 'MA179CB50D',
  589. 'title': 'LiSA',
  590. 'genres': ['Anime', 'J-Pop', 'Rock'],
  591. 'description': 'md5:16d87de61a55c3f7d6c454b73285938e',
  592. },
  593. 'playlist_mincount': 83,
  594. }, {
  595. 'url': 'https://www.crunchyroll.com/artist/MA179CB50D/lisa',
  596. 'only_matching': True,
  597. }]
  598. _API_ENDPOINT = 'music'
  599. def _real_extract(self, url):
  600. lang, internal_id = self._match_valid_url(url).group('lang', 'id')
  601. response = traverse_obj(self._call_api(
  602. f'artists/{internal_id}', internal_id, lang, 'artist info'), ('data', 0))
  603. def entries():
  604. for attribute, path in [('concerts', 'concert'), ('videos', 'musicvideo')]:
  605. for internal_id in traverse_obj(response, (attribute, ...)):
  606. yield self.url_result(f'{self._BASE_URL}/watch/{path}/{internal_id}', CrunchyrollMusicIE, internal_id)
  607. return self.playlist_result(entries(), **self._transform_artist_response(response))
  608. @staticmethod
  609. def _transform_artist_response(data):
  610. return {
  611. 'id': data['id'],
  612. **traverse_obj(data, {
  613. 'title': 'name',
  614. 'description': ('description', {str}, {lambda x: x.replace(r'\r\n', '\n')}),
  615. 'thumbnails': ('images', ..., ..., {
  616. 'url': ('source', {url_or_none}),
  617. 'width': ('width', {int_or_none}),
  618. 'height': ('height', {int_or_none}),
  619. }),
  620. 'genres': ('genres', ..., 'displayValue'),
  621. }),
  622. }