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