]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/crunchyroll.py
[tva] fix extraction(closes #14736)
[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 base64
7import zlib
8
c8434e83 9from hashlib import sha1
10from math import pow, sqrt, floor
b5857f62 11from .common import InfoExtractor
1cc79574 12from ..compat import (
36e6f62c 13 compat_etree_fromstring,
15707c7e 14 compat_urllib_parse_urlencode,
c8434e83 15 compat_urllib_request,
a01da8bb 16 compat_urlparse,
1cc79574
PH
17)
18from ..utils import (
19 ExtractorError,
c8434e83 20 bytes_to_intlist,
21 intlist_to_bytes,
725d1c58 22 int_or_none,
6d02b9a3 23 lowercase_escape,
a01da8bb 24 remove_end,
5c2266df 25 sanitized_Request,
c8434e83 26 unified_strdate,
723e04d0 27 urlencode_postdata,
725d1c58 28 xpath_text,
065216d9 29 extract_attributes,
c8434e83 30)
31from ..aes import (
32 aes_cbc_decrypt,
c8434e83 33)
34
34440095 35
12810c9c 36class CrunchyrollBaseIE(InfoExtractor):
eb5b1fc0
S
37 _LOGIN_URL = 'https://www.crunchyroll.com/login'
38 _LOGIN_FORM = 'login_form'
80f48920
S
39 _NETRC_MACHINE = 'crunchyroll'
40
41 def _login(self):
42 (username, password) = self._get_login_info()
43 if username is None:
44 return
eb5b1fc0 45
cc6a960e
RA
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 '''
eb5b1fc0
S
57 login_page = self._download_webpage(
58 self._LOGIN_URL, None, 'Downloading login page')
59
70b4cf9b
S
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
eb5b1fc0
S
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,
80f48920 82 })
eb5b1fc0
S
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
70b4cf9b 90 if is_logged(response):
eb5b1fc0
S
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')
cc6a960e 100 '''
80f48920
S
101
102 def _real_initialize(self):
103 self._login()
104
cc162f6a 105 def _download_webpage(self, url_or_request, *args, **kwargs):
12810c9c 106 request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
5c2266df 107 else sanitized_Request(url_or_request))
12810c9c
S
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', '*')
cc162f6a 116 return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
12810c9c 117
80f48920
S
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(
15707c7e 129 parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
80f48920 130
12810c9c
S
131
132class CrunchyrollIE(CrunchyrollBaseIE):
ede21449 133 _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
a8896c5a 134 _TESTS = [{
38a40276 135 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
38a40276 136 'info_dict': {
34440095 137 'id': '645513',
b5869560 138 'ext': 'mp4',
38a40276 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',
b1edd7a4 144 'url': 're:(?!.*&amp)',
c8434e83 145 },
38a40276 146 'params': {
c8434e83 147 # rtmp
38a40276 148 'skip_download': True,
c8434e83 149 },
ede21449
S
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',
6d02b9a3 156 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
ec85ded8 157 'thumbnail': r're:^https?://.*\.jpg$',
ede21449
S
158 'uploader': 'Danny Choo Network',
159 'upload_date': '20120213',
160 },
161 'params': {
162 # rtmp
163 'skip_download': True,
164 },
77c5b98d 165 'skip': 'Video gone',
990d533e
S
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',
ec85ded8 173 'thumbnail': r're:^https?://.*\.jpg$',
990d533e
S
174 'uploader': 'TV TOKYO',
175 'upload_date': '20160508',
176 },
177 'params': {
178 # m3u8 download
179 'skip_download': True,
180 },
e0b6e50c
S
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',
b9f9f361 186 'title': "KONOSUBA -God's blessing on this wonderful world! 2 Episode 1 – Give Me Deliverance From This Judicial Injustice!",
e0b6e50c
S
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!",
8c996232 192 'season': "KONOSUBA -God's blessing on this wonderful world! 2",
e0b6e50c 193 'season_number': 2,
b9f9f361 194 'episode': 'Give Me Deliverance From This Judicial Injustice!',
e0b6e50c
S
195 'episode_number': 1,
196 },
197 'params': {
198 # m3u8 download
199 'skip_download': True,
200 },
a8896c5a
S
201 }, {
202 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
203 'only_matching': True,
49941c4e
S
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,
b5869560
YCH
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 },
7fd46552 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 },
8c996232
S
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 },
a8896c5a 255 }]
c8434e83 256
257 _FORMAT_IDS = {
38a40276 258 '360': ('60', '106'),
259 '480': ('61', '106'),
260 '720': ('62', '106'),
261 '1080': ('80', '108'),
c8434e83 262 }
263
264 def _decrypt_subtitles(self, data, iv, id):
1a5b77dc
S
265 data = bytes_to_intlist(base64.b64decode(data.encode('utf-8')))
266 iv = bytes_to_intlist(base64.b64decode(iv.encode('utf-8')))
c8434e83 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)))
38a40276 284 shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
c8434e83 285 # Extend 160 Bit hash to 256 Bit
286 return shaHash + [0] * 12
34440095 287
c8434e83 288 key = obfuscate_key(id)
5f6a1245 289
c8434e83 290 decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
291 return zlib.decompress(decrypted_data)
292
d65d6286 293 def _convert_subtitles_to_srt(self, sub_root):
38a40276 294 output = ''
d65d6286
JMF
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')
38a40276 300 output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
c8434e83 301 return output
302
d65d6286 303 def _convert_subtitles_to_ass(self, sub_root):
78272a07
A
304 output = ''
305
306 def ass_bool(strvalue):
307 assvalue = '0'
308 if strvalue == '1':
309 assvalue = '-1'
310 return assvalue
311
78272a07 312 output = '[Script Info]\n'
611c1dd9 313 output += 'Title: %s\n' % sub_root.attrib['title']
78272a07 314 output += 'ScriptType: v4.00+\n'
611c1dd9
S
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']
2b2d5d31 318 output += """
78272a07
A
319[V4+ Styles]
320Format: 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'):
611c1dd9
S
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']
78272a07
A
346 output += '\n'
347
348 output += """
349[Events]
350Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
351"""
352 for event in sub_root.findall('./events/event'):
353 output += 'Dialogue: 0'
611c1dd9
S
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']
78272a07
A
363 output += '\n'
364
365 return output
366
0385d642 367 def _extract_subtitles(self, subtitle):
36e6f62c 368 sub_root = compat_etree_fromstring(subtitle)
0385d642
S
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
b5857f62
JMF
377 def _get_subtitles(self, video_id, webpage):
378 subtitles = {}
76907875 379 for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage):
b5857f62
JMF
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
b5857f62
JMF
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
0385d642 392 subtitles[lang_code] = self._extract_subtitles(subtitle)
b5857f62
JMF
393 return subtitles
394
5f6a1245 395 def _real_extract(self, url):
c8434e83 396 mobj = re.match(self._VALID_URL, url)
38a40276 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')
c8434e83 404
ca77b92f
RA
405 webpage = self._download_webpage(
406 self._add_skip_wall(webpage_url), video_id,
407 headers=self.geo_verification_headers())
2f72e83b
S
408 note_m = self._html_search_regex(
409 r'<div class="showmedia-trailer-notice">(.+?)</div>',
410 webpage, 'trailer-notice', default='')
c8434e83 411 if note_m:
412 raise ExtractorError(note_m)
413
1d430674
S
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)
2f72e83b
S
419
420 if 'To view this, please log in to verify you are 18 or older.' in webpage:
39affb5a 421 self.raise_login_required()
1d430674 422
5214f1e3
S
423 video_title = self._html_search_regex(
424 r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title["\'][^>]*>(?:(?!<h1).)+?)</h1>',
425 webpage, 'video_title')
38a40276 426 video_title = re.sub(r' {2,}', ' ', video_title)
b5869560
YCH
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')
6d02b9a3
S
430 if video_description:
431 video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
47004d95
S
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)
c8434e83 435 if video_upload_date:
436 video_upload_date = unified_strdate(video_upload_date)
47004d95 437 video_uploader = self._html_search_regex(
7fd46552 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)
c8434e83 441
065216d9 442 available_fmts = []
6ff44695 443 for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
065216d9 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:
8312b1a3
S
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
e757fb3d 454 video_encode_ids = []
065216d9 455 formats = []
456 for fmt in available_fmts:
c8434e83 457 stream_quality, stream_format = self._FORMAT_IDS[fmt]
2514d263 458 video_format = fmt + 'p'
5c2266df 459 streamdata_req = sanitized_Request(
ede21449 460 'http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s&video_format=%s&video_quality=%s'
e757fb3d 461 % (video_id, stream_format, stream_quality),
15707c7e 462 compat_urllib_parse_urlencode({'current_page': url}).encode('utf-8'))
38a40276 463 streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
b1edd7a4
PH
464 streamdata = self._download_xml(
465 streamdata_req, video_id,
466 note='Downloading media info for %s' % video_format)
ede21449 467 stream_info = streamdata.find('./{default}preload/stream_info')
e757fb3d 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)
990d533e
S
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
e4f49a87 482 video_url = xpath_text(stream_info, './host')
990d533e 483 if not video_url:
e4f49a87 484 continue
725d1c58
JMF
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 }
a01da8bb
S
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',
990d533e 498 path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
a01da8bb 499 if self._is_valid_url(direct_video_url, video_id, video_format):
725d1c58 500 format_info.update({
a01da8bb 501 'url': direct_video_url,
a01da8bb 502 })
725d1c58 503 formats.append(format_info)
a01da8bb
S
504 continue
505
725d1c58 506 format_info.update({
38a40276 507 'url': video_url,
990d533e 508 'play_path': video_file,
38a40276 509 'ext': 'flv',
c8434e83 510 })
725d1c58 511 formats.append(format_info)
00a17a9e 512 self._sort_formats(formats)
c8434e83 513
e757fb3d 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
b5857f62 521 subtitles = self.extract_subtitles(video_id, webpage)
11b3ce85 522
e0b6e50c
S
523 # webpage provide more accurate data than series_title from XML
524 series = self._html_search_regex(
7abed4e0 525 r'(?s)<h\d[^>]+\bid=["\']showmedia_about_episode_num[^>]+>(.+?)</h\d',
8c996232
S
526 webpage, 'series', fatal=False)
527 season = xpath_text(metadata, 'series_title')
e0b6e50c
S
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(
7abed4e0 533 r'(?s)<h\d[^>]+id=["\']showmedia_about_episode_num[^>]+>.+?</h\d>\s*<h4>\s*Season (\d+)',
e0b6e50c
S
534 webpage, 'season number', default=None))
535
c8434e83 536 return {
8bcc8756
JW
537 'id': video_id,
538 'title': video_title,
38a40276 539 'description': video_description,
e757fb3d 540 'thumbnail': xpath_text(metadata, 'episode_image_url'),
8bcc8756 541 'uploader': video_uploader,
38a40276 542 'upload_date': video_upload_date,
e0b6e50c 543 'series': series,
8c996232 544 'season': season,
e0b6e50c
S
545 'season_number': season_number,
546 'episode': episode,
547 'episode_number': episode_number,
8bcc8756
JW
548 'subtitles': subtitles,
549 'formats': formats,
d0a72674 550 }
8230018c
GS
551
552
12810c9c 553class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
611c1dd9 554 IE_NAME = 'crunchyroll:playlist'
80f48920 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\-]+))/?(?:\?|$)'
8230018c
GS
556
557 _TESTS = [{
09e5d6a6
PH
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'
8230018c 562 },
09e5d6a6 563 'playlist_count': 13,
49941c4e
S
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,
8230018c
GS
577 }]
578
8230018c 579 def _real_extract(self, url):
09e5d6a6
PH
580 show_id = self._match_id(url)
581
ca77b92f
RA
582 webpage = self._download_webpage(
583 self._add_skip_wall(url), show_id,
584 headers=self.geo_verification_headers())
09e5d6a6
PH
585 title = self._html_search_regex(
586 r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
587 webpage, 'title')
588 episode_paths = re.findall(
9e03aa75 589 r'(?s)<li id="showview_videos_media_(\d+)"[^>]+>.*?<a href="([^"]+)"',
09e5d6a6
PH
590 webpage)
591 entries = [
9e03aa75
RA
592 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll', ep_id)
593 for ep_id, ep in episode_paths
09e5d6a6
PH
594 ]
595 entries.reverse()
596
8230018c 597 return {
09e5d6a6
PH
598 '_type': 'playlist',
599 'id': show_id,
600 'title': title,
601 'entries': entries,
602 }