2 from __future__ import unicode_literals
8 import xml.etree.ElementTree
10 from hashlib import sha1
11 from math import pow, sqrt, floor
12 from .common import InfoExtractor
13 from ..compat import (
15 compat_urllib_parse_unquote,
16 compat_urllib_request,
34 class CrunchyrollBaseIE(InfoExtractor):
35 def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None):
36 request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
37 else compat_urllib_request.Request(url_or_request))
38 # Accept-Language must be set explicitly to accept any language to avoid issues
39 # similar to https://github.com/rg3/youtube-dl/issues/6797.
40 # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
41 # should be imposed or not (from what I can see it just takes the first language
42 # ignoring the priority and requires it to correspond the IP). By the way this causes
43 # Crunchyroll to not work in georestriction cases in some browsers that don't place
44 # the locale lang first in header. However allowing any language seems to workaround the issue.
45 request.add_header('Accept-Language', '*')
46 return super(CrunchyrollBaseIE, self)._download_webpage(
47 request, video_id, note, errnote, fatal, tries, timeout, encoding)
50 class CrunchyrollIE(CrunchyrollBaseIE):
51 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
52 _NETRC_MACHINE = 'crunchyroll'
54 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
58 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
59 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
60 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
61 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
62 'upload_date': '20131013',
63 'url': 're:(?!.*&)',
67 'skip_download': True,
70 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
74 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
75 'description': 'md5:fe2743efedb49d279552926d0bd0cd9e',
76 'thumbnail': 're:^https?://.*\.jpg$',
77 'uploader': 'Danny Choo Network',
78 'upload_date': '20120213',
82 'skip_download': True,
86 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
87 'only_matching': True,
94 '1080': ('80', '108'),
98 (username, password) = self._get_login_info()
102 login_url = 'https://www.crunchyroll.com/?a=formhandler'
103 data = urlencode_postdata({
104 'formname': 'RpcApiUser_Login',
106 'password': password,
108 login_request = compat_urllib_request.Request(login_url, data)
109 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
110 self._download_webpage(login_request, None, False, 'Wrong login info')
112 def _real_initialize(self):
115 def _decrypt_subtitles(self, data, iv, id):
116 data = bytes_to_intlist(base64.b64decode(data.encode('utf-8')))
117 iv = bytes_to_intlist(base64.b64decode(iv.encode('utf-8')))
120 def obfuscate_key_aux(count, modulo, start):
122 for _ in range(count):
123 output.append(output[-1] + output[-2])
124 # cut off start values
126 output = list(map(lambda x: x % modulo + 33, output))
129 def obfuscate_key(key):
130 num1 = int(floor(pow(2, 25) * sqrt(6.9)))
131 num2 = (num1 ^ key) << 5
133 num4 = num3 ^ (num3 >> 3) ^ num2
134 prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
135 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
136 # Extend 160 Bit hash to 256 Bit
137 return shaHash + [0] * 12
139 key = obfuscate_key(id)
141 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
142 return zlib.decompress(decrypted_data)
144 def _convert_subtitles_to_srt(self, sub_root):
147 for i, event in enumerate(sub_root.findall('./events/event'), 1):
148 start = event.attrib['start'].replace('.', ',')
149 end = event.attrib['end'].replace('.', ',')
150 text = event.attrib['text'].replace('\\N', '\n')
151 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
154 def _convert_subtitles_to_ass(self, sub_root):
157 def ass_bool(strvalue):
163 output = '[Script Info]\n'
164 output += 'Title: %s\n' % sub_root.attrib["title"]
165 output += 'ScriptType: v4.00+\n'
166 output += 'WrapStyle: %s\n' % sub_root.attrib["wrap_style"]
167 output += 'PlayResX: %s\n' % sub_root.attrib["play_res_x"]
168 output += 'PlayResY: %s\n' % sub_root.attrib["play_res_y"]
169 output += """ScaledBorderAndShadow: yes
172 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
174 for style in sub_root.findall('./styles/style'):
175 output += 'Style: ' + style.attrib["name"]
176 output += ',' + style.attrib["font_name"]
177 output += ',' + style.attrib["font_size"]
178 output += ',' + style.attrib["primary_colour"]
179 output += ',' + style.attrib["secondary_colour"]
180 output += ',' + style.attrib["outline_colour"]
181 output += ',' + style.attrib["back_colour"]
182 output += ',' + ass_bool(style.attrib["bold"])
183 output += ',' + ass_bool(style.attrib["italic"])
184 output += ',' + ass_bool(style.attrib["underline"])
185 output += ',' + ass_bool(style.attrib["strikeout"])
186 output += ',' + style.attrib["scale_x"]
187 output += ',' + style.attrib["scale_y"]
188 output += ',' + style.attrib["spacing"]
189 output += ',' + style.attrib["angle"]
190 output += ',' + style.attrib["border_style"]
191 output += ',' + style.attrib["outline"]
192 output += ',' + style.attrib["shadow"]
193 output += ',' + style.attrib["alignment"]
194 output += ',' + style.attrib["margin_l"]
195 output += ',' + style.attrib["margin_r"]
196 output += ',' + style.attrib["margin_v"]
197 output += ',' + style.attrib["encoding"]
202 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
204 for event in sub_root.findall('./events/event'):
205 output += 'Dialogue: 0'
206 output += ',' + event.attrib["start"]
207 output += ',' + event.attrib["end"]
208 output += ',' + event.attrib["style"]
209 output += ',' + event.attrib["name"]
210 output += ',' + event.attrib["margin_l"]
211 output += ',' + event.attrib["margin_r"]
212 output += ',' + event.attrib["margin_v"]
213 output += ',' + event.attrib["effect"]
214 output += ',' + event.attrib["text"]
219 def _extract_subtitles(self, subtitle):
220 sub_root = xml.etree.ElementTree.fromstring(subtitle)
223 'data': self._convert_subtitles_to_srt(sub_root),
226 'data': self._convert_subtitles_to_ass(sub_root),
229 def _get_subtitles(self, video_id, webpage):
231 for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
232 sub_page = self._download_webpage(
233 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
234 video_id, note='Downloading subtitles for ' + sub_name)
235 id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
236 iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
237 data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
238 if not id or not iv or not data:
240 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
241 lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
244 subtitles[lang_code] = self._extract_subtitles(subtitle)
247 def _real_extract(self, url):
248 mobj = re.match(self._VALID_URL, url)
249 video_id = mobj.group('video_id')
251 if mobj.group('prefix') == 'm':
252 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
253 webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
255 webpage_url = 'http://www.' + mobj.group('url')
257 webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
258 note_m = self._html_search_regex(
259 r'<div class="showmedia-trailer-notice">(.+?)</div>',
260 webpage, 'trailer-notice', default='')
262 raise ExtractorError(note_m)
264 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
266 msg = json.loads(mobj.group('msg'))
267 if msg.get('type') == 'error':
268 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
270 if 'To view this, please log in to verify you are 18 or older.' in webpage:
271 self.raise_login_required()
273 video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
274 video_title = re.sub(r' {2,}', ' ', video_title)
275 video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
276 if not video_description:
277 video_description = None
278 video_upload_date = self._html_search_regex(
279 [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
280 webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
281 if video_upload_date:
282 video_upload_date = unified_strdate(video_upload_date)
283 video_uploader = self._html_search_regex(
284 r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', webpage,
285 'video_uploader', fatal=False)
287 playerdata_url = compat_urllib_parse_unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
288 playerdata_req = compat_urllib_request.Request(playerdata_url)
289 playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
290 playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
291 playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
293 stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
294 video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
297 for fmt in re.findall(r'showmedia\.([0-9]{3,4})p', webpage):
298 stream_quality, stream_format = self._FORMAT_IDS[fmt]
299 video_format = fmt + 'p'
300 streamdata_req = compat_urllib_request.Request(
301 'http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s&video_format=%s&video_quality=%s'
302 % (stream_id, stream_format, stream_quality),
303 compat_urllib_parse.urlencode({'current_page': url}).encode('utf-8'))
304 streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
305 streamdata = self._download_xml(
306 streamdata_req, video_id,
307 note='Downloading media info for %s' % video_format)
308 stream_info = streamdata.find('./{default}preload/stream_info')
309 video_url = stream_info.find('./host').text
310 video_play_path = stream_info.find('./file').text
311 metadata = stream_info.find('./metadata')
313 'format': video_format,
314 'format_id': video_format,
315 'height': int_or_none(xpath_text(metadata, './height')),
316 'width': int_or_none(xpath_text(metadata, './width')),
319 if '.fplive.net/' in video_url:
320 video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
321 parsed_video_url = compat_urlparse.urlparse(video_url)
322 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
323 netloc='v.lvlt.crcdn.net',
324 path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_play_path.split(':')[-1])))
325 if self._is_valid_url(direct_video_url, video_id, video_format):
327 'url': direct_video_url,
329 formats.append(format_info)
334 'play_path': video_play_path,
337 formats.append(format_info)
339 subtitles = self.extract_subtitles(video_id, webpage)
343 'title': video_title,
344 'description': video_description,
345 'thumbnail': video_thumbnail,
346 'uploader': video_uploader,
347 'upload_date': video_upload_date,
348 'subtitles': subtitles,
353 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
354 IE_NAME = "crunchyroll:playlist"
355 _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\-]+))/?$'
358 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
360 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
361 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
363 'playlist_count': 13,
366 def _real_extract(self, url):
367 show_id = self._match_id(url)
369 webpage = self._download_webpage(url, show_id)
370 title = self._html_search_regex(
371 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
373 episode_paths = re.findall(
374 r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
377 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
378 for ep in episode_paths