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