[crunchyroll] Add support for HLS (Closes #10301)
[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
9 from hashlib import sha1
10 from math import pow, sqrt, floor
11 from .common import InfoExtractor
12 from ..compat import (
13     compat_etree_fromstring,
14     compat_urllib_parse_urlencode,
15     compat_urllib_request,
16     compat_urlparse,
17 )
18 from ..utils import (
19     ExtractorError,
20     bytes_to_intlist,
21     intlist_to_bytes,
22     int_or_none,
23     lowercase_escape,
24     remove_end,
25     sanitized_Request,
26     unified_strdate,
27     urlencode_postdata,
28     xpath_text,
29     extract_attributes,
30 )
31 from ..aes import (
32     aes_cbc_decrypt,
33 )
34
35
36 class CrunchyrollBaseIE(InfoExtractor):
37     _NETRC_MACHINE = 'crunchyroll'
38
39     def _login(self):
40         (username, password) = self._get_login_info()
41         if username is None:
42             return
43         self.report_login()
44         login_url = 'https://www.crunchyroll.com/?a=formhandler'
45         data = urlencode_postdata({
46             'formname': 'RpcApiUser_Login',
47             'name': username,
48             'password': password,
49         })
50         login_request = sanitized_Request(login_url, data)
51         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
52         self._download_webpage(login_request, None, False, 'Wrong login info')
53
54     def _real_initialize(self):
55         self._login()
56
57     def _download_webpage(self, url_or_request, *args, **kwargs):
58         request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
59                    else sanitized_Request(url_or_request))
60         # Accept-Language must be set explicitly to accept any language to avoid issues
61         # similar to https://github.com/rg3/youtube-dl/issues/6797.
62         # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
63         # should be imposed or not (from what I can see it just takes the first language
64         # ignoring the priority and requires it to correspond the IP). By the way this causes
65         # Crunchyroll to not work in georestriction cases in some browsers that don't place
66         # the locale lang first in header. However allowing any language seems to workaround the issue.
67         request.add_header('Accept-Language', '*')
68         return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
69
70     @staticmethod
71     def _add_skip_wall(url):
72         parsed_url = compat_urlparse.urlparse(url)
73         qs = compat_urlparse.parse_qs(parsed_url.query)
74         # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
75         # > This content may be inappropriate for some people.
76         # > Are you sure you want to continue?
77         # since it's not disabled by default in crunchyroll account's settings.
78         # See https://github.com/rg3/youtube-dl/issues/7202.
79         qs['skip_wall'] = ['1']
80         return compat_urlparse.urlunparse(
81             parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
82
83
84 class CrunchyrollIE(CrunchyrollBaseIE):
85     _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
86     _TESTS = [{
87         'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
88         'info_dict': {
89             'id': '645513',
90             'ext': 'flv',
91             'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
92             'description': 'md5:2d17137920c64f2f49981a7797d275ef',
93             'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
94             'uploader': 'Yomiuri Telecasting Corporation (YTV)',
95             'upload_date': '20131013',
96             'url': 're:(?!.*&amp)',
97         },
98         'params': {
99             # rtmp
100             'skip_download': True,
101         },
102     }, {
103         'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
104         'info_dict': {
105             'id': '589804',
106             'ext': 'flv',
107             'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
108             'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
109             'thumbnail': 're:^https?://.*\.jpg$',
110             'uploader': 'Danny Choo Network',
111             'upload_date': '20120213',
112         },
113         'params': {
114             # rtmp
115             'skip_download': True,
116         },
117     }, {
118         'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409',
119         'info_dict': {
120             'id': '702409',
121             'ext': 'mp4',
122             'title': 'Re:ZERO -Starting Life in Another World- Episode 5 – The Morning of Our Promise Is Still Distant',
123             'description': 'md5:97664de1ab24bbf77a9c01918cb7dca9',
124             'thumbnail': 're:^https?://.*\.jpg$',
125             'uploader': 'TV TOKYO',
126             'upload_date': '20160508',
127         },
128         'params': {
129             # m3u8 download
130             'skip_download': True,
131         },
132     }, {
133         'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
134         'only_matching': True,
135     }, {
136         # geo-restricted (US), 18+ maturity wall, non-premium available
137         'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
138         'only_matching': True,
139     }]
140
141     _FORMAT_IDS = {
142         '360': ('60', '106'),
143         '480': ('61', '106'),
144         '720': ('62', '106'),
145         '1080': ('80', '108'),
146     }
147
148     def _decrypt_subtitles(self, data, iv, id):
149         data = bytes_to_intlist(base64.b64decode(data.encode('utf-8')))
150         iv = bytes_to_intlist(base64.b64decode(iv.encode('utf-8')))
151         id = int(id)
152
153         def obfuscate_key_aux(count, modulo, start):
154             output = list(start)
155             for _ in range(count):
156                 output.append(output[-1] + output[-2])
157             # cut off start values
158             output = output[2:]
159             output = list(map(lambda x: x % modulo + 33, output))
160             return output
161
162         def obfuscate_key(key):
163             num1 = int(floor(pow(2, 25) * sqrt(6.9)))
164             num2 = (num1 ^ key) << 5
165             num3 = key ^ num1
166             num4 = num3 ^ (num3 >> 3) ^ num2
167             prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
168             shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
169             # Extend 160 Bit hash to 256 Bit
170             return shaHash + [0] * 12
171
172         key = obfuscate_key(id)
173
174         decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
175         return zlib.decompress(decrypted_data)
176
177     def _convert_subtitles_to_srt(self, sub_root):
178         output = ''
179
180         for i, event in enumerate(sub_root.findall('./events/event'), 1):
181             start = event.attrib['start'].replace('.', ',')
182             end = event.attrib['end'].replace('.', ',')
183             text = event.attrib['text'].replace('\\N', '\n')
184             output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
185         return output
186
187     def _convert_subtitles_to_ass(self, sub_root):
188         output = ''
189
190         def ass_bool(strvalue):
191             assvalue = '0'
192             if strvalue == '1':
193                 assvalue = '-1'
194             return assvalue
195
196         output = '[Script Info]\n'
197         output += 'Title: %s\n' % sub_root.attrib['title']
198         output += 'ScriptType: v4.00+\n'
199         output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style']
200         output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x']
201         output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y']
202         output += """ScaledBorderAndShadow: yes
203
204 [V4+ Styles]
205 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
206 """
207         for style in sub_root.findall('./styles/style'):
208             output += 'Style: ' + style.attrib['name']
209             output += ',' + style.attrib['font_name']
210             output += ',' + style.attrib['font_size']
211             output += ',' + style.attrib['primary_colour']
212             output += ',' + style.attrib['secondary_colour']
213             output += ',' + style.attrib['outline_colour']
214             output += ',' + style.attrib['back_colour']
215             output += ',' + ass_bool(style.attrib['bold'])
216             output += ',' + ass_bool(style.attrib['italic'])
217             output += ',' + ass_bool(style.attrib['underline'])
218             output += ',' + ass_bool(style.attrib['strikeout'])
219             output += ',' + style.attrib['scale_x']
220             output += ',' + style.attrib['scale_y']
221             output += ',' + style.attrib['spacing']
222             output += ',' + style.attrib['angle']
223             output += ',' + style.attrib['border_style']
224             output += ',' + style.attrib['outline']
225             output += ',' + style.attrib['shadow']
226             output += ',' + style.attrib['alignment']
227             output += ',' + style.attrib['margin_l']
228             output += ',' + style.attrib['margin_r']
229             output += ',' + style.attrib['margin_v']
230             output += ',' + style.attrib['encoding']
231             output += '\n'
232
233         output += """
234 [Events]
235 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
236 """
237         for event in sub_root.findall('./events/event'):
238             output += 'Dialogue: 0'
239             output += ',' + event.attrib['start']
240             output += ',' + event.attrib['end']
241             output += ',' + event.attrib['style']
242             output += ',' + event.attrib['name']
243             output += ',' + event.attrib['margin_l']
244             output += ',' + event.attrib['margin_r']
245             output += ',' + event.attrib['margin_v']
246             output += ',' + event.attrib['effect']
247             output += ',' + event.attrib['text']
248             output += '\n'
249
250         return output
251
252     def _extract_subtitles(self, subtitle):
253         sub_root = compat_etree_fromstring(subtitle)
254         return [{
255             'ext': 'srt',
256             'data': self._convert_subtitles_to_srt(sub_root),
257         }, {
258             'ext': 'ass',
259             'data': self._convert_subtitles_to_ass(sub_root),
260         }]
261
262     def _get_subtitles(self, video_id, webpage):
263         subtitles = {}
264         for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage):
265             sub_page = self._download_webpage(
266                 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
267                 video_id, note='Downloading subtitles for ' + sub_name)
268             id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
269             iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
270             data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
271             if not id or not iv or not data:
272                 continue
273             subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
274             lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
275             if not lang_code:
276                 continue
277             subtitles[lang_code] = self._extract_subtitles(subtitle)
278         return subtitles
279
280     def _real_extract(self, url):
281         mobj = re.match(self._VALID_URL, url)
282         video_id = mobj.group('video_id')
283
284         if mobj.group('prefix') == 'm':
285             mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
286             webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
287         else:
288             webpage_url = 'http://www.' + mobj.group('url')
289
290         webpage = self._download_webpage(self._add_skip_wall(webpage_url), video_id, 'Downloading webpage')
291         note_m = self._html_search_regex(
292             r'<div class="showmedia-trailer-notice">(.+?)</div>',
293             webpage, 'trailer-notice', default='')
294         if note_m:
295             raise ExtractorError(note_m)
296
297         mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
298         if mobj:
299             msg = json.loads(mobj.group('msg'))
300             if msg.get('type') == 'error':
301                 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
302
303         if 'To view this, please log in to verify you are 18 or older.' in webpage:
304             self.raise_login_required()
305
306         video_title = self._html_search_regex(
307             r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title["\'][^>]*>(?:(?!<h1).)+?)</h1>',
308             webpage, 'video_title')
309         video_title = re.sub(r' {2,}', ' ', video_title)
310         video_description = self._html_search_regex(
311             r'<script[^>]*>\s*.+?\[media_id=%s\].+?"description"\s*:\s*"([^"]+)' % video_id,
312             webpage, 'description', default=None)
313         if video_description:
314             video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
315         video_upload_date = self._html_search_regex(
316             [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
317             webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
318         if video_upload_date:
319             video_upload_date = unified_strdate(video_upload_date)
320         video_uploader = self._html_search_regex(
321             r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', webpage,
322             'video_uploader', fatal=False)
323
324         available_fmts = []
325         for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
326             attrs = extract_attributes(a)
327             href = attrs.get('href')
328             if href and '/freetrial' in href:
329                 continue
330             available_fmts.append(fmt)
331         if not available_fmts:
332             for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'):
333                 available_fmts = re.findall(p, webpage)
334                 if available_fmts:
335                     break
336         video_encode_ids = []
337         formats = []
338         for fmt in available_fmts:
339             stream_quality, stream_format = self._FORMAT_IDS[fmt]
340             video_format = fmt + 'p'
341             streamdata_req = sanitized_Request(
342                 'http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s&video_format=%s&video_quality=%s'
343                 % (video_id, stream_format, stream_quality),
344                 compat_urllib_parse_urlencode({'current_page': url}).encode('utf-8'))
345             streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
346             streamdata = self._download_xml(
347                 streamdata_req, video_id,
348                 note='Downloading media info for %s' % video_format)
349             stream_info = streamdata.find('./{default}preload/stream_info')
350             video_encode_id = xpath_text(stream_info, './video_encode_id')
351             if video_encode_id in video_encode_ids:
352                 continue
353             video_encode_ids.append(video_encode_id)
354
355             video_file = xpath_text(stream_info, './file')
356             if not video_file:
357                 continue
358             if video_file.startswith('http'):
359                 formats.extend(self._extract_m3u8_formats(
360                     video_file, video_id, 'mp4', entry_protocol='m3u8_native',
361                     m3u8_id='hls', fatal=False))
362                 continue
363
364             video_url = xpath_text(stream_info, './host')
365             if not video_url:
366                 continue
367             metadata = stream_info.find('./metadata')
368             format_info = {
369                 'format': video_format,
370                 'format_id': video_format,
371                 'height': int_or_none(xpath_text(metadata, './height')),
372                 'width': int_or_none(xpath_text(metadata, './width')),
373             }
374
375             if '.fplive.net/' in video_url:
376                 video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
377                 parsed_video_url = compat_urlparse.urlparse(video_url)
378                 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
379                     netloc='v.lvlt.crcdn.net',
380                     path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
381                 if self._is_valid_url(direct_video_url, video_id, video_format):
382                     format_info.update({
383                         'url': direct_video_url,
384                     })
385                     formats.append(format_info)
386                     continue
387
388             format_info.update({
389                 'url': video_url,
390                 'play_path': video_file,
391                 'ext': 'flv',
392             })
393             formats.append(format_info)
394         self._sort_formats(formats)
395
396         metadata = self._download_xml(
397             'http://www.crunchyroll.com/xml', video_id,
398             note='Downloading media info', query={
399                 'req': 'RpcApiVideoPlayer_GetMediaMetadata',
400                 'media_id': video_id,
401             })
402
403         subtitles = self.extract_subtitles(video_id, webpage)
404
405         return {
406             'id': video_id,
407             'title': video_title,
408             'description': video_description,
409             'thumbnail': xpath_text(metadata, 'episode_image_url'),
410             'uploader': video_uploader,
411             'upload_date': video_upload_date,
412             'series': xpath_text(metadata, 'series_title'),
413             'episode': xpath_text(metadata, 'episode_title'),
414             'episode_number': int_or_none(xpath_text(metadata, 'episode_number')),
415             'subtitles': subtitles,
416             'formats': formats,
417         }
418
419
420 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
421     IE_NAME = 'crunchyroll:playlist'
422     _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\-]+))/?(?:\?|$)'
423
424     _TESTS = [{
425         'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
426         'info_dict': {
427             'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
428             'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
429         },
430         'playlist_count': 13,
431     }, {
432         # geo-restricted (US), 18+ maturity wall, non-premium available
433         'url': 'http://www.crunchyroll.com/cosplay-complex-ova',
434         'info_dict': {
435             'id': 'cosplay-complex-ova',
436             'title': 'Cosplay Complex OVA'
437         },
438         'playlist_count': 3,
439         'skip': 'Georestricted',
440     }, {
441         # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
442         'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1',
443         'only_matching': True,
444     }]
445
446     def _real_extract(self, url):
447         show_id = self._match_id(url)
448
449         webpage = self._download_webpage(self._add_skip_wall(url), show_id)
450         title = self._html_search_regex(
451             r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
452             webpage, 'title')
453         episode_paths = re.findall(
454             r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
455             webpage)
456         entries = [
457             self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
458             for ep in episode_paths
459         ]
460         entries.reverse()
461
462         return {
463             '_type': 'playlist',
464             'id': show_id,
465             'title': title,
466             'entries': entries,
467         }