reset state to PLAY when a new service starts
[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 from Screens.SubserviceSelection import SubserviceSelection
12 import NavigationInstance
13
14 from Tools.XMLTools import elementsWithTag, mergeText
15 from ServiceReference import ServiceReference
16
17 # ok, for descriptions etc we have:
18 # service reference  (to get the service name)
19 # name               (title)
20 # description        (description)
21 # event data         (ONLY for time adjustments etc.)
22
23
24 # parses an event, and gives out a (begin, end, name, duration, eit)-tuple.
25 def parseEvent(ev):
26         name = ev.getEventName()
27         description = ev.getShortDescription()
28         begin = ev.getBeginTime()
29         end = begin + ev.getDuration()
30         eit = ev.getEventId()
31         return (begin, end, name, description, eit)
32
33 # please do not translate log messages
34 class RecordTimerEntry(timer.TimerEntry):
35         def __init__(self, serviceref, begin, end, name, description, eit):
36                 timer.TimerEntry.__init__(self, int(begin), int(end))
37                 
38                 assert isinstance(serviceref, ServiceReference)
39                 
40                 self.service_ref = serviceref
41                 self.eit = eit
42                 self.dontSave = False
43                 self.name = name
44                 self.description = description
45                 self.timer = None
46                 self.record_service = None
47                 self.start_prepare = 0
48                 
49                 self.log_entries = []
50                 self.resetState()
51         
52         def log(self, code, msg):
53                 self.log_entries.append((int(time.time()), code, msg))
54                 print "[TIMER]", msg
55         
56         def resetState(self):
57                 self.state = self.StateWaiting
58                 self.first_try_prepare = True
59                 self.timeChanged()
60         
61         def calculateFilename(self):
62                 service_name = self.service_ref.getServiceName()
63 #               begin_date = datetime.fromtimestamp(begin).strf...
64                 begin_date = ""
65                 
66                 print "begin_date: ", begin_date
67                 print "service_name: ", service_name
68                 print "name:", self.name
69                 print "description: ", self.description
70
71                 self.Filename = Directories.getRecordingFilename(service_name)
72                 self.log(0, "Filename calculated as: '%s'" % self.Filename)
73                 #begin_date + " - " + service_name + description)
74         
75         def tryPrepare(self):
76                 self.calculateFilename()
77                 self.record_service = NavigationInstance.instance.recordService(self.service_ref)
78                 if self.record_service == None:
79                         self.log(1, "'record service' failed")
80                         return False
81                 else:
82                         prep_res = self.record_service.prepare(self.Filename + ".ts")
83                         if prep_res:
84                                 self.log(2, "'prepare' failed: error %d" % prep_res)
85                                 self.record_service = None
86                                 return False
87
88                         self.log(3, "prepare ok, writing meta information to %s" % self.Filename)
89                         try:
90                                 f = open(self.Filename + ".ts.meta", "w")
91                                 f.write(str(self.service_ref) + "\n")
92                                 f.write(self.name + "\n")
93                                 f.write(self.description + "\n")
94                                 f.write(str(self.begin) + "\n")
95                                 f.close()
96                         except:
97                                 self.log(4, "failed to write meta information")
98                         return True
99
100         def do_backoff(self):
101                 if self.backoff == 0:
102                         self.backoff = 5
103                 else:
104                         self.backoff *= 2
105                         if self.backoff > 100:
106                                 self.backoff = 100
107                 self.log(10, "backoff: retry in %d seconds" % self.backoff)
108
109         def activate(self):
110                 next_state = self.state + 1
111                 self.log(5, "activating state %d" % next_state)
112                 
113                 if next_state == self.StatePrepared:
114                         if self.tryPrepare():
115                                 self.log(6, "prepare ok, waiting for begin")
116                                 # fine. it worked, resources are allocated.
117                                 self.next_activation = self.begin
118                                 self.backoff = 0
119                                 return True
120                         
121                         self.log(7, "prepare failed")
122                         if self.first_try_prepare:
123                                 self.first_try_prepare = False
124                                 if config.recording.asktozap.value == 0:
125                                         self.log(8, "asking user to zap away")
126                                         Notifications.AddNotificationWithCallback(self.failureCB, MessageBox, _("A timer failed to record!\nDisable TV and try again?\n"))
127                                 else: # zap without asking
128                                         self.log(9, "zap without asking")
129                                         self.failureCB(True)
130
131                         self.do_backoff()
132                         # retry
133                         self.start_prepare = time.time() + self.backoff
134                         return False
135                 elif next_state == self.StateRunning:
136                         self.log(11, "start recording")
137                         record_res = self.record_service.start()
138                         
139                         if record_res:
140                                 self.log(13, "start record returned %d" % record_res)
141                                 self.do_backoff()
142                                 # retry
143                                 self.begin = time.time() + self.backoff
144                                 return False
145                         
146                         return True
147                 elif next_state == self.StateEnded:
148                         self.log(12, "stop recording")
149                         self.record_service.stop()
150                         self.record_service = None
151                         return True
152
153         def getNextActivation(self):
154                 if self.state == self.StateEnded:
155                         return self.end
156                 
157                 next_state = self.state + 1
158                 
159                 return {self.StatePrepared: self.start_prepare, 
160                                 self.StateRunning: self.begin, 
161                                 self.StateEnded: self.end }[next_state]
162
163         def failureCB(self, answer):
164                 if answer == True:
165                         self.log(13, "ok, zapped away")
166                         #NavigationInstance.instance.stopUserServices()
167                         NavigationInstance.instance.playService(self.service_ref.ref)
168                 else:
169                         self.log(14, "user didn't want to zap away, record will probably fail")
170
171         def timeChanged(self):
172                 old_prepare = self.start_prepare
173                 self.start_prepare = self.begin - self.prepare_time
174                 self.backoff = 0
175                 
176                 if old_prepare != self.start_prepare:
177                         self.log(15, "record time changed, start prepare is now: %s" % time.ctime(self.start_prepare))
178
179 def createTimer(xml):
180         begin = int(xml.getAttribute("begin"))
181         end = int(xml.getAttribute("end"))
182         serviceref = ServiceReference(str(xml.getAttribute("serviceref")))
183         description = xml.getAttribute("description").encode("utf-8")
184         repeated = xml.getAttribute("repeated").encode("utf-8")
185         try:
186                 eit = long(xml.getAttribute("eit").encode("utf-8"))
187         except:
188                 eit = None
189         name = xml.getAttribute("name").encode("utf-8")
190         #filename = xml.getAttribute("filename").encode("utf-8")
191         entry = RecordTimerEntry(serviceref, begin, end, name, description, eit)
192         entry.repeated = int(repeated)
193         
194         for l in elementsWithTag(xml.childNodes, "log"):
195                 time = int(l.getAttribute("time"))
196                 code = int(l.getAttribute("code"))
197                 msg = mergeText(l.childNodes).strip()
198                 entry.log_entries.append((time, code, msg))
199         
200         return entry
201
202 class RecordTimer(timer.Timer):
203         def __init__(self):
204                 timer.Timer.__init__(self)
205                 
206                 self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
207                 
208                 try:
209                         self.loadTimer()
210                 except IOError:
211                         print "unable to load timers from file!"
212
213         def isRecording(self):
214                 isRunning = False
215                 for timer in self.timer_list:
216                         if timer.isRunning():
217                                 isRunning = True
218                 return isRunning
219         
220         def loadTimer(self):
221                 # TODO: PATH!
222                 doc = xml.dom.minidom.parse(self.Filename)
223                 
224                 root = doc.childNodes[0]
225                 for timer in elementsWithTag(root.childNodes, "timer"):
226                         self.record(createTimer(timer))
227         
228         def saveTimer(self):
229                 #doc = xml.dom.minidom.Document()
230                 #root_element = doc.createElement('timers')
231                 #doc.appendChild(root_element)
232                 #root_element.appendChild(doc.createTextNode("\n"))
233                 
234                 #for timer in self.timer_list + self.processed_timers:
235                         # some timers (instant records) don't want to be saved.
236                         # skip them
237                         #if timer.dontSave:
238                                 #continue
239                         #t = doc.createTextNode("\t")
240                         #root_element.appendChild(t)
241                         #t = doc.createElement('timer')
242                         #t.setAttribute("begin", str(int(timer.begin)))
243                         #t.setAttribute("end", str(int(timer.end)))
244                         #t.setAttribute("serviceref", str(timer.service_ref))
245                         #t.setAttribute("repeated", str(timer.repeated))                        
246                         #t.setAttribute("name", timer.name)
247                         #t.setAttribute("description", timer.description)
248                         #t.setAttribute("eit", str(timer.eit))
249                         
250                         #for time, code, msg in timer.log_entries:
251                                 #t.appendChild(doc.createTextNode("\t\t"))
252                                 #l = doc.createElement('log')
253                                 #l.setAttribute("time", str(time))
254                                 #l.setAttribute("code", str(code))
255                                 #l.appendChild(doc.createTextNode(msg))
256                                 #t.appendChild(l)
257                                 #t.appendChild(doc.createTextNode("\n"))
258
259                         #root_element.appendChild(t)
260                         #t = doc.createTextNode("\n")
261                         #root_element.appendChild(t)
262
263
264                 #file = open(self.Filename, "w")
265                 #doc.writexml(file)
266                 #file.write("\n")
267                 #file.close()
268
269                 list = []
270
271                 list.append('<?xml version="1.0" ?>\n')
272                 list.append('<timers>\n')
273                 
274                 for timer in self.timer_list + self.processed_timers:
275                         list.append('<timer')
276                         list.append(' begin="' + str(int(timer.begin)) + '"')
277                         list.append(' end="' + str(int(timer.end)) + '"')
278                         list.append(' serviceref="' + str(timer.service_ref) + '"')
279                         list.append(' repeated="' + str(int(timer.repeated)) + '"')
280                         list.append(' name="' + str(timer.name) + '"')
281                         list.append(' description="' + str(timer.description) + '"')
282                         list.append(' eit="' + str(timer.eit) + '"')
283                         list.append('>\n')
284                         
285                         for time, code, msg in timer.log_entries:
286                                 list.append('<log')
287                                 list.append(' code="' + str(code) + '"')
288                                 list.append(' time="' + str(time) + '"')
289                                 list.append('>')
290                                 list.append(str(msg))
291                                 list.append('</log>\n')
292
293                         
294                         list.append('</timer>\n')
295
296                 list.append('</timers>\n')
297
298                 file = open(self.Filename, "w")
299                 for x in list:
300                         file.write(x)
301                 file.close()
302
303         def record(self, entry):
304                 entry.timeChanged()
305                 print "[Timer] Record " + str(entry)
306                 entry.Timer = self
307                 self.addTimerEntry(entry)
308
309         def removeEntry(self, entry):
310                 print "[Timer] Remove " + str(entry)
311                 
312                 # avoid re-enqueuing
313                 entry.repeated = False
314
315                 # abort timer.
316                 # this sets the end time to current time, so timer will be stopped.
317                 entry.abort()
318                 
319                 if entry.state != entry.StateEnded:
320                         self.timeChanged(entry)
321                 
322                 print "state: ", entry.state
323                 print "in processed: ", entry in self.processed_timers
324                 print "in running: ", entry in self.timer_list
325                 # now the timer should be in the processed_timers list. remove it from there.
326                 self.processed_timers.remove(entry)
327
328         def shutdown(self):
329                 self.saveTimer()