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