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