effd9eb922c5b164fc5a8b622b8f780b0139d0a9
[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
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_urllib_parse,
11     compat_urllib_request,
12     compat_ord,
13 )
14 from ..utils import (
15     determine_ext,
16     ExtractorError,
17     parse_iso8601,
18     int_or_none,
19     encode_data_uri,
20 )
21
22
23 class LetvIE(InfoExtractor):
24     IE_DESC = '乐视网'
25     _VALID_URL = r'http://www\.letv\.com/ptv/vplay/(?P<id>\d+).html'
26
27     _TESTS = [{
28         'url': 'http://www.letv.com/ptv/vplay/22005890.html',
29         'md5': 'edadcfe5406976f42f9f266057ee5e40',
30         'info_dict': {
31             'id': '22005890',
32             'ext': 'mp4',
33             'title': '第87届奥斯卡颁奖礼完美落幕 《鸟人》成最大赢家',
34             'description': 'md5:a9cb175fd753e2962176b7beca21a47c',
35         },
36         'params': {
37             'hls_prefer_native': True,
38         },
39     }, {
40         'url': 'http://www.letv.com/ptv/vplay/1415246.html',
41         'info_dict': {
42             'id': '1415246',
43             'ext': 'mp4',
44             'title': '美人天下01',
45             'description': 'md5:f88573d9d7225ada1359eaf0dbf8bcda',
46         },
47         'params': {
48             'hls_prefer_native': True,
49         },
50     }, {
51         'note': 'This video is available only in Mainland China, thus a proxy is needed',
52         'url': 'http://www.letv.com/ptv/vplay/1118082.html',
53         'md5': '2424c74948a62e5f31988438979c5ad1',
54         'info_dict': {
55             'id': '1118082',
56             'ext': 'mp4',
57             'title': '与龙共舞 完整版',
58             'description': 'md5:7506a5eeb1722bb9d4068f85024e3986',
59         },
60         'params': {
61             'hls_prefer_native': True,
62         },
63         'skip': 'Only available in China',
64     }]
65
66     @staticmethod
67     def urshift(val, n):
68         return val >> n if val >= 0 else (val + 0x100000000) >> n
69
70     # ror() and calc_time_key() are reversed from a embedded swf file in KLetvPlayer.swf
71     def ror(self, param1, param2):
72         _loc3_ = 0
73         while _loc3_ < param2:
74             param1 = self.urshift(param1, 1) + ((param1 & 1) << 31)
75             _loc3_ += 1
76         return param1
77
78     def calc_time_key(self, param1):
79         _loc2_ = 773625421
80         _loc3_ = self.ror(param1, _loc2_ % 13)
81         _loc3_ = _loc3_ ^ _loc2_
82         _loc3_ = self.ror(_loc3_, _loc2_ % 17)
83         return _loc3_
84
85     # see M3U8Encryption class in KLetvPlayer.swf
86     @staticmethod
87     def decrypt_m3u8(encrypted_data):
88         if encrypted_data[:5].decode('utf-8').lower() != 'vc_01':
89             return encrypted_data
90         encrypted_data = encrypted_data[5:]
91
92         _loc4_ = bytearray()
93         while encrypted_data:
94             b = compat_ord(encrypted_data[0])
95             _loc4_.extend([b // 16, b & 0x0f])
96             encrypted_data = encrypted_data[1:]
97         idx = len(_loc4_) - 11
98         _loc4_ = _loc4_[idx:] + _loc4_[:idx]
99         _loc7_ = bytearray()
100         while _loc4_:
101             _loc7_.append(_loc4_[0] * 16 + _loc4_[1])
102             _loc4_ = _loc4_[2:]
103
104         return bytes(_loc7_)
105
106     def _real_extract(self, url):
107         media_id = self._match_id(url)
108         page = self._download_webpage(url, media_id)
109         params = {
110             'id': media_id,
111             'platid': 1,
112             'splatid': 101,
113             'format': 1,
114             'tkey': self.calc_time_key(int(time.time())),
115             'domain': 'www.letv.com'
116         }
117         play_json_req = compat_urllib_request.Request(
118             'http://api.letv.com/mms/out/video/playJson?' + compat_urllib_parse.urlencode(params)
119         )
120         cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
121         if cn_verification_proxy:
122             play_json_req.add_header('Ytdl-request-proxy', cn_verification_proxy)
123
124         play_json = self._download_json(
125             play_json_req,
126             media_id, 'Downloading playJson data')
127
128         # Check for errors
129         playstatus = play_json['playstatus']
130         if playstatus['status'] == 0:
131             flag = playstatus['flag']
132             if flag == 1:
133                 msg = 'Country %s auth error' % playstatus['country']
134             else:
135                 msg = 'Generic error. flag = %d' % flag
136             raise ExtractorError(msg, expected=True)
137
138         playurl = play_json['playurl']
139
140         formats = ['350', '1000', '1300', '720p', '1080p']
141         dispatch = playurl['dispatch']
142
143         urls = []
144         for format_id in formats:
145             if format_id in dispatch:
146                 media_url = playurl['domain'][0] + dispatch[format_id][0]
147                 media_url += '&' + compat_urllib_parse.urlencode({
148                     'm3v': 1,
149                     'format': 1,
150                     'expect': 3,
151                     'rateid': format_id,
152                 })
153
154                 nodes_data = self._download_json(
155                     media_url, media_id,
156                     'Download JSON metadata for format %s' % format_id)
157
158                 req = self._request_webpage(
159                     nodes_data['nodelist'][0]['location'], media_id,
160                     note='Downloading m3u8 information for format %s' % format_id)
161
162                 m3u8_data = self.decrypt_m3u8(req.read())
163
164                 url_info_dict = {
165                     'url': encode_data_uri(m3u8_data, 'application/vnd.apple.mpegurl'),
166                     'ext': determine_ext(dispatch[format_id][1]),
167                     'format_id': format_id,
168                     'protocol': 'm3u8',
169                 }
170
171                 if format_id[-1:] == 'p':
172                     url_info_dict['height'] = int_or_none(format_id[:-1])
173
174                 urls.append(url_info_dict)
175
176         publish_time = parse_iso8601(self._html_search_regex(
177             r'发布时间&nbsp;([^<>]+) ', page, 'publish time', default=None),
178             delimiter=' ', timezone=datetime.timedelta(hours=8))
179         description = self._html_search_meta('description', page, fatal=False)
180
181         return {
182             'id': media_id,
183             'formats': urls,
184             'title': playurl['title'],
185             'thumbnail': playurl['pic'],
186             'description': description,
187             'timestamp': publish_time,
188         }
189
190
191 class LetvTvIE(InfoExtractor):
192     _VALID_URL = r'http://www.letv.com/tv/(?P<id>\d+).html'
193     _TESTS = [{
194         'url': 'http://www.letv.com/tv/46177.html',
195         'info_dict': {
196             'id': '46177',
197             'title': '美人天下',
198             'description': 'md5:395666ff41b44080396e59570dbac01c'
199         },
200         'playlist_count': 35
201     }]
202
203     def _real_extract(self, url):
204         playlist_id = self._match_id(url)
205         page = self._download_webpage(url, playlist_id)
206
207         media_urls = list(set(re.findall(
208             r'http://www.letv.com/ptv/vplay/\d+.html', page)))
209         entries = [self.url_result(media_url, ie='Letv')
210                    for media_url in media_urls]
211
212         title = self._html_search_meta('keywords', page,
213                                        fatal=False).split(',')[0]
214         description = self._html_search_meta('description', page, fatal=False)
215
216         return self.playlist_result(entries, playlist_id, playlist_title=title,
217                                     playlist_description=description)
218
219
220 class LetvPlaylistIE(LetvTvIE):
221     _VALID_URL = r'http://tv.letv.com/[a-z]+/(?P<id>[a-z]+)/index.s?html'
222     _TESTS = [{
223         'url': 'http://tv.letv.com/izt/wuzetian/index.html',
224         'info_dict': {
225             'id': 'wuzetian',
226             'title': '武媚娘传奇',
227             'description': 'md5:e12499475ab3d50219e5bba00b3cb248'
228         },
229         # This playlist contains some extra videos other than the drama itself
230         'playlist_mincount': 96
231     }, {
232         'url': 'http://tv.letv.com/pzt/lswjzzjc/index.shtml',
233         'info_dict': {
234             'id': 'lswjzzjc',
235             # The title should be "劲舞青春", but I can't find a simple way to
236             # determine the playlist title
237             'title': '乐视午间自制剧场',
238             'description': 'md5:b1eef244f45589a7b5b1af9ff25a4489'
239         },
240         'playlist_mincount': 7
241     }]