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