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