Plugins-Meta: rework plugin meta files and prepare for inclusion into enigma2 transla...
[enigma2-plugins.git] / partnerbox / src / PartnerboxFunctions.py
1 #
2 #  Partnerbox E2
3 #
4 #  $Id$
5 #
6 #  Coded by Dr.Best (c) 2009
7 #  Support: www.dreambox-tools.info
8 #
9 #  This program is free software; you can redistribute it and/or
10 #  modify it under the terms of the GNU General Public License
11 #  as published by the Free Software Foundation; either version 2
12 #  of the License, or (at your option) any later version.
13 #
14 #  This program is distributed in the hope that it will be useful,
15 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
16 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 #  GNU General Public License for more details.
18 #
19
20 import urllib
21 from time import localtime
22 from timer import TimerEntry
23 from twisted.internet import reactor
24 from twisted.web import client
25 from twisted.web.client import HTTPClientFactory
26 from base64 import encodestring
27 import xml.etree.cElementTree
28
29
30 remote_timer_list = None
31 oldIP = None
32
33 def getTimerType(refstr, beginTime, duration, eventId, timer_list):
34         pre = 1
35         post = 2
36         type = 0
37         endTime = beginTime + duration
38         for x in timer_list:
39                 if x.servicereference.upper() == refstr.upper():
40                         if x.eventId == eventId:
41                                 return True
42                         beg = x.timebegin
43                         end = x.timeend
44                         if beginTime > beg and beginTime < end and endTime > end:
45                                 type |= pre
46                         elif beginTime < beg and endTime > beg and endTime < end:
47                                 type |= post
48         if type == 0:
49                 return True
50         elif type == pre:
51                 return False
52         elif type == post:
53                 return False
54         else:
55                 return True
56
57 def isInTimerList(begin, duration, service, eventid, timer_list):
58         time_match = 0
59         chktime = None
60         chktimecmp = None
61         chktimecmp_end = None
62         end = begin + duration
63         timerentry = None
64         for x in timer_list:
65                 if x.servicereference.upper() == service.upper():
66                         if x.repeated != 0:
67                                 if chktime is None:
68                                         chktime = localtime(begin)
69                                         chktimecmp = chktime.tm_wday * 1440 + chktime.tm_hour * 60 + chktime.tm_min
70                                         chktimecmp_end = chktimecmp + (duration / 60)
71                                 time = localtime(x.timebegin)
72                                 for y in range(7):
73                                         if x.repeated & (2 ** y):
74                                                 timecmp = y * 1440 + time.tm_hour * 60 + time.tm_min
75                                                 if timecmp <= chktimecmp < (timecmp + ((x.timeend - x.timebegin) / 60)):
76                                                         time_match = ((timecmp + ((x.timeend - x.timebegin) / 60)) - chktimecmp) * 60
77                                                 elif chktimecmp <= timecmp < chktimecmp_end:
78                                                         time_match = (chktimecmp_end - timecmp) * 60
79                         else: 
80                                 if begin <= x.timebegin <= end:
81                                         diff = end - x.timebegin
82                                         if time_match < diff:
83                                                 time_match = diff
84                                 elif x.timebegin <= begin <= x.timeend:
85                                         diff = x.timeend - begin
86                                         if time_match < diff:
87                                                 time_match = diff
88                         if time_match:
89                                 if getTimerType(service, begin, duration, eventid, timer_list):
90                                         timerentry = x
91                                 break
92         return timerentry
93
94
95 class E2Timer:
96         def __init__(self, servicereference = "", servicename = "", name = "", disabled = 0, timebegin = 0, timeend = 0, duration = 0, startprepare = 0, state = 0, repeated = 0, justplay = 0, eventId = 0, afterevent = 0, dirname = "", description = "", type = 0):
97                 self.servicereference = servicereference
98                 self.servicename = servicename
99                 self.name = name
100                 self.disabled = disabled
101                 self.timebegin = timebegin
102                 self.timeend = timeend
103                 self.duration = duration
104                 self.startprepare = startprepare
105                 self.state = state
106                 self.repeated = repeated
107                 self.justplay = justplay
108                 self.eventId = eventId
109                 self.afterevent = afterevent
110                 self.dirname = dirname
111                 self.description = description
112                 self.type = type
113                 if type != 0: # E1 Timerlist
114                         self.timeend = timebegin + duration
115                         self.name = description
116                         if type & PlaylistEntry.isRepeating:
117                                 self.repeated = 1
118                         self.dirname = "/hdd/movie/"
119
120 def FillE2TimerList(xmlstring, sreference = None):
121         E2TimerList = []
122         try: root = xml.etree.cElementTree.fromstring(xmlstring)
123         except: return E2TimerList
124         for timer in root.findall("e2timer"):
125                 go = False
126                 state = 0
127                 try: state = int(timer.findtext("e2state", 0))
128                 except: state = 0
129                 disabled = 0
130                 try: disabled = int(timer.findtext("e2disabled", 0))
131                 except: disabled = 0
132                 servicereference = str(timer.findtext("e2servicereference", '').encode("utf-8", 'ignore'))
133                 if sreference is None:
134                         go = True
135                 else:
136                         if sreference.upper() == servicereference.upper() and state != TimerEntry.StateEnded and not disabled:
137                                 go = True
138                 if go:
139                         timebegin = 0
140                         timeend = 0
141                         duration = 0
142                         startprepare = 0
143                         repeated = 0
144                         justplay = 0
145                         afterevent = 0
146                         eventId = -1
147                         try: timebegin = int(timer.findtext("e2timebegin", 0))
148                         except: timebegin = 0
149                         try: timeend = int(timer.findtext("e2timeend", 0))
150                         except: timeend = 0
151                         try: duration = int(timer.findtext("e2duration", 0))
152                         except: duration = 0
153                         try: startprepare = int(timer.findtext("e2startprepare", 0))
154                         except: startprepare = 0
155                         try: repeated = int(timer.findtext("e2repeated", 0))
156                         except: repeated = 0
157                         try: justplay = int(timer.findtext("e2justplay", 0)) 
158                         except: justplay = 0
159                         try: afterevent = int(timer.findtext("e2afterevent", 0))
160                         except: afterevent = 0
161                         try: eventId = int(timer.findtext("e2eit", -1))
162                         except: eventId = -1
163                         E2TimerList.append(E2Timer(
164                                 servicereference = servicereference,
165                                 servicename = str(timer.findtext("e2servicename", 'n/a').encode("utf-8", 'ignore')),
166                                 name = str(timer.findtext("e2name", '').encode("utf-8", 'ignore')),
167                                 disabled = disabled,
168                                 timebegin = timebegin,
169                                 timeend = timeend,
170                                 duration = duration,
171                                 startprepare = startprepare,
172                                 state = state,
173                                 repeated = repeated,
174                                 justplay = justplay,
175                                 eventId = eventId,
176                                 afterevent = afterevent,
177                                 dirname = str(timer.findtext("e2location", '').encode("utf-8", 'ignore')),
178                                 description = str(timer.findtext("e2description", '').encode("utf-8", 'ignore')),
179                                 type = 0))
180         return E2TimerList
181
182
183 def FillE1TimerList(xmlstring, sreference = None):
184         E1TimerList = []
185         try: root = xml.etree.cElementTree.fromstring(xmlstring)
186         except: return E1TimerList
187         for timer in root.findall("timer"):
188                 try: typedata = int(timer.findtext("typedata", 0))
189                 except: typedata = 0
190                 for service in timer.findall("service"):
191                         servicereference = str(service.findtext("reference", '').encode("utf-8", 'ignore'))
192                         servicename = str(service.findtext("name", 'n/a').encode("utf-8", 'ignore'))
193                 for event in timer.findall("event"):
194                         try: timebegin = int(event.findtext("start", 0))
195                         except: timebegin = 0
196                         try: duration = int(event.findtext("duration", 0))
197                         except: duration = 0
198                         description = str(event.findtext("description", '').encode("utf-8", 'ignore'))
199                 go = False
200                 if sreference is None:
201                         go = True
202                 else:
203                         if sreference.upper() == servicereference.upper() and ( (typedata & PlaylistEntry.stateWaiting) or (typedata & PlaylistEntry.stateRunning)):
204                                 go = True
205                 if go:
206                         E1TimerList.append(E2Timer(servicereference = servicereference, servicename = servicename, name = "", disabled = 0, timebegin = timebegin, timeend = 0, duration = duration, startprepare = 0, state = 0 , repeated = 0, justplay= 0, eventId = -1, afterevent = 0, dirname = "", description = description, type = typedata))
207         return E1TimerList
208
209 class myHTTPClientFactory(HTTPClientFactory):
210         def __init__(self, url, method='GET', postdata=None, headers=None,
211         agent="Twisted Remotetimer", timeout=0, cookies=None,
212         followRedirect=1, lastModified=None, etag=None):
213                 HTTPClientFactory.__init__(self, url, method=method, postdata=postdata,
214                 headers=headers, agent=agent, timeout=timeout, cookies=cookies,followRedirect=followRedirect)
215
216
217 def sendPartnerBoxWebCommand(url, contextFactory=None, timeout=60, username = "root", password = "", *args, **kwargs):
218         scheme, host, port, path = client._parse(url)
219         basicAuth = encodestring(("%s:%s")%(username,password))
220         authHeader = "Basic " + basicAuth.strip()
221         AuthHeaders = {"Authorization": authHeader}
222         if kwargs.has_key("headers"):
223                 kwargs["headers"].update(AuthHeaders)
224         else:
225                 kwargs["headers"] = AuthHeaders
226         factory = myHTTPClientFactory(url, *args, **kwargs)
227         reactor.connectTCP(host, port, factory, timeout=timeout)
228         return factory.deferred
229
230 class PlaylistEntry:
231
232         PlaylistEntry=1                 # normal PlaylistEntry (no Timerlist entry)
233         SwitchTimerEntry=2              #simple service switch timer
234         RecTimerEntry=4                 #timer do recording
235         
236         recDVR=8                                #timer do DVR recording
237         recVCR=16                               #timer do VCR recording (LIRC) not used yet
238         recNgrab=131072                 #timer do record via Ngrab Server
239
240         stateWaiting=32                 #timer is waiting
241         stateRunning=64                 #timer is running
242         statePaused=128                 #timer is paused
243         stateFinished=256               #timer is finished
244         stateError=512                  #timer has error state(s)
245
246         errorNoSpaceLeft=1024   #HDD no space Left ( recDVR )
247         errorUserAborted=2048   #User Action aborts this event
248         errorZapFailed=4096             #Zap to service failed
249         errorOutdated=8192              #Outdated event
250
251         boundFile=16384                 #Playlistentry have an bounded file
252         isSmartTimer=32768              #this is a smart timer (EIT related) not uses Yet
253         isRepeating=262144              #this timer is repeating
254         doFinishOnly=65536              #Finish an running event/action
255
256         doShutdown=67108864             #timer shutdown the box
257         doGoSleep=134217728             #timer set box to standby
258
259         Su=524288
260         Mo=1048576
261         Tue=2097152
262         Wed=4194304
263         Thu=8388608
264         Fr=16777216
265         Sa=33554432
266
267
268 def SetPartnerboxTimerlist(partnerboxentry = None, sreference = None):
269         global remote_timer_list
270         global CurrentIP
271         if partnerboxentry is None:
272                 return  
273         try:
274                 password = partnerboxentry.password.value
275                 username = "root"
276                 CurrentIP = partnerboxentry.ip.value
277                 ip = "%d.%d.%d.%d" % tuple(partnerboxentry.ip.value)
278                 port = partnerboxentry.port.value
279                 if int(partnerboxentry.enigma.value) == 0:
280                         sCommand = "http://%s:%s@%s:%d/web/timerlist" % (username, password, ip,port)
281                 else:
282                         sCommand = "http://%s:%s@%s:%d/xml/timers" % (username, password, ip,port)
283                 print "[RemoteEPGList] Getting timerlist data from %s..."%ip
284                 f = urllib.urlopen(sCommand)
285                 sxml = f.read()
286                 if int(partnerboxentry.enigma.value) == 0:
287                         remote_timer_list = FillE2TimerList(sxml, sreference)
288                 else:
289                         remote_timer_list = FillE1TimerList(sxml, sreference)
290         except: pass