Add login support to Crunchyroll extractor
[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 ..utils import (
13     ExtractorError,
14     compat_urllib_parse,
15     compat_urllib_request,
16     bytes_to_intlist,
17     intlist_to_bytes,
18     unified_strdate,
19     clean_html,
20     urlencode_postdata,
21 )
22 from ..aes import (
23     aes_cbc_decrypt,
24     inc,
25 )
26
27
28 class CrunchyrollIE(InfoExtractor):
29     _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
30     _TEST = {
31         'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
32         #'md5': 'b1639fd6ddfaa43788c85f6d1dddd412',
33         'info_dict': {
34             'id': '645513',
35             'ext': 'flv',
36             'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
37             'description': 'md5:2d17137920c64f2f49981a7797d275ef',
38             'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
39             'uploader': 'Yomiuri Telecasting Corporation (YTV)',
40             'upload_date': '20131013',
41         },
42         'params': {
43             # rtmp
44             'skip_download': True,
45         },
46     }
47
48     _FORMAT_IDS = {
49         '360': ('60', '106'),
50         '480': ('61', '106'),
51         '720': ('62', '106'),
52         '1080': ('80', '108'),
53     }
54
55     def _login(self):
56         (username, password) = self._get_login_info()
57         if username is None:
58             return
59         self.report_login()
60         login_url = 'https://www.crunchyroll.com/?a=formhandler'
61         data = urlencode_postdata({
62             'formname': 'RpcApiUser_Login',
63             'name': username,
64             'password': password,
65         })
66         login_request = compat_urllib_request.Request(login_url, data)
67         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
68         self._download_webpage(login_request, None, False, 'Wrong login info')
69
70     def _real_initialize(self):
71         self._login()
72
73     def _decrypt_subtitles(self, data, iv, id):
74         data = bytes_to_intlist(data)
75         iv = bytes_to_intlist(iv)
76         id = int(id)
77
78         def obfuscate_key_aux(count, modulo, start):
79             output = list(start)
80             for _ in range(count):
81                 output.append(output[-1] + output[-2])
82             # cut off start values
83             output = output[2:]
84             output = list(map(lambda x: x % modulo + 33, output))
85             return output
86
87         def obfuscate_key(key):
88             num1 = int(floor(pow(2, 25) * sqrt(6.9)))
89             num2 = (num1 ^ key) << 5
90             num3 = key ^ num1
91             num4 = num3 ^ (num3 >> 3) ^ num2
92             prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
93             shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
94             # Extend 160 Bit hash to 256 Bit
95             return shaHash + [0] * 12
96
97         key = obfuscate_key(id)
98         class Counter:
99             __value = iv
100             def next_value(self):
101                 temp = self.__value
102                 self.__value = inc(self.__value)
103                 return temp
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, subtitles):
108         output = ''
109         for i, (start, end, text) in enumerate(re.findall(r'<event [^>]*?start="([^"]+)" [^>]*?end="([^"]+)" [^>]*?text="([^"]+)"[^>]*?>', subtitles), 1):
110             start = start.replace('.', ',')
111             end = end.replace('.', ',')
112             text = clean_html(text)
113             text = text.replace('\\N', '\n')
114             if not text:
115                 continue
116             output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
117         return output
118
119     def _real_extract(self,url):
120         mobj = re.match(self._VALID_URL, url)
121         video_id = mobj.group('video_id')
122
123         if mobj.group('prefix') == 'm':
124             mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
125             webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
126         else:
127             webpage_url = 'http://www.' + mobj.group('url')
128
129         webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
130         note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, 'trailer-notice', default='')
131         if note_m:
132             raise ExtractorError(note_m)
133
134         mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
135         if mobj:
136             msg = json.loads(mobj.group('msg'))
137             if msg.get('type') == 'error':
138                 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
139
140         video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
141         video_title = re.sub(r' {2,}', ' ', video_title)
142         video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
143         if not video_description:
144             video_description = None
145         video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
146         if video_upload_date:
147             video_upload_date = unified_strdate(video_upload_date)
148         video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, 'video_uploader', fatal=False, flags=re.DOTALL)
149
150         playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
151         playerdata_req = compat_urllib_request.Request(playerdata_url)
152         playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
153         playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
154         playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
155
156         stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
157         video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
158
159         formats = []
160         for fmt in re.findall(r'\?p([0-9]{3,4})=1', webpage):
161             stream_quality, stream_format = self._FORMAT_IDS[fmt]
162             video_format = fmt+'p'
163             streamdata_req = compat_urllib_request.Request('http://www.crunchyroll.com/xml/')
164             # urlencode doesn't work!
165             streamdata_req.data = 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality='+stream_quality+'&media%5Fid='+stream_id+'&video%5Fformat='+stream_format
166             streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
167             streamdata_req.add_header('Content-Length', str(len(streamdata_req.data)))
168             streamdata = self._download_webpage(streamdata_req, video_id, note='Downloading media info for '+video_format)
169             video_url = self._search_regex(r'<host>([^<]+)', streamdata, 'video_url')
170             video_play_path = self._search_regex(r'<file>([^<]+)', streamdata, 'video_play_path')
171             formats.append({
172                 'url': video_url,
173                 'play_path':   video_play_path,
174                 'ext': 'flv',
175                 'format': video_format,
176                 'format_id': video_format,
177             })
178
179         subtitles = {}
180         for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
181             sub_page = self._download_webpage('http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id='+sub_id,\
182                                               video_id, note='Downloading subtitles for '+sub_name)
183             id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
184             iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
185             data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
186             if not id or not iv or not data:
187                 continue
188             id = int(id)
189             iv = base64.b64decode(iv)
190             data = base64.b64decode(data)
191
192             subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
193             lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
194             if not lang_code:
195                 continue
196             subtitles[lang_code] = self._convert_subtitles_to_srt(subtitle)
197
198         return {
199             'id':          video_id,
200             'title':       video_title,
201             'description': video_description,
202             'thumbnail':   video_thumbnail,
203             'uploader':    video_uploader,
204             'upload_date': video_upload_date,
205             'subtitles':   subtitles,
206             'formats':     formats,
207         }