]>
Commit | Line | Data |
---|---|---|
706dfe44 | 1 | import base64 |
1d430674 | 2 | import json |
ac668111 | 3 | import re |
4 | import urllib.request | |
f9934b96 | 5 | import xml.etree.ElementTree |
ac668111 | 6 | import zlib |
c8434e83 | 7 | from hashlib import sha1 |
ac668111 | 8 | from math import floor, pow, sqrt |
9 | ||
46279958 | 10 | from .common import InfoExtractor |
11078c6d | 11 | from .vrv import VRVBaseIE |
ac668111 | 12 | from ..aes import aes_cbc_decrypt |
1cc79574 | 13 | from ..compat import ( |
cf282071 | 14 | compat_b64decode, |
36e6f62c | 15 | compat_etree_fromstring, |
6ffc3cf7 | 16 | compat_str, |
15707c7e | 17 | compat_urllib_parse_urlencode, |
a01da8bb | 18 | compat_urlparse, |
1cc79574 PH |
19 | ) |
20 | from ..utils import ( | |
21 | ExtractorError, | |
c8434e83 | 22 | bytes_to_intlist, |
54a5be4d RA |
23 | extract_attributes, |
24 | float_or_none, | |
706dfe44 | 25 | format_field, |
725d1c58 | 26 | int_or_none, |
ac668111 | 27 | intlist_to_bytes, |
706dfe44 | 28 | join_nonempty, |
6d02b9a3 | 29 | lowercase_escape, |
6ffc3cf7 | 30 | merge_dicts, |
b99ba3df | 31 | parse_iso8601, |
a9d4da60 | 32 | qualities, |
a01da8bb | 33 | remove_end, |
5c2266df | 34 | sanitized_Request, |
706dfe44 | 35 | traverse_obj, |
245d43ca | 36 | try_get, |
725d1c58 | 37 | xpath_text, |
c8434e83 | 38 | ) |
c8434e83 | 39 | |
34440095 | 40 | |
46279958 | 41 | class CrunchyrollBaseIE(InfoExtractor): |
7c74a015 JH |
42 | _LOGIN_URL = 'https://www.crunchyroll.com/welcome/login' |
43 | _API_BASE = 'https://api.crunchyroll.com' | |
80f48920 S |
44 | _NETRC_MACHINE = 'crunchyroll' |
45 | ||
05dee6c5 RA |
46 | def _call_rpc_api(self, method, video_id, note=None, data=None): |
47 | data = data or {} | |
48 | data['req'] = 'RpcApi' + method | |
49 | data = compat_urllib_parse_urlencode(data).encode('utf-8') | |
50 | return self._download_xml( | |
d98cb62e | 51 | 'https://www.crunchyroll.com/xml/', |
05dee6c5 RA |
52 | video_id, note, fatal=False, data=data, headers={ |
53 | 'Content-Type': 'application/x-www-form-urlencoded', | |
54 | }) | |
55 | ||
52efa4b3 | 56 | def _perform_login(self, username, password): |
7c74a015 | 57 | if self._get_cookies(self._LOGIN_URL).get('etp_rt'): |
eb5b1fc0 S |
58 | return |
59 | ||
7c74a015 JH |
60 | upsell_response = self._download_json( |
61 | f'{self._API_BASE}/get_upsell_data.0.json', None, 'Getting session id', | |
62 | query={ | |
63 | 'sess_id': 1, | |
64 | 'device_id': 'whatvalueshouldbeforweb', | |
65 | 'device_type': 'com.crunchyroll.static', | |
66 | 'access_token': 'giKq5eY27ny3cqz', | |
67 | 'referer': self._LOGIN_URL | |
68 | }) | |
69 | if upsell_response['code'] != 'ok': | |
70 | raise ExtractorError('Could not get session id') | |
71 | session_id = upsell_response['data']['session_id'] | |
72 | ||
73 | login_response = self._download_json( | |
74 | f'{self._API_BASE}/login.1.json', None, 'Logging in', | |
75 | data=compat_urllib_parse_urlencode({ | |
76 | 'account': username, | |
77 | 'password': password, | |
78 | 'session_id': session_id | |
79 | }).encode('ascii')) | |
80 | if login_response['code'] != 'ok': | |
97bef011 | 81 | raise ExtractorError('Login failed. Server message: %s' % login_response['message'], expected=True) |
7c74a015 JH |
82 | if not self._get_cookies(self._LOGIN_URL).get('etp_rt'): |
83 | raise ExtractorError('Login succeeded but did not set etp_rt cookie') | |
80f48920 | 84 | |
f4d706a9 JH |
85 | # Beta-specific, but needed for redirects |
86 | def _get_beta_embedded_json(self, webpage, display_id): | |
87 | initial_state = self._parse_json(self._search_regex( | |
88 | r'__INITIAL_STATE__\s*=\s*({.+?})\s*;', webpage, 'initial state'), display_id) | |
89 | app_config = self._parse_json(self._search_regex( | |
90 | r'__APP_CONFIG__\s*=\s*({.+?})\s*;', webpage, 'app config'), display_id) | |
91 | return initial_state, app_config | |
92 | ||
93 | def _redirect_to_beta(self, webpage, iekey, video_id): | |
94 | if not self._get_cookies(self._LOGIN_URL).get('etp_rt'): | |
95 | raise ExtractorError('Received a beta page from non-beta url when not logged in.') | |
96 | initial_state, app_config = self._get_beta_embedded_json(webpage, video_id) | |
97 | url = app_config['baseSiteUrl'] + initial_state['router']['locations']['current']['pathname'] | |
98 | self.to_screen(f'{video_id}: Redirected to beta site - {url}') | |
99 | return self.url_result(f'{url}', iekey, video_id) | |
100 | ||
80f48920 S |
101 | @staticmethod |
102 | def _add_skip_wall(url): | |
103 | parsed_url = compat_urlparse.urlparse(url) | |
104 | qs = compat_urlparse.parse_qs(parsed_url.query) | |
105 | # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message: | |
106 | # > This content may be inappropriate for some people. | |
107 | # > Are you sure you want to continue? | |
108 | # since it's not disabled by default in crunchyroll account's settings. | |
067aa17e | 109 | # See https://github.com/ytdl-org/youtube-dl/issues/7202. |
80f48920 S |
110 | qs['skip_wall'] = ['1'] |
111 | return compat_urlparse.urlunparse( | |
15707c7e | 112 | parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True))) |
80f48920 | 113 | |
12810c9c | 114 | |
11078c6d | 115 | class CrunchyrollIE(CrunchyrollBaseIE, VRVBaseIE): |
46279958 | 116 | IE_NAME = 'crunchyroll' |
56b5b832 | 117 | _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|(?!series/|watch/)(?:[^/]+/){1,2}[^/?&]*?)(?P<id>[0-9]+))(?:[/?&]|$)' |
a8896c5a | 118 | _TESTS = [{ |
38a40276 | 119 | 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513', |
38a40276 | 120 | 'info_dict': { |
34440095 | 121 | 'id': '645513', |
b5869560 | 122 | 'ext': 'mp4', |
38a40276 | 123 | 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!', |
124 | 'description': 'md5:2d17137920c64f2f49981a7797d275ef', | |
54a5be4d | 125 | 'thumbnail': r're:^https?://.*\.jpg$', |
38a40276 | 126 | 'uploader': 'Yomiuri Telecasting Corporation (YTV)', |
127 | 'upload_date': '20131013', | |
b1edd7a4 | 128 | 'url': 're:(?!.*&)', |
c8434e83 | 129 | }, |
38a40276 | 130 | 'params': { |
c8434e83 | 131 | # rtmp |
38a40276 | 132 | 'skip_download': True, |
c8434e83 | 133 | }, |
6ffc3cf7 | 134 | 'skip': 'Video gone', |
ede21449 S |
135 | }, { |
136 | 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1', | |
137 | 'info_dict': { | |
138 | 'id': '589804', | |
139 | 'ext': 'flv', | |
140 | 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11', | |
6d02b9a3 | 141 | 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12', |
ec85ded8 | 142 | 'thumbnail': r're:^https?://.*\.jpg$', |
ede21449 S |
143 | 'uploader': 'Danny Choo Network', |
144 | 'upload_date': '20120213', | |
145 | }, | |
146 | 'params': { | |
147 | # rtmp | |
148 | 'skip_download': True, | |
149 | }, | |
77c5b98d | 150 | 'skip': 'Video gone', |
990d533e S |
151 | }, { |
152 | 'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409', | |
153 | 'info_dict': { | |
154 | 'id': '702409', | |
155 | 'ext': 'mp4', | |
6ffc3cf7 S |
156 | 'title': compat_str, |
157 | 'description': compat_str, | |
ec85ded8 | 158 | 'thumbnail': r're:^https?://.*\.jpg$', |
6ffc3cf7 S |
159 | 'uploader': 'Re:Zero Partners', |
160 | 'timestamp': 1462098900, | |
161 | 'upload_date': '20160501', | |
990d533e S |
162 | }, |
163 | 'params': { | |
164 | # m3u8 download | |
165 | 'skip_download': True, | |
166 | }, | |
e0b6e50c S |
167 | }, { |
168 | 'url': 'http://www.crunchyroll.com/konosuba-gods-blessing-on-this-wonderful-world/episode-1-give-me-deliverance-from-this-judicial-injustice-727589', | |
169 | 'info_dict': { | |
170 | 'id': '727589', | |
171 | 'ext': 'mp4', | |
6ffc3cf7 S |
172 | 'title': compat_str, |
173 | 'description': compat_str, | |
e0b6e50c S |
174 | 'thumbnail': r're:^https?://.*\.jpg$', |
175 | 'uploader': 'Kadokawa Pictures Inc.', | |
6ffc3cf7 S |
176 | 'timestamp': 1484130900, |
177 | 'upload_date': '20170111', | |
178 | 'series': compat_str, | |
8c996232 | 179 | 'season': "KONOSUBA -God's blessing on this wonderful world! 2", |
e0b6e50c | 180 | 'season_number': 2, |
b9f9f361 | 181 | 'episode': 'Give Me Deliverance From This Judicial Injustice!', |
e0b6e50c S |
182 | 'episode_number': 1, |
183 | }, | |
184 | 'params': { | |
185 | # m3u8 download | |
186 | 'skip_download': True, | |
187 | }, | |
a8896c5a S |
188 | }, { |
189 | 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697', | |
190 | 'only_matching': True, | |
49941c4e S |
191 | }, { |
192 | # geo-restricted (US), 18+ maturity wall, non-premium available | |
193 | 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617', | |
194 | 'only_matching': True, | |
b5869560 YCH |
195 | }, { |
196 | # A description with double quotes | |
197 | 'url': 'http://www.crunchyroll.com/11eyes/episode-1-piros-jszaka-red-night-535080', | |
198 | 'info_dict': { | |
199 | 'id': '535080', | |
200 | 'ext': 'mp4', | |
6ffc3cf7 S |
201 | 'title': compat_str, |
202 | 'description': compat_str, | |
b5869560 | 203 | 'uploader': 'Marvelous AQL Inc.', |
6ffc3cf7 S |
204 | 'timestamp': 1255512600, |
205 | 'upload_date': '20091014', | |
b5869560 YCH |
206 | }, |
207 | 'params': { | |
208 | # Just test metadata extraction | |
209 | 'skip_download': True, | |
210 | }, | |
7fd46552 | 211 | }, { |
212 | # make sure we can extract an uploader name that's not a link | |
213 | 'url': 'http://www.crunchyroll.com/hakuoki-reimeiroku/episode-1-dawn-of-the-divine-warriors-606899', | |
214 | 'info_dict': { | |
215 | 'id': '606899', | |
216 | 'ext': 'mp4', | |
217 | 'title': 'Hakuoki Reimeiroku Episode 1 – Dawn of the Divine Warriors', | |
218 | 'description': 'Ryunosuke was left to die, but Serizawa-san asked him a simple question "Do you want to live?"', | |
219 | 'uploader': 'Geneon Entertainment', | |
220 | 'upload_date': '20120717', | |
221 | }, | |
222 | 'params': { | |
223 | # just test metadata extraction | |
224 | 'skip_download': True, | |
225 | }, | |
6ffc3cf7 | 226 | 'skip': 'Video gone', |
8c996232 S |
227 | }, { |
228 | # A video with a vastly different season name compared to the series name | |
229 | 'url': 'http://www.crunchyroll.com/nyarko-san-another-crawling-chaos/episode-1-test-590532', | |
230 | 'info_dict': { | |
231 | 'id': '590532', | |
232 | 'ext': 'mp4', | |
6ffc3cf7 S |
233 | 'title': compat_str, |
234 | 'description': compat_str, | |
8c996232 | 235 | 'uploader': 'TV TOKYO', |
6ffc3cf7 | 236 | 'timestamp': 1330956000, |
8c996232 S |
237 | 'upload_date': '20120305', |
238 | 'series': 'Nyarko-san: Another Crawling Chaos', | |
239 | 'season': 'Haiyoru! Nyaruani (ONA)', | |
240 | }, | |
241 | 'params': { | |
242 | # Just test metadata extraction | |
243 | 'skip_download': True, | |
244 | }, | |
b2286f8f | 245 | }, { |
246 | 'url': 'http://www.crunchyroll.com/media-723735', | |
247 | 'only_matching': True, | |
6510a3aa S |
248 | }, { |
249 | 'url': 'https://www.crunchyroll.com/en-gb/mob-psycho-100/episode-2-urban-legends-encountering-rumors-780921', | |
250 | 'only_matching': True, | |
a8896c5a | 251 | }] |
c8434e83 | 252 | |
253 | _FORMAT_IDS = { | |
38a40276 | 254 | '360': ('60', '106'), |
255 | '480': ('61', '106'), | |
256 | '720': ('62', '106'), | |
257 | '1080': ('80', '108'), | |
c8434e83 | 258 | } |
259 | ||
d415957d | 260 | def _download_webpage(self, url_or_request, *args, **kwargs): |
ac668111 | 261 | request = (url_or_request if isinstance(url_or_request, urllib.request.Request) |
d415957d S |
262 | else sanitized_Request(url_or_request)) |
263 | # Accept-Language must be set explicitly to accept any language to avoid issues | |
264 | # similar to https://github.com/ytdl-org/youtube-dl/issues/6797. | |
265 | # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction | |
266 | # should be imposed or not (from what I can see it just takes the first language | |
267 | # ignoring the priority and requires it to correspond the IP). By the way this causes | |
268 | # Crunchyroll to not work in georestriction cases in some browsers that don't place | |
269 | # the locale lang first in header. However allowing any language seems to workaround the issue. | |
270 | request.add_header('Accept-Language', '*') | |
271 | return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs) | |
272 | ||
c8434e83 | 273 | def _decrypt_subtitles(self, data, iv, id): |
cf282071 S |
274 | data = bytes_to_intlist(compat_b64decode(data)) |
275 | iv = bytes_to_intlist(compat_b64decode(iv)) | |
c8434e83 | 276 | id = int(id) |
277 | ||
278 | def obfuscate_key_aux(count, modulo, start): | |
279 | output = list(start) | |
280 | for _ in range(count): | |
281 | output.append(output[-1] + output[-2]) | |
282 | # cut off start values | |
283 | output = output[2:] | |
284 | output = list(map(lambda x: x % modulo + 33, output)) | |
285 | return output | |
286 | ||
287 | def obfuscate_key(key): | |
288 | num1 = int(floor(pow(2, 25) * sqrt(6.9))) | |
289 | num2 = (num1 ^ key) << 5 | |
290 | num3 = key ^ num1 | |
291 | num4 = num3 ^ (num3 >> 3) ^ num2 | |
292 | prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2))) | |
38a40276 | 293 | shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest()) |
c8434e83 | 294 | # Extend 160 Bit hash to 256 Bit |
295 | return shaHash + [0] * 12 | |
34440095 | 296 | |
c8434e83 | 297 | key = obfuscate_key(id) |
5f6a1245 | 298 | |
c8434e83 | 299 | decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv)) |
300 | return zlib.decompress(decrypted_data) | |
301 | ||
d65d6286 | 302 | def _convert_subtitles_to_srt(self, sub_root): |
38a40276 | 303 | output = '' |
d65d6286 JMF |
304 | |
305 | for i, event in enumerate(sub_root.findall('./events/event'), 1): | |
306 | start = event.attrib['start'].replace('.', ',') | |
307 | end = event.attrib['end'].replace('.', ',') | |
308 | text = event.attrib['text'].replace('\\N', '\n') | |
38a40276 | 309 | output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text) |
c8434e83 | 310 | return output |
311 | ||
d65d6286 | 312 | def _convert_subtitles_to_ass(self, sub_root): |
78272a07 A |
313 | output = '' |
314 | ||
315 | def ass_bool(strvalue): | |
316 | assvalue = '0' | |
317 | if strvalue == '1': | |
318 | assvalue = '-1' | |
319 | return assvalue | |
320 | ||
78272a07 | 321 | output = '[Script Info]\n' |
611c1dd9 | 322 | output += 'Title: %s\n' % sub_root.attrib['title'] |
78272a07 | 323 | output += 'ScriptType: v4.00+\n' |
611c1dd9 S |
324 | output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style'] |
325 | output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x'] | |
326 | output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y'] | |
2b2d5d31 | 327 | output += """ |
78272a07 A |
328 | [V4+ Styles] |
329 | Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding | |
330 | """ | |
331 | for style in sub_root.findall('./styles/style'): | |
611c1dd9 S |
332 | output += 'Style: ' + style.attrib['name'] |
333 | output += ',' + style.attrib['font_name'] | |
334 | output += ',' + style.attrib['font_size'] | |
335 | output += ',' + style.attrib['primary_colour'] | |
336 | output += ',' + style.attrib['secondary_colour'] | |
337 | output += ',' + style.attrib['outline_colour'] | |
338 | output += ',' + style.attrib['back_colour'] | |
339 | output += ',' + ass_bool(style.attrib['bold']) | |
340 | output += ',' + ass_bool(style.attrib['italic']) | |
341 | output += ',' + ass_bool(style.attrib['underline']) | |
342 | output += ',' + ass_bool(style.attrib['strikeout']) | |
343 | output += ',' + style.attrib['scale_x'] | |
344 | output += ',' + style.attrib['scale_y'] | |
345 | output += ',' + style.attrib['spacing'] | |
346 | output += ',' + style.attrib['angle'] | |
347 | output += ',' + style.attrib['border_style'] | |
348 | output += ',' + style.attrib['outline'] | |
349 | output += ',' + style.attrib['shadow'] | |
350 | output += ',' + style.attrib['alignment'] | |
351 | output += ',' + style.attrib['margin_l'] | |
352 | output += ',' + style.attrib['margin_r'] | |
353 | output += ',' + style.attrib['margin_v'] | |
354 | output += ',' + style.attrib['encoding'] | |
78272a07 A |
355 | output += '\n' |
356 | ||
357 | output += """ | |
358 | [Events] | |
359 | Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text | |
360 | """ | |
361 | for event in sub_root.findall('./events/event'): | |
362 | output += 'Dialogue: 0' | |
611c1dd9 S |
363 | output += ',' + event.attrib['start'] |
364 | output += ',' + event.attrib['end'] | |
365 | output += ',' + event.attrib['style'] | |
366 | output += ',' + event.attrib['name'] | |
367 | output += ',' + event.attrib['margin_l'] | |
368 | output += ',' + event.attrib['margin_r'] | |
369 | output += ',' + event.attrib['margin_v'] | |
370 | output += ',' + event.attrib['effect'] | |
371 | output += ',' + event.attrib['text'] | |
78272a07 A |
372 | output += '\n' |
373 | ||
374 | return output | |
375 | ||
0385d642 | 376 | def _extract_subtitles(self, subtitle): |
36e6f62c | 377 | sub_root = compat_etree_fromstring(subtitle) |
0385d642 S |
378 | return [{ |
379 | 'ext': 'srt', | |
380 | 'data': self._convert_subtitles_to_srt(sub_root), | |
381 | }, { | |
382 | 'ext': 'ass', | |
383 | 'data': self._convert_subtitles_to_ass(sub_root), | |
384 | }] | |
385 | ||
b5857f62 JMF |
386 | def _get_subtitles(self, video_id, webpage): |
387 | subtitles = {} | |
76907875 | 388 | for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage): |
05dee6c5 RA |
389 | sub_doc = self._call_rpc_api( |
390 | 'Subtitle_GetXml', video_id, | |
391 | 'Downloading subtitles for ' + sub_name, data={ | |
392 | 'subtitle_script_id': sub_id, | |
393 | }) | |
f9934b96 | 394 | if not isinstance(sub_doc, xml.etree.ElementTree.Element): |
b5857f62 | 395 | continue |
05dee6c5 RA |
396 | sid = sub_doc.get('id') |
397 | iv = xpath_text(sub_doc, 'iv', 'subtitle iv') | |
398 | data = xpath_text(sub_doc, 'data', 'subtitle data') | |
399 | if not sid or not iv or not data: | |
400 | continue | |
401 | subtitle = self._decrypt_subtitles(data, iv, sid).decode('utf-8') | |
b5857f62 JMF |
402 | lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False) |
403 | if not lang_code: | |
404 | continue | |
0385d642 | 405 | subtitles[lang_code] = self._extract_subtitles(subtitle) |
b5857f62 JMF |
406 | return subtitles |
407 | ||
5f6a1245 | 408 | def _real_extract(self, url): |
5ad28e7f | 409 | mobj = self._match_valid_url(url) |
d3d8d818 | 410 | video_id = mobj.group('id') |
38a40276 | 411 | |
412 | if mobj.group('prefix') == 'm': | |
413 | mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage') | |
414 | webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url') | |
415 | else: | |
416 | webpage_url = 'http://www.' + mobj.group('url') | |
c8434e83 | 417 | |
ca77b92f RA |
418 | webpage = self._download_webpage( |
419 | self._add_skip_wall(webpage_url), video_id, | |
420 | headers=self.geo_verification_headers()) | |
f4d706a9 JH |
421 | if re.search(r'<div id="preload-data">', webpage): |
422 | return self._redirect_to_beta(webpage, CrunchyrollBetaIE.ie_key(), video_id) | |
2f72e83b S |
423 | note_m = self._html_search_regex( |
424 | r'<div class="showmedia-trailer-notice">(.+?)</div>', | |
425 | webpage, 'trailer-notice', default='') | |
c8434e83 | 426 | if note_m: |
a7191c6f | 427 | raise ExtractorError(note_m, expected=True) |
c8434e83 | 428 | |
1d430674 S |
429 | mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage) |
430 | if mobj: | |
431 | msg = json.loads(mobj.group('msg')) | |
432 | if msg.get('type') == 'error': | |
433 | raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True) | |
2f72e83b S |
434 | |
435 | if 'To view this, please log in to verify you are 18 or older.' in webpage: | |
39affb5a | 436 | self.raise_login_required() |
1d430674 | 437 | |
54a5be4d RA |
438 | media = self._parse_json(self._search_regex( |
439 | r'vilos\.config\.media\s*=\s*({.+?});', | |
440 | webpage, 'vilos media', default='{}'), video_id) | |
441 | media_metadata = media.get('metadata') or {} | |
442 | ||
1084563e S |
443 | language = self._search_regex( |
444 | r'(?:vilos\.config\.player\.language|LOCALE)\s*=\s*(["\'])(?P<lang>(?:(?!\1).)+)\1', | |
445 | webpage, 'language', default=None, group='lang') | |
446 | ||
5214f1e3 | 447 | video_title = self._html_search_regex( |
6ffc3cf7 S |
448 | (r'(?s)<h1[^>]*>((?:(?!<h1).)*?<(?:span[^>]+itemprop=["\']title["\']|meta[^>]+itemprop=["\']position["\'])[^>]*>(?:(?!<h1).)+?)</h1>', |
449 | r'<title>(.+?),\s+-\s+.+? Crunchyroll'), | |
450 | webpage, 'video_title', default=None) | |
451 | if not video_title: | |
452 | video_title = re.sub(r'^Watch\s+', '', self._og_search_description(webpage)) | |
38a40276 | 453 | video_title = re.sub(r' {2,}', ' ', video_title) |
54a5be4d | 454 | video_description = (self._parse_json(self._html_search_regex( |
b5869560 | 455 | r'<script[^>]*>\s*.+?\[media_id=%s\].+?({.+?"description"\s*:.+?})\);' % video_id, |
54a5be4d | 456 | webpage, 'description', default='{}'), video_id) or media_metadata).get('description') |
245d43ca | 457 | |
458 | thumbnails = [] | |
459 | thumbnail_url = (self._parse_json(self._html_search_regex( | |
460 | r'<script type="application\/ld\+json">\n\s*(.+?)<\/script>', | |
461 | webpage, 'thumbnail_url', default='{}'), video_id)).get('image') | |
462 | if thumbnail_url: | |
463 | thumbnails.append({ | |
464 | 'url': thumbnail_url, | |
465 | 'width': 1920, | |
466 | 'height': 1080 | |
467 | }) | |
468 | ||
6d02b9a3 S |
469 | if video_description: |
470 | video_description = lowercase_escape(video_description.replace(r'\r\n', '\n')) | |
47004d95 | 471 | video_uploader = self._html_search_regex( |
7fd46552 | 472 | # try looking for both an uploader that's a link and one that's not |
473 | [r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', r'<div>\s*Publisher:\s*<span>\s*(.+?)\s*</span>\s*</div>'], | |
6ffc3cf7 | 474 | webpage, 'video_uploader', default=False) |
c8434e83 | 475 | |
a9d4da60 | 476 | requested_languages = self._configuration_arg('language') |
477 | requested_hardsubs = [('' if val == 'none' else val) for val in self._configuration_arg('hardsub')] | |
478 | language_preference = qualities((requested_languages or [language or ''])[::-1]) | |
479 | hardsub_preference = qualities((requested_hardsubs or ['', language or ''])[::-1]) | |
480 | ||
065216d9 | 481 | formats = [] |
54a5be4d | 482 | for stream in media.get('streams', []): |
a9d4da60 | 483 | audio_lang = stream.get('audio_lang') or '' |
484 | hardsub_lang = stream.get('hardsub_lang') or '' | |
485 | if (requested_languages and audio_lang.lower() not in requested_languages | |
486 | or requested_hardsubs and hardsub_lang.lower() not in requested_hardsubs): | |
487 | continue | |
1084563e | 488 | vrv_formats = self._extract_vrv_formats( |
54a5be4d | 489 | stream.get('url'), video_id, stream.get('format'), |
1084563e S |
490 | audio_lang, hardsub_lang) |
491 | for f in vrv_formats: | |
a9d4da60 | 492 | f['language_preference'] = language_preference(audio_lang) |
493 | f['quality'] = hardsub_preference(hardsub_lang) | |
1084563e | 494 | formats.extend(vrv_formats) |
54a5be4d RA |
495 | if not formats: |
496 | available_fmts = [] | |
497 | for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage): | |
498 | attrs = extract_attributes(a) | |
499 | href = attrs.get('href') | |
500 | if href and '/freetrial' in href: | |
501 | continue | |
502 | available_fmts.append(fmt) | |
503 | if not available_fmts: | |
504 | for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'): | |
505 | available_fmts = re.findall(p, webpage) | |
506 | if available_fmts: | |
507 | break | |
508 | if not available_fmts: | |
509 | available_fmts = self._FORMAT_IDS.keys() | |
510 | video_encode_ids = [] | |
511 | ||
512 | for fmt in available_fmts: | |
513 | stream_quality, stream_format = self._FORMAT_IDS[fmt] | |
514 | video_format = fmt + 'p' | |
515 | stream_infos = [] | |
516 | streamdata = self._call_rpc_api( | |
517 | 'VideoPlayer_GetStandardConfig', video_id, | |
518 | 'Downloading media info for %s' % video_format, data={ | |
519 | 'media_id': video_id, | |
520 | 'video_format': stream_format, | |
521 | 'video_quality': stream_quality, | |
522 | 'current_page': url, | |
523 | }) | |
f9934b96 | 524 | if isinstance(streamdata, xml.etree.ElementTree.Element): |
54a5be4d RA |
525 | stream_info = streamdata.find('./{default}preload/stream_info') |
526 | if stream_info is not None: | |
527 | stream_infos.append(stream_info) | |
528 | stream_info = self._call_rpc_api( | |
529 | 'VideoEncode_GetStreamInfo', video_id, | |
530 | 'Downloading stream info for %s' % video_format, data={ | |
531 | 'media_id': video_id, | |
532 | 'video_format': stream_format, | |
533 | 'video_encode_quality': stream_quality, | |
534 | }) | |
f9934b96 | 535 | if isinstance(stream_info, xml.etree.ElementTree.Element): |
05dee6c5 | 536 | stream_infos.append(stream_info) |
54a5be4d RA |
537 | for stream_info in stream_infos: |
538 | video_encode_id = xpath_text(stream_info, './video_encode_id') | |
539 | if video_encode_id in video_encode_ids: | |
540 | continue | |
541 | video_encode_ids.append(video_encode_id) | |
c8434e83 | 542 | |
54a5be4d RA |
543 | video_file = xpath_text(stream_info, './file') |
544 | if not video_file: | |
545 | continue | |
546 | if video_file.startswith('http'): | |
547 | formats.extend(self._extract_m3u8_formats( | |
548 | video_file, video_id, 'mp4', entry_protocol='m3u8_native', | |
549 | m3u8_id='hls', fatal=False)) | |
05dee6c5 RA |
550 | continue |
551 | ||
54a5be4d RA |
552 | video_url = xpath_text(stream_info, './host') |
553 | if not video_url: | |
554 | continue | |
555 | metadata = stream_info.find('./metadata') | |
556 | format_info = { | |
557 | 'format': video_format, | |
558 | 'height': int_or_none(xpath_text(metadata, './height')), | |
559 | 'width': int_or_none(xpath_text(metadata, './width')), | |
560 | } | |
561 | ||
562 | if '.fplive.net/' in video_url: | |
563 | video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip()) | |
564 | parsed_video_url = compat_urlparse.urlparse(video_url) | |
565 | direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace( | |
566 | netloc='v.lvlt.crcdn.net', | |
567 | path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1]))) | |
568 | if self._is_valid_url(direct_video_url, video_id, video_format): | |
569 | format_info.update({ | |
570 | 'format_id': 'http-' + video_format, | |
571 | 'url': direct_video_url, | |
572 | }) | |
573 | formats.append(format_info) | |
574 | continue | |
575 | ||
576 | format_info.update({ | |
577 | 'format_id': 'rtmp-' + video_format, | |
578 | 'url': video_url, | |
579 | 'play_path': video_file, | |
580 | 'ext': 'flv', | |
581 | }) | |
582 | formats.append(format_info) | |
54f37eea | 583 | self._sort_formats(formats) |
05dee6c5 RA |
584 | |
585 | metadata = self._call_rpc_api( | |
586 | 'VideoPlayer_GetMediaMetadata', video_id, | |
587 | note='Downloading media info', data={ | |
e757fb3d | 588 | 'media_id': video_id, |
589 | }) | |
590 | ||
54a5be4d RA |
591 | subtitles = {} |
592 | for subtitle in media.get('subtitles', []): | |
593 | subtitle_url = subtitle.get('url') | |
594 | if not subtitle_url: | |
595 | continue | |
596 | subtitles.setdefault(subtitle.get('language', 'enUS'), []).append({ | |
597 | 'url': subtitle_url, | |
598 | 'ext': subtitle.get('format', 'ass'), | |
599 | }) | |
600 | if not subtitles: | |
601 | subtitles = self.extract_subtitles(video_id, webpage) | |
11b3ce85 | 602 | |
e0b6e50c S |
603 | # webpage provide more accurate data than series_title from XML |
604 | series = self._html_search_regex( | |
7abed4e0 | 605 | r'(?s)<h\d[^>]+\bid=["\']showmedia_about_episode_num[^>]+>(.+?)</h\d', |
8c996232 | 606 | webpage, 'series', fatal=False) |
e0b6e50c | 607 | |
245d43ca | 608 | season = episode = episode_number = duration = None |
08c7d3da | 609 | |
f9934b96 | 610 | if isinstance(metadata, xml.etree.ElementTree.Element): |
08c7d3da S |
611 | season = xpath_text(metadata, 'series_title') |
612 | episode = xpath_text(metadata, 'episode_title') | |
613 | episode_number = int_or_none(xpath_text(metadata, 'episode_number')) | |
614 | duration = float_or_none(media_metadata.get('duration'), 1000) | |
08c7d3da S |
615 | |
616 | if not episode: | |
617 | episode = media_metadata.get('title') | |
618 | if not episode_number: | |
619 | episode_number = int_or_none(media_metadata.get('episode_number')) | |
245d43ca | 620 | thumbnail_url = try_get(media, lambda x: x['thumbnail']['url']) |
621 | if thumbnail_url: | |
622 | thumbnails.append({ | |
623 | 'url': thumbnail_url, | |
624 | 'width': 640, | |
625 | 'height': 360 | |
626 | }) | |
e0b6e50c S |
627 | |
628 | season_number = int_or_none(self._search_regex( | |
7abed4e0 | 629 | r'(?s)<h\d[^>]+id=["\']showmedia_about_episode_num[^>]+>.+?</h\d>\s*<h4>\s*Season (\d+)', |
e0b6e50c S |
630 | webpage, 'season number', default=None)) |
631 | ||
6ffc3cf7 S |
632 | info = self._search_json_ld(webpage, video_id, default={}) |
633 | ||
634 | return merge_dicts({ | |
8bcc8756 JW |
635 | 'id': video_id, |
636 | 'title': video_title, | |
38a40276 | 637 | 'description': video_description, |
08c7d3da | 638 | 'duration': duration, |
245d43ca | 639 | 'thumbnails': thumbnails, |
8bcc8756 | 640 | 'uploader': video_uploader, |
e0b6e50c | 641 | 'series': series, |
8c996232 | 642 | 'season': season, |
e0b6e50c S |
643 | 'season_number': season_number, |
644 | 'episode': episode, | |
645 | 'episode_number': episode_number, | |
8bcc8756 JW |
646 | 'subtitles': subtitles, |
647 | 'formats': formats, | |
6ffc3cf7 | 648 | }, info) |
8230018c GS |
649 | |
650 | ||
12810c9c | 651 | class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE): |
611c1dd9 | 652 | IE_NAME = 'crunchyroll:playlist' |
f1042989 | 653 | _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?:\w{2}(?:-\w{2})?/)?(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login|media-\d+))(?P<id>[\w\-]+))/?(?:\?|$)' |
8230018c GS |
654 | |
655 | _TESTS = [{ | |
d9488f69 | 656 | 'url': 'https://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi', |
09e5d6a6 PH |
657 | 'info_dict': { |
658 | 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi', | |
659 | 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi' | |
8230018c | 660 | }, |
09e5d6a6 | 661 | 'playlist_count': 13, |
49941c4e S |
662 | }, { |
663 | # geo-restricted (US), 18+ maturity wall, non-premium available | |
664 | 'url': 'http://www.crunchyroll.com/cosplay-complex-ova', | |
665 | 'info_dict': { | |
666 | 'id': 'cosplay-complex-ova', | |
667 | 'title': 'Cosplay Complex OVA' | |
668 | }, | |
669 | 'playlist_count': 3, | |
670 | 'skip': 'Georestricted', | |
671 | }, { | |
672 | # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14 | |
673 | 'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1', | |
674 | 'only_matching': True, | |
dd078970 | 675 | }, { |
676 | 'url': 'http://www.crunchyroll.com/fr/ladies-versus-butlers', | |
677 | 'only_matching': True, | |
8230018c GS |
678 | }] |
679 | ||
8230018c | 680 | def _real_extract(self, url): |
09e5d6a6 PH |
681 | show_id = self._match_id(url) |
682 | ||
ca77b92f | 683 | webpage = self._download_webpage( |
d9488f69 | 684 | # https:// gives a 403, but http:// does not |
685 | self._add_skip_wall(url).replace('https://', 'http://'), show_id, | |
ca77b92f | 686 | headers=self.geo_verification_headers()) |
f4d706a9 JH |
687 | if re.search(r'<div id="preload-data">', webpage): |
688 | return self._redirect_to_beta(webpage, CrunchyrollBetaShowIE.ie_key(), show_id) | |
4681441d S |
689 | title = self._html_search_meta('name', webpage, default=None) |
690 | ||
ec3f6640 | 691 | episode_re = r'<li id="showview_videos_media_(\d+)"[^>]+>.*?<a href="([^"]+)"' |
692 | season_re = r'<a [^>]+season-dropdown[^>]+>([^<]+)' | |
693 | paths = re.findall(f'(?s){episode_re}|{season_re}', webpage) | |
694 | ||
695 | entries, current_season = [], None | |
696 | for ep_id, ep, season in paths: | |
697 | if season: | |
698 | current_season = season | |
699 | continue | |
700 | entries.append(self.url_result( | |
701 | f'http://www.crunchyroll.com{ep}', CrunchyrollIE.ie_key(), ep_id, season=current_season)) | |
09e5d6a6 | 702 | |
8230018c | 703 | return { |
09e5d6a6 PH |
704 | '_type': 'playlist', |
705 | 'id': show_id, | |
706 | 'title': title, | |
ec3f6640 | 707 | 'entries': reversed(entries), |
09e5d6a6 | 708 | } |
dd078970 | 709 | |
710 | ||
f4d706a9 JH |
711 | class CrunchyrollBetaBaseIE(CrunchyrollBaseIE): |
712 | params = None | |
713 | ||
714 | def _get_params(self, lang): | |
715 | if not CrunchyrollBetaBaseIE.params: | |
716 | initial_state, app_config = self._get_beta_embedded_json(self._download_webpage( | |
717 | f'https://beta.crunchyroll.com/{lang}', None, note='Retrieving main page'), None) | |
718 | api_domain = app_config['cxApiParams']['apiDomain'] | |
719 | basic_token = str(base64.b64encode(('%s:' % app_config['cxApiParams']['accountAuthClientId']).encode('ascii')), 'ascii') | |
720 | auth_response = self._download_json( | |
721 | f'{api_domain}/auth/v1/token', None, note='Authenticating with cookie', | |
722 | headers={ | |
723 | 'Authorization': 'Basic ' + basic_token | |
724 | }, data='grant_type=etp_rt_cookie'.encode('ascii')) | |
725 | policy_response = self._download_json( | |
726 | f'{api_domain}/index/v2', None, note='Retrieving signed policy', | |
727 | headers={ | |
728 | 'Authorization': auth_response['token_type'] + ' ' + auth_response['access_token'] | |
729 | }) | |
88d62206 JH |
730 | cms = traverse_obj(policy_response, 'cms_beta', 'cms') |
731 | bucket = cms['bucket'] | |
f4d706a9 | 732 | params = { |
88d62206 JH |
733 | 'Policy': cms['policy'], |
734 | 'Signature': cms['signature'], | |
735 | 'Key-Pair-Id': cms['key_pair_id'] | |
f4d706a9 JH |
736 | } |
737 | locale = traverse_obj(initial_state, ('localization', 'locale')) | |
738 | if locale: | |
739 | params['locale'] = locale | |
740 | CrunchyrollBetaBaseIE.params = (api_domain, bucket, params) | |
741 | return CrunchyrollBetaBaseIE.params | |
742 | ||
743 | def _redirect_from_beta(self, url, lang, internal_id, display_id, is_episode, iekey): | |
744 | initial_state, app_config = self._get_beta_embedded_json(self._download_webpage(url, display_id), display_id) | |
745 | content_data = initial_state['content']['byId'][internal_id] | |
746 | if is_episode: | |
747 | video_id = content_data['external_id'].split('.')[1] | |
748 | series_id = content_data['episode_metadata']['series_slug_title'] | |
749 | else: | |
750 | series_id = content_data['slug_title'] | |
751 | series_id = re.sub(r'-{2,}', '-', series_id) | |
752 | url = f'https://www.crunchyroll.com/{lang}{series_id}' | |
753 | if is_episode: | |
754 | url = url + f'/{display_id}-{video_id}' | |
755 | self.to_screen(f'{display_id}: Not logged in. Redirecting to non-beta site - {url}') | |
756 | return self.url_result(url, iekey, display_id) | |
757 | ||
758 | ||
759 | class CrunchyrollBetaIE(CrunchyrollBetaBaseIE): | |
dd078970 | 760 | IE_NAME = 'crunchyroll:beta' |
f1042989 | 761 | _VALID_URL = r'https?://beta\.crunchyroll\.com/(?P<lang>(?:\w{2}(?:-\w{2})?/)?)watch/(?P<id>\w+)/(?P<display_id>[\w\-]*)/?(?:\?|$)' |
dd078970 | 762 | _TESTS = [{ |
763 | 'url': 'https://beta.crunchyroll.com/watch/GY2P1Q98Y/to-the-future', | |
764 | 'info_dict': { | |
b99ba3df | 765 | 'id': 'GY2P1Q98Y', |
dd078970 | 766 | 'ext': 'mp4', |
b99ba3df JH |
767 | 'duration': 1380.241, |
768 | 'timestamp': 1459632600, | |
dd078970 | 769 | 'description': 'md5:a022fbec4fbb023d43631032c91ed64b', |
dd078970 | 770 | 'title': 'World Trigger Episode 73 – To the Future', |
771 | 'upload_date': '20160402', | |
f4d706a9 | 772 | 'series': 'World Trigger', |
b99ba3df | 773 | 'series_id': 'GR757DMKY', |
f4d706a9 | 774 | 'season': 'World Trigger', |
b99ba3df | 775 | 'season_id': 'GR9P39NJ6', |
f4d706a9 | 776 | 'season_number': 1, |
b99ba3df JH |
777 | 'episode': 'To the Future', |
778 | 'episode_number': 73, | |
779 | 'thumbnail': r're:^https://beta.crunchyroll.com/imgsrv/.*\.jpeg$', | |
dd078970 | 780 | }, |
781 | 'params': {'skip_download': 'm3u8'}, | |
f4d706a9 JH |
782 | }, { |
783 | 'url': 'https://beta.crunchyroll.com/watch/GY2P1Q98Y/', | |
784 | 'only_matching': True, | |
964b5493 | 785 | }, { |
786 | 'url': 'https://beta.crunchyroll.com/pt-br/watch/G8WUN8VKP/the-ruler-of-conspiracy', | |
787 | 'only_matching': True, | |
dd078970 | 788 | }] |
789 | ||
790 | def _real_extract(self, url): | |
f4d706a9 JH |
791 | lang, internal_id, display_id = self._match_valid_url(url).group('lang', 'id', 'display_id') |
792 | ||
706dfe44 | 793 | if not self._get_cookies(url).get('etp_rt'): |
f4d706a9 JH |
794 | return self._redirect_from_beta(url, lang, internal_id, display_id, True, CrunchyrollIE.ie_key()) |
795 | ||
796 | api_domain, bucket, params = self._get_params(lang) | |
797 | ||
706dfe44 JH |
798 | episode_response = self._download_json( |
799 | f'{api_domain}/cms/v2{bucket}/episodes/{internal_id}', display_id, | |
7d0f6f0c | 800 | note='Retrieving episode metadata', query=params) |
706dfe44 JH |
801 | if episode_response.get('is_premium_only') and not episode_response.get('playback'): |
802 | raise ExtractorError('This video is for premium members only.', expected=True) | |
706dfe44 | 803 | |
7d0f6f0c B |
804 | stream_response = self._download_json(episode_response['playback'], display_id, note='Retrieving stream info') |
805 | get_streams = lambda name: (traverse_obj(stream_response, name) or {}).items() | |
706dfe44 JH |
806 | |
807 | requested_hardsubs = [('' if val == 'none' else val) for val in (self._configuration_arg('hardsub') or ['none'])] | |
808 | hardsub_preference = qualities(requested_hardsubs[::-1]) | |
809 | requested_formats = self._configuration_arg('format') or ['adaptive_hls'] | |
810 | ||
811 | formats = [] | |
7d0f6f0c | 812 | for stream_type, streams in get_streams('streams'): |
706dfe44 JH |
813 | if stream_type not in requested_formats: |
814 | continue | |
815 | for stream in streams.values(): | |
816 | hardsub_lang = stream.get('hardsub_locale') or '' | |
817 | if hardsub_lang.lower() not in requested_hardsubs: | |
818 | continue | |
7d0f6f0c | 819 | format_id = join_nonempty(stream_type, format_field(stream, 'hardsub_locale', 'hardsub-%s')) |
706dfe44 JH |
820 | if not stream.get('url'): |
821 | continue | |
7d0f6f0c | 822 | if stream_type.endswith('hls'): |
706dfe44 JH |
823 | adaptive_formats = self._extract_m3u8_formats( |
824 | stream['url'], display_id, 'mp4', m3u8_id=format_id, | |
7d0f6f0c B |
825 | fatal=False, note=f'Downloading {format_id} HLS manifest') |
826 | elif stream_type.endswith('dash'): | |
706dfe44 JH |
827 | adaptive_formats = self._extract_mpd_formats( |
828 | stream['url'], display_id, mpd_id=format_id, | |
7d0f6f0c | 829 | fatal=False, note=f'Downloading {format_id} MPD manifest') |
706dfe44 JH |
830 | for f in adaptive_formats: |
831 | if f.get('acodec') != 'none': | |
832 | f['language'] = stream_response.get('audio_locale') | |
833 | f['quality'] = hardsub_preference(hardsub_lang.lower()) | |
834 | formats.extend(adaptive_formats) | |
835 | self._sort_formats(formats) | |
836 | ||
837 | return { | |
838 | 'id': internal_id, | |
7d0f6f0c B |
839 | 'title': '%s Episode %s – %s' % ( |
840 | episode_response.get('season_title'), episode_response.get('episode'), episode_response.get('title')), | |
841 | 'description': try_get(episode_response, lambda x: x['description'].replace(r'\r\n', '\n')), | |
706dfe44 | 842 | 'duration': float_or_none(episode_response.get('duration_ms'), 1000), |
b99ba3df | 843 | 'timestamp': parse_iso8601(episode_response.get('upload_date')), |
706dfe44 JH |
844 | 'series': episode_response.get('series_title'), |
845 | 'series_id': episode_response.get('series_id'), | |
846 | 'season': episode_response.get('season_title'), | |
847 | 'season_id': episode_response.get('season_id'), | |
848 | 'season_number': episode_response.get('season_number'), | |
849 | 'episode': episode_response.get('title'), | |
850 | 'episode_number': episode_response.get('sequence_number'), | |
7d0f6f0c B |
851 | 'formats': formats, |
852 | 'thumbnails': [{ | |
853 | 'url': thumb.get('source'), | |
854 | 'width': thumb.get('width'), | |
855 | 'height': thumb.get('height'), | |
856 | } for thumb in traverse_obj(episode_response, ('images', 'thumbnail', ..., ...)) or []], | |
857 | 'subtitles': { | |
858 | lang: [{ | |
859 | 'url': subtitle_data.get('url'), | |
860 | 'ext': subtitle_data.get('format') | |
861 | }] for lang, subtitle_data in get_streams('subtitles') | |
862 | }, | |
706dfe44 | 863 | } |
dd078970 | 864 | |
865 | ||
f4d706a9 | 866 | class CrunchyrollBetaShowIE(CrunchyrollBetaBaseIE): |
dd078970 | 867 | IE_NAME = 'crunchyroll:playlist:beta' |
f1042989 | 868 | _VALID_URL = r'https?://beta\.crunchyroll\.com/(?P<lang>(?:\w{2}(?:-\w{2})?/)?)series/(?P<id>\w+)/(?P<display_id>[\w\-]*)/?(?:\?|$)' |
dd078970 | 869 | _TESTS = [{ |
870 | 'url': 'https://beta.crunchyroll.com/series/GY19NQ2QR/Girl-Friend-BETA', | |
871 | 'info_dict': { | |
b99ba3df | 872 | 'id': 'GY19NQ2QR', |
dd078970 | 873 | 'title': 'Girl Friend BETA', |
874 | }, | |
875 | 'playlist_mincount': 10, | |
876 | }, { | |
877 | 'url': 'https://beta.crunchyroll.com/it/series/GY19NQ2QR/Girl-Friend-BETA', | |
878 | 'only_matching': True, | |
879 | }] | |
880 | ||
881 | def _real_extract(self, url): | |
f4d706a9 JH |
882 | lang, internal_id, display_id = self._match_valid_url(url).group('lang', 'id', 'display_id') |
883 | ||
884 | if not self._get_cookies(url).get('etp_rt'): | |
885 | return self._redirect_from_beta(url, lang, internal_id, display_id, False, CrunchyrollShowPlaylistIE.ie_key()) | |
886 | ||
887 | api_domain, bucket, params = self._get_params(lang) | |
888 | ||
889 | series_response = self._download_json( | |
890 | f'{api_domain}/cms/v2{bucket}/series/{internal_id}', display_id, | |
891 | note='Retrieving series metadata', query=params) | |
892 | ||
893 | seasons_response = self._download_json( | |
894 | f'{api_domain}/cms/v2{bucket}/seasons?series_id={internal_id}', display_id, | |
895 | note='Retrieving season list', query=params) | |
896 | ||
897 | def entries(): | |
898 | for season in seasons_response['items']: | |
899 | episodes_response = self._download_json( | |
900 | f'{api_domain}/cms/v2{bucket}/episodes?season_id={season["id"]}', display_id, | |
901 | note=f'Retrieving episode list for {season.get("slug_title")}', query=params) | |
902 | for episode in episodes_response['items']: | |
903 | episode_id = episode['id'] | |
904 | episode_display_id = episode['slug_title'] | |
905 | yield { | |
906 | '_type': 'url', | |
907 | 'url': f'https://beta.crunchyroll.com/{lang}watch/{episode_id}/{episode_display_id}', | |
908 | 'ie_key': CrunchyrollBetaIE.ie_key(), | |
909 | 'id': episode_id, | |
910 | 'title': '%s Episode %s – %s' % (episode.get('season_title'), episode.get('episode'), episode.get('title')), | |
911 | 'description': try_get(episode, lambda x: x['description'].replace(r'\r\n', '\n')), | |
912 | 'duration': float_or_none(episode.get('duration_ms'), 1000), | |
913 | 'series': episode.get('series_title'), | |
914 | 'series_id': episode.get('series_id'), | |
915 | 'season': episode.get('season_title'), | |
916 | 'season_id': episode.get('season_id'), | |
917 | 'season_number': episode.get('season_number'), | |
918 | 'episode': episode.get('title'), | |
919 | 'episode_number': episode.get('sequence_number') | |
920 | } | |
921 | ||
922 | return self.playlist_result(entries(), internal_id, series_response.get('title')) |