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