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