]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/crunchyroll.py
90a64303d3282c925d1620787922622e99a8b612
[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
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,
16 compat_urlparse,
17 )
18 from ..utils import (
19 ExtractorError,
20 bytes_to_intlist,
21 intlist_to_bytes,
22 int_or_none,
23 lowercase_escape,
24 remove_end,
25 sanitized_Request,
26 unified_strdate,
27 urlencode_postdata,
28 xpath_text,
29 extract_attributes,
30 )
31 from ..aes import (
32 aes_cbc_decrypt,
33 )
34
35
36 class CrunchyrollBaseIE(InfoExtractor):
37 _NETRC_MACHINE = 'crunchyroll'
38
39 def _login(self):
40 (username, password) = self._get_login_info()
41 if username is None:
42 return
43 self.report_login()
44 login_url = 'https://www.crunchyroll.com/?a=formhandler'
45 data = urlencode_postdata({
46 'formname': 'RpcApiUser_Login',
47 'name': username,
48 'password': password,
49 })
50 login_request = sanitized_Request(login_url, data)
51 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
52 self._download_webpage(login_request, None, False, 'Wrong login info')
53
54 def _real_initialize(self):
55 self._login()
56
57 def _download_webpage(self, url_or_request, *args, **kwargs):
58 request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
59 else sanitized_Request(url_or_request))
60 # Accept-Language must be set explicitly to accept any language to avoid issues
61 # similar to https://github.com/rg3/youtube-dl/issues/6797.
62 # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
63 # should be imposed or not (from what I can see it just takes the first language
64 # ignoring the priority and requires it to correspond the IP). By the way this causes
65 # Crunchyroll to not work in georestriction cases in some browsers that don't place
66 # the locale lang first in header. However allowing any language seems to workaround the issue.
67 request.add_header('Accept-Language', '*')
68 return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
69
70 @staticmethod
71 def _add_skip_wall(url):
72 parsed_url = compat_urlparse.urlparse(url)
73 qs = compat_urlparse.parse_qs(parsed_url.query)
74 # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
75 # > This content may be inappropriate for some people.
76 # > Are you sure you want to continue?
77 # since it's not disabled by default in crunchyroll account's settings.
78 # See https://github.com/rg3/youtube-dl/issues/7202.
79 qs['skip_wall'] = ['1']
80 return compat_urlparse.urlunparse(
81 parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
82
83
84 class CrunchyrollIE(CrunchyrollBaseIE):
85 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
86 _TESTS = [{
87 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
88 'info_dict': {
89 'id': '645513',
90 'ext': 'flv',
91 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
92 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
93 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
94 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
95 'upload_date': '20131013',
96 'url': 're:(?!.*&amp)',
97 },
98 'params': {
99 # rtmp
100 'skip_download': True,
101 },
102 }, {
103 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
104 'info_dict': {
105 'id': '589804',
106 'ext': 'flv',
107 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
108 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
109 'thumbnail': 're:^https?://.*\.jpg$',
110 'uploader': 'Danny Choo Network',
111 'upload_date': '20120213',
112 },
113 'params': {
114 # rtmp
115 'skip_download': True,
116 },
117 }, {
118 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
119 'only_matching': True,
120 }, {
121 # geo-restricted (US), 18+ maturity wall, non-premium available
122 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
123 'only_matching': True,
124 }]
125
126 _FORMAT_IDS = {
127 '360': ('60', '106'),
128 '480': ('61', '106'),
129 '720': ('62', '106'),
130 '1080': ('80', '108'),
131 }
132
133 def _decrypt_subtitles(self, data, iv, id):
134 data = bytes_to_intlist(base64.b64decode(data.encode('utf-8')))
135 iv = bytes_to_intlist(base64.b64decode(iv.encode('utf-8')))
136 id = int(id)
137
138 def obfuscate_key_aux(count, modulo, start):
139 output = list(start)
140 for _ in range(count):
141 output.append(output[-1] + output[-2])
142 # cut off start values
143 output = output[2:]
144 output = list(map(lambda x: x % modulo + 33, output))
145 return output
146
147 def obfuscate_key(key):
148 num1 = int(floor(pow(2, 25) * sqrt(6.9)))
149 num2 = (num1 ^ key) << 5
150 num3 = key ^ num1
151 num4 = num3 ^ (num3 >> 3) ^ num2
152 prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
153 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
154 # Extend 160 Bit hash to 256 Bit
155 return shaHash + [0] * 12
156
157 key = obfuscate_key(id)
158
159 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
160 return zlib.decompress(decrypted_data)
161
162 def _convert_subtitles_to_srt(self, sub_root):
163 output = ''
164
165 for i, event in enumerate(sub_root.findall('./events/event'), 1):
166 start = event.attrib['start'].replace('.', ',')
167 end = event.attrib['end'].replace('.', ',')
168 text = event.attrib['text'].replace('\\N', '\n')
169 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
170 return output
171
172 def _convert_subtitles_to_ass(self, sub_root):
173 output = ''
174
175 def ass_bool(strvalue):
176 assvalue = '0'
177 if strvalue == '1':
178 assvalue = '-1'
179 return assvalue
180
181 output = '[Script Info]\n'
182 output += 'Title: %s\n' % sub_root.attrib['title']
183 output += 'ScriptType: v4.00+\n'
184 output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style']
185 output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x']
186 output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y']
187 output += """ScaledBorderAndShadow: yes
188
189 [V4+ Styles]
190 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
191 """
192 for style in sub_root.findall('./styles/style'):
193 output += 'Style: ' + style.attrib['name']
194 output += ',' + style.attrib['font_name']
195 output += ',' + style.attrib['font_size']
196 output += ',' + style.attrib['primary_colour']
197 output += ',' + style.attrib['secondary_colour']
198 output += ',' + style.attrib['outline_colour']
199 output += ',' + style.attrib['back_colour']
200 output += ',' + ass_bool(style.attrib['bold'])
201 output += ',' + ass_bool(style.attrib['italic'])
202 output += ',' + ass_bool(style.attrib['underline'])
203 output += ',' + ass_bool(style.attrib['strikeout'])
204 output += ',' + style.attrib['scale_x']
205 output += ',' + style.attrib['scale_y']
206 output += ',' + style.attrib['spacing']
207 output += ',' + style.attrib['angle']
208 output += ',' + style.attrib['border_style']
209 output += ',' + style.attrib['outline']
210 output += ',' + style.attrib['shadow']
211 output += ',' + style.attrib['alignment']
212 output += ',' + style.attrib['margin_l']
213 output += ',' + style.attrib['margin_r']
214 output += ',' + style.attrib['margin_v']
215 output += ',' + style.attrib['encoding']
216 output += '\n'
217
218 output += """
219 [Events]
220 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
221 """
222 for event in sub_root.findall('./events/event'):
223 output += 'Dialogue: 0'
224 output += ',' + event.attrib['start']
225 output += ',' + event.attrib['end']
226 output += ',' + event.attrib['style']
227 output += ',' + event.attrib['name']
228 output += ',' + event.attrib['margin_l']
229 output += ',' + event.attrib['margin_r']
230 output += ',' + event.attrib['margin_v']
231 output += ',' + event.attrib['effect']
232 output += ',' + event.attrib['text']
233 output += '\n'
234
235 return output
236
237 def _extract_subtitles(self, subtitle):
238 sub_root = compat_etree_fromstring(subtitle)
239 return [{
240 'ext': 'srt',
241 'data': self._convert_subtitles_to_srt(sub_root),
242 }, {
243 'ext': 'ass',
244 'data': self._convert_subtitles_to_ass(sub_root),
245 }]
246
247 def _get_subtitles(self, video_id, webpage):
248 subtitles = {}
249 for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage):
250 sub_page = self._download_webpage(
251 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
252 video_id, note='Downloading subtitles for ' + sub_name)
253 id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
254 iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
255 data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
256 if not id or not iv or not data:
257 continue
258 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
259 lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
260 if not lang_code:
261 continue
262 subtitles[lang_code] = self._extract_subtitles(subtitle)
263 return subtitles
264
265 def _real_extract(self, url):
266 mobj = re.match(self._VALID_URL, url)
267 video_id = mobj.group('video_id')
268
269 if mobj.group('prefix') == 'm':
270 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
271 webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
272 else:
273 webpage_url = 'http://www.' + mobj.group('url')
274
275 webpage = self._download_webpage(self._add_skip_wall(webpage_url), video_id, 'Downloading webpage')
276 note_m = self._html_search_regex(
277 r'<div class="showmedia-trailer-notice">(.+?)</div>',
278 webpage, 'trailer-notice', default='')
279 if note_m:
280 raise ExtractorError(note_m)
281
282 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
283 if mobj:
284 msg = json.loads(mobj.group('msg'))
285 if msg.get('type') == 'error':
286 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
287
288 if 'To view this, please log in to verify you are 18 or older.' in webpage:
289 self.raise_login_required()
290
291 video_title = self._html_search_regex(
292 r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title["\'][^>]*>(?:(?!<h1).)+?)</h1>',
293 webpage, 'video_title')
294 video_title = re.sub(r' {2,}', ' ', video_title)
295 video_description = self._html_search_regex(
296 r'<script[^>]*>\s*.+?\[media_id=%s\].+?"description"\s*:\s*"([^"]+)' % video_id,
297 webpage, 'description', default=None)
298 if video_description:
299 video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
300 video_upload_date = self._html_search_regex(
301 [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
302 webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
303 if video_upload_date:
304 video_upload_date = unified_strdate(video_upload_date)
305 video_uploader = self._html_search_regex(
306 r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', webpage,
307 'video_uploader', fatal=False)
308
309 available_fmts = []
310 for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
311 attrs = extract_attributes(a)
312 href = attrs.get('href')
313 if href and '/freetrial' in href:
314 continue
315 available_fmts.append(fmt)
316 if not available_fmts:
317 for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'):
318 available_fmts = re.findall(p, webpage)
319 if available_fmts:
320 break
321 video_encode_ids = []
322 formats = []
323 for fmt in available_fmts:
324 stream_quality, stream_format = self._FORMAT_IDS[fmt]
325 video_format = fmt + 'p'
326 streamdata_req = sanitized_Request(
327 'http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s&video_format=%s&video_quality=%s'
328 % (video_id, stream_format, stream_quality),
329 compat_urllib_parse_urlencode({'current_page': url}).encode('utf-8'))
330 streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
331 streamdata = self._download_xml(
332 streamdata_req, video_id,
333 note='Downloading media info for %s' % video_format)
334 stream_info = streamdata.find('./{default}preload/stream_info')
335 video_encode_id = xpath_text(stream_info, './video_encode_id')
336 if video_encode_id in video_encode_ids:
337 continue
338 video_encode_ids.append(video_encode_id)
339 video_url = xpath_text(stream_info, './host')
340 video_play_path = xpath_text(stream_info, './file')
341 if not video_url or not video_play_path:
342 continue
343 metadata = stream_info.find('./metadata')
344 format_info = {
345 'format': video_format,
346 'format_id': video_format,
347 'height': int_or_none(xpath_text(metadata, './height')),
348 'width': int_or_none(xpath_text(metadata, './width')),
349 }
350
351 if '.fplive.net/' in video_url:
352 video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
353 parsed_video_url = compat_urlparse.urlparse(video_url)
354 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
355 netloc='v.lvlt.crcdn.net',
356 path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_play_path.split(':')[-1])))
357 if self._is_valid_url(direct_video_url, video_id, video_format):
358 format_info.update({
359 'url': direct_video_url,
360 })
361 formats.append(format_info)
362 continue
363
364 format_info.update({
365 'url': video_url,
366 'play_path': video_play_path,
367 'ext': 'flv',
368 })
369 formats.append(format_info)
370 self._sort_formats(formats)
371
372 metadata = self._download_xml(
373 'http://www.crunchyroll.com/xml', video_id,
374 note='Downloading media info', query={
375 'req': 'RpcApiVideoPlayer_GetMediaMetadata',
376 'media_id': video_id,
377 })
378
379 subtitles = self.extract_subtitles(video_id, webpage)
380
381 return {
382 'id': video_id,
383 'title': video_title,
384 'description': video_description,
385 'thumbnail': xpath_text(metadata, 'episode_image_url'),
386 'uploader': video_uploader,
387 'upload_date': video_upload_date,
388 'series': xpath_text(metadata, 'series_title'),
389 'episode': xpath_text(metadata, 'episode_title'),
390 'episode_number': int_or_none(xpath_text(metadata, 'episode_number')),
391 'subtitles': subtitles,
392 'formats': formats,
393 }
394
395
396 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
397 IE_NAME = 'crunchyroll:playlist'
398 _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\-]+))/?(?:\?|$)'
399
400 _TESTS = [{
401 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
402 'info_dict': {
403 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
404 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
405 },
406 'playlist_count': 13,
407 }, {
408 # geo-restricted (US), 18+ maturity wall, non-premium available
409 'url': 'http://www.crunchyroll.com/cosplay-complex-ova',
410 'info_dict': {
411 'id': 'cosplay-complex-ova',
412 'title': 'Cosplay Complex OVA'
413 },
414 'playlist_count': 3,
415 'skip': 'Georestricted',
416 }, {
417 # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
418 'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1',
419 'only_matching': True,
420 }]
421
422 def _real_extract(self, url):
423 show_id = self._match_id(url)
424
425 webpage = self._download_webpage(self._add_skip_wall(url), show_id)
426 title = self._html_search_regex(
427 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
428 webpage, 'title')
429 episode_paths = re.findall(
430 r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
431 webpage)
432 entries = [
433 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
434 for ep in episode_paths
435 ]
436 entries.reverse()
437
438 return {
439 '_type': 'playlist',
440 'id': show_id,
441 'title': title,
442 'entries': entries,
443 }