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