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