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