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