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