Merge branch 'master' of https://github.com/linhua55/youtube-dl into linhua55-master
[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_parse_unquote,
16     compat_urllib_request,
17     compat_urlparse,
18 )
19 from ..utils import (
20     ExtractorError,
21     bytes_to_intlist,
22     intlist_to_bytes,
23     int_or_none,
24     remove_end,
25     unified_strdate,
26     urlencode_postdata,
27     xpath_text,
28 )
29 from ..aes import (
30     aes_cbc_decrypt,
31 )
32
33
34 class CrunchyrollBaseIE(InfoExtractor):
35     def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None):
36         request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
37                    else compat_urllib_request.Request(url_or_request))
38         # Accept-Language must be set explicitly to accept any language to avoid issues
39         # similar to https://github.com/rg3/youtube-dl/issues/6797.
40         # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
41         # should be imposed or not (from what I can see it just takes the first language
42         # ignoring the priority and requires it to correspond the IP). By the way this causes
43         # Crunchyroll to not work in georestriction cases in some browsers that don't place
44         # the locale lang first in header. However allowing any language seems to workaround the issue.
45         request.add_header('Accept-Language', '*')
46         return super(CrunchyrollBaseIE, self)._download_webpage(
47             request, video_id, note, errnote, fatal, tries, timeout, encoding)
48
49
50 class CrunchyrollIE(CrunchyrollBaseIE):
51     _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
52     _NETRC_MACHINE = 'crunchyroll'
53     _TESTS = [{
54         'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
55         'info_dict': {
56             'id': '645513',
57             'ext': 'flv',
58             'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
59             'description': 'md5:2d17137920c64f2f49981a7797d275ef',
60             'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
61             'uploader': 'Yomiuri Telecasting Corporation (YTV)',
62             'upload_date': '20131013',
63             'url': 're:(?!.*&amp)',
64         },
65         'params': {
66             # rtmp
67             'skip_download': True,
68         },
69     }, {
70         'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
71         'info_dict': {
72             'id': '589804',
73             'ext': 'flv',
74             'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
75             'description': 'md5:fe2743efedb49d279552926d0bd0cd9e',
76             'thumbnail': 're:^https?://.*\.jpg$',
77             'uploader': 'Danny Choo Network',
78             'upload_date': '20120213',
79         },
80         'params': {
81             # rtmp
82             'skip_download': True,
83         },
84
85     }, {
86         'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
87         'only_matching': True,
88     }]
89
90     _FORMAT_IDS = {
91         '360': ('60', '106'),
92         '480': ('61', '106'),
93         '720': ('62', '106'),
94         '1080': ('80', '108'),
95     }
96
97     def _login(self):
98         (username, password) = self._get_login_info()
99         if username is None:
100             return
101         self.report_login()
102         login_url = 'https://www.crunchyroll.com/?a=formhandler'
103         data = urlencode_postdata({
104             'formname': 'RpcApiUser_Login',
105             'name': username,
106             'password': password,
107         })
108         login_request = compat_urllib_request.Request(login_url, data)
109         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
110         self._download_webpage(login_request, None, False, 'Wrong login info')
111
112     def _real_initialize(self):
113         self._login()
114
115     def _decrypt_subtitles(self, data, iv, id):
116         data = bytes_to_intlist(base64.b64decode(data.encode('utf-8')))
117         iv = bytes_to_intlist(base64.b64decode(iv.encode('utf-8')))
118         id = int(id)
119
120         def obfuscate_key_aux(count, modulo, start):
121             output = list(start)
122             for _ in range(count):
123                 output.append(output[-1] + output[-2])
124             # cut off start values
125             output = output[2:]
126             output = list(map(lambda x: x % modulo + 33, output))
127             return output
128
129         def obfuscate_key(key):
130             num1 = int(floor(pow(2, 25) * sqrt(6.9)))
131             num2 = (num1 ^ key) << 5
132             num3 = key ^ num1
133             num4 = num3 ^ (num3 >> 3) ^ num2
134             prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
135             shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
136             # Extend 160 Bit hash to 256 Bit
137             return shaHash + [0] * 12
138
139         key = obfuscate_key(id)
140
141         decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
142         return zlib.decompress(decrypted_data)
143
144     def _convert_subtitles_to_srt(self, sub_root):
145         output = ''
146
147         for i, event in enumerate(sub_root.findall('./events/event'), 1):
148             start = event.attrib['start'].replace('.', ',')
149             end = event.attrib['end'].replace('.', ',')
150             text = event.attrib['text'].replace('\\N', '\n')
151             output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
152         return output
153
154     def _convert_subtitles_to_ass(self, sub_root):
155         output = ''
156
157         def ass_bool(strvalue):
158             assvalue = '0'
159             if strvalue == '1':
160                 assvalue = '-1'
161             return assvalue
162
163         output = '[Script Info]\n'
164         output += 'Title: %s\n' % sub_root.attrib["title"]
165         output += 'ScriptType: v4.00+\n'
166         output += 'WrapStyle: %s\n' % sub_root.attrib["wrap_style"]
167         output += 'PlayResX: %s\n' % sub_root.attrib["play_res_x"]
168         output += 'PlayResY: %s\n' % sub_root.attrib["play_res_y"]
169         output += """ScaledBorderAndShadow: yes
170
171 [V4+ Styles]
172 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
173 """
174         for style in sub_root.findall('./styles/style'):
175             output += 'Style: ' + style.attrib["name"]
176             output += ',' + style.attrib["font_name"]
177             output += ',' + style.attrib["font_size"]
178             output += ',' + style.attrib["primary_colour"]
179             output += ',' + style.attrib["secondary_colour"]
180             output += ',' + style.attrib["outline_colour"]
181             output += ',' + style.attrib["back_colour"]
182             output += ',' + ass_bool(style.attrib["bold"])
183             output += ',' + ass_bool(style.attrib["italic"])
184             output += ',' + ass_bool(style.attrib["underline"])
185             output += ',' + ass_bool(style.attrib["strikeout"])
186             output += ',' + style.attrib["scale_x"]
187             output += ',' + style.attrib["scale_y"]
188             output += ',' + style.attrib["spacing"]
189             output += ',' + style.attrib["angle"]
190             output += ',' + style.attrib["border_style"]
191             output += ',' + style.attrib["outline"]
192             output += ',' + style.attrib["shadow"]
193             output += ',' + style.attrib["alignment"]
194             output += ',' + style.attrib["margin_l"]
195             output += ',' + style.attrib["margin_r"]
196             output += ',' + style.attrib["margin_v"]
197             output += ',' + style.attrib["encoding"]
198             output += '\n'
199
200         output += """
201 [Events]
202 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
203 """
204         for event in sub_root.findall('./events/event'):
205             output += 'Dialogue: 0'
206             output += ',' + event.attrib["start"]
207             output += ',' + event.attrib["end"]
208             output += ',' + event.attrib["style"]
209             output += ',' + event.attrib["name"]
210             output += ',' + event.attrib["margin_l"]
211             output += ',' + event.attrib["margin_r"]
212             output += ',' + event.attrib["margin_v"]
213             output += ',' + event.attrib["effect"]
214             output += ',' + event.attrib["text"]
215             output += '\n'
216
217         return output
218
219     def _extract_subtitles(self, subtitle):
220         sub_root = xml.etree.ElementTree.fromstring(subtitle)
221         return [{
222             'ext': 'srt',
223             'data': self._convert_subtitles_to_srt(sub_root),
224         }, {
225             'ext': 'ass',
226             'data': self._convert_subtitles_to_ass(sub_root),
227         }]
228
229     def _get_subtitles(self, video_id, webpage):
230         subtitles = {}
231         for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
232             sub_page = self._download_webpage(
233                 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
234                 video_id, note='Downloading subtitles for ' + sub_name)
235             id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
236             iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
237             data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
238             if not id or not iv or not data:
239                 continue
240             subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
241             lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
242             if not lang_code:
243                 continue
244             subtitles[lang_code] = self._extract_subtitles(subtitle)
245         return subtitles
246
247     def _real_extract(self, url):
248         mobj = re.match(self._VALID_URL, url)
249         video_id = mobj.group('video_id')
250
251         if mobj.group('prefix') == 'm':
252             mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
253             webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
254         else:
255             webpage_url = 'http://www.' + mobj.group('url')
256
257         webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
258         note_m = self._html_search_regex(
259             r'<div class="showmedia-trailer-notice">(.+?)</div>',
260             webpage, 'trailer-notice', default='')
261         if note_m:
262             raise ExtractorError(note_m)
263
264         mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
265         if mobj:
266             msg = json.loads(mobj.group('msg'))
267             if msg.get('type') == 'error':
268                 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
269
270         if 'To view this, please log in to verify you are 18 or older.' in webpage:
271             self.raise_login_required()
272
273         video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
274         video_title = re.sub(r' {2,}', ' ', video_title)
275         video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
276         if not video_description:
277             video_description = None
278         video_upload_date = self._html_search_regex(
279             [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
280             webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
281         if video_upload_date:
282             video_upload_date = unified_strdate(video_upload_date)
283         video_uploader = self._html_search_regex(
284             r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', webpage,
285             'video_uploader', fatal=False)
286
287         playerdata_url = compat_urllib_parse_unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
288         playerdata_req = compat_urllib_request.Request(playerdata_url)
289         playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
290         playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
291         playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
292
293         stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
294         video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
295
296         formats = []
297         for fmt in re.findall(r'showmedia\.([0-9]{3,4})p', webpage):
298             stream_quality, stream_format = self._FORMAT_IDS[fmt]
299             video_format = fmt + 'p'
300             streamdata_req = compat_urllib_request.Request(
301                 'http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s&video_format=%s&video_quality=%s'
302                 % (stream_id, stream_format, stream_quality),
303                 compat_urllib_parse.urlencode({'current_page': url}).encode('utf-8'))
304             streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
305             streamdata = self._download_xml(
306                 streamdata_req, video_id,
307                 note='Downloading media info for %s' % video_format)
308             stream_info = streamdata.find('./{default}preload/stream_info')
309             video_url = stream_info.find('./host').text
310             video_play_path = stream_info.find('./file').text
311             metadata = stream_info.find('./metadata')
312             format_info = {
313                 'format': video_format,
314                 'format_id': video_format,
315                 'height': int_or_none(xpath_text(metadata, './height')),
316                 'width': int_or_none(xpath_text(metadata, './width')),
317             }
318
319             if '.fplive.net/' in video_url:
320                 video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
321                 parsed_video_url = compat_urlparse.urlparse(video_url)
322                 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
323                     netloc='v.lvlt.crcdn.net',
324                     path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_play_path.split(':')[-1])))
325                 if self._is_valid_url(direct_video_url, video_id, video_format):
326                     format_info.update({
327                         'url': direct_video_url,
328                     })
329                     formats.append(format_info)
330                     continue
331
332             format_info.update({
333                 'url': video_url,
334                 'play_path': video_play_path,
335                 'ext': 'flv',
336             })
337             formats.append(format_info)
338
339         subtitles = self.extract_subtitles(video_id, webpage)
340
341         return {
342             'id': video_id,
343             'title': video_title,
344             'description': video_description,
345             'thumbnail': video_thumbnail,
346             'uploader': video_uploader,
347             'upload_date': video_upload_date,
348             'subtitles': subtitles,
349             'formats': formats,
350         }
351
352
353 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
354     IE_NAME = "crunchyroll:playlist"
355     _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\-]+))/?$'
356
357     _TESTS = [{
358         'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
359         'info_dict': {
360             'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
361             'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
362         },
363         'playlist_count': 13,
364     }]
365
366     def _real_extract(self, url):
367         show_id = self._match_id(url)
368
369         webpage = self._download_webpage(url, show_id)
370         title = self._html_search_regex(
371             r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
372             webpage, 'title')
373         episode_paths = re.findall(
374             r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
375             webpage)
376         entries = [
377             self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
378             for ep in episode_paths
379         ]
380         entries.reverse()
381
382         return {
383             '_type': 'playlist',
384             'id': show_id,
385             'title': title,
386             'entries': entries,
387         }