]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/youku.py
Update changelog.
[youtubedl] / youtube_dl / extractor / youku.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import itertools
6 import random
7 import re
8 import string
9 import time
10
11 from .common import InfoExtractor
12 from ..compat import (
13 compat_urllib_parse_urlencode,
14 compat_ord,
15 )
16 from ..utils import (
17 ExtractorError,
18 get_element_by_attribute,
19 sanitized_Request,
20 )
21
22
23 class YoukuIE(InfoExtractor):
24 IE_NAME = 'youku'
25 IE_DESC = '优酷'
26 _VALID_URL = r'''(?x)
27 (?:
28 http://(?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
29 youku:)
30 (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
31 '''
32
33 _TESTS = [{
34 # MD5 is unstable
35 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
36 'info_dict': {
37 'id': 'XMTc1ODE5Njcy_part1',
38 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
39 'ext': 'flv'
40 }
41 }, {
42 'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
43 'only_matching': True,
44 }, {
45 'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
46 'info_dict': {
47 'id': 'XODgxNjg1Mzk2',
48 'title': '武媚娘传奇 85',
49 },
50 'playlist_count': 11,
51 'skip': 'Available in China only',
52 }, {
53 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
54 'info_dict': {
55 'id': 'XMTI1OTczNDM5Mg',
56 'title': '花千骨 04',
57 },
58 'playlist_count': 13,
59 }, {
60 'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
61 'note': 'Video protected with password',
62 'info_dict': {
63 'id': 'XNjA1NzA2Njgw',
64 'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
65 },
66 'playlist_count': 19,
67 'params': {
68 'videopassword': '100600',
69 },
70 }, {
71 # /play/get.json contains streams with "channel_type":"tail"
72 'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
73 'info_dict': {
74 'id': 'XOTUxMzg4NDMy',
75 'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
76 },
77 'playlist_count': 6,
78 }]
79
80 def construct_video_urls(self, data):
81 # get sid, token
82 def yk_t(s1, s2):
83 ls = list(range(256))
84 t = 0
85 for i in range(256):
86 t = (t + ls[i] + compat_ord(s1[i % len(s1)])) % 256
87 ls[i], ls[t] = ls[t], ls[i]
88 s = bytearray()
89 x, y = 0, 0
90 for i in range(len(s2)):
91 y = (y + 1) % 256
92 x = (x + ls[y]) % 256
93 ls[x], ls[y] = ls[y], ls[x]
94 s.append(compat_ord(s2[i]) ^ ls[(ls[x] + ls[y]) % 256])
95 return bytes(s)
96
97 sid, token = yk_t(
98 b'becaf9be', base64.b64decode(data['security']['encrypt_string'].encode('ascii'))
99 ).decode('ascii').split('_')
100
101 # get oip
102 oip = data['security']['ip']
103
104 fileid_dict = {}
105 for stream in data['stream']:
106 if stream.get('channel_type') == 'tail':
107 continue
108 format = stream.get('stream_type')
109 fileid = stream['stream_fileid']
110 fileid_dict[format] = fileid
111
112 def get_fileid(format, n):
113 number = hex(int(str(n), 10))[2:].upper()
114 if len(number) == 1:
115 number = '0' + number
116 streamfileids = fileid_dict[format]
117 fileid = streamfileids[0:8] + number + streamfileids[10:]
118 return fileid
119
120 # get ep
121 def generate_ep(format, n):
122 fileid = get_fileid(format, n)
123 ep_t = yk_t(
124 b'bf7e5f01',
125 ('%s_%s_%s' % (sid, fileid, token)).encode('ascii')
126 )
127 ep = base64.b64encode(ep_t).decode('ascii')
128 return ep
129
130 # generate video_urls
131 video_urls_dict = {}
132 for stream in data['stream']:
133 if stream.get('channel_type') == 'tail':
134 continue
135 format = stream.get('stream_type')
136 video_urls = []
137 for dt in stream['segs']:
138 n = str(stream['segs'].index(dt))
139 param = {
140 'K': dt['key'],
141 'hd': self.get_hd(format),
142 'myp': 0,
143 'ypp': 0,
144 'ctype': 12,
145 'ev': 1,
146 'token': token,
147 'oip': oip,
148 'ep': generate_ep(format, n)
149 }
150 video_url = \
151 'http://k.youku.com/player/getFlvPath/' + \
152 'sid/' + sid + \
153 '_00' + \
154 '/st/' + self.parse_ext_l(format) + \
155 '/fileid/' + get_fileid(format, n) + '?' + \
156 compat_urllib_parse_urlencode(param)
157 video_urls.append(video_url)
158 video_urls_dict[format] = video_urls
159
160 return video_urls_dict
161
162 @staticmethod
163 def get_ysuid():
164 return '%d%s' % (int(time.time()), ''.join([
165 random.choice(string.ascii_letters) for i in range(3)]))
166
167 def get_hd(self, fm):
168 hd_id_dict = {
169 '3gp': '0',
170 '3gphd': '1',
171 'flv': '0',
172 'flvhd': '0',
173 'mp4': '1',
174 'mp4hd': '1',
175 'mp4hd2': '1',
176 'mp4hd3': '1',
177 'hd2': '2',
178 'hd3': '3',
179 }
180 return hd_id_dict[fm]
181
182 def parse_ext_l(self, fm):
183 ext_dict = {
184 '3gp': 'flv',
185 '3gphd': 'mp4',
186 'flv': 'flv',
187 'flvhd': 'flv',
188 'mp4': 'mp4',
189 'mp4hd': 'mp4',
190 'mp4hd2': 'flv',
191 'mp4hd3': 'flv',
192 'hd2': 'flv',
193 'hd3': 'flv',
194 }
195 return ext_dict[fm]
196
197 def get_format_name(self, fm):
198 _dict = {
199 '3gp': 'h6',
200 '3gphd': 'h5',
201 'flv': 'h4',
202 'flvhd': 'h4',
203 'mp4': 'h3',
204 'mp4hd': 'h3',
205 'mp4hd2': 'h4',
206 'mp4hd3': 'h4',
207 'hd2': 'h2',
208 'hd3': 'h1',
209 }
210 return _dict[fm]
211
212 def _real_extract(self, url):
213 video_id = self._match_id(url)
214
215 self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
216
217 def retrieve_data(req_url, note):
218 headers = {
219 'Referer': req_url,
220 }
221 self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
222 req = sanitized_Request(req_url, headers=headers)
223
224 cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
225 if cn_verification_proxy:
226 req.add_header('Ytdl-request-proxy', cn_verification_proxy)
227
228 raw_data = self._download_json(req, video_id, note=note)
229
230 return raw_data['data']
231
232 video_password = self._downloader.params.get('videopassword')
233
234 # request basic data
235 basic_data_url = 'http://play.youku.com/play/get.json?vid=%s&ct=12' % video_id
236 if video_password:
237 basic_data_url += '&pwd=%s' % video_password
238
239 data = retrieve_data(basic_data_url, 'Downloading JSON metadata')
240
241 error = data.get('error')
242 if error:
243 error_note = error.get('note')
244 if error_note is not None and '因版权原因无法观看此视频' in error_note:
245 raise ExtractorError(
246 'Youku said: Sorry, this video is available in China only', expected=True)
247 elif error_note and '该视频被设为私密' in error_note:
248 raise ExtractorError(
249 'Youku said: Sorry, this video is private', expected=True)
250 else:
251 msg = 'Youku server reported error %i' % error.get('code')
252 if error_note is not None:
253 msg += ': ' + error_note
254 raise ExtractorError(msg)
255
256 # get video title
257 title = data['video']['title']
258
259 # generate video_urls_dict
260 video_urls_dict = self.construct_video_urls(data)
261
262 # construct info
263 entries = [{
264 'id': '%s_part%d' % (video_id, i + 1),
265 'title': title,
266 'formats': [],
267 # some formats are not available for all parts, we have to detect
268 # which one has all
269 } for i in range(max(len(v.get('segs')) for v in data['stream']))]
270 for stream in data['stream']:
271 if stream.get('channel_type') == 'tail':
272 continue
273 fm = stream.get('stream_type')
274 video_urls = video_urls_dict[fm]
275 for video_url, seg, entry in zip(video_urls, stream['segs'], entries):
276 entry['formats'].append({
277 'url': video_url,
278 'format_id': self.get_format_name(fm),
279 'ext': self.parse_ext_l(fm),
280 'filesize': int(seg['size']),
281 'width': stream.get('width'),
282 'height': stream.get('height'),
283 })
284
285 return {
286 '_type': 'multi_video',
287 'id': video_id,
288 'title': title,
289 'entries': entries,
290 }
291
292
293 class YoukuShowIE(InfoExtractor):
294 _VALID_URL = r'https?://(?:www\.)?youku\.com/show_page/id_(?P<id>[0-9a-z]+)\.html'
295 IE_NAME = 'youku:show'
296
297 _TEST = {
298 'url': 'http://www.youku.com/show_page/id_zc7c670be07ff11e48b3f.html',
299 'info_dict': {
300 'id': 'zc7c670be07ff11e48b3f',
301 'title': '花千骨 未删减版',
302 'description': 'md5:578d4f2145ae3f9128d9d4d863312910',
303 },
304 'playlist_count': 50,
305 }
306
307 _PAGE_SIZE = 40
308
309 def _find_videos_in_page(self, webpage):
310 videos = re.findall(
311 r'<li><a[^>]+href="(?P<url>https?://v\.youku\.com/[^"]+)"[^>]+title="(?P<title>[^"]+)"', webpage)
312 return [
313 self.url_result(video_url, YoukuIE.ie_key(), title)
314 for video_url, title in videos]
315
316 def _real_extract(self, url):
317 show_id = self._match_id(url)
318 webpage = self._download_webpage(url, show_id)
319
320 entries = self._find_videos_in_page(webpage)
321
322 playlist_title = self._html_search_regex(
323 r'<span[^>]+class="name">([^<]+)</span>', webpage, 'playlist title', fatal=False)
324 detail_div = get_element_by_attribute('class', 'detail', webpage) or ''
325 playlist_description = self._html_search_regex(
326 r'<span[^>]+style="display:none"[^>]*>([^<]+)</span>',
327 detail_div, 'playlist description', fatal=False)
328
329 for idx in itertools.count(1):
330 episodes_page = self._download_webpage(
331 'http://www.youku.com/show_episode/id_%s.html' % show_id,
332 show_id, query={'divid': 'reload_%d' % (idx * self._PAGE_SIZE + 1)},
333 note='Downloading episodes page %d' % idx)
334 new_entries = self._find_videos_in_page(episodes_page)
335 entries.extend(new_entries)
336 if len(new_entries) < self._PAGE_SIZE:
337 break
338
339 return self.playlist_result(entries, show_id, playlist_title, playlist_description)