Many changes, commented in
[enigma2-plugins.git] / webinterface / src / WebComponents / Sources / Timer.py
1 from enigma import *
2 from enigma import eServiceReference 
3 from enigma import eServiceCenter
4
5 from Components.Sources.Source import Source
6 from ServiceReference import ServiceReference
7 from RecordTimer import RecordTimerEntry, RecordTimer, AFTEREVENT,parseEvent
8 from Components.config import config
9
10 import time, string
11 # import sys, traceback
12
13 class Timer( Source):
14     LIST = 0
15     ADDBYID = 1
16     ADD = 2
17     DEL = 3
18     TVBROWSER = 4
19     CHANGE = 5
20     WRITE = 6
21     
22     def __init__(self, session,func = LIST):
23         self.func = func
24         Source.__init__(self)        
25         self.session = session
26         self.recordtimer = session.nav.RecordTimer
27         self.epgcache = eEPGCache.getInstance()
28
29     def handleCommand(self,cmd):
30         if self.func is self.ADDBYID:
31             self.result = self.addTimerByEventID(cmd)
32         elif self.func is self.ADD:
33             self.result = self.addTimer(cmd)
34         elif self.func is self.TVBROWSER:
35             self.result = self.tvBrowser(cmd)
36         elif self.func is self.DEL:
37             self.result = self.delTimer(cmd)
38         elif self.func is self.CHANGE:
39             self.result = self.changeTimer(cmd)
40         elif self.func is self.WRITE:
41             self.result = self.writeTimerList(cmd)
42         else:
43             self.result = False,"unknown command"
44
45     def delTimer(self,param):
46         # is there an easier and better way? :\ 
47         print "delTimer",param
48         
49         if param['serviceref'] is None:
50             return False,"ServiceReference missing"
51         else: 
52             serviceref = ServiceReference(param['serviceref'])
53         
54         if param['begin'] is None:
55            return False,"begin missing"
56         else:
57             begin = float(param['begin'])
58         
59         if param['end'] is None:
60             return False,"end missing"
61         else:
62                 end = float(param['end'])
63              
64         toDelete = None
65         try:
66             print "timer_list ", self.recordtimer.timer_list
67             print "processed_timers", self.recordtimer.processed_timers
68             for x in self.recordtimer.timer_list + self.recordtimer.processed_timers:
69                 print "x.begin(%s), x.end(%s), x.service_ref(%s)" % (x.begin, x.end, x.service_ref)
70                 if str(x.service_ref) == str(serviceref) and float(x.begin) == begin and float(x.end) == end:
71                                   toDelete = x
72         except:
73             print "Fehler\n"
74             
75         if toDelete is not None:
76                 self.recordtimer.removeEntry(toDelete)
77                 return True,"Timer removed"
78         else:
79                 return False,"Timer not found"
80                 print "Timer not found"
81         
82         #self.session.nav.RecordTimer.saveTimer()
83     
84     def tvBrowser(self,param):
85         print "tvbrowser",param
86         
87         """ Therefor the URL's for the tvBrowser-Capture-Driver are:
88         
89             http://dreambox/web/tvbrowser? +
90             
91         To add something:
92             &command=add&&syear={start_year}&smonth={start_month}&sday={start_day}&shour={start_hour}&smin={start_minute}&eyear={end_year}&emonth={end_month}&eday={end_day}&ehour={end_hour}&emin={end_minute}&serviceref={urlencode(channel_name_external, "utf8")}&name={urlencode(title, "utf8")}&description={urlencode(title, "utf8")}&afterevent=0&eit=&disabled=0&justplay=0&repeated=0
93         
94         to zap for some time:
95             &command=add&&syear={start_year}&smonth={start_month}&sday={start_day}&shour={start_hour}&smin={start_minute}&eyear={end_year}&emonth={end_month}&eday={end_day}&ehour={end_hour}&emin={end_minute}&serviceref={urlencode(channel_name_external, "utf8")}&name={urlencode(title, "utf8")}&description={urlencode(title, "utf8")}&afterevent=0&eit=&disabled=0&justplay=1&repeated=0
96         
97         to delete something:
98             &command=del&&syear={start_year}&smonth={start_month}&sday={start_day}&shour={start_hour}&smin={start_minute}&eyear={end_year}&emonth={end_month}&eday={end_day}&ehour={end_hour}&emin={end_minute}&serviceref={urlencode(channel_name_external, "utf8")}&name={urlencode(title, "utf8")}&description={urlencode(title, "utf8")}&afterevent=0&eit=&disabled=0&justplay=0&repeated=0
99         """
100         
101         syear = 0
102         if param['syear'] is None:
103            return False,"syear missing"
104         else:
105             syear = int(param['syear'])
106         
107         smonth = 0
108         if param['smonth'] is None:
109            return False,"smonth missing"
110         else:
111             smonth = int(param['smonth'])
112         
113         sday = 0
114         if param['sday'] is None:
115            return False,"sday missing"
116         else:
117             sday = int(param['sday'])
118         
119         shour = 0
120         if param['shour'] is None:
121            return False,"shour missing"
122         else:
123             shour = int(param['shour'])
124         
125         smin = 0
126         if param['smin'] is None:
127            return False,"smin missing"
128         else:
129             smin = int(param['smin'])
130             
131         eyear = 0
132         if param['eyear'] is None:
133            return False,"eyear missing"
134         else:
135             eyear = int(param['eyear'])
136         
137         emonth = 0
138         if param['emonth'] is None:
139            return False,"emonth missing"
140         else:
141             emonth = int(param['emonth'])
142         
143         eday = 0
144         if param['eday'] is None:
145            return False,"eday missing"
146         else:
147             eday = int(param['eday'])
148         
149         ehour = 0
150         if param['ehour'] is None:
151            return False,"ehour missing"
152         else:
153             ehour = int(param['ehour'])
154         
155         emin = 0
156         if param['emin'] is None:
157            return False,"emin missing"
158         else:
159             emin = int(param['emin'])
160         
161         # for compatibility reasons
162         if param['serviceref'] is None:
163             return False,"ServiceReference missing"
164         else:
165             takeApart = string.split(param['serviceref'], '|')
166             if len(takeApart) > 1:
167                 param['serviceref'] = takeApart[1]
168
169         param['begin'] = int( time.strftime("%s",  time.localtime(time.mktime( (syear, smonth, sday, shour, smin, 0, 0, 0, 0) ) ) ) )
170         param['end']   = int( time.strftime("%s",  time.localtime(time.mktime( (eyear, emonth, eday, ehour, emin, 0, 0, 0, 0) ) ) ) )
171         
172         if param['command'] == "add":
173             return self.addTimer(param)
174         elif param['command'] == "del":
175             return self.delTimer(param)
176         else:
177             return False,"command missing"
178         
179     def addTimer(self,param):
180         # is there an easier and better way? :\ 
181         print "addTimer",param
182         if param['serviceref'] is None:
183             return False,"ServiceReference missing"
184         else: 
185             serviceref = ServiceReference(param['serviceref'])
186         
187         if param['begin'] is None:
188            return False,"begin missing"
189         elif time.time() <= float(param['begin']):
190             begin = float(param['begin'])
191         else:
192             return False,"incorrect time begin"
193         
194         if param['end'] is None:
195             return False,"end missing"
196         elif begin < float(param['end']):
197             end = float(param['end'])
198         else:
199              return False,"incorrect time end"
200                 
201         if param['name'] is None:
202             return False,"name is missing"
203         else:
204             name = param['name']
205             
206         if param['description'] is not None:
207             description = param['description']
208         else: 
209             description = ""
210             
211         if param['disabled'] =="0":
212             disabled = False
213         elif param['disabled'] =="1":
214             disabled = True
215         else:
216             return False,"disabled incorrect"
217         
218         if param['justplay'] == "0":
219             justplay = False
220         elif param['justplay'] == "1":
221             justplay = True
222         else:
223             return False,"justplay incorrect"
224             
225         if param['afterevent'] == "0":
226             afterevent = 0
227         elif param['afterevent'] == "1":
228             afterevent = 1
229         elif param['afterevent'] == "2":
230             afterevent = 2
231         else:
232             return False,"afterevent incorrect"
233         
234         if param['repeated'] is not None:
235             repeated = int(param['repeated'])
236         else: 
237             repeated = 0
238             
239         newtimer = RecordTimerEntry(serviceref, begin, end, name, description, 0, disabled, justplay, afterevent)
240         newtimer.repeated = repeated
241         self.recordtimer.record(newtimer)
242         #self.session.nav.RecordTimer.saveTimer()
243         return True,"Timer added"        
244
245     def addTimerByEventID(self,param):
246         print "addTimerByEventID",param['serviceref'],param['eventid']
247         if param['serviceref'] is None:
248             return False,"ServiceReference not set"
249         if param['eventid'] is None:
250             return False,"Eventid not set"
251         epgcache = eEPGCache.getInstance()
252         event = epgcache.lookupEventId(eServiceReference(param['serviceref']),int(param['eventid']))
253         if event is None:
254             return False,"Eventid not found"
255         (begin, end, name, description, eit) =parseEvent(event)
256         justplay = False
257         if param['justplay'] is None and param['justplay'] == "1":
258             justplay = True
259         
260         newtimer = RecordTimerEntry(ServiceReference(param['serviceref']), (begin - (int(config.recording.margin_before.value)*60)), (end + (int(config.recording.margin_after.value)*60)), name, description, eit, False, justplay, AFTEREVENT.NONE)
261         self.recordtimer.record(newtimer)
262         return True,"Timer added"    
263             
264     def changeTimer(self,param):
265         
266         print "changeTimer ",param
267         
268         if int(param['deleteOldOnSave']) == 1:
269             
270             if param['serviceref'] is None:
271                 return False,"ServiceReference missing"
272             else: 
273                 serviceref = ServiceReference(param['serviceref'])
274             
275             if param['begin'] is None:
276                 return False,"begin missing"
277             elif time.time() <= float(param['begin']):
278                 begin = float(param['begin'])
279             else:
280                 return False,"incorrect time begin"
281         
282             if param['end'] is None:
283                 return False,"end missing"
284             elif begin < float(param['end']):
285                 end = float(param['end'])
286             else:
287                 return False,"incorrect time end"
288                 
289             if param['name'] is None:
290                 return False,"name is missing"
291             else:
292                 name = param['name']
293             
294             if param['description'] is not None:
295                 description = param['description']
296             else: 
297                 description = ""
298
299             if param['repeated'] is not None:
300                 repeated = int(param['repeated'])
301             else: 
302                 repeated = 0
303
304             if param['disabled'] =="0":
305                 disabled = False
306             elif param['disabled'] =="1":
307                 disabled = True
308             else:
309                 return False,"disabled incorrect"
310         
311             if param['justplay'] == "0":
312                 justplay = False
313             elif param['justplay'] == "1":
314                 justplay = True
315             else:
316                 return False,"justplay incorrect"
317             
318             if param['afterevent'] == "0":
319                 afterevent = 0
320             elif param['afterevent'] == "1":
321                 afterevent = 1
322             elif param['afterevent'] == "2":
323                 afterevent = 2
324             else:
325                 return False,"afterevent incorrect"
326         
327             if param['channelOld'] is None:
328                 return False,"channelOld missing"
329             else: 
330                 channelOld = ServiceReference(param['channelOld'])
331             
332             if param['beginOld'] is None:
333                 return False,"beginOld missing"
334             else:
335                 beginOld = float(param['beginOld'])
336             
337             if param['endOld'] is None:
338                 return False,"endOld missing"
339             else:
340                 endOld = float(param['endOld'])
341                 
342             toChange = None
343             try:
344                 for x in self.recordtimer.timer_list + self.recordtimer.processed_timers:
345                     #print "x.begin(%s), x.end(%s), x.service_ref(%s)" % (x.begin, x.end, x.service_ref)
346                     #print "beginOld(%s), endOld(%s), channelOld(%s)" % (beginOld, endOld, channelOld)
347                     if str(x.service_ref) == str(channelOld) and float(x.begin) == beginOld and float(x.end) == endOld:
348                         toChange = x
349                         toChange.service_ref = ServiceReference(param['serviceref'])
350                         toChange.begin = begin
351                         toChange.end = end
352                         toChange.name = name
353                         toChange.description = description
354                         toChange.disabled = disabled
355                         toChange.justplay = justplay
356                         toChange.afterEvent = afterevent
357                         toChange.repeated = repeated
358                         if disabled is True:
359                             toChange.state = 3
360                         else:
361                             toChange.state = 0
362                         print "Timer changed"
363                         return True,"Timer changed"
364                         break
365             except:
366                 return False,"error searching for old Timer"
367             
368             if toChange is None:
369                 return False,"Timer not found"
370                 print "Timer not found"
371         else:
372             return self.addTimer(param)
373     
374     def writeTimerList(self,param):
375         # is there an easier and better way? :\ 
376         print "saveTimerList",param
377         self.session.nav.RecordTimer.saveTimer()
378         
379         return True,"TimerList was saved "
380             
381     def getText(self):
382         (result,text) = self.result
383         xml = "<?xml version=\"1.0\"?>\n"
384         xml  += "<e2simplexmlresult>\n"
385         if result:
386             xml += "<e2state>True</e2state>\n"
387         else:
388             xml += "<e2state>False</e2state>\n"            
389         xml += "<e2statetext>%s</e2statetext>\n" % text
390         xml += "</e2simplexmlresult>\n"
391         return xml
392     
393     text = property(getText)
394     
395     ## part for listfiller requests
396     def command(self):
397         timerlist = []
398 #        print "len(self.recordtimer.timer_list) ", len(self.recordtimer.timer_list)
399  #       print "timer_list ", self.recordtimer.timer_list
400   #      print "processed_timers", self.recordtimer.processed_timers
401 #        try:
402         for item in self.recordtimer.timer_list + self.recordtimer.processed_timers:
403             timer = []
404             timer.append(item.service_ref)
405             timer.append(item.service_ref.getServiceName())
406             timer.append(item.eit)
407             timer.append(item.name)
408             timer.append(item.description)
409             if item.disabled is True:
410                 timer.append("1")
411             else:
412                 timer.append("0")
413             #timer.append(item.disabled)
414
415             timer.append(item.begin)
416             timer.append(item.end)
417             timer.append(item.end - item.begin)
418             timer.append(item.start_prepare)
419             
420             if item.justplay is True:
421                 timer.append(1)
422             else:
423                 timer.append(0)
424
425             timer.append(item.afterEvent)
426             
427             """
428 No passing Logevents, because of error:
429 XML-Verarbeitungsfehler: nicht wohlgeformt
430 Adresse: http://dreambox/web/timerlist
431 Zeile Nr. 374, Spalte 259:        <e2logentries>[(1171275272, 15, 'record time changed, start prepare is now: Mon Feb 12 12:29:40 2007'), (1171279780, 5, 'activating state 1'), (1171279780, 0, "Filename calculated as: '/hdd/movie/20070212 1230 - DISNEY CHANNEL - Quack Pack - Onkel Donald & Die Boys'"), (1171279780, 3, 'prepare ok, writing meta information to /hdd/movie/20070212 1230 - DISNEY CHANNEL - Quack Pack - Onkel Donald & Die Boys'), (1171279780, 6, 'prepare ok, waiting for begin'), (1171279800, 5, 'activating state 2'), (1171279800, 11, 'start recording'), (1171281900, 5, 'activating state 3'), (1171281900, 12, 'stop recording')]</e2logentries>
432 ------------------------------------------------------------------------------------------------------------
433 No clue, what it could be.
434             """
435             #timer.append(item.log_entries)
436             timer.append("")
437             
438             try:
439                 timer.append(item.Filename)
440             except:
441                 timer.append("")
442             
443             timer.append(item.backoff)       
444             
445             try:
446                 timer.append(item.next_activation)
447             except:
448                 timer.append("")
449                 
450             timer.append(item.first_try_prepare)  
451             timer.append(item.state)
452             timer.append(item.repeated)
453             timer.append(item.dontSave)
454             timer.append(item.cancelled)
455             
456             if item.eit is not None:
457                 event = self.epgcache.lookupEvent(['E',("%s" % item.service_ref ,2,item.eit)])
458                 if event[0][0] is not None:
459                     timer.append(event[0][0])
460                 else:
461                     timer.append("N/A")
462             else:
463                 timer.append("N/A")
464                 
465             timerlist.append(timer)
466 #        except:
467 #            print sys.exc_info()[0]
468 #            print sys.exc_info()[1]
469 #            print traceback.extract_tb(sys.exc_info()[2])
470             
471         return timerlist
472     
473     list = property(command)
474     lut = {"ServiceReference":0
475            ,"ServiceName": 1
476            ,"EIT":2
477            ,"Name":3
478            ,"Description":4
479            ,"Disabled":5
480            ,"TimeBegin":6
481            ,"TimeEnd":7
482            ,"Duration":8
483            ,"startPrepare":9
484            ,"justPlay":10
485            ,"afterEvent":11
486            ,"LogEntries":12
487            ,"Filename":13
488            ,"Backoff":14
489            ,"nextActivation":15
490            ,"firstTryPrepare":16
491            ,"State":17
492            ,"Repeated":18
493            ,"dontSave":19
494            ,"Cancled":20
495            ,"DescriptionExtended":21
496            }
497