2 from __future__
import unicode_literals
8 import xml
.etree
.ElementTree
10 from hashlib
import sha1
11 from math
import pow, sqrt
, floor
12 from .subtitles
import SubtitlesInfoExtractor
16 compat_urllib_request
,
27 from .common
import InfoExtractor
30 class CrunchyrollIE(SubtitlesInfoExtractor
):
31 _VALID_URL
= r
'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
33 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
34 #'md5': 'b1639fd6ddfaa43788c85f6d1dddd412',
38 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
39 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
40 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
41 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
42 'upload_date': '20131013',
43 'url': 're:(?!.*&)',
47 'skip_download': True,
55 '1080': ('80', '108'),
59 (username
, password
) = self
._get
_login
_info
()
63 login_url
= 'https://www.crunchyroll.com/?a=formhandler'
64 data
= urlencode_postdata({
65 'formname': 'RpcApiUser_Login',
69 login_request
= compat_urllib_request
.Request(login_url
, data
)
70 login_request
.add_header('Content-Type', 'application/x-www-form-urlencoded')
71 self
._download
_webpage
(login_request
, None, False, 'Wrong login info')
74 def _real_initialize(self
):
78 def _decrypt_subtitles(self
, data
, iv
, id):
79 data
= bytes_to_intlist(data
)
80 iv
= bytes_to_intlist(iv
)
83 def obfuscate_key_aux(count
, modulo
, start
):
85 for _
in range(count
):
86 output
.append(output
[-1] + output
[-2])
87 # cut off start values
89 output
= list(map(lambda x
: x
% modulo
+ 33, output
))
92 def obfuscate_key(key
):
93 num1
= int(floor(pow(2, 25) * sqrt(6.9)))
94 num2
= (num1 ^ key
) << 5
96 num4
= num3 ^
(num3
>> 3) ^ num2
97 prefix
= intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
98 shaHash
= bytes_to_intlist(sha1(prefix
+ str(num4
).encode('ascii')).digest())
99 # Extend 160 Bit hash to 256 Bit
100 return shaHash
+ [0] * 12
102 key
= obfuscate_key(id)
105 def next_value(self
):
107 self
.__value
= inc(self
.__value
)
109 decrypted_data
= intlist_to_bytes(aes_cbc_decrypt(data
, key
, iv
))
110 return zlib
.decompress(decrypted_data
)
112 def _convert_subtitles_to_srt(self
, sub_root
):
115 for i
, event
in enumerate(sub_root
.findall('./events/event'), 1):
116 start
= event
.attrib
['start'].replace('.', ',')
117 end
= event
.attrib
['end'].replace('.', ',')
118 text
= event
.attrib
['text'].replace('\\N', '\n')
119 output
+= '%d\n%s --> %s\n%s\n\n' % (i
, start
, end
, text
)
122 def _convert_subtitles_to_ass(self
, sub_root
):
125 def ass_bool(strvalue
):
131 output
= '[Script Info]\n'
132 output
+= 'Title: %s\n' % sub_root
.attrib
["title"]
133 output
+= 'ScriptType: v4.00+\n'
134 output
+= 'WrapStyle: %s\n' % sub_root
.attrib
["wrap_style"]
135 output
+= 'PlayResX: %s\n' % sub_root
.attrib
["play_res_x"]
136 output
+= 'PlayResY: %s\n' % sub_root
.attrib
["play_res_y"]
137 output
+= """ScaledBorderAndShadow: yes
140 Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
142 for style
in sub_root
.findall('./styles/style'):
143 output
+= 'Style: ' + style
.attrib
["name"]
144 output
+= ',' + style
.attrib
["font_name"]
145 output
+= ',' + style
.attrib
["font_size"]
146 output
+= ',' + style
.attrib
["primary_colour"]
147 output
+= ',' + style
.attrib
["secondary_colour"]
148 output
+= ',' + style
.attrib
["outline_colour"]
149 output
+= ',' + style
.attrib
["back_colour"]
150 output
+= ',' + ass_bool(style
.attrib
["bold"])
151 output
+= ',' + ass_bool(style
.attrib
["italic"])
152 output
+= ',' + ass_bool(style
.attrib
["underline"])
153 output
+= ',' + ass_bool(style
.attrib
["strikeout"])
154 output
+= ',' + style
.attrib
["scale_x"]
155 output
+= ',' + style
.attrib
["scale_y"]
156 output
+= ',' + style
.attrib
["spacing"]
157 output
+= ',' + style
.attrib
["angle"]
158 output
+= ',' + style
.attrib
["border_style"]
159 output
+= ',' + style
.attrib
["outline"]
160 output
+= ',' + style
.attrib
["shadow"]
161 output
+= ',' + style
.attrib
["alignment"]
162 output
+= ',' + style
.attrib
["margin_l"]
163 output
+= ',' + style
.attrib
["margin_r"]
164 output
+= ',' + style
.attrib
["margin_v"]
165 output
+= ',' + style
.attrib
["encoding"]
170 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
172 for event
in sub_root
.findall('./events/event'):
173 output
+= 'Dialogue: 0'
174 output
+= ',' + event
.attrib
["start"]
175 output
+= ',' + event
.attrib
["end"]
176 output
+= ',' + event
.attrib
["style"]
177 output
+= ',' + event
.attrib
["name"]
178 output
+= ',' + event
.attrib
["margin_l"]
179 output
+= ',' + event
.attrib
["margin_r"]
180 output
+= ',' + event
.attrib
["margin_v"]
181 output
+= ',' + event
.attrib
["effect"]
182 output
+= ',' + event
.attrib
["text"]
187 def _real_extract(self
,url
):
188 mobj
= re
.match(self
._VALID
_URL
, url
)
189 video_id
= mobj
.group('video_id')
191 if mobj
.group('prefix') == 'm':
192 mobile_webpage
= self
._download
_webpage
(url
, video_id
, 'Downloading mobile webpage')
193 webpage_url
= self
._search
_regex
(r
'<link rel="canonical" href="([^"]+)" />', mobile_webpage
, 'webpage_url')
195 webpage_url
= 'http://www.' + mobj
.group('url')
197 webpage
= self
._download
_webpage
(webpage_url
, video_id
, 'Downloading webpage')
198 note_m
= self
._html
_search
_regex
(r
'<div class="showmedia-trailer-notice">(.+?)</div>', webpage
, 'trailer-notice', default
='')
200 raise ExtractorError(note_m
)
202 mobj
= re
.search(r
'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage
)
204 msg
= json
.loads(mobj
.group('msg'))
205 if msg
.get('type') == 'error':
206 raise ExtractorError('crunchyroll returned error: %s' % msg
['message_body'], expected
=True)
208 video_title
= self
._html
_search
_regex
(r
'<h1[^>]*>(.+?)</h1>', webpage
, 'video_title', flags
=re
.DOTALL
)
209 video_title
= re
.sub(r
' {2,}', ' ', video_title
)
210 video_description
= self
._html
_search
_regex
(r
'"description":"([^"]+)', webpage
, 'video_description', default
='')
211 if not video_description
:
212 video_description
= None
213 video_upload_date
= self
._html
_search
_regex
(r
'<div>Availability for free users:(.+?)</div>', webpage
, 'video_upload_date', fatal
=False, flags
=re
.DOTALL
)
214 if video_upload_date
:
215 video_upload_date
= unified_strdate(video_upload_date
)
216 video_uploader
= self
._html
_search
_regex
(r
'<div>\s*Publisher:(.+?)</div>', webpage
, 'video_uploader', fatal
=False, flags
=re
.DOTALL
)
218 playerdata_url
= compat_urllib_parse
.unquote(self
._html
_search
_regex
(r
'"config_url":"([^"]+)', webpage
, 'playerdata_url'))
219 playerdata_req
= compat_urllib_request
.Request(playerdata_url
)
220 playerdata_req
.data
= compat_urllib_parse
.urlencode({'current_page': webpage_url
})
221 playerdata_req
.add_header('Content-Type', 'application/x-www-form-urlencoded')
222 playerdata
= self
._download
_webpage
(playerdata_req
, video_id
, note
='Downloading media info')
224 stream_id
= self
._search
_regex
(r
'<media_id>([^<]+)', playerdata
, 'stream_id')
225 video_thumbnail
= self
._search
_regex
(r
'<episode_image_url>([^<]+)', playerdata
, 'thumbnail', fatal
=False)
228 for fmt
in re
.findall(r
'\?p([0-9]{3,4})=1', webpage
):
229 stream_quality
, stream_format
= self
._FORMAT
_IDS
[fmt
]
230 video_format
= fmt
+'p'
231 streamdata_req
= compat_urllib_request
.Request('http://www.crunchyroll.com/xml/')
232 # urlencode doesn't work!
233 streamdata_req
.data
= 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality='+stream_quality
+'&media%5Fid='+stream_id
+'&video%5Fformat='+stream_format
234 streamdata_req
.add_header('Content-Type', 'application/x-www-form-urlencoded')
235 streamdata_req
.add_header('Content-Length', str(len(streamdata_req
.data
)))
236 streamdata
= self
._download
_xml
(
237 streamdata_req
, video_id
,
238 note
='Downloading media info for %s' % video_format
)
239 video_url
= streamdata
.find('.//host').text
240 video_play_path
= streamdata
.find('.//file').text
243 'play_path': video_play_path
,
245 'format': video_format
,
246 'format_id': video_format
,
250 sub_format
= self
._downloader
.params
.get('subtitlesformat', 'srt')
251 for sub_id
, sub_name
in re
.findall(r
'\?ssid=([0-9]+)" title="([^"]+)', webpage
):
252 sub_page
= self
._download
_webpage
('http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id='+sub_id
,\
253 video_id
, note
='Downloading subtitles for '+sub_name
)
254 id = self
._search
_regex
(r
'id=\'([0-9]+)', sub_page, 'subtitle_id
', fatal=False)
255 iv = self._search_regex(r'<iv
>([^
<]+)', sub_page, 'subtitle_iv
', fatal=False)
256 data = self._search_regex(r'<data
>([^
<]+)', sub_page, 'subtitle_data
', fatal=False)
257 if not id or not iv or not data:
260 iv = base64.b64decode(iv)
261 data = base64.b64decode(data)
263 subtitle = self._decrypt_subtitles(data, iv, id).decode('utf
-8')
264 lang_code = self._search_regex(r'lang_code
=["\']([^"\']+)', subtitle, 'subtitle_lang_code
', fatal=False)
267 sub_root = xml.etree.ElementTree.fromstring(subtitle)
269 subtitles[lang_code] = ''
270 if sub_format == 'ass
':
271 subtitles[lang_code] = self._convert_subtitles_to_ass(sub_root)
273 subtitles[lang_code] = self._convert_subtitles_to_srt(sub_root)
275 if self._downloader.params.get('listsubtitles
', False):
276 self._list_available_subtitles(video_id, subtitles)
281 'title
': video_title,
282 'description
': video_description,
283 'thumbnail
': video_thumbnail,
284 'uploader
': video_uploader,
285 'upload_date
': video_upload_date,
286 'subtitles
': subtitles,
291 class CrunchyrollShowPlaylistIE(InfoExtractor):
292 IE_NAME = "crunchyroll:playlist"
293 _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\
-]+))/?$
'
296 'url
': 'http
://www
.crunchyroll
.com
/a
-bridge
-to
-the
-starry
-skies
-hoshizora
-e
-kakaru
-hashi
',
298 'id': 'a
-bridge
-to
-the
-starry
-skies
-hoshizora
-e
-kakaru
-hashi
',
299 'title
': 'A Bridge to the Starry Skies
- Hoshizora e Kakaru Hashi
'
301 'playlist_count
': 13,
304 def _real_extract(self, url):
305 show_id = self._match_id(url)
307 webpage = self._download_webpage(url, show_id)
308 title = self._html_search_regex(
309 r'(?s
)<h1
[^
>]*>\s
*<span itemprop
="name">(.*?
)</span
>',
311 episode_paths = re.findall(
312 r'(?s
)<li
id="showview_videos_media_[0-9]+"[^
>]+>.*?
<a href
="([^"]+)"',
315 self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
316 for ep in episode_paths