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