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