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