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