[crunchyroll] switch to HTTPS for RpcApi(closes #17749)
[youtube-dl] / youtube_dl / 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_fromstring,
15     compat_urllib_parse_urlencode,
16     compat_urllib_request,
17     compat_urlparse,
18 )
19 from ..utils import (
20     ExtractorError,
21     bytes_to_intlist,
22     extract_attributes,
23     float_or_none,
24     intlist_to_bytes,
25     int_or_none,
26     lowercase_escape,
27     remove_end,
28     sanitized_Request,
29     unified_strdate,
30     urlencode_postdata,
31     xpath_text,
32 )
33 from ..aes import (
34     aes_cbc_decrypt,
35 )
36
37
38 class CrunchyrollBaseIE(InfoExtractor):
39     _LOGIN_URL = 'https://www.crunchyroll.com/login'
40     _LOGIN_FORM = 'login_form'
41     _NETRC_MACHINE = 'crunchyroll'
42
43     def _call_rpc_api(self, method, video_id, note=None, data=None):
44         data = data or {}
45         data['req'] = 'RpcApi' + method
46         data = compat_urllib_parse_urlencode(data).encode('utf-8')
47         return self._download_xml(
48             'https://www.crunchyroll.com/xml/',
49             video_id, note, fatal=False, data=data, headers={
50                 'Content-Type': 'application/x-www-form-urlencoded',
51             })
52
53     def _login(self):
54         username, password = self._get_login_info()
55         if username is None:
56             return
57
58         self._download_webpage(
59             'https://www.crunchyroll.com/?a=formhandler',
60             None, 'Logging in', 'Wrong login info',
61             data=urlencode_postdata({
62                 'formname': 'RpcApiUser_Login',
63                 'next_url': 'https://www.crunchyroll.com/acct/membership',
64                 'name': username,
65                 'password': password,
66             }))
67
68         '''
69         login_page = self._download_webpage(
70             self._LOGIN_URL, None, 'Downloading login page')
71
72         def is_logged(webpage):
73             return '<title>Redirecting' in webpage
74
75         # Already logged in
76         if is_logged(login_page):
77             return
78
79         login_form_str = self._search_regex(
80             r'(?P<form><form[^>]+?id=(["\'])%s\2[^>]*>)' % self._LOGIN_FORM,
81             login_page, 'login form', group='form')
82
83         post_url = extract_attributes(login_form_str).get('action')
84         if not post_url:
85             post_url = self._LOGIN_URL
86         elif not post_url.startswith('http'):
87             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
88
89         login_form = self._form_hidden_inputs(self._LOGIN_FORM, login_page)
90
91         login_form.update({
92             'login_form[name]': username,
93             'login_form[password]': password,
94         })
95
96         response = self._download_webpage(
97             post_url, None, 'Logging in', 'Wrong login info',
98             data=urlencode_postdata(login_form),
99             headers={'Content-Type': 'application/x-www-form-urlencoded'})
100
101         # Successful login
102         if is_logged(response):
103             return
104
105         error = self._html_search_regex(
106             '(?s)<ul[^>]+class=["\']messages["\'][^>]*>(.+?)</ul>',
107             response, 'error message', default=None)
108         if error:
109             raise ExtractorError('Unable to login: %s' % error, expected=True)
110
111         raise ExtractorError('Unable to log in')
112         '''
113
114     def _real_initialize(self):
115         self._login()
116
117     def _download_webpage(self, url_or_request, *args, **kwargs):
118         request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
119                    else sanitized_Request(url_or_request))
120         # Accept-Language must be set explicitly to accept any language to avoid issues
121         # similar to https://github.com/rg3/youtube-dl/issues/6797.
122         # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
123         # should be imposed or not (from what I can see it just takes the first language
124         # ignoring the priority and requires it to correspond the IP). By the way this causes
125         # Crunchyroll to not work in georestriction cases in some browsers that don't place
126         # the locale lang first in header. However allowing any language seems to workaround the issue.
127         request.add_header('Accept-Language', '*')
128         return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
129
130     @staticmethod
131     def _add_skip_wall(url):
132         parsed_url = compat_urlparse.urlparse(url)
133         qs = compat_urlparse.parse_qs(parsed_url.query)
134         # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
135         # > This content may be inappropriate for some people.
136         # > Are you sure you want to continue?
137         # since it's not disabled by default in crunchyroll account's settings.
138         # See https://github.com/rg3/youtube-dl/issues/7202.
139         qs['skip_wall'] = ['1']
140         return compat_urlparse.urlunparse(
141             parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
142
143
144 class CrunchyrollIE(CrunchyrollBaseIE, VRVIE):
145     IE_NAME = 'crunchyroll'
146     _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
147     _TESTS = [{
148         'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
149         'info_dict': {
150             'id': '645513',
151             'ext': 'mp4',
152             'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
153             'description': 'md5:2d17137920c64f2f49981a7797d275ef',
154             'thumbnail': r're:^https?://.*\.jpg$',
155             'uploader': 'Yomiuri Telecasting Corporation (YTV)',
156             'upload_date': '20131013',
157             'url': 're:(?!.*&amp)',
158         },
159         'params': {
160             # rtmp
161             'skip_download': True,
162         },
163     }, {
164         'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
165         'info_dict': {
166             'id': '589804',
167             'ext': 'flv',
168             'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
169             'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
170             'thumbnail': r're:^https?://.*\.jpg$',
171             'uploader': 'Danny Choo Network',
172             'upload_date': '20120213',
173         },
174         'params': {
175             # rtmp
176             'skip_download': True,
177         },
178         'skip': 'Video gone',
179     }, {
180         'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409',
181         'info_dict': {
182             'id': '702409',
183             'ext': 'mp4',
184             'title': 'Re:ZERO -Starting Life in Another World- Episode 5 – The Morning of Our Promise Is Still Distant',
185             'description': 'md5:97664de1ab24bbf77a9c01918cb7dca9',
186             'thumbnail': r're:^https?://.*\.jpg$',
187             'uploader': 'TV TOKYO',
188             'upload_date': '20160508',
189         },
190         'params': {
191             # m3u8 download
192             'skip_download': True,
193         },
194     }, {
195         'url': 'http://www.crunchyroll.com/konosuba-gods-blessing-on-this-wonderful-world/episode-1-give-me-deliverance-from-this-judicial-injustice-727589',
196         'info_dict': {
197             'id': '727589',
198             'ext': 'mp4',
199             'title': "KONOSUBA -God's blessing on this wonderful world! 2 Episode 1 – Give Me Deliverance From This Judicial Injustice!",
200             'description': 'md5:cbcf05e528124b0f3a0a419fc805ea7d',
201             'thumbnail': r're:^https?://.*\.jpg$',
202             'uploader': 'Kadokawa Pictures Inc.',
203             'upload_date': '20170118',
204             'series': "KONOSUBA -God's blessing on this wonderful world!",
205             'season': "KONOSUBA -God's blessing on this wonderful world! 2",
206             'season_number': 2,
207             'episode': 'Give Me Deliverance From This Judicial Injustice!',
208             'episode_number': 1,
209         },
210         'params': {
211             # m3u8 download
212             'skip_download': True,
213         },
214     }, {
215         'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
216         'only_matching': True,
217     }, {
218         # geo-restricted (US), 18+ maturity wall, non-premium available
219         'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
220         'only_matching': True,
221     }, {
222         # A description with double quotes
223         'url': 'http://www.crunchyroll.com/11eyes/episode-1-piros-jszaka-red-night-535080',
224         'info_dict': {
225             'id': '535080',
226             'ext': 'mp4',
227             'title': '11eyes Episode 1 – Red Night ~ Piros éjszaka',
228             'description': 'Kakeru and Yuka are thrown into an alternate nightmarish world they call "Red Night".',
229             'uploader': 'Marvelous AQL Inc.',
230             'upload_date': '20091021',
231         },
232         'params': {
233             # Just test metadata extraction
234             'skip_download': True,
235         },
236     }, {
237         # make sure we can extract an uploader name that's not a link
238         'url': 'http://www.crunchyroll.com/hakuoki-reimeiroku/episode-1-dawn-of-the-divine-warriors-606899',
239         'info_dict': {
240             'id': '606899',
241             'ext': 'mp4',
242             'title': 'Hakuoki Reimeiroku Episode 1 – Dawn of the Divine Warriors',
243             'description': 'Ryunosuke was left to die, but Serizawa-san asked him a simple question "Do you want to live?"',
244             'uploader': 'Geneon Entertainment',
245             'upload_date': '20120717',
246         },
247         'params': {
248             # just test metadata extraction
249             'skip_download': True,
250         },
251     }, {
252         # A video with a vastly different season name compared to the series name
253         'url': 'http://www.crunchyroll.com/nyarko-san-another-crawling-chaos/episode-1-test-590532',
254         'info_dict': {
255             'id': '590532',
256             'ext': 'mp4',
257             'title': 'Haiyoru! Nyaruani (ONA) Episode 1 – Test',
258             'description': 'Mahiro and Nyaruko talk about official certification.',
259             'uploader': 'TV TOKYO',
260             'upload_date': '20120305',
261             'series': 'Nyarko-san: Another Crawling Chaos',
262             'season': 'Haiyoru! Nyaruani (ONA)',
263         },
264         'params': {
265             # Just test metadata extraction
266             'skip_download': True,
267         },
268     }, {
269         'url': 'http://www.crunchyroll.com/media-723735',
270         'only_matching': True,
271     }]
272
273     _FORMAT_IDS = {
274         '360': ('60', '106'),
275         '480': ('61', '106'),
276         '720': ('62', '106'),
277         '1080': ('80', '108'),
278     }
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 sub_doc is None:
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 = re.match(self._VALID_URL, url)
417         video_id = mobj.group('video_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)
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["\'][^>]*>(?:(?!<h1).)+?)</h1>',
454             webpage, 'video_title')
455         video_title = re.sub(r' {2,}', ' ', video_title)
456         video_description = (self._parse_json(self._html_search_regex(
457             r'<script[^>]*>\s*.+?\[media_id=%s\].+?({.+?"description"\s*:.+?})\);' % video_id,
458             webpage, 'description', default='{}'), video_id) or media_metadata).get('description')
459         if video_description:
460             video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
461         video_upload_date = self._html_search_regex(
462             [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
463             webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
464         if video_upload_date:
465             video_upload_date = unified_strdate(video_upload_date)
466         video_uploader = self._html_search_regex(
467             # try looking for both an uploader that's a link and one that's not
468             [r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', r'<div>\s*Publisher:\s*<span>\s*(.+?)\s*</span>\s*</div>'],
469             webpage, 'video_uploader', fatal=False)
470
471         formats = []
472         for stream in media.get('streams', []):
473             audio_lang = stream.get('audio_lang')
474             hardsub_lang = stream.get('hardsub_lang')
475             vrv_formats = self._extract_vrv_formats(
476                 stream.get('url'), video_id, stream.get('format'),
477                 audio_lang, hardsub_lang)
478             for f in vrv_formats:
479                 if not hardsub_lang:
480                     f['preference'] = 1
481                 language_preference = 0
482                 if audio_lang == language:
483                     language_preference += 1
484                 if hardsub_lang == language:
485                     language_preference += 1
486                 if language_preference:
487                     f['language_preference'] = language_preference
488             formats.extend(vrv_formats)
489         if not formats:
490             available_fmts = []
491             for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
492                 attrs = extract_attributes(a)
493                 href = attrs.get('href')
494                 if href and '/freetrial' in href:
495                     continue
496                 available_fmts.append(fmt)
497             if not available_fmts:
498                 for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'):
499                     available_fmts = re.findall(p, webpage)
500                     if available_fmts:
501                         break
502             if not available_fmts:
503                 available_fmts = self._FORMAT_IDS.keys()
504             video_encode_ids = []
505
506             for fmt in available_fmts:
507                 stream_quality, stream_format = self._FORMAT_IDS[fmt]
508                 video_format = fmt + 'p'
509                 stream_infos = []
510                 streamdata = self._call_rpc_api(
511                     'VideoPlayer_GetStandardConfig', video_id,
512                     'Downloading media info for %s' % video_format, data={
513                         'media_id': video_id,
514                         'video_format': stream_format,
515                         'video_quality': stream_quality,
516                         'current_page': url,
517                     })
518                 if streamdata is not None:
519                     stream_info = streamdata.find('./{default}preload/stream_info')
520                     if stream_info is not None:
521                         stream_infos.append(stream_info)
522                 stream_info = self._call_rpc_api(
523                     'VideoEncode_GetStreamInfo', video_id,
524                     'Downloading stream info for %s' % video_format, data={
525                         'media_id': video_id,
526                         'video_format': stream_format,
527                         'video_encode_quality': stream_quality,
528                     })
529                 if stream_info is not None:
530                     stream_infos.append(stream_info)
531                 for stream_info in stream_infos:
532                     video_encode_id = xpath_text(stream_info, './video_encode_id')
533                     if video_encode_id in video_encode_ids:
534                         continue
535                     video_encode_ids.append(video_encode_id)
536
537                     video_file = xpath_text(stream_info, './file')
538                     if not video_file:
539                         continue
540                     if video_file.startswith('http'):
541                         formats.extend(self._extract_m3u8_formats(
542                             video_file, video_id, 'mp4', entry_protocol='m3u8_native',
543                             m3u8_id='hls', fatal=False))
544                         continue
545
546                     video_url = xpath_text(stream_info, './host')
547                     if not video_url:
548                         continue
549                     metadata = stream_info.find('./metadata')
550                     format_info = {
551                         'format': video_format,
552                         'height': int_or_none(xpath_text(metadata, './height')),
553                         'width': int_or_none(xpath_text(metadata, './width')),
554                     }
555
556                     if '.fplive.net/' in video_url:
557                         video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
558                         parsed_video_url = compat_urlparse.urlparse(video_url)
559                         direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
560                             netloc='v.lvlt.crcdn.net',
561                             path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
562                         if self._is_valid_url(direct_video_url, video_id, video_format):
563                             format_info.update({
564                                 'format_id': 'http-' + video_format,
565                                 'url': direct_video_url,
566                             })
567                             formats.append(format_info)
568                             continue
569
570                     format_info.update({
571                         'format_id': 'rtmp-' + video_format,
572                         'url': video_url,
573                         'play_path': video_file,
574                         'ext': 'flv',
575                     })
576                     formats.append(format_info)
577         self._sort_formats(formats, ('preference', 'language_preference', 'height', 'width', 'tbr', 'fps'))
578
579         metadata = self._call_rpc_api(
580             'VideoPlayer_GetMediaMetadata', video_id,
581             note='Downloading media info', data={
582                 'media_id': video_id,
583             })
584
585         subtitles = {}
586         for subtitle in media.get('subtitles', []):
587             subtitle_url = subtitle.get('url')
588             if not subtitle_url:
589                 continue
590             subtitles.setdefault(subtitle.get('language', 'enUS'), []).append({
591                 'url': subtitle_url,
592                 'ext': subtitle.get('format', 'ass'),
593             })
594         if not subtitles:
595             subtitles = self.extract_subtitles(video_id, webpage)
596
597         # webpage provide more accurate data than series_title from XML
598         series = self._html_search_regex(
599             r'(?s)<h\d[^>]+\bid=["\']showmedia_about_episode_num[^>]+>(.+?)</h\d',
600             webpage, 'series', fatal=False)
601         season = xpath_text(metadata, 'series_title')
602
603         episode = xpath_text(metadata, 'episode_title') or media_metadata.get('title')
604         episode_number = int_or_none(xpath_text(metadata, 'episode_number') or media_metadata.get('episode_number'))
605
606         season_number = int_or_none(self._search_regex(
607             r'(?s)<h\d[^>]+id=["\']showmedia_about_episode_num[^>]+>.+?</h\d>\s*<h4>\s*Season (\d+)',
608             webpage, 'season number', default=None))
609
610         return {
611             'id': video_id,
612             'title': video_title,
613             'description': video_description,
614             'duration': float_or_none(media_metadata.get('duration'), 1000),
615             'thumbnail': xpath_text(metadata, 'episode_image_url') or media_metadata.get('thumbnail', {}).get('url'),
616             'uploader': video_uploader,
617             'upload_date': video_upload_date,
618             'series': series,
619             'season': season,
620             'season_number': season_number,
621             'episode': episode,
622             'episode_number': episode_number,
623             'subtitles': subtitles,
624             'formats': formats,
625         }
626
627
628 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
629     IE_NAME = 'crunchyroll:playlist'
630     _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\-]+))/?(?:\?|$)'
631
632     _TESTS = [{
633         'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
634         'info_dict': {
635             'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
636             'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
637         },
638         'playlist_count': 13,
639     }, {
640         # geo-restricted (US), 18+ maturity wall, non-premium available
641         'url': 'http://www.crunchyroll.com/cosplay-complex-ova',
642         'info_dict': {
643             'id': 'cosplay-complex-ova',
644             'title': 'Cosplay Complex OVA'
645         },
646         'playlist_count': 3,
647         'skip': 'Georestricted',
648     }, {
649         # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
650         'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1',
651         'only_matching': True,
652     }]
653
654     def _real_extract(self, url):
655         show_id = self._match_id(url)
656
657         webpage = self._download_webpage(
658             self._add_skip_wall(url), show_id,
659             headers=self.geo_verification_headers())
660         title = self._html_search_regex(
661             r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
662             webpage, 'title')
663         episode_paths = re.findall(
664             r'(?s)<li id="showview_videos_media_(\d+)"[^>]+>.*?<a href="([^"]+)"',
665             webpage)
666         entries = [
667             self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll', ep_id)
668             for ep_id, ep in episode_paths
669         ]
670         entries.reverse()
671
672         return {
673             '_type': 'playlist',
674             'id': show_id,
675             'title': title,
676             'entries': entries,
677         }