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