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