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