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