Merge remote-tracking branch 'gabeos/crunchyroll-show-playlist'
[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 .subtitles import SubtitlesInfoExtractor
13 from ..utils import (
14     ExtractorError,
15     compat_urllib_parse,
16     compat_urllib_request,
17     bytes_to_intlist,
18     intlist_to_bytes,
19     unified_strdate,
20     clean_html,
21     urlencode_postdata,
22 )
23 from ..aes import (
24     aes_cbc_decrypt,
25     inc,
26 )
27 from .common import InfoExtractor
28
29
30 class CrunchyrollIE(SubtitlesInfoExtractor):
31     _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
32     _TEST = {
33         'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
34         #'md5': 'b1639fd6ddfaa43788c85f6d1dddd412',
35         'info_dict': {
36             'id': '645513',
37             'ext': 'flv',
38             'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
39             'description': 'md5:2d17137920c64f2f49981a7797d275ef',
40             'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
41             'uploader': 'Yomiuri Telecasting Corporation (YTV)',
42             'upload_date': '20131013',
43             'url': 're:(?!.*&amp)',
44         },
45         'params': {
46             # rtmp
47             'skip_download': True,
48         },
49     }
50
51     _FORMAT_IDS = {
52         '360': ('60', '106'),
53         '480': ('61', '106'),
54         '720': ('62', '106'),
55         '1080': ('80', '108'),
56     }
57
58     def _login(self):
59         (username, password) = self._get_login_info()
60         if username is None:
61             return
62         self.report_login()
63         login_url = 'https://www.crunchyroll.com/?a=formhandler'
64         data = urlencode_postdata({
65             'formname': 'RpcApiUser_Login',
66             'name': username,
67             'password': password,
68         })
69         login_request = compat_urllib_request.Request(login_url, data)
70         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
71         self._download_webpage(login_request, None, False, 'Wrong login info')
72
73
74     def _real_initialize(self):
75         self._login()
76
77
78     def _decrypt_subtitles(self, data, iv, id):
79         data = bytes_to_intlist(data)
80         iv = bytes_to_intlist(iv)
81         id = int(id)
82
83         def obfuscate_key_aux(count, modulo, start):
84             output = list(start)
85             for _ in range(count):
86                 output.append(output[-1] + output[-2])
87             # cut off start values
88             output = output[2:]
89             output = list(map(lambda x: x % modulo + 33, output))
90             return output
91
92         def obfuscate_key(key):
93             num1 = int(floor(pow(2, 25) * sqrt(6.9)))
94             num2 = (num1 ^ key) << 5
95             num3 = key ^ num1
96             num4 = num3 ^ (num3 >> 3) ^ num2
97             prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
98             shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
99             # Extend 160 Bit hash to 256 Bit
100             return shaHash + [0] * 12
101
102         key = obfuscate_key(id)
103         class Counter:
104             __value = iv
105             def next_value(self):
106                 temp = self.__value
107                 self.__value = inc(self.__value)
108                 return temp
109         decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
110         return zlib.decompress(decrypted_data)
111
112     def _convert_subtitles_to_srt(self, subtitles):
113         output = ''
114         for i, (start, end, text) in enumerate(re.findall(r'<event [^>]*?start="([^"]+)" [^>]*?end="([^"]+)" [^>]*?text="([^"]+)"[^>]*?>', subtitles), 1):
115             start = start.replace('.', ',')
116             end = end.replace('.', ',')
117             text = clean_html(text)
118             text = text.replace('\\N', '\n')
119             if not text:
120                 continue
121             output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
122         return output
123
124     def _convert_subtitles_to_ass(self, subtitles):
125         output = ''
126
127         def ass_bool(strvalue):
128             assvalue = '0'
129             if strvalue == '1':
130                 assvalue = '-1'
131             return assvalue
132
133         sub_root = xml.etree.ElementTree.fromstring(subtitles)
134         if not sub_root:
135             return output
136
137         output = '[Script Info]\n'
138         output += 'Title: %s\n' % sub_root.attrib["title"]
139         output += 'ScriptType: v4.00+\n'
140         output += 'WrapStyle: %s\n' % sub_root.attrib["wrap_style"]
141         output += 'PlayResX: %s\n' % sub_root.attrib["play_res_x"]
142         output += 'PlayResY: %s\n' % sub_root.attrib["play_res_y"]
143         output += """ScaledBorderAndShadow: yes
144
145 [V4+ Styles]
146 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
147 """
148         for style in sub_root.findall('./styles/style'):
149             output += 'Style: ' + style.attrib["name"]
150             output += ',' + style.attrib["font_name"]
151             output += ',' + style.attrib["font_size"]
152             output += ',' + style.attrib["primary_colour"]
153             output += ',' + style.attrib["secondary_colour"]
154             output += ',' + style.attrib["outline_colour"]
155             output += ',' + style.attrib["back_colour"]
156             output += ',' + ass_bool(style.attrib["bold"])
157             output += ',' + ass_bool(style.attrib["italic"])
158             output += ',' + ass_bool(style.attrib["underline"])
159             output += ',' + ass_bool(style.attrib["strikeout"])
160             output += ',' + style.attrib["scale_x"]
161             output += ',' + style.attrib["scale_y"]
162             output += ',' + style.attrib["spacing"]
163             output += ',' + style.attrib["angle"]
164             output += ',' + style.attrib["border_style"]
165             output += ',' + style.attrib["outline"]
166             output += ',' + style.attrib["shadow"]
167             output += ',' + style.attrib["alignment"]
168             output += ',' + style.attrib["margin_l"]
169             output += ',' + style.attrib["margin_r"]
170             output += ',' + style.attrib["margin_v"]
171             output += ',' + style.attrib["encoding"]
172             output += '\n'
173
174         output += """
175 [Events]
176 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
177 """
178         for event in sub_root.findall('./events/event'):
179             output += 'Dialogue: 0'
180             output += ',' + event.attrib["start"]
181             output += ',' + event.attrib["end"]
182             output += ',' + event.attrib["style"]
183             output += ',' + event.attrib["name"]
184             output += ',' + event.attrib["margin_l"]
185             output += ',' + event.attrib["margin_r"]
186             output += ',' + event.attrib["margin_v"]
187             output += ',' + event.attrib["effect"]
188             output += ',' + event.attrib["text"]
189             output += '\n'
190
191         return output
192
193     def _real_extract(self,url):
194         mobj = re.match(self._VALID_URL, url)
195         video_id = mobj.group('video_id')
196
197         if mobj.group('prefix') == 'm':
198             mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
199             webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
200         else:
201             webpage_url = 'http://www.' + mobj.group('url')
202
203         webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
204         note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, 'trailer-notice', default='')
205         if note_m:
206             raise ExtractorError(note_m)
207
208         mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
209         if mobj:
210             msg = json.loads(mobj.group('msg'))
211             if msg.get('type') == 'error':
212                 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
213
214         video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
215         video_title = re.sub(r' {2,}', ' ', video_title)
216         video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
217         if not video_description:
218             video_description = None
219         video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
220         if video_upload_date:
221             video_upload_date = unified_strdate(video_upload_date)
222         video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, 'video_uploader', fatal=False, flags=re.DOTALL)
223
224         playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
225         playerdata_req = compat_urllib_request.Request(playerdata_url)
226         playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
227         playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
228         playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
229
230         stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
231         video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
232
233         formats = []
234         for fmt in re.findall(r'\?p([0-9]{3,4})=1', webpage):
235             stream_quality, stream_format = self._FORMAT_IDS[fmt]
236             video_format = fmt+'p'
237             streamdata_req = compat_urllib_request.Request('http://www.crunchyroll.com/xml/')
238             # urlencode doesn't work!
239             streamdata_req.data = 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality='+stream_quality+'&media%5Fid='+stream_id+'&video%5Fformat='+stream_format
240             streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
241             streamdata_req.add_header('Content-Length', str(len(streamdata_req.data)))
242             streamdata = self._download_xml(
243                 streamdata_req, video_id,
244                 note='Downloading media info for %s' % video_format)
245             video_url = streamdata.find('.//host').text
246             video_play_path = streamdata.find('.//file').text
247             formats.append({
248                 'url': video_url,
249                 'play_path': video_play_path,
250                 'ext': 'flv',
251                 'format': video_format,
252                 'format_id': video_format,
253             })
254
255         subtitles = {}
256         sub_format = self._downloader.params.get('subtitlesformat', 'srt')
257         for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
258             sub_page = self._download_webpage('http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id='+sub_id,\
259                                               video_id, note='Downloading subtitles for '+sub_name)
260             id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
261             iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
262             data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
263             if not id or not iv or not data:
264                 continue
265             id = int(id)
266             iv = base64.b64decode(iv)
267             data = base64.b64decode(data)
268
269             subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
270             lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
271             if not lang_code:
272                 continue
273             if sub_format == 'ass':
274                 subtitles[lang_code] = self._convert_subtitles_to_ass(subtitle)
275             else:
276                 subtitles[lang_code] = self._convert_subtitles_to_srt(subtitle)
277
278         if self._downloader.params.get('listsubtitles', False):
279             self._list_available_subtitles(video_id, subtitles)
280             return
281
282         return {
283             'id':          video_id,
284             'title':       video_title,
285             'description': video_description,
286             'thumbnail':   video_thumbnail,
287             'uploader':    video_uploader,
288             'upload_date': video_upload_date,
289             'subtitles':   subtitles,
290             'formats':     formats,
291         }
292
293
294 class CrunchyrollShowPlaylistIE(InfoExtractor):
295     IE_NAME = "crunchyroll:playlist"
296     _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login))(?P<show>[\w\-]+))/?$'
297     _TITLE_EXTR = r'<span\s+itemprop="name">\s*(?P<showtitle>[\w\s]+)'
298
299     _TESTS = [{
300         'url' : 'http://www.crunchyroll.com/attack-on-titan',
301         'info_dict' : {
302             'title' : 'Attack on Titan'
303         },
304         'playlist_count' : 15
305     }]
306
307     def _extract_title_entries(self,id,webpage):
308         _EPISODE_ID_EXTR = r'id="showview_videos_media_(?P<vidid>\d+)".*?href="/{0}/(?P<vidurl>[\w\-]+-(?P=vidid))"'.format(id)
309         title = self._html_search_regex(self._TITLE_EXTR,webpage,"title",flags=re.UNICODE|re.MULTILINE)
310         episode_urls = [self.url_result('http://www.crunchyroll.com/{0}/{1}'.format(id, showmatch[1])) for
311                     showmatch in re.findall(_EPISODE_ID_EXTR, webpage,re.UNICODE|re.MULTILINE|re.DOTALL)]
312         episode_urls.reverse()
313         return title, episode_urls
314
315
316     def _real_extract(self, url):
317         url_match = re.match(self._VALID_URL,url)
318         show_id = url_match.group('show')
319         webpage = self._download_webpage(url,show_id)
320         (title,entries) = self._extract_title_entries(show_id,webpage)
321         return {
322             '_type' : 'playlist',
323             'id' : show_id,
324             'title' : title,
325             'entries' : entries
326         }