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