- Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathsdAPI.py
More file actions
Latest commit
304 lines (269 loc) · 11.6 KB
/
Copy pathsdAPI.py
File metadata and controls
304 lines (269 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Thomas Geppert [bluezed] - bluezed.apps@gmail.com
#
# This Program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This Program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this Program; see the file LICENSE.txt. If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# http://www.gnu.org/copyleft/gpl.html
#
importdatetime
importrequests
importxbmcgui
fromutilsimport*
fromstringsimport*
MAIN_URL='https://json.schedulesdirect.org/20141201'
classSdAPI(object):
def__init__(self, user=get_setting('sd.username'), passw=get_setting('sd.password')):
agent="KODI-%s"% (ADDON.getAddonInfo('id'))
self._headers= {'User-agent': agent}
xbmc.log("[%s] SD-Header set to: %s"% (ADDON.getAddonInfo('id'), self._headers),
xbmc.LOGDEBUG)
self._main_url=MAIN_URL
self._user=user
self.logged_in=False
self.changes_remaining=0
self.max_lineups=0
self.lineups= []
ifself._main_urlandself._userandpassw:
self._pass=passw# Needs to be SHA1-Hex!
self._get_token()
ifself.logged_in:
self._get_status()
else:
raiseSourceException('SD-Data not configured!')
def_get_token(self):
if'token'inself._headers:
delself._headers['token']
resp=self._post('token', {"password": self._pass, "username": self._user})
if'code'inrespandint(resp['code']) !=0:
xbmc.log("[%s] Error trying to log in: %s"% (ADDON.getAddonInfo('id'), resp['message']),
xbmc.LOGDEBUG)
xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), 'Error trying to log into SchedulesDirect:', resp['message'])
self.logged_in=False
elif'token'inresp:
xbmc.log("[%s] SD-Token received: %s"% (ADDON.getAddonInfo('id'), resp['token']),
xbmc.LOGDEBUG)
self._headers['token'] =resp['token']
self.logged_in=True
def_get_status(self):
status=self._get('status')
if'account'instatusand'maxLineups'instatus['account']:
self.max_lineups=int(status['account']['maxLineups'])
if'lineups'instatus:
self.lineups= []
forlineupinstatus['lineups']:
self.lineups.append(lineup['lineup'])
@staticmethod
def_check_resp(resp):
ifresp.status_code==requests.codes.ok:
info= (resp.text[:1000] +'..') iflen(resp.text) >1000elseresp.text
xbmc.log("[%s] Reply from SD: %s - %s"%
(ADDON.getAddonInfo('id'), resp.status_code, info), xbmc.LOGDEBUG)
returnTrue
else:
message=''
try:
info=resp.json()
if'message'ininfo:
message=info['message']
exceptValueError:
message=resp.text
xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), 'SchedulesDirect server reply:', message)
xbmc.log("[%s] SD-Server response: %s - %s"%
(ADDON.getAddonInfo('id'), resp.status_code, resp.text), xbmc.LOGDEBUG)
returnFalse
def_get(self, path):
url=MAIN_URL+"/"+path
xbmc.log('[%s] GET request: %s'% (ADDON.getAddonInfo('id'), url), xbmc.LOGDEBUG)
resp=requests.get(url, headers=self._headers)
ifself._check_resp(resp):
returnresp.json()
else:
return []
def_put(self, path):
url=MAIN_URL+"/"+path
xbmc.log('[%s] PUT request: %s'% (ADDON.getAddonInfo('id'), url), xbmc.LOGDEBUG)
resp=requests.put(url, headers=self._headers)
ifself._check_resp(resp):
returnresp.json()
else:
return []
def_post(self, path, post_data=None):
url=MAIN_URL+"/"+path
data=""
ifpost_data:
data=json.dumps(post_data)
info= (data[:1000] +'..') iflen(data) >1000elsedata
xbmc.log('[%s] POST request: %s - data: %s'% (ADDON.getAddonInfo('id'), url, info),
xbmc.LOGDEBUG)
resp=requests.post(url, headers=self._headers, data=data)
ifself._check_resp(resp):
returnresp.json()
else:
return []
def_delete(self, path):
url=MAIN_URL+"/"+path
xbmc.log('[%s] DELETE request: %s'% (ADDON.getAddonInfo('id'), url),
xbmc.LOGDEBUG)
resp=requests.delete(url, headers=self._headers)
ifself._check_resp(resp):
returnresp.json()
else:
return []
defget_user_lineups(self):
data=self._get('lineups')
lineups= []
self.lineups= []
if"lineups"indata:
forlineupindata['lineups']:
lineups.append(lineup)
self.lineups.append(lineup['lineup'])
returnlineups
defget_countries(self):
data=self._get('available/COUNTRIES')
countries= []
for_, country_listindata.iteritems():
forcountryincountry_list:
countries.append(country)
returncountries
defget_lineups(self, country, postcode):
data=self._get('headends?country=%s&postalcode=%s'% (country, postcode))
lineups= []
foritemindata:
if"lineups"initem:
forlineupinitem['lineups']:
lineups.append(lineup)
returnlineups
defget_stations(self, lineup):
data=self._get('lineups/%s'%lineup)
stations= []
if'stations'indata:
forstationindata['stations']:
logo=''
if'logo'instationand'URL'instation['logo']:
logo=station['logo']['URL']
logo_type=int(ADDON.getSetting('logos.source'))
iflogo_type==1:
logo="%s%s.png"% (ADDON.getSetting('logos.folder'),station['name'])
eliflogo_type==2:
url=ADDON.getSetting('logos.url').rstrip('/')
logo="%s/%s.png"% (url,station['name'].replace(' ','%20'))
channel=Channel(station['stationID'], station['name'], lineup, logo)
stations.append(channel)
returnstations
defsave_lineup(self, lineup):
resp=self._put('lineups/%s'%lineup)
if"changesRemaining"inresp:
self.changes_remaining=int(resp["changesRemaining"])
if"response"inrespandresp["response"] =="OK":
self.lineups.append(lineup)
returnTrue
else:
returnFalse
defdelete_lineup(self, lineup):
xbmc.log('[%s] Removing lineup "%s" form current lineups: %s'%
(ADDON.getAddonInfo('id'), str(lineup), str(self.lineups)), xbmc.LOGDEBUG)
resp=self._delete('lineups/%s'%lineup)
if"changesRemaining"inresp:
self.changes_remaining=int(resp["changesRemaining"])
if"response"inrespandresp["response"] =="OK":
self.lineups.remove(lineup)
returnTrue
else:
returnFalse
defget_schedules(self, stations, date, progress_callback):
req_data= []
dates= [date.strftime('%Y-%m-%d')]
date2=date
fordinrange(1, int(get_setting('sd.range'))):
date2=date2+datetime.timedelta(days=1)
dates.append(date2.strftime('%Y-%m-%d'))
forsinstations:
req_data.append({'stationID': s, 'date': dates})
resp=self._post('schedules', req_data)
ifprogress_callback:
ifnotprogress_callback(10):
raiseSourceException()
prg_list= []
schedule= []
forrecordinresp:
if"stationID"inrecord:
station_id=record['stationID']
else:
continue
if"programs"inrecord:
forprograminrecord['programs']:
p_id=program['programID']
start=program['airDateTime']
dur=program['duration']
prg_list.append(p_id)
schedule.append({'station_id': station_id, 'p_id': p_id, 'start': start,
'dur': dur, 'title': '', 'desc': '', 'logo': ''})
prg_count=len(prg_list)
ifprg_count<3000:
xbmc.log("[%s] Number of programs requested: %d"%
(ADDON.getAddonInfo('id'), prg_count), xbmc.LOGDEBUG)
p_resp=self._post('programs', prg_list)
ifprogress_callback:
ifnotprogress_callback(75):
raiseSourceException()
else:
xbmc.log("[%s] Number of programs requested: %d... Requesting batches of 3000"%
(ADDON.getAddonInfo('id'), prg_count), xbmc.LOGDEBUG)
# Deal with more data requestes
p_resp= []
batches=list(grouper(3000, prg_list))
step= (75-10) /len(batches)
forctr, batchinenumerate(batches):
batch=filter(None, batch)
xbmc.log("[%s] Requesting batch %d with %d items"%
(ADDON.getAddonInfo('id'), ctr+1, len(batch)), xbmc.LOGDEBUG)
p_resp+=self._post('programs', batch)
ifprogress_callback:
ifnotprogress_callback(10+ (ctr*step)):
raiseSourceException()
elements_parsed=0
forprg_datainp_resp:
if'programID'inprg_data:
prg_id=prg_data['programID']
else:
continue
# find the idx in the schedule
idx= []
fori, sinenumerate(schedule):
ifs['p_id'] ==prg_id:
idx.append(i)
title=''
if'titles'inprg_dataandlen(prg_data['titles']) >0:
if'title120'inprg_data['titles'][0]:
title=prg_data['titles'][0]['title120']
desc=''
if'episodeTitle150'inprg_data:
desc=prg_data['episodeTitle150'] +' - '
if'descriptions'inprg_data:
tmp_d=None
if'description1000'inprg_data['descriptions']:
tmp_d=prg_data['descriptions']['description1000']
elif'description100'inprg_data['descriptions']:
tmp_d=prg_data['descriptions']['description100']
iftmp_dandlen(tmp_d) >0and'description'intmp_d[0]:
desc+=tmp_d[0]['description']
foriinidx:
schedule[i]['title'] =title
schedule[i]['desc'] =desc
elements_parsed+=1
ifprogress_callbackandelements_parsed%100==0:
ifnotprogress_callback(100.0/prg_count*elements_parsed):
raiseSourceException()
returnschedule