3 #from time import datetime
4 from Tools import Directories, Notifications
6 from Components.config import config, ConfigYesNo
10 from enigma import eEPGCache, getBestPlayableServiceReference, \
11 eServiceReference, iRecordableService, quitMainloop
13 from Screens.MessageBox import MessageBox
15 import NavigationInstance
17 import Screens.Standby
19 from time import localtime
21 from Tools.XMLTools import elementsWithTag, mergeText, stringToXML
22 from ServiceReference import ServiceReference
24 # ok, for descriptions etc we have:
25 # service reference (to get the service name)
27 # description (description)
28 # event data (ONLY for time adjustments etc.)
31 # parses an event, and gives out a (begin, end, name, duration, eit)-tuple.
32 # begin and end will be corrected
33 def parseEvent(ev, description = True):
35 name = ev.getEventName()
36 description = ev.getShortDescription()
40 begin = ev.getBeginTime()
41 end = begin + ev.getDuration()
43 begin -= config.recording.margin_before.value * 60
44 end += config.recording.margin_after.value * 60
45 return (begin, end, name, description, eit)
52 # please do not translate log messages
53 class RecordTimerEntry(timer.TimerEntry):
54 ######### the following static methods and members are only in use when the box is in (soft) standby
55 receiveRecordEvents = False
62 def gotRecordEvent(recservice, event):
63 if event == iRecordableService.evEnd:
64 print "RecordTimer.gotRecordEvent(iRecordableService.evEnd)"
65 recordings = NavigationInstance.instance.getRecordings()
66 if not len(recordings): # no more recordings exist
67 rec_time = NavigationInstance.instance.RecordTimer.getNextRecordingTime()
68 if rec_time > 0 and (rec_time - time.time()) < 360:
69 print "another recording starts in", rec_time - time.time(), "seconds... do not shutdown yet"
71 print "no starting records in the next 360 seconds... immediate shutdown"
72 RecordTimerEntry.shutdown() # immediate shutdown
73 elif event == iRecordableService.evStart:
74 print "RecordTimer.gotRecordEvent(iRecordableService.evStart)"
77 def stopTryQuitMainloop():
78 print "RecordTimer.stopTryQuitMainloop"
79 NavigationInstance.instance.record_event.remove(RecordTimerEntry.gotRecordEvent)
80 RecordTimerEntry.receiveRecordEvents = False
83 def TryQuitMainloop():
84 if not RecordTimerEntry.receiveRecordEvents:
85 print "RecordTimer.TryQuitMainloop"
86 NavigationInstance.instance.record_event.append(RecordTimerEntry.gotRecordEvent)
87 RecordTimerEntry.receiveRecordEvents = True
88 # send fake event.. to check if another recordings are running or
89 # other timers start in a few seconds
90 RecordTimerEntry.gotRecordEvent(None, iRecordableService.evEnd)
91 # send normal notification for the case the user leave the standby now..
92 Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1, onSessionOpenCallback=RecordTimerEntry.stopTryQuitMainloop)
93 #################################################################
95 def __init__(self, serviceref, begin, end, name, description, eit, disabled = False, justplay = False, afterEvent = AFTEREVENT.NONE, checkOldTimers = False):
96 timer.TimerEntry.__init__(self, int(begin), int(end))
98 if checkOldTimers == True:
99 if self.begin < time.time() - 1209600:
100 self.begin = int(time.time())
102 if self.end < self.begin:
103 self.end = self.begin
105 assert isinstance(serviceref, ServiceReference)
107 self.service_ref = serviceref
109 self.dontSave = False
111 self.description = description
112 self.disabled = disabled
114 self.record_service = None
115 self.start_prepare = 0
116 self.justplay = justplay
117 self.afterEvent = afterEvent
119 self.log_entries = []
122 def log(self, code, msg):
123 self.log_entries.append((int(time.time()), code, msg))
126 def resetState(self):
127 self.state = self.StateWaiting
128 self.cancelled = False
129 self.first_try_prepare = True
132 def calculateFilename(self):
133 service_name = self.service_ref.getServiceName()
134 begin_date = time.strftime("%Y%m%d %H%M", time.localtime(self.begin))
136 print "begin_date: ", begin_date
137 print "service_name: ", service_name
138 print "name:", self.name
139 print "description: ", self.description
141 filename = begin_date + " - " + service_name
143 filename += " - " + self.name
145 self.Filename = Directories.getRecordingFilename(filename)
146 self.log(0, "Filename calculated as: '%s'" % self.Filename)
147 #begin_date + " - " + service_name + description)
149 def tryPrepare(self):
153 self.calculateFilename()
154 rec_ref = self.service_ref and self.service_ref.ref
155 if rec_ref and rec_ref.flags & eServiceReference.isGroup:
156 rec_ref = getBestPlayableServiceReference(rec_ref, eServiceReference())
158 self.log(1, "'get best playable service for group... record' failed")
161 self.record_service = rec_ref and NavigationInstance.instance.recordService(rec_ref)
162 if not self.record_service:
163 self.log(1, "'record service' failed")
170 prep_res=self.record_service.prepare(self.Filename + ".ts", self.begin, self.end, event_id)
172 self.log(2, "'prepare' failed: error %d" % prep_res)
173 self.record_service = None
177 epgcache = eEPGCache.getInstance()
178 queryTime=self.begin+(self.end-self.begin)/2
179 evt = epgcache.lookupEventTime(rec_ref, queryTime)
181 self.description = evt.getShortDescription()
183 self.log(3, "prepare ok, writing meta information to %s" % self.Filename)
185 f = open(self.Filename + ".ts.meta", "w")
186 f.write(rec_ref.toString() + "\n")
187 f.write(self.name + "\n")
188 f.write(self.description + "\n")
189 f.write(str(self.begin) + "\n")
192 self.log(4, "failed to write meta information")
193 self.record_service = None
197 def do_backoff(self):
198 if self.backoff == 0:
202 if self.backoff > 100:
204 self.log(10, "backoff: retry in %d seconds" % self.backoff)
207 next_state = self.state + 1
208 self.log(5, "activating state %d" % next_state)
210 if next_state == self.StatePrepared:
211 if self.tryPrepare():
212 self.log(6, "prepare ok, waiting for begin")
213 # fine. it worked, resources are allocated.
214 self.next_activation = self.begin
218 self.log(7, "prepare failed")
219 if self.first_try_prepare:
220 self.first_try_prepare = False
221 if not config.recording.asktozap.value:
222 self.log(8, "asking user to zap away")
223 Notifications.AddNotificationWithCallback(self.failureCB, MessageBox, _("A timer failed to record!\nDisable TV and try again?\n"), timeout=20)
224 else: # zap without asking
225 self.log(9, "zap without asking")
226 Notifications.AddNotification(MessageBox, _("In order to record a timer, the TV was switched to the recording service!\n"), type=MessageBox.TYPE_INFO, timeout=20)
231 self.start_prepare = time.time() + self.backoff
233 elif next_state == self.StateRunning:
234 # if this timer has been cancelled, just go to "end" state.
239 self.log(11, "zapping")
240 NavigationInstance.instance.playService(self.service_ref.ref)
243 self.log(11, "start recording")
244 record_res = self.record_service.start()
247 self.log(13, "start record returned %d" % record_res)
250 self.begin = time.time() + self.backoff
254 elif next_state == self.StateEnded:
255 self.log(12, "stop recording")
256 if not self.justplay:
257 NavigationInstance.instance.stopRecordService(self.record_service)
258 self.record_service = None
259 if self.afterEvent == AFTEREVENT.STANDBY:
260 if not Screens.Standby.inStandby: # not already in standby
261 Notifications.AddNotificationWithCallback(self.sendStandbyNotification, MessageBox, _("A finished record timer wants to set your\nDreambox to standby. Do that now?"), timeout = 20)
262 if self.afterEvent == AFTEREVENT.DEEPSTANDBY:
263 if not Screens.Standby.inTryQuitMainloop: # not a shutdown messagebox is open
264 if Screens.Standby.inStandby: # not in standby
265 RecordTimerEntry.TryQuitMainloop() # start shutdown handling without screen
267 Notifications.AddNotificationWithCallback(self.sendTryQuitMainloopNotification, MessageBox, _("A finished record timer wants to shut down\nyour Dreambox. Shutdown now?"), timeout = 20)
270 def sendStandbyNotification(self, answer):
272 Notifications.AddNotification(Screens.Standby.Standby)
274 def sendTryQuitMainloopNotification(self, answer):
276 Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1)
278 def getNextActivation(self):
279 if self.state == self.StateEnded:
282 next_state = self.state + 1
284 return {self.StatePrepared: self.start_prepare,
285 self.StateRunning: self.begin,
286 self.StateEnded: self.end }[next_state]
288 def failureCB(self, answer):
290 self.log(13, "ok, zapped away")
291 #NavigationInstance.instance.stopUserServices()
292 NavigationInstance.instance.playService(self.service_ref.ref)
294 self.log(14, "user didn't want to zap away, record will probably fail")
296 def timeChanged(self):
297 old_prepare = self.start_prepare
298 self.start_prepare = self.begin - self.prepare_time
301 if int(old_prepare) != int(self.start_prepare):
302 self.log(15, "record time changed, start prepare is now: %s" % time.ctime(self.start_prepare))
304 def createTimer(xml):
305 begin = int(xml.getAttribute("begin"))
306 end = int(xml.getAttribute("end"))
307 serviceref = ServiceReference(xml.getAttribute("serviceref").encode("utf-8"))
308 description = xml.getAttribute("description").encode("utf-8")
309 repeated = xml.getAttribute("repeated").encode("utf-8")
310 disabled = long(xml.getAttribute("disabled") or "0")
311 justplay = long(xml.getAttribute("justplay") or "0")
312 afterevent = str(xml.getAttribute("afterevent") or "nothing")
313 afterevent = { "nothing": AFTEREVENT.NONE, "standby": AFTEREVENT.STANDBY, "deepstandby": AFTEREVENT.DEEPSTANDBY }[afterevent]
314 if xml.hasAttribute("eit") and xml.getAttribute("eit") != "None":
315 eit = long(xml.getAttribute("eit"))
319 name = xml.getAttribute("name").encode("utf-8")
320 #filename = xml.getAttribute("filename").encode("utf-8")
321 entry = RecordTimerEntry(serviceref, begin, end, name, description, eit, disabled, justplay, afterevent)
322 entry.repeated = int(repeated)
324 for l in elementsWithTag(xml.childNodes, "log"):
325 time = int(l.getAttribute("time"))
326 code = int(l.getAttribute("code"))
327 msg = mergeText(l.childNodes).strip().encode("utf-8")
328 entry.log_entries.append((time, code, msg))
332 class RecordTimer(timer.Timer):
334 timer.Timer.__init__(self)
336 self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
341 print "unable to load timers from file!"
343 def isRecording(self):
345 for timer in self.timer_list:
346 if timer.isRunning() and not timer.justplay:
352 doc = xml.dom.minidom.parse(self.Filename)
354 root = doc.childNodes[0]
355 for timer in elementsWithTag(root.childNodes, "timer"):
356 self.record(createTimer(timer))
359 #doc = xml.dom.minidom.Document()
360 #root_element = doc.createElement('timers')
361 #doc.appendChild(root_element)
362 #root_element.appendChild(doc.createTextNode("\n"))
364 #for timer in self.timer_list + self.processed_timers:
365 # some timers (instant records) don't want to be saved.
369 #t = doc.createTextNode("\t")
370 #root_element.appendChild(t)
371 #t = doc.createElement('timer')
372 #t.setAttribute("begin", str(int(timer.begin)))
373 #t.setAttribute("end", str(int(timer.end)))
374 #t.setAttribute("serviceref", str(timer.service_ref))
375 #t.setAttribute("repeated", str(timer.repeated))
376 #t.setAttribute("name", timer.name)
377 #t.setAttribute("description", timer.description)
378 #t.setAttribute("eit", str(timer.eit))
380 #for time, code, msg in timer.log_entries:
381 #t.appendChild(doc.createTextNode("\t\t"))
382 #l = doc.createElement('log')
383 #l.setAttribute("time", str(time))
384 #l.setAttribute("code", str(code))
385 #l.appendChild(doc.createTextNode(msg))
387 #t.appendChild(doc.createTextNode("\n"))
389 #root_element.appendChild(t)
390 #t = doc.createTextNode("\n")
391 #root_element.appendChild(t)
394 #file = open(self.Filename, "w")
401 list.append('<?xml version="1.0" ?>\n')
402 list.append('<timers>\n')
404 for timer in self.timer_list + self.processed_timers:
408 list.append('<timer')
409 list.append(' begin="' + str(int(timer.begin)) + '"')
410 list.append(' end="' + str(int(timer.end)) + '"')
411 list.append(' serviceref="' + stringToXML(str(timer.service_ref)) + '"')
412 list.append(' repeated="' + str(int(timer.repeated)) + '"')
413 list.append(' name="' + str(stringToXML(timer.name)) + '"')
414 list.append(' description="' + str(stringToXML(timer.description)) + '"')
415 list.append(' afterevent="' + str(stringToXML({ AFTEREVENT.NONE: "nothing", AFTEREVENT.STANDBY: "standby", AFTEREVENT.DEEPSTANDBY: "deepstandby" }[timer.afterEvent])) + '"')
416 if timer.eit is not None:
417 list.append(' eit="' + str(timer.eit) + '"')
418 list.append(' disabled="' + str(int(timer.disabled)) + '"')
419 list.append(' justplay="' + str(int(timer.justplay)) + '"')
422 if config.recording.debug.value:
423 for time, code, msg in timer.log_entries:
425 list.append(' code="' + str(code) + '"')
426 list.append(' time="' + str(time) + '"')
428 list.append(str(stringToXML(msg)))
429 list.append('</log>\n')
431 list.append('</timer>\n')
433 list.append('</timers>\n')
435 file = open(self.Filename, "w")
440 def getNextRecordingTime(self):
441 llen = len(self.timer_list)
444 timer = self.timer_list[idx]
451 def record(self, entry):
453 print "[Timer] Record " + str(entry)
455 self.addTimerEntry(entry)
457 def isInTimer(self, eventid, begin, duration, service):
461 chktimecmp_end = None
462 end = begin + duration
463 for x in self.timer_list:
464 if str(x.service_ref) == str(service):
465 #if x.eit is not None and x.repeated == 0:
466 # if x.eit == eventid:
470 chktime = localtime(begin)
471 chktimecmp = chktime.tm_wday * 1440 + chktime.tm_hour * 60 + chktime.tm_min
472 chktimecmp_end = chktimecmp + (duration / 60)
473 time = localtime(x.begin)
475 if x.repeated & (2 ** y):
476 timecmp = y * 1440 + time.tm_hour * 60 + time.tm_min
477 if timecmp <= chktimecmp < (timecmp + ((x.end - x.begin) / 60)):
478 time_match = ((timecmp + ((x.end - x.begin) / 60)) - chktimecmp) * 60
479 elif chktimecmp <= timecmp < chktimecmp_end:
480 time_match = (chktimecmp_end - timecmp) * 60
481 else: #if x.eit is None:
482 if begin <= x.begin <= end:
484 if time_match < diff:
486 elif x.begin <= begin <= x.end:
488 if time_match < diff:
492 def removeEntry(self, entry):
493 print "[Timer] Remove " + str(entry)
496 entry.repeated = False
499 # this sets the end time to current time, so timer will be stopped.
502 if entry.state != entry.StateEnded:
503 self.timeChanged(entry)
505 print "state: ", entry.state
506 print "in processed: ", entry in self.processed_timers
507 print "in running: ", entry in self.timer_list
508 # now the timer should be in the processed_timers list. remove it from there.
509 self.processed_timers.remove(entry)