zap to the recording channel... otherwise user sees a black screen
[enigma2.git] / RecordTimer.py
1 import time
2 import codecs
3 #from time import datetime
4 from Tools import Directories, Notifications
5
6 from Components.config import config
7 import timer
8 import xml.dom.minidom
9
10 from Screens.MessageBox import MessageBox
11 import NavigationInstance
12
13 from Tools.XMLTools import elementsWithTag
14 from ServiceReference import ServiceReference
15
16 # ok, for descriptions etc we have:
17 # service reference  (to get the service name)
18 # name               (title)
19 # description        (description)
20 # event data         (ONLY for time adjustments etc.)
21
22
23 # parses an event, and gives out a (begin, end, name, duration, eit)-tuple.
24 def parseEvent(ev):
25         name = ev.getEventName()
26         description = ev.getShortDescription()
27         begin = ev.getBeginTime()
28         end = begin + ev.getDuration()
29         eit = None
30         return (begin, end, name, description, eit)
31
32 class RecordTimerEntry(timer.TimerEntry):
33         def __init__(self, serviceref, begin, end, name, description, eit):
34                 timer.TimerEntry.__init__(self, int(begin), int(end))
35                 
36                 assert isinstance(serviceref, ServiceReference)
37                 
38                 self.service_ref = serviceref
39                 
40                 self.eit = eit
41                 
42                 self.dontSave = False
43                 self.name = name
44                 self.description = description
45                 self.timer = None
46                 self.record_service = None
47                 self.wantStart = False
48                 self.prepareOK = False
49                 
50         def calculateFilename(self):
51                 service_name = self.service_ref.getServiceName()
52 #               begin_date = datetime.fromtimestamp(begin).strf...
53                 begin_date = ""
54                 
55                 print "begin_date: ", begin_date
56                 print "service_name: ", service_name
57                 print "name:", self.name
58                 print "description: ", self.description
59
60                 self.Filename = Directories.getRecordingFilename(service_name)
61                 #begin_date + " - " + service_name + description)
62                 
63         
64         def tryPrepare(self):
65                 self.calculateFilename()
66                 self.record_service = NavigationInstance.instance.recordService(self.service_ref)
67                 if self.record_service == None:
68                         return False
69                 else:
70                         if self.record_service.prepare(self.Filename + ".ts"):
71                                 self.record_service = None
72                                 return False
73
74                         f = open(self.Filename + ".ts.meta", "w")
75                         f.write(str(self.service_ref) + "\n")
76                         f.write(self.name + "\n")
77                         f.write(self.description + "\n")
78                         f.write(str(self.begin) + "\n")
79                         del f
80                         return True
81
82         def activate(self, event):
83                 if event == self.EventPrepare:
84                         self.prepareOK = False
85                         if self.tryPrepare():
86                                 self.prepareOK = True
87                         else:
88                                 # error.
89                                 if config.recording.asktozap.value == 0:
90                                         Notifications.AddNotificationWithCallback(self.failureCB, MessageBox, _("A timer failed to record!\nDisable TV and try again?\n"))
91                                 else: # zap without asking
92                                         self.failureCB(True)
93                 elif event == self.EventStart:
94                         if self.prepareOK:
95                                 self.record_service.start()
96                                 print "timer started!"
97                         else:
98                                 print "prepare failed, thus start failed, too."
99                                 self.wantStart = True
100                 elif event == self.EventEnd or event == self.EventAbort:
101                         self.wantStart = False
102                         if self.prepareOK:
103                                 self.record_service.stop()
104                                 self.record_service = None
105                                 
106                                 print "Timer successfully ended"
107                         else:
108                                 print "prepare failed, thus nothing was recorded."
109
110         def abort():
111                 # fixme
112                 pass
113
114         def failureCB(self, answer):
115                 if answer == True:
116                         #NavigationInstance.instance.stopUserServices()
117                         print "[RecordTimer] zapping to", self.service_ref
118                         NavigationInstance.instance.playService(self.service_ref.ref)
119                         self.activate(self.EventPrepare)
120
121                         if self.wantStart:
122                                 print "post-activating record"
123                                 self.activate(self.EventStart)
124                 else:
125                         print "user killed record"
126
127 def createTimer(xml):
128         begin = int(xml.getAttribute("begin"))
129         end = int(xml.getAttribute("end"))
130         serviceref = ServiceReference(str(xml.getAttribute("serviceref")))
131         description = xml.getAttribute("description").encode("utf-8")
132         repeated = xml.getAttribute("repeated").encode("utf-8")
133         eit = xml.getAttribute("eit").encode("utf-8")
134         name = xml.getAttribute("name").encode("utf-8")
135         #filename = xml.getAttribute("filename").encode("utf-8")
136         entry = RecordTimerEntry(serviceref, begin, end, name, description, eit)
137         entry.repeated = int(repeated)
138         return entry
139
140 class RecordTimer(timer.Timer):
141         def __init__(self):
142                 timer.Timer.__init__(self)
143                 
144                 self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
145                 
146                 try:
147                         self.loadTimer()
148                 except IOError:
149                         print "unable to load timers from file!"
150                         
151         def isRecording(self):
152                 isRunning = False
153                 for timer in self.timer_list:
154                         if timer.isRunning():
155                                 isRunning = True
156                 return isRunning
157         
158         def loadTimer(self):
159                 # TODO: PATH!
160                 doc = xml.dom.minidom.parse(self.Filename)
161                 
162                 root = doc.childNodes[0]
163                 for timer in elementsWithTag(root.childNodes, "timer"):
164                         self.record(createTimer(timer))
165         
166         def saveTimer(self):
167                 doc = xml.dom.minidom.Document()
168                 root_element = doc.createElement('timers')
169                 doc.appendChild(root_element)
170                 root_element.appendChild(doc.createTextNode("\n"))
171                 
172                 for timer in self.timer_list + self.processed_timers:
173                         # some timers (instant records) don't want to be saved.
174                         # skip them
175                         if timer.dontSave:
176                                 continue
177                         t = doc.createTextNode("\t")
178                         root_element.appendChild(t)
179                         t = doc.createElement('timer')
180                         t.setAttribute("begin", str(timer.begin))
181                         t.setAttribute("end", str(timer.end))
182                         t.setAttribute("serviceref", str(timer.service_ref))
183                         t.setAttribute("repeated", str(timer.repeated))                 
184                         t.setAttribute("name", timer.name)
185                         t.setAttribute("description", timer.description)
186                         t.setAttribute("eit", str(timer.eit))
187                         
188                         root_element.appendChild(t)
189                         t = doc.createTextNode("\n")
190                         root_element.appendChild(t)
191
192                 file = open(self.Filename, "w")
193                 doc.writexml(file)
194                 file.write("\n")
195                 file.close()
196         
197         def record(self, entry):
198                 print "[Timer] Record " + str(entry)
199                 entry.Timer = self
200                 self.addTimerEntry(entry)
201
202         def removeEntry(self, entry):
203                 print "[Timer] Remove " + str(entry)
204                 
205                 entry.repeated = False
206
207                 if entry.state == timer.TimerEntry.StateRunning:
208                         print "remove running timer."
209                         entry.end = time.time()
210                         self.timeChanged(entry)
211                 elif entry.state != timer.TimerEntry.StateEnded:
212                         entry.activate(timer.TimerEntry.EventAbort)
213                         self.timer_list.remove(entry)
214
215                         self.calcNextActivation()
216                         print "timer did not yet start - removing"
217
218                         # the timer was aborted, and removed.
219                         return
220                 else:
221                         print "timer did already end - doing nothing."
222                 
223                 print "state: ", entry.state
224                 print "in processed: ", entry in self.processed_timers
225                 print "in running: ", entry in self.timer_list
226                 # now the timer should be in the processed_timers list. remove it from there.
227                 self.processed_timers.remove(entry)
228
229         def shutdown(self):
230                 self.saveTimer()