2 from __future__ import unicode_literals
9 from hashlib import sha1
10 from math import pow, sqrt, floor
11 from .common import InfoExtractor
12 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'
42 (username, password) = self._get_login_info()
46 login_page = self._download_webpage(
47 self._LOGIN_URL, None, 'Downloading login page')
49 login_form_str = self._search_regex(
50 r'(?P<form><form[^>]+?id=(["\'])%s\2[^>]*>)' % self._LOGIN_FORM,
51 login_page, 'login form', group='form')
53 post_url = extract_attributes(login_form_str).get('action')
55 post_url = self._LOGIN_URL
56 elif not post_url.startswith('http'):
57 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
59 login_form = self._form_hidden_inputs(self._LOGIN_FORM, login_page)
62 'login_form[name]': username,
63 'login_form[password]': password,
66 response = self._download_webpage(
67 post_url, None, 'Logging in', 'Wrong login info',
68 data=urlencode_postdata(login_form),
69 headers={'Content-Type': 'application/x-www-form-urlencoded'})
72 if '<title>Redirecting' in response:
75 error = self._html_search_regex(
76 '(?s)<ul[^>]+class=["\']messages["\'][^>]*>(.+?)</ul>',
77 response, 'error message', default=None)
79 raise ExtractorError('Unable to login: %s' % error, expected=True)
81 raise ExtractorError('Unable to log in')
83 def _real_initialize(self):
86 def _download_webpage(self, url_or_request, *args, **kwargs):
87 request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
88 else sanitized_Request(url_or_request))
89 # Accept-Language must be set explicitly to accept any language to avoid issues
90 # similar to https://github.com/rg3/youtube-dl/issues/6797.
91 # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
92 # should be imposed or not (from what I can see it just takes the first language
93 # ignoring the priority and requires it to correspond the IP). By the way this causes
94 # Crunchyroll to not work in georestriction cases in some browsers that don't place
95 # the locale lang first in header. However allowing any language seems to workaround the issue.
96 request.add_header('Accept-Language', '*')
97 return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
100 def _add_skip_wall(url):
101 parsed_url = compat_urlparse.urlparse(url)
102 qs = compat_urlparse.parse_qs(parsed_url.query)
103 # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
104 # > This content may be inappropriate for some people.
105 # > Are you sure you want to continue?
106 # since it's not disabled by default in crunchyroll account's settings.
107 # See https://github.com/rg3/youtube-dl/issues/7202.
108 qs['skip_wall'] = ['1']
109 return compat_urlparse.urlunparse(
110 parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
113 class CrunchyrollIE(CrunchyrollBaseIE):
114 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
116 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
120 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
121 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
122 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
123 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
124 'upload_date': '20131013',
125 'url': 're:(?!.*&)',
129 'skip_download': True,
132 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
136 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
137 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
138 'thumbnail': 're:^https?://.*\.jpg$',
139 'uploader': 'Danny Choo Network',
140 'upload_date': '20120213',
144 'skip_download': True,
147 'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409',
151 'title': 'Re:ZERO -Starting Life in Another World- Episode 5 – The Morning of Our Promise Is Still Distant',
152 'description': 'md5:97664de1ab24bbf77a9c01918cb7dca9',
153 'thumbnail': 're:^https?://.*\.jpg$',
154 'uploader': 'TV TOKYO',
155 'upload_date': '20160508',
159 'skip_download': True,
162 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
163 'only_matching': True,
165 # geo-restricted (US), 18+ maturity wall, non-premium available
166 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
167 'only_matching': True,
171 '360': ('60', '106'),
172 '480': ('61', '106'),
173 '720': ('62', '106'),
174 '1080': ('80', '108'),
177 def _decrypt_subtitles(self, data, iv, id):
178 data = bytes_to_intlist(base64.b64decode(data.encode('utf-8')))
179 iv = bytes_to_intlist(base64.b64decode(iv.encode('utf-8')))
182 def obfuscate_key_aux(count, modulo, start):
184 for _ in range(count):
185 output.append(output[-1] + output[-2])
186 # cut off start values
188 output = list(map(lambda x: x % modulo + 33, output))
191 def obfuscate_key(key):
192 num1 = int(floor(pow(2, 25) * sqrt(6.9)))
193 num2 = (num1 ^ key) << 5
195 num4 = num3 ^ (num3 >> 3) ^ num2
196 prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
197 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
198 # Extend 160 Bit hash to 256 Bit
199 return shaHash + [0] * 12
201 key = obfuscate_key(id)
203 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
204 return zlib.decompress(decrypted_data)
206 def _convert_subtitles_to_srt(self, sub_root):
209 for i, event in enumerate(sub_root.findall('./events/event'), 1):
210 start = event.attrib['start'].replace('.', ',')
211 end = event.attrib['end'].replace('.', ',')
212 text = event.attrib['text'].replace('\\N', '\n')
213 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
216 def _convert_subtitles_to_ass(self, sub_root):
219 def ass_bool(strvalue):
225 output = '[Script Info]\n'
226 output += 'Title: %s\n' % sub_root.attrib['title']
227 output += 'ScriptType: v4.00+\n'
228 output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style']
229 output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x']
230 output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y']
231 output += """ScaledBorderAndShadow: yes
234 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
236 for style in sub_root.findall('./styles/style'):
237 output += 'Style: ' + style.attrib['name']
238 output += ',' + style.attrib['font_name']
239 output += ',' + style.attrib['font_size']
240 output += ',' + style.attrib['primary_colour']
241 output += ',' + style.attrib['secondary_colour']
242 output += ',' + style.attrib['outline_colour']
243 output += ',' + style.attrib['back_colour']
244 output += ',' + ass_bool(style.attrib['bold'])
245 output += ',' + ass_bool(style.attrib['italic'])
246 output += ',' + ass_bool(style.attrib['underline'])
247 output += ',' + ass_bool(style.attrib['strikeout'])
248 output += ',' + style.attrib['scale_x']
249 output += ',' + style.attrib['scale_y']
250 output += ',' + style.attrib['spacing']
251 output += ',' + style.attrib['angle']
252 output += ',' + style.attrib['border_style']
253 output += ',' + style.attrib['outline']
254 output += ',' + style.attrib['shadow']
255 output += ',' + style.attrib['alignment']
256 output += ',' + style.attrib['margin_l']
257 output += ',' + style.attrib['margin_r']
258 output += ',' + style.attrib['margin_v']
259 output += ',' + style.attrib['encoding']
264 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
266 for event in sub_root.findall('./events/event'):
267 output += 'Dialogue: 0'
268 output += ',' + event.attrib['start']
269 output += ',' + event.attrib['end']
270 output += ',' + event.attrib['style']
271 output += ',' + event.attrib['name']
272 output += ',' + event.attrib['margin_l']
273 output += ',' + event.attrib['margin_r']
274 output += ',' + event.attrib['margin_v']
275 output += ',' + event.attrib['effect']
276 output += ',' + event.attrib['text']
281 def _extract_subtitles(self, subtitle):
282 sub_root = compat_etree_fromstring(subtitle)
285 'data': self._convert_subtitles_to_srt(sub_root),
288 'data': self._convert_subtitles_to_ass(sub_root),
291 def _get_subtitles(self, video_id, webpage):
293 for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage):
294 sub_page = self._download_webpage(
295 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
296 video_id, note='Downloading subtitles for ' + sub_name)
297 id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
298 iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
299 data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
300 if not id or not iv or not data:
302 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
303 lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
306 subtitles[lang_code] = self._extract_subtitles(subtitle)
309 def _real_extract(self, url):
310 mobj = re.match(self._VALID_URL, url)
311 video_id = mobj.group('video_id')
313 if mobj.group('prefix') == 'm':
314 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
315 webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
317 webpage_url = 'http://www.' + mobj.group('url')
319 webpage = self._download_webpage(self._add_skip_wall(webpage_url), video_id, 'Downloading webpage')
320 note_m = self._html_search_regex(
321 r'<div class="showmedia-trailer-notice">(.+?)</div>',
322 webpage, 'trailer-notice', default='')
324 raise ExtractorError(note_m)
326 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
328 msg = json.loads(mobj.group('msg'))
329 if msg.get('type') == 'error':
330 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
332 if 'To view this, please log in to verify you are 18 or older.' in webpage:
333 self.raise_login_required()
335 video_title = self._html_search_regex(
336 r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title["\'][^>]*>(?:(?!<h1).)+?)</h1>',
337 webpage, 'video_title')
338 video_title = re.sub(r' {2,}', ' ', video_title)
339 video_description = self._html_search_regex(
340 r'<script[^>]*>\s*.+?\[media_id=%s\].+?"description"\s*:\s*"([^"]+)' % video_id,
341 webpage, 'description', default=None)
342 if video_description:
343 video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
344 video_upload_date = self._html_search_regex(
345 [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
346 webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
347 if video_upload_date:
348 video_upload_date = unified_strdate(video_upload_date)
349 video_uploader = self._html_search_regex(
350 r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', webpage,
351 'video_uploader', fatal=False)
354 for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
355 attrs = extract_attributes(a)
356 href = attrs.get('href')
357 if href and '/freetrial' in href:
359 available_fmts.append(fmt)
360 if not available_fmts:
361 for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'):
362 available_fmts = re.findall(p, webpage)
365 video_encode_ids = []
367 for fmt in available_fmts:
368 stream_quality, stream_format = self._FORMAT_IDS[fmt]
369 video_format = fmt + 'p'
370 streamdata_req = sanitized_Request(
371 'http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s&video_format=%s&video_quality=%s'
372 % (video_id, stream_format, stream_quality),
373 compat_urllib_parse_urlencode({'current_page': url}).encode('utf-8'))
374 streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
375 streamdata = self._download_xml(
376 streamdata_req, video_id,
377 note='Downloading media info for %s' % video_format)
378 stream_info = streamdata.find('./{default}preload/stream_info')
379 video_encode_id = xpath_text(stream_info, './video_encode_id')
380 if video_encode_id in video_encode_ids:
382 video_encode_ids.append(video_encode_id)
384 video_file = xpath_text(stream_info, './file')
387 if video_file.startswith('http'):
388 formats.extend(self._extract_m3u8_formats(
389 video_file, video_id, 'mp4', entry_protocol='m3u8_native',
390 m3u8_id='hls', fatal=False))
393 video_url = xpath_text(stream_info, './host')
396 metadata = stream_info.find('./metadata')
398 'format': video_format,
399 'format_id': video_format,
400 'height': int_or_none(xpath_text(metadata, './height')),
401 'width': int_or_none(xpath_text(metadata, './width')),
404 if '.fplive.net/' in video_url:
405 video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
406 parsed_video_url = compat_urlparse.urlparse(video_url)
407 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
408 netloc='v.lvlt.crcdn.net',
409 path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
410 if self._is_valid_url(direct_video_url, video_id, video_format):
412 'url': direct_video_url,
414 formats.append(format_info)
419 'play_path': video_file,
422 formats.append(format_info)
423 self._sort_formats(formats)
425 metadata = self._download_xml(
426 'http://www.crunchyroll.com/xml', video_id,
427 note='Downloading media info', query={
428 'req': 'RpcApiVideoPlayer_GetMediaMetadata',
429 'media_id': video_id,
432 subtitles = self.extract_subtitles(video_id, webpage)
436 'title': video_title,
437 'description': video_description,
438 'thumbnail': xpath_text(metadata, 'episode_image_url'),
439 'uploader': video_uploader,
440 'upload_date': video_upload_date,
441 'series': xpath_text(metadata, 'series_title'),
442 'episode': xpath_text(metadata, 'episode_title'),
443 'episode_number': int_or_none(xpath_text(metadata, 'episode_number')),
444 'subtitles': subtitles,
449 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
450 IE_NAME = 'crunchyroll:playlist'
451 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login))(?P<id>[\w\-]+))/?(?:\?|$)'
454 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
456 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
457 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
459 'playlist_count': 13,
461 # geo-restricted (US), 18+ maturity wall, non-premium available
462 'url': 'http://www.crunchyroll.com/cosplay-complex-ova',
464 'id': 'cosplay-complex-ova',
465 'title': 'Cosplay Complex OVA'
468 'skip': 'Georestricted',
470 # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
471 'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1',
472 'only_matching': True,
475 def _real_extract(self, url):
476 show_id = self._match_id(url)
478 webpage = self._download_webpage(self._add_skip_wall(url), show_id)
479 title = self._html_search_regex(
480 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
482 episode_paths = re.findall(
483 r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
486 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
487 for ep in episode_paths