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