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