2 from __future__
import unicode_literals
9 from hashlib
import sha1
10 from math
import pow, sqrt
, floor
11 from .common
import InfoExtractor
12 from ..compat
import (
13 compat_etree_fromstring
,
14 compat_urllib_parse_urlencode
,
15 compat_urllib_request
,
36 class CrunchyrollBaseIE(InfoExtractor
):
37 _LOGIN_URL
= 'https://www.crunchyroll.com/login'
38 _LOGIN_FORM
= 'login_form'
39 _NETRC_MACHINE
= 'crunchyroll'
42 (username
, password
) = self
._get
_login
_info
()
46 login_page
= self
._download
_webpage
(
47 self
._LOGIN
_URL
, None, 'Downloading login page')
49 def is_logged(webpage
):
50 return '<title>Redirecting' in webpage
53 if is_logged(login_page
):
56 login_form_str
= self
._search
_regex
(
57 r
'(?P<form><form[^>]+?id=(["\'])%s\
2[^
>]*>)' % self._LOGIN_FORM,
58 login_page, 'login form
', group='form
')
60 post_url = extract_attributes(login_form_str).get('action
')
62 post_url = self._LOGIN_URL
63 elif not post_url.startswith('http
'):
64 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
66 login_form = self._form_hidden_inputs(self._LOGIN_FORM, login_page)
69 'login_form
[name
]': username,
70 'login_form
[password
]': password,
73 response = self._download_webpage(
74 post_url, None, 'Logging
in', 'Wrong login info
',
75 data=urlencode_postdata(login_form),
76 headers={'Content
-Type
': 'application
/x
-www
-form
-urlencoded
'})
79 if is_logged(response):
82 error = self._html_search_regex(
83 '(?s
)<ul
[^
>]+class=["\']messages["\'][^
>]*>(.+?
)</ul
>',
84 response, 'error message
', default=None)
86 raise ExtractorError('Unable to login
: %s' % error, expected=True)
88 raise ExtractorError('Unable to log
in')
90 def _real_initialize(self):
93 def _download_webpage(self, url_or_request, *args, **kwargs):
94 request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
95 else sanitized_Request(url_or_request))
96 # Accept-Language must be set explicitly to accept any language to avoid issues
97 # similar to https://github.com/rg3/youtube-dl/issues/6797.
98 # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
99 # should be imposed or not (from what I can see it just takes the first language
100 # ignoring the priority and requires it to correspond the IP). By the way this causes
101 # Crunchyroll to not work in georestriction cases in some browsers that don't place
102 # the locale lang first in header. However allowing any language seems to workaround the issue.
103 request
.add_header('Accept-Language', '*')
104 return super(CrunchyrollBaseIE
, self
)._download
_webpage
(request
, *args
, **kwargs
)
107 def _add_skip_wall(url
):
108 parsed_url
= compat_urlparse
.urlparse(url
)
109 qs
= compat_urlparse
.parse_qs(parsed_url
.query
)
110 # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
111 # > This content may be inappropriate for some people.
112 # > Are you sure you want to continue?
113 # since it's not disabled by default in crunchyroll account's settings.
114 # See https://github.com/rg3/youtube-dl/issues/7202.
115 qs
['skip_wall'] = ['1']
116 return compat_urlparse
.urlunparse(
117 parsed_url
._replace
(query
=compat_urllib_parse_urlencode(qs
, True)))
120 class CrunchyrollIE(CrunchyrollBaseIE
):
121 _VALID_URL
= r
'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
123 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
127 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
128 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
129 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
130 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
131 'upload_date': '20131013',
132 'url': 're:(?!.*&)',
136 'skip_download': True,
139 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
143 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
144 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
145 'thumbnail': r
're:^https?://.*\.jpg$',
146 'uploader': 'Danny Choo Network',
147 'upload_date': '20120213',
151 'skip_download': True,
153 'skip': 'Video gone',
155 'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409',
159 'title': 'Re:ZERO -Starting Life in Another World- Episode 5 – The Morning of Our Promise Is Still Distant',
160 'description': 'md5:97664de1ab24bbf77a9c01918cb7dca9',
161 'thumbnail': r
're:^https?://.*\.jpg$',
162 'uploader': 'TV TOKYO',
163 'upload_date': '20160508',
167 'skip_download': True,
170 'url': 'http://www.crunchyroll.com/konosuba-gods-blessing-on-this-wonderful-world/episode-1-give-me-deliverance-from-this-judicial-injustice-727589',
174 'title': "KONOSUBA -God's blessing on this wonderful world! 2 Episode 1 – Give Me Deliverance from this Judicial Injustice!",
175 'description': 'md5:cbcf05e528124b0f3a0a419fc805ea7d',
176 'thumbnail': r
're:^https?://.*\.jpg$',
177 'uploader': 'Kadokawa Pictures Inc.',
178 'upload_date': '20170118',
179 'series': "KONOSUBA -God's blessing on this wonderful world!",
181 'episode': 'Give Me Deliverance from this Judicial Injustice!',
186 'skip_download': True,
189 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
190 'only_matching': True,
192 # geo-restricted (US), 18+ maturity wall, non-premium available
193 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
194 'only_matching': True,
196 # A description with double quotes
197 'url': 'http://www.crunchyroll.com/11eyes/episode-1-piros-jszaka-red-night-535080',
201 'title': '11eyes Episode 1 – Piros éjszaka - Red Night',
202 'description': 'Kakeru and Yuka are thrown into an alternate nightmarish world they call "Red Night".',
203 'uploader': 'Marvelous AQL Inc.',
204 'upload_date': '20091021',
207 # Just test metadata extraction
208 'skip_download': True,
213 '360': ('60', '106'),
214 '480': ('61', '106'),
215 '720': ('62', '106'),
216 '1080': ('80', '108'),
219 def _decrypt_subtitles(self
, data
, iv
, id):
220 data
= bytes_to_intlist(base64
.b64decode(data
.encode('utf-8')))
221 iv
= bytes_to_intlist(base64
.b64decode(iv
.encode('utf-8')))
224 def obfuscate_key_aux(count
, modulo
, start
):
226 for _
in range(count
):
227 output
.append(output
[-1] + output
[-2])
228 # cut off start values
230 output
= list(map(lambda x
: x
% modulo
+ 33, output
))
233 def obfuscate_key(key
):
234 num1
= int(floor(pow(2, 25) * sqrt(6.9)))
235 num2
= (num1 ^ key
) << 5
237 num4
= num3 ^
(num3
>> 3) ^ num2
238 prefix
= intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
239 shaHash
= bytes_to_intlist(sha1(prefix
+ str(num4
).encode('ascii')).digest())
240 # Extend 160 Bit hash to 256 Bit
241 return shaHash
+ [0] * 12
243 key
= obfuscate_key(id)
245 decrypted_data
= intlist_to_bytes(aes_cbc_decrypt(data
, key
, iv
))
246 return zlib
.decompress(decrypted_data
)
248 def _convert_subtitles_to_srt(self
, sub_root
):
251 for i
, event
in enumerate(sub_root
.findall('./events/event'), 1):
252 start
= event
.attrib
['start'].replace('.', ',')
253 end
= event
.attrib
['end'].replace('.', ',')
254 text
= event
.attrib
['text'].replace('\\N', '\n')
255 output
+= '%d\n%s --> %s\n%s\n\n' % (i
, start
, end
, text
)
258 def _convert_subtitles_to_ass(self
, sub_root
):
261 def ass_bool(strvalue
):
267 output
= '[Script Info]\n'
268 output
+= 'Title: %s\n' % sub_root
.attrib
['title']
269 output
+= 'ScriptType: v4.00+\n'
270 output
+= 'WrapStyle: %s\n' % sub_root
.attrib
['wrap_style']
271 output
+= 'PlayResX: %s\n' % sub_root
.attrib
['play_res_x']
272 output
+= 'PlayResY: %s\n' % sub_root
.attrib
['play_res_y']
275 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
277 for style
in sub_root
.findall('./styles/style'):
278 output
+= 'Style: ' + style
.attrib
['name']
279 output
+= ',' + style
.attrib
['font_name']
280 output
+= ',' + style
.attrib
['font_size']
281 output
+= ',' + style
.attrib
['primary_colour']
282 output
+= ',' + style
.attrib
['secondary_colour']
283 output
+= ',' + style
.attrib
['outline_colour']
284 output
+= ',' + style
.attrib
['back_colour']
285 output
+= ',' + ass_bool(style
.attrib
['bold'])
286 output
+= ',' + ass_bool(style
.attrib
['italic'])
287 output
+= ',' + ass_bool(style
.attrib
['underline'])
288 output
+= ',' + ass_bool(style
.attrib
['strikeout'])
289 output
+= ',' + style
.attrib
['scale_x']
290 output
+= ',' + style
.attrib
['scale_y']
291 output
+= ',' + style
.attrib
['spacing']
292 output
+= ',' + style
.attrib
['angle']
293 output
+= ',' + style
.attrib
['border_style']
294 output
+= ',' + style
.attrib
['outline']
295 output
+= ',' + style
.attrib
['shadow']
296 output
+= ',' + style
.attrib
['alignment']
297 output
+= ',' + style
.attrib
['margin_l']
298 output
+= ',' + style
.attrib
['margin_r']
299 output
+= ',' + style
.attrib
['margin_v']
300 output
+= ',' + style
.attrib
['encoding']
305 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
307 for event
in sub_root
.findall('./events/event'):
308 output
+= 'Dialogue: 0'
309 output
+= ',' + event
.attrib
['start']
310 output
+= ',' + event
.attrib
['end']
311 output
+= ',' + event
.attrib
['style']
312 output
+= ',' + event
.attrib
['name']
313 output
+= ',' + event
.attrib
['margin_l']
314 output
+= ',' + event
.attrib
['margin_r']
315 output
+= ',' + event
.attrib
['margin_v']
316 output
+= ',' + event
.attrib
['effect']
317 output
+= ',' + event
.attrib
['text']
322 def _extract_subtitles(self
, subtitle
):
323 sub_root
= compat_etree_fromstring(subtitle
)
326 'data': self
._convert
_subtitles
_to
_srt
(sub_root
),
329 'data': self
._convert
_subtitles
_to
_ass
(sub_root
),
332 def _get_subtitles(self
, video_id
, webpage
):
334 for sub_id
, sub_name
in re
.findall(r
'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage
):
335 sub_page
= self
._download
_webpage
(
336 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id
,
337 video_id
, note
='Downloading subtitles for ' + sub_name
)
338 id = self
._search
_regex
(r
'id=\'([0-9]+)', sub_page, 'subtitle_id
', fatal=False)
339 iv = self._search_regex(r'<iv
>([^
<]+)', sub_page, 'subtitle_iv
', fatal=False)
340 data = self._search_regex(r'<data
>([^
<]+)', sub_page, 'subtitle_data
', fatal=False)
341 if not id or not iv or not data:
343 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf
-8')
344 lang_code = self._search_regex(r'lang_code
=["\']([^"\']+)', subtitle, 'subtitle_lang_code
', fatal=False)
347 subtitles[lang_code] = self._extract_subtitles(subtitle)
350 def _real_extract(self, url):
351 mobj = re.match(self._VALID_URL, url)
352 video_id = mobj.group('video_id
')
354 if mobj.group('prefix
') == 'm
':
355 mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage
')
356 webpage_url = self._search_regex(r'<link rel
="canonical" href
="([^"]+)" />', mobile_webpage, 'webpage_url')
358 webpage_url = 'http://www.' + mobj.group('url')
360 webpage = self._download_webpage(self._add_skip_wall(webpage_url), video_id, 'Downloading webpage')
361 note_m = self._html_search_regex(
362 r'<div class="showmedia
-trailer
-notice
">(.+?)</div>',
363 webpage, 'trailer-notice', default='')
365 raise ExtractorError(note_m)
367 mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
369 msg = json.loads(mobj.group('msg'))
370 if msg.get('type') == 'error':
371 raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
373 if 'To view this, please log in to verify you are 18 or older.' in webpage:
374 self.raise_login_required()
376 video_title = self._html_search_regex(
377 r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title
["\'][^>]*>(?:(?!<h1).)+?)</h1>',
378 webpage, 'video_title')
379 video_title = re.sub(r' {2,}', ' ', video_title)
380 video_description = self._parse_json(self._html_search_regex(
381 r'<script[^>]*>\s*.+?\[media_id=%s\].+?({.+?"description
"\s*:.+?})\);' % video_id,
382 webpage, 'description', default='{}'), video_id).get('description')
383 if video_description:
384 video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
385 video_upload_date = self._html_search_regex(
386 [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
387 webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
388 if video_upload_date:
389 video_upload_date = unified_strdate(video_upload_date)
390 video_uploader = self._html_search_regex(
391 r'<a[^>]+href="/publisher
/[^
"]+"[^
>]*>([^
<]+)</a
>', webpage,
392 'video_uploader
', fatal=False)
395 for a, fmt in re.findall(r'(<a
[^
>]+token
=["\']showmedia\.([0-9]{3,4})p["\'][^
>]+>)', webpage):
396 attrs = extract_attributes(a)
397 href = attrs.get('href
')
398 if href and '/freetrial
' in href:
400 available_fmts.append(fmt)
401 if not available_fmts:
402 for p in (r'token
=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\
.([0-9]{3,4})p
'):
403 available_fmts = re.findall(p, webpage)
406 video_encode_ids = []
408 for fmt in available_fmts:
409 stream_quality, stream_format = self._FORMAT_IDS[fmt]
410 video_format = fmt + 'p
'
411 streamdata_req = sanitized_Request(
412 'http
://www
.crunchyroll
.com
/xml
/?req
=RpcApiVideoPlayer_GetStandardConfig
&media_id
=%s&video_format
=%s&video_quality
=%s'
413 % (video_id, stream_format, stream_quality),
414 compat_urllib_parse_urlencode({'current_page
': url}).encode('utf
-8'))
415 streamdata_req.add_header('Content
-Type
', 'application
/x
-www
-form
-urlencoded
')
416 streamdata = self._download_xml(
417 streamdata_req, video_id,
418 note='Downloading media info
for %s' % video_format)
419 stream_info = streamdata.find('./{default}preload
/stream_info
')
420 video_encode_id = xpath_text(stream_info, './video_encode_id
')
421 if video_encode_id in video_encode_ids:
423 video_encode_ids.append(video_encode_id)
425 video_file = xpath_text(stream_info, './file')
428 if video_file.startswith('http
'):
429 formats.extend(self._extract_m3u8_formats(
430 video_file, video_id, 'mp4
', entry_protocol='m3u8_native
',
431 m3u8_id='hls
', fatal=False))
434 video_url = xpath_text(stream_info, './host
')
437 metadata = stream_info.find('./metadata
')
439 'format
': video_format,
440 'format_id
': video_format,
441 'height
': int_or_none(xpath_text(metadata, './height
')),
442 'width
': int_or_none(xpath_text(metadata, './width
')),
445 if '.fplive
.net
/' in video_url:
446 video_url = re.sub(r'^rtmpe?
://', 'http
://', video_url.strip())
447 parsed_video_url = compat_urlparse.urlparse(video_url)
448 direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
449 netloc='v
.lvlt
.crcdn
.net
',
450 path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
451 if self._is_valid_url(direct_video_url, video_id, video_format):
453 'url
': direct_video_url,
455 formats.append(format_info)
460 'play_path
': video_file,
463 formats.append(format_info)
464 self._sort_formats(formats)
466 metadata = self._download_xml(
467 'http
://www
.crunchyroll
.com
/xml
', video_id,
468 note='Downloading media info
', query={
469 'req
': 'RpcApiVideoPlayer_GetMediaMetadata
',
470 'media_id
': video_id,
473 subtitles = self.extract_subtitles(video_id, webpage)
475 # webpage provide more accurate data than series_title from XML
476 series = self._html_search_regex(
477 r'id=["\']showmedia_about_episode_num[^>]+>\s*<a[^>]+>([^<]+)',
478 webpage, 'series', default=xpath_text(metadata, 'series_title'))
480 episode = xpath_text(metadata, 'episode_title')
481 episode_number = int_or_none(xpath_text(metadata, 'episode_number'))
483 season_number = int_or_none(self._search_regex(
484 r'(?s)<h4[^>]+id=["\']showmedia_about_episode_num
[^
>]+>.+?
</h4
>\s
*<h4
>\s
*Season (\d
+)',
485 webpage, 'season number
', default=None))
489 'title
': video_title,
490 'description
': video_description,
491 'thumbnail
': xpath_text(metadata, 'episode_image_url
'),
492 'uploader
': video_uploader,
493 'upload_date
': video_upload_date,
495 'season_number
': season_number,
497 'episode_number
': episode_number,
498 'subtitles
': subtitles,
503 class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
504 IE_NAME = 'crunchyroll
:playlist
'
505 _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\
-]+))/?
(?
:\?|$
)'
508 'url
': 'http
://www
.crunchyroll
.com
/a
-bridge
-to
-the
-starry
-skies
-hoshizora
-e
-kakaru
-hashi
',
510 'id': 'a
-bridge
-to
-the
-starry
-skies
-hoshizora
-e
-kakaru
-hashi
',
511 'title
': 'A Bridge to the Starry Skies
- Hoshizora e Kakaru Hashi
'
513 'playlist_count
': 13,
515 # geo-restricted (US), 18+ maturity wall, non-premium available
516 'url
': 'http
://www
.crunchyroll
.com
/cosplay
-complex-ova
',
518 'id': 'cosplay
-complex-ova
',
519 'title
': 'Cosplay Complex OVA
'
522 'skip
': 'Georestricted
',
524 # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
525 'url
': 'http
://www
.crunchyroll
.com
/ladies
-versus
-butlers?skip_wall
=1',
526 'only_matching
': True,
529 def _real_extract(self, url):
530 show_id = self._match_id(url)
532 webpage = self._download_webpage(self._add_skip_wall(url), show_id)
533 title = self._html_search_regex(
534 r'(?s
)<h1
[^
>]*>\s
*<span itemprop
="name">(.*?
)</span
>',
536 episode_paths = re.findall(
537 r'(?s
)<li
id="showview_videos_media_(\d+)"[^
>]+>.*?
<a href
="([^"]+)"',
540 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll', ep_id)
541 for ep_id, ep in episode_paths