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