forked from b-jesch/service.kn.switchtimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.py
168 lines (138 loc) · 6.14 KB
/
handler.py
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time
from dateutil import parser
import xbmc, xbmcaddon, xbmcgui
import os
import operator
import json
__addon__ = xbmcaddon.Addon()
__addonid__ = __addon__.getAddonInfo('id')
__addonname__ = __addon__.getAddonInfo('name')
__path__ = __addon__.getAddonInfo('path')
__profiles__ = __addon__.getAddonInfo('profile')
__version__ = __addon__.getAddonInfo('version')
__LS__ = __addon__.getLocalizedString
IconDefault = xbmc.translatePath(os.path.join(__path__, 'resources', 'media', 'default.png'))
IconAlert = xbmc.translatePath(os.path.join(__path__, 'resources', 'media', 'alert.png'))
IconOk = xbmc.translatePath(os.path.join(__path__, 'resources', 'media', 'ok.png'))
confirmTmrAdded = True if __addon__.getSetting('confirmTmrAdded').upper() == 'TRUE' else False
OSD = xbmcgui.Dialog()
OSDProgress = xbmcgui.DialogProgress()
HOME = xbmcgui.Window(10000)
__settingspath__ = xbmc.translatePath(__profiles__)
if not os.path.exists(__settingspath__): os.makedirs(__settingspath__, 0755)
__timer__ = os.path.join(__settingspath__, 'timer.json')
__timerdict__ = {'channel': None, 'icon': None, 'date': None, 'title': None, 'plot': None}
def putTimer(timers):
for timer in timers:
if not timer['utime'] or timer['utime'] < time.time(): timers.pop(0)
with open(__timer__, 'w') as handle:
json.dump(timers, handle)
HOME.setProperty('SwitchTimerActiveItems', str(len(timers)))
notifyLog('%s timer(s) written' % (len(timers)), xbmc.LOGNOTICE)
def getTimer():
try:
with open(__timer__, 'r') as handle:
timers = json.load(handle)
except IOError:
return []
return timers
def getSetting(setting):
return __addon__.getSetting(setting)
def notifyLog(message, level=xbmc.LOGDEBUG):
xbmc.log('[%s]: %s' % (__addonid__, message.encode('utf-8')), level)
def notifyOSD(header, message, icon=IconDefault, time=5000):
OSD.notification(header.encode('utf-8'), message.encode('utf-8'), icon, time)
def date2timeStamp(pdate, dayfirst=True):
df=xbmc.getRegion('dateshort')
dtt = parser.parse(pdate, fuzzy=True, dayfirst=dayfirst).timetuple()
return int(time.mktime(dtt))
def setTimer(params):
utime = date2timeStamp(params['date'])
if not utime: return False
_now = int(time.time())
if _now > utime:
notifyLog('Timer date possibly in the past, trying another date format', xbmc.LOGNOTICE)
utime =date2timeStamp(params['date'], dayfirst=False)
if _now > utime:
notifyLog('Timer date in the past or couldn\'t determine date format', xbmc.LOGNOTICE)
notifyOSD(__LS__(30000), __LS__(30022), icon=IconAlert)
return False
timers = getTimer()
for timer in timers:
if date2timeStamp(timer['date']) == utime:
notifyLog('Timer already set, ask for replace', xbmc.LOGNOTICE)
_res = OSD.yesno(__addonname__, __LS__(30031) % (timer['channel'], timer['title']))
if not _res: return False
timers.remove(timer)
if len(timers) > 9:
notifyLog('Timer limit exceeded, no free slot', xbmc.LOGFATAL)
notifyOSD(__LS__(30000), __LS__(30024), icon=IconAlert)
return False
# append timer and sort timerlist
params['utime'] = utime
timers.append(params)
timers.sort(key=operator.itemgetter('utime'))
setTimerProperties(timers)
putTimer(timers)
notifyLog('Timer added @%s, %s, %s' % (params['date'], params['channel'].decode('utf-8'), params['title'].decode('utf-8')), xbmc.LOGNOTICE)
notifyLog('Plot: %s...' % (params['plot'].decode('utf-8')[0:63]))
if confirmTmrAdded: notifyOSD(__LS__(30000), __LS__(30021), icon=IconOk)
return True
def setTimerProperties(timerlist):
_idx = 0
for prefix in ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9']:
if _idx < len(timerlist):
# Set timer properties
for element in __timerdict__:
try:
HOME.setProperty('%s:%s' % (prefix, element), timerlist[_idx][element])
except KeyError:
pass
_idx += 1
else:
# Clear remaining properties
clearTimerProperties(prefix)
def clearTimerProperties(prefix=None):
if not prefix:
for prefix in ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9']:
for element in __timerdict__: HOME.clearProperty('%s:%s' % (prefix, element))
timers = []
notifyLog('Properties of all timers deleted, timerlist cleared')
else:
_date = HOME.getProperty('%s:date' % (prefix))
if _date == '': return False
timers = getTimer()
for timer in timers:
if timer['date'] == _date: timer['utime'] = None
for element in __timerdict__: HOME.clearProperty('%s:%s' % (prefix, element))
notifyLog('Properties for timer %s @%s deleted' % (prefix, _date))
putTimer(timers)
return True
if __name__ == '__main__':
notifyLog('Parameter handler called')
try:
if sys.argv[1]:
args = {'action':None, 'channel':'', 'icon': '', 'date':'', 'title':'', 'plot': ''}
pars = sys.argv[1:]
for par in pars:
try:
item, value = par.split('=')
args[item] = value.replace(',', ',').decode('utf-8')
notifyLog('Provided parameter %s: %s' % (item, args[item]))
except ValueError:
args[item] += ', ' + par
if args['action'] == 'add':
if not setTimer(args):
notifyLog('Timer couldn\'t or wouldn\'t set', xbmc.LOGERROR)
elif args['action'] == 'del':
clearTimerProperties(args['timer'])
elif args['action'] == 'delall':
for prefix in ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9']: clearTimerProperties()
except IndexError:
notifyLog('Calling this script without parameters is not allowed', xbmc.LOGERROR)
OSD.ok(__LS__(30000),__LS__(30030))
except Exception, e:
notifyLog('Script error: %s' % (e.message), xbmc.LOGERROR)