[letv] Add --cn-verification-proxy (Closes #5077)
[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_urlparse,
13 )
14 from ..utils import (
15     determine_ext,
16     ExtractorError,
17     parse_iso8601,
18 )
19
20
21 class LetvIE(InfoExtractor):
22     _VALID_URL = r'http://www\.letv\.com/ptv/vplay/(?P<id>\d+).html'
23
24     _TESTS = [{
25         'url': 'http://www.letv.com/ptv/vplay/22005890.html',
26         'md5': 'cab23bd68d5a8db9be31c9a222c1e8df',
27         'info_dict': {
28             'id': '22005890',
29             'ext': 'mp4',
30             'title': '第87届奥斯卡颁奖礼完美落幕 《鸟人》成最大赢家',
31             'timestamp': 1424747397,
32             'upload_date': '20150224',
33             'description': 'md5:a9cb175fd753e2962176b7beca21a47c',
34         }
35     }, {
36         'url': 'http://www.letv.com/ptv/vplay/1415246.html',
37         'info_dict': {
38             'id': '1415246',
39             'ext': 'mp4',
40             'title': '美人天下01',
41             'description': 'md5:f88573d9d7225ada1359eaf0dbf8bcda',
42         },
43         'expected_warnings': [
44             'publish time'
45         ]
46     }, {
47         'note': 'This video is available only in Mainland China, thus a proxy is needed',
48         'url': 'http://www.letv.com/ptv/vplay/1118082.html',
49         'md5': 'f80936fbe20fb2f58648e81386ff7927',
50         'info_dict': {
51             'id': '1118082',
52             'ext': 'mp4',
53             'title': '与龙共舞 完整版',
54             'description': 'md5:7506a5eeb1722bb9d4068f85024e3986',
55         },
56         'expected_warnings': [
57             'publish time'
58         ],
59         'params': {
60             'cn_verification_proxy': 'proxy.uku.im:8888'
61         },
62     }]
63
64     @staticmethod
65     def urshift(val, n):
66         return val >> n if val >= 0 else (val + 0x100000000) >> n
67
68     # ror() and calc_time_key() are reversed from a embedded swf file in KLetvPlayer.swf
69     def ror(self, param1, param2):
70         _loc3_ = 0
71         while _loc3_ < param2:
72             param1 = self.urshift(param1, 1) + ((param1 & 1) << 31)
73             _loc3_ += 1
74         return param1
75
76     def calc_time_key(self, param1):
77         _loc2_ = 773625421
78         _loc3_ = self.ror(param1, _loc2_ % 13)
79         _loc3_ = _loc3_ ^ _loc2_
80         _loc3_ = self.ror(_loc3_, _loc2_ % 17)
81         return _loc3_
82
83     def _real_extract(self, url):
84         media_id = self._match_id(url)
85         page = self._download_webpage(url, media_id)
86         params = {
87             'id': media_id,
88             'platid': 1,
89             'splatid': 101,
90             'format': 1,
91             'tkey': self.calc_time_key(int(time.time())),
92             'domain': 'www.letv.com'
93         }
94         play_json_req = compat_urllib_request.Request(
95             'http://api.letv.com/mms/out/video/playJson?' + compat_urllib_parse.urlencode(params)
96         )
97         play_json_req.add_header(
98             'Ytdl-Request-Proxy',
99             self._downloader.params.get('cn_verification_proxy'))
100         play_json = self._download_json(
101             play_json_req,
102             media_id, 'playJson data')
103
104         # Check for errors
105         playstatus = play_json['playstatus']
106         if playstatus['status'] == 0:
107             flag = playstatus['flag']
108             if flag == 1:
109                 msg = 'Country %s auth error' % playstatus['country']
110             else:
111                 msg = 'Generic error. flag = %d' % flag
112             raise ExtractorError(msg, expected=True)
113
114         playurl = play_json['playurl']
115
116         formats = ['350', '1000', '1300', '720p', '1080p']
117         dispatch = playurl['dispatch']
118
119         urls = []
120         for format_id in formats:
121             if format_id in dispatch:
122                 media_url = playurl['domain'][0] + dispatch[format_id][0]
123
124                 # Mimic what flvxz.com do
125                 url_parts = list(compat_urlparse.urlparse(media_url))
126                 qs = dict(compat_urlparse.parse_qs(url_parts[4]))
127                 qs.update({
128                     'platid': '14',
129                     'splatid': '1401',
130                     'tss': 'no',
131                     'retry': 1
132                 })
133                 url_parts[4] = compat_urllib_parse.urlencode(qs)
134                 media_url = compat_urlparse.urlunparse(url_parts)
135
136                 url_info_dict = {
137                     'url': media_url,
138                     'ext': determine_ext(dispatch[format_id][1]),
139                     'format_id': format_id,
140                 }
141
142                 if format_id[-1:] == 'p':
143                     url_info_dict['height'] = format_id[:-1]
144
145                 urls.append(url_info_dict)
146
147         publish_time = parse_iso8601(self._html_search_regex(
148             r'发布时间&nbsp;([^<>]+) ', page, 'publish time', default=None),
149             delimiter=' ', timezone=datetime.timedelta(hours=8))
150         description = self._html_search_meta('description', page, fatal=False)
151
152         return {
153             'id': media_id,
154             'formats': urls,
155             'title': playurl['title'],
156             'thumbnail': playurl['pic'],
157             'description': description,
158             'timestamp': publish_time,
159         }
160
161
162 class LetvTvIE(InfoExtractor):
163     _VALID_URL = r'http://www.letv.com/tv/(?P<id>\d+).html'
164     _TESTS = [{
165         'url': 'http://www.letv.com/tv/46177.html',
166         'info_dict': {
167             'id': '46177',
168             'title': '美人天下',
169             'description': 'md5:395666ff41b44080396e59570dbac01c'
170         },
171         'playlist_count': 35
172     }]
173
174     def _real_extract(self, url):
175         playlist_id = self._match_id(url)
176         page = self._download_webpage(url, playlist_id)
177
178         media_urls = list(set(re.findall(
179             r'http://www.letv.com/ptv/vplay/\d+.html', page)))
180         entries = [self.url_result(media_url, ie='Letv')
181                    for media_url in media_urls]
182
183         title = self._html_search_meta('keywords', page,
184                                        fatal=False).split(',')[0]
185         description = self._html_search_meta('description', page, fatal=False)
186
187         return self.playlist_result(entries, playlist_id, playlist_title=title,
188                                     playlist_description=description)
189
190
191 class LetvPlaylistIE(LetvTvIE):
192     _VALID_URL = r'http://tv.letv.com/[a-z]+/(?P<id>[a-z]+)/index.s?html'
193     _TESTS = [{
194         'url': 'http://tv.letv.com/izt/wuzetian/index.html',
195         'info_dict': {
196             'id': 'wuzetian',
197             'title': '武媚娘传奇',
198             'description': 'md5:e12499475ab3d50219e5bba00b3cb248'
199         },
200         # This playlist contains some extra videos other than the drama itself
201         'playlist_mincount': 96
202     }, {
203         'url': 'http://tv.letv.com/pzt/lswjzzjc/index.shtml',
204         'info_dict': {
205             'id': 'lswjzzjc',
206             # The title should be "劲舞青春", but I can't find a simple way to
207             # determine the playlist title
208             'title': '乐视午间自制剧场',
209             'description': 'md5:b1eef244f45589a7b5b1af9ff25a4489'
210         },
211         'playlist_mincount': 7
212     }]