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