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_request,
30 class CrunchyrollIE(InfoExtractor):
31 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
32 _NETRC_MACHINE = 'crunchyroll'
34 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
38 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
39 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
40 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
41 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
42 'upload_date': '20131013',
43 'url': 're:(?!.*&)',
47 'skip_download': True,
50 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
51 'only_matching': True,
58 '1080': ('80', '108'),
62 (username, password) = self._get_login_info()
66 login_url = 'https://www.crunchyroll.com/?a=formhandler'
67 data = urlencode_postdata({
68 'formname': 'RpcApiUser_Login',
72 login_request = compat_urllib_request.Request(login_url, data)
73 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
74 self._download_webpage(login_request, None, False, 'Wrong login info')
76 def _real_initialize(self):
79 def _decrypt_subtitles(self, data, iv, id):
80 data = bytes_to_intlist(data)
81 iv = bytes_to_intlist(iv)
84 def obfuscate_key_aux(count, modulo, start):
86 for _ in range(count):
87 output.append(output[-1] + output[-2])
88 # cut off start values
90 output = list(map(lambda x: x % modulo + 33, output))
93 def obfuscate_key(key):
94 num1 = int(floor(pow(2, 25) * sqrt(6.9)))
95 num2 = (num1 ^ key) << 5
97 num4 = num3 ^ (num3 >> 3) ^ num2
98 prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
99 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
100 # Extend 160 Bit hash to 256 Bit
101 return shaHash + [0] * 12
103 key = obfuscate_key(id)
108 def next_value(self):
110 self.__value = inc(self.__value)
112 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
113 return zlib.decompress(decrypted_data)
115 def _convert_subtitles_to_srt(self, sub_root):
118 for i, event in enumerate(sub_root.findall('./events/event'), 1):
119 start = event.attrib['start'].replace('.', ',')
120 end = event.attrib['end'].replace('.', ',')
121 text = event.attrib['text'].replace('\\N', '\n')
122 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
125 def _convert_subtitles_to_ass(self, sub_root):
128 def ass_bool(strvalue):
134 output = '[Script Info]\n'
135 output += 'Title: %s\n' % sub_root.attrib["title"]
136 output += 'ScriptType: v4.00+\n'
137 output += 'WrapStyle: %s\n' % sub_root.attrib["wrap_style"]
138 output += 'PlayResX: %s\n' % sub_root.attrib["play_res_x"]
139 output += 'PlayResY: %s\n' % sub_root.attrib["play_res_y"]
140 output += """ScaledBorderAndShadow: yes
143 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
145 for style in sub_root.findall('./styles/style'):
146 output += 'Style: ' + style.attrib["name"]
147 output += ',' + style.attrib["font_name"]
148 output += ',' + style.attrib["font_size"]
149 output += ',' + style.attrib["primary_colour"]
150 output += ',' + style.attrib["secondary_colour"]
151 output += ',' + style.attrib["outline_colour"]
152 output += ',' + style.attrib["back_colour"]
153 output += ',' + ass_bool(style.attrib["bold"])
154 output += ',' + ass_bool(style.attrib["italic"])
155 output += ',' + ass_bool(style.attrib["underline"])
156 output += ',' + ass_bool(style.attrib["strikeout"])
157 output += ',' + style.attrib["scale_x"]
158 output += ',' + style.attrib["scale_y"]
159 output += ',' + style.attrib["spacing"]
160 output += ',' + style.attrib["angle"]
161 output += ',' + style.attrib["border_style"]
162 output += ',' + style.attrib["outline"]
163 output += ',' + style.attrib["shadow"]
164 output += ',' + style.attrib["alignment"]
165 output += ',' + style.attrib["margin_l"]
166 output += ',' + style.attrib["margin_r"]
167 output += ',' + style.attrib["margin_v"]
168 output += ',' + style.attrib["encoding"]
173 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
175 for event in sub_root.findall('./events/event'):
176 output += 'Dialogue: 0'
177 output += ',' + event.attrib["start"]
178 output += ',' + event.attrib["end"]
179 output += ',' + event.attrib["style"]
180 output += ',' + event.attrib["name"]
181 output += ',' + event.attrib["margin_l"]
182 output += ',' + event.attrib["margin_r"]
183 output += ',' + event.attrib["margin_v"]
184 output += ',' + event.attrib["effect"]
185 output += ',' + event.attrib["text"]
190 def _get_subtitles(self, video_id, webpage):
192 for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
193 sub_page = self._download_webpage(
194 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
195 video_id, note='Downloading subtitles for ' + sub_name)
196 id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
197 iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
198 data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
199 if not id or not iv or not data:
202 iv = base64.b64decode(iv)
203 data = base64.b64decode(data)
205 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
206 lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
209 sub_root = xml.etree.ElementTree.fromstring(subtitle)
210 subtitles[lang_code] = [
213 'data': self._convert_subtitles_to_srt(sub_root),
217 'data': self._convert_subtitles_to_ass(sub_root),
222 def _real_extract(self, url):
223 mobj = re.match(self._VALID_URL, url)
224 video_id = mobj.group('video_id')
226 if mobj.group('prefix') == 'm':
227 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
228 webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
230 webpage_url = 'http://www.' + mobj.group('url')
232 webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
233 note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, 'trailer-notice', default='')
235 raise ExtractorError(note_m)
237 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
239 msg = json.loads(mobj.group('msg'))
240 if msg.get('type') == 'error':
241 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
243 video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
244 video_title = re.sub(r' {2,}', ' ', video_title)
245 video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
246 if not video_description:
247 video_description = None
248 video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
249 if video_upload_date:
250 video_upload_date = unified_strdate(video_upload_date)
251 video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, 'video_uploader', fatal=False, flags=re.DOTALL)
253 playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
254 playerdata_req = compat_urllib_request.Request(playerdata_url)
255 playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
256 playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
257 playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
259 stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
260 video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
263 for fmt in re.findall(r'showmedia\.([0-9]{3,4})p', webpage):
264 stream_quality, stream_format = self._FORMAT_IDS[fmt]
265 video_format = fmt + 'p'
266 streamdata_req = compat_urllib_request.Request('http://www.crunchyroll.com/xml/')
267 # urlencode doesn't work!
268 streamdata_req.data = 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality=' + stream_quality + '&media%5Fid=' + stream_id + '&video%5Fformat=' + stream_format
269 streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
270 streamdata_req.add_header('Content-Length', str(len(streamdata_req.data)))
271 streamdata = self._download_xml(
272 streamdata_req, video_id,
273 note='Downloading media info for %s' % video_format)
274 video_url = streamdata.find('.//host').text
275 video_play_path = streamdata.find('.//file').text
278 'play_path': video_play_path,
280 'format': video_format,
281 'format_id': video_format,
284 subtitles = self.extract_subtitles(video_id, webpage)
288 'title': video_title,
289 'description': video_description,
290 'thumbnail': video_thumbnail,
291 'uploader': video_uploader,
292 'upload_date': video_upload_date,
293 'subtitles': subtitles,
298 class CrunchyrollShowPlaylistIE(InfoExtractor):
299 IE_NAME = "crunchyroll:playlist"
300 _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\-]+))/?$'
303 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
305 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
306 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
308 'playlist_count': 13,
311 def _real_extract(self, url):
312 show_id = self._match_id(url)
314 webpage = self._download_webpage(url, show_id)
315 title = self._html_search_regex(
316 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
318 episode_paths = re.findall(
319 r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
322 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
323 for ep in episode_paths