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