fit the new plugin paths
[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         disabled = long(xml.getAttribute("disabled") or "0")
193         if xml.hasAttribute("eit") and xml.getAttribute("eit") != "None":
194                 eit = long(xml.getAttribute("eit"))
195         else:
196                 eit = None
197         
198         name = xml.getAttribute("name").encode("utf-8")
199         #filename = xml.getAttribute("filename").encode("utf-8")
200         entry = RecordTimerEntry(serviceref, begin, end, name, description, eit, disabled)
201         entry.repeated = int(repeated)
202         
203         for l in elementsWithTag(xml.childNodes, "log"):
204                 time = int(l.getAttribute("time"))
205                 code = int(l.getAttribute("code"))
206                 msg = mergeText(l.childNodes).strip().encode("utf-8")
207                 entry.log_entries.append((time, code, msg))
208         
209         return entry
210
211 class RecordTimer(timer.Timer):
212         def __init__(self):
213                 timer.Timer.__init__(self)
214                 
215                 self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
216                 
217                 try:
218                         self.loadTimer()
219                 except IOError:
220                         print "unable to load timers from file!"
221
222         def isRecording(self):
223                 isRunning = False
224                 for timer in self.timer_list:
225                         if timer.isRunning():
226                                 isRunning = True
227                 return isRunning
228         
229         def loadTimer(self):
230                 # TODO: PATH!
231                 doc = xml.dom.minidom.parse(self.Filename)
232                 
233                 root = doc.childNodes[0]
234                 for timer in elementsWithTag(root.childNodes, "timer"):
235                         self.record(createTimer(timer))
236
237         def strToXML(self, str):
238                 return str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("'", '&apos;'). replace('"', '&qout;')
239
240         def saveTimer(self):
241                 #doc = xml.dom.minidom.Document()
242                 #root_element = doc.createElement('timers')
243                 #doc.appendChild(root_element)
244                 #root_element.appendChild(doc.createTextNode("\n"))
245                 
246                 #for timer in self.timer_list + self.processed_timers:
247                         # some timers (instant records) don't want to be saved.
248                         # skip them
249                         #if timer.dontSave:
250                                 #continue
251                         #t = doc.createTextNode("\t")
252                         #root_element.appendChild(t)
253                         #t = doc.createElement('timer')
254                         #t.setAttribute("begin", str(int(timer.begin)))
255                         #t.setAttribute("end", str(int(timer.end)))
256                         #t.setAttribute("serviceref", str(timer.service_ref))
257                         #t.setAttribute("repeated", str(timer.repeated))                        
258                         #t.setAttribute("name", timer.name)
259                         #t.setAttribute("description", timer.description)
260                         #t.setAttribute("eit", str(timer.eit))
261                         
262                         #for time, code, msg in timer.log_entries:
263                                 #t.appendChild(doc.createTextNode("\t\t"))
264                                 #l = doc.createElement('log')
265                                 #l.setAttribute("time", str(time))
266                                 #l.setAttribute("code", str(code))
267                                 #l.appendChild(doc.createTextNode(msg))
268                                 #t.appendChild(l)
269                                 #t.appendChild(doc.createTextNode("\n"))
270
271                         #root_element.appendChild(t)
272                         #t = doc.createTextNode("\n")
273                         #root_element.appendChild(t)
274
275
276                 #file = open(self.Filename, "w")
277                 #doc.writexml(file)
278                 #file.write("\n")
279                 #file.close()
280
281                 list = []
282
283                 list.append('<?xml version="1.0" ?>\n')
284                 list.append('<timers>\n')
285                 
286                 for timer in self.timer_list + self.processed_timers:
287                         if timer.dontSave:
288                                 continue
289
290                         list.append('<timer')
291                         list.append(' begin="' + str(int(timer.begin)) + '"')
292                         list.append(' end="' + str(int(timer.end)) + '"')
293                         list.append(' serviceref="' + str(timer.service_ref) + '"')
294                         list.append(' repeated="' + str(int(timer.repeated)) + '"')
295                         list.append(' name="' + str(self.strToXML(timer.name)) + '"')
296                         list.append(' description="' + str(self.strToXML(timer.description)) + '"')
297                         if timer.eit is not None:
298                                 list.append(' eit="' + str(timer.eit) + '"')
299                         list.append(' disabled="' + str(int(timer.disabled)) + '"')
300                         list.append('>\n')
301                         
302                         for time, code, msg in timer.log_entries:
303                                 list.append('<log')
304                                 list.append(' code="' + str(code) + '"')
305                                 list.append(' time="' + str(time) + '"')
306                                 list.append('>')
307                                 list.append(str(msg))
308                                 list.append('</log>\n')
309
310                         
311                         list.append('</timer>\n')
312
313                 list.append('</timers>\n')
314
315                 file = open(self.Filename, "w")
316                 for x in list:
317                         file.write(x)
318                 file.close()
319
320         def record(self, entry):
321                 entry.timeChanged()
322                 print "[Timer] Record " + str(entry)
323                 entry.Timer = self
324                 self.addTimerEntry(entry)
325
326         def removeEntry(self, entry):
327                 print "[Timer] Remove " + str(entry)
328                 
329                 # avoid re-enqueuing
330                 entry.repeated = False
331
332                 # abort timer.
333                 # this sets the end time to current time, so timer will be stopped.
334                 entry.abort()
335                 
336                 if entry.state != entry.StateEnded:
337                         self.timeChanged(entry)
338                 
339                 print "state: ", entry.state
340                 print "in processed: ", entry in self.processed_timers
341                 print "in running: ", entry in self.timer_list
342                 # now the timer should be in the processed_timers list. remove it from there.
343                 self.processed_timers.remove(entry)
344
345         def shutdown(self):
346                 self.saveTimer()