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