crunchyroll.py 28 KB

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