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