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