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