fix Screen order in channelselectionradio
[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                 self.start_prepare = self.begin - self.prepare_time
172                 self.backoff = 0
173                 self.log(15, "record time changed, start prepare is now: %s" % time.ctime(self.start_prepare))
174
175 def createTimer(xml):
176         begin = int(xml.getAttribute("begin"))
177         end = int(xml.getAttribute("end"))
178         serviceref = ServiceReference(str(xml.getAttribute("serviceref")))
179         description = xml.getAttribute("description").encode("utf-8")
180         repeated = xml.getAttribute("repeated").encode("utf-8")
181         eit = xml.getAttribute("eit").encode("utf-8")
182         name = xml.getAttribute("name").encode("utf-8")
183         #filename = xml.getAttribute("filename").encode("utf-8")
184         entry = RecordTimerEntry(serviceref, begin, end, name, description, eit)
185         entry.repeated = int(repeated)
186         
187         for l in elementsWithTag(xml.childNodes, "log"):
188                 time = int(l.getAttribute("time"))
189                 code = int(l.getAttribute("code"))
190                 msg = mergeText(l.childNodes).strip()
191                 entry.log_entries.append((time, code, msg))
192         
193         return entry
194
195 class RecordTimer(timer.Timer):
196         def __init__(self):
197                 timer.Timer.__init__(self)
198                 
199                 self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
200                 
201                 try:
202                         self.loadTimer()
203                 except IOError:
204                         print "unable to load timers from file!"
205
206         def isRecording(self):
207                 isRunning = False
208                 for timer in self.timer_list:
209                         if timer.isRunning():
210                                 isRunning = True
211                 return isRunning
212         
213         def loadTimer(self):
214                 # TODO: PATH!
215                 doc = xml.dom.minidom.parse(self.Filename)
216                 
217                 root = doc.childNodes[0]
218                 for timer in elementsWithTag(root.childNodes, "timer"):
219                         self.record(createTimer(timer))
220         
221         def saveTimer(self):
222                 doc = xml.dom.minidom.Document()
223                 root_element = doc.createElement('timers')
224                 doc.appendChild(root_element)
225                 root_element.appendChild(doc.createTextNode("\n"))
226                 
227                 for timer in self.timer_list + self.processed_timers:
228                         # some timers (instant records) don't want to be saved.
229                         # skip them
230                         if timer.dontSave:
231                                 continue
232                         t = doc.createTextNode("\t")
233                         root_element.appendChild(t)
234                         t = doc.createElement('timer')
235                         t.setAttribute("begin", str(int(timer.begin)))
236                         t.setAttribute("end", str(int(timer.end)))
237                         t.setAttribute("serviceref", str(timer.service_ref))
238                         t.setAttribute("repeated", str(timer.repeated))                 
239                         t.setAttribute("name", timer.name)
240                         t.setAttribute("description", timer.description)
241                         t.setAttribute("eit", str(timer.eit))
242                         
243                         for time, code, msg in timer.log_entries:
244                                 t.appendChild(doc.createTextNode("\t\t"))
245                                 l = doc.createElement('log')
246                                 l.setAttribute("time", str(time))
247                                 l.setAttribute("code", str(code))
248                                 l.appendChild(doc.createTextNode(msg))
249                                 t.appendChild(l)
250                                 t.appendChild(doc.createTextNode("\n"))
251
252                         root_element.appendChild(t)
253                         t = doc.createTextNode("\n")
254                         root_element.appendChild(t)
255
256                 file = open(self.Filename, "w")
257                 doc.writexml(file)
258                 file.write("\n")
259                 file.close()
260
261         def record(self, entry):
262                 entry.timeChanged()
263                 print "[Timer] Record " + str(entry)
264                 entry.Timer = self
265                 self.addTimerEntry(entry)
266
267         def removeEntry(self, entry):
268                 print "[Timer] Remove " + str(entry)
269                 
270                 # avoid re-enqueuing
271                 entry.repeated = False
272
273                 # abort timer.
274                 # this sets the end time to current time, so timer will be stopped.
275                 entry.abort()
276                 
277                 if entry.state != entry.StateEnded:
278                         self.timeChanged(entry)
279                 
280                 print "state: ", entry.state
281                 print "in processed: ", entry in self.processed_timers
282                 print "in running: ", entry in self.timer_list
283                 # now the timer should be in the processed_timers list. remove it from there.
284                 self.processed_timers.remove(entry)
285
286         def shutdown(self):
287                 self.saveTimer()