]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/youku.py
69ecc837a4d6d94c82a1055cb7cc41d6e6663763
[youtubedl] / youtube_dl / extractor / youku.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5
6 from .common import InfoExtractor
7 from ..compat import (
8 compat_urllib_parse,
9 compat_ord,
10 )
11 from ..utils import (
12 ExtractorError,
13 sanitized_Request,
14 )
15
16
17 class YoukuIE(InfoExtractor):
18 IE_NAME = 'youku'
19 IE_DESC = '优酷'
20 _VALID_URL = r'''(?x)
21 (?:
22 http://(?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
23 youku:)
24 (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
25 '''
26
27 _TESTS = [{
28 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
29 'md5': '5f3af4192eabacc4501508d54a8cabd7',
30 'info_dict': {
31 'id': 'XMTc1ODE5Njcy_part1',
32 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
33 'ext': 'flv'
34 }
35 }, {
36 'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
37 'only_matching': True,
38 }, {
39 'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
40 'info_dict': {
41 'id': 'XODgxNjg1Mzk2',
42 'title': '武媚娘传奇 85',
43 },
44 'playlist_count': 11,
45 }, {
46 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
47 'info_dict': {
48 'id': 'XMTI1OTczNDM5Mg',
49 'title': '花千骨 04',
50 },
51 'playlist_count': 13,
52 'skip': 'Available in China only',
53 }, {
54 'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
55 'note': 'Video protected with password',
56 'info_dict': {
57 'id': 'XNjA1NzA2Njgw',
58 'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
59 },
60 'playlist_count': 19,
61 'params': {
62 'videopassword': '100600',
63 },
64 }]
65
66 def construct_video_urls(self, data1, data2):
67 # get sid, token
68 def yk_t(s1, s2):
69 ls = list(range(256))
70 t = 0
71 for i in range(256):
72 t = (t + ls[i] + compat_ord(s1[i % len(s1)])) % 256
73 ls[i], ls[t] = ls[t], ls[i]
74 s = bytearray()
75 x, y = 0, 0
76 for i in range(len(s2)):
77 y = (y + 1) % 256
78 x = (x + ls[y]) % 256
79 ls[x], ls[y] = ls[y], ls[x]
80 s.append(compat_ord(s2[i]) ^ ls[(ls[x] + ls[y]) % 256])
81 return bytes(s)
82
83 sid, token = yk_t(
84 b'becaf9be', base64.b64decode(data2['ep'].encode('ascii'))
85 ).decode('ascii').split('_')
86
87 # get oip
88 oip = data2['ip']
89
90 # get fileid
91 string_ls = list(
92 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890')
93 shuffled_string_ls = []
94 seed = data1['seed']
95 N = len(string_ls)
96 for ii in range(N):
97 seed = (seed * 0xd3 + 0x754f) % 0x10000
98 idx = seed * len(string_ls) // 0x10000
99 shuffled_string_ls.append(string_ls[idx])
100 del string_ls[idx]
101
102 fileid_dict = {}
103 for format in data1['streamtypes']:
104 streamfileid = [
105 int(i) for i in data1['streamfileids'][format].strip('*').split('*')]
106 fileid = ''.join(
107 [shuffled_string_ls[i] for i in streamfileid])
108 fileid_dict[format] = fileid[:8] + '%s' + fileid[10:]
109
110 def get_fileid(format, n):
111 fileid = fileid_dict[format] % hex(int(n))[2:].upper().zfill(2)
112 return fileid
113
114 # get ep
115 def generate_ep(format, n):
116 fileid = get_fileid(format, n)
117 ep_t = yk_t(
118 b'bf7e5f01',
119 ('%s_%s_%s' % (sid, fileid, token)).encode('ascii')
120 )
121 ep = base64.b64encode(ep_t).decode('ascii')
122 return ep
123
124 # generate video_urls
125 video_urls_dict = {}
126 for format in data1['streamtypes']:
127 video_urls = []
128 for dt in data1['segs'][format]:
129 n = str(int(dt['no']))
130 param = {
131 'K': dt['k'],
132 'hd': self.get_hd(format),
133 'myp': 0,
134 'ts': dt['seconds'],
135 'ypp': 0,
136 'ctype': 12,
137 'ev': 1,
138 'token': token,
139 'oip': oip,
140 'ep': generate_ep(format, n)
141 }
142 video_url = \
143 'http://k.youku.com/player/getFlvPath/' + \
144 'sid/' + sid + \
145 '_' + str(int(n) + 1).zfill(2) + \
146 '/st/' + self.parse_ext_l(format) + \
147 '/fileid/' + get_fileid(format, n) + '?' + \
148 compat_urllib_parse.urlencode(param)
149 video_urls.append(video_url)
150 video_urls_dict[format] = video_urls
151
152 return video_urls_dict
153
154 def get_hd(self, fm):
155 hd_id_dict = {
156 'flv': '0',
157 'mp4': '1',
158 'hd2': '2',
159 'hd3': '3',
160 '3gp': '0',
161 '3gphd': '1'
162 }
163 return hd_id_dict[fm]
164
165 def parse_ext_l(self, fm):
166 ext_dict = {
167 'flv': 'flv',
168 'mp4': 'mp4',
169 'hd2': 'flv',
170 'hd3': 'flv',
171 '3gp': 'flv',
172 '3gphd': 'mp4'
173 }
174 return ext_dict[fm]
175
176 def get_format_name(self, fm):
177 _dict = {
178 '3gp': 'h6',
179 '3gphd': 'h5',
180 'flv': 'h4',
181 'mp4': 'h3',
182 'hd2': 'h2',
183 'hd3': 'h1'
184 }
185 return _dict[fm]
186
187 def _real_extract(self, url):
188 video_id = self._match_id(url)
189
190 def retrieve_data(req_url, note):
191 req = sanitized_Request(req_url)
192
193 cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
194 if cn_verification_proxy:
195 req.add_header('Ytdl-request-proxy', cn_verification_proxy)
196
197 raw_data = self._download_json(req, video_id, note=note)
198 return raw_data['data'][0]
199
200 video_password = self._downloader.params.get('videopassword', None)
201
202 # request basic data
203 basic_data_url = 'http://v.youku.com/player/getPlayList/VideoIDS/%s' % video_id
204 if video_password:
205 basic_data_url += '?password=%s' % video_password
206
207 data1 = retrieve_data(
208 basic_data_url,
209 'Downloading JSON metadata 1')
210 data2 = retrieve_data(
211 'http://v.youku.com/player/getPlayList/VideoIDS/%s/Pf/4/ctype/12/ev/1' % video_id,
212 'Downloading JSON metadata 2')
213
214 error_code = data1.get('error_code')
215 if error_code:
216 error = data1.get('error')
217 if error is not None and '因版权原因无法观看此视频' in error:
218 raise ExtractorError(
219 'Youku said: Sorry, this video is available in China only', expected=True)
220 else:
221 msg = 'Youku server reported error %i' % error_code
222 if error is not None:
223 msg += ': ' + error
224 raise ExtractorError(msg)
225
226 title = data1['title']
227
228 # generate video_urls_dict
229 video_urls_dict = self.construct_video_urls(data1, data2)
230
231 # construct info
232 entries = [{
233 'id': '%s_part%d' % (video_id, i + 1),
234 'title': title,
235 'formats': [],
236 # some formats are not available for all parts, we have to detect
237 # which one has all
238 } for i in range(max(len(v) for v in data1['segs'].values()))]
239 for fm in data1['streamtypes']:
240 video_urls = video_urls_dict[fm]
241 for video_url, seg, entry in zip(video_urls, data1['segs'][fm], entries):
242 entry['formats'].append({
243 'url': video_url,
244 'format_id': self.get_format_name(fm),
245 'ext': self.parse_ext_l(fm),
246 'filesize': int(seg['size']),
247 })
248
249 return {
250 '_type': 'multi_video',
251 'id': video_id,
252 'title': title,
253 'entries': entries,
254 }