def setWakeup(self, shutdown=True): if not self.__wakeUpUT: tools.writeLog('No recordings or EPG update to schedule') elif self.__wakeUpUT == self.__wakeUpUTRec: tools.writeLog('Recording wake-up time: %s' % (self.__wakeUp.strftime('%d.%m.%y %H:%M'))) elif self.__wakeUpUT == self.__wakeUpUTEpg: tools.writeLog('EPG update wake-up time: %s' % (self.__wakeUp.strftime('%d.%m.%y %H:%M'))) tools.writeLog('Wake-up Unix time: %s' % (self.__wakeUpUT), xbmc.LOGINFO) # tools.writeLog('Flags before shutdown are: {0:05b}'.format(self.__flags)) if shutdown: # Show notifications if self.__nextsched: if self.__wakeUpUT == self.__wakeUpUTRec: tools.Notify().notify( __LS__(30017), __LS__(30018) % (self.__wakeUp.strftime('%d.%m.%Y %H:%M'))) elif self.__wakeUpUT == self.__wakeUpUTEpg: tools.Notify().notify( __LS__(30017), __LS__(30019) % (self.__wakeUp.strftime('%d.%m.%Y %H:%M'))) else: tools.Notify().notify(__LS__(30010), __LS__(30014)) if xbmc.getCondVisibility( 'Player.Playing') or xbmc.getCondVisibility( 'Player.Paused'): tools.writeLog('Stopping Player') xbmc.Player().stop() tools.writeLog( 'Instruct the system to shut down using %s' % ('Application' if self.__shutdown == 0 else 'OS'), xbmc.LOGINFO) os.system( '%s%s %s %s' % (self.__sudo, SHUTDOWN_CMD, self.__wakeUpUT, self.__shutdown)) if self.__shutdown == 0: xbmc.shutdown() xbmc.sleep(1000) return True else: os.system('%s%s %s %s' % (self.__sudo, SHUTDOWN_CMD, self.__wakeUpUT, 0)) return False
def __getPvrStatusXML(self): _attempts = self.__maxattempts if not self.hasPVR: tools.writeLog('No HTS PVR client installed or inactive', level=xbmc.LOGERROR) tools.Notify().notify(__LS__(30030), __LS__(30032), icon=xbmcgui.NOTIFICATION_ERROR) self.__xml = None return False else: while self.hasPVR and _attempts > 0: # try DigestAuth as first, as this is the default auth on TVH > 3.9 try: conn = requests.get('%s:%s/status.xml' % (self.__server, self.__port), auth=requests.auth.HTTPDigestAuth( self.__user, self.__pass)) conn.close() if conn.status_code == 200: # tools.writeLog('Getting status.xml (Digest Auth)') self.__xml = conn.content return True else: # try BasicAuth as older method conn = requests.get('%s:%s/status.xml' % (self.__server, self.__port), auth=requests.auth.HTTPBasicAuth( self.__user, self.__pass)) conn.close() if conn.status_code == 200: # tools.writeLog('Getting status.xml (Basic Auth)') self.__xml = conn.content return True if conn.status_code == 401: tools.writeLog('Unauthorized access (401)') break except requests.ConnectionError: _attempts -= 1 tools.writeLog('%s unreachable, remaining attempts: %s' % (self.__server, _attempts)) xbmc.sleep(5000) continue tools.Notify().notify(__LS__(30030), __LS__(30031), icon=xbmcgui.NOTIFICATION_ERROR) self.__xml = None return False
def updateAutoModeDialog(self): if not self.__dialog_pb is None: if self.__auto_mode_counter == 0: self.disableScreensaver() tools.writeLog('Display countdown dialog for %s secs' % (self.__auto_mode_set)) if xbmc.getCondVisibility('VideoPlayer.isFullscreen'): tools.writeLog( 'Countdown possibly invisible (fullscreen mode)') tools.writeLog('Showing additional notification') tools.Notify().notify( __LS__(30010), __LS__(30011) % (self.__auto_mode_set)) # actualize progressbar if self.__auto_mode_counter < self.__auto_mode_set: __percent = int(self.__auto_mode_counter * 100 / self.__auto_mode_set) self.__dialog_pb.update( __percent, __LS__(30010), __LS__(30011) % (self.__auto_mode_set - self.__auto_mode_counter)) self.__auto_mode_counter += 1 if self.__auto_mode_counter == self.__auto_mode_set: return True return False
def countDown(cls, counter=5): __bar = 0 __percent = 0 __counter = counter __idleTime = xbmc.getGlobalIdleTime() # deactivate screensaver (send key select) if xbmc.getCondVisibility('System.ScreenSaverActive'): query = {"method": "Input.Select"} tools.jsonrpc(query) if xbmc.getCondVisibility('VideoPlayer.isFullscreen'): tools.writeLog('Countdown possibly invisible (fullscreen mode)') tools.writeLog('Showing additional notification') tools.Notify().notify(__LS__(30010), __LS__(30011) % (__counter)) # show countdown tools.writeLog('Display countdown dialog for %s secs' % __counter) pb = xbmcgui.DialogProgressBG() pb.create(__LS__(30010), __LS__(30011) % __counter) pb.update(__percent) # actualize progressbar while __bar <= __counter: __percent = int(__bar * 100 / __counter) pb.update(__percent, __LS__(30010), __LS__(30011) % (__counter - __bar)) if __idleTime > xbmc.getGlobalIdleTime(): tools.writeLog('Countdown aborted by user', level=xbmc.LOGNOTICE) pb.close() return True xbmc.sleep(1000) __idleTime += 1 __bar += 1 pb.close() return False
def controller(mode=None, handle=None, content=None, eventId=None, actor=None): now = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z' timemax = ( datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) + relativedelta.relativedelta(months=tools.getAddonSetting( 'timemax', sType=tools.NUM))).isoformat() + 'Z' if mode == 'load_glotz_key': glotz_apikey = tools.dialogFile(__LS__(30089)) if glotz_apikey != '': tools.setAddonSetting('glotz_apikey', glotz_apikey) tools.writeLog('API key for glotz.info successfull stored') tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'abort_reminders': tools.writeLog('abort notification service by setup', xbmc.LOGNOTICE) xbmcgui.Window(10000).setProperty('reminders', '0') elif mode == 'getcontent': googlecal = Calendar() googlecal.build_sheet(handle, TEMP_STORAGE_EVENTS, content, now, timemax, maxResult=30) elif mode == 'getinfo' and eventId != '': googlecal = Calendar() events = eventId.strip(' ').split(' ') _header = '' _msg = '' for event in events: _ev = googlecal.get_event(event, TEMP_STORAGE_EVENTS) _mev = googlecal.prepareForAddon(_ev, optTimeStamps=True) _time = '' if _mev.get( 'range', '') == '' else '[B]%s[/B]: ' % (_mev.get('range')) if actor and actor == 'eventlist': _header = 'S%02iE%02i: %s' % ( _mev.get('season'), _mev.get('episode'), _mev.get('title')) _msg = '%s' % (_mev.get('plot')) else: _header = '%s %s %s' % (__LS__(30109), __LS__(30145), _mev.get('shortdate', '')) _msg += '%s%s[CR]%s[CR][CR]' % (_time, _mev.get( 'summary', ''), _mev.get('description') or __LS__(30093)) tools.dialogOK(_header, _msg) elif mode == 'prev': calc_boundaries(-1) elif mode == 'next': calc_boundaries(1) # this is the real controller bootstrap elif mode == 'gui': try: Popup = xbmcgui.WindowXMLDialog(__xml__, __path__) Popup.doModal() del Popup except RuntimeError as e: raise FileNotFoundException('%s: %s' % (e.message, __xml__)) else: pass
arguments = sys.argv if len(arguments) > 1: if arguments[0][0:6] == 'plugin': # calling as plugin path _addonHandle = int(arguments[1]) arguments.pop(0) arguments[1] = arguments[1][1:] tools.writeLog('parameter hash: %s' % (str(arguments[1])), xbmc.LOGNOTICE) params = tools.ParamsToDict(arguments[1]) action = params.get('action', '') content = params.get('content', '') eventId = params.get('id', '') actor = params.get('actor') # call the controller of MVC try: if action is not None: controller(mode=action, handle=_addonHandle, content=content, eventId=eventId, actor=actor) else: controller(mode='gui') except FileNotFoundException as e: tools.writeLog(e.message, xbmc.LOGERROR) tools.Notify().notify(__LS__(30010), __LS__(30079))
months=t.getAddonSetting('timemax', sType=t.NUM)) ).isoformat() + 'Z' events = googlecal.get_events( TEMP_STORAGE_NOTIFICATIONS, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('notifications'), evtype='notification') _ev_count = 1 for event in events: event = googlecal.prepareForAddon(event) t.Notify().notify( '%s %s %s' % (event['timestamps'], __LS__(30145), event['shortdate']), event['description'] or event['summary'], icon=__icon__) _ev_count += 1 xbmc.Monitor().waitForAbort(7) if _ev_count > t.getAddonSetting( 'numreminders', sType=t.NUM) or xbmcgui.Window( 10000).getProperty('reminders') != '1': break if events and _cycle > 0: DialogKT = DKT.DialogKaiToast.createDialogKaiToast() DialogKT.label_1 = __LS__(30019) DialogKT.label_2 = __LS__(30018) DialogKT.icon = __icon2__ DialogKT.show()
def controller(mode=None, handle=None, content=None, eventId=None): now = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z' timemax = ( datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) + relativedelta.relativedelta(months=tools.getAddonSetting( 'timemax', sType=tools.NUM))).isoformat() + 'Z' if mode == 'require_oauth_key': Calendar().require_credentials(Calendar().CLIENT_CREDENTIALS, require_from_setup=True) tools.writeLog('new credentials successfull received and stored', xbmc.LOGDEBUG) tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'reenter_oauth_key': Calendar().require_credentials(Calendar().CLIENT_CREDENTIALS, require_from_setup=True, reenter='kb') tools.writeLog('new credentials successfull received and stored', xbmc.LOGDEBUG) tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'load_oauth_key': Calendar().require_credentials(Calendar().CLIENT_CREDENTIALS, require_from_setup=True, reenter='file') tools.writeLog('new credentials successfull received and stored', xbmc.LOGDEBUG) tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'load_glotz_key': glotz_apikey = tools.dialogFile(__LS__(30089)) if glotz_apikey != '': tools.setAddonSetting('glotz_apikey', glotz_apikey) tools.writeLog('API key for glotz.info successfull stored') tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'check_mailsettings': mail = SMTPMail() mail.checkproperties() mail.sendmail( __LS__(30074) % (__LS__(30010), tools.release().hostname), __LS__(30075)) tools.writeLog('mail delivered', xbmc.LOGNOTICE) tools.dialogOK(__LS__(30010), __LS__(30076) % (mail.smtp_client['recipient'])) elif mode == 'abort_reminders': tools.writeLog('abort notification service by setup', xbmc.LOGNOTICE) xbmcgui.Window(10000).setProperty('reminders', '0') elif mode == 'set_calendars': set_localsetting('calendars') googlecal = Calendar() googlecal.get_events( TEMP_STORAGE_EVENTS, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('calendars')) elif mode == 'set_notifications': set_localsetting('notifications') googlecal = Calendar() googlecal.get_events( TEMP_STORAGE_NOTIFICATIONS, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('notifications')) elif mode == 'getcontent': googlecal = Calendar() googlecal.build_sheet( handle, TEMP_STORAGE_EVENTS, content, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('calendars')) elif mode == 'getinfo' and eventId != '': googlecal = Calendar() events = eventId.strip(' ').split(' ') _msg = '' for event in events: _ev = googlecal.get_event(event, TEMP_STORAGE_EVENTS) _mev = googlecal.prepareForAddon(_ev, optTimeStamps=True) _time = '' if _mev.get( 'range', '') == '' else '[B]%s[/B]: ' % (_mev.get('range')) _msg += '%s%s[CR]%s[CR][CR]' % (_time, _mev.get( 'summary', ''), _mev.get('description', False) or _mev.get( 'location', False) or __LS__(30093)) tools.dialogOK( '%s %s %s' % (__LS__(30109), __LS__(30145), _mev.get('shortdate', '')), _msg) elif mode == 'prev': calc_boundaries(-1) elif mode == 'next': calc_boundaries(1) # this is the real controller bootstrap elif mode == 'gui': try: Popup = xbmcgui.WindowXMLDialog(__xml__, __path__) Popup.doModal() del Popup except RuntimeError, e: raise FileNotFoundException('%s: %s' % (e.message, __xml__))
content = params.get('content', '') eventId = params.get('id', '') # call the controller of MVC try: if action is not None: controller(mode=action, handle=_addonHandle, content=content, eventId=eventId) else: controller(mode='gui') except FileNotFoundException, e: tools.writeLog(e.message, xbmc.LOGERROR) tools.Notify().notify(__LS__(30010), __LS__(30079)) except SMTPMail.SMPTMailInvalidOrMissingParameterException, e: tools.writeLog(e.message, xbmc.LOGERROR) tools.dialogOK(__LS__(30010), __LS__(30078)) except SMTPMail.SMTPMailNotDeliveredException, e: tools.writeLog(e.message, xbmc.LOGERROR) tools.dialogOK(__LS__(30010), __LS__(30077) % (SMTPMail.smtp_client['recipient'])) except Calendar.oAuthMissingSecretFile, e: tools.writeLog(e.message, xbmc.LOGERROR) tools.Notify().notify(__LS__(30010), __LS__(30070), icon=xbmcgui.NOTIFICATION_ERROR, repeat=True) except Calendar.oAuthMissingCredentialsFile, e: tools.writeLog(e.message, xbmc.LOGERROR)
def start(self, mode=None): tools.writeLog('Starting service with id:%s@mode:%s' % (self.rndProcNum, mode)) # reset RTC os.system('%s%s %s %s' % (self.__sudo, SHUTDOWN_CMD, 0, 0)) tools.writeLog('Reset RTC') _flags = self.getSysState(verbose=True) if mode is None: if not (_flags & (isREC | isEPG | isPRG | isNET)): tools.writeLog('Service with id %s finished' % (self.rndProcNum), level=xbmc.LOGNOTICE) return elif mode == 'sendmail': if self.deliverMail(__LS__(30065) % (release.hostname)): tools.dialogOK(__LS__(30066), __LS__(30068) % (self.__smtpto)) else: tools.dialogOK(__LS__(30067), __LS__(30069) % (self.__smtpto)) return elif mode == 'poweroff': tools.writeLog('Poweroff command received', level=xbmc.LOGNOTICE) if (_flags & isREC): tools.Notify().notify(__LS__(30015), __LS__(30020), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'Recording in progress' elif (_flags & isEPG): tools.Notify().notify( __LS__(30015), __LS__(30021), icon=xbmcgui.NOTIFICATION_WARNING) # Notify 'EPG-Update' elif (_flags & isPRG): tools.Notify().notify(__LS__(30015), __LS__(30022), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'Postprocessing' elif (_flags & isNET): tools.Notify().notify(__LS__(30015), __LS__(30023), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'Network active' else: if self.countDown(): return _flags = self.setWakeup() else: return # RESUME POINT #1 if (_flags & isRES) and mode == 'poweroff': tools.writeLog('Resume point #1 passed', xbmc.LOGNOTICE) _flags = self.getSysState(verbose=True) & (isREC | isEPG | isPRG | isNET) if not _flags: return mode = None if (_flags & isEPG) and self.__epg_grab_ext and os.path.isfile(EXTGRABBER): tools.writeLog('Starting script for grabbing external EPG') # # ToDo: implement startup of external script (epg grabbing) # _epgpath = self.__epg_path if self.__epg_store and _epgpath == '': _epgpath = '/dev/null' _start = datetime.datetime.now() try: _comm = subprocess.Popen( '%s %s %s' % (EXTGRABBER, _epgpath, self.__epg_socket), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, universal_newlines=True) while _comm.poll() is None: tools.writeLog(_comm.stdout.readline().decode( 'utf-8', 'ignore').strip()) tools.writeLog('external EPG grabber script tooks %s seconds' % ((datetime.datetime.now() - _start).seconds)) except Exception: tools.writeLog('Could not start external EPG grabber script', xbmc.LOGERROR) idle = xbmc.getGlobalIdleTime() ### START MAIN LOOP ### mon = xbmc.Monitor() while _flags: _flags = self.getSysState(verbose=True) & (isREC | isEPG | isPRG | isNET) if mon.waitForAbort(CYCLE): tools.writeLog('Abort request received', level=xbmc.LOGNOTICE) break if idle > xbmc.getGlobalIdleTime(): tools.writeLog('User activty detected (was %s idle)' % (time.strftime('%H:%M:%S', time.gmtime(idle)))) break idle = xbmc.getGlobalIdleTime() # check outdated recordings nodedata = self.readStatusXML('title') for item in nodedata: if not item in self.__recTitles: self.__recTitles.append(item) tools.writeLog('Recording of "%s" is active' % (item)) for item in self.__recTitles: if not item in nodedata: self.__recTitles.remove(item) tools.writeLog('Recording of "%s" has finished' % (item)) if mode is None: self.deliverMail( __LS__(30047) % (release.hostname, item)) if not _flags: if mode == 'poweroff': if self.countDown(counter=self.__counter): break _flags = self.setWakeup() else: tools.writeLog('Service was running w/o user activity', level=xbmc.LOGNOTICE) _flags = self.setWakeup() # RESUME POINT #2 tools.writeLog('Resume point #2 passed', xbmc.LOGNOTICE) mode = None idle = 0 _flags = self.getSysState(verbose=True) & (isREC | isEPG | isPRG | isNET)
def calcNextSched(self): __WakeUpUTRec = 0 __WakeUpUTEpg = 0 __WakeEPG = 0 __curTime = datetime.datetime.now() __msgid = 30018 _flags = isUSR nodedata = self.readStatusXML('next') if nodedata: self.__wakeUp = (__curTime + datetime.timedelta( minutes=int(nodedata[0]) - self.__prerun)).replace(second=0) __WakeUpUTRec = int(time.mktime(self.__wakeUp.timetuple())) _flags |= isRES else: tools.writeLog('No recordings to schedule') if self.__epg_interval > 0: __dayDelta = self.__epg_interval if int(__curTime.strftime('%j')) % __dayDelta == 0: __dayDelta = 0 __WakeEPG = ( __curTime + datetime.timedelta(days=__dayDelta) - datetime.timedelta(days=int(__curTime.strftime('%j')) % self.__epg_interval)).replace( hour=self.__epg_time, minute=0, second=0) if __curTime > __WakeEPG: __WakeEPG = __WakeEPG + datetime.timedelta( days=self.__epg_interval) __WakeUpUTEpg = int(time.mktime(__WakeEPG.timetuple())) _flags |= isRES else: tools.writeLog('No EPG to schedule') if _flags: if __WakeUpUTRec <= __WakeUpUTEpg: if __WakeUpUTRec > 0: self.__wakeUpUT = __WakeUpUTRec elif __WakeUpUTEpg > 0: self.__wakeUpUT = __WakeUpUTEpg self.__wakeUp = __WakeEPG __msgid = 30019 else: if __WakeUpUTEpg > 0: self.__wakeUpUT = __WakeUpUTEpg self.__wakeUp = __WakeEPG __msgid = 30019 elif __WakeUpUTRec > 0: self.__wakeUpUT = __WakeUpUTRec # show notifications if __msgid == 30018: tools.writeLog('Wakeup for recording at %s' % (self.__wakeUp.strftime('%d.%m.%y %H:%M'))) _flags |= isREC if self.__nextsched: tools.Notify().notify( __LS__(30017), __LS__(__msgid) % (self.__wakeUp.strftime('%d.%m.%Y %H:%M'))) elif __msgid == 30019: tools.writeLog('Wakeup for EPG update at %s' % (self.__wakeUp.strftime('%d.%m.%y %H:%M'))) _flags |= isEPG if self.__nextsched: tools.Notify().notify( __LS__(30017), __LS__(__msgid) % (self.__wakeUp.strftime('%d.%m.%Y %H:%M'))) else: if self.__nextsched: tools.Notify().notify(__LS__(30010), __LS__(30014)) xbmc.sleep(6000) return _flags
def start(self, mode=None): tools.writeLog('Starting with id:%s@mode:%s' % (self.rndProcNum, mode)) # reset RTC #os.system('%s%s %s %s' % (self.__sudo, SHUTDOWN_CMD, 0, 0)) #tools.writeLog('Reset RTC') if mode == 'CHECKMAILSETTINGS': if self.deliverMail(__LS__(30065) % (release.hostname)): tools.dialogOK(__LS__(30066), __LS__(30068) % (self.__smtpto)) else: tools.dialogOK(__LS__(30067), __LS__(30069) % (self.__smtpto)) return elif mode == 'POWEROFF': tools.Notify().notify(__LS__(30010), __LS__(30013)) tools.writeLog('Poweroff command received', level=xbmc.LOGINFO) # Notify service loop of power off event self.setPowerOffEvent() return elif not mode == None: tools.writeLog('Unknown parameter %s' % (mode), level=xbmc.LOGFATAL) return ### START SERVICE LOOP ### tools.writeLog('Starting service', level=xbmc.LOGINFO) idle_timer = 0 wake_up_last = 0 resume_last = 0 resumed = False first_start = True power_off = False mon = xbmc.Monitor() uit = UserIdleThread() uit.start() while (1): if resumed or first_start: # Get updated system state (and store new status) self.updateSysState(verbose=True) # Check if we resumed automatically if self.__flags & (isREC | isEPG | isPRG | isNET): self.enableAutoMode() tools.writeLog('Wakeup in automode', level=xbmc.LOGINFO) if ( self.__flags & isEPG ) and self.__epg_grab_ext and os.path.isfile(EXTGRABBER): tools.writeLog( 'Starting script for grabbing external EPG') # # ToDo: implement startup of external script (epg grabbing) # _epgpath = self.__epg_path if self.__epg_store and _epgpath == '': _epgpath = '/dev/null' _start = datetime.datetime.now() try: _comm = subprocess.Popen( '%s %s %s' % (EXTGRABBER, _epgpath, self.__epg_socket), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, universal_newlines=True) while _comm.poll() is None: tools.writeLog(_comm.stdout.readline().decode( 'utf-8', 'ignore').strip()) tools.writeLog( 'external EPG grabber script took %s seconds' % ((datetime.datetime.now() - _start).seconds)) except Exception: tools.writeLog( 'Could not start external EPG grabber script', level=xbmc.LOGERROR) if resumed and os.path.isfile(RESUME_SCRIPT): _user_idle = not uit.IsUserActive(False) xbmc.executebuiltin( "RunScript(%s, %s, %s)" % (RESUME_SCRIPT, int( self.__auto_mode_set), int(_user_idle))) # Reset flags ############# first_start = False resumed = False wake_up_last = 0 # Force update of wakeup time, just in case # Update wake time, in case a new value is set # NOTE: We keep doing this (instead of only on powerdown), # just in case Kodi crashes/freezes if not self.__wakeUpUT == wake_up_last: wake_up_last = self.__wakeUpUT self.setWakeup(shutdown=False) # Check outdated recordings self.checkOutdatedRecordings(mode) # 1 Minute wait loop wait_count = 0 SLOW_CYCLE = 60 while wait_count < SLOW_CYCLE: wait_count += 1 if mon.waitForAbort(1): tools.writeLog('Service with id %s aborted' % (self.rndProcNum), level=xbmc.LOGINFO) return # User activity detected? if uit.IsUserActive(): idle_timer = 0 if self.__auto_mode_set: tools.writeLog( 'User interaction detected, disabling automode') self.disableAutoMode() # Update countdown dialog (if any) if not self.__flags & (isREC | isEPG | isPRG | isNET): if self.updateAutoModeDialog(): power_off = True # Countdown reached 0 break # Break loop so we can power off # Check if power off event was set if self.getPowerOffEvent(): tools.writeLog('Poweroff request detected by service') if int(time.time()) < resume_last + RESUME_MARGIN: tools.writeLog( 'Not enough time passed since last power up, skipping poweroff' ) else: if xbmc.getCondVisibility( 'Player.Playing') or xbmc.getCondVisibility( 'Player.Paused'): tools.writeLog('Stopping Player') xbmc.Player().stop() # Make sure system state is updated self.updateSysState(verbose=True) if (self.__flags & isREC): tools.Notify().notify( __LS__(30015), __LS__(30020), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'Recording in progress' tools.writeLog( 'Recording in progress: Postponing poweroff with automode', level=xbmc.LOGINFO) self.enableAutoMode() elif (self.__flags & isEPG): tools.Notify().notify( __LS__(30015), __LS__(30021), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'EPG-Update' tools.writeLog( 'EPG-update in progress: Postponing poweroff with automode', level=xbmc.LOGINFO) self.enableAutoMode() elif (self.__flags & isPRG): tools.Notify().notify( __LS__(30015), __LS__(30022), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'Postprocessing' tools.writeLog( 'Postprocessing in progress: Postponing poweroff with automode', level=xbmc.LOGINFO) self.enableAutoMode() elif (self.__flags & isNET): tools.Notify().notify( __LS__(30015), __LS__(30023), icon=xbmcgui.NOTIFICATION_WARNING ) # Notify 'Network active' tools.writeLog( 'Network active: Postponing poweroff with automode', level=xbmc.LOGINFO) self.enableAutoMode() else: power_off = True break # Break wait loop so we can perform power off # Wait loop ends if not power_off: # Get updated system state (and store new status) self.updateSysState(verbose=True) # When flags are set, make sure we don't automatically shutdown # and prevent the screensaver from starting if self.__flags & (isREC | isEPG | isPRG | isNET): xbmc.executebuiltin('InhibitIdleShutdown(true)') #self.disableScreensaver() # Doesn't work as intended # (Re)set idle timer idle_timer = 0 else: xbmc.executebuiltin('InhibitIdleShutdown(false)') # Auto shutdown handling if xbmc.getCondVisibility( 'Player.Playing') or self.__auto_mode_set: tools.writeLog( 'Player is playing or automode set, resetting idle timer' ) idle_timer = 0 else: idle_timer += 1 tools.writeLog('No user activity for %s minutes' % idle_timer) if idle_timer > IDLE_SHUTDOWN: tools.writeLog( 'No user activity detected for %s minutes. Powering down' % idle_timer) idle_timer = 0 # In case powerdown is aborted by user self.enableAutoMode( ) # Enable auto-mode (also for countdown dialog) if power_off: # Set power off event. This is in case suspend in the shutdown script fails, # as a fallback it will then reboot and immediately power off self.setPowerOffEvent() # Always disable automode (+close dialog) self.disableAutoMode() # Set RTC wakeup + suspend system: # NOTE: setWakeup() will block when the system suspends # and continue as soon as it resumes again if self.setWakeup(): resumed = True # Notify next iteration we have resumed from suspend uit.IsUserActive() # Reset user active event resume_last = int( time.time()) # Save resume time for later use self.getPowerOffEvent() # Reset power off event tools.writeLog('Resume point passed', level=xbmc.LOGINFO) power_off = False # Reset power off flag ### END MAIN LOOP ### uit.stop() # Stop user idle thread
def main(mode=None, handle=None, content=None): now = datetime.utcnow().isoformat() + 'Z' timemax = (datetime.utcnow() + relativedelta.relativedelta( months=tools.getAddonSetting('timemax', sType=tools.NUM)) ).isoformat() + 'Z' if mode == 'require_oauth_key': Calendar().require_credentials(Calendar().CLIENT_CREDENTIALS, require_from_setup=True) tools.writeLog('new credentials successfull received and stored', xbmc.LOGDEBUG) tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'reenter_oauth_key': Calendar().require_credentials(Calendar().CLIENT_CREDENTIALS, require_from_setup=True, reenter='kb') tools.writeLog('new credentials successfull received and stored', xbmc.LOGDEBUG) tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'load_oauth_key': Calendar().require_credentials(Calendar().CLIENT_CREDENTIALS, require_from_setup=True, reenter='file') tools.writeLog('new credentials successfull received and stored', xbmc.LOGDEBUG) tools.Notify().notify(__LS__(30010), __LS__(30073)) elif mode == 'check_mailsettings': mail = SMTPMail() mail.checkproperties() mail.sendmail( __LS__(30074) % (__LS__(30010), tools.release().hostname), __LS__(30075)) tools.writeLog('mail delivered', xbmc.LOGNOTICE) tools.dialogOK(__LS__(30010), __LS__(30076) % (mail.smtp_client['recipient'])) elif mode == 'abort_reminders': tools.writeLog('abort notification service by setup', xbmc.LOGNOTICE) xbmcgui.Window(10000).setProperty('reminders', '0') elif mode == 'set_calendars': set_localsetting('calendars') googlecal = Calendar() googlecal.get_events( TEMP_STORAGE_EVENTS, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('calendars')) elif mode == 'set_notifications': set_localsetting('notifications') googlecal = Calendar() googlecal.get_events( TEMP_STORAGE_NOTIFICATIONS, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('notifications')) elif mode == 'getcontent': googlecal = Calendar() googlecal.build_sheet( handle, TEMP_STORAGE_EVENTS, content, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('calendars')) elif mode == 'prev': calc_boundaries(-1) elif mode == 'next': calc_boundaries(1) # this is the real controller bootstrap elif mode == 'gui': try: Popup = xbmcgui.WindowXMLDialog(__xml__, __path__) Popup.doModal() del Popup except RuntimeError, e: raise FileNotFoundException('%s: %s' % (e.message, __xml__))
timemax = (datetime.utcnow() + relativedelta.relativedelta( months=t.getAddonSetting('timemax', sType=t.NUM)) ).isoformat() + 'Z' events = googlecal.get_events( TEMP_STORAGE_NOTIFICATIONS, now, timemax, maxResult=30, calendars=googlecal.get_calendarIdFromSetup('notifications')) _ev_count = 1 for event in events: _ev = googlecal.prepare_events(event) t.Notify().notify( '%s %s %s' % (_ev['timestamps'], __LS__(30145), _ev['shortdate']), _ev['summary'], icon=__icon__) _ev_count += 1 xbmc.Monitor().waitForAbort(7) if _ev_count > t.getAddonSetting( 'numreminders', sType=t.NUM) or xbmcgui.Window( 10000).getProperty('reminders') != '1': break if events and _cycle > 0: DialogKT = DKT.DialogKaiToast.createDialogKaiToast() DialogKT.label_1 = __LS__(30019) DialogKT.label_2 = __LS__(30018) DialogKT.icon = __icon2__ DialogKT.show()