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