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