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