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