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