]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/crunchyroll.py
1c77df47ef346173fc11a58396c98768e5afc986
[youtubedl] / youtube_dl / extractor / crunchyroll.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 import base64
7 import zlib
8 import xml.etree.ElementTree
9
10 from hashlib import sha1
11 from math import pow, sqrt, floor
12 from .common import InfoExtractor
13 from ..compat import (
14 compat_urllib_parse,
15 compat_urllib_request,
16 )
17 from ..utils import (
18 ExtractorError,
19 bytes_to_intlist,
20 intlist_to_bytes,
21 unified_strdate,
22 urlencode_postdata,
23 )
24 from ..aes import (
25 aes_cbc_decrypt,
26 )
27
28
29 class CrunchyrollIE(InfoExtractor):
30 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
31 _NETRC_MACHINE = 'crunchyroll'
32 _TESTS = [{
33 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
34 'info_dict': {
35 'id': '645513',
36 'ext': 'flv',
37 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
38 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
39 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
40 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
41 'upload_date': '20131013',
42 'url': 're:(?!.*&amp)',
43 },
44 'params': {
45 # rtmp
46 'skip_download': True,
47 },
48 }, {
49 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
50 'only_matching': True,
51 }]
52
53 _FORMAT_IDS = {
54 '360': ('60', '106'),
55 '480': ('61', '106'),
56 '720': ('62', '106'),
57 '1080': ('80', '108'),
58 }
59
60 def _login(self):
61 (username, password) = self._get_login_info()
62 if username is None:
63 return
64 self.report_login()
65 login_url = 'https://www.crunchyroll.com/?a=formhandler'
66 data = urlencode_postdata({
67 'formname': 'RpcApiUser_Login',
68 'name': username,
69 'password': password,
70 })
71 login_request = compat_urllib_request.Request(login_url, data)
72 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
73 self._download_webpage(login_request, None, False, 'Wrong login info')
74
75 def _real_initialize(self):
76 self._login()
77
78 def _decrypt_subtitles(self, data, iv, id):
79 data = bytes_to_intlist(data)
80 iv = bytes_to_intlist(iv)
81 id = int(id)
82
83 def obfuscate_key_aux(count, modulo, start):
84 output = list(start)
85 for _ in range(count):
86 output.append(output[-1] + output[-2])
87 # cut off start values
88 output = output[2:]
89 output = list(map(lambda x: x % modulo + 33, output))
90 return output
91
92 def obfuscate_key(key):
93 num1 = int(floor(pow(2, 25) * sqrt(6.9)))
94 num2 = (num1 ^ key) << 5
95 num3 = key ^ num1
96 num4 = num3 ^ (num3 >> 3) ^ num2
97 prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
98 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
99 # Extend 160 Bit hash to 256 Bit
100 return shaHash + [0] * 12
101
102 key = obfuscate_key(id)
103
104 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
105 return zlib.decompress(decrypted_data)
106
107 def _convert_subtitles_to_srt(self, sub_root):
108 output = ''
109
110 for i, event in enumerate(sub_root.findall('./events/event'), 1):
111 start = event.attrib['start'].replace('.', ',')
112 end = event.attrib['end'].replace('.', ',')
113 text = event.attrib['text'].replace('\\N', '\n')
114 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
115 return output
116
117 def _convert_subtitles_to_ass(self, sub_root):
118 output = ''
119
120 def ass_bool(strvalue):
121 assvalue = '0'
122 if strvalue == '1':
123 assvalue = '-1'
124 return assvalue
125
126 output = '[Script Info]\n'
127 output += 'Title: %s\n' % sub_root.attrib["title"]
128 output += 'ScriptType: v4.00+\n'
129 output += 'WrapStyle: %s\n' % sub_root.attrib["wrap_style"]
130 output += 'PlayResX: %s\n' % sub_root.attrib["play_res_x"]
131 output += 'PlayResY: %s\n' % sub_root.attrib["play_res_y"]
132 output += """ScaledBorderAndShadow: yes
133
134 [V4+ Styles]
135 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
136 """
137 for style in sub_root.findall('./styles/style'):
138 output += 'Style: ' + style.attrib["name"]
139 output += ',' + style.attrib["font_name"]
140 output += ',' + style.attrib["font_size"]
141 output += ',' + style.attrib["primary_colour"]
142 output += ',' + style.attrib["secondary_colour"]
143 output += ',' + style.attrib["outline_colour"]
144 output += ',' + style.attrib["back_colour"]
145 output += ',' + ass_bool(style.attrib["bold"])
146 output += ',' + ass_bool(style.attrib["italic"])
147 output += ',' + ass_bool(style.attrib["underline"])
148 output += ',' + ass_bool(style.attrib["strikeout"])
149 output += ',' + style.attrib["scale_x"]
150 output += ',' + style.attrib["scale_y"]
151 output += ',' + style.attrib["spacing"]
152 output += ',' + style.attrib["angle"]
153 output += ',' + style.attrib["border_style"]
154 output += ',' + style.attrib["outline"]
155 output += ',' + style.attrib["shadow"]
156 output += ',' + style.attrib["alignment"]
157 output += ',' + style.attrib["margin_l"]
158 output += ',' + style.attrib["margin_r"]
159 output += ',' + style.attrib["margin_v"]
160 output += ',' + style.attrib["encoding"]
161 output += '\n'
162
163 output += """
164 [Events]
165 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
166 """
167 for event in sub_root.findall('./events/event'):
168 output += 'Dialogue: 0'
169 output += ',' + event.attrib["start"]
170 output += ',' + event.attrib["end"]
171 output += ',' + event.attrib["style"]
172 output += ',' + event.attrib["name"]
173 output += ',' + event.attrib["margin_l"]
174 output += ',' + event.attrib["margin_r"]
175 output += ',' + event.attrib["margin_v"]
176 output += ',' + event.attrib["effect"]
177 output += ',' + event.attrib["text"]
178 output += '\n'
179
180 return output
181
182 def _get_subtitles(self, video_id, webpage):
183 subtitles = {}
184 for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
185 sub_page = self._download_webpage(
186 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
187 video_id, note='Downloading subtitles for ' + sub_name)
188 id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
189 iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
190 data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
191 if not id or not iv or not data:
192 continue
193 id = int(id)
194 iv = base64.b64decode(iv)
195 data = base64.b64decode(data)
196
197 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
198 lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
199 if not lang_code:
200 continue
201 sub_root = xml.etree.ElementTree.fromstring(subtitle)
202 subtitles[lang_code] = [
203 {
204 'ext': 'srt',
205 'data': self._convert_subtitles_to_srt(sub_root),
206 },
207 {
208 'ext': 'ass',
209 'data': self._convert_subtitles_to_ass(sub_root),
210 },
211 ]
212 return subtitles
213
214 def _real_extract(self, url):
215 mobj = re.match(self._VALID_URL, url)
216 video_id = mobj.group('video_id')
217
218 if mobj.group('prefix') == 'm':
219 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
220 webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
221 else:
222 webpage_url = 'http://www.' + mobj.group('url')
223
224 webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
225 note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, 'trailer-notice', default='')
226 if note_m:
227 raise ExtractorError(note_m)
228
229 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
230 if mobj:
231 msg = json.loads(mobj.group('msg'))
232 if msg.get('type') == 'error':
233 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
234
235 video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
236 video_title = re.sub(r' {2,}', ' ', video_title)
237 video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
238 if not video_description:
239 video_description = None
240 video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
241 if video_upload_date:
242 video_upload_date = unified_strdate(video_upload_date)
243 video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, 'video_uploader', fatal=False, flags=re.DOTALL)
244
245 playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
246 playerdata_req = compat_urllib_request.Request(playerdata_url)
247 playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
248 playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
249 playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
250
251 stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
252 video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
253
254 formats = []
255 for fmt in re.findall(r'showmedia\.([0-9]{3,4})p', webpage):
256 stream_quality, stream_format = self._FORMAT_IDS[fmt]
257 video_format = fmt + 'p'
258 streamdata_req = compat_urllib_request.Request('http://www.crunchyroll.com/xml/')
259 # urlencode doesn't work!
260 streamdata_req.data = 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality=' + stream_quality + '&media%5Fid=' + stream_id + '&video%5Fformat=' + stream_format
261 streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
262 streamdata_req.add_header('Content-Length', str(len(streamdata_req.data)))
263 streamdata = self._download_xml(
264 streamdata_req, video_id,
265 note='Downloading media info for %s' % video_format)
266 video_url = streamdata.find('./host').text
267 video_play_path = streamdata.find('./file').text
268 formats.append({
269 'url': video_url,
270 'play_path': video_play_path,
271 'ext': 'flv',
272 'format': video_format,
273 'format_id': video_format,
274 })
275
276 subtitles = self.extract_subtitles(video_id, webpage)
277
278 return {
279 'id': video_id,
280 'title': video_title,
281 'description': video_description,
282 'thumbnail': video_thumbnail,
283 'uploader': video_uploader,
284 'upload_date': video_upload_date,
285 'subtitles': subtitles,
286 'formats': formats,
287 }
288
289
290 class CrunchyrollShowPlaylistIE(InfoExtractor):
291 IE_NAME = "crunchyroll:playlist"
292 _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\-]+))/?$'
293
294 _TESTS = [{
295 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
296 'info_dict': {
297 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
298 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
299 },
300 'playlist_count': 13,
301 }]
302
303 def _real_extract(self, url):
304 show_id = self._match_id(url)
305
306 webpage = self._download_webpage(url, show_id)
307 title = self._html_search_regex(
308 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
309 webpage, 'title')
310 episode_paths = re.findall(
311 r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
312 webpage)
313 entries = [
314 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
315 for ep in episode_paths
316 ]
317 entries.reverse()
318
319 return {
320 '_type': 'playlist',
321 'id': show_id,
322 'title': title,
323 'entries': entries,
324 }