for the better
[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, 0) ) ) ) )
118         param['end']   = int( time.strftime("%s",  time.localtime(time.mktime( (param['eyear'], param['emonth'], param['eday'], param['ehour'], param['emin'], 0, 0, 0, 0) ) ) ) )
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         else:
151             return False,"command missing"
152     
153     def recordNow(self,param):
154         print "recordNow ",param
155         
156         limitEvent = True
157         if param == "undefinitely":
158             limitEvent = False
159         
160         serviceref = self.session.nav.getCurrentlyPlayingServiceReference()
161         print serviceref
162         #assert isinstance(serviceref, ServiceReference)
163         serviceref = ServiceReference(serviceref.toString())
164         event = None
165         try:
166             service = self.session.nav.getCurrentService()
167             event = self.epgcache.lookupEventTime(serviceref, -1, 0)
168             if event is None:
169                 info = service.info()
170                 ev = info.getEvent(0)
171                 event = ev
172         except:
173             pass
174
175         begin = time.time()
176         end = begin + 3600 * 10
177         name = "instant record"
178         description = ""
179         eventid = 0
180
181         if event is not None:
182             curEvent = parseEvent(event)
183             name = curEvent[2]
184             description = curEvent[3]
185             eventid = curEvent[4]
186             if limitEvent:
187                 end = curEvent[1]
188         else:
189             if limitEvent:
190                 return False, "No event found, started recording undefinitely"
191
192         newtimer = RecordTimerEntry(serviceref, begin, end, name, description, eventid, False, False, 0)
193         newtimer.dontSave = True
194         self.recordtimer.record(newtimer)
195
196         return True,"recording was startet"
197         
198     def addTimer(self,param):
199         # is there an easier and better way? :\ 
200         print "addTimer",param
201         if param['sRef'] is None:
202             return False,"ServiceReference missing"
203         else: 
204             serviceref = ServiceReference(param['sRef'])
205         
206         if param['begin'] is None:
207            return False,"begin missing"
208         else:
209             begin = float(param['begin'])
210         
211         if param['end'] is None:
212             return False,"end missing"
213         elif float(param['end']) > time.time():
214             end = float(param['end'])
215         else:
216              return False,"end is in the past"
217                 
218         if param['name'] is None:
219             return False,"name is missing"
220         else:
221             print "name1 ",param['name']
222             name = unescape(param['name'])#.encode("UTF-16LE")#.decode('utf-8')
223             print "name2 ",name
224             #).decode('utf_8')
225             
226         if param['description'] is not None:
227             print "description1 ",param['description']
228             description = unescape(param['description'])#.encode("UTF-16LE")#.decode('utf-8')
229             print "description2 ",description
230         else: 
231             description = ""
232             
233         if param['disabled'] =="0":
234             disabled = False
235         elif param['disabled'] =="1":
236             disabled = True
237         else:
238             return False,"disabled incorrect"
239         
240         if param['justplay'] == "0":
241             justplay = False
242         elif param['justplay'] == "1":
243             justplay = True
244         else:
245             return False,"justplay incorrect"
246             
247         if param['afterevent'] == "0":
248             afterevent = 0
249         elif param['afterevent'] == "1":
250             afterevent = 1
251         elif param['afterevent'] == "2":
252             afterevent = 2
253         else:
254             return False,"afterevent incorrect"
255         
256         repeated = 0
257         if param.has_key('repeated'):
258             repeated = int(param['repeated'])
259         
260         newtimer = RecordTimerEntry(serviceref, begin, end, name, description, 0, disabled, justplay, afterevent)
261         newtimer.repeated = repeated
262         self.recordtimer.record(newtimer)
263         #self.session.nav.RecordTimer.saveTimer()
264         return True,"Timer added"        
265
266     def addTimerByEventID(self,param):
267         print "addTimerByEventID",param
268         if param['sRef'] is None:
269             return False,"ServiceReference not set"
270         if param['eventid'] is None:
271             return False,"Eventid not set"
272         
273         justplay = False
274         if param['justplay'] is not None:
275             if param['justplay'] == "1":
276                 justplay = True
277
278         epgcache = eEPGCache.getInstance()
279         event = epgcache.lookupEventId(eServiceReference(param['sRef']),int(param['eventid']))
280         if event is None:
281             return False,"Eventid not found"
282         (begin, end, name, description, eit) =parseEvent(event)
283         
284         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
285         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)
286                         #RecordTimerEntry(serviceref, begin, end, name, description, eit, disabled, justplay, afterevent)
287                 
288         self.recordtimer.record(newtimer)
289         return True,"Timer added"    
290             
291     def changeTimer(self,param):
292         
293         print "changeTimer ",param
294         
295         if int(param['deleteOldOnSave']) == 1:
296             
297             if param['sRef'] is None:
298                 return False,"ServiceReference missing"
299             else: 
300                 serviceref = ServiceReference(param['sRef'])
301             
302             if param['begin'] is None:
303                 return False,"begin missing"
304             elif time.time() <= float(param['begin']):
305                 begin = float(param['begin'])
306             else:
307                 return False,"incorrect time begin"
308         
309             if param['end'] is None:
310                 return False,"end missing"
311             elif begin < float(param['end']):
312                 end = float(param['end'])
313             else:
314                 return False,"incorrect time end"
315                 
316             if param['name'] is None:
317                 return False,"name is missing"
318             else:
319                 name = param['name']
320             
321             if param['description'] is not None:
322                 description = param['description']
323             else: 
324                 description = ""
325
326             if param['repeated'] is not None:
327                 repeated = int(param['repeated'])
328             else: 
329                 repeated = 0
330
331             if param['disabled'] =="0":
332                 disabled = False
333             elif param['disabled'] =="1":
334                 disabled = True
335             else:
336                 return False,"disabled incorrect"
337         
338             if param['justplay'] == "0":
339                 justplay = False
340             elif param['justplay'] == "1":
341                 justplay = True
342             else:
343                 return False,"justplay incorrect"
344             
345             if param['afterevent'] == "0":
346                 afterevent = 0
347             elif param['afterevent'] == "1":
348                 afterevent = 1
349             elif param['afterevent'] == "2":
350                 afterevent = 2
351             else:
352                 return False,"afterevent incorrect"
353         
354             if param['channelOld'] is None:
355                 return False,"channelOld missing"
356             else: 
357                 channelOld = ServiceReference(param['channelOld'])
358             
359             if param['beginOld'] is None:
360                 return False,"beginOld missing"
361             else:
362                 beginOld = float(param['beginOld'])
363             
364             if param['endOld'] is None:
365                 return False,"endOld missing"
366             else:
367                 endOld = float(param['endOld'])
368                 
369             toChange = None
370             try:
371                 for x in self.recordtimer.timer_list + self.recordtimer.processed_timers:
372                     #print "x.begin(%s), x.end(%s), x.service_ref(%s)" % (x.begin, x.end, x.service_ref)
373                     #print "beginOld(%s), endOld(%s), channelOld(%s)" % (beginOld, endOld, channelOld)
374                     if str(x.service_ref) == str(channelOld) and float(x.begin) == beginOld and float(x.end) == endOld:
375                         toChange = x
376                         toChange.service_ref = ServiceReference(param['sRef'])
377                         toChange.begin = int(begin)
378                         toChange.end = int(end)
379                         toChange.name = name
380                         toChange.description = description
381                         toChange.disabled = disabled
382                         toChange.justplay = justplay
383                         toChange.afterEvent = afterevent
384                         toChange.repeated = repeated
385                         self.session.nav.RecordTimer.timeChanged(toChange)
386                         print "Timer changed"
387                         return True,"Timer changed"
388                         break
389             except:
390                 return False,"error searching for old Timer"            
391             if toChange is None:
392                 return False,"Timer not found"
393                 print "Timer not found"
394         else:
395             return self.addTimer(param)
396     
397     def writeTimerList(self,param):
398         # is there an easier and better way? :\ 
399         print "saveTimerList",param
400         self.session.nav.RecordTimer.saveTimer()
401         
402         return True,"TimerList was saved "
403             
404     def getText(self):
405         print self.result
406         (result,text) = self.result
407         xml  = "<e2simplexmlresult>\n"
408         if result:
409             xml += "<e2state>True</e2state>\n"
410         else:
411             xml += "<e2state>False</e2state>\n"            
412         xml += "<e2statetext>%s</e2statetext>\n" % text
413         xml += "</e2simplexmlresult>\n"
414         return xml
415     
416     text = property(getText)
417     
418     ## part for listfiller requests
419     def command(self):
420         timerlist = []
421
422         for item in self.recordtimer.timer_list + self.recordtimer.processed_timers:
423             timer = []
424             timer.append(item.service_ref)
425             timer.append(item.service_ref.getServiceName())
426             timer.append(item.eit)
427             timer.append(item.name)
428             timer.append(item.description)
429             if item.disabled is True:
430                 timer.append("1")
431             else:
432                 timer.append("0")
433             #timer.append(item.disabled)
434
435             timer.append(item.begin)
436             timer.append(item.end)
437             timer.append(item.end - item.begin)
438             timer.append(item.start_prepare)
439             
440             if item.justplay is True:
441                 timer.append(1)
442             else:
443                 timer.append(0)
444
445             timer.append(item.afterEvent)
446             
447             """
448 No passing Logevents, because of error:
449 XML-Verarbeitungsfehler: nicht wohlgeformt
450 Adresse: http://dreambox/web/timerlist
451 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>
452 ------------------------------------------------------------------------------------------------------------
453 No clue, what it could be.
454             """
455             #timer.append(item.log_entries)
456             timer.append("")
457             
458             try:
459                 timer.append(item.Filename)
460             except:
461                 timer.append("")
462             
463             timer.append(item.backoff)       
464             
465             try:
466                 timer.append(item.next_activation)
467             except:
468                 timer.append("")
469                 
470             timer.append(item.first_try_prepare)  
471             timer.append(item.state)
472             timer.append(item.repeated)
473             
474             if item.dontSave is True:
475                 timer.append(1)
476             else:
477                 timer.append(0)
478 #            timer.append(item.dontSave)
479
480             timer.append(item.cancelled)
481             
482             if item.eit is not None:
483                 event = self.epgcache.lookupEvent(['E',("%s" % item.service_ref ,2,item.eit)])
484                 if event[0][0] is not None:
485                     timer.append(event[0][0])
486                 else:
487                     timer.append("N/A")
488             else:
489                 timer.append("N/A")
490             
491             if item.state == 0:
492                 timer.append("000000")
493             elif item.state == 1:
494                 timer.append("00BCBC")
495             elif item.state == 2:
496                 timer.append("9F1919")
497             else:
498                 timer.append("00BCBC")
499             #toggleDisabled
500             if item.disabled is True:
501                 timer.append("0")
502                 timer.append("on")
503             else:
504                 timer.append("1")
505                 timer.append("off")
506
507             timerlist.append(timer)
508             
509         return timerlist
510     
511     list = property(command)
512     lut = {"ServiceReference":0
513            ,"ServiceName": 1
514            ,"EIT":2
515            ,"Name":3
516            ,"Description":4
517            ,"Disabled":5
518            ,"TimeBegin":6
519            ,"TimeEnd":7
520            ,"Duration":8
521            ,"startPrepare":9
522            ,"justPlay":10
523            ,"afterEvent":11
524            ,"LogEntries":12
525            ,"Filename":13
526            ,"Backoff":14
527            ,"nextActivation":15
528            ,"firstTryPrepare":16
529            ,"State":17
530            ,"Repeated":18
531            ,"dontSave":19
532            ,"Cancled":20
533            ,"DescriptionExtended":21
534            ,"Color":22
535            ,"toggleDisabled":23
536            ,"toggleDisabledIMG":24
537            }