class EmptySlot(): MOUNT = 0 UNMOUNT = 1 def __init__(self, Contents, callback): self.callback = callback self.container = Console() (self.firstslot, self.numberofslots, self.mtdboot) = SystemInfo["canMultiBoot"] self.slot = Contents if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') if SystemInfo["HasSDmmc"]: # allow for mmc & SDcard in passed slot number, so SDcard slot -1 self.slot -= 1 self.part = "%s%s" %(self.mtdboot, str(self.slot * 2 + self.firstslot)) if SystemInfo["HasSDmmc"] and self.slot == 0: # this is the mmc slot, so pick up from MtdRoot self.part = getMachineMtdRoot() self.phase = self.MOUNT self.run() def run(self): self.container.ePopen('mount /dev/%s /tmp/testmount' %self.part if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): os.rename('/tmp/testmount/usr/bin/enigma2', '/tmp/testmount/usr/bin/enigmax.bin') self.phase = self.UNMOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback()
def leaveStandby(self): printDEBUG( "leaveStandby" , "CEC Box status: Left Standby, CEC_ActiveHDMI: %s" % (self.CEC_ActiveHDMI) ) if config.plugins.CEC.MiniEnable.value == True: printDEBUG( "standbyCounterChanged" , "MiniMode enabled" ) from Components.Console import Console myConsole = Console() with open("/proc/sys/vm/drop_caches", "w") as f: f.write("1\n") myConsole.ePopen("/etc/cron/moderatestandby_off/40cec") return if config.plugins.CEC.Enable.value == True: if self.standby==0: self.standby = 1 printDEBUG( "leaveStandby" , "CEC Box status: Not Standby!, CEC_Delay: %i, CEC_Counter: %i" % (self.CEC_Delay, self.CEC_Counter) ) if not self.timelock: self.licz = self.CEC_Counter self.timelock=True if self.CEC_ActiveHDMI == "Auto": self.timer2.callback.append(self.CEC_OneTouchPlay) else: self.timer2.callback.append(self.CEC_ImageViewOn) self.timer2.start(self.CEC_Delay,1) return
class CamdKill(resource.Resource): def __init__(self, input): self.Console = Console() self.container = eConsoleAppContainer() self.container.appClosed.append(self.finished) self.actcam = config.NFRSoftcam.actcam.value self.input = input def render_GET(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') req.setHeader('charset', 'UTF-8') html = header_string for info in infoList: if info == self.input: cmd = "killall -15 " + self.input self.Console.ePopen(cmd) config.NFRSoftcam.actcam.value = "" config.NFRSoftcam.actcam.save() configfile.save() html += '<center>%s erfolgreich beendet! <a href="SoftcamControl" target="_self"><input type="submit" value="Zurück"></a></center>' % self.input continue html += '<p></p>' return html def finished(self, retval): print 'finished', retval
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.phase = self.MOUNT self.run() else: callback({}) def run(self): self.container.ePopen('mount /dev/mmcblk0p%s /tmp/testmount' % str(self.slot * 2 + 1) if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): self.imagelist[self.slot] = { 'imagename': open("/tmp/testmount/etc/issue").readlines()[-2].capitalize().strip()[:-6] } self.phase = self.UNMOUNT self.run() elif self.slot < 4: self.slot += 1 self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
def standbyCounterChanged(self, configElement): printDEBUG( "standbyCounterChanged" , "CEC Box status: Go to Standby" ) from Screens.Standby import inStandby inStandby.onClose.append(self.leaveStandby) if config.plugins.CEC.MiniEnable.value == True: printDEBUG( "standbyCounterChanged" , "MiniMode enabled" ) from Components.Console import Console myConsole = Console() with open("/proc/sys/vm/drop_caches", "w") as f: f.write("1\n") myConsole.ePopen("/etc/cron/moderatestandby_on/20cec") return if config.plugins.CEC.Enable.value == True: if self.standby==1: self.standby = 0 printDEBUG( "standbyCounterChanged" , "CEC Box status: Standby!, CEC_Delay: %i, CEC_Counter: %i" % (self.CEC_Delay, self.CEC_Counter) ) if not self.timelock: self.licz = self.CEC_Counter self.timelock=True if self.CEC_ActiveHDMI == "Auto": self.timer2.callback.append(self.CEC_SystemStandby) else: self.timer2.callback.append(self.CEC_Standby) self.timer2.start(self.CEC_Delay,1) return
class StartCamOnStart: def __init__(self): self.Console = Console() self.Timer = eTimer() self.Timer.timeout.get().append(self.__camnotrun) def start(self): self.Timer.start(2000, False) def __camnotrun(self): self.Timer.stop() self.Console.ePopen("ps", self.checkprocess) def checkprocess(self, result, retval, extra_args): processes = result.lower() camlist = ["oscam", "mgcamd", "wicard", "camd3", "mcas", "cccam", "gbox", "mpcs", "mbox", "newcs", "vizcam", "rucam"] camlist.insert(0, config.plugins.AltSoftcam.actcam.value) for cam in camlist: if cam in processes: print "[Alternative SoftCam Manager] ERROR in start cam! In processes find:", cam break else: cmd = getcamcmd(config.plugins.AltSoftcam.actcam.value) print "[Alternative SoftCam Manager]", cmd Console().ePopen(cmd)
class NTPSyncPoller: """Automatically Poll NTP""" def __init__(self): # Init Timer self.timer = eTimer() self.Console = Console() def start(self): if self.ntp_sync not in self.timer.callback: self.timer.callback.append(self.ntp_sync) self.timer.startLongTimer(0) def stop(self): if self.version_check in self.timer.callback: self.timer.callback.remove(self.ntp_sync) self.timer.stop() def ntp_sync(self): if config.misc.SyncTimeUsing.getValue() == "1": print '[NTP]: Updating' self.Console.ePopen('/usr/bin/ntpdate -s -u pool.ntp.org', self.update_schedule) def update_schedule(self, result = None, retval = None, extra_args = None): nowTime = time() print '[NTP]: setting E2 time:',nowTime setRTCtime(nowTime) eDVBLocalTimeHandler.getInstance().setUseDVBTime(False) self.timer.startLongTimer(int(config.misc.useNTPminutes.getValue()) * 60)
def grabFrame(self): path = self.session.nav.getCurrentlyPlayingServiceReference().getPath() from Components.Console import Console grabConsole = Console() cmd = 'grab -vblpr%d "%s"' % (180, path.rsplit('.',1)[0] + ".png") grabConsole.ePopen(cmd) self.playpauseService()
class NTPSyncPoller: """Automatically Poll NTP""" def __init__(self): self.timer = eTimer() self.Console = Console() def start(self): if not self.timer.callback: self.timer.callback.append(self.NTPStart) self.timer.startLongTimer(0) def stop(self): if self.timer.callback: self.timer.callback.remove(self.NTPStart) self.timer.stop() def NTPStart(self): if config.plugins.SystemTime.choiceSystemTime.value == "1": cmd = '/usr/sbin/ntpdate -s -u %s' % config.plugins.SystemTime.ip.value self.Console.ePopen(cmd, self.update_schedule) self.timer.startLongTimer(int(config.plugins.SystemTime.useNTPminutes.value) * 60) def update_schedule(self, result = None, retval = None, extra_args = None): if eDVBLocalTimeHandler.getInstance().ready(): nowTime = time() if nowTime > 1388534400: setRTCtime(nowTime) if config.plugins.SystemTime.choiceSystemTime.value == "0": eDVBLocalTimeHandler.getInstance().setUseDVBTime(True) else: eDVBLocalTimeHandler.getInstance().setUseDVBTime(False) try: eEPGCache.getInstance().timeUpdated() except: pass
class SystemMemoryInfo(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Memory Information")) self.skinName = ["SystemMemoryInfo", "About"] self["lab1"] = StaticText(_("INFO RAM / FLASH")) #self["lab2"] = StaticText(_("Developer:\t Javilonas (Javier Sayago)")) self["AboutScrollLabel"] = ScrollLabel() self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, }) out_lines = file("/proc/meminfo").readlines() self.AboutText = _("RAM") + '\n\n' RamTotal = "-" RamFree = "-" for lidx in range(len(out_lines) - 1): tstLine = out_lines[lidx].split() if "MemTotal:" in tstLine: MemTotal = out_lines[lidx].split() self.AboutText += _("Total Memory:") + "\t" + MemTotal[1] + "\n" if "MemFree:" in tstLine: MemFree = out_lines[lidx].split() self.AboutText += _("Free Memory:") + "\t" + MemFree[1] + "\n" self.AboutText += _("Memory Usage:\t%s") % str(about.getRAMusageString()) + "\n" if "Buffers:" in tstLine: Buffers = out_lines[lidx].split() self.AboutText += _("Buffers:") + "\t" + Buffers[1] + "\n" if "Cached:" in tstLine: Cached = out_lines[lidx].split() self.AboutText += _("Cached:") + "\t" + Cached[1] + "\n" if "SwapTotal:" in tstLine: SwapTotal = out_lines[lidx].split() self.AboutText += _("Total Swap:") + "\t" + SwapTotal[1] + "\n" if "SwapFree:" in tstLine: SwapFree = out_lines[lidx].split() self.AboutText += _("Free Swap:") + "\t" + SwapFree[1] + "\n\n" self["actions"].setEnabled(False) self.Console = Console() self.Console.ePopen("df -mh / | grep -v '^Filesystem'", self.Stage1Complete) def Stage1Complete(self, result, retval, extra_args=None): flash = str(result).replace('\n', '') flash = flash.split() RamTotal = flash[1] RamFree = flash[3] self.AboutText += _("FLASH") + '\n\n' self.AboutText += _("Total:") + "\t" + RamTotal + "\n" self.AboutText += _("Free:") + "\t" + RamFree + "\n\n" self["AboutScrollLabel"].setText(self.AboutText) self["actions"].setEnabled(True) def createSummary(self): return AboutSummary
class SystemMemoryInfo(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Memory Information")) self.skinName = ["SystemMemoryInfo", "About"] self["lab1"] = StaticText(_("Virtuosso Image Xtreme")) self["lab2"] = StaticText(_("By Team ViX")) self["lab3"] = StaticText(_("Support at") + " www.world-of-satellite.com") self["AboutScrollLabel"] = ScrollLabel() self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, }) out_lines = file("/proc/meminfo").readlines() self.AboutText = _("RAM") + '\n\n' RamTotal = "-" RamFree = "-" for lidx in range(len(out_lines) - 1): tstLine = out_lines[lidx].split() if "MemTotal:" in tstLine: MemTotal = out_lines[lidx].split() self.AboutText += _("Total memory:") + "\t" + MemTotal[1] + "\n" if "MemFree:" in tstLine: MemFree = out_lines[lidx].split() self.AboutText += _("Free memory:") + "\t" + MemFree[1] + "\n" if "Buffers:" in tstLine: Buffers = out_lines[lidx].split() self.AboutText += _("Buffers:") + "\t" + Buffers[1] + "\n" if "Cached:" in tstLine: Cached = out_lines[lidx].split() self.AboutText += _("Cached:") + "\t" + Cached[1] + "\n" if "SwapTotal:" in tstLine: SwapTotal = out_lines[lidx].split() self.AboutText += _("Total swap:") + "\t" + SwapTotal[1] + "\n" if "SwapFree:" in tstLine: SwapFree = out_lines[lidx].split() self.AboutText += _("Free swap:") + "\t" + SwapFree[1] + "\n\n" self["actions"].setEnabled(False) self.Console = Console() self.Console.ePopen("df -mh / | grep -v '^Filesystem'", self.Stage1Complete) def Stage1Complete(self, result, retval, extra_args=None): flash = str(result).replace('\n', '') flash = flash.split() RamTotal = flash[1] RamFree = flash[3] self.AboutText += _("FLASH") + '\n\n' self.AboutText += _("Total:") + "\t" + RamTotal + "\n" self.AboutText += _("Free:") + "\t" + RamFree + "\n\n" self["AboutScrollLabel"].setText(self.AboutText) self["actions"].setEnabled(True) def createSummary(self): return AboutSummary
class UserInterfacePositionerWizard(WizardLanguage, Rc): def __init__(self, session, interface = None): self.xmlfile = resolveFilename(SCOPE_SKIN, 'userinterfacepositionerwizard.xml') WizardLanguage.__init__(self, session, showSteps=False, showStepSlider=False) Rc.__init__(self) self.skinName = 'StartWizard' self.session = session Screen.setTitle(self, _('Welcome...')) self.Console = Console() self['wizard'] = Pixmap() self['HelpWindow'] = Pixmap() self['HelpWindow'].hide() self['VKeyIcon'] = Boolean(False) self.NextStep = None self.Text = None self.onLayoutFinish.append(self.layoutFinished) self.onClose.append(self.__onClose) def layoutFinished(self): self.Console.ePopen('/usr/bin/showiframe /usr/share/enigma2/hd-testcard.mvi') def exitWizardQuestion(self, ret = False): if ret: self.markDone() self.close() def markDone(self): pass def back(self): WizardLanguage.back(self) def __onClose(self): self.Console.ePopen('/usr/bin/showiframe /usr/share/backdrop.mvi')
class SystemMemoryInfo(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Memory Information")) #self.skinName = ["SystemMemoryInfo", "About"] self.skinName = ["About"] self["AboutScrollLabel"] = ScrollLabel() self["actions"] = ActionMap(["SetupActions", "ColorActions", "TimerEditActions"], { "cancel": self.close, "ok": self.close, }) out_lines = file("/proc/meminfo").readlines() self.AboutText = _("RAM") + '\n\n' RamTotal = "-" RamFree = "-" for lidx in range(len(out_lines)-1): tstLine = out_lines[lidx].split() if "MemTotal:" in tstLine: MemTotal = out_lines[lidx].split() self.AboutText += _("Total Memory:") + "\t" + MemTotal[1] + "\n" if "MemFree:" in tstLine: MemFree = out_lines[lidx].split() self.AboutText += _("Free Memory:") + "\t" + MemFree[1] + "\n" if "Buffers:" in tstLine: Buffers = out_lines[lidx].split() self.AboutText += _("Buffers:") + "\t" + Buffers[1] + "\n" if "Cached:" in tstLine: Cached = out_lines[lidx].split() self.AboutText += _("Cached:") + "\t" + Cached[1] + "\n" if "SwapTotal:" in tstLine: SwapTotal = out_lines[lidx].split() self.AboutText += _("Total Swap:") + "\t" + SwapTotal[1] + "\n" if "SwapFree:" in tstLine: SwapFree = out_lines[lidx].split() self.AboutText += _("Free Swap:") + "\t" + SwapFree[1] + "\n\n" self.Console = Console() self.Console.ePopen("df -mh / | grep -v '^Filesystem'", self.Stage1Complete) def Stage1Complete(self,result, retval, extra_args = None): flash = str(result).replace('\n','') flash = flash.split() RamTotal=flash[1] RamFree=flash[3] self.AboutText += _("FLASH") + '\n\n' self.AboutText += _("Total:") + "\t" + RamTotal + "\n" self.AboutText += _("Free:") + "\t" + RamFree + "\n\n" self["AboutScrollLabel"].setText(self.AboutText) self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, })
def NTPserverChanged(configelement): f = open("/etc/default/ntpdate", "w") f.write('NTPSERVERS="' + configelement.value + '"\n') f.close() os.chmod("/etc/default/ntpdate", 0755) from Components.Console import Console Console = Console() Console.ePopen('/usr/bin/ntpdate-sync')
def dorun(self, ret): if ret == True: tytul = config.GOShddmanager.partitions.value partycja = tytul.split(" ")[0] folder = config.GOShddmanager.folders.value from Components.Console import Console myConsole = Console() myConsole.ePopen("mount /dev/%s %s" % (partycja, folder), self.middlerun())
class UpdateNotification: def setSession(self, session, plugin_path): self.session = session self.plugin_path = plugin_path def show_NewsCenter(self, res = None): if config.usage.check_for_updates.value > 0: intervall = config.usage.check_for_updates.value * 1000 * 3600 self.update_timer.start(intervall, True) if res: f = open(packagetmpfile, 'w+') f.write(self.upgradable_packages) f.close self.session.open(AllNews, self.plugin_path) def check_updates(self): self.Console = Console() cmd = 'opkg update' self.Console.ePopen(cmd, self.opkg_update_finished) def opkg_update_finished(self, result, retval, extra_args = None): if not self.Console: self.Console = Console() cmd = 'opkg list-upgradable' self.Console.ePopen(cmd, self.opkg_upgrade_finished) def opkg_upgrade_finished(self, result, retval, extra_args = None): is_update = False if len(result): check_result = result.split('\n', 10) if len(check_result): for line in check_result: line = line.split(' - ') if len(line) >= 3: is_update = True break if is_update: self.upgradable_packages = result config.usage.update_available.value = True if config.usage.show_notification_for_updates.value: message = _('There are updates available.\nDo you want to open Software Update menu ?') AddNotificationWithCallback(boundFunction(self.show_NewsCenter), MessageBox, message, timeout=0) else: self.show_NewsCenter(res=None) else: config.usage.update_available.value = False if config.usage.check_for_updates.value > 0: intervall = config.usage.check_for_updates.value * 1000 * 3600 self.update_timer.start(intervall, True) def init_timer(self): self.update_timer = eTimer() self.update_timer.callback.append(self.check_updates) self.update_timer.start(60000, True)
def __init__(self): self.automounts = {} self.restartConsole = Console() self.MountConsole = Console() self.removeConsole = Console() self.activeMountsCounter = 0 self.callback = None self.timer = eTimer() self.timer.callback.append(self.mountTimeout) self.getAutoMountPoints()
def grabCallback(choice = None): if choice is None: self.playpauseService() return x_size = choice[1] path = service.getPath() grabConsole = Console() cmd = 'grab -vblpr%d "%s"' % (x_size, path.rsplit('.',1)[0] + strftime("_%Y%m%d%H%M%S", gmtime()) + ".png") grabConsole.ePopen(cmd) self.playpauseService()
def NTPserverChanged(configelement): if configelement.value == "pool.ntp.org": return f = open("/etc/default/ntpdate", "w") f.write('NTPSERVERS="' + configelement.value + '"\n') f.close() os.chmod("/etc/default/ntpdate", 0755) from Components.Console import Console Console = Console() Console.ePopen('/usr/bin/ntpdate ' + config.misc.NTPserver.value)
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def collectDataForInterface(self, iface): w = Wireless(iface) wsconfig = { } simpleConfigs = ( ("essid", w.getEssid, "off"), ("frequency", w.getFrequency, ""), ("accesspoint", w.getAPaddr, "Not-Associated"), ("bitrate", w.getBitrate, "0"), ("encryption", w.getEncryption, "off"), ) for name, func, default in simpleConfigs: try: wsconfig[name] = func() except: wsconfig[name] = default try: wsconfig["quality"] = str(Iwstats("wlan0").qual.quality) + "/" + str(w.getQualityMax().quality) except: wsconfig["quality"] = "" try: wsconfig["signal"] = str(w.getQualityAvg().siglevel-128) + " dBm" except: wsconfig["signal"] = "" return wsconfig def getDataForInterface(self, iface, callback = None): wsconfig = self.collectDataForInterface(iface) self.wlaniface[iface] = wsconfig self.backupwlaniface = self.wlaniface if callback is not None: callback(True, self.wlaniface) return self.wlaniface def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.iface in self.wlaniface: if attribute in self.wlaniface[self.iface]: return self.wlaniface[self.iface][attribute] return None
def NTPserverChanged(configelement): if config.misc.NTPserver.getValue() == "pool.ntp.org": return print "[NTPDATE] save /etc/default/ntpdate" f = open("/etc/default/ntpdate", "w") f.write('NTPSERVERS="' + config.misc.NTPserver.getValue() + '"') f.close() os.chmod("/etc/default/ntpdate", 0755) from Components.Console import Console Console = Console() Console.ePopen('/usr/bin/ntpdate ' + config.misc.NTPserver.getValue())
def useSyncUsingChanged(configElement): if config.misc.SyncTimeUsing.getValue() == "0": print "[Time By]: Transponder" value = True enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(value) else: print "[Time By]: NTP" value = False enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(value) from Components.Console import Console Console = Console() Console.ePopen('/usr/bin/ntpdate ' + config.misc.NTPserver.getValue())
class SystemMemoryInfo(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _('Memory Information')) self.skinName = ['SystemMemoryInfo', 'About'] self['lab1'] = StaticText(_('ItalySat')) self['lab2'] = StaticText(_('By ItalySat Team')) self['AboutScrollLabel'] = ScrollLabel() self['actions'] = ActionMap(['SetupActions', 'ColorActions'], {'cancel': self.close, 'ok': self.close}) out_lines = file('/proc/meminfo').readlines() self.AboutText = _('RAM') + '\n\n' RamTotal = '-' RamFree = '-' for lidx in range(len(out_lines) - 1): tstLine = out_lines[lidx].split() if 'MemTotal:' in tstLine: MemTotal = out_lines[lidx].split() self.AboutText += _('Total Memory:') + '\t' + MemTotal[1] + '\n' if 'MemFree:' in tstLine: MemFree = out_lines[lidx].split() self.AboutText += _('Free Memory:') + '\t' + MemFree[1] + '\n' if 'Buffers:' in tstLine: Buffers = out_lines[lidx].split() self.AboutText += _('Buffers:') + '\t' + Buffers[1] + '\n' if 'Cached:' in tstLine: Cached = out_lines[lidx].split() self.AboutText += _('Cached:') + '\t' + Cached[1] + '\n' if 'SwapTotal:' in tstLine: SwapTotal = out_lines[lidx].split() self.AboutText += _('Total Swap:') + '\t' + SwapTotal[1] + '\n' if 'SwapFree:' in tstLine: SwapFree = out_lines[lidx].split() self.AboutText += _('Free Swap:') + '\t' + SwapFree[1] + '\n\n' self['actions'].setEnabled(False) self.Console = Console() self.Console.ePopen("df -mh / | grep -v '^Filesystem'", self.Stage1Complete) def Stage1Complete(self, result, retval, extra_args = None): flash = str(result).replace('\n', '') flash = flash.split() RamTotal = flash[1] RamFree = flash[3] self.AboutText += _('FLASH') + '\n\n' self.AboutText += _('Total:') + '\t' + RamTotal + '\n' self.AboutText += _('Free:') + '\t' + RamFree + '\n\n' self['AboutScrollLabel'].setText(self.AboutText) self['actions'].setEnabled(True) def createSummary(self): return AboutSummary
class UserInterfacePositionerWizard(WizardLanguage, Rc): def __init__(self, session, interface = None): self.xmlfile = resolveFilename(SCOPE_SKIN, "userinterfacepositionerwizard.xml") WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False) Rc.__init__(self) self.skinName = "StartWizard" self.session = session self.Console = Console() self["wizard"] = Pixmap() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self.NextStep = None self.Text = None self.onClose.append(self.__onClose) if self.welcomeWarning not in self.onShow: self.onShow.append(self.welcomeWarning) def welcomeWarning(self): if self.welcomeWarning in self.onShow: self.onShow.remove(self.welcomeWarning) popup = self.session.openWithCallback(self.welcomeAction, MessageBox, _("Welcome to OpenBlackHole!\n\n" "NOTE: This section of the wizard is intended for people who cannot disable overscan " "on their television / display. Please first try to disable overscan before using this feature.\n\n" "USAGE: If you continue adjust the screen size and position settings so that the shaded user interface layer *just* " "covers the test pattern in the background.\n\n" "Select Yes to change these settings or No to skip this step."), type=MessageBox.TYPE_YESNO, timeout=-1, default=False) popup.setTitle("Start Wizard - Screen Alignment") def welcomeAction(self, answer): if answer: self.Console.ePopen('/usr/bin/showiframe /usr/share/enigma2/hd-testcard.mvi') else: self.close() def exitWizardQuestion(self, ret = False): if ret: self.markDone() self.close() def markDone(self): pass def back(self): WizardLanguage.back(self) def __onClose(self): self.Console.ePopen('/usr/bin/showiframe /usr/share/backdrop.mvi')
class CamdStart(resource.Resource): def __init__(self, input): self.Console = Console() self.camstartcmd = "" self.container = eConsoleAppContainer() self.container.appClosed.append(self.finished) self.actcam = config.NFRSoftcam.actcam.value self.input = input def render_GET(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') req.setHeader('charset', 'UTF-8') html = header_string for info in infoList: if info == self.input: self.camstartcmd = Softcam.getcamcmd(self.input) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.stopping) self.activityTimer.start(1000, False) #self.container.execute(info) html += '<center>%s erfolgreich Gestartet! <a href="SoftcamControl" target="_self"><input type="submit" value="Zurück"></a></center>' % self.input continue html += '<p></p>' return html def finished(self, retval): print 'finished', retval def stopping(self): self.activityTimer.stop() self.actcam = config.NFRSoftcam.actcam.value Softcam.stopcam(self.actcam) print "[NFR-SoftCam Manager stop] ", self.actcam cmd = "killall -15 " + self.actcam self.Console.ePopen(cmd) self.actcam = self.input if config.NFRSoftcam.actcam.value != self.actcam: config.NFRSoftcam.actcam.value = self.actcam print "[save actcam] ", self.actcam config.NFRSoftcam.actcam.save() configfile.save() #config.NFRSoftcam.actcam.save() #configfile.save() self.Console.ePopen(self.camstartcmd) print "[NFR-SoftCam Manager] ", self.camstartcmd
class PreviewCreator: def __init__(self): self.callback = None self.Console = Console() def grab(self, file): if not self.Console: self.Console = Console() self.Console.ePopen('/usr/bin/grab -v -r 250 -l -j 100 "%s"'%file, self.grabDone) def grabDone(self, result, retval, extra_args): if retval != 0: print result if self.callback: self.callback()
class Ceparted(Screen): skin = """<screen position="center,center" size="820,320" title="eParted v0.13"> <widget name="list" position="10,10" size="800,300" enableWrapAround="1" scrollbarMode="showOnDemand"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.Exit, "ok": self.Ok }, -1) self["list"] = MenuList(list=[]) self.Console = Console() global rereaddevices rereaddevices = True self.__readDev() def Ok(self): sel = self["list"].getCurrent() if sel and sel[1]: global rereaddevices rereaddevices = False self.session.openWithCallback(self.__readDev, Cpart, sel[1]) def __readDev(self): global rereaddevices if rereaddevices: self.Console.ePopen("parted -m -l", self.__FinishedConsole) def Exit(self): self.Console.killAll() self.close() #cleanexit(__name__) def __FinishedConsole(self, result, retval, extra_args=None): if retval == 0 and '\n' in result: list = [] for x in parseCmd(result): if x[0][LIST_TYPE] == LIST_TYPE_DEV: name = x[0][DEV_NAME] if len(name) == 0: name = x[0][DEV_PATH] tstr = name tstr += " (%s - %d %s %s)" % (x[0][DEV_SIZE], len(x) - 1, _("partition(s)"), x[0][DEV_PATH]) list.append((tstr, (name, x[0][DEV_PATH], x[0][DEV_SIZE]))) self["list"].setList(list)
def deactivateInterface(self,ifaces,callback = None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append("ifdown " + iface) commands.append("ip addr flush dev " + iface + " scope global") #wpa_supplicant sometimes doesn't quit properly on SIGTERM if os.path.exists('/var/run/wpa_supplicant/'+ iface): commands.append("wpa_cli -i" + iface + " terminate") if not self.deactivateInterfaceConsole: self.deactivateInterfaceConsole = Console() if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces,callback], debug=True)
def writeDefaultNetworkConfig(self,mode='lan', callback = None): fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.resetNetworkConsole = Console() self.commands = [] if mode == 'wlan': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig ath0 down") self.commands.append("ifconfig wlan0 up") if mode == 'wlan-mpci': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 up") if mode == 'lan': self.commands.append("ifconfig eth0 up") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 down") self.commands.append("/etc/init.d/avahi-daemon start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)
def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("CIHelper Setup")) self.skinName = "CIHelper" self.onChangedEntry = [ ] self['ci0'] = Label(_("CIHelper for SLOT CI0")) self['ci0active'] = Pixmap() self['ci0inactive'] = Pixmap() self['ci1'] = Label(_("CIHelper for SLOT CI1")) self['ci1active'] = Pixmap() self['ci1inactive'] = Pixmap() self['autostart'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Active"))) self['labdisabled'] = Label(_(_("Disabled"))) self['status'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['key_red'] = Label() self['key_green'] = Label(_("Start")) self['key_yellow'] = Label(_("Autostart")) self['key_blue'] = Label() self.Console = Console() self.my_cihelper_active = False self.my_cihelper_run = False self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'SetupActions'], {'ok': self.setupcihelper, 'back': self.close, 'menu': self.setupcihelper, 'green': self.CIHelperStartStop, 'yellow': self.CIHelperset}) self.onLayoutFinish.append(self.updateService)
class DevicePanelConf(Screen, ConfigListScreen): skin = """ <screen position="center,center" size="640,460" title="Choose where to mount your devices to:"> <ePixmap pixmap="skin_default/buttons/red.png" position="25,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="175,0" size="140,40" alphatest="on" /> <widget name="key_red" position="25,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="175,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="config" position="30,60" size="580,275" scrollbarMode="showOnDemand"/> <widget name="Linconn" position="30,375" size="580,20" font="Regular;18" halign="center" valign="center" backgroundColor="#9f1313"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) self.list = [] self.device_type = 'auto' self.device_uuid = "" ConfigListScreen.__init__(self, self.list) Screen.setTitle(self, _("Choose where to mount your devices to:")) self['key_green'] = Label(_("Save")) self['key_red'] = Label(_("Cancel")) self['Linconn'] = Label(_("Wait please while scanning your %s %s devices...") % (getMachineBrand(), getMachineName())) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'green': self.saveMypoints, 'ok': self.saveMypoints, 'red': self.close, 'back': self.close}) self.updateList() def updateList(self): self.list = [] list2 = [] self.Console = Console() self.Console.ePopen("sfdisk -l | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp") sleep(0.5) try: f = open('/tmp/devices.tmp', 'r') swapdevices = f.read() f.close() except: swapdevices = '' if path.exists('/tmp/devices.tmp'): remove('/tmp/devices.tmp') swapdevices = swapdevices.replace('\n','') swapdevices = swapdevices.split('/') f = open('/proc/partitions', 'r') for line in f.readlines(): parts = line.strip().split() if not parts: continue device = parts[3] if not search('sd[a-z][1-9]',device) and not search('mmcblk[0-9]p[1-9]',device): continue if getMachineBuild() in ('sf5008','et13000','et1x000','vuuno4k', 'vuultimo4k', 'vusolo4k', 'hd51', 'hd52', 'dm820', 'dm7080', 'sf4008', 'dm900', 'dm920', 'gb7252', 'dags7252', 'vs1500','h7','8100s') and search('mmcblk0p[1-9]',device): continue if getMachineBuild() in ('xc7439') and search('mmcblk1p[1-9]',device): continue if getMachineBuild() in ('u5') and search('mmcblk1p[1]',device): continue if device in list2: continue if device in swapdevices: continue self.buildMy_rec(device) list2.append(device) f.close() self['config'].list = self.list self['config'].l.setList(self.list) self['Linconn'].hide() def buildMy_rec(self, device): try: if device.find('1') > 1: device2 = device.replace('1', '') except: device2 = '' try: if device.find('2') > 1: device2 = device.replace('2', '') except: device2 = '' try: if device.find('3') > 1: device2 = device.replace('3', '') except: device2 = '' try: if device.find('4') > 1: device2 = device.replace('4', '') except: device2 = '' try: if device.find('5') > 1: device2 = device.replace('5', '') except: device2 = '' try: if device.find('6') > 1: device2 = device.replace('6', '') except: device2 = '' try: if device.find('7') > 1: device2 = device.replace('7', '') except: device2 = '' try: if device.find('8') > 1: device2 = device.replace('8', '') except: device2 = '' try: if device.find('p1') > 1: device2 = device.replace('p1', '') except: device2 = '' try: if device.find('p2') > 1: device2 = device.replace('p2', '') except: device2 = '' try: if device.find('p3') > 1: device2 = device.replace('p3', '') except: device2 = '' try: if device.find('p4') > 1: device2 = device.replace('p4', '') except: device2 = '' try: if device.find('p5') > 1: device2 = device.replace('p5', '') except: device2 = '' try: if device.find('p6') > 1: device2 = device.replace('p6', '') except: device2 = '' try: if device.find('p7') > 1: device2 = device.replace('p7', '') except: device2 = '' try: if device.find('p8') > 1: device2 = device.replace('p8', '') except: device2 = '' try: devicetype = path.realpath('/sys/block/' + device2 + '/device') except: devicetype = '' d2 = device model = '-?-' name = 'USB: ' mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/LDteam/images/icons/dev_usbstick.png' if 'sdhci' in devicetype or device2.startswith('mmcblk'): name = 'MMC: ' try: model = file('/sys/block/' + device2 + '/device/name').read() model = str(model).replace('\n', '') mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/LDteam/images/icons/dev_mmc.png' except: pass else: try: model = file('/sys/block/' + device2 + '/device/model').read() model = str(model).replace('\n', '') except: pass des = '' print "test:" if devicetype.find('/devices/pci') != -1 or devicetype.find('ahci') != -1 or devicetype.find('/devices/platform/strict-ahci') != -1: name = _("HARD DISK: ") mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/LDteam/images/icons/dev_hdd.png' name = name + model f = open('/proc/mounts', 'r') for line in f.readlines(): if line.find(device) != -1: parts = line.strip().split() d1 = parts[1] dtype = parts[2] break continue else: d1 = _("None") dtype = _("unavailable") f.close() f = open('/proc/partitions', 'r') for line in f.readlines(): if line.find(device) != -1: parts = line.strip().split() size = int(parts[2]) if (((float(size) / 1024) / 1024) / 1024) > 1: des = _("Size: ") + str(round((((float(size) / 1024) / 1024) / 1024),2)) + _("TB") elif ((size / 1024) / 1024) > 1: des = _("Size: ") + str((size / 1024) / 1024) + _("GB") else: des = _("Size: ") + str(size / 1024) + _("MB") else: try: size = file('/sys/block/' + device2 + '/' + device + '/size').read() size = str(size).replace('\n', '') size = int(size) except: size = 0 if ((((float(size) / 2) / 1024) / 1024) / 1024) > 1: des = _("Size: ") + str(round(((((float(size) / 2) / 1024) / 1024) / 1024),2)) + _("TB") elif (((size / 2) / 1024) / 1024) > 1: des = _("Size: ") + str(((size / 2) / 1024) / 1024) + _("GB") else: des = _("Size: ") + str((size / 2) / 1024) + _("MB") f.close() item = NoSave(ConfigSelection(default='/media/' + device, choices=[('/media/' + device, '/media/' + device), ('/media/hdd', '/media/hdd'), ('/media/hdd2', '/media/hdd2'), ('/media/hdd3', '/media/hdd3'), ('/media/usb', '/media/usb'), ('/media/usb2', '/media/usb2'), ('/media/usb3', '/media/usb3'), ('/media/mmc', '/media/mmc'), ('/media/mmc1', '/media/mmc1'), ('/media/mmc2', '/media/mmc2'), ('/media/mmc3', '/media/mmc3'), ('/media/cf', '/media/cf'), ('/media/cf2', '/media/cf2'), ('/media/cf3', '/media/cf3'), ('/media/uSDextra', '/media/uSDextra'), ('/media/net', '/media/net'), ('/media/upnp', '/media/upnp'), ('/media/downloads', '/media/downloads'), ('/media/music', '/media/music'), ('/media/personal', '/media/personal'), ('/media/photo', '/media/photo'), ('/media/video', '/media/video'), ('/usr', '/usr')])) if dtype == 'Linux': dtype = 'ext2' or 'ext3' or 'ext4' elif dtype == 'vfat': dtype = 'vfat' or 'fat' or 'fat16' or 'fat32' else: dtype = 'auto' item.value = d1.strip() text = name + ' ' + des + ' /dev/' + device res = getConfigListEntry(text, item, device, dtype) if des != '' and self.list.append(res): pass def saveMypoints(self): self.Console = Console() mycheck = False for x in self['config'].list: self.device = x[2] self.mountp = x[1].value self.type = x[3] self.Console.ePopen('umount ' + self.device) self.Console.ePopen("/sbin/blkid | grep " + self.device, self.add_fstab, [self.device, self.mountp] ) message = _("Updating mount locations.") ybox = self.session.openWithCallback(self.delay, MessageBox, message, type=MessageBox.TYPE_INFO, timeout=5, enable_input = False) ybox.setTitle(_("Please wait.")) def delay(self, val): message = _("Changes need a system restart to take effect.\nRestart your %s %s now?") % (getMachineBrand(), getMachineName()) ybox = self.session.openWithCallback(self.restartBox, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_("Restart %s %s.") % (getMachineBrand(), getMachineName())) def add_fstab(self, result = None, retval = None, extra_args = None): self.device = extra_args[0] self.mountp = extra_args[1] self.device_tmp = result.split(' ') if self.device_tmp[0].startswith('UUID='): self.device_uuid = self.device_tmp[0].replace('"',"") self.device_uuid = self.device_uuid.replace('\n',"") elif self.device_tmp[1].startswith('UUID='): self.device_uuid = self.device_tmp[1].replace('"',"") self.device_uuid = self.device_uuid.replace('\n',"") elif self.device_tmp[2].startswith('UUID='): self.device_uuid = self.device_tmp[2].replace('"',"") self.device_uuid = self.device_uuid.replace('\n',"") elif self.device_tmp[3].startswith('UUID='): self.device_uuid = self.device_tmp[3].replace('"',"") self.device_uuid = self.device_uuid.replace('\n',"") elif self.device_tmp[4].startswith('UUID='): self.device_uuid = self.device_tmp[4].replace('"',"") self.device_uuid = self.device_uuid.replace('\n',"") try: if self.device_tmp[0].startswith('TYPE='): self.device_type = self.device_tmp[0].replace('TYPE=',"") self.device_type = self.device_type.replace('"',"") self.device_type = self.device_type.replace('\n',"") elif self.device_tmp[1].startswith('TYPE='): self.device_type = self.device_tmp[1].replace('TYPE=',"") self.device_type = self.device_type.replace('"',"") self.device_type = self.device_type.replace('\n',"") elif self.device_tmp[2].startswith('TYPE='): self.device_type = self.device_tmp[2].replace('TYPE=',"") self.device_type = self.device_type.replace('"',"") self.device_type = self.device_type.replace('\n',"") elif self.device_tmp[3].startswith('TYPE='): self.device_type = self.device_tmp[3].replace('TYPE=',"") self.device_type = self.device_type.replace('"',"") self.device_type = self.device_type.replace('\n',"") elif self.device_tmp[4].startswith('TYPE='): self.device_type = self.device_tmp[4].replace('TYPE=',"") self.device_type = self.device_type.replace('"',"") self.device_type = self.device_type.replace('\n',"") except: self.device_type = 'auto' if self.device_type.startswith('ext'): self.device_type = 'auto' if not path.exists(self.mountp): mkdir(self.mountp, 0755) file('/etc/fstab.tmp', 'w').writelines([l for l in file('/etc/fstab').readlines() if self.device not in l]) rename('/etc/fstab.tmp','/etc/fstab') file('/etc/fstab.tmp', 'w').writelines([l for l in file('/etc/fstab').readlines() if self.device_uuid not in l]) rename('/etc/fstab.tmp','/etc/fstab') out = open('/etc/fstab', 'a') line = self.device_uuid + ' ' + self.mountp + ' ' + self.device_type + ' defaults,rw,relatime,noatime,nodiratime,barrier=1,data=ordered 0 0\n' out.write(line) out.close() def restartBox(self, answer): if answer is True: self.session.open(TryQuitMainloop, 2) else: self.close()
class CronTimers(Screen): def __init__(self, session): Screen.__init__(self, session) if not path.exists('/usr/script'): mkdir('/usr/script', 0755) Screen.setTitle(self, _("Cron Manager")) self.onChangedEntry = [] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Active"))) self['labdisabled'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['labrun'].hide() self['labactive'].hide() self.summary_running = '' self['key'] = Label( _("H: = Hourly / D: = Daily / W: = Weekly / M: = Monthly")) self.Console = Console() self.my_crond_active = False self.my_crond_run = False self['key_red'] = Label(_("Delete")) self['key_green'] = Label(_("Add")) self['key_yellow'] = StaticText(_("Start")) self['key_blue'] = Label(_("Autostart")) self.list = [] self['list'] = List(self.list) self['actions'] = ActionMap( ['WizardActions', 'ColorActions', "MenuActions"], { 'ok': self.info, 'back': self.UninstallCheck, 'red': self.delcron, 'green': self.addtocron, 'yellow': self.CrondStart, 'blue': self.autostart }) if not self.selectionChanged in self["list"].onSelectionChanged: self["list"].onSelectionChanged.append(self.selectionChanged) self.service_name = 'cronie' self.InstallCheck() def InstallCheck(self): self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def checkNetworkState(self, str, retval, extra_args): if not str: self.feedscheck = self.session.open( MessageBox, _('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input=False) self.feedscheck.setTitle(_('Checking Feeds')) cmd1 = "opkg update" self.CheckConsole = Console() self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished) else: self.updateList() def checkNetworkStateFinished(self, result, retval, extra_args=None): if 'bad address' in result: self.session.openWithCallback( self.InstallPackageFailed, MessageBox, _("Your %s %s is not connected to the internet, please check your network settings and try again." ) % (getMachineBrand(), getMachineName()), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif ('wget returned 1' or 'wget returned 255' or '404 Not Found') in result: self.session.openWithCallback( self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later." ), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) else: self.session.openWithCallback( self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO) def InstallPackage(self, val): if val: self.doInstall(self.installComplete, self.service_name) else: self.feedscheck.close() self.close() def InstallPackageFailed(self, val): self.feedscheck.close() self.close() def doInstall(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Installing Service')) self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback) def installComplete(self, result=None, retval=None, extra_args=None): self.message.close() self.feedscheck.close() self.updateList() def UninstallCheck(self): if not self.my_crond_run: self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail) else: self.close() def RemovedataAvail(self, str, retval, extra_args): if str: self.session.openWithCallback( self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name) else: self.close() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) else: self.close() def doRemove(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Removing Service')) self.Console.ePopen( '/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback) def removeComplete(self, result=None, retval=None, extra_args=None): self.message.close() self.close() def createSummary(self): from Screens.PluginBrowser import PluginBrowserSummary return PluginBrowserSummary def selectionChanged(self): try: if self["list"].getCurrent(): name = str(self["list"].getCurrent()[0]) else: name = "" except: name = "" desc = _("Current Status:") + ' ' + self.summary_running for cb in self.onChangedEntry: cb(name, desc) def CrondStart(self): if not self.my_crond_run: self.Console.ePopen('/etc/init.d/crond start', self.StartStopCallback) elif self.my_crond_run: self.Console.ePopen('/etc/init.d/crond stop', self.StartStopCallback) def StartStopCallback(self, result=None, retval=None, extra_args=None): sleep(3) self.updateList() def autostart(self): if fileExists('/etc/rc2.d/S90crond'): self.Console.ePopen('update-rc.d -f crond remove') else: self.Console.ePopen('update-rc.d -f crond defaults 90 60') sleep(3) self.updateList() def addtocron(self): self.session.openWithCallback(self.updateList, CronTimersConfig) def updateList(self, result=None, retval=None, extra_args=None): import process p = process.ProcessList() crond_process = str(p.named('crond')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].hide() self['labdisabled'].hide() self.my_crond_active = False self.my_crond_run = False if path.exists('/etc/rc3.d/S90crond'): self['labdisabled'].hide() self['labactive'].show() self.my_crond_active = True else: self['labactive'].hide() self['labdisabled'].show() if crond_process: self.my_crond_run = True if self.my_crond_run: self['labstop'].hide() self['labrun'].show() self['key_yellow'].setText(_("Stop")) self.summary_running = _("Running") else: self['labstop'].show() self['labrun'].hide() self['key_yellow'].setText(_("Start")) self.summary_running = _("Stopped") self.list = [] if path.exists('/etc/cron/crontabs/root'): f = open('/etc/cron/crontabs/root', 'r') for line in f.readlines(): parts = line.strip().split() if len(parts) > 5 and not parts[0].startswith("#"): if parts[1] == '*': line2 = 'H: 00:' + parts[0].zfill(2) + '\t' for i in range(5, len(parts)): line2 = line2 + parts[i] + ' ' res = (line2, line) self.list.append(res) elif parts[2] == '*' and parts[4] == '*': line2 = 'D: ' + parts[1].zfill( 2) + ':' + parts[0].zfill(2) + '\t' for i in range(5, len(parts)): line2 = line2 + parts[i] + ' ' res = (line2, line) self.list.append(res) elif parts[3] == '*': if parts[4] == "*": line2 = 'M: Day ' + parts[2] + ' ' + parts[ 1].zfill(2) + ':' + parts[0].zfill(2) + '\t' for i in range(5, len(parts)): line2 = line2 + parts[i] + ' ' header = 'W: ' day = "" if str(parts[4]).find('0') >= 0: day = 'Sun ' if str(parts[4]).find('1') >= 0: day += 'Mon ' if str(parts[4]).find('2') >= 0: day += 'Tues ' if str(parts[4]).find('3') >= 0: day += 'Wed ' if str(parts[4]).find('4') >= 0: day += 'Thurs ' if str(parts[4]).find('5') >= 0: day += 'Fri ' if str(parts[4]).find('6') >= 0: day += 'Sat ' if day: line2 = header + day + parts[1].zfill( 2) + ':' + parts[0].zfill(2) + '\t' for i in range(5, len(parts)): line2 = line2 + parts[i] + ' ' res = (line2, line) self.list.append(res) f.close() self['list'].list = self.list self["actions"].setEnabled(True) def delcron(self): self.sel = self['list'].getCurrent() if self.sel: parts = self.sel[0] parts = parts.split('\t') message = _("Are you sure you want to delete this:\n ") + parts[1] ybox = self.session.openWithCallback(self.doDelCron, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_("Remove Confirmation")) def doDelCron(self, answer): if answer: mysel = self['list'].getCurrent() if mysel: myline = mysel[1] file('/etc/cron/crontabs/root.tmp', 'w').writelines([ l for l in file('/etc/cron/crontabs/root').readlines() if myline not in l ]) rename('/etc/cron/crontabs/root.tmp', '/etc/cron/crontabs/root') rc = system( 'crontab /etc/cron/crontabs/root -c /etc/cron/crontabs') self.updateList() def info(self): mysel = self['list'].getCurrent() if mysel: myline = mysel[1] self.session.open(MessageBox, _(myline), MessageBox.TYPE_INFO)
def getLinkState(self, iface, callback): cmd = self.ethtool_bin + " " + iface self.LinkConsole = Console() self.LinkConsole.ePopen(cmd, self.getLinkStateFinished, callback)
class Network: def __init__(self): self.ifaces = {} self.onlyWoWifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "ethtool" self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.PingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: import Harddisk for parts in Harddisk.getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'tap0', 'sys0', 'p2p0') def getInterfaces(self, callback=None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [int(n) for n in ip.split('.')] def getAddrInet(self, iface, callback): if not self.Console: self.Console = Console() cmd = "busybox ip -o addr show dev " + iface + " | grep -v inet6" self.Console.ePopen(cmd, self.IPaddrFinished, [iface, callback]) def IPaddrFinished(self, result, retval, extra_args): (iface, callback) = extra_args data = {'up': False, 'dhcp': False, 'preup': False, 'predown': False} globalIPpattern = re.compile("scope global") ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' netRegexp = '[0-9]{1,2}' macRegexp = '[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}' ipLinePattern = re.compile('inet ' + ipRegexp + '/') ipPattern = re.compile(ipRegexp) netmaskLinePattern = re.compile('/' + netRegexp) netmaskPattern = re.compile(netRegexp) bcastLinePattern = re.compile(' brd ' + ipRegexp) upPattern = re.compile('UP') macPattern = re.compile(macRegexp) macLinePattern = re.compile('link/ether ' + macRegexp) for line in result.splitlines(): split = line.strip().split(' ', 2) if (split[1][:-1] == iface) or (split[1][:-1] == (iface + '@sys0')): up = self.regExpMatch(upPattern, split[2]) mac = self.regExpMatch( macPattern, self.regExpMatch(macLinePattern, split[2])) if up is not None: data['up'] = True if iface is not 'lo': self.configuredInterfaces.append(iface) if mac is not None: data['mac'] = mac if split[1] == iface: if re.search(globalIPpattern, split[2]): ip = self.regExpMatch( ipPattern, self.regExpMatch(ipLinePattern, split[2])) netmask = self.calc_netmask( self.regExpMatch( netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2]))) bcast = self.regExpMatch( ipPattern, self.regExpMatch(bcastLinePattern, split[2])) if ip is not None: data['ip'] = self.convertIP(ip) if netmask is not None: data['netmask'] = self.convertIP(netmask) if bcast is not None: data['bcast'] = self.convertIP(bcast) if not data.has_key('ip'): data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] cmd = "route -n | grep " + iface self.Console.ePopen(cmd, self.routeFinished, [iface, data, callback]) def routeFinished(self, result, retval, extra_args): (iface, data, callback) = extra_args ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = re.compile(ipRegexp) ipLinePattern = re.compile(ipRegexp) for line in result.splitlines(): print line[0:7] if line[0:7] == "0.0.0.0": gateway = self.regExpMatch(ipPattern, line[16:31]) if gateway: data['gateway'] = self.convertIP(gateway) self.ifaces[iface] = data self.loadNetworkConfig(iface, callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = file('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") for ifacename, iface in self.ifaces.items(): WoW = False if self.onlyWoWifaces.has_key(ifacename): WoW = self.onlyWoWifaces[ifacename] if WoW == False and iface['up'] == True: fp.write("auto " + ifacename + "\n") self.configuredInterfaces.append(ifacename) self.onlyWoWifaces[ifacename] = False elif WoW == True: self.onlyWoWifaces[ifacename] = True fp.write("#only WakeOnWiFi " + ifacename + "\n") if iface['dhcp']: fp.write("iface " + ifacename + " inet dhcp\n") if not iface['dhcp']: fp.write("iface " + ifacename + " inet static\n") fp.write(" hostname $(hostname)\n") if iface.has_key('ip'): # print tuple(iface['ip']) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if iface.has_key('gateway'): fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if iface.has_key("configStrings"): fp.write(iface["configStrings"]) if iface["preup"] is not False and not iface.has_key( "configStrings"): fp.write(iface["preup"]) if iface["predown"] is not False and not iface.has_key( "configStrings"): fp.write(iface["predown"]) dnses = self.makeLineDnsNameservers(self.nameservers) fp.write(dnses) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def makeLineDnsNameservers(self, nameservers=[]): line = "" entry = ' '.join([("%d.%d.%d.%d" % tuple(x)) for x in nameservers if x != [0, 0, 0, 0]]) if len(entry): line += "\tdns-nameservers %s\n" % entry return line def writeNameserverConfig(self): try: os.system('rm -rf /etc/resolv.conf') fp = file('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() except: print "[Network.py] interfaces - resolv.conf write failed" def loadNetworkConfig(self, iface, callback=None): interfaces = [] # parse the interfaces-file try: fp = file('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print "[Network.py] interfaces - opening failed" ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if split[0] == "iface" and split[2] != "inet6": currif = split[1] ifaces[currif] = {} if len(split) == 4 and split[3] == "dhcp": ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if currif == iface: #read information only for available interfaces if split[0] == "address": ifaces[currif]["address"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("ip"): if self.ifaces[currif]["ip"] != ifaces[currif][ "address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = map( int, split[1].split('.')) if split[0] == "netmask": ifaces[currif]["netmask"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("netmask"): if self.ifaces[currif]["netmask"] != ifaces[currif][ "netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = map( int, split[1].split('.')) if split[0] == "gateway": ifaces[currif]["gateway"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("gateway"): if self.ifaces[currif]["gateway"] != ifaces[currif][ "gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = map( int, split[1].split('.')) if split[0] == "pre-up": if self.ifaces[currif].has_key("preup"): self.ifaces[currif]["preup"] = i if split[0] in ("pre-down", "post-down"): if self.ifaces[currif].has_key("predown"): self.ifaces[currif]["predown"] = i for ifacename, iface in ifaces.items(): if self.ifaces.has_key(ifacename): self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if self.Console: if len(self.Console.appContainers) == 0: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() # print "read configured interface:", ifaces # print "self.ifaces after loading:", self.ifaces self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = re.compile("nameserver +" + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = file('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print "[Network.py] resolv.conf - opening failed" for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) # print "nameservers:", self.nameservers def getInstalledAdapters(self): return [ x for x in os.listdir('/sys/class/net') if not self.isBlacklisted(x) ] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get( x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _("WLAN connection") if len(self.wlan_interfaces): name += " " + str(len(self.wlan_interfaces) + 1) self.wlan_interfaces.append(iface) else: if iface not in self.lan_interfaces: if getBoxType() == "et10000" and iface == "eth1": name = _("VLAN connection") else: name = _("LAN connection") if len( self.lan_interfaces ) and not getBoxType() == "et10000" and not iface == "eth1": name += " " + str(len(self.lan_interfaces) + 1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = os.path.basename(os.path.realpath(moduledir)) if name in ('ath_pci', 'ath5k', 'ar6k_wlan'): name = 'Atheros' elif name in ('rt73', 'rt73usb', 'rt3070sta'): name = 'Ralink' elif name == 'zd1211b': name = 'Zydas' elif name == 'r871x_usb_drv': name = 'Realtek' elif name == 'brcm-systemport': name = 'Broadcom' else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return self.ifaces.keys() def getAdapterAttribute(self, iface, attribute): if self.ifaces.has_key(iface): if self.ifaces[iface].has_key(attribute): return self.ifaces[iface][attribute] return None def setAdapterAttribute(self, iface, attribute, value): # print "setting for adapter", iface, "attribute", attribute, " to value", value if self.ifaces.has_key(iface): self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if self.ifaces.has_key(iface): if self.ifaces[iface].has_key(attribute): del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback=None): self.resetNetworkConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self, mode='lan', callback=None): fp = file('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.resetNetworkConsole = Console() self.commands = [] if mode == 'wlan': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig ath0 down") self.commands.append("ifconfig wlan0 up") if mode == 'wlan-mpci': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 up") if mode == 'lan': self.commands.append("ifconfig eth0 up") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 down") self.commands.append("/etc/init.d/avahi-daemon start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode, callback], debug=True) def resetNetworkFinished(self, extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: if callback is not None: callback(True, mode) def checkNetworkState(self, statecallback): self.NetworkState = 0 cmd1 = "ping -c 1 www.zdf.de" cmd2 = "ping -c 1 www.google.nl" cmd3 = "ping -c 1 www.google.com" self.PingConsole = Console() self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished, statecallback) self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished, statecallback) self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished, statecallback) def checkNetworkStateFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.PingConsole is not None: if retval == 0: self.PingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if len(self.PingConsole.appContainers) == 0: statecallback(self.NetworkState) def restartNetwork(self, callback=None): self.restartConsole = Console() self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self, extra_args): (callback) = extra_args if callback is not None: try: callback(True) except: pass def getLinkState(self, iface, callback): cmd = self.ethtool_bin + " " + iface self.LinkConsole = Console() self.LinkConsole.ePopen(cmd, self.getLinkStateFinished, callback) def getLinkStateFinished(self, result, retval, extra_args): (callback) = extra_args if self.LinkConsole is not None: if len(self.LinkConsole.appContainers) == 0: callback(result) def stopPingConsole(self): if self.PingConsole is not None: if len(self.PingConsole.appContainers): for name in self.PingConsole.appContainers.keys(): self.PingConsole.kill(name) def stopLinkStateConsole(self): if self.LinkConsole is not None: if len(self.LinkConsole.appContainers): for name in self.LinkConsole.appContainers.keys(): self.LinkConsole.kill(name) def stopDNSConsole(self): if self.DnsConsole is not None: if len(self.DnsConsole.appContainers): for name in self.DnsConsole.appContainers.keys(): self.DnsConsole.kill(name) def stopRestartConsole(self): if self.restartConsole is not None: if len(self.restartConsole.appContainers): for name in self.restartConsole.appContainers.keys(): self.restartConsole.kill(name) def stopGetInterfacesConsole(self): if self.Console is not None: if len(self.Console.appContainers): for name in self.Console.appContainers.keys(): self.Console.kill(name) def stopDeactivateInterfaceConsole(self): if self.deactivateInterfaceConsole is not None: self.deactivateInterfaceConsole.killAll() self.deactivateInterfaceConsole = None def stopActivateInterfaceConsole(self): if self.activateInterfaceConsole is not None: self.activateInterfaceConsole.killAll() self.activateInterfaceConsole = None def checkforInterface(self, iface): if self.getAdapterAttribute(iface, 'up') is True: return True else: ret = os.system("ifconfig " + iface + " up") os.system("ifconfig " + iface + " down") if ret == 0: return True else: return False def checkDNSLookup(self, statecallback): cmd1 = "nslookup www.dream-multimedia-tv.de" cmd2 = "nslookup www.heise.de" cmd3 = "nslookup www.google.de" self.DnsConsole = Console() self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished, statecallback) self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished, statecallback) self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished, statecallback) def checkDNSLookupFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.DnsConsole is not None: if retval == 0: self.DnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if len(self.DnsConsole.appContainers) == 0: statecallback(self.DnsState) def deactivateInterface(self, ifaces, callback=None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append("ifdown " + iface) commands.append("ip addr flush dev " + iface + " scope global") #wpa_supplicant sometimes doesn't quit properly on SIGTERM if os.path.exists('/var/run/wpa_supplicant/' + iface): commands.append("wpa_cli -i" + iface + " terminate") if not self.deactivateInterfaceConsole: self.deactivateInterfaceConsole = Console() if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch( commands, self.deactivateInterfaceFinished, [ifaces, callback], debug=True) def deactivateInterfaceFinished(self, extra_args): (ifaces, callback) = extra_args def checkCommandResult(iface): if self.deactivateInterfaceConsole and self.deactivateInterfaceConsole.appResults.has_key( "ifdown " + iface): result = str( self.deactivateInterfaceConsole.appResults.get( "ifdown " + iface)).strip("\n") if result == "ifdown: interface " + iface + " not configured": return False else: return True #ifdown sometimes can't get the interface down. if isinstance(ifaces, (list, tuple)): for iface in ifaces: if checkCommandResult(iface) is False: Console().ePopen(("ifconfig " + iface + " down")) else: if checkCommandResult(ifaces) is False: Console().ePopen(("ifconfig " + ifaces + " down")) if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def activateInterface(self, iface, callback=None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return if not self.activateInterfaceConsole: self.activateInterfaceConsole = Console() commands = ["ifup " + iface] self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self, extra_args): callback = extra_args if self.activateInterfaceConsole: if len(self.activateInterfaceConsole.appContainers) == 0: if callback is not None: try: callback(True) except: pass def sysfsPath(self, iface): return '/sys/class/net/' + iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True if os.path.isdir(self.sysfsPath(iface) + '/wireless'): return True # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless device = re.compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass fp.close() if iface in ifnames: return True return False def canWakeOnWiFi(self, iface): if self.sysfsPath(iface) == "/sys/class/net/wlan3" and os.path.exists( "/tmp/bcm/%s" % iface): return True def getWlanModuleDir(self, iface=None): if self.sysfsPath(iface) == "/sys/class/net/wlan3" and os.path.exists( "/tmp/bcm/%s" % iface): devicedir = self.sysfsPath("sys0") + '/device' else: devicedir = self.sysfsPath(iface) + '/device' moduledir = devicedir + '/driver/module' if os.path.isdir(moduledir): return moduledir # identification is not possible over default moduledir try: for x in os.listdir(devicedir): # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx if x.startswith("1-"): moduledir = devicedir + '/' + x + '/driver/module' if os.path.isdir(moduledir): return moduledir # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here moduledir = devicedir + '/driver' if os.path.isdir(moduledir): return moduledir except: pass return None def detectWlanModule(self, iface=None): if not self.isWirelessInterface(iface): return None devicedir = self.sysfsPath(iface) + '/device' if os.path.isdir(devicedir + '/ieee80211'): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = os.path.basename(os.path.realpath(moduledir)) if module in ('brcm-systemport', ): return 'brcm-wl' if module in ('ath_pci', 'ath5k'): return 'madwifi' if module in ('rt73', 'rt73'): return 'ralink' if module == 'zd1211b': return 'zydas' return 'wext' def calc_netmask(self, nmask): from struct import pack from socket import inet_ntoa mask = 1L << 31 xnet = (1L << 32) - 1 cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print 'cidr invalid: %d' % cidr return None else: nm = ((1L << cidr) - 1) << (32 - cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins( PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == "add": print "[Network] Add new interface:", interface self.getAddrInet(interface, None) elif action == "remove": print "[Network] Removed interface:", interface try: del self.ifaces[interface] except KeyError: pass def getInterfacesNameserverList(self, iface): result = [] nameservers = self.getAdapterAttribute(iface, "dns-nameservers") if nameservers: ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = re.compile(ipRegexp) for x in nameservers.split()[1:]: ip = self.regExpMatch(ipPattern, x) if ip: result.append([int(n) for n in ip.split('.')]) if len( self.nameservers ) and not result: # use also global nameserver if we got no one from interface result.extend(self.nameservers) return result
class UserInterfacePositioner(Screen, ConfigListScreen): def __init__(self, session, menu_path=""): Screen.__init__(self, session) screentitle = _("OSD position") if config.usage.show_menupath.value == 'large': menu_path += screentitle title = menu_path self.setup_title = title self["menu_path_compressed"] = StaticText("") elif config.usage.show_menupath.value == 'small': title = screentitle self.setup_title = screentitle self["menu_path_compressed"] = StaticText( menu_path + " >" if not menu_path.endswith(' / ') else menu_path[:-3] + " >" or "") else: title = screentitle self.setup_title = title self["menu_path_compressed"] = StaticText("") self.Console = Console() self["status"] = StaticText() self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("OK")) self["key_yellow"] = StaticText(_("Defaults")) self["actions"] = ActionMap( ["SetupActions", "ColorActions"], { "cancel": self.keyCancel, "save": self.keySave, "left": self.keyLeft, "right": self.keyRight, "yellow": self.keyDefault, }, -2) self.onChangedEntry = [] self.list = [] ConfigListScreen.__init__(self, self.list, session=self.session, on_change=self.changedEntry) if SystemInfo["CanChangeOsdAlpha"]: self.list.append( getConfigListEntry( _("User interface visibility"), config.osd.alpha, _("This option lets you adjust the transparency of the user interface" ))) if SystemInfo["CanChangeOsdPosition"]: self.list.append( getConfigListEntry( _("Move Left/Right"), config.osd.dst_left, _("Use the LEFT/RIGHT buttons on your remote to move the user interface left/right." ))) self.list.append( getConfigListEntry( _("Width"), config.osd.dst_width, _("Use the LEFT/RIGHT buttons on your remote to adjust the width of the user interface. LEFT button decreases the size, RIGHT increases the size." ))) self.list.append( getConfigListEntry( _("Move Up/Down"), config.osd.dst_top, _("Use the LEFT/RIGHT buttons on your remote to move the user interface up/down." ))) self.list.append( getConfigListEntry( _("Height"), config.osd.dst_height, _("Use the LEFT/RIGHT buttons on your remote to adjust the height of the user interface. LEFT button decreases the size, RIGHT increases the size." ))) self["config"].list = self.list self["config"].l.setList(self.list) self.serviceRef = None self.onLayoutFinish.append(self.layoutFinished) if self.welcomeWarning not in self.onShow: self.onShow.append(self.welcomeWarning) if self.selectionChanged not in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.selectionChanged) self.selectionChanged() def selectionChanged(self): self["status"].setText(self["config"].getCurrent()[2]) def layoutFinished(self): self.setTitle(_(self.setup_title)) def welcomeWarning(self): if self.welcomeWarning in self.onShow: self.onShow.remove(self.welcomeWarning) popup = self.session.openWithCallback( self.welcomeAction, MessageBox, _("NOTE: This feature is intended for people who cannot disable overscan " "on their television / display. Please first try to disable overscan before using this feature.\n\n" "USAGE: Adjust the screen size and position settings so that the shaded user interface layer *just* " "covers the test pattern in the background.\n\n" "Select Yes to continue or No to exit."), type=MessageBox.TYPE_YESNO, timeout=-1, default=False) popup.setTitle(self.setup_title) def welcomeAction(self, answer): if answer: self.serviceRef = self.session.nav.getCurrentlyPlayingServiceReference( ) self.session.nav.stopService() if self.restoreService not in self.onClose: self.onClose.append(self.restoreService) self.Console.ePopen( '/usr/bin/showiframe /usr/share/enigma2/hd-testcard.mvi') else: self.close() def restoreService(self): try: self.session.nav.playService(self.serviceRef) except: pass def createSummary(self): from Screens.Setup import SetupSummary return SetupSummary # for summary: def changedEntry(self): for x in self.onChangedEntry: x() def getCurrentEntry(self): return self["config"].getCurrent()[0] def getCurrentValue(self): return str(self["config"].getCurrent()[1].getText()) def keyLeft(self): ConfigListScreen.keyLeft(self) self.setPreviewPosition() def keyRight(self): ConfigListScreen.keyRight(self) self.setPreviewPosition() def keyDefault(self): config.osd.alpha.setValue(255) config.osd.dst_left.setValue(0) config.osd.dst_width.setValue(720) config.osd.dst_top.setValue(0) config.osd.dst_height.setValue(576) for item in self["config"].list: self["config"].invalidate(item) print '[UserInterfacePositioner] Setting default OSD position: %s %s %s %s' % ( config.osd.dst_left.value, config.osd.dst_width.value, config.osd.dst_top.value, config.osd.dst_height.value) def setPreviewPosition(self): size_w = getDesktop(0).size().width() size_h = getDesktop(0).size().height() dsk_w = int(float(size_w)) / float(720) dsk_h = int(float(size_h)) / float(576) dst_left = int(config.osd.dst_left.value) dst_width = int(config.osd.dst_width.value) dst_top = int(config.osd.dst_top.value) dst_height = int(config.osd.dst_height.value) while dst_width + (dst_left / float(dsk_w) ) >= 720.5 or dst_width + dst_left > 720: dst_width = int(dst_width) - 1 while dst_height + ( dst_top / float(dsk_h)) >= 576.5 or dst_height + dst_top > 576: dst_height = int(dst_height) - 1 config.osd.dst_left.setValue(dst_left) config.osd.dst_width.setValue(dst_width) config.osd.dst_top.setValue(dst_top) config.osd.dst_height.setValue(dst_height) for item in self["config"].list: self["config"].invalidate(item) print '[UserInterfacePositioner] Setting OSD position: %s %s %s %s' % ( config.osd.dst_left.value, config.osd.dst_width.value, config.osd.dst_top.value, config.osd.dst_height.value) def saveAll(self): for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): from Screens.MessageBox import MessageBox self.session.openWithCallback( self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default=False) else: self.close() # This is called by the Wizard... def run(self): config.osd.dst_left.save() config.osd.dst_width.save() config.osd.dst_top.save() config.osd.dst_height.save() configfile.save() self.close()
class Network: def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "/usr/sbin/ethtool" self.ip_bin = "/sbin/ip" self.ifconfig_bin = "/sbin/ifconfig" self.ifdown_bin = "/sbin/ifdown" self.ifup_bin = "/sbin/ifup" self.ping_bin = "/bin/ping" self.nslookup_bin = "/usr/bin/nslookup" self.avahi_daemon = "/etc/init.d/avahi-daemon" self.networking_initd = "/etc/init.d/networking" self.console = Console() self.linkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.dnsConsole = Console() self.pingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: import Harddisk for parts in Harddisk.getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'sys0', 'p2p0', 'tap0', 'tunl0', 'ip6tnl0') def getInterfaces(self, callback=None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [int(n) for n in ip.split('.')] def getAddrInet(self, iface, callback): data = {'up': False, 'dhcp': False, 'preup': False, 'predown': False} try: data['up'] = int( open('/sys/class/net/%s/flags' % iface).read().strip(), 16) & 1 == 1 if data['up']: self.configuredInterfaces.append(iface) nit = ni.ifaddresses(iface) data['ip'] = self.convertIP(nit[ni.AF_INET][0]['addr']) # ipv4 data['netmask'] = self.convertIP(nit[ni.AF_INET][0]['netmask']) data['bcast'] = self.convertIP(nit[ni.AF_INET][0]['broadcast']) data['mac'] = nit[ni.AF_LINK][0]['addr'] # mac data['gateway'] = self.convertIP( ni.gateways()['default'][ni.AF_INET][0]) # default gw except: data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] self.ifaces[iface] = data self.loadNetworkConfig(iface, callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = open('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") for ifacename, iface in self.ifaces.items(): if "dns-nameservers" in iface and iface['dns-nameservers']: dns = [] for s in iface['dns-nameservers'].split()[1:]: dns.append((self.convertIP(s))) if dns: self.nameservers = dns if iface['up']: fp.write("auto " + ifacename + "\n") self.configuredInterfaces.append(ifacename) if iface['dhcp']: fp.write("iface " + ifacename + " inet dhcp\n") fp.write("udhcpc_opts -T1 -t9\n") if not iface['dhcp']: fp.write("iface " + ifacename + " inet static\n") if 'ip' in iface: print(tuple(iface['ip'])) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if 'gateway' in iface: fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if "configStrings" in iface: fp.write(iface["configStrings"]) if iface["preup"] is not False and "configStrings" not in iface: fp.write(iface["preup"]) if iface["predown"] is not False and "configStrings" not in iface: fp.write(iface["predown"]) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): try: Console().ePopen('rm -f /etc/resolv.conf') fp = open('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() except: print("[Network] resolv.conf - writing failed") def loadNetworkConfig(self, iface, callback=None): interfaces = [] # parse the interfaces-file try: fp = open('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print("[Network] interfaces - opening failed") ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if split[0] == "iface" and split[2] != "inet6": currif = split[1] ifaces[currif] = {} if len(split) == 4 and split[3] == "dhcp": ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if currif == iface: #read information only for available interfaces if split[0] == "address": ifaces[currif]["address"] = map(int, split[1].split('.')) if "ip" in self.ifaces[currif]: if self.ifaces[currif]["ip"] != ifaces[currif][ "address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = map( int, split[1].split('.')) if split[0] == "netmask": ifaces[currif]["netmask"] = map(int, split[1].split('.')) if "netmask" in self.ifaces[currif]: if self.ifaces[currif]["netmask"] != ifaces[currif][ "netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = map( int, split[1].split('.')) if split[0] == "gateway": ifaces[currif]["gateway"] = map(int, split[1].split('.')) if "gateway" in self.ifaces[currif]: if self.ifaces[currif]["gateway"] != ifaces[currif][ "gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = map( int, split[1].split('.')) if split[0] == "pre-up": if "preup" in self.ifaces[currif]: self.ifaces[currif]["preup"] = i if split[0] in ("pre-down", "post-down"): if "predown" in self.ifaces[currif]: self.ifaces[currif]["predown"] = i for ifacename, iface in ifaces.items(): if ifacename in self.ifaces: self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if not self.console.appContainers: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() print("[Network] read configured interface:", ifaces) # remove any password before info is printed to the debug log safe_ifaces = self.ifaces.copy() for intf in safe_ifaces: if 'preup' in safe_ifaces[intf] and safe_ifaces[intf][ 'preup'] is not False: safe_ifaces[intf]['preup'] = re.sub( ' -k \S* ', ' -k ********* ', safe_ifaces[intf]['preup']) print("[Network] self.ifaces after loading:", safe_ifaces) self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = re.compile("nameserver +" + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = open('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print("[Network] resolv.conf - opening failed") for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) print("[Network] nameservers:", self.nameservers) def getInstalledAdapters(self): return [ x for x in os.listdir('/sys/class/net') if not self.isBlacklisted(x) ] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get( x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _("WLAN connection") if len(self.wlan_interfaces): name += " " + str(len(self.wlan_interfaces) + 1) self.wlan_interfaces.append(iface) else: if iface not in self.lan_interfaces: if iface == "eth1": name = _("VLAN connection") else: name = _("LAN connection") if len(self.lan_interfaces) and not iface == "eth1": name += " " + str(len(self.lan_interfaces) + 1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = os.path.basename(os.path.realpath(moduledir)) if name.startswith('ath') or name.startswith('carl'): name = 'Atheros' elif name.startswith('rt2') or name.startswith( 'rt3') or name.startswith('rt5') or name.startswith( 'rt6') or name.startswith('rt7'): name = 'Ralink' elif name.startswith('zd'): name = 'Zydas' elif name.startswith('rtl') or name.startswith('r8'): name = 'Realtek' elif name.startswith('smsc'): name = 'SMSC' elif name.startswith('peg'): name = 'Pegasus' elif name.startswith('rn'): name = 'RNDIS' elif name.startswith('mw') or name.startswith('libertas'): name = 'Marvel' elif name.startswith('p5'): name = 'Prism' elif name.startswith('as') or name.startswith('ax'): name = 'ASIX' elif name.startswith('dm'): name = 'Davicom' elif name.startswith('mcs'): name = 'MosChip' elif name.startswith('at'): name = 'Atmel' elif name.startswith('iwm'): name = 'Intel' elif name.startswith('brcm') or name.startswith('bcm'): name = 'Broadcom' elif os.path.isdir('/tmp/bcm/' + iface): name = 'Broadcom' else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return self.ifaces.keys() def getAdapterAttribute(self, iface, attribute): return self.ifaces.get(iface, {}).get(attribute) def setAdapterAttribute(self, iface, attribute, value): print("[Network] setting for adapter", iface, "attribute", attribute, " to value", value) if iface in self.ifaces: self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if iface in self.ifaces and attribute in self.ifaces[iface]: del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback=None): self.commands = [] self.commands.append(self.avahi_daemon + " stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append(self.ip_bin + " addr flush dev " + iface + " scope global") self.commands.append(self.networking_initd + " stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm -f /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self, mode='lan', callback=None): fp = open('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.commands = [] if mode == 'wlan': self.commands.append(self.ifconfig_bin + " eth0 down") self.commands.append(self.ifconfig_bin + " ath0 down") self.commands.append(self.ifconfig_bin + " wlan0 up") if mode == 'wlan-mpci': self.commands.append(self.ifconfig_bin + " eth0 down") self.commands.append(self.ifconfig_bin + " wlan0 down") self.commands.append(self.ifconfig_bin + " ath0 up") if mode == 'lan': self.commands.append(self.ifconfig_bin + " eth0 up") self.commands.append(self.ifconfig_bin + " wlan0 down") self.commands.append(self.ifconfig_bin + " ath0 down") self.commands.append(self.avahi_daemon + " start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode, callback], debug=True) def resetNetworkFinished(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: if callback is not None: callback(True, mode) def checkNetworkState(self, statecallback): self.NetworkState = 0 self.pingConsole = Console() for server in ("www.google.com", "www.bing.com", "www.microsoft.com"): self.pingConsole.ePopen( (self.ping_bin, self.ping_bin, "-c", "1", server), self.checkNetworkStateFinished, statecallback) def checkNetworkStateFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.pingConsole is not None: if retval == 0: self.pingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if not self.pingConsole.appContainers: statecallback(self.NetworkState) def restartNetwork(self, callback=None): self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append(self.avahi_daemon + " stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append((self.ifdown_bin, self.ifdown_bin, iface)) self.commands.append(self.ip_bin + " addr flush dev " + iface + " scope global") self.commands.append(self.networking_initd + " stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm -f /var/run/udhcpc*") self.commands.append(self.networking_initd + " start") self.commands.append(self.avahi_daemon + " start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self, extra_args): (callback) = extra_args if callback is not None: try: callback(True) except: pass def getLinkState(self, iface, callback): self.linkConsole.ePopen((self.ethtool_bin, self.ethtool_bin, iface), self.getLinkStateFinished, callback) def getLinkStateFinished(self, result, retval, extra_args): (callback) = extra_args if not self.linkConsole.appContainers: callback(result) def stopPingConsole(self): if self.pingConsole is not None: self.pingConsole.killAll() def stopLinkStateConsole(self): self.linkConsole.killAll() def stopDNSConsole(self): if self.dnsConsole is not None: self.dnsConsole.killAll() def stopRestartConsole(self): self.restartConsole.killAll() def stopGetInterfacesConsole(self): self.console.killAll() def stopDeactivateInterfaceConsole(self): self.deactivateInterfaceConsole.killAll() def stopActivateInterfaceConsole(self): self.activateInterfaceConsole.killAll() def checkforInterface(self, iface): if self.getAdapterAttribute(iface, 'up') is True: return True else: ret = Console().ePopen(self.ifconfig_bin + " " + iface + " up") Console().ePopen(self.ifconfig_bin + " " + iface + " down") if ret == 0: return True else: return False def checkDNSLookup(self, statecallback): self.DnsState = 0 self.dnsConsole = Console() for server in ("www.google.com", "www.bing.com", "www.microsoft.com"): self.dnsConsole.ePopen( (self.nslookup_bin, self.nslookup_bin, server), self.checkDNSLookupFinished, statecallback) def checkDNSLookupFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.dnsConsole is not None: if retval == 0: self.dnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if not self.dnsConsole.appContainers: statecallback(self.DnsState) def deactivateInterface(self, ifaces, callback=None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append((self.ifdown_bin, self.ifdown_bin, "-f", iface)) commands.append((self.ip_bin, self.ip_bin, "addr", "flush", "dev", iface, "scope", "global")) #wpa_supplicant sometimes doesn't quit properly on SIGTERM if os.path.exists('/var/run/wpa_supplicant/' + iface): commands.append("wpa_cli -i" + iface + " terminate") if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch( commands, self.deactivateInterfaceFinished, (ifaces, callback), debug=True) def deactivateInterfaceFinished(self, extra_args): (ifaces, callback) = extra_args if not self.deactivateInterfaceConsole.appContainers: if callback is not None: callback(True) def activateInterface(self, iface, callback=None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return commands = [] commands.append((self.ifup_bin, self.ifup_bin, iface)) self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self, extra_args): callback = extra_args if not self.activateInterfaceConsole.appContainers: if callback is not None: try: callback(True) except: pass def sysfsPath(self, iface): return '/sys/class/net/' + iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True if os.path.isdir(self.sysfsPath(iface) + '/wireless'): return True # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless device = re.compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass if iface in ifnames: return True return False def getWlanModuleDir(self, iface=None): if self.sysfsPath(iface) == "/sys/class/net/wlan3" and os.path.exists( "/tmp/bcm/%s" % iface): devicedir = self.sysfsPath("sys0") + '/device' else: devicedir = self.sysfsPath(iface) + '/device' if not os.path.isdir(devicedir): return None moduledir = devicedir + '/driver/module' if os.path.isdir(moduledir): return moduledir # identification is not possible over default moduledir try: for x in os.listdir(devicedir): # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx if x.startswith("1-"): moduledir = devicedir + '/' + x + '/driver/module' if os.path.isdir(moduledir): return moduledir # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here moduledir = devicedir + '/driver' if os.path.isdir(moduledir): return moduledir except: pass return None def detectWlanModule(self, iface=None): if not self.isWirelessInterface(iface): return None devicedir = self.sysfsPath(iface) + '/device' if os.path.isdir(devicedir + '/ieee80211'): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = os.path.basename(os.path.realpath(moduledir)) if module in ('ath_pci', 'ath5k'): return 'madwifi' if module == 'rt73': return 'ralink' if module == 'zd1211b': return 'zydas' if module == 'brcm-systemport': return 'brcm-wl' return 'wext' def calc_netmask(self, nmask): from struct import pack from socket import inet_ntoa mask = 1L << 31 xnet = (1L << 32) - 1 cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print('[Network] cidr invalid: %d' % cidr) return None else: nm = ((1L << cidr) - 1) << (32 - cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins( PluginDescriptor.WHERE_NETWORKCONFIG_READ): p.__call__(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == "add": print("[Network] Add new interface:", interface) self.getAddrInet(interface, None) elif action == "remove": print("[Network] Removed interface:", interface) try: del self.ifaces[interface] except KeyError: pass
def populate2(self): self.activityTimer.stop() self.Console = Console() niminfo = "" nims = nimmanager.nimListCompressed() for count in range(len(nims)): if niminfo: niminfo += "\n" niminfo += nims[count] self["nims"].setText(niminfo) nims = nimmanager.nimList() if len(nims) <= 4 : for count in (0, 1, 2, 3): if count < len(nims): self["Tuner" + str(count)].setText(nims[count]) else: self["Tuner" + str(count)].setText("") else: desc_list = [] count = 0 cur_idx = -1 while count < len(nims): data = nims[count].split(":") idx = data[0].strip('Tuner').strip() desc = data[1].strip() if desc_list and desc_list[cur_idx]['desc'] == desc: desc_list[cur_idx]['end'] = idx else: desc_list.append({'desc' : desc, 'start' : idx, 'end' : idx}) cur_idx += 1 count += 1 for count in (0, 1, 2, 3): if count < len(desc_list): if desc_list[count]['start'] == desc_list[count]['end']: text = "Tuner %s: %s" % (desc_list[count]['start'], desc_list[count]['desc']) else: text = "Tuner %s-%s: %s" % (desc_list[count]['start'], desc_list[count]['end'], desc_list[count]['desc']) else: text = "" self["Tuner" + str(count)].setText(text) self.hddlist = harddiskmanager.HDDList() self.list = [] if self.hddlist: for count in range(len(self.hddlist)): hdd = self.hddlist[count][1] hddp = self.hddlist[count][0] if "ATA" in hddp: hddp = hddp.replace('ATA', '') hddp = hddp.replace('Internal', 'ATA Bus ') free = hdd.Totalfree() if ((float(free) / 1024) / 1024) >= 1: freeline = _("Free: ") + str(round(((float(free) / 1024) / 1024), 2)) + _("TB") elif (free / 1024) >= 1: freeline = _("Free: ") + str(round((float(free) / 1024), 2)) + _("GB") elif free >= 1: freeline = _("Free: ") + str(free) + _("MB") elif "Generic(STORAGE" in hddp: # This is the SDA boot volume for SF8008 if "full" # continue else: freeline = _("Free: ") + _("full") line = "%s %s" %(hddp, freeline) self.list.append(line) self.list = '\n'.join(self.list) self["hdd"].setText(self.list) self.Console.ePopen("df -mh | grep -v '^Filesystem'", self.Stage1Complete)
class SystemMemoryInfo(Screen): def __init__(self, session): Screen.__init__(self, session) self.setTitle(_("Memory")) self.skinName = ["SystemMemoryInfo", "About"] self["lab1"] = StaticText(_("Virtuosso Image Xtreme")) self["lab2"] = StaticText(_("By Team ViX")) self["lab3"] = StaticText(_("Support at %s") % "www.world-of-satellite.com") self["AboutScrollLabel"] = ScrollLabel() self["key_red"] = Button(_("Close")) self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, "red": self.close, }) out_lines = file("/proc/meminfo").readlines() self.AboutText = _("RAM") + '\n\n' RamTotal = "-" RamFree = "-" for lidx in range(len(out_lines) - 1): tstLine = out_lines[lidx].split() if "MemTotal:" in tstLine: MemTotal = out_lines[lidx].split() self.AboutText += _("Total memory:") + "\t" + MemTotal[1] + "\n" if "MemFree:" in tstLine: MemFree = out_lines[lidx].split() self.AboutText += _("Free memory:") + "\t" + MemFree[1] + "\n" if "Buffers:" in tstLine: Buffers = out_lines[lidx].split() self.AboutText += _("Buffers:") + "\t" + Buffers[1] + "\n" if "Cached:" in tstLine: Cached = out_lines[lidx].split() self.AboutText += _("Cached:") + "\t" + Cached[1] + "\n" if "SwapTotal:" in tstLine: SwapTotal = out_lines[lidx].split() self.AboutText += _("Total swap:") + "\t" + SwapTotal[1] + "\n" if "SwapFree:" in tstLine: SwapFree = out_lines[lidx].split() self.AboutText += _("Free swap:") + "\t" + SwapFree[1] + "\n\n" self["actions"].setEnabled(False) self.Console = Console() self.Console.ePopen("df -mh / | grep -v '^Filesystem'", self.Stage1Complete) def Stage1Complete(self, result, retval, extra_args=None): flash = str(result).replace('\n', '') flash = flash.split() RamTotal = flash[1] RamFree = flash[3] self.AboutText += _("FLASH") + '\n\n' self.AboutText += _("Total:") + "\t" + RamTotal + "\n" self.AboutText += _("Free:") + "\t" + RamFree + "\n\n" self["AboutScrollLabel"].setText(self.AboutText) self["actions"].setEnabled(True) def createSummary(self): return AboutSummary
class EmptySlot(): MOUNT = 0 UNMOUNT = 1 def __init__(self, Contents, callback): self.callback = callback self.container = Console() (self.firstslot, self.numberofslots, self.mtdboot) = SystemInfo["canMultiBoot"] if SystemInfo["HasSDmmc"]: self.numberofslots -= 1 self.slot = Contents if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') if SystemInfo["HasRootSubdir"]: self.part = "%s%s" % (self.mtdboot, GetCurrentRoot()) else: if SystemInfo[ "HasSDmmc"]: # allow for mmc & SDcard in passed slot number, so SDcard slot -1 self.slot -= 1 self.part = "%s%s" % (self.mtdboot, str(self.slot * 2 + self.firstslot)) if SystemInfo[ "HasSDmmc"] and self.slot == 0: # this is the mmc slot, so pick up from MtdRoot self.part = getMachineMtdRoot() self.phase = self.MOUNT self.run() def run(self): if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.islink( "/dev/block/by-name/linuxrootfs"): self.container.ePopen( 'mount /dev/block/by-name/linuxrootfs /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.container.ePopen( 'mount /dev/block/by-name/userdata /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.container.ePopen( 'mount /dev/%s /tmp/testmount' % self.part if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if SystemInfo["HasRootSubdir"]: if os.path.isfile( "/tmp/testmount/linuxrootfs%s/usr/bin/enigma2" % self.slot): os.rename( '/tmp/testmount/linuxrootfs%s/usr/bin/enigma2' % self.slot, '/tmp/testmount/linuxrootfs%s/usr/bin/enigmax.bin' % self.slot) else: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): os.rename('/tmp/testmount/usr/bin/enigma2', '/tmp/testmount/usr/bin/enigmax.bin') self.phase = self.UNMOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback()
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 NoRun = 0 # receivers only uses 1 media for multiboot FirstRun = 1 # receiver uses eMMC and SD card for multiboot - so handle SDcard slots 1st via SystemInfo(canMultiBoot) LastRun = 2 # receiver uses eMMC and SD card for multiboot - and then handle eMMC (currently one time) def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots) = SystemInfo["canMultiBoot"][:2] if SystemInfo["HasSDmmc"]: self.numberofslots -= 1 self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.slot2 = 1 if SystemInfo["HasSDmmc"]: self.SDmmc = self.FirstRun # process SDcard slots else: self.SDmmc = self.NoRun # only mmc slots self.phase = self.MOUNT self.part = SystemInfo["canMultiBoot"][2] # pick up slot type self.run() else: callback({}) def run(self): if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.islink( "/dev/block/by-name/linuxrootfs"): self.part2 = os.readlink("/dev/block/by-name/linuxrootfs")[5:] self.container.ePopen( 'mount /dev/block/by-name/linuxrootfs /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.part2 = os.readlink("/dev/block/by-name/userdata")[5:] self.container.ePopen( 'mount /dev/block/by-name/userdata /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' % self.part2 } else: if self.SDmmc == self.LastRun: self.part2 = getMachineMtdRoot() # process mmc slot self.slot2 = 1 else: self.part2 = "%s" % (self.part + str(self.slot * 2 + self.firstslot)) if self.SDmmc == self.FirstRun: self.slot2 += 1 # allow for mmc slot" if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' % self.part2 } self.container.ePopen( 'mount /dev/%s /tmp/testmount' % self.part2 if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: BuildVersion = " " Build = " " #ViX Build No.# Dev = " " #ViX Dev No.# Creator = " " #Openpli Openvix Openatv etc # Date = " " BuildType = " " #release etc # self.OsPath = "NoPath" if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.isfile( "/tmp/testmount/linuxrootfs1/usr/bin/enigma2"): self.OsPath = "/tmp/testmount/linuxrootfs1" elif os.path.isfile( "/tmp/testmount/linuxrootfs%s/usr/bin/enigma2" % self.slot): self.OsPath = "/tmp/testmount/linuxrootfs%s" % self.slot print "multiboot tools 1 slots", self.slot, self.slot2 else: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): self.OsPath = '/tmp/testmount' print "Tools/Multiboot OsPath %s " % self.OsPath if self.OsPath != "NoPath": try: Creator = open("%s/etc/issue" % self.OsPath).readlines( )[-2].capitalize().strip()[:-6].replace( "-release", " rel") except: Creator = _("unknow") if Creator.startswith("Openesi"): reader = boxbranding_reader(self.OsPath) BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild( ) or '' BuildVersionESI = "%s %s %s" % (Creator, BuildType[0:3], Build) BuildVersionESI = BuildVersionESI.replace("rel", "#") if Creator.startswith("Openpli"): build = [ x.split("-")[-2:-1][0][-8:] for x in open("%s/var/lib/opkg/info/openpli-bootlogo.control" % self.OsPath).readlines() if x.startswith("Version:") ] Date = "%s-%s-%s" % (build[0][6:], build[0][4:6], build[0][2:4]) BuildVersion = "%s %s" % (Creator, Date) elif Creator.startswith("Openvix"): reader = boxbranding_reader(self.OsPath) BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild( ) or '' BuildVersion = "%s %s %s %s" % (Creator, BuildType[0:3], Build, Dev) else: st = os.stat('%s/var/lib/opkg/status' % self.OsPath) tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: Date = time.strftime("%d.%m.%Y", tm) BuildVersion = _("%s release %s") % (Creator, Date) if Creator.startswith("Openesi"): BuildVersion = _("%s release %s") % (BuildVersionESI, Date) self.imagelist[self.slot2] = { 'imagename': '%s' % BuildVersion, 'part': '%s' % self.part2 } self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.slot2 = self.slot self.phase = self.MOUNT self.run() elif self.SDmmc == self.FirstRun: self.phase = self.MOUNT self.SDmmc = self.LastRun # processed SDcard now process mmc slot self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
def __init__(self, session, StandbyCounterIncrease=True): self.skinName = "Standby" Screen.__init__(self, session) self.avswitch = AVSwitch() print("[Standby] enter standby") SystemInfo["StandbyState"] = True if os.path.exists("/usr/script/standby_enter.sh"): Console().ePopen("/usr/script/standby_enter.sh") self["actions"] = ActionMap(["StandbyActions"], { "power": self.Power, "discrete_on": self.Power }, -1) globalActionMap.setEnabled(False) self.infoBarInstance = isInfoBarInstance() from Screens.SleepTimerEdit import isNextWakeupTime self.StandbyCounterIncrease = StandbyCounterIncrease self.standbyTimeoutTimer = eTimer() self.standbyTimeoutTimer.callback.append(self.standbyTimeout) self.standbyStopServiceTimer = eTimer() self.standbyStopServiceTimer.callback.append(self.stopService) self.standbyWakeupTimer = eTimer() self.standbyWakeupTimer.callback.append(self.standbyWakeup) self.timeHandler = None self.setMute() self.paused_service = self.paused_action = False self.prev_running_service = self.session.nav.getCurrentlyPlayingServiceOrGroup( ) if Components.ParentalControl.parentalControl.isProtected( self.prev_running_service): self.prev_running_service = eServiceReference( config.tv.lastservice.value) service = self.prev_running_service and self.prev_running_service.toString( ) if service: if service.rsplit(":", 1)[1].startswith("/"): self.paused_service = hasattr( self.session.current_dialog, "pauseService") and hasattr( self.session.current_dialog, "unPauseService" ) and self.session.current_dialog or self.infoBarInstance self.paused_action = hasattr( self.paused_service, "seekstate" ) and hasattr( self.paused_service, "SEEK_STATE_PLAY" ) and self.paused_service.seekstate == self.paused_service.SEEK_STATE_PLAY self.paused_action and self.paused_service.pauseService() if not self.paused_service: self.timeHandler = eDVBLocalTimeHandler.getInstance() if self.timeHandler.ready(): if self.session.nav.getCurrentlyPlayingServiceOrGroup(): self.stopService() else: self.standbyStopServiceTimer.startLongTimer(5) self.timeHandler = None else: self.timeHandler.m_timeUpdated.get().append(self.stopService) if self.session.pipshown: self.infoBarInstance and hasattr( self.infoBarInstance, "showPiP") and self.infoBarInstance.showPiP() if SystemInfo["ScartSwitch"]: self.avswitch.setInput("SCART") else: self.avswitch.setInput("AUX") if SystemInfo["HiSilicon"]: try: open("/proc/stb/hdmi/output", "w").write("off") except: pass if SystemInfo["AmlogicFamily"]: try: open("/sys/class/leds/led-sys/brightness", "w").write("0") except: pass try: open("/sys/class/cec/cmd", "w").write("0f 36") except: pass gotoShutdownTime = int(config.usage.standby_to_shutdown_timer.value) if gotoShutdownTime: self.standbyTimeoutTimer.startLongTimer(gotoShutdownTime) if self.StandbyCounterIncrease is not 1: gotoWakeupTime = isNextWakeupTime(True) if gotoWakeupTime != -1: curtime = localtime(time()) if curtime.tm_year > 1970: wakeup_time = int(gotoWakeupTime - time()) if wakeup_time > 0: self.standbyWakeupTimer.startLongTimer(wakeup_time) self.onFirstExecBegin.append(self.__onFirstExecBegin) self.onClose.append(self.__onClose)
def backupsettings(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" BACKUP_SCRIPT = "/usr/lib/enigma2/python/Plugins/Extensions/AutoBackup/settings-backup.sh" def findmedia(destination): def avail(path): if not (SystemInfo["HasMMC"] and '/mmc' in path) and not os.path.islink(path): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / ( 1 << 20) >= 500 and path except: pass for path in [destination] + getNonNetworkMediaMounts(): if avail(path): return path self.destination = findmedia( os.path.isfile(BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = "/".join([self.destination, 'downloaded_images']) self.zippedimage = "://" in self.source and "/".join( [destination, self.imagename]) or self.source self.unzippedimage = "/".join( [destination, '%s.unzipped' % self.imagename[:-4]]) if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if os.path.isfile(BACKUP_SCRIPT): self["info"].setText( _("Backing up to: %s") % self.destination) configfile.save() if config.plugins.autobackup.epgcache.value: eEPGCache.getInstance().save() self.containerbackup = Console() self.containerbackup.ePopen( "%s%s'%s' %s" % (BACKUP_SCRIPT, config.plugins.autobackup.autoinstall.value and " -a " or " ", self.destination, int(config.plugins.autobackup.prevbackup.value)), self.backupsettingsDone) else: self.session.openWithCallback( self.startDownload, MessageBox, _("Unable to backup settings as the AutoBackup plugin is missing, do you want to continue?" ), default=False, simple=True) else: self.startDownload() else: self.session.openWithCallback( self.abort, MessageBox, _("Could not find suitable media - Please insert a media (e.g. USB stick) and try again!" ), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort()
class SystemNetworkInfo(Screen): def __init__(self, session): Screen.__init__(self, session) self.setTitle(_("Network")) self.skinName = ["SystemNetworkInfo", "WlanStatus"] self["LabelBSSID"] = StaticText() self["LabelESSID"] = StaticText() self["LabelQuality"] = StaticText() self["LabelSignal"] = StaticText() self["LabelBitrate"] = StaticText() self["LabelEnc"] = StaticText() self["BSSID"] = StaticText() self["ESSID"] = StaticText() self["quality"] = StaticText() self["signal"] = StaticText() self["bitrate"] = StaticText() self["enc"] = StaticText() self["IFtext"] = StaticText() self["IF"] = StaticText() self["Statustext"] = StaticText() self["statuspic"] = MultiPixmap() self["statuspic"].setPixmapNum(1) self["statuspic"].show() self["devicepic"] = MultiPixmap() self["AboutScrollLabel"] = ScrollLabel() self.iface = None self.createscreen() self.iStatus = None if iNetwork.isWirelessInterface(self.iface): try: from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus self.iStatus = iStatus except: pass self.resetList() self.onClose.append(self.cleanup) self["key_red"] = StaticText(_("Close")) self["actions"] = ActionMap(["SetupActions", "ColorActions", "DirectionActions"], { "cancel": self.close, "ok": self.close, "up": self["AboutScrollLabel"].pageUp, "down": self["AboutScrollLabel"].pageDown }) self.onLayoutFinish.append(self.updateStatusbar) def createscreen(self): self.AboutText = "" self.iface = "eth0" eth0 = about.getIfConfig('eth0') if eth0.has_key('addr'): self.AboutText += _("IP:") + "\t" + eth0['addr'] + "\n" if eth0.has_key('netmask'): self.AboutText += _("Netmask:") + "\t" + eth0['netmask'] + "\n" if eth0.has_key('hwaddr'): self.AboutText += _("MAC:") + "\t" + eth0['hwaddr'] + "\n" self.iface = 'eth0' eth1 = about.getIfConfig('eth1') if eth1.has_key('addr'): self.AboutText += _("IP:") + "\t" + eth1['addr'] + "\n" if eth1.has_key('netmask'): self.AboutText += _("Netmask:") + "\t" + eth1['netmask'] + "\n" if eth1.has_key('hwaddr'): self.AboutText += _("MAC:") + "\t" + eth1['hwaddr'] + "\n" self.iface = 'eth1' ra0 = about.getIfConfig('ra0') if ra0.has_key('addr'): self.AboutText += _("IP:") + "\t" + ra0['addr'] + "\n" if ra0.has_key('netmask'): self.AboutText += _("Netmask:") + "\t" + ra0['netmask'] + "\n" if ra0.has_key('hwaddr'): self.AboutText += _("MAC:") + "\t" + ra0['hwaddr'] + "\n" self.iface = 'ra0' wlan0 = about.getIfConfig('wlan0') if wlan0.has_key('addr'): self.AboutText += _("IP:") + "\t" + wlan0['addr'] + "\n" if wlan0.has_key('netmask'): self.AboutText += _("Netmask:") + "\t" + wlan0['netmask'] + "\n" if wlan0.has_key('hwaddr'): self.AboutText += _("MAC:") + "\t" + wlan0['hwaddr'] + "\n" self.iface = 'wlan0' wlan3 = about.getIfConfig('wlan3') if wlan3.has_key('addr'): self.AboutText += _("IP:") + "\t" + wlan3['addr'] + "\n" if wlan3.has_key('netmask'): self.AboutText += _("Netmask:") + "\t" + wlan3['netmask'] + "\n" if wlan3.has_key('hwaddr'): self.AboutText += _("MAC:") + "\t" + wlan3['hwaddr'] + "\n" self.iface = 'wlan3' rx_bytes, tx_bytes = about.getIfTransferredData(self.iface) self.AboutText += "\n" + _("Bytes received:") + "\t" + rx_bytes + "\n" self.AboutText += _("Bytes sent:") + "\t" + tx_bytes + "\n" self.console = Console() self.console.ePopen('ethtool %s' % self.iface, self.SpeedFinished) def SpeedFinished(self, result, retval, extra_args): result_tmp = result.split('\n') for line in result_tmp: if 'Speed:' in line: speed = line.split(': ')[1][:-4] self.AboutText += _("Speed:") + "\t" + speed + _('Mb/s') hostname = file('/proc/sys/kernel/hostname').read() self.AboutText += "\n" + _("Hostname:") + "\t" + hostname + "\n" self["AboutScrollLabel"].setText(self.AboutText) def cleanup(self): if self.iStatus: self.iStatus.stopWlanConsole() def resetList(self): if self.iStatus: self.iStatus.getDataForInterface(self.iface, self.getInfoCB) def getInfoCB(self, data, status): self.LinkState = None if data is not None and data: if status is not None: # getDataForInterface()->iwconfigFinished() in # Plugins/SystemPlugins/WirelessLan/Wlan.py sets fields to boolean False # if there is no info for them, so we need to check that possibility # for each status[self.iface] field... # if self.iface == 'wlan0' or self.iface == 'wlan3' or self.iface == 'ra0': # accesspoint is used in the "enc" code too, so we get it regardless # if not status[self.iface]["accesspoint"]: accesspoint = _("Unknown") else: if status[self.iface]["accesspoint"] == "Not-Associated": accesspoint = _("Not-Associated") essid = _("No connection") else: accesspoint = status[self.iface]["accesspoint"] if self.has_key("BSSID"): self.AboutText += _('Accesspoint:') + '\t' + accesspoint + '\n' if self.has_key("ESSID"): if not status[self.iface]["essid"]: essid = _("Unknown") else: if status[self.iface]["essid"] == "off": essid = _("No connection") else: essid = status[self.iface]["essid"] self.AboutText += _('SSID:') + '\t' + essid + '\n' if self.has_key("quality"): if not status[self.iface]["quality"]: quality = _("Unknown") else: quality = status[self.iface]["quality"] self.AboutText += _('Link quality:') + '\t' + quality + '\n' if self.has_key("bitrate"): if not status[self.iface]["bitrate"]: bitrate = _("Unknown") else: if status[self.iface]["bitrate"] == '0': bitrate = _("Unsupported") else: bitrate = str(status[self.iface]["bitrate"]) + " Mb/s" self.AboutText += _('Bitrate:') + '\t' + bitrate + '\n' if self.has_key("signal"): if not status[self.iface]["signal"]: signal = _("Unknown") else: signal = status[self.iface]["signal"] self.AboutText += _('Signal strength:') + '\t' + signal + '\n' if self.has_key("enc"): if not status[self.iface]["encryption"]: encryption = _("Unknown") else: if status[self.iface]["encryption"] == "off": if accesspoint == "Not-Associated": encryption = _("Disabled") else: encryption = _("Unsupported") else: encryption = _("Enabled") self.AboutText += _('Encryption:') + '\t' + encryption + '\n' if ((status[self.iface]["essid"] and status[self.iface]["essid"] == "off") or not status[self.iface]["accesspoint"] or status[self.iface]["accesspoint"] == "Not-Associated"): self.LinkState = False self["statuspic"].setPixmapNum(1) self["statuspic"].show() else: self.LinkState = True iNetwork.checkNetworkState(self.checkNetworkCB) self["AboutScrollLabel"].setText(self.AboutText) def exit(self): self.close(True) def updateStatusbar(self): self["IFtext"].setText(_("Network:")) self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface)) self["Statustext"].setText(_("Link:")) if iNetwork.isWirelessInterface(self.iface): self["devicepic"].setPixmapNum(1) try: self.iStatus.getDataForInterface(self.iface, self.getInfoCB) except: self["statuspic"].setPixmapNum(1) self["statuspic"].show() else: iNetwork.getLinkState(self.iface, self.dataAvail) self["devicepic"].setPixmapNum(0) self["devicepic"].show() def dataAvail(self, data): self.LinkState = None for line in data.splitlines(): line = line.strip() if 'Link detected:' in line: if "yes" in line: self.LinkState = True else: self.LinkState = False if self.LinkState: iNetwork.checkNetworkState(self.checkNetworkCB) else: self["statuspic"].setPixmapNum(1) self["statuspic"].show() def checkNetworkCB(self, data): try: if iNetwork.getAdapterAttribute(self.iface, "up") is True: if self.LinkState is True: if data <= 2: self["statuspic"].setPixmapNum(0) else: self["statuspic"].setPixmapNum(1) else: self["statuspic"].setPixmapNum(1) else: self["statuspic"].setPixmapNum(1) self["statuspic"].show() except: pass def createSummary(self): return AboutSummary
class CronTimers(Screen): def __init__(self, session, menu_path=""): Screen.__init__(self, session) if not path.exists('/usr/scripts'): mkdir('/usr/scripts', 0755) screentitle = _("Cron Manager") menu_path += screentitle if config.usage.show_menupath.value == 'large': title = menu_path self["menu_path_compressed"] = StaticText("") elif config.usage.show_menupath.value == 'small': title = screentitle print 'menu_path:', menu_path self["menu_path_compressed"] = StaticText( menu_path + " >" if not menu_path.endswith(' / ') else menu_path[:-3] + " >" or "") else: title = screentitle self["menu_path_compressed"] = StaticText("") Screen.setTitle(self, title) self.onChangedEntry = [] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Active"))) self['labdisabled'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['labrun'].hide() self['labactive'].hide() self.summary_running = '' self['key'] = Label( _("H: = Hourly / D: = Daily / W: = Weekly / M: = Monthly")) self.Console = Console() self.my_crond_active = False self.my_crond_run = False self['key_red'] = Label(_("Delete")) self['key_green'] = Label(_("Add")) self['key_yellow'] = Label(_("Start")) self['key_blue'] = Label(_("Autostart")) self.list = [] self['list'] = List(self.list) self['actions'] = ActionMap( ['WizardActions', 'ColorActions', "MenuActions"], { 'ok': self.info, 'back': self.UninstallCheck, 'red': self.delcron, 'green': self.addtocron, 'yellow': self.CrondStart, 'blue': self.autostart, "menu": self.closeRecursive }) if not self.selectionChanged in self["list"].onSelectionChanged: self["list"].onSelectionChanged.append(self.selectionChanged) self.service_name = 'busybox-cron' self.onLayoutFinish.append(self.InstallCheck) def InstallCheck(self): self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def checkNetworkState(self, str, retval, extra_args): if 'Collected errors' in str: self.session.openWithCallback( self.close, MessageBox, _("A background update check is in progress, please wait a few minutes and try again." ), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif not str: if (getImageType() != 'release' and feedsstatuscheck.getFeedsBool() != 'unknown') or ( getImageType() == 'release' and feedsstatuscheck.getFeedsBool() not in ('stable', 'unstable')): self.session.openWithCallback( self.InstallPackageFailed, MessageBox, feedsstatuscheck.getFeedsErrorMessage(), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) else: self.session.openWithCallback( self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO) else: self.updateList() def InstallPackage(self, val): if val: self.doInstall(self.installComplete, self.service_name) else: self.close() def InstallPackageFailed(self, val): self.close() def doInstall(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Installing Service')) self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback) def installComplete(self, result=None, retval=None, extra_args=None): self.message.close() self.updateList() def UninstallCheck(self): if not self.my_crond_run: self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail) else: self.close() def RemovedataAvail(self, str, retval, extra_args): if str: self.session.openWithCallback( self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name) else: self.close() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) else: self.close() def doRemove(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Removing Service')) self.Console.ePopen( '/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback) def removeComplete(self, result=None, retval=None, extra_args=None): self.message.close() self.close() def createSummary(self): from Screens.PluginBrowser import PluginBrowserSummary return PluginBrowserSummary def selectionChanged(self): try: if self["list"].getCurrent(): name = str(self["list"].getCurrent()[0]) else: name = "" except: name = "" desc = _("Current Status:") + ' ' + self.summary_running for cb in self.onChangedEntry: cb(name, desc) def CrondStart(self): if not self.my_crond_run: self.Console.ePopen('/etc/init.d/busybox-cron start', self.StartStopCallback) elif self.my_crond_run: self.Console.ePopen('/etc/init.d/busybox-cron stop', self.StartStopCallback) def StartStopCallback(self, result=None, retval=None, extra_args=None): sleep(3) self.updateList() def autostart(self): if fileExists('/etc/rc2.d/S20busybox-cron'): self.Console.ePopen('update-rc.d -f busybox-cron remove') else: self.Console.ePopen('update-rc.d -f busybox-cron defaults') sleep(3) self.updateList() def addtocron(self): self.session.openWithCallback(self.updateList, CronTimersConfig) def updateList(self, result=None, retval=None, extra_args=None): import process p = process.ProcessList() crond_process = str(p.named('crond')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].hide() self['labdisabled'].hide() self.my_crond_active = False self.my_crond_run = False if path.exists('/etc/rc3.d/S20busybox-cron'): self['labdisabled'].hide() self['labactive'].show() self.my_crond_active = True else: self['labactive'].hide() self['labdisabled'].show() if crond_process: self.my_crond_run = True if self.my_crond_run: self['labstop'].hide() self['labrun'].show() self['key_yellow'].setText(_("Stop")) self.summary_running = _("Running") else: self['labstop'].show() self['labrun'].hide() self['key_yellow'].setText(_("Start")) self.summary_running = _("Stopped") self.list = [] if path.exists('/etc/cron/crontabs/root'): f = open('/etc/cron/crontabs/root', 'r') for line in f.readlines(): parts = line.strip().split() if parts: if parts[1] == '*': try: line2 = 'H: 00:' + parts[0].zfill( 2) + '\t' + parts[5] + parts[6] + parts[ 7] + parts[8] + parts[9] except: try: line2 = 'H: 00:' + parts[0].zfill( 2) + '\t' + parts[5] + parts[6] + parts[ 7] + parts[8] except: try: line2 = 'H: 00:' + parts[0].zfill( 2 ) + '\t' + parts[5] + parts[6] + parts[7] except: try: line2 = 'H: 00:' + parts[0].zfill( 2) + '\t' + parts[5] + parts[6] except: line2 = 'H: 00:' + parts[0].zfill( 2) + '\t' + parts[5] res = (line2, line) self.list.append(res) elif parts[2] == '*' and parts[4] == '*': try: line2 = 'D: ' + parts[1].zfill(2) + ':' + parts[ 0].zfill(2) + '\t' + parts[5] + parts[ 6] + parts[7] + parts[8] + parts[9] except: try: line2 = 'D: ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] + parts[8] except: try: line2 = 'D: ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] except: try: line2 = 'D: ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[6] except: line2 = 'D: ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] res = (line2, line) self.list.append(res) elif parts[3] == '*': if parts[4] == "*": try: line2 = 'M: Day ' + parts[2] + ' ' + parts[ 1].zfill(2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] + parts[8] + parts[9] except: try: line2 = 'M: Day ' + parts[ 2] + ' ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] + parts[8] except: try: line2 = 'M: Day ' + parts[ 2] + ' ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2 ) + '\t' + parts[5] + parts[ 6] + parts[7] except: try: line2 = 'M: Day ' + parts[ 2] + ' ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[ 5] + parts[6] except: line2 = 'M: Day ' + parts[ 2] + ' ' + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] header = 'W: ' day = "" if str(parts[4]).find('0') >= 0: day = 'Sun ' if str(parts[4]).find('1') >= 0: day += 'Mon ' if str(parts[4]).find('2') >= 0: day += 'Tues ' if str(parts[4]).find('3') >= 0: day += 'Wed ' if str(parts[4]).find('4') >= 0: day += 'Thurs ' if str(parts[4]).find('5') >= 0: day += 'Fri ' if str(parts[4]).find('6') >= 0: day += 'Sat ' if day: try: line2 = header + day + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] + parts[8] + parts[9] except: try: line2 = header + day + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] + parts[8] except: try: line2 = header + day + parts[1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] + parts[ 6] + parts[7] except: try: line2 = header + day + parts[ 1].zfill(2) + ':' + parts[ 0].zfill(2) + '\t' + parts[ 5] + parts[6] except: line2 = header + day + parts[ 1].zfill( 2) + ':' + parts[0].zfill( 2) + '\t' + parts[5] res = (line2, line) self.list.append(res) f.close() self['list'].list = self.list self["actions"].setEnabled(True) def delcron(self): self.sel = self['list'].getCurrent() if self.sel: parts = self.sel[0] parts = parts.split('\t') message = _("Are you sure you want to delete this:\n ") + parts[1] ybox = self.session.openWithCallback(self.doDelCron, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_("Remove Confirmation")) def doDelCron(self, answer): if answer: mysel = self['list'].getCurrent() if mysel: myline = mysel[1] file('/etc/cron/crontabs/root.tmp', 'w').writelines([ l for l in file('/etc/cron/crontabs/root').readlines() if myline not in l ]) rename('/etc/cron/crontabs/root.tmp', '/etc/cron/crontabs/root') rc = system( 'crontab /etc/cron/crontabs/root -c /etc/cron/crontabs') self.updateList() def info(self): mysel = self['list'].getCurrent() if mysel: myline = mysel[1] self.session.open(MessageBox, _(myline), MessageBox.TYPE_INFO) def closeRecursive(self): self.close(True)
def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "/usr/sbin/ethtool" self.ip_bin = "/sbin/ip" self.ifconfig_bin = "/sbin/ifconfig" self.ifdown_bin = "/sbin/ifdown" self.ifup_bin = "/sbin/ifup" self.ping_bin = "/bin/ping" self.nslookup_bin = "/usr/bin/nslookup" self.avahi_daemon = "/etc/init.d/avahi-daemon" self.networking_initd = "/etc/init.d/networking" self.console = Console() self.linkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.dnsConsole = Console() self.pingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces()
class Devices(Screen): def __init__(self, session): Screen.__init__(self, session) self.setTitle(_("Devices")) self["TunerHeader"] = StaticText(_("Detected tuners:")) self["HDDHeader"] = StaticText(_("Detected devices:")) self["MountsHeader"] = StaticText(_("Network servers:")) self["nims"] = StaticText() for count in (0, 1, 2, 3): self["Tuner" + str(count)] = StaticText("") self["hdd"] = StaticText() self["mounts"] = StaticText() self.list = [] self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.populate2) self["key_red"] = Button(_("Close")) self["actions"] = ActionMap(["SetupActions", "ColorActions", "TimerEditActions"], { "cancel": self.close, "ok": self.close, "red": self.close, }) self.onLayoutFinish.append(self.populate) def populate(self): self.mountinfo = '' self["actions"].setEnabled(False) scanning = _("Please wait while scanning for devices...") self["nims"].setText(scanning) for count in (0, 1, 2, 3): self["Tuner" + str(count)].setText(scanning) self["hdd"].setText(scanning) self['mounts'].setText(scanning) self.activityTimer.start(1) def populate2(self): self.activityTimer.stop() self.Console = Console() niminfo = "" nims = nimmanager.nimListCompressed() for count in range(len(nims)): if niminfo: niminfo += "\n" niminfo += nims[count] self["nims"].setText(niminfo) nims = nimmanager.nimList() if len(nims) <= 4 : for count in (0, 1, 2, 3): if count < len(nims): self["Tuner" + str(count)].setText(nims[count]) else: self["Tuner" + str(count)].setText("") else: desc_list = [] count = 0 cur_idx = -1 while count < len(nims): data = nims[count].split(":") idx = data[0].strip('Tuner').strip() desc = data[1].strip() if desc_list and desc_list[cur_idx]['desc'] == desc: desc_list[cur_idx]['end'] = idx else: desc_list.append({'desc' : desc, 'start' : idx, 'end' : idx}) cur_idx += 1 count += 1 for count in (0, 1, 2, 3): if count < len(desc_list): if desc_list[count]['start'] == desc_list[count]['end']: text = "Tuner %s: %s" % (desc_list[count]['start'], desc_list[count]['desc']) else: text = "Tuner %s-%s: %s" % (desc_list[count]['start'], desc_list[count]['end'], desc_list[count]['desc']) else: text = "" self["Tuner" + str(count)].setText(text) self.hddlist = harddiskmanager.HDDList() self.list = [] if self.hddlist: for count in range(len(self.hddlist)): hdd = self.hddlist[count][1] hddp = self.hddlist[count][0] if "ATA" in hddp: hddp = hddp.replace('ATA', '') hddp = hddp.replace('Internal', 'ATA Bus ') free = hdd.Totalfree() if ((float(free) / 1024) / 1024) >= 1: freeline = _("Free: ") + str(round(((float(free) / 1024) / 1024), 2)) + _("TB") elif (free / 1024) >= 1: freeline = _("Free: ") + str(round((float(free) / 1024), 2)) + _("GB") elif free >= 1: freeline = _("Free: ") + str(free) + _("MB") elif "Generic(STORAGE" in hddp: # This is the SDA boot volume for SF8008 if "full" # continue else: freeline = _("Free: ") + _("full") line = "%s %s" %(hddp, freeline) self.list.append(line) self.list = '\n'.join(self.list) self["hdd"].setText(self.list) self.Console.ePopen("df -mh | grep -v '^Filesystem'", self.Stage1Complete) def Stage1Complete(self, result, retval, extra_args=None): result = result.replace('\n ', ' ').split('\n') self.mountinfo = "" for line in result: self.parts = line.split() if line and self.parts[0] and (self.parts[0].startswith('192') or self.parts[0].startswith('//192')): line = line.split() ipaddress = line[0] mounttotal = line[1] mountfree = line[3] if self.mountinfo: self.mountinfo += "\n" self.mountinfo += "%s (%sB, %sB %s)" % (ipaddress, mounttotal, mountfree, _("free")) if pathExists("/media/autofs"): for entry in sorted(listdir("/media/autofs")): mountEntry = path.join("/media/autofs", entry) self.mountinfo += _("\n %s is also enabled for autofs network mount" % (mountEntry)) if self.mountinfo: self["mounts"].setText(self.mountinfo) else: self["mounts"].setText(_('none')) self["actions"].setEnabled(True) def createSummary(self): return AboutSummary
def __init__(self, session, menu_path=""): Screen.__init__(self, session) screentitle = _("OSD position") if config.usage.show_menupath.value == 'large': menu_path += screentitle title = menu_path self.setup_title = title self["menu_path_compressed"] = StaticText("") elif config.usage.show_menupath.value == 'small': title = screentitle self.setup_title = screentitle self["menu_path_compressed"] = StaticText( menu_path + " >" if not menu_path.endswith(' / ') else menu_path[:-3] + " >" or "") else: title = screentitle self.setup_title = title self["menu_path_compressed"] = StaticText("") self.Console = Console() self["status"] = StaticText() self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("OK")) self["key_yellow"] = StaticText(_("Defaults")) self["actions"] = ActionMap( ["SetupActions", "ColorActions"], { "cancel": self.keyCancel, "save": self.keySave, "left": self.keyLeft, "right": self.keyRight, "yellow": self.keyDefault, }, -2) self.onChangedEntry = [] self.list = [] ConfigListScreen.__init__(self, self.list, session=self.session, on_change=self.changedEntry) if SystemInfo["CanChangeOsdAlpha"]: self.list.append( getConfigListEntry( _("User interface visibility"), config.osd.alpha, _("This option lets you adjust the transparency of the user interface" ))) if SystemInfo["CanChangeOsdPosition"]: self.list.append( getConfigListEntry( _("Move Left/Right"), config.osd.dst_left, _("Use the LEFT/RIGHT buttons on your remote to move the user interface left/right." ))) self.list.append( getConfigListEntry( _("Width"), config.osd.dst_width, _("Use the LEFT/RIGHT buttons on your remote to adjust the width of the user interface. LEFT button decreases the size, RIGHT increases the size." ))) self.list.append( getConfigListEntry( _("Move Up/Down"), config.osd.dst_top, _("Use the LEFT/RIGHT buttons on your remote to move the user interface up/down." ))) self.list.append( getConfigListEntry( _("Height"), config.osd.dst_height, _("Use the LEFT/RIGHT buttons on your remote to adjust the height of the user interface. LEFT button decreases the size, RIGHT increases the size." ))) self["config"].list = self.list self["config"].l.setList(self.list) self.serviceRef = None self.onLayoutFinish.append(self.layoutFinished) if self.welcomeWarning not in self.onShow: self.onShow.append(self.welcomeWarning) if self.selectionChanged not in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.selectionChanged) self.selectionChanged()
def __init__(self, session): Screen.__init__(self, session) self.skinName = "Standby" self.avswitch = AVSwitch() print "[Standby] enter standby" if path.exists("/usr/scripts/standby_enter.sh"): Console().ePopen("/usr/scripts/standby_enter.sh") self["actions"] = ActionMap(["StandbyActions"], { "power": self.Power, "discrete_on": self.Power }, -1) globalActionMap.setEnabled(False) from Screens.InfoBar import InfoBar self.infoBarInstance = InfoBar.instance self.standbyStopServiceTimer = eTimer() self.standbyStopServiceTimer.callback.append(self.stopService) self.timeHandler = None self.setMute() if SystemInfo["Display"] and SystemInfo["LCDMiniTV"]: # set LCDminiTV off setLCDMiniTVMode("0") self.paused_service = self.paused_action = False self.prev_running_service = self.session.nav.getCurrentlyPlayingServiceOrGroup( ) if Components.ParentalControl.parentalControl.isProtected( self.prev_running_service): self.prev_running_service = eServiceReference( config.tv.lastservice.value) service = self.prev_running_service and self.prev_running_service.toString( ) if service: if service.rsplit(":", 1)[1].startswith("/"): self.paused_service = hasattr( self.session.current_dialog, "pauseService") and hasattr( self.session.current_dialog, "unPauseService" ) and self.session.current_dialog or self.infoBarInstance self.paused_action = hasattr( self.paused_service, "seekstate" ) and hasattr( self.paused_service, "SEEK_STATE_PLAY" ) and self.paused_service.seekstate == self.paused_service.SEEK_STATE_PLAY self.paused_action and self.paused_service.pauseService() if not self.paused_service: self.timeHandler = eDVBLocalTimeHandler.getInstance() if self.timeHandler.ready(): if self.session.nav.getCurrentlyPlayingServiceOrGroup(): self.stopService() else: self.standbyStopServiceTimer.startLongTimer(5) self.timeHandler = None else: self.timeHandler.m_timeUpdated.get().append(self.stopService) if self.session.pipshown: self.infoBarInstance and hasattr( self.infoBarInstance, "showPiP") and self.infoBarInstance.showPiP() if SystemInfo["ScartSwitch"]: self.avswitch.setInput("SCART") else: self.avswitch.setInput("AUX") if getBrandOEM() in ('dinobot') or SystemInfo["HasHiSi"]: try: open("/proc/stb/hdmi/output", "w").write("off") except: pass self.onFirstExecBegin.append(self.__onFirstExecBegin) self.onClose.append(self.__onClose)
def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "/usr/sbin/ethtool" self.console = Console() self.linkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.dnsConsole = Console() self.pingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces()
def download_subtitles(subtitles_list, pos, zip_subs, tmp_sub_dir, sub_folder, session_id, screen_session): #standard input #username = __settings__.getSetting( "ITuser" ) #password = __settings__.getSetting( "ITpass" ) username = config.plugins.subsdownloader.ItasaUser.value password = config.plugins.subsdownloader.ItasaPassword.value if login(username, password): log(__name__, " Login successful") id = subtitles_list[pos]["id"] link = subtitles_list[pos]["link"] content = geturl(main_url + link) match = re.search(subtitle_download_pattern % id, content, re.IGNORECASE | re.DOTALL) if match: language = subtitles_list[pos]["language_name"] log( __name__, " Fetching subtitles using url %s" % (main_url + match.group(1))) content = geturl(main_url + match.group(1)) if content is not None: header = content[:4] if header == 'Rar!': local_tmp_file = os.path.join(tmp_sub_dir, "undertexter.rar") packed = True elif header == 'PK': local_tmp_file = os.path.join(tmp_sub_dir, "undertexter.zip") packed = True else: # never found/downloaded an unpacked subtitles file, but just to be sure ... local_tmp_file = os.path.join( tmp_sub_dir, "undertexter.srt" ) # assume unpacked subtitels file is an '.srt' subs_file = local_tmp_file packed = False log(__name__, " Saving subtitles to '%s'" % (local_tmp_file)) try: local_file_handle = open(local_tmp_file, "wb") local_file_handle.write(content) local_file_handle.close() except: log(__name__, " Failed to save subtitles to '%s'" % (local_tmp_file)) if packed: if header == 'PK': zipped_file = zip_extractor(local_tmp_file, tmp_sub_dir) subs_file = zipped_file.extract_zipped_file() os.remove(local_tmp_file) if header == 'Rar!': if os.path.exists("/usr/bin/unrar"): files_before_unrar = list_directory_files( tmp_sub_dir) Console().ePopen('unrar -p- -y x %s %s' % (local_tmp_file, tmp_sub_dir)) files_after_unrar = list_directory_files( tmp_sub_dir) subs_file = new_file_in_directory( files_before_unrar, files_after_unrar) os.remove(local_tmp_file) else: from Components.Opkg import OpkgComponent from Screens.Opkg import Opkg __cmdList = [] __cmdList.append((OpkgComponent.CMD_INSTALL, { "package": 'unrar' })) screen_session.openWithCallback(__restartMessage__( screen_session, callback=None), Opkg, cmdList=__cmdList) return False, language, subs_file #standard output #log( __name__ ," Login to Itasa failed. Check your username/password at the addon configuration.") screen_session.open( MessageBox, _(" Login to Itasa failed. Check your username/password at the configuration menu." ), MessageBox.TYPE_INFO, timeout=5) return False, "None", []
def getAddrInet(self, iface, callback): if not self.Console: self.Console = Console() cmd = "busybox ip -o addr show dev " + iface + " | grep -v inet6" self.Console.ePopen(cmd, self.IPaddrFinished, [iface, callback])
def __init__(self): # Init Timer self.timer = eTimer() self.Console = Console()
def __init__(self, type): if DBG: j00zekDEBUG('[j00zekGetWebPic:__init__] >>>') Converter.__init__(self, type) self.refreshTimer = eTimer() self.refreshTimer.callback.append(self.getPic) self.myConsole = Console() self.isSuspended = False self.RefreshTimeMS = 10000 self.downloadCommand = 'curl -L https://picsum.photos/800 -o /tmp/randomWebPic.jpg' self.downloadToFile = '/tmp/randomWebPic.jpg' if os.path.exists(type): with open(type, 'r') as f: for line in f: line = line.strip() if line.startswith('#') or line == '' or not '=' in line: continue else: cfg = line.split('=') if cfg[0] == 'RefreshTime': self.RefreshTimeMS = int(cfg[1]) * 1000 elif cfg[0] == 'downloadCommand': self.downloadCommand = cfg[1] elif cfg[0] == 'downloadToFile': self.downloadToFile = cfg[1] f.close() elif type == '/etc/enigma2/user_webCam1.cfg': from Components.Language import language with open(type, 'w') as f: if language.getLanguage() == 'pl_PL': f.write("#Przykladowa konfiguracja WebCam-a\n") f.write( "# RefreshTime - czas w sekundach do odswierzenia obrazka\n" ) f.write( "# downloadCommand -komenda basha pobierajaca obrazek, musi byc dostosowana do kamery!!!\n" ) f.write( "# W znalezieniu poprawnego adresu pomoze strona https://www.ispyconnect.com/sources.aspx\n" ) f.write("# Przyklady:\n") f.write( "# kamery dahua:curl --user 'usr:passwd' 'http://192.168.1.102:80/cgi-bin/snapshot.cgi' --digest -o /tmp/WebCamSpanshot.jpg\n" ) f.write( '# strumien rtsp (ffmpeg musi być zainstalowany): ffmpeg -i "rtsp://*****:*****@15.15.15.15:1234/cam/realmonitor?channel=1&subtype=1" -ss 00:00:01 -f image2 -vframes 1 /tmp/WebCam1Spanshot.jpg\n' ) f.write( "# curl 'http://193.242.215.2:8001/axis-cgi/jpg/image.cgi' -o /tmp/WebCamSpanshot.jpg\n" ) f.write( "# downloadToFile - nazwa pliku do ktorego jest pobrany obrazek\n" ) else: f.write("#:Example webCam configuration\n") f.write( "# RefreshTime - time in seconds to refresh picture\n" ) f.write( "# downloadCommand - bash command to download picture\n" ) f.write( "# Use the https://www.ispyconnect.com/sources.aspx webpage to find correct URL\n" ) f.write("# Examples (depends on webcam functions):\n") f.write( "# dahua webcam image:curl --user 'usr:passwd' 'http://192.168.1.102:80/cgi-bin/snapshot.cgi' --digest -o /tmp/WebCamSpanshot.jpg\n" ) f.write( '# for rtsp stream (ffmpeg must be installed): ffmpeg -i "rtsp://*****:*****@15.15.15.15:1234/cam/realmonitor?channel=1&subtype=1" -ss 00:00:01 -f image2 -vframes 1 /tmp/WebCam1Spanshot.jpg\n' ) f.write( "# curl 'http://193.242.215.2:8001/axis-cgi/jpg/image.cgi' -o /tmp/WebCamSpanshot.jpg\n" ) f.write( "# downloadToFile - filename of downloaded picture\n") f.write("RefreshTime=10\n") f.write( "downloadCommand=curl -L https://picsum.photos/800 -o /tmp/randomWebPic.jpg\n" ) f.write("downloadToFile=/tmp/randomWebPic.jpg\n") f.close() if DBG: j00zekDEBUG( '\n\t read params: type="%s"\n\t\t self.RefreshTimeMS=%s, self.downloadCommand=%s,\n\t\t self.downloadToFile=%s' % (type, self.RefreshTimeMS, self.downloadCommand, self.downloadToFile)) self.lastFile = '%s.last.jpg' % self.downloadToFile MoveCMD = 'mv -f %s %s' % (self.downloadToFile, self.lastFile) rmCMD = 'rm -f %s' % self.lastFile self.runCMD = '%s;%s;%s' % (MoveCMD, self.downloadCommand, rmCMD) self.refreshTimer.start(100)
def setSleep(self): if self.bus() == _('External'): Console().ePopen(('sdparm', 'sdparm', '--flexible', '--readonly', '--command=stop', self.disk_path)) else: Console().ePopen(('hdparm', 'hdparm', '-y', self.disk_path))
class HddMount(Screen): skin = """ <screen position="center,center" size="640,460" title="Mount Manager"> <ePixmap pixmap="skin_default/buttons/red.png" position="25,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="175,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="325,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="475,0" size="140,40" alphatest="on" /> <widget name="key_red" position="25,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="175,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="325,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="key_blue" position="475,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" /> <widget source="list" render="Listbox" position="10,50" size="620,450" scrollbarMode="showOnDemand" > <convert type="TemplatedMultiContent"> {"template": [ MultiContentEntryText(pos = (90, 0), size = (600, 30), font=0, text = 0), MultiContentEntryText(pos = (110, 30), size = (600, 50), font=1, flags = RT_VALIGN_TOP, text = 1), MultiContentEntryPixmapAlphaBlend(pos = (0, 0), size = (80, 80), png = 2), ], "fonts": [gFont("Regular", 24),gFont("Regular", 20)], "itemHeight": 85 } </convert> </widget> <widget name="lab1" zPosition="2" position="50,90" size="600,40" font="Regular;22" halign="center" transparent="1"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Mount Manager")) self['key_red'] = Label(_("Save")) self['key_green'] = Label(_("Setup Mounts")) self['key_yellow'] = Label("Unmount") self['key_blue'] = Label("Mount") self['lab1'] = Label() self.onChangedEntry = [ ] self.list = [] self['list'] = List(self.list) self["list"].onSelectionChanged.append(self.selectionChanged) self['actions'] = ActionMap(['WizardActions', 'ColorActions', "MenuActions"], {'back': self.close, 'green': self.SetupMounts, 'ok': self.SetupMounts, 'red': self.saveMypoints, 'yellow': self.Unmount, 'blue': self.Mount, "menu": self.close}) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.updateList2) self.updateList() def createSummary(self): return DevicesPanelSummary def selectionChanged(self): if len(self.list) == 0: return self.sel = self['list'].getCurrent() try: mountp = self.sel[3] if mountp.find('/media/hdd') < 0: self["key_red"].setText(_("Use as HDD")) else: self["key_red"].setText(" ") except: pass if self.sel: try: name = str(self.sel[0]) desc = str(self.sel[1].replace('\t',' ')) except: name = "" desc = "" else: name = "" desc = "" for cb in self.onChangedEntry: cb(name, desc) def updateList(self, result = None, retval = None, extra_args = None): scanning = _("Wait please while scanning for devices...") self['lab1'].setText(scanning) self.activityTimer.start(10) def updateList2(self): self.activityTimer.stop() self.list = [] list2 = [] f = open('/proc/partitions', 'r') try: f = open('/proc/partitions', 'r') fd = open('/proc/mounts', 'r') mnt = fd.readlines() fd.close() except: self['list'].list = self.list self['lab1'].hide() self.selectionChanged() return for line in f.readlines(): mount_list =[] parts = line.strip().split() if not parts: continue device = parts[3] if not search('sd[a-z][1-9]',device) and not search('mmcblk[0-9]p[1-9]',device): continue if getMachineBuild() in ('sf5008','et13000','et1x000','vuuno4k', 'vuultimo4k', 'vusolo4k', 'hd51', 'hd52', 'dm820', 'dm7080', 'sf4008', 'dm900', 'dm920', 'gb7252', 'dags7252', 'vs1500','h7','8100s') and search('mmcblk0p[1-9]',device): continue if getMachineBuild() in ('xc7439') and search('mmcblk1p[1-9]',device): continue if getMachineBuild() in ('u5') and search('mmcblk1p[1]',device): continue if device in list2: continue self.buildMy_rec(device) list2.append(device) f.close() self['list'].list = self.list self['lab1'].hide() def buildMy_rec(self, device): device2 = '' try: if device.find('1') > 1: device2 = device.replace('1', '') except: device2 = '' try: if device.find('2') > 1: device2 = device.replace('2', '') except: device2 = '' try: if device.find('3') > 1: device2 = device.replace('3', '') except: device2 = '' try: if device.find('4') > 1: device2 = device.replace('4', '') except: device2 = '' try: if device.find('5') > 1: device2 = device.replace('5', '') except: device2 = '' try: if device.find('6') > 1: device2 = device.replace('6', '') except: device2 = '' try: if device.find('7') > 1: device2 = device.replace('7', '') except: device2 = '' try: if device.find('8') > 1: device2 = device.replace('8', '') except: device2 = '' try: if device.find('p1') > 1: device2 = device.replace('p1', '') except: device2 = '' try: if device.find('p2') > 1: device2 = device.replace('p2', '') except: device2 = '' try: if device.find('p3') > 1: device2 = device.replace('p3', '') except: device2 = '' try: if device.find('p4') > 1: device2 = device.replace('p4', '') except: device2 = '' try: if device.find('p5') > 1: device2 = device.replace('p5', '') except: device2 = '' try: if device.find('p6') > 1: device2 = device.replace('p6', '') except: device2 = '' try: if device.find('p7') > 1: device2 = device.replace('p7', '') except: device2 = '' try: if device.find('p8') > 1: device2 = device.replace('p8', '') except: device2 = '' devicetype = path.realpath('/sys/block/' + device2 + '/device') d2 = device name = 'USB: ' mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/LDteam/images/icons/dev_usbstick.png' if device2.startswith('mmcblk'): model = file('/sys/block/' + device2 + '/device/name').read() mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/LDteam/images/icons/dev_mmc.png' name = 'MMC: ' else: model = file('/sys/block/' + device2 + '/device/model').read() model = str(model).replace('\n', '') des = '' if devicetype.find('/devices/pci') != -1 or devicetype.find('ahci') != -1: name = _("HARD DISK: ") mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/LDteam/images/icons/dev_hdd.png' name = name + model self.Console = Console() self.Console.ePopen("sfdisk -l | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp") sleep(0.5) try: f = open('/tmp/devices.tmp', 'r') swapdevices = f.read() f.close() except: swapdevices = ' ' if path.exists('/tmp/devices.tmp'): remove('/tmp/devices.tmp') swapdevices = swapdevices.replace('\n','') swapdevices = swapdevices.split('/') f = open('/proc/mounts', 'r') for line in f.readlines(): if line.find(device) != -1: parts = line.strip().split() d1 = parts[1] dtype = parts[2] rw = parts[3] break continue else: if device in swapdevices: parts = line.strip().split() d1 = _("None") dtype = 'swap' rw = _("None") break continue else: d1 = _("None") dtype = _("unavailable") rw = _("None") f.close() f = open('/proc/partitions', 'r') for line in f.readlines(): if line.find(device) != -1: parts = line.strip().split() size = int(parts[2]) if (((float(size) / 1024) / 1024) / 1024) > 1: des = _("Size: ") + str(round((((float(size) / 1024) / 1024) / 1024),2)) + _("TB") elif ((size / 1024) / 1024) > 1: des = _("Size: ") + str((size / 1024) / 1024) + _("GB") else: des = _("Size: ") + str(size / 1024) + _("MB") else: try: size = file('/sys/block/' + device2 + '/' + device + '/size').read() size = str(size).replace('\n', '') size = int(size) except: size = 0 if ((((float(size) / 2) / 1024) / 1024) / 1024) > 1: des = _("Size: ") + str(round(((((float(size) / 2) / 1024) / 1024) / 1024),2)) + _("TB") elif (((size / 2) / 1024) / 1024) > 1: des = _("Size: ") + str(((size / 2) / 1024) / 1024) + _("GB") else: des = _("Size: ") + str((size / 2) / 1024) + _("MB") f.close() if des != '': if rw.startswith('rw'): rw = ' R/W' elif rw.startswith('ro'): rw = ' R/O' else: rw = "" des += '\t' + _("Mount: ") + d1 + '\n' + _("Device: ") + '/dev/' + device + '\t' + _("Type: ") + dtype + rw png = LoadPixmap(mypixmap) mountP = d1 deviceP = '/dev/' + device res = (name, des, png, mountP, deviceP) self.list.append(res) def SetupMounts(self): self.session.openWithCallback(self.updateList, DevicePanelConf) def Mount(self): sel = self['list'].getCurrent() if sel: mountp = sel[3] device = sel[4] system ('mount ' + device) mountok = False f = open('/proc/mounts', 'r') for line in f.readlines(): if line.find(device) != -1: mountok = True if not mountok: self.session.open(MessageBox, _("Mount failed"), MessageBox.TYPE_INFO, timeout=5) self.updateList() def Unmount(self): sel = self['list'].getCurrent() if sel: mountp = sel[3] device = sel[4] system ('umount ' + mountp) try: mounts = open("/proc/mounts") except IOError: return -1 mountcheck = mounts.readlines() mounts.close() for line in mountcheck: parts = line.strip().split(" ") if path.realpath(parts[0]).startswith(device): self.session.open(MessageBox, _("Can't unmount partiton, make sure it is not being used for swap or record/timeshift paths"), MessageBox.TYPE_INFO) self.updateList() def saveMypoints(self): sel = self['list'].getCurrent() if sel: self.mountp = sel[3] self.device = sel[4] if self.mountp.find('/media/hdd') < 0: self.Console.ePopen('umount ' + self.device) if not path.exists('/media/hdd'): mkdir('/media/hdd', 0755) else: self.Console.ePopen('umount /media/hdd') self.Console.ePopen('mount ' + self.device + ' /media/hdd') self.Console.ePopen("/sbin/blkid | grep " + self.device, self.add_fstab, [self.device, self.mountp]) else: self.session.open(MessageBox, _("This Device is already mounted as HDD."), MessageBox.TYPE_INFO, timeout = 10, close_on_any_key = True) def add_fstab(self, result = None, retval = None, extra_args = None): self.device = extra_args[0] self.mountp = extra_args[1] self.device_uuid_tmp = result.split('UUID=') if str(self.device_uuid_tmp) != "['']": self.device_uuid_tmp = self.device_uuid_tmp[1].replace('TYPE="ext2"','').replace('TYPE="ext3"','').replace('TYPE="ext4"','').replace('TYPE="ntfs"','').replace('TYPE="exfat"','').replace('TYPE="vfat"','').replace('TYPE="fat"','').replace('TYPE="fat16"','').replace('TYPE="fat32"','').replace('TYPE="xfs"','').replace('"','') self.device_uuid_tmp = self.device_uuid_tmp.replace('\n',"") self.device_uuid_tmp = self.device_uuid_tmp.split()[0] self.device_uuid = 'UUID=' + self.device_uuid_tmp if not path.exists(self.mountp): mkdir(self.mountp, 0755) file('/etc/fstab.tmp', 'w').writelines([l for l in file('/etc/fstab').readlines() if '/media/hdd' not in l]) rename('/etc/fstab.tmp','/etc/fstab') file('/etc/fstab.tmp', 'w').writelines([l for l in file('/etc/fstab').readlines() if self.device not in l]) rename('/etc/fstab.tmp','/etc/fstab') file('/etc/fstab.tmp', 'w').writelines([l for l in file('/etc/fstab').readlines() if self.device_uuid not in l]) rename('/etc/fstab.tmp','/etc/fstab') out = open('/etc/fstab', 'a') line = self.device_uuid + ' /media/hdd auto defaults,rw,relatime,noatime,nodiratime,barrier=1,data=ordered 0 0\n' out.write(line) out.close() self.Console.ePopen('mount /media/hdd', self.updateList) def restBo(self, answer): if answer is True: self.session.open(TryQuitMainloop, 2) else: self.updateList() self.selectionChanged()
def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface)
def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console()
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface) def iwconfigFinished(self, result, retval, extra_args): iface = extra_args data = { 'essid': False, 'frequency': False, 'accesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False } for line in result.splitlines(): line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = "off" else: if "Nickname" in line: ssid = (line[line.index('ESSID') + 7:line.index('" Nickname')]) else: ssid = (line[line.index('ESSID') + 7:len(line) - 1]) if ssid is not None: data['essid'] = ssid if "Frequency" in line: frequency = line[line.index('Frequency') + 10:line.index(' GHz')] if frequency is not None: data['frequency'] = frequency if "Access Point" in line: if "Sensitivity" in line: ap = line[line.index('Access Point') + 14:line.index(' Sensitivity')] else: ap = line[line.index('Access Point') + 14:len(line)] if ap is not None: data['accesspoint'] = ap if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate') + 9:line.index(' kb/s')] else: br = line[line.index('Bit Rate') + 9:line.index(' Mb/s')] if br is not None: data['bitrate'] = br if "Encryption key" in line: if ":off" in line: enc = "off" elif "Security" in line: enc = line[line.index('Encryption key') + 15:line.index(' Security')] if enc is not None: enc = "on" else: enc = line[line.index('Encryption key') + 15:len(line)] if enc is not None: enc = "on" if enc is not None: data['encryption'] = enc if 'Quality' in line: if "/100" in line: qual = line[line.index('Quality') + 8:line.index(' Signal')] else: qual = line[line.index('Quality') + 8:line.index('Sig')] if qual is not None: data['quality'] = qual if 'Signal level' in line: if "dBm" in line: signal = line[line.index('Signal level') + 13:line.index(' dBm')] + " dBm" elif "/100" in line: if "Noise" in line: signal = line[line.index('Signal level') + 13:line.index(' Noise')] else: signal = line[line.index('Signal level') + 13:len(line)] else: if "Noise" in line: signal = line[line.index('Signal level') + 13:line.index(' Noise')] else: signal = line[line.index('Signal level') + 13:len(line)] if signal is not None: data['signal'] = signal self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if len(self.WlanConsole.appContainers) == 0: print "[Wlan.py] self.wlaniface after loading:", self.wlaniface if self.statusCallback is not None: self.statusCallback(True, self.wlaniface) self.statusCallback = None def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.wlaniface.has_key(self.iface): if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None
class FlashImage(Screen): skin = """<screen position="center,center" size="640,150" flags="wfNoBorder" backgroundColor="#54242424"> <widget name="header" position="5,10" size="e-10,50" font="Regular;40" backgroundColor="#54242424"/> <widget name="info" position="5,60" size="e-10,130" font="Regular;24" backgroundColor="#54242424"/> <widget name="progress" position="5,e-39" size="e-10,24" backgroundColor="#54242424"/> </screen>""" def __init__(self, session, imagename, source): Screen.__init__(self, session) self.containerbackup = None self.containerofgwrite = None self.getImageList = None self.downloader = None self.source = source self.imagename = imagename self["header"] = Label(_("Backup settings")) self["info"] = Label(_("Save settings and EPG data")) self["progress"] = ProgressBar() self["progress"].setRange((0, 100)) self["progress"].setValue(0) self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "cancel": self.abort, "red": self.abort, }, -1) self.delay = eTimer() self.delay.callback.append(self.confirmation) self.delay.start(0, True) self.hide() def confirmation(self): recordings = self.session.nav.getRecordings() if not recordings: next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime() if recordings or (next_rec_time > 0 and (next_rec_time - time.time()) < 360): self.message = _( "Recording(s) are in progress or coming up in few seconds!\nDo you still want to flash image\n%s?" ) % self.imagename else: self.message = _("Do you want to flash image\n%s") % self.imagename if SystemInfo["canMultiBoot"]: self.getImageList = GetImagelist(self.getImagelistCallback) else: choices = [(_("Yes, with backup"), "with backup"), (_("No, do not flash image"), False), (_("Yes, without backup"), "without backup")] self.session.openWithCallback(self.backupsettings, MessageBox, self.message, list=choices, default=False, simple=True) def getImagelistCallback(self, imagedict): self.getImageList = None choices = [] currentimageslot = GetCurrentImage() for x in range(1, 5): if x in imagedict: choices.append( ((_("slot%s - %s (current image) with, backup") if x == currentimageslot else _("slot%s - %s, with backup")) % (x, imagedict[x]['imagename']), (x, "with backup"))) else: choices.append( (_("slot%s - empty, with backup") % x, (x, "with backup"))) choices.append((_("No, do not flash image"), False)) for x in range(1, 5): if x in imagedict: choices.append( ((_("slot%s - %s (current image), without backup") if x == currentimageslot else _("slot%s - %s, without backup")) % (x, imagedict[x]['imagename']), (x, "without backup"))) else: choices.append((_("slot%s - empty, without backup") % x, (x, "without backup"))) self.session.openWithCallback(self.backupsettings, MessageBox, self.message, list=choices, default=currentimageslot, simple=True) def backupsettings(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" BACKUP_SCRIPT = "/usr/lib/enigma2/python/Plugins/Extensions/AutoBackup/settings-backup.sh" def findmedia(destination): def avail(path): if not (SystemInfo["HasMMC"] and '/mmc' in path) and not os.path.islink(path): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / ( 1 << 20) >= 500 and path except: pass for path in [destination] + getNonNetworkMediaMounts(): if avail(path): return path self.destination = findmedia( os.path.isfile(BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = "/".join([self.destination, 'downloaded_images']) self.zippedimage = "://" in self.source and "/".join( [destination, self.imagename]) or self.source self.unzippedimage = "/".join( [destination, '%s.unzipped' % self.imagename[:-4]]) if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if os.path.isfile(BACKUP_SCRIPT): self["info"].setText( _("Backing up to: %s") % self.destination) configfile.save() if config.plugins.autobackup.epgcache.value: eEPGCache.getInstance().save() self.containerbackup = Console() self.containerbackup.ePopen( "%s%s'%s' %s" % (BACKUP_SCRIPT, config.plugins.autobackup.autoinstall.value and " -a " or " ", self.destination, int(config.plugins.autobackup.prevbackup.value)), self.backupsettingsDone) else: self.session.openWithCallback( self.startDownload, MessageBox, _("Unable to backup settings as the AutoBackup plugin is missing, do you want to continue?" ), default=False, simple=True) else: self.startDownload() else: self.session.openWithCallback( self.abort, MessageBox, _("Could not find suitable media - Please insert a media (e.g. USB stick) and try again!" ), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort() def backupsettingsDone(self, data, retval, extra_args): self.containerbackup = None if retval == 0: self.startDownload() else: self.session.openWithCallback( self.abort, MessageBox, _("Error during backup settings\n%s") % reval, type=MessageBox.TYPE_ERROR, simple=True) def startDownload(self, reply=True): self.show() if reply: if "://" in self.source: from Tools.Downloader import downloadWithProgress self["header"].setText(_("Downloading Image")) self["info"].setText(self.imagename) self.downloader = downloadWithProgress(self.source, self.zippedimage) self.downloader.addProgress(self.downloadProgress) self.downloader.addEnd(self.downloadEnd) self.downloader.addError(self.downloadError) self.downloader.start() else: self.unzip() else: self.abort() def downloadProgress(self, current, total): self["progress"].setValue(int(100 * current / total)) def downloadError(self, reason, status): self.downloader.stop() self.session.openWithCallback( self.abort, MessageBox, _("Error during downloading image\n%s\n%s") % (self.imagename, reason), type=MessageBox.TYPE_ERROR, simple=True) def downloadEnd(self): self.downloader.stop() self.unzip() def unzip(self): try: zipfile.ZipFile(self.zippedimage, 'r').extractall(self.unzippedimage) self.flashimage() except: self.session.openWithCallback( self.abort, MessageBox, _("Error during unzipping image\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def flashimage(self): def findimagefiles(path): for path, subdirs, files in os.walk(path): if not subdirs and files: return checkimagefiles(files) and path imagefiles = findimagefiles(self.unzippedimage) if imagefiles: if SystemInfo["canMultiBoot"]: command = "/usr/bin/ofgwrite -k -r -m%s '%s'" % ( self.multibootslot, imagefiles) else: command = "/usr/bin/ofgwrite -k -r '%s'" % imagefiles self.containerofgwrite = Console() self.containerofgwrite.ePopen(command, self.FlashimageDone) else: self.session.openWithCallback( self.abort, MessageBox, _("Image to install is invalid\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def FlashimageDone(self, data, retval, extra_args): self.containerofgwrite = None if retval == 0: self["header"].setText(_("Flashing image succesfull")) self["info"].setText(_("%s\nPress exit to close") % self.imagename) self["progress"].hide() else: self.session.openWithCallback( self.abort, MessageBox, _("Flashing image was not succesfull\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def abort(self, reply=None): if self.getImageList or self.containerofgwrite: return 0 if self.downloader: self.downloader.stop() if self.containerbackup: self.containerbackup.killAll() self.close()
def setSleep(self): if self.bus() == _("External"): Console().ePopen(("sdparm", "sdparm", "--flexible", "--readonly", "--command=stop", self.disk_path)) else: Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))