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