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