2 from __future__ import unicode_literals
8 from hashlib import sha1
9 from math import pow, sqrt, floor
10 from .common import InfoExtractor
11 from ..compat import (
13 compat_etree_fromstring,
14 compat_urllib_parse_urlencode,
15 compat_urllib_request,
36 class CrunchyrollBaseIE(InfoExtractor):
37 _LOGIN_URL = 'https://www.crunchyroll.com/login'
38 _LOGIN_FORM = 'login_form'
39 _NETRC_MACHINE = 'crunchyroll'
41 def _call_rpc_api(self, method, video_id, note=None, data=None):
43 data['req'] = 'RpcApi' + method
44 data = compat_urllib_parse_urlencode(data).encode('utf-8')
45 return self._download_xml(
46 'http://www.crunchyroll.com/xml/',
47 video_id, note, fatal=False, data=data, headers={
48 'Content-Type': 'application/x-www-form-urlencoded',
52 username, password = self._get_login_info()
56 self._download_webpage(
57 'https://www.crunchyroll.com/?a=formhandler',
58 None, 'Logging in', 'Wrong login info',
59 data=urlencode_postdata({
60 'formname': 'RpcApiUser_Login',
61 'next_url': 'https://www.crunchyroll.com/acct/membership',
67 login_page = self._download_webpage(
68 self._LOGIN_URL, None, 'Downloading login page')
70 def is_logged(webpage):
71 return '<title>Redirecting' in webpage
74 if is_logged(login_page):
77 login_form_str = self._search_regex(
78 r'(?P<form><form[^>]+?id=(["\'])%s\2[^>]*>)' % self._LOGIN_FORM,
79 login_page, 'login form', group='form')
81 post_url = extract_attributes(login_form_str).get('action')
83 post_url = self._LOGIN_URL
84 elif not post_url.startswith('http'):
85 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
87 login_form = self._form_hidden_inputs(self._LOGIN_FORM, login_page)
90 'login_form[name]': username,
91 'login_form[password]': password,
94 response = self._download_webpage(
95 post_url, None, 'Logging in', 'Wrong login info',
96 data=urlencode_postdata(login_form),
97 headers={'Content-Type': 'application/x-www-form-urlencoded'})
100 if is_logged(response):
103 error = self._html_search_regex(
104 '(?s)<ul[^>]+class=["\']messages["\'][^>]*>(.+?)</ul>',
105 response, 'error message', default=None)
107 raise ExtractorError('Unable to login: %s' % error, expected=True)
109 raise ExtractorError('Unable to log in')
112 def _real_initialize(self):
115 def _download_webpage(self, url_or_request, *args, **kwargs):
116 request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
117 else sanitized_Request(url_or_request))
118 # Accept-Language must be set explicitly to accept any language to avoid issues
119 # similar to https://github.com/rg3/youtube-dl/issues/6797.
120 # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
121 # should be imposed or not (from what I can see it just takes the first language
122 # ignoring the priority and requires it to correspond the IP). By the way this causes
123 # Crunchyroll to not work in georestriction cases in some browsers that don't place
124 # the locale lang first in header. However allowing any language seems to workaround the issue.
125 request.add_header('Accept-Language', '*')
126 return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
129 def _add_skip_wall(url):
130 parsed_url = compat_urlparse.urlparse(url)
131 qs = compat_urlparse.parse_qs(parsed_url.query)
132 # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
133 # > This content may be inappropriate for some people.
134 # > Are you sure you want to continue?
135 # since it's not disabled by default in crunchyroll account's settings.
136 # See https://github.com/rg3/youtube-dl/issues/7202.
137 qs['skip_wall'] = ['1']
138 return compat_urlparse.urlunparse(
139 parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
142 class CrunchyrollIE(CrunchyrollBaseIE):
143 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
145 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
149 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
150 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
151 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
152 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
153 'upload_date': '20131013',
154 'url': 're:(?!.*&)',
158 'skip_download': True,
161 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
165 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
166 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
167 'thumbnail': r're:^https?://.*\.jpg$',
168 'uploader': 'Danny Choo Network',
169 'upload_date': '20120213',
173 'skip_download': True,
175 'skip': 'Video gone',
177 'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409',
181 'title': 'Re:ZERO -Starting Life in Another World- Episode 5 – The Morning of Our Promise Is Still Distant',
182 'description': 'md5:97664de1ab24bbf77a9c01918cb7dca9',
183 'thumbnail': r're:^https?://.*\.jpg$',
184 'uploader': 'TV TOKYO',
185 'upload_date': '20160508',
189 'skip_download': True,
192 'url': 'http://www.crunchyroll.com/konosuba-gods-blessing-on-this-wonderful-world/episode-1-give-me-deliverance-from-this-judicial-injustice-727589',
196 'title': "KONOSUBA -God's blessing on this wonderful world! 2 Episode 1 – Give Me Deliverance From This Judicial Injustice!",
197 'description': 'md5:cbcf05e528124b0f3a0a419fc805ea7d',
198 'thumbnail': r're:^https?://.*\.jpg$',
199 'uploader': 'Kadokawa Pictures Inc.',
200 'upload_date': '20170118',
201 'series': "KONOSUBA -God's blessing on this wonderful world!",
202 'season': "KONOSUBA -God's blessing on this wonderful world! 2",
204 'episode': 'Give Me Deliverance From This Judicial Injustice!',
209 'skip_download': True,
212 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
213 'only_matching': True,
215 # geo-restricted (US), 18+ maturity wall, non-premium available
216 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
217 'only_matching': True,
219 # A description with double quotes
220 'url': 'http://www.crunchyroll.com/11eyes/episode-1-piros-jszaka-red-night-535080',
224 'title': '11eyes Episode 1 – Piros éjszaka - Red Night',
225 'description': 'Kakeru and Yuka are thrown into an alternate nightmarish world they call "Red Night".',
226 'uploader': 'Marvelous AQL Inc.',
227 'upload_date': '20091021',
230 # Just test metadata extraction
231 'skip_download': True,
234 # make sure we can extract an uploader name that's not a link
235 'url': 'http://www.crunchyroll.com/hakuoki-reimeiroku/episode-1-dawn-of-the-divine-warriors-606899',
239 'title': 'Hakuoki Reimeiroku Episode 1 – Dawn of the Divine Warriors',
240 'description': 'Ryunosuke was left to die, but Serizawa-san asked him a simple question "Do you want to live?"',
241 'uploader': 'Geneon Entertainment',
242 'upload_date': '20120717',
245 # just test metadata extraction
246 'skip_download': True,
249 # A video with a vastly different season name compared to the series name
250 'url': 'http://www.crunchyroll.com/nyarko-san-another-crawling-chaos/episode-1-test-590532',
254 'title': 'Haiyoru! Nyaruani (ONA) Episode 1 – Test',
255 'description': 'Mahiro and Nyaruko talk about official certification.',
256 'uploader': 'TV TOKYO',
257 'upload_date': '20120305',
258 'series': 'Nyarko-san: Another Crawling Chaos',
259 'season': 'Haiyoru! Nyaruani (ONA)',
262 # Just test metadata extraction
263 'skip_download': True,
266 'url': 'http://www.crunchyroll.com/media-723735',
267 'only_matching': True,
271 '360': ('60', '106'),
272 '480': ('61', '106'),
273 '720': ('62', '106'),
274 '1080': ('80', '108'),
277 def _decrypt_subtitles(self, data, iv, id):
278 data = bytes_to_intlist(compat_b64decode(data))
279 iv = bytes_to_intlist(compat_b64decode(iv))
282 def obfuscate_key_aux(count, modulo, start):
284 for _ in range(count):
285 output.append(output[-1] + output[-2])
286 # cut off start values
288 output = list(map(lambda x: x % modulo + 33, output))
291 def obfuscate_key(key):
292 num1 = int(floor(pow(2, 25) * sqrt(6.9)))
293 num2 = (num1 ^ key) << 5
295 num4 = num3 ^ (num3 >> 3) ^ num2
296 prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
297 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
298 # Extend 160 Bit hash to 256 Bit
299 return shaHash + [0] * 12
301 key = obfuscate_key(id)
303 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
304 return zlib.decompress(decrypted_data)
306 def _convert_subtitles_to_srt(self, sub_root):
309 for i, event in enumerate(sub_root.findall('./events/event'), 1):
310 start = event.attrib['start'].replace('.', ',')
311 end = event.attrib['end'].replace('.', ',')
312 text = event.attrib['text'].replace('\\N', '\n')
313 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
316 def _convert_subtitles_to_ass(self, sub_root):
319 def ass_bool(strvalue):
325 output = '[Script Info]\n'
326 output += 'Title: %s\n' % sub_root.attrib['title']
327 output += 'ScriptType: v4.00+\n'
328 output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style']
329 output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x']
330 output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y']
333 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
335 for style in sub_root.findall('./styles/style'):
336 output += 'Style: ' + style.attrib['name']
337 output += ',' + style.attrib['font_name']
338 output += ',' + style.attrib['font_size']
339 output += ',' + style.attrib['primary_colour']
340 output += ',' + style.attrib['secondary_colour']
341 output += ',' + style.attrib['outline_colour']
342 output += ',' + style.attrib['back_colour']
343 output += ',' + ass_bool(style.attrib['bold'])
344 output += ',' + ass_bool(style.attrib['italic'])
345 output += ',' + ass_bool(style.attrib['underline'])
346 output += ',' + ass_bool(style.attrib['strikeout'])
347 output += ',' + style.attrib['scale_x']
348 output += ',' + style.attrib['scale_y']
349 output += ',' + style.attrib['spacing']
350 output += ',' + style.attrib['angle']
351 output += ',' + style.attrib['border_style']
352 output += ',' + style.attrib['outline']
353 output += ',' + style.attrib['shadow']
354 output += ',' + style.attrib['alignment']
355 output += ',' + style.attrib['margin_l']
356 output += ',' + style.attrib['margin_r']
357 output += ',' + style.attrib['margin_v']
358 output += ',' + style.attrib['encoding']
363 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
365 for event in sub_root.findall('./events/event'):
366 output += 'Dialogue: 0'
367 output += ',' + event.attrib['start']
368 output += ',' + event.attrib['end']
369 output += ',' + event.attrib['style']
370 output += ',' + event.attrib['name']
371 output += ',' + event.attrib['margin_l']
372 output += ',' + event.attrib['margin_r']
373 output += ',' + event.attrib['margin_v']
374 output += ',' + event.attrib['effect']
375 output += ',' + event.attrib['text']
380 def _extract_subtitles(self, subtitle):
381 sub_root = compat_etree_fromstring(subtitle)
384 'data': self._convert_subtitles_to_srt(sub_root),
387 'data': self._convert_subtitles_to_ass(sub_root),
390 def _get_subtitles(self, video_id, webpage):
392 for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage):
393 sub_doc = self._call_rpc_api(
394 'Subtitle_GetXml', video_id,
395 'Downloading subtitles for ' + sub_name, data={
396 'subtitle_script_id': sub_id,
400 sid = sub_doc.get('id')
401 iv = xpath_text(sub_doc, 'iv', 'subtitle iv')
402 data = xpath_text(sub_doc, 'data', 'subtitle data')
403 if not sid or not iv or not data:
405 subtitle = self._decrypt_subtitles(data, iv, sid).decode('utf-8')
406 lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
409 subtitles[lang_code] = self._extract_subtitles(subtitle)
412 def _real_extract(self, url):
413 mobj = re.match(self._VALID_URL, url)
414 video_id = mobj.group('video_id')
416 if mobj.group('prefix') == 'm':
417 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
418 webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
420 webpage_url = 'http://www.' + mobj.group('url')
422 webpage = self._download_webpage(
423 self._add_skip_wall(webpage_url), video_id,
424 headers=self.geo_verification_headers())
425 note_m = self._html_search_regex(
426 r'<div class="showmedia-trailer-notice">(.+?)</div>',
427 webpage, 'trailer-notice', default='')
429 raise ExtractorError(note_m)
431 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
433 msg = json.loads(mobj.group('msg'))
434 if msg.get('type') == 'error':
435 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
437 if 'To view this, please log in to verify you are 18 or older.' in webpage:
438 self.raise_login_required()
440 video_title = self._html_search_regex(
441 r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title["\'][^>]*>(?:(?!<h1).)+?)</h1>',
442 webpage, 'video_title')
443 video_title = re.sub(r' {2,}', ' ', video_title)
444 video_description = self._parse_json(self._html_search_regex(
445 r'<script[^>]*>\s*.+?\[media_id=%s\].+?({.+?"description"\s*:.+?})\);' % video_id,
446 webpage, 'description', default='{}'), video_id).get('description')
447 if video_description:
448 video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
449 video_upload_date = self._html_search_regex(
450 [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
451 webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
452 if video_upload_date:
453 video_upload_date = unified_strdate(video_upload_date)
454 video_uploader = self._html_search_regex(
455 # try looking for both an uploader that's a link and one that's not
456 [r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', r'<div>\s*Publisher:\s*<span>\s*(.+?)\s*</span>\s*</div>'],
457 webpage, 'video_uploader', fatal=False)
460 for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
461 attrs = extract_attributes(a)
462 href = attrs.get('href')
463 if href and '/freetrial' in href:
465 available_fmts.append(fmt)
466 if not available_fmts:
467 for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'):
468 available_fmts = re.findall(p, webpage)
471 video_encode_ids = []
473 for fmt in available_fmts:
474 stream_quality, stream_format = self._FORMAT_IDS[fmt]
475 video_format = fmt + 'p'
477 streamdata = self._call_rpc_api(
478 'VideoPlayer_GetStandardConfig', video_id,
479 'Downloading media info for %s' % video_format, data={
480 'media_id': video_id,
481 'video_format': stream_format,
482 'video_quality': stream_quality,
485 if streamdata is not None:
486 stream_info = streamdata.find('./{default}preload/stream_info')
487 if stream_info is not None:
488 stream_infos.append(stream_info)
489 stream_info = self._call_rpc_api(
490 'VideoEncode_GetStreamInfo', video_id,
491 'Downloading stream info for %s' % video_format, data={
492 'media_id': video_id,
493 'video_format': stream_format,
494 'video_encode_quality': stream_quality,
496 if stream_info is not None:
497 stream_infos.append(stream_info)
498 for stream_info in stream_infos:
499 video_encode_id = xpath_text(stream_info, './video_encode_id')
500 if video_encode_id in video_encode_ids:
502 video_encode_ids.append(video_encode_id)
504 video_file = xpath_text(stream_info, './file')
507 if video_file.startswith('http'):
508 formats.extend(self._extract_m3u8_formats(
509 video_file, video_id, 'mp4', entry_protocol='m3u8_native',
510 m3u8_id='hls', fatal=False))
513 video_url = xpath_text(stream_info, './host')
516 metadata = stream_info.find('./metadata')
518 'format': video_format,
519 'height': int_or_none(xpath_text(metadata, './height')),
520 'width': int_or_none(xpath_text(metadata, './width')),
523 if '.fplive.net/' in video_url:
524 video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
525 parsed_video_url = compat_urlparse.urlparse(video_url)
526 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
527 netloc='v.lvlt.crcdn.net',
528 path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
529 if self._is_valid_url(direct_video_url, video_id, video_format):
531 'format_id': 'http-' + video_format,
532 'url': direct_video_url,
534 formats.append(format_info)
538 'format_id': 'rtmp-' + video_format,
540 'play_path': video_file,
543 formats.append(format_info)
544 self._sort_formats(formats, ('height', 'width', 'tbr', 'fps'))
546 metadata = self._call_rpc_api(
547 'VideoPlayer_GetMediaMetadata', video_id,
548 note='Downloading media info', data={
549 'media_id': video_id,
552 subtitles = self.extract_subtitles(video_id, webpage)
554 # webpage provide more accurate data than series_title from XML
555 series = self._html_search_regex(
556 r'(?s)<h\d[^>]+\bid=["\']showmedia_about_episode_num[^>]+>(.+?)</h\d',
557 webpage, 'series', fatal=False)
558 season = xpath_text(metadata, 'series_title')
560 episode = xpath_text(metadata, 'episode_title')
561 episode_number = int_or_none(xpath_text(metadata, 'episode_number'))
563 season_number = int_or_none(self._search_regex(
564 r'(?s)<h\d[^>]+id=["\']showmedia_about_episode_num[^>]+>.+?</h\d>\s*<h4>\s*Season (\d+)',
565 webpage, 'season number', default=None))
569 'title': video_title,
570 'description': video_description,
571 'thumbnail': xpath_text(metadata, 'episode_image_url'),
572 'uploader': video_uploader,
573 'upload_date': video_upload_date,
576 'season_number': season_number,
578 'episode_number': episode_number,
579 'subtitles': subtitles,
584 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
585 IE_NAME = 'crunchyroll:playlist'
586 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login|media-\d+))(?P<id>[\w\-]+))/?(?:\?|$)'
589 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
591 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
592 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
594 'playlist_count': 13,
596 # geo-restricted (US), 18+ maturity wall, non-premium available
597 'url': 'http://www.crunchyroll.com/cosplay-complex-ova',
599 'id': 'cosplay-complex-ova',
600 'title': 'Cosplay Complex OVA'
603 'skip': 'Georestricted',
605 # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
606 'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1',
607 'only_matching': True,
610 def _real_extract(self, url):
611 show_id = self._match_id(url)
613 webpage = self._download_webpage(
614 self._add_skip_wall(url), show_id,
615 headers=self.geo_verification_headers())
616 title = self._html_search_regex(
617 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
619 episode_paths = re.findall(
620 r'(?s)<li id="showview_videos_media_(\d+)"[^>]+>.*?<a href="([^"]+)"',
623 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll', ep_id)
624 for ep_id, ep in episode_paths