]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/letv.py
9665ece89c9bc4cd64707ca3f7516749e4a33e91
[youtubedl] / youtube_dl / extractor / letv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import datetime
5 import re
6 import time
7 import base64
8 import hashlib
9
10 from .common import InfoExtractor
11 from ..compat import (
12 compat_urllib_parse,
13 compat_ord,
14 compat_str,
15 )
16 from ..utils import (
17 determine_ext,
18 ExtractorError,
19 parse_iso8601,
20 sanitized_Request,
21 int_or_none,
22 str_or_none,
23 encode_data_uri,
24 url_basename,
25 )
26
27
28 class LetvIE(InfoExtractor):
29 IE_DESC = '乐视网'
30 _VALID_URL = r'http://www\.letv\.com/ptv/vplay/(?P<id>\d+).html'
31
32 _TESTS = [{
33 'url': 'http://www.letv.com/ptv/vplay/22005890.html',
34 'md5': 'edadcfe5406976f42f9f266057ee5e40',
35 'info_dict': {
36 'id': '22005890',
37 'ext': 'mp4',
38 'title': '第87届奥斯卡颁奖礼完美落幕 《鸟人》成最大赢家',
39 'description': 'md5:a9cb175fd753e2962176b7beca21a47c',
40 },
41 'params': {
42 'hls_prefer_native': True,
43 },
44 }, {
45 'url': 'http://www.letv.com/ptv/vplay/1415246.html',
46 'info_dict': {
47 'id': '1415246',
48 'ext': 'mp4',
49 'title': '美人天下01',
50 'description': 'md5:f88573d9d7225ada1359eaf0dbf8bcda',
51 },
52 'params': {
53 'hls_prefer_native': True,
54 },
55 }, {
56 'note': 'This video is available only in Mainland China, thus a proxy is needed',
57 'url': 'http://www.letv.com/ptv/vplay/1118082.html',
58 'md5': '2424c74948a62e5f31988438979c5ad1',
59 'info_dict': {
60 'id': '1118082',
61 'ext': 'mp4',
62 'title': '与龙共舞 完整版',
63 'description': 'md5:7506a5eeb1722bb9d4068f85024e3986',
64 },
65 'params': {
66 'hls_prefer_native': True,
67 },
68 'skip': 'Only available in China',
69 }]
70
71 @staticmethod
72 def urshift(val, n):
73 return val >> n if val >= 0 else (val + 0x100000000) >> n
74
75 # ror() and calc_time_key() are reversed from a embedded swf file in KLetvPlayer.swf
76 def ror(self, param1, param2):
77 _loc3_ = 0
78 while _loc3_ < param2:
79 param1 = self.urshift(param1, 1) + ((param1 & 1) << 31)
80 _loc3_ += 1
81 return param1
82
83 def calc_time_key(self, param1):
84 _loc2_ = 773625421
85 _loc3_ = self.ror(param1, _loc2_ % 13)
86 _loc3_ = _loc3_ ^ _loc2_
87 _loc3_ = self.ror(_loc3_, _loc2_ % 17)
88 return _loc3_
89
90 # see M3U8Encryption class in KLetvPlayer.swf
91 @staticmethod
92 def decrypt_m3u8(encrypted_data):
93 if encrypted_data[:5].decode('utf-8').lower() != 'vc_01':
94 return encrypted_data
95 encrypted_data = encrypted_data[5:]
96
97 _loc4_ = bytearray()
98 while encrypted_data:
99 b = compat_ord(encrypted_data[0])
100 _loc4_.extend([b // 16, b & 0x0f])
101 encrypted_data = encrypted_data[1:]
102 idx = len(_loc4_) - 11
103 _loc4_ = _loc4_[idx:] + _loc4_[:idx]
104 _loc7_ = bytearray()
105 while _loc4_:
106 _loc7_.append(_loc4_[0] * 16 + _loc4_[1])
107 _loc4_ = _loc4_[2:]
108
109 return bytes(_loc7_)
110
111 def _real_extract(self, url):
112 media_id = self._match_id(url)
113 page = self._download_webpage(url, media_id)
114 params = {
115 'id': media_id,
116 'platid': 1,
117 'splatid': 101,
118 'format': 1,
119 'tkey': self.calc_time_key(int(time.time())),
120 'domain': 'www.letv.com'
121 }
122 play_json_req = sanitized_Request(
123 'http://api.letv.com/mms/out/video/playJson?' + compat_urllib_parse.urlencode(params)
124 )
125 cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
126 if cn_verification_proxy:
127 play_json_req.add_header('Ytdl-request-proxy', cn_verification_proxy)
128
129 play_json = self._download_json(
130 play_json_req,
131 media_id, 'Downloading playJson data')
132
133 # Check for errors
134 playstatus = play_json['playstatus']
135 if playstatus['status'] == 0:
136 flag = playstatus['flag']
137 if flag == 1:
138 msg = 'Country %s auth error' % playstatus['country']
139 else:
140 msg = 'Generic error. flag = %d' % flag
141 raise ExtractorError(msg, expected=True)
142
143 playurl = play_json['playurl']
144
145 formats = ['350', '1000', '1300', '720p', '1080p']
146 dispatch = playurl['dispatch']
147
148 urls = []
149 for format_id in formats:
150 if format_id in dispatch:
151 media_url = playurl['domain'][0] + dispatch[format_id][0]
152 media_url += '&' + compat_urllib_parse.urlencode({
153 'm3v': 1,
154 'format': 1,
155 'expect': 3,
156 'rateid': format_id,
157 })
158
159 nodes_data = self._download_json(
160 media_url, media_id,
161 'Download JSON metadata for format %s' % format_id)
162
163 req = self._request_webpage(
164 nodes_data['nodelist'][0]['location'], media_id,
165 note='Downloading m3u8 information for format %s' % format_id)
166
167 m3u8_data = self.decrypt_m3u8(req.read())
168
169 url_info_dict = {
170 'url': encode_data_uri(m3u8_data, 'application/vnd.apple.mpegurl'),
171 'ext': determine_ext(dispatch[format_id][1]),
172 'format_id': format_id,
173 'protocol': 'm3u8',
174 }
175
176 if format_id[-1:] == 'p':
177 url_info_dict['height'] = int_or_none(format_id[:-1])
178
179 urls.append(url_info_dict)
180
181 publish_time = parse_iso8601(self._html_search_regex(
182 r'发布时间&nbsp;([^<>]+) ', page, 'publish time', default=None),
183 delimiter=' ', timezone=datetime.timedelta(hours=8))
184 description = self._html_search_meta('description', page, fatal=False)
185
186 return {
187 'id': media_id,
188 'formats': urls,
189 'title': playurl['title'],
190 'thumbnail': playurl['pic'],
191 'description': description,
192 'timestamp': publish_time,
193 }
194
195
196 class LetvTvIE(InfoExtractor):
197 _VALID_URL = r'http://www.letv.com/tv/(?P<id>\d+).html'
198 _TESTS = [{
199 'url': 'http://www.letv.com/tv/46177.html',
200 'info_dict': {
201 'id': '46177',
202 'title': '美人天下',
203 'description': 'md5:395666ff41b44080396e59570dbac01c'
204 },
205 'playlist_count': 35
206 }]
207
208 def _real_extract(self, url):
209 playlist_id = self._match_id(url)
210 page = self._download_webpage(url, playlist_id)
211
212 media_urls = list(set(re.findall(
213 r'http://www.letv.com/ptv/vplay/\d+.html', page)))
214 entries = [self.url_result(media_url, ie='Letv')
215 for media_url in media_urls]
216
217 title = self._html_search_meta('keywords', page,
218 fatal=False).split(',')[0]
219 description = self._html_search_meta('description', page, fatal=False)
220
221 return self.playlist_result(entries, playlist_id, playlist_title=title,
222 playlist_description=description)
223
224
225 class LetvPlaylistIE(LetvTvIE):
226 _VALID_URL = r'http://tv.letv.com/[a-z]+/(?P<id>[a-z]+)/index.s?html'
227 _TESTS = [{
228 'url': 'http://tv.letv.com/izt/wuzetian/index.html',
229 'info_dict': {
230 'id': 'wuzetian',
231 'title': '武媚娘传奇',
232 'description': 'md5:e12499475ab3d50219e5bba00b3cb248'
233 },
234 # This playlist contains some extra videos other than the drama itself
235 'playlist_mincount': 96
236 }, {
237 'url': 'http://tv.letv.com/pzt/lswjzzjc/index.shtml',
238 'info_dict': {
239 'id': 'lswjzzjc',
240 # The title should be "劲舞青春", but I can't find a simple way to
241 # determine the playlist title
242 'title': '乐视午间自制剧场',
243 'description': 'md5:b1eef244f45589a7b5b1af9ff25a4489'
244 },
245 'playlist_mincount': 7
246 }]
247
248
249 class LetvCloudIE(InfoExtractor):
250 IE_DESC = '乐视云'
251 _VALID_URL = r'https?://yuntv\.letv\.com/bcloud.html\?.+'
252
253 _TESTS = [{
254 'url': 'http://yuntv.letv.com/bcloud.html?uu=p7jnfw5hw9&vu=467623dedf',
255 'md5': '26450599afd64c513bc77030ad15db44',
256 'info_dict': {
257 'id': 'p7jnfw5hw9_467623dedf',
258 'ext': 'mp4',
259 'title': 'Video p7jnfw5hw9_467623dedf',
260 },
261 }, {
262 'url': 'http://yuntv.letv.com/bcloud.html?uu=p7jnfw5hw9&vu=ec93197892&pu=2c7cd40209&auto_play=1&gpcflag=1&width=640&height=360',
263 'md5': 'e03d9cc8d9c13191e1caf277e42dbd31',
264 'info_dict': {
265 'id': 'p7jnfw5hw9_ec93197892',
266 'ext': 'mp4',
267 'title': 'Video p7jnfw5hw9_ec93197892',
268 },
269 }, {
270 'url': 'http://yuntv.letv.com/bcloud.html?uu=p7jnfw5hw9&vu=187060b6fd',
271 'md5': 'cb988699a776b22d4a41b9d43acfb3ac',
272 'info_dict': {
273 'id': 'p7jnfw5hw9_187060b6fd',
274 'ext': 'mp4',
275 'title': 'Video p7jnfw5hw9_187060b6fd',
276 },
277 }]
278
279 @staticmethod
280 def sign_data(obj):
281 if obj['cf'] == 'flash':
282 salt = '2f9d6924b33a165a6d8b5d3d42f4f987'
283 items = ['cf', 'format', 'ran', 'uu', 'ver', 'vu']
284 elif obj['cf'] == 'html5':
285 salt = 'fbeh5player12c43eccf2bec3300344'
286 items = ['cf', 'ran', 'uu', 'bver', 'vu']
287 input_data = ''.join([item + obj[item] for item in items]) + salt
288 obj['sign'] = hashlib.md5(input_data.encode('utf-8')).hexdigest()
289
290 def _get_formats(self, cf, uu, vu, media_id):
291 def get_play_json(cf, timestamp):
292 data = {
293 'cf': cf,
294 'ver': '2.2',
295 'bver': 'firefox44.0',
296 'format': 'json',
297 'uu': uu,
298 'vu': vu,
299 'ran': compat_str(timestamp),
300 }
301 self.sign_data(data)
302 return self._download_json(
303 'http://api.letvcloud.com/gpc.php?' + compat_urllib_parse.urlencode(data),
304 media_id, 'Downloading playJson data for type %s' % cf)
305
306 play_json = get_play_json(cf, time.time())
307 # The server time may be different from local time
308 if play_json.get('code') == 10071:
309 play_json = get_play_json(cf, play_json['timestamp'])
310
311 if not play_json.get('data'):
312 if play_json.get('message'):
313 raise ExtractorError('Letv cloud said: %s' % play_json['message'], expected=True)
314 elif play_json.get('code'):
315 raise ExtractorError('Letv cloud returned error %d' % play_json['code'], expected=True)
316 else:
317 raise ExtractorError('Letv cloud returned an unknwon error')
318
319 def b64decode(s):
320 return base64.b64decode(s.encode('utf-8')).decode('utf-8')
321
322 formats = []
323 for media in play_json['data']['video_info']['media'].values():
324 play_url = media['play_url']
325 url = b64decode(play_url['main_url'])
326 decoded_url = b64decode(url_basename(url))
327 formats.append({
328 'url': url,
329 'ext': determine_ext(decoded_url),
330 'format_id': int_or_none(play_url.get('vtype')),
331 'format_note': str_or_none(play_url.get('definition')),
332 'width': int_or_none(play_url.get('vwidth')),
333 'height': int_or_none(play_url.get('vheight')),
334 })
335
336 return formats
337
338 def _real_extract(self, url):
339 uu_mobj = re.search('uu=([\w]+)', url)
340 vu_mobj = re.search('vu=([\w]+)', url)
341
342 if not uu_mobj or not vu_mobj:
343 raise ExtractorError('Invalid URL: %s' % url, expected=True)
344
345 uu = uu_mobj.group(1)
346 vu = vu_mobj.group(1)
347 media_id = uu + '_' + vu
348
349 formats = self._get_formats('flash', uu, vu, media_id) + self._get_formats('html5', uu, vu, media_id)
350 self._sort_formats(formats)
351
352 return {
353 'id': media_id,
354 'title': 'Video %s' % media_id,
355 'formats': formats,
356 }