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