]>
Commit | Line | Data |
---|---|---|
dcdb292f | 1 | # coding: utf-8 |
38a40276 | 2 | from __future__ import unicode_literals |
3 | ||
34440095 | 4 | import re |
1d430674 | 5 | import json |
34440095 S |
6 | import zlib |
7 | ||
c8434e83 | 8 | from hashlib import sha1 |
9 | from math import pow, sqrt, floor | |
46279958 | 10 | from .common import InfoExtractor |
54a5be4d | 11 | from .vrv import VRVIE |
1cc79574 | 12 | from ..compat import ( |
cf282071 | 13 | compat_b64decode, |
ee0ba927 | 14 | compat_etree_Element, |
36e6f62c | 15 | compat_etree_fromstring, |
6ffc3cf7 | 16 | compat_str, |
15707c7e | 17 | compat_urllib_parse_urlencode, |
c8434e83 | 18 | compat_urllib_request, |
a01da8bb | 19 | compat_urlparse, |
1cc79574 PH |
20 | ) |
21 | from ..utils import ( | |
22 | ExtractorError, | |
c8434e83 | 23 | bytes_to_intlist, |
54a5be4d RA |
24 | extract_attributes, |
25 | float_or_none, | |
c8434e83 | 26 | intlist_to_bytes, |
725d1c58 | 27 | int_or_none, |
6d02b9a3 | 28 | lowercase_escape, |
6ffc3cf7 | 29 | merge_dicts, |
a01da8bb | 30 | remove_end, |
5c2266df | 31 | sanitized_Request, |
723e04d0 | 32 | urlencode_postdata, |
725d1c58 | 33 | xpath_text, |
c8434e83 | 34 | ) |
35 | from ..aes import ( | |
36 | aes_cbc_decrypt, | |
c8434e83 | 37 | ) |
38 | ||
34440095 | 39 | |
46279958 | 40 | class CrunchyrollBaseIE(InfoExtractor): |
eb5b1fc0 S |
41 | _LOGIN_URL = 'https://www.crunchyroll.com/login' |
42 | _LOGIN_FORM = 'login_form' | |
80f48920 S |
43 | _NETRC_MACHINE = 'crunchyroll' |
44 | ||
05dee6c5 RA |
45 | def _call_rpc_api(self, method, video_id, note=None, data=None): |
46 | data = data or {} | |
47 | data['req'] = 'RpcApi' + method | |
48 | data = compat_urllib_parse_urlencode(data).encode('utf-8') | |
49 | return self._download_xml( | |
d98cb62e | 50 | 'https://www.crunchyroll.com/xml/', |
05dee6c5 RA |
51 | video_id, note, fatal=False, data=data, headers={ |
52 | 'Content-Type': 'application/x-www-form-urlencoded', | |
53 | }) | |
54 | ||
80f48920 | 55 | def _login(self): |
68217024 | 56 | username, password = self._get_login_info() |
80f48920 S |
57 | if username is None: |
58 | return | |
eb5b1fc0 S |
59 | |
60 | login_page = self._download_webpage( | |
61 | self._LOGIN_URL, None, 'Downloading login page') | |
62 | ||
70b4cf9b | 63 | def is_logged(webpage): |
a8f83f0c | 64 | return 'href="/logout"' in webpage |
70b4cf9b S |
65 | |
66 | # Already logged in | |
67 | if is_logged(login_page): | |
68 | return | |
69 | ||
eb5b1fc0 S |
70 | login_form_str = self._search_regex( |
71 | r'(?P<form><form[^>]+?id=(["\'])%s\2[^>]*>)' % self._LOGIN_FORM, | |
72 | login_page, 'login form', group='form') | |
73 | ||
74 | post_url = extract_attributes(login_form_str).get('action') | |
75 | if not post_url: | |
76 | post_url = self._LOGIN_URL | |
77 | elif not post_url.startswith('http'): | |
78 | post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url) | |
79 | ||
80 | login_form = self._form_hidden_inputs(self._LOGIN_FORM, login_page) | |
81 | ||
82 | login_form.update({ | |
83 | 'login_form[name]': username, | |
84 | 'login_form[password]': password, | |
80f48920 | 85 | }) |
eb5b1fc0 S |
86 | |
87 | response = self._download_webpage( | |
88 | post_url, None, 'Logging in', 'Wrong login info', | |
89 | data=urlencode_postdata(login_form), | |
90 | headers={'Content-Type': 'application/x-www-form-urlencoded'}) | |
91 | ||
92 | # Successful login | |
70b4cf9b | 93 | if is_logged(response): |
eb5b1fc0 S |
94 | return |
95 | ||
96 | error = self._html_search_regex( | |
97 | '(?s)<ul[^>]+class=["\']messages["\'][^>]*>(.+?)</ul>', | |
98 | response, 'error message', default=None) | |
99 | if error: | |
100 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
101 | ||
102 | raise ExtractorError('Unable to log in') | |
80f48920 S |
103 | |
104 | def _real_initialize(self): | |
105 | self._login() | |
106 | ||
80f48920 S |
107 | @staticmethod |
108 | def _add_skip_wall(url): | |
109 | parsed_url = compat_urlparse.urlparse(url) | |
110 | qs = compat_urlparse.parse_qs(parsed_url.query) | |
111 | # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message: | |
112 | # > This content may be inappropriate for some people. | |
113 | # > Are you sure you want to continue? | |
114 | # since it's not disabled by default in crunchyroll account's settings. | |
067aa17e | 115 | # See https://github.com/ytdl-org/youtube-dl/issues/7202. |
80f48920 S |
116 | qs['skip_wall'] = ['1'] |
117 | return compat_urlparse.urlunparse( | |
15707c7e | 118 | parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True))) |
80f48920 | 119 | |
12810c9c | 120 | |
46279958 RA |
121 | class CrunchyrollIE(CrunchyrollBaseIE, VRVIE): |
122 | IE_NAME = 'crunchyroll' | |
d3d8d818 | 123 | _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|(?:[^/]*/){1,2}[^/?&]*?)(?P<id>[0-9]+))(?:[/?&]|$)' |
a8896c5a | 124 | _TESTS = [{ |
38a40276 | 125 | 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513', |
38a40276 | 126 | 'info_dict': { |
34440095 | 127 | 'id': '645513', |
b5869560 | 128 | 'ext': 'mp4', |
38a40276 | 129 | 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!', |
130 | 'description': 'md5:2d17137920c64f2f49981a7797d275ef', | |
54a5be4d | 131 | 'thumbnail': r're:^https?://.*\.jpg$', |
38a40276 | 132 | 'uploader': 'Yomiuri Telecasting Corporation (YTV)', |
133 | 'upload_date': '20131013', | |
b1edd7a4 | 134 | 'url': 're:(?!.*&)', |
c8434e83 | 135 | }, |
38a40276 | 136 | 'params': { |
c8434e83 | 137 | # rtmp |
38a40276 | 138 | 'skip_download': True, |
c8434e83 | 139 | }, |
6ffc3cf7 | 140 | 'skip': 'Video gone', |
ede21449 S |
141 | }, { |
142 | 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1', | |
143 | 'info_dict': { | |
144 | 'id': '589804', | |
145 | 'ext': 'flv', | |
146 | 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11', | |
6d02b9a3 | 147 | 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12', |
ec85ded8 | 148 | 'thumbnail': r're:^https?://.*\.jpg$', |
ede21449 S |
149 | 'uploader': 'Danny Choo Network', |
150 | 'upload_date': '20120213', | |
151 | }, | |
152 | 'params': { | |
153 | # rtmp | |
154 | 'skip_download': True, | |
155 | }, | |
77c5b98d | 156 | 'skip': 'Video gone', |
990d533e S |
157 | }, { |
158 | 'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409', | |
159 | 'info_dict': { | |
160 | 'id': '702409', | |
161 | 'ext': 'mp4', | |
6ffc3cf7 S |
162 | 'title': compat_str, |
163 | 'description': compat_str, | |
ec85ded8 | 164 | 'thumbnail': r're:^https?://.*\.jpg$', |
6ffc3cf7 S |
165 | 'uploader': 'Re:Zero Partners', |
166 | 'timestamp': 1462098900, | |
167 | 'upload_date': '20160501', | |
990d533e S |
168 | }, |
169 | 'params': { | |
170 | # m3u8 download | |
171 | 'skip_download': True, | |
172 | }, | |
e0b6e50c S |
173 | }, { |
174 | 'url': 'http://www.crunchyroll.com/konosuba-gods-blessing-on-this-wonderful-world/episode-1-give-me-deliverance-from-this-judicial-injustice-727589', | |
175 | 'info_dict': { | |
176 | 'id': '727589', | |
177 | 'ext': 'mp4', | |
6ffc3cf7 S |
178 | 'title': compat_str, |
179 | 'description': compat_str, | |
e0b6e50c S |
180 | 'thumbnail': r're:^https?://.*\.jpg$', |
181 | 'uploader': 'Kadokawa Pictures Inc.', | |
6ffc3cf7 S |
182 | 'timestamp': 1484130900, |
183 | 'upload_date': '20170111', | |
184 | 'series': compat_str, | |
8c996232 | 185 | 'season': "KONOSUBA -God's blessing on this wonderful world! 2", |
e0b6e50c | 186 | 'season_number': 2, |
b9f9f361 | 187 | 'episode': 'Give Me Deliverance From This Judicial Injustice!', |
e0b6e50c S |
188 | 'episode_number': 1, |
189 | }, | |
190 | 'params': { | |
191 | # m3u8 download | |
192 | 'skip_download': True, | |
193 | }, | |
a8896c5a S |
194 | }, { |
195 | 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697', | |
196 | 'only_matching': True, | |
49941c4e S |
197 | }, { |
198 | # geo-restricted (US), 18+ maturity wall, non-premium available | |
199 | 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617', | |
200 | 'only_matching': True, | |
b5869560 YCH |
201 | }, { |
202 | # A description with double quotes | |
203 | 'url': 'http://www.crunchyroll.com/11eyes/episode-1-piros-jszaka-red-night-535080', | |
204 | 'info_dict': { | |
205 | 'id': '535080', | |
206 | 'ext': 'mp4', | |
6ffc3cf7 S |
207 | 'title': compat_str, |
208 | 'description': compat_str, | |
b5869560 | 209 | 'uploader': 'Marvelous AQL Inc.', |
6ffc3cf7 S |
210 | 'timestamp': 1255512600, |
211 | 'upload_date': '20091014', | |
b5869560 YCH |
212 | }, |
213 | 'params': { | |
214 | # Just test metadata extraction | |
215 | 'skip_download': True, | |
216 | }, | |
7fd46552 | 217 | }, { |
218 | # make sure we can extract an uploader name that's not a link | |
219 | 'url': 'http://www.crunchyroll.com/hakuoki-reimeiroku/episode-1-dawn-of-the-divine-warriors-606899', | |
220 | 'info_dict': { | |
221 | 'id': '606899', | |
222 | 'ext': 'mp4', | |
223 | 'title': 'Hakuoki Reimeiroku Episode 1 – Dawn of the Divine Warriors', | |
224 | 'description': 'Ryunosuke was left to die, but Serizawa-san asked him a simple question "Do you want to live?"', | |
225 | 'uploader': 'Geneon Entertainment', | |
226 | 'upload_date': '20120717', | |
227 | }, | |
228 | 'params': { | |
229 | # just test metadata extraction | |
230 | 'skip_download': True, | |
231 | }, | |
6ffc3cf7 | 232 | 'skip': 'Video gone', |
8c996232 S |
233 | }, { |
234 | # A video with a vastly different season name compared to the series name | |
235 | 'url': 'http://www.crunchyroll.com/nyarko-san-another-crawling-chaos/episode-1-test-590532', | |
236 | 'info_dict': { | |
237 | 'id': '590532', | |
238 | 'ext': 'mp4', | |
6ffc3cf7 S |
239 | 'title': compat_str, |
240 | 'description': compat_str, | |
8c996232 | 241 | 'uploader': 'TV TOKYO', |
6ffc3cf7 | 242 | 'timestamp': 1330956000, |
8c996232 S |
243 | 'upload_date': '20120305', |
244 | 'series': 'Nyarko-san: Another Crawling Chaos', | |
245 | 'season': 'Haiyoru! Nyaruani (ONA)', | |
246 | }, | |
247 | 'params': { | |
248 | # Just test metadata extraction | |
249 | 'skip_download': True, | |
250 | }, | |
b2286f8f | 251 | }, { |
252 | 'url': 'http://www.crunchyroll.com/media-723735', | |
253 | 'only_matching': True, | |
6510a3aa S |
254 | }, { |
255 | 'url': 'https://www.crunchyroll.com/en-gb/mob-psycho-100/episode-2-urban-legends-encountering-rumors-780921', | |
256 | 'only_matching': True, | |
a8896c5a | 257 | }] |
c8434e83 | 258 | |
259 | _FORMAT_IDS = { | |
38a40276 | 260 | '360': ('60', '106'), |
261 | '480': ('61', '106'), | |
262 | '720': ('62', '106'), | |
263 | '1080': ('80', '108'), | |
c8434e83 | 264 | } |
265 | ||
d415957d S |
266 | def _download_webpage(self, url_or_request, *args, **kwargs): |
267 | request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request) | |
268 | else sanitized_Request(url_or_request)) | |
269 | # Accept-Language must be set explicitly to accept any language to avoid issues | |
270 | # similar to https://github.com/ytdl-org/youtube-dl/issues/6797. | |
271 | # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction | |
272 | # should be imposed or not (from what I can see it just takes the first language | |
273 | # ignoring the priority and requires it to correspond the IP). By the way this causes | |
274 | # Crunchyroll to not work in georestriction cases in some browsers that don't place | |
275 | # the locale lang first in header. However allowing any language seems to workaround the issue. | |
276 | request.add_header('Accept-Language', '*') | |
277 | return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs) | |
278 | ||
c8434e83 | 279 | def _decrypt_subtitles(self, data, iv, id): |
cf282071 S |
280 | data = bytes_to_intlist(compat_b64decode(data)) |
281 | iv = bytes_to_intlist(compat_b64decode(iv)) | |
c8434e83 | 282 | id = int(id) |
283 | ||
284 | def obfuscate_key_aux(count, modulo, start): | |
285 | output = list(start) | |
286 | for _ in range(count): | |
287 | output.append(output[-1] + output[-2]) | |
288 | # cut off start values | |
289 | output = output[2:] | |
290 | output = list(map(lambda x: x % modulo + 33, output)) | |
291 | return output | |
292 | ||
293 | def obfuscate_key(key): | |
294 | num1 = int(floor(pow(2, 25) * sqrt(6.9))) | |
295 | num2 = (num1 ^ key) << 5 | |
296 | num3 = key ^ num1 | |
297 | num4 = num3 ^ (num3 >> 3) ^ num2 | |
298 | prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2))) | |
38a40276 | 299 | shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest()) |
c8434e83 | 300 | # Extend 160 Bit hash to 256 Bit |
301 | return shaHash + [0] * 12 | |
34440095 | 302 | |
c8434e83 | 303 | key = obfuscate_key(id) |
5f6a1245 | 304 | |
c8434e83 | 305 | decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv)) |
306 | return zlib.decompress(decrypted_data) | |
307 | ||
d65d6286 | 308 | def _convert_subtitles_to_srt(self, sub_root): |
38a40276 | 309 | output = '' |
d65d6286 JMF |
310 | |
311 | for i, event in enumerate(sub_root.findall('./events/event'), 1): | |
312 | start = event.attrib['start'].replace('.', ',') | |
313 | end = event.attrib['end'].replace('.', ',') | |
314 | text = event.attrib['text'].replace('\\N', '\n') | |
38a40276 | 315 | output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text) |
c8434e83 | 316 | return output |
317 | ||
d65d6286 | 318 | def _convert_subtitles_to_ass(self, sub_root): |
78272a07 A |
319 | output = '' |
320 | ||
321 | def ass_bool(strvalue): | |
322 | assvalue = '0' | |
323 | if strvalue == '1': | |
324 | assvalue = '-1' | |
325 | return assvalue | |
326 | ||
78272a07 | 327 | output = '[Script Info]\n' |
611c1dd9 | 328 | output += 'Title: %s\n' % sub_root.attrib['title'] |
78272a07 | 329 | output += 'ScriptType: v4.00+\n' |
611c1dd9 S |
330 | output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style'] |
331 | output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x'] | |
332 | output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y'] | |
2b2d5d31 | 333 | output += """ |
78272a07 A |
334 | [V4+ Styles] |
335 | Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding | |
336 | """ | |
337 | for style in sub_root.findall('./styles/style'): | |
611c1dd9 S |
338 | output += 'Style: ' + style.attrib['name'] |
339 | output += ',' + style.attrib['font_name'] | |
340 | output += ',' + style.attrib['font_size'] | |
341 | output += ',' + style.attrib['primary_colour'] | |
342 | output += ',' + style.attrib['secondary_colour'] | |
343 | output += ',' + style.attrib['outline_colour'] | |
344 | output += ',' + style.attrib['back_colour'] | |
345 | output += ',' + ass_bool(style.attrib['bold']) | |
346 | output += ',' + ass_bool(style.attrib['italic']) | |
347 | output += ',' + ass_bool(style.attrib['underline']) | |
348 | output += ',' + ass_bool(style.attrib['strikeout']) | |
349 | output += ',' + style.attrib['scale_x'] | |
350 | output += ',' + style.attrib['scale_y'] | |
351 | output += ',' + style.attrib['spacing'] | |
352 | output += ',' + style.attrib['angle'] | |
353 | output += ',' + style.attrib['border_style'] | |
354 | output += ',' + style.attrib['outline'] | |
355 | output += ',' + style.attrib['shadow'] | |
356 | output += ',' + style.attrib['alignment'] | |
357 | output += ',' + style.attrib['margin_l'] | |
358 | output += ',' + style.attrib['margin_r'] | |
359 | output += ',' + style.attrib['margin_v'] | |
360 | output += ',' + style.attrib['encoding'] | |
78272a07 A |
361 | output += '\n' |
362 | ||
363 | output += """ | |
364 | [Events] | |
365 | Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text | |
366 | """ | |
367 | for event in sub_root.findall('./events/event'): | |
368 | output += 'Dialogue: 0' | |
611c1dd9 S |
369 | output += ',' + event.attrib['start'] |
370 | output += ',' + event.attrib['end'] | |
371 | output += ',' + event.attrib['style'] | |
372 | output += ',' + event.attrib['name'] | |
373 | output += ',' + event.attrib['margin_l'] | |
374 | output += ',' + event.attrib['margin_r'] | |
375 | output += ',' + event.attrib['margin_v'] | |
376 | output += ',' + event.attrib['effect'] | |
377 | output += ',' + event.attrib['text'] | |
78272a07 A |
378 | output += '\n' |
379 | ||
380 | return output | |
381 | ||
0385d642 | 382 | def _extract_subtitles(self, subtitle): |
36e6f62c | 383 | sub_root = compat_etree_fromstring(subtitle) |
0385d642 S |
384 | return [{ |
385 | 'ext': 'srt', | |
386 | 'data': self._convert_subtitles_to_srt(sub_root), | |
387 | }, { | |
388 | 'ext': 'ass', | |
389 | 'data': self._convert_subtitles_to_ass(sub_root), | |
390 | }] | |
391 | ||
b5857f62 JMF |
392 | def _get_subtitles(self, video_id, webpage): |
393 | subtitles = {} | |
76907875 | 394 | for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage): |
05dee6c5 RA |
395 | sub_doc = self._call_rpc_api( |
396 | 'Subtitle_GetXml', video_id, | |
397 | 'Downloading subtitles for ' + sub_name, data={ | |
398 | 'subtitle_script_id': sub_id, | |
399 | }) | |
ee0ba927 | 400 | if not isinstance(sub_doc, compat_etree_Element): |
b5857f62 | 401 | continue |
05dee6c5 RA |
402 | sid = sub_doc.get('id') |
403 | iv = xpath_text(sub_doc, 'iv', 'subtitle iv') | |
404 | data = xpath_text(sub_doc, 'data', 'subtitle data') | |
405 | if not sid or not iv or not data: | |
406 | continue | |
407 | subtitle = self._decrypt_subtitles(data, iv, sid).decode('utf-8') | |
b5857f62 JMF |
408 | lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False) |
409 | if not lang_code: | |
410 | continue | |
0385d642 | 411 | subtitles[lang_code] = self._extract_subtitles(subtitle) |
b5857f62 JMF |
412 | return subtitles |
413 | ||
5f6a1245 | 414 | def _real_extract(self, url): |
c8434e83 | 415 | mobj = re.match(self._VALID_URL, url) |
d3d8d818 | 416 | video_id = mobj.group('id') |
38a40276 | 417 | |
418 | if mobj.group('prefix') == 'm': | |
419 | mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage') | |
420 | webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url') | |
421 | else: | |
422 | webpage_url = 'http://www.' + mobj.group('url') | |
c8434e83 | 423 | |
ca77b92f RA |
424 | webpage = self._download_webpage( |
425 | self._add_skip_wall(webpage_url), video_id, | |
426 | headers=self.geo_verification_headers()) | |
2f72e83b S |
427 | note_m = self._html_search_regex( |
428 | r'<div class="showmedia-trailer-notice">(.+?)</div>', | |
429 | webpage, 'trailer-notice', default='') | |
c8434e83 | 430 | if note_m: |
a7191c6f | 431 | raise ExtractorError(note_m, expected=True) |
c8434e83 | 432 | |
1d430674 S |
433 | mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage) |
434 | if mobj: | |
435 | msg = json.loads(mobj.group('msg')) | |
436 | if msg.get('type') == 'error': | |
437 | raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True) | |
2f72e83b S |
438 | |
439 | if 'To view this, please log in to verify you are 18 or older.' in webpage: | |
39affb5a | 440 | self.raise_login_required() |
1d430674 | 441 | |
54a5be4d RA |
442 | media = self._parse_json(self._search_regex( |
443 | r'vilos\.config\.media\s*=\s*({.+?});', | |
444 | webpage, 'vilos media', default='{}'), video_id) | |
445 | media_metadata = media.get('metadata') or {} | |
446 | ||
1084563e S |
447 | language = self._search_regex( |
448 | r'(?:vilos\.config\.player\.language|LOCALE)\s*=\s*(["\'])(?P<lang>(?:(?!\1).)+)\1', | |
449 | webpage, 'language', default=None, group='lang') | |
450 | ||
5214f1e3 | 451 | video_title = self._html_search_regex( |
6ffc3cf7 S |
452 | (r'(?s)<h1[^>]*>((?:(?!<h1).)*?<(?:span[^>]+itemprop=["\']title["\']|meta[^>]+itemprop=["\']position["\'])[^>]*>(?:(?!<h1).)+?)</h1>', |
453 | r'<title>(.+?),\s+-\s+.+? Crunchyroll'), | |
454 | webpage, 'video_title', default=None) | |
455 | if not video_title: | |
456 | video_title = re.sub(r'^Watch\s+', '', self._og_search_description(webpage)) | |
38a40276 | 457 | video_title = re.sub(r' {2,}', ' ', video_title) |
54a5be4d | 458 | video_description = (self._parse_json(self._html_search_regex( |
b5869560 | 459 | r'<script[^>]*>\s*.+?\[media_id=%s\].+?({.+?"description"\s*:.+?})\);' % video_id, |
54a5be4d | 460 | webpage, 'description', default='{}'), video_id) or media_metadata).get('description') |
6d02b9a3 S |
461 | if video_description: |
462 | video_description = lowercase_escape(video_description.replace(r'\r\n', '\n')) | |
47004d95 | 463 | video_uploader = self._html_search_regex( |
7fd46552 | 464 | # try looking for both an uploader that's a link and one that's not |
465 | [r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', r'<div>\s*Publisher:\s*<span>\s*(.+?)\s*</span>\s*</div>'], | |
6ffc3cf7 | 466 | webpage, 'video_uploader', default=False) |
c8434e83 | 467 | |
065216d9 | 468 | formats = [] |
54a5be4d | 469 | for stream in media.get('streams', []): |
1084563e S |
470 | audio_lang = stream.get('audio_lang') |
471 | hardsub_lang = stream.get('hardsub_lang') | |
472 | vrv_formats = self._extract_vrv_formats( | |
54a5be4d | 473 | stream.get('url'), video_id, stream.get('format'), |
1084563e S |
474 | audio_lang, hardsub_lang) |
475 | for f in vrv_formats: | |
f983b875 | 476 | f['language_preference'] = 1 if audio_lang == language else 0 |
477 | f['quality'] = ( | |
478 | 1 if not hardsub_lang | |
479 | else 0 if hardsub_lang == language | |
480 | else -1) | |
1084563e | 481 | formats.extend(vrv_formats) |
54a5be4d RA |
482 | if not formats: |
483 | available_fmts = [] | |
484 | for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage): | |
485 | attrs = extract_attributes(a) | |
486 | href = attrs.get('href') | |
487 | if href and '/freetrial' in href: | |
488 | continue | |
489 | available_fmts.append(fmt) | |
490 | if not available_fmts: | |
491 | for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'): | |
492 | available_fmts = re.findall(p, webpage) | |
493 | if available_fmts: | |
494 | break | |
495 | if not available_fmts: | |
496 | available_fmts = self._FORMAT_IDS.keys() | |
497 | video_encode_ids = [] | |
498 | ||
499 | for fmt in available_fmts: | |
500 | stream_quality, stream_format = self._FORMAT_IDS[fmt] | |
501 | video_format = fmt + 'p' | |
502 | stream_infos = [] | |
503 | streamdata = self._call_rpc_api( | |
504 | 'VideoPlayer_GetStandardConfig', video_id, | |
505 | 'Downloading media info for %s' % video_format, data={ | |
506 | 'media_id': video_id, | |
507 | 'video_format': stream_format, | |
508 | 'video_quality': stream_quality, | |
509 | 'current_page': url, | |
510 | }) | |
ee0ba927 | 511 | if isinstance(streamdata, compat_etree_Element): |
54a5be4d RA |
512 | stream_info = streamdata.find('./{default}preload/stream_info') |
513 | if stream_info is not None: | |
514 | stream_infos.append(stream_info) | |
515 | stream_info = self._call_rpc_api( | |
516 | 'VideoEncode_GetStreamInfo', video_id, | |
517 | 'Downloading stream info for %s' % video_format, data={ | |
518 | 'media_id': video_id, | |
519 | 'video_format': stream_format, | |
520 | 'video_encode_quality': stream_quality, | |
521 | }) | |
ee0ba927 | 522 | if isinstance(stream_info, compat_etree_Element): |
05dee6c5 | 523 | stream_infos.append(stream_info) |
54a5be4d RA |
524 | for stream_info in stream_infos: |
525 | video_encode_id = xpath_text(stream_info, './video_encode_id') | |
526 | if video_encode_id in video_encode_ids: | |
527 | continue | |
528 | video_encode_ids.append(video_encode_id) | |
c8434e83 | 529 | |
54a5be4d RA |
530 | video_file = xpath_text(stream_info, './file') |
531 | if not video_file: | |
532 | continue | |
533 | if video_file.startswith('http'): | |
534 | formats.extend(self._extract_m3u8_formats( | |
535 | video_file, video_id, 'mp4', entry_protocol='m3u8_native', | |
536 | m3u8_id='hls', fatal=False)) | |
05dee6c5 RA |
537 | continue |
538 | ||
54a5be4d RA |
539 | video_url = xpath_text(stream_info, './host') |
540 | if not video_url: | |
541 | continue | |
542 | metadata = stream_info.find('./metadata') | |
543 | format_info = { | |
544 | 'format': video_format, | |
545 | 'height': int_or_none(xpath_text(metadata, './height')), | |
546 | 'width': int_or_none(xpath_text(metadata, './width')), | |
547 | } | |
548 | ||
549 | if '.fplive.net/' in video_url: | |
550 | video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip()) | |
551 | parsed_video_url = compat_urlparse.urlparse(video_url) | |
552 | direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace( | |
553 | netloc='v.lvlt.crcdn.net', | |
554 | path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1]))) | |
555 | if self._is_valid_url(direct_video_url, video_id, video_format): | |
556 | format_info.update({ | |
557 | 'format_id': 'http-' + video_format, | |
558 | 'url': direct_video_url, | |
559 | }) | |
560 | formats.append(format_info) | |
561 | continue | |
562 | ||
563 | format_info.update({ | |
564 | 'format_id': 'rtmp-' + video_format, | |
565 | 'url': video_url, | |
566 | 'play_path': video_file, | |
567 | 'ext': 'flv', | |
568 | }) | |
569 | formats.append(format_info) | |
54f37eea | 570 | self._sort_formats(formats) |
05dee6c5 RA |
571 | |
572 | metadata = self._call_rpc_api( | |
573 | 'VideoPlayer_GetMediaMetadata', video_id, | |
574 | note='Downloading media info', data={ | |
e757fb3d | 575 | 'media_id': video_id, |
576 | }) | |
577 | ||
54a5be4d RA |
578 | subtitles = {} |
579 | for subtitle in media.get('subtitles', []): | |
580 | subtitle_url = subtitle.get('url') | |
581 | if not subtitle_url: | |
582 | continue | |
583 | subtitles.setdefault(subtitle.get('language', 'enUS'), []).append({ | |
584 | 'url': subtitle_url, | |
585 | 'ext': subtitle.get('format', 'ass'), | |
586 | }) | |
587 | if not subtitles: | |
588 | subtitles = self.extract_subtitles(video_id, webpage) | |
11b3ce85 | 589 | |
e0b6e50c S |
590 | # webpage provide more accurate data than series_title from XML |
591 | series = self._html_search_regex( | |
7abed4e0 | 592 | r'(?s)<h\d[^>]+\bid=["\']showmedia_about_episode_num[^>]+>(.+?)</h\d', |
8c996232 | 593 | webpage, 'series', fatal=False) |
e0b6e50c | 594 | |
08c7d3da S |
595 | season = episode = episode_number = duration = thumbnail = None |
596 | ||
ee0ba927 | 597 | if isinstance(metadata, compat_etree_Element): |
08c7d3da S |
598 | season = xpath_text(metadata, 'series_title') |
599 | episode = xpath_text(metadata, 'episode_title') | |
600 | episode_number = int_or_none(xpath_text(metadata, 'episode_number')) | |
601 | duration = float_or_none(media_metadata.get('duration'), 1000) | |
602 | thumbnail = xpath_text(metadata, 'episode_image_url') | |
603 | ||
604 | if not episode: | |
605 | episode = media_metadata.get('title') | |
606 | if not episode_number: | |
607 | episode_number = int_or_none(media_metadata.get('episode_number')) | |
608 | if not thumbnail: | |
609 | thumbnail = media_metadata.get('thumbnail', {}).get('url') | |
e0b6e50c S |
610 | |
611 | season_number = int_or_none(self._search_regex( | |
7abed4e0 | 612 | r'(?s)<h\d[^>]+id=["\']showmedia_about_episode_num[^>]+>.+?</h\d>\s*<h4>\s*Season (\d+)', |
e0b6e50c S |
613 | webpage, 'season number', default=None)) |
614 | ||
6ffc3cf7 S |
615 | info = self._search_json_ld(webpage, video_id, default={}) |
616 | ||
617 | return merge_dicts({ | |
8bcc8756 JW |
618 | 'id': video_id, |
619 | 'title': video_title, | |
38a40276 | 620 | 'description': video_description, |
08c7d3da S |
621 | 'duration': duration, |
622 | 'thumbnail': thumbnail, | |
8bcc8756 | 623 | 'uploader': video_uploader, |
e0b6e50c | 624 | 'series': series, |
8c996232 | 625 | 'season': season, |
e0b6e50c S |
626 | 'season_number': season_number, |
627 | 'episode': episode, | |
628 | 'episode_number': episode_number, | |
8bcc8756 JW |
629 | 'subtitles': subtitles, |
630 | 'formats': formats, | |
6ffc3cf7 | 631 | }, info) |
8230018c GS |
632 | |
633 | ||
12810c9c | 634 | class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE): |
611c1dd9 | 635 | IE_NAME = 'crunchyroll:playlist' |
b2286f8f | 636 | _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login|media-\d+))(?P<id>[\w\-]+))/?(?:\?|$)' |
8230018c GS |
637 | |
638 | _TESTS = [{ | |
d9488f69 | 639 | 'url': 'https://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi', |
09e5d6a6 PH |
640 | 'info_dict': { |
641 | 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi', | |
642 | 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi' | |
8230018c | 643 | }, |
09e5d6a6 | 644 | 'playlist_count': 13, |
49941c4e S |
645 | }, { |
646 | # geo-restricted (US), 18+ maturity wall, non-premium available | |
647 | 'url': 'http://www.crunchyroll.com/cosplay-complex-ova', | |
648 | 'info_dict': { | |
649 | 'id': 'cosplay-complex-ova', | |
650 | 'title': 'Cosplay Complex OVA' | |
651 | }, | |
652 | 'playlist_count': 3, | |
653 | 'skip': 'Georestricted', | |
654 | }, { | |
655 | # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14 | |
656 | 'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1', | |
657 | 'only_matching': True, | |
8230018c GS |
658 | }] |
659 | ||
8230018c | 660 | def _real_extract(self, url): |
09e5d6a6 PH |
661 | show_id = self._match_id(url) |
662 | ||
ca77b92f | 663 | webpage = self._download_webpage( |
d9488f69 | 664 | # https:// gives a 403, but http:// does not |
665 | self._add_skip_wall(url).replace('https://', 'http://'), show_id, | |
ca77b92f | 666 | headers=self.geo_verification_headers()) |
4681441d S |
667 | title = self._html_search_meta('name', webpage, default=None) |
668 | ||
09e5d6a6 | 669 | episode_paths = re.findall( |
9e03aa75 | 670 | r'(?s)<li id="showview_videos_media_(\d+)"[^>]+>.*?<a href="([^"]+)"', |
09e5d6a6 PH |
671 | webpage) |
672 | entries = [ | |
9e03aa75 RA |
673 | self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll', ep_id) |
674 | for ep_id, ep in episode_paths | |
09e5d6a6 PH |
675 | ] |
676 | entries.reverse() | |
677 | ||
8230018c | 678 | return { |
09e5d6a6 PH |
679 | '_type': 'playlist', |
680 | 'id': show_id, | |
681 | 'title': title, | |
682 | 'entries': entries, | |
683 | } |