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)
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()
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
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 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 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
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 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')
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): # 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)
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.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 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)
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)
class OnErrorRestart: def __init__(self, session): self.Console = Console() self.session = session self.error = False self.timercount = 0 self.Timer = eTimer() self.Timer.callback.append(self.checklog) def StartLongTimer(self): print "[OnErrorRestartService] start long timer" self.Timer.start(20000, False) def StartFastTimer(self): print "[OnErrorRestartService] check error, start fast timer" self.Timer.start(3000, False) def checklog(self): self.Console.ePopen('dmesg -c | grep "Error-pti_task"' , self.checkerror) def checkerror(self, result, retval, extra_args): if result.strip(): if self.error: print "[OnErrorRestartService] restart service" self.error = False service = self.session.nav.getCurrentlyPlayingServiceOrGroup() if service: self.session.nav.stopService() self.session.nav.playService(service) self.ResetTimer() else: self.error = True self.Timer.stop() self.timercount += 1 self.StartFastTimer() elif self.timercount > 0: if self.timercount < 11: self.timercount += 1 else: self.ResetTimer() def ResetTimer(self): self.timercount = 0 self.error = False self.Timer.stop() self.StartLongTimer()
class NetworkSambaLog(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Samba Log")) self.skinName = "NetworkLog" self['infotext'] = ScrollLabel('') self.Console = Console() self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'up': self['infotext'].pageUp, 'down': self['infotext'].pageDown}) strview = '' self.Console.ePopen('tail /tmp/smb.log > /tmp/tmp.log') time.sleep(1) if fileExists('/tmp/tmp.log'): f = open('/tmp/tmp.log', 'r') for line in f.readlines(): strview += line f.close() remove('/tmp/tmp.log') self['infotext'].setText(strview)
class StartSwap: def __init__(self): self.Console = Console() def start(self): self.Console.ePopen("parted -l /dev/sd? | grep swap", self.startSwap2) def startSwap2(self, result=None, retval=None, extra_args=None): swap_place = "" if result and result.find('sd') != -1: for line in result.split('\n'): if line.find('sd') != -1: parts = line.strip().split() swap_place = parts[0] tmpfile = file('/etc/fstab.tmp', 'w') fstabfile = file('/etc/fstab') tmpfile.writelines([l for l in fstabfile.readlines() if swap_place not in l]) rename('/etc/fstab.tmp', '/etc/fstab') tmpfile.close() fstabfile.close() print "[SwapManager] Found a swap partition:", swap_place else: devicelist = [] for p in harddiskmanager.getMountedPartitions(): d = path.normpath(p.mountpoint) if path.exists(p.mountpoint) and p.mountpoint != "/" and not p.mountpoint.startswith('/media/net'): devicelist.append((p.description, d)) if len(devicelist): for device in devicelist: for filename in glob(device[1] + '/swap*'): if path.exists(filename): swap_place = filename print "[SwapManager] Found a swapfile on ", swap_place f = file('/proc/swaps') swapfile = f.read() if swapfile.find(swap_place) == -1: print "[SwapManager] Starting swapfile on ", swap_place system('swapon ' + swap_place) else: print "[SwapManager] Swapfile is already active on ", swap_place f.close()
class MountDevice: def __init__(self): self.Console = Console() def Mount(self, device, dirpath, enableswap = False): dir = "" self.enableswap = enableswap for line in dirpath[1:].split("/"): dir += "/" + line if not os.path.exists(dir): try: os.mkdir(dir) print "[HddManager] mkdir", dir except: print "[HddManager] Failed to mkdir", dir if os.path.exists("/bin/ntfs-3g"): self.Console.ePopen("sfdisk -l /dev/sd? | grep NTFS", self.__CheckNtfs, [device, dirpath]) else: self.__StartMount("mount " + device + " " + dirpath) def __CheckNtfs(self, result, retval, extra_args): (device, dirpath) = extra_args cmd = "mount " for line in result.splitlines(): if line and line[:9] == device: for line in __ReadMounts(): if device in line[0]: self.Console.ePopen("umount -f " + device) break cmd = "ntfs-3g " cmd += device + " " + dirpath self.__StartMount(cmd) def __StartMount(self, cmd): if self.enableswap: self.enableswap = False self.Console.ePopen(cmd, self.EnableSwap) else: self.Console.ePopen(cmd) def EnableSwap(self, result=None, retval=None, extra_args=None): if os.path.exists("/media/hdd/swapfile"): Console().ePopen("swapon /media/hdd/swapfile") else: print "[HddManager] not found /media/hdd/swapfile" sleep(5) if os.path.exists("/media/hdd/swapfile"): Console().ePopen("swapon /media/hdd/swapfile") else: print "[HddManager] not found /media/hdd/swapfile" self.enableswap = True
class NetworkSambaLog(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Samba Log")) self.skinName = "NetworkLog" self["infotext"] = ScrollLabel("") self.Console = Console() self["actions"] = ActionMap( ["WizardActions", "ColorActions"], {"ok": self.close, "back": self.close, "up": self["infotext"].pageUp, "down": self["infotext"].pageDown}, ) strview = "" self.Console.ePopen("tail /tmp/smb.log > /tmp/tmp.log") time.sleep(1) if fileExists("/tmp/tmp.log"): f = open("/tmp/tmp.log", "r") for line in f.readlines(): strview += line f.close() remove("/tmp/tmp.log") self["infotext"].setText(strview)
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.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 SABnzbdSetupScreen(Screen): skin = """ <screen position="center,center" size="560,310" title="Samba Setup"> <widget name="lab1" position="20,90" size="150,30" font="Regular;20" valign="center" transparent="0"/> <widget name="labactive" position="180,90" size="250,30" font="Regular;20" valign="center" transparent="0"/> <widget name="lab2" position="20,160" size="150,30" font="Regular;20" valign="center" transparent="0"/> <widget name="labstop" position="180,160" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/> <widget name="labrun" position="180,160" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/> <ePixmap pixmap="buttons/red.png" position="0,260" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/green.png" position="140,260" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/yellow.png" position="280,260" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/blue.png" position="420,260" size="140,40" alphatest="on" /> <widget name="key_red" position="0,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="140,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="280,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="key_blue" position="420,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("SABnzbd Setup")) self.skinName = "NetworkServiceSetup" self.onChangedEntry = [] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['key_red'] = Label(_("Remove Service")) self['key_green'] = Label(_("Start")) self['key_yellow'] = Label(_("Autostart")) self['key_blue'] = Label() self['status_summary'] = StaticText() self['autostartstatus_summary'] = StaticText() self.Console = Console() self.my_sabnzbd_active = False self.my_sabnzbd_run = False self['actions'] = ActionMap( ['WizardActions', 'ColorActions'], { 'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.SABnzbdStartStop, 'yellow': self.activateSABnzbd }) self.service_name = ("sabnzbd3" if sys.version_info[0] >= 3 else "sabnzbd") self.onLayoutFinish.append(self.InstallCheck) def InstallCheck(self): self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.InstalldataAvail) def InstalldataAvail(self, str, retval, extra_args): str = six.ensure_str(str) if not str: restartbox = self.session.openWithCallback( self.InstallPackage, MessageBox, _('Your %s %s will be restarted after the installation of service.\n\nDo you want to install now ?' ) % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO) restartbox.setTitle( _('Ready to install "%s" ?') % self.service_name) else: self.updateService() def InstallPackage(self, val): if val: self.doInstall(self.installComplete, self.service_name) else: self.close() def doInstall(self, callback, pkgname): self["actions"].setEnabled(False) self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO) self.message.setTitle(_('Installing Service')) self.Console.ePopen('/usr/bin/opkg install ' + pkgname + ' sync', callback) def installComplete(self, result=None, retval=None, extra_args=None): self["actions"].setEnabled(True) from Screens.Standby import TryQuitMainloop self.session.open(TryQuitMainloop, 2) def UninstallCheck(self): self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.UninstalldataAvail) def UninstalldataAvail(self, str, retval, extra_args): str = six.ensure_str(str) if str: restartbox = self.session.openWithCallback( self.RemovePackage, MessageBox, _('Your %s %s will be restarted after the removal of service\nDo you want to remove now ?' ) % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO) restartbox.setTitle( _('Ready to remove "%s" ?') % self.service_name) else: self.updateService() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) def doRemove(self, callback, pkgname): self["actions"].setEnabled(False) self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO) self.message.setTitle(_('Removing Service')) self.Console.ePopen( '/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove sync', callback) def removeComplete(self, result=None, retval=None, extra_args=None): self["actions"].setEnabled(True) from Screens.Standby import TryQuitMainloop self.session.open(TryQuitMainloop, 2) def createSummary(self): from Screens.NetworkSetup import NetworkServicesSummary return NetworkServicesSummary def SABnzbdStartStop(self): if not self.my_sabnzbd_run: self.Console.ePopen('/etc/init.d/sabnzbd start') time.sleep(3) self.updateService() elif self.my_sabnzbd_run: self.Console.ePopen('/etc/init.d/sabnzbd stop') time.sleep(3) self.updateService() def activateSABnzbd(self): if fileExists('/etc/rc2.d/S20sabnzbd'): self.Console.ePopen('update-rc.d -f sabnzbd remove') else: self.Console.ePopen('update-rc.d -f sabnzbd defaults') time.sleep(3) self.updateService() def updateService(self, result=None, retval=None, extra_args=None): import process p = process.ProcessList() sabnzbd_process = str(p.named('SABnzbd.py')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].setText(_("Disabled")) self.my_sabnzbd_active = False self.my_sabnzbd_run = False if fileExists('/etc/rc2.d/S20sabnzbd'): self['labactive'].setText(_("Enabled")) self['labactive'].show() self.my_sabnzbd_active = True if sabnzbd_process: self.my_sabnzbd_run = True if self.my_sabnzbd_run: self['labstop'].hide() self['labactive'].show() self['labrun'].show() self['key_green'].setText(_("Stop")) status_summary = self['lab2'].text + ' ' + self['labrun'].text else: self['labrun'].hide() self['labstop'].show() self['labactive'].show() self['key_green'].setText(_("Start")) status_summary = self['lab2'].text + ' ' + self['labstop'].text title = _("SABnzbd Setup") autostartstatus_summary = self['lab1'].text + ' ' + self[ 'labactive'].text for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary)
class j00zekGetWebPic(Converter, object): 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 getPic(self): if DBG: j00zekDEBUG('[j00zekGetWebPic:getPic] >>>') self.refreshTimer.stop() if isINETworking(): try: with open("/proc/sys/vm/drop_caches", "w") as f: f.write("1\n") self.myConsole.ePopen(self.runCMD) #os.system('rm -f %s;%s &' % (self.downloadToFile, self.downloadCommand)) except Exception as e: if DBG: j00zekDEBUG('j00zekGetWebPic:getPic] got Exception: %s' % str(e)) self.refreshTimer.start(self.RefreshTimeMS) def doSuspend(self, suspended): if suspended == 1: self.refreshTimer.stop() self.isSuspended = True try: if os.path.exists('%s.last.jpg' % self.downloadToFile): os.remove('%s.last.jpg' % self.downloadToFile) if os.path.exists(self.downloadToFile): os.remove(self.downloadToFile) except Exception as e: if DBG: j00zekDEBUG('[j00zekGetWebPic:doSuspend] Exception: %s' % str(e)) else: if self.isSuspended: if DBG: j00zekDEBUG( '[j00zekGetWebPic:doSuspend] initiates refreshTimer') self.refreshTimer.start(100) self.isSuspended = False @cached def getText(self): retVal = '' if os.path.exists(self.downloadToFile): retVal = self.downloadToFile if DBG: j00zekDEBUG('[j00zekGetWebPic:getText] newFile = %s' % self.downloadToFile) elif os.path.exists(self.lastFile): retVal = self.lastFile if DBG: j00zekDEBUG('[j00zekGetWebPic:getText] lastFile = %s' % self.downloadToFile) return retVal text = property(getText)
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()
class NetworkInstalledApp(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Installed Networkplugins")) self.skinName = ["SystemNetworkInfo", "About"] OpenNFRVersion = _("OpenNFR %s") % about.getImageVersionString() self["OpenNFRVersion"] = Label(OpenNFRVersion) self["AboutScrollLabel"] = ScrollLabel() self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, }) self.AboutText = _( "List of Networkplugins with Installedinfo") + '\n\n' self.InstallCheck() def InstallCheck(self): self.Console = Console() self.Console.ePopen('/usr/bin/opkg list_installed ', self.checkNetworkState) def checkNetworkState(self, str, retval, extra_args): import subprocess import os os.system('ps -ef > /tmp/ps.txt') ftp_process = subprocess.getoutput("grep -i vsftpd /tmp/ps.txt") telnetd_process = subprocess.getoutput("grep -i telnetd /tmp/ps.txt") ipv6_process = subprocess.getoutput( "cat /proc/sys/net/ipv6/conf/all/disable_ipv6") afp_process = subprocess.getoutput("grep -i afpd /tmp/ps.txt") sabnzbd_process = subprocess.getoutput("grep -i SABnzbd /tmp/ps.txt") nfs_process = subprocess.getoutput("grep -i nfsd /tmp/ps.txt") openvpn_process = subprocess.getoutput("grep -i openvpn /tmp/ps.txt") samba_process = subprocess.getoutput("grep -i smbd /tmp/ps.txt") inadyn_process = subprocess.getoutput("grep -i inadyn-mt /tmp/ps.txt") ushare_process = subprocess.getoutput("grep -i ushare /tmp/ps.txt") minidlna_process = subprocess.getoutput( "grep -i minidlnad /tmp/ps.txt") str = six.ensure_str(str) xtext1 = _(": \t Installed and running") + "\n" xtext2 = _(": \t Installed and not running") + "\n" if ftp_process: self.AboutText += _("FTP") + xtext1 else: self.AboutText += _("FTP") + xtext2 if telnetd_process: self.AboutText += _("Telnet") + xtext1 else: self.AboutText += _("Telnet") + xtext2 if ipv6_process == "0": self.AboutText += _("IPV6") + xtext1 else: self.AboutText += _("IPV6") + xtext2 if '-appletalk netatalk' in str: if afp_process: self.AboutText += _("Appletalk Netatalk") + xtext1 else: self.AboutText += _("Appletalk Netatalk") + xtext2 if 'sabnzbd3' in str: if sabnzbd_process: self.AboutText += _("SABnzbd") + xtext1 else: self.AboutText += _("SABnzbd") + xtext2 if '-nfs' in str: if nfs_process: self.AboutText += _("NFS") + xtext1 else: self.AboutText += _("NFS") + xtext2 if 'openvpn' in str: if openvpn_process: self.AboutText += _("OpenVPN") + xtext1 else: self.AboutText += _("OpenVPN") + xtext2 if '-smbfs-server' in str: if samba_process: self.AboutText += _("Samba") + xtext1 else: self.AboutText += _("Samba") + xtext2 if 'inadyn-mt' in str: if inadyn_process: self.AboutText += _("Inadyn") + xtext1 else: self.AboutText += _("Inadyn") + xtext2 if 'ushare' in str: if ushare_process: self.AboutText += _("uShare") + xtext1 else: self.AboutText += _("uShare") + xtext2 if 'minidlna' in str: if minidlna_process: self.AboutText += _("MiniDLNA") + xtext1 else: self.AboutText += _("MiniDLNA") + xtext2 self["AboutScrollLabel"].setText(self.AboutText) self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, })
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>""" BACKUP_SCRIPT = "/usr/lib/enigma2/python/Plugins/Extensions/AutoBackup/settings-backup.sh" 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.reasons = getReasons(session) 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, "ok": self.ok, "green": self.ok, }, -1) self.delay = eTimer() self.delay.callback.append(self.confirmation) self.delay.start(0, True) self.hide() def confirmation(self): if self.reasons: self.message = _("%s\nDo you still want to flash image\n%s?") % ( self.reasons, 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"), (_("Yes, without backup"), "without backup"), (_("No, do not flash image"), False)] self.session.openWithCallback(self.checkMedia, MessageBox, self.message, list=choices, default=False, simple=True) def getImagelistCallback(self, imagedict): self.getImageList = None choices = [] currentimageslot = GetCurrentImage() for x in range(1, SystemInfo["canMultiBoot"][1] + 1): 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"))) for x in range(1, SystemInfo["canMultiBoot"][1] + 1): 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"))) choices.append((_("No, do not flash image"), False)) self.session.openWithCallback(self.checkMedia, MessageBox, self.message, list=choices, default=currentimageslot, simple=True) def checkMedia(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" def findmedia(path): def avail(path): if not '/mmc' in path and os.path.isdir( path) and os.access(path, os.W_OK): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / (1 << 20) except: pass def checkIfDevice(path, diskstats): st_dev = os.stat(path).st_dev return (os.major(st_dev), os.minor(st_dev)) in diskstats diskstats = [(int(x[0]), int(x[1])) for x in [ x.split()[0:3] for x in open('/proc/diskstats').readlines() ] if x[2].startswith("sd")] if os.path.isdir(path) and checkIfDevice( path, diskstats) and avail(path) > 500: return (path, True) mounts = [] devices = [] for path in ['/media/%s' % x for x in os.listdir('/media')] + ([ '/media/net/%s' % x for x in os.listdir('/media/net') ] if os.path.isdir('/media/net') else []): if checkIfDevice(path, diskstats): devices.append((path, avail(path))) else: mounts.append((path, avail(path))) devices.sort(key=lambda x: x[1], reverse=True) mounts.sort(key=lambda x: x[1], reverse=True) return ((devices[0][1] > 500 and (devices[0][0], True)) if devices else mounts and mounts[0][1] > 500 and (mounts[0][0], False)) or (None, None) self.destination, isDevice = findmedia( os.path.isfile(self.BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = os.path.join(self.destination, 'downloaded_images') self.zippedimage = "://" in self.source and os.path.join( destination, self.imagename) or self.source self.unzippedimage = os.path.join( destination, '%s.unzipped' % self.imagename[:-4]) try: if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if isDevice: self.startBackupsettings(True) else: self.session.openWithCallback( self.startBackupsettings, MessageBox, _("Can only find a network drive to store the backup this means after the flash the autorestore will not work. Alternativaly you can mount the network drive after the flash and perform a manufacurer reset to autorestore" ), simple=True) else: self.startDownload() except: self.session.openWithCallback( self.abort, MessageBox, _("Could not some setup the required directories on the media (e.g. USB stick) - Please verify media and try again!" ), type=MessageBox.TYPE_ERROR, simple=True) else: self.session.openWithCallback( self.abort, MessageBox, _("Could not find suitable media - Please remove some downloaded images or insert a media (e.g. USB stick) with sufficiant free space and try again!" ), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort() def startBackupsettings(self, retval): if retval: if os.path.isfile(self.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" % (self.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.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): self["header"].setText(_("Unzipping Image")) self["info"].setText("%s\n%s" % (self.imagename, _("Please wait"))) self["progress"].hide() self.delay.callback.remove(self.confirmation) self.delay.callback.append(self.doUnzip) self.delay.start(0, True) def doUnzip(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): self["header"].setText(_("Flashing Image")) 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 successful")) self["info"].setText( _("%s\nPress ok for multiboot selection\nPress exit to close") % self.imagename) else: self.session.openWithCallback( self.abort, MessageBox, _("Flashing image was not successful\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 ok(self): if self["header"].text == _("Flashing image successful"): self.session.openWithCallback(self.abort, MultibootSelection) else: return 0
class SwapCheck: def __init__(self, callback=None, extra_args=None): self.Console = Console() if not extra_args: extra_args = [] self.extra_args = extra_args self.callback = callback self.retry = 0 if self.callback: self.MemCheck1() def MemCheck1(self): global swapdevice path = bigStorage(9000000) if path: swapdevice = os.path.join(path, 'swapfile_tmp') print '[SwapCheck] Location:', swapdevice if os.path.exists(swapdevice): print '[SwapCheck] Removing old swapfile' self.Console.ePopen('swapoff ' + swapdevice + ' && rm ' + swapdevice) f = open('/proc/meminfo', 'r') for line in f.readlines(): if line.find('MemFree') != -1: parts = line.strip().split() memfree = int(parts[1]) elif line.find('SwapFree') != -1: parts = line.strip().split() swapfree = int(parts[1]) f.close() TotalFree = memfree + swapfree print '[SwapCheck] Free Mem', TotalFree if int(TotalFree) < 5000: print '[SwapCheck] Not Enough Ram' self.MemCheck2() else: print '[SwapCheck] Found Enough Ram' if self.extra_args: self.callback(self.extra_args) else: self.callback() elif self.extra_args: self.callback(self.extra_args) else: self.callback() def MemCheck2(self): print '[SwapCheck] Creating Swapfile' self.Console.ePopen( 'dd if=/dev/zero of=' + swapdevice + ' bs=1024 count=16440', self.MemCheck3) def MemCheck3(self, result, retval, extra_args=None): if retval == 0: self.Console.ePopen('mkswap ' + swapdevice, self.MemCheck4) else: self.retry += 1 if self.retry < 5: self.Console.ePopen( 'dd if=/dev/zero of=' + swapdevice + ' bs=1024 count=16440', self.MemCheck3) elif self.extra_args: self.callback(self.extra_args) else: self.callback() def MemCheck4(self, result, retval, extra_args=None): if retval == 0: self.Console.ePopen('swapon ' + swapdevice, self.MemCheck5) def MemCheck5(self, result, retval, extra_args=None): if self.extra_args: self.callback(self.extra_args) else: self.callback() def RemoveSwap(self): if swapdevice and os.path.exists(swapdevice): print '[SwapCheck] Removing Swapfile', swapdevice self.Console.ePopen('swapoff ' + swapdevice + ' && rm ' + swapdevice)
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 CIHelper(Screen): 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) def CIHelperStartStop(self): if not self.my_cihelper_run: self.Console.ePopen('/etc/init.d/cihelper.sh start', self.StartStopCallback) elif self.my_cihelper_run: self.Console.ePopen('/etc/init.d/cihelper.sh stop', self.StartStopCallback) def StartStopCallback(self, result=None, retval=None, extra_args=None): time.sleep(5) self.updateService() def CIHelperset(self): if fileExists('/etc/rcS.d/S50cihelper.sh') or fileExists( '/etc/rc4.d/S50cihelper.sh'): self.Console.ePopen('update-rc.d -f cihelper.sh remove', self.StartStopCallback) else: self.Console.ePopen('update-rc.d -f -s cihelper.sh start 50 S .', self.StartStopCallback) def updateService(self): import process p = process.ProcessList() cihelper_process = str(p.named('cihelper')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].hide() self['labdisabled'].hide() self.my_cihelper_active = False self.my_cihelper_run = False if fileExists('/etc/rcS.d/S50cihelper.sh') or fileExists( '/etc/rc4.d/S50cihelper.sh'): self['labdisabled'].hide() self['labactive'].show() self.my_cihelper_active = True autostartstatus_summary = self['autostart'].text + ' ' + self[ 'labactive'].text else: self['labactive'].hide() self['labdisabled'].show() autostartstatus_summary = self['autostart'].text + ' ' + self[ 'labdisabled'].text if cihelper_process: self.my_cihelper_run = True if self.my_cihelper_run: self['labstop'].hide() self['labrun'].show() self['key_green'].setText(_('Stop')) status_summary = self['status'].text + ' ' + self['labstop'].text else: self['labstop'].show() self['labrun'].hide() self['key_green'].setText(_('Start')) status_summary = self['status'].text + ' ' + self['labstop'].text if fileExists('/etc/cihelper.conf'): f = open('/etc/cihelper.conf', 'r') for line in f.readlines(): line = line.strip() if line.startswith('ENABLE_CI0='): if line[11:] == 'no': self['ci0active'].hide() self['ci0inactive'].show() else: self['ci0active'].show() self['ci0inactive'].hide() elif fileExists('/dev/ci1'): if line.startswith('ENABLE_CI1='): if line[11:] == 'no': self['ci1active'].hide() self['ci1inactive'].show() else: self['ci1active'].show() self['ci1inactive'].hide() else: self['ci1active'].hide() self['ci1inactive'].hide() self['ci1'].hide() f.close() title = _('CIHelper Setup') for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary) def setupcihelper(self): self.session.openWithCallback(self.updateService, CIHelperSetup)
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
class MultiBootSelector(Screen, HelpableScreen): skinTemplate = """ <screen title="MultiBoot Image Selector" position="center,center" size="%d,%d"> <widget name="config" position="%d,%d" size="%d,%d" font="Regular;%d" itemHeight="%d" scrollbarMode="showOnDemand" /> <widget source="options" render="Label" position="%d,e-160" size="%d,%d" font="Regular;%d" halign="center" valign="center" /> <widget source="description" render="Label" position="%d,e-90" size="%d,%d" font="Regular;%d" /> <widget source="key_red" render="Label" position="%d,e-50" size="%d,%d" backgroundColor="key_red" font="Regular;%d" foregroundColor="key_text" halign="center" noWrap="1" valign="center" /> <widget source="key_green" render="Label" position="%d,e-50" size="%d,%d" backgroundColor="key_green" font="Regular;%d" foregroundColor="key_text" halign="center" noWrap="1" valign="center" /> </screen>""" scaleData = [ 800, 485, 10, 10, 780, 306, 24, 34, 10, 780, 60, 20, 10, 780, 30, 22, 10, 140, 40, 20, 160, 140, 40, 20 ] skin = None def __init__(self, session, *args): Screen.__init__(self, session) HelpableScreen.__init__(self) if MultiBootSelector.skin is None: # The skin template is designed for a HD screen so the scaling factor is 720. MultiBootSelector.skin = MultiBootSelector.skinTemplate % tuple([ x * getDesktop(0).size().height() / 720 for x in MultiBootSelector.scaleData ]) Screen.setTitle(self, _("MultiBoot Image Selector")) self["config"] = ChoiceList(list=[ ChoiceEntryComponent("", ( (_("Retrieving image slots - Please wait...")), "Queued")) ]) self["options"] = StaticText( _("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work." ) if SystemInfo["canMode12"] else "") self["description"] = StaticText( _("Use the cursor keys to select an installed image and then Reboot button." )) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Reboot")) self["actions"] = HelpableActionMap( self, [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "red": (boundFunction(self.close, None), _("Cancel the image selection and exit")), "green": (self.reboot, _("Select the highlighted image and reboot")), "ok": (self.reboot, _("Select the highlighted image and reboot")), "cancel": (boundFunction(self.close, None), _("Cancel the image selection and exit")), "up": (self.keyUp, _("Move up a line")), "down": (self.keyDown, _("Move down a line")), "left": (self.keyLeft, _("Move up a line")), "right": (self.keyRight, _("Move down a line")), "upRepeated": (self.keyUp, _("Move up a line")), "downRepeated": (self.keyDown, _("Move down a line")), "leftRepeated": (self.keyLeft, _("Move up a line")), "rightRepeated": (self.keyRight, _("Move down a line")), "menu": (boundFunction(self.close, True), _("Cancel the image selection and exit all menus")) }, -1, description=_("MultiBootSelector Actions")) imagedict = [] self.getImageList = None self.mountDir = "/tmp/startupmount" self.callLater(self.getBootOptions) def cancel(self, value=None): self.container = Console() self.container.ePopen("umount %s" % self.mountDir, boundFunction(self.unmountCallback, value)) def unmountCallback(self, value, data=None, retval=None, extra_args=None): self.container.killAll() if not path.ismount(self.mountDir): rmdir(self.mountDir) self.close(value) def getBootOptions(self, value=None): self.container = Console() if path.isdir(self.mountDir) and path.ismount(self.mountDir): self.getImagesList() else: if not path.isdir(self.mountDir): mkdir(self.mountDir) self.container.ePopen( "mount %s %s" % (SystemInfo["MBbootdevice"], self.mountDir), self.getImagesList) def getImagesList(self, data=None, retval=None, extra_args=None): self.container.killAll() self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagedict): list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() print "[MultiBootSelector] reboot1 slot:", currentimageslot current = " %s" % _("(current image)") slotSingle = _("Slot %s: %s%s") slotMulti = _("Slot %s: %s - Mode %d%s") if imagedict: indextot = 0 for index, x in enumerate(sorted(imagedict.keys())): if imagedict[x]["imagename"] != _("Empty slot"): if SystemInfo["canMode12"]: list.insert( index, ChoiceEntryComponent( "", (slotMulti % (x, imagedict[x]["imagename"], 1, current if x == currentimageslot and mode != 12 else ""), (x, 1)))) list.append( ChoiceEntryComponent("", ( slotMulti % (x, imagedict[x]["imagename"], 12, current if x == currentimageslot and mode == 12 else ""), (x, 12)))) indextot = index + 1 else: list.append( ChoiceEntryComponent( "", (slotSingle % (x, imagedict[x]["imagename"], current if x == currentimageslot else ""), (x, 1)))) if SystemInfo["canMode12"]: list.insert(indextot, " ") else: list.append( ChoiceEntryComponent("", ((_("No images found")), "Waiter"))) self["config"].setList(list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() self.slot = self.currentSelected[0][1] if self.currentSelected[0][1] != "Queued": slot = self.currentSelected[0][1][0] boxmode = self.currentSelected[0][1][1] print "[MultiBootSelector] reboot2 reboot slot = %s, " % slot print "[MultiBootSelector] reboot2 reboot boxmode = %s, " % boxmode print "[MultiBootSelector] reboot3 slotinfo = %s" % SystemInfo[ "canMultiBoot"] if SystemInfo["canMode12"]: if "BOXMODE" in SystemInfo["canMultiBoot"][slot][ 'startupfile']: startupfile = path.join( self.mountDir, "%s_%s" % (SystemInfo["canMultiBoot"][slot] ['startupfile'].rsplit('_', 1)[0], boxmode)) copyfile(startupfile, path.join(self.mountDir, "STARTUP")) else: f = open( path.join( self.mountDir, SystemInfo["canMultiBoot"][slot]['startupfile']), "r").read() if boxmode == 12: f = f.replace("boxmode=1'", "boxmode=12'").replace( "%s" % SystemInfo["canMode12"][0], "%s" % SystemInfo["canMode12"][1]) open(path.join(self.mountDir, "STARTUP"), "w").write(f) else: copyfile( path.join(self.mountDir, SystemInfo["canMultiBoot"][slot]["startupfile"]), path.join(self.mountDir, "STARTUP")) if SystemInfo["canDualBoot"]: with open('/dev/block/by-name/flag', 'wb') as f: f.write(struct.pack("B", int(slot))) self.session.open(TryQuitMainloop, QUIT_REBOOT) def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
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 UserInterfacePositioner(Screen, ConfigListScreen): def __init__(self, session): Screen.__init__(self, session) self.setup_title = _("Position Setup") 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 inyterface left/right" ))) self.list.append( getConfigListEntry( _("Width"), config.osd.dst_width, _("Use the Left/Right buttons on your remote to adjust the size 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 size 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.onLayoutFinish.append(self.layoutFinished) if not self.selectionChanged 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)) self.Console.ePopen( '/usr/bin/showiframe /usr/share/enigma2/hd-testcard.mvi') 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) 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) print '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() 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 NetworkSamba(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Samba Setup")) self.skinName = "NetworkSamba" self.onChangedEntry = [ ] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['key_green'] = Label(_("Start")) self['key_red'] = Label(_("Remove Service")) self['key_yellow'] = Label(_("Autostart")) self['key_blue'] = Label(_("Show Log")) self.Console = Console() self.my_Samba_active = False self.my_Samba_run = False self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.SambaStartStop, 'yellow': self.activateSamba, 'blue': self.Sambashowlog}) self.service_name = basegroup + '-smbfs-server' 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: self.feedscheck = self.session.open(MessageBox,_('Please wait while 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.updateService() 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.QuestionCallback, MessageBox,_('Your %s %s will be restarted after the installation of service.\nReady to install %s ?') % (getMachineBrand(), getMachineName(), self.service_name), MessageBox.TYPE_YESNO) def QuestionCallback(self, val): if val: self.session.openWithCallback(self.InstallPackage, MessageBox, _('Do you want to also install samba client?\nThis allows you to mount your windows shares on this device.'), MessageBox.TYPE_YESNO) else: self.feedscheck.close() self.close() def InstallPackage(self, val): if val: self.service_name = self.service_name + ' ' + basegroup + '-smbfs-client' self.doInstall(self.installComplete, self.service_name) 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.session.open(TryQuitMainloop, 2) def UninstallCheck(self): self.service_name = self.service_name + ' ' + basegroup + '-smbfs-client' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail) def RemovedataAvail(self, str, retval, extra_args): if str: restartbox = self.session.openWithCallback(self.RemovePackage,MessageBox,_('Your %s %s will be restarted after the removal of service.\nDo you want to remove now ?') % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO) restartbox.setTitle(_('Ready to remove %s ?') % self.service_name) else: self.updateService() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) 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.session.open(TryQuitMainloop, 2) def createSummary(self): return NetworkServicesSummary def Sambashowlog(self): self.session.open(NetworkSambaLog) def SambaStartStop(self): commands = [] if not self.my_Samba_run: commands.append('/etc/init.d/samba start') elif self.my_Samba_run: commands.append('/etc/init.d/samba stop') commands.append('killall nmbd') commands.append('killall smbd') self.Console.eBatch(commands, self.StartStopCallback, debug=True) def StartStopCallback(self, result = None, retval = None, extra_args = None): time.sleep(3) self.updateService() def activateSamba(self): commands = [] if fileExists('/etc/rc2.d/S20samba'): commands.append('update-rc.d -f samba remove') else: commands.append('update-rc.d -f samba defaults') self.Console.eBatch(commands, self.StartStopCallback, debug=True) def updateService(self): import process p = process.ProcessList() samba_process = str(p.named('smbd')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].setText(_("Disabled")) self.my_Samba_active = False if fileExists('/etc/rc2.d/S20samba'): self['labactive'].setText(_("Enabled")) self['labactive'].show() self.my_Samba_active = True self.my_Samba_run = False if samba_process: self.my_Samba_run = True if self.my_Samba_run: self['labstop'].hide() self['labactive'].show() self['labrun'].show() self['key_green'].setText(_("Stop")) status_summary = self['lab2'].text + ' ' + self['labrun'].text else: self['labrun'].hide() self['labstop'].show() self['labactive'].show() self['key_green'].setText(_("Start")) status_summary = self['lab2'].text + ' ' + self['labstop'].text title = _("Samba Setup") autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary)
class Wlan: def __init__(self, iface): a = '' b = '' for i in range(0, 255): a = a + chr(i) if i < 32 or i > 127: b = b + ' ' else: b = b + chr(i) self.iface = iface self.wlaniface = {} self.WlanConsole = Console() self.asciitrans = maketrans(a, b) def stopWlanConsole(self): if self.WlanConsole is not None: print "killing self.WlanConsole" self.WlanConsole = None del self.WlanConsole def getDataForInterface(self, callback=None): #get ip out of ip addr, as avahi sometimes overrides it in ifconfig. print "self.iface im getDataForInterface", self.iface if len(self.WlanConsole.appContainers) == 0: self.WlanConsole = Console() cmd = "iwconfig " + self.iface self.WlanConsole.ePopen(cmd, self.iwconfigFinished, callback) def iwconfigFinished(self, result, retval, extra_args): print "self.iface im iwconfigFinished", self.iface callback = extra_args data = { 'essid': False, 'frequency': False, 'acesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False } #print "result im iwconfigFinished",result for line in result.splitlines(): #print "line",line line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = _("No Connection") else: tmpssid = (line[line.index('ESSID') + 7:len(line) - 1]) if tmpssid == '': ssid = _("Hidden networkname") elif tmpssid == ' ': ssid = _("Hidden networkname") else: ssid = tmpssid #print "SSID->",ssid if ssid is not None: data['essid'] = ssid if 'Frequency' in line: frequency = line[line.index('Frequency') + 10:line.index(' GHz')] #print "Frequency",frequency if frequency is not None: data['frequency'] = frequency if "Access Point" in line: ap = line[line.index('Access Point') + 14:len(line) - 1] #print "AP",ap if ap is not None: data['acesspoint'] = ap if "Bit Rate" in line: br = line[line.index('Bit Rate') + 9:line.index(' Mb/s')] #print "Bitrate",br if br is not None: data['bitrate'] = br if 'Encryption key' in line: if ":off" in line: enc = _("Disabled") else: enc = line[line.index('Encryption key') + 15:line.index(' Security')] #print "Encryption key",enc if enc is not None: data['encryption'] = _("Enabled") if 'Quality' in line: if "/100" in line: qual = line[line.index('Quality') + 8:line.index('/100')] else: qual = line[line.index('Quality') + 8:line.index('Sig')] #print "Quality",qual if qual is not None: data['quality'] = qual if 'Signal level' in line: signal = line[line.index('Signal level') + 14:line.index(' dBm')] #print "Signal level",signal if signal is not None: data['signal'] = signal self.wlaniface[self.iface] = data if len(self.WlanConsole.appContainers) == 0: print "self.wlaniface after loading:", self.wlaniface self.WlanConsole = None if callback is not None: callback(True, self.wlaniface) def getAdapterAttribute(self, attribute): print "im getAdapterAttribute" if self.wlaniface.has_key(self.iface): print "self.wlaniface.has_key", self.iface if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None def asciify(self, str): return str.translate(self.asciitrans) def getWirelessInterfaces(self): iwifaces = None try: iwifaces = getNICnames() except: print "[Wlan.py] No Wireless Networkcards could be found" return iwifaces def getNetworkList(self): system("ifconfig " + self.iface + " up") ifobj = Wireless(self.iface) # a Wireless NIC Object #Association mappings stats, quality, discard, missed_beacon = ifobj.getStatistics() snr = quality.signallevel - quality.noiselevel try: scanresults = ifobj.scan() except: scanresults = None print "[Wlan.py] No Wireless Networks could be found" if scanresults is not None: aps = {} for result in scanresults: bssid = result.bssid encryption = map(lambda x: hex(ord(x)), result.encode) if encryption[-1] == "0x8": encryption = True else: encryption = False extra = [] for element in result.custom: element = element.encode() extra.append(strip(self.asciify(element))) if result.quality.sl is 0 and len(extra) > 0: begin = extra[0].find('SignalStrength=') + 15 done = False end = begin + 1 while not done: if extra[0][begin:end].isdigit(): end += 1 else: done = True end -= 1 signal = extra[0][begin:end] #print "[Wlan.py] signal is:" + str(signal) else: signal = str(result.quality.sl) aps[bssid] = { 'active': True, 'bssid': result.bssid, 'channel': result.frequency.getChannel( result.frequency.getFrequency()), 'encrypted': encryption, 'essid': strip(self.asciify(result.essid)), 'iface': self.iface, 'maxrate': result.rate[-1], 'noise': result.quality.getNoiselevel(), 'quality': str(result.quality.quality), 'signal': signal, 'custom': extra, } print aps[bssid] return aps def getStatus(self): ifobj = Wireless(self.iface) fq = Iwfreq() try: self.channel = str(fq.getChannel(str(ifobj.getFrequency()[0:-3]))) except: self.channel = 0 #print ifobj.getStatistics() status = { 'BSSID': str(ifobj.getAPaddr()), 'ESSID': str(ifobj.getEssid()), 'quality': str(ifobj.getStatistics()[1].quality), 'signal': str(ifobj.getStatistics()[1].sl), 'bitrate': str(ifobj.getBitrate()), 'channel': str(self.channel), #'channel': str(fq.getChannel(str(ifobj.getFrequency()[0:-3]))), } for (key, item) in status.items(): if item is "None" or item is "": status[key] = _("N/A") return status
class NetworkNfs(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("NFS Setup")) self.skinName = "NetworkNfs" self.onChangedEntry = [ ] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['key_green'] = Label(_("Start")) self['key_red'] = Label(_("Remove Service")) self['key_yellow'] = Label(_("Autostart")) self['lab4'] = Label(_("active NFS Shares:")) self['key_blue'] = Label( (" ") ) self['lab3'] = Label( (" ")) self.Console = Console() self.my_nfs_active = False self.my_nfs_run = False self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.NfsStartStop, 'yellow': self.Nfsset, 'blue':self.NfsExportOnOff}) self.service_name = basegroup + '-nfs' self.NfsExportCheck() 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: self.feedscheck = self.session.open(MessageBox,_('Please wait while 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.updateService() 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,_('Your %s %s will be restarted after the installation of service.\nReady to install %s ?') % (getMachineBrand(), getMachineName(), 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.session.open(TryQuitMainloop, 2) def UninstallCheck(self): self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail) def RemovedataAvail(self, str, retval, extra_args): if str: restartbox = self.session.openWithCallback(self.RemovePackage,MessageBox,_('Your %s %s will be restarted after the removal of service.\nDo you want to remove now ?') % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO) restartbox.setTitle(_('Ready to remove %s ?') % self.service_name) else: self.updateService() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) 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.session.open(TryQuitMainloop, 2) def createSummary(self): return NetworkServicesSummary def NfsStartStop(self): if not self.my_nfs_run: self.Console.ePopen('/etc/init.d/nfsserver start', self.StartStopCallback) elif self.my_nfs_run: self.Console.ePopen('/etc/init.d/nfsserver stop', self.StartStopCallback) def NfsExportCheck(self): self.Console.ePopen('/usr/sbin/exportfs -ua') time.sleep(1) self.Console.ePopen('/usr/sbin/exportfs -ra') time.sleep(1) if fileExists('/etc/exports'): exports = popen('/usr/sbin/exportfs').read() if exports == "": self['lab3'].setText (_("no valid entrys in /etc/exports found\nPress blue button to activate default Enigma2\nHDD and USB as NFS exports,\nif valid mounted hardware is available.")) self['key_blue'].setText(_("NFS Shares ON")) else: self['lab3'].setText(exports) self['key_blue'].setText(_("NFS Shares OFF")) else: self['lab3'].setText(_("No '/etc/exports' Configuration File found.\nPress blue button to activate default Enigma2\nHDD and USB as NFS exports, if the hardware is available.")) self['key_blue'].setText(_("NFS Shares ON")) def NfsExportOnOff(self): if fileExists('/etc/exports') and popen('/usr/sbin/exportfs').read() != "": self.message = self.session.open(MessageBox,_("please wait\nwhile deacticate NFS exports"), MessageBox.TYPE_INFO,5) self.message.setTitle(_('Info')) self.Console.ePopen('/usr/sbin/exportfs -ua') self.Console.ePopen('rm /etc/exports && touch /etc/exports') self['lab3'].setText(_("No '/etc/exports' Configuration File found.\nPress blue button to activate default Enigma2\nHDD and USB as NFS exports, if the hardware is available.")) self['key_blue'].setText(_("NFS Shares ON")) else: self.message = self.session.open(MessageBox,_("please wait\nwhile acticate NFS exports"), MessageBox.TYPE_INFO,5) self.message.setTitle(_("Info")) netz = popen('ip route show |grep "/" |cut -d " " -f 0').read().strip() opt = "(sync,no_subtree_check,rw)" i=0 z = os.listdir("/media") h = open("/etc/exports","w") while i < len(z): if z[i] !="autofs" and z[i] !="net": h.write( "/media/" + str(z[i]) + " " + netz + opt + "\n" ) i = i + 1 h.close() self.Console.ePopen('/usr/sbin/exportfs -ra') self.NfsExportCheck() def StartStopCallback(self, result = None, retval = None, extra_args = None): time.sleep(3) self.updateService() def Nfsset(self): if fileExists('/etc/rc2.d/S13nfsserver'): self.Console.ePopen('update-rc.d -f nfsserver remove', self.StartStopCallback) else: self.Console.ePopen('update-rc.d -f nfsserver defaults 13', self.StartStopCallback) def updateService(self): import process p = process.ProcessList() nfs_process = str(p.named('nfsd')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].setText(_("Disabled")) self.my_nfs_active = False self.my_nfs_run = False if fileExists('/etc/rc2.d/S13nfsserver'): self['labactive'].setText(_("Enabled")) self['labactive'].show() self.my_nfs_active = True if nfs_process: self.my_nfs_run = True if self.my_nfs_run: self['labstop'].hide() self['labrun'].show() self['key_green'].setText(_("Stop")) status_summary= self['lab2'].text + ' ' + self['labrun'].text else: self['labstop'].show() self['labrun'].hide() self['key_green'].setText(_("Start")) status_summary= self['lab2'].text + ' ' + self['labstop'].text title = _("NFS Setup") autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary)
class QuickMenuDevices(Screen): skin = """ <screen name="QuickMenuDevices" position="center,center" size="840,525" title="Devices" flags="wfBorder"> <widget source="devicelist" render="Listbox" position="30,46" size="780,450" font="Regular;16" scrollbarMode="showOnDemand" transparent="1" backgroundColorSelected="grey" foregroundColorSelected="black"> <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="126,92" size="600,40" font="Regular;22" halign="center" backgroundColor="black" transparent="1" /> </screen> """ def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Devices")) self['lab1'] = Label() self.devicelist = [] self['devicelist'] = List(self.devicelist) self['actions'] = ActionMap(['WizardActions'], { 'back': self.close, }) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.updateList2) self.updateList() 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.devicelist = [] list2 = [] 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): continue if device in list2: continue self.buildMy_rec(device) list2.append(device) f.close() self['devicelist'].list = self.devicelist if len(self.devicelist) == 0: self['lab1'].setText(_("No Devices Found !!")) else: self['lab1'].hide() def buildMy_rec(self, device): device2 = device[:-1] #strip device number devicetype = path.realpath('/sys/block/' + device2 + '/device') d2 = device name = 'USB: ' mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/icons/dev_usbstick.png' model = file('/sys/block/' + device2 + '/device/model').read() model = str(model).replace('\n', '') des = '' if devicetype.find('/devices/pci') != -1: name = _("HARD DISK: ") mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/icons/dev_hdd.png' name = name + model from Components.Console import Console self.Console = Console() self.Console.ePopen("sfdisk -l /dev/sd? | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp") sleep(0.5) f = open('/tmp/devices.tmp', 'r') swapdevices = f.read() f.close() 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 ((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 (((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) res = (name, des, png) self.devicelist.append(res)
class MultibootSelection(SelectImage): def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "SelectImage" self.session = session self.imagesList = None self.expanded = [] self.setTitle(_("Select Multiboot")) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Reboot")) self["list"] = ChoiceList(list=[ ChoiceEntryComponent('', ( (_("Retrieving image slots - Please wait...")), "Waiter")) ]) self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "ok": self.keyOk, "cancel": boundFunction(self.close, None), "red": boundFunction(self.close, None), "green": self.keyOk, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.delay = eTimer() self.delay.callback.append(self.getImagesList) self.delay.start(0, True) def getImagesList(self, reply=None): self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagesdict): list = [] currentimageslot = GetCurrentImage() mode = GetCurrentImageMode() or 0 for x in sorted(imagesdict.keys()): if imagesdict[x]["imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagesdict[x]['imagename']), x))) if SystemInfo["canMode12"]: list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagesdict[x]['imagename']), x + 12))) self["list"].setList(list) def keyOk(self): self.currentSelected = self["list"].l.getCurrentSelection() if self.currentSelected[0][1] != "Waiter": self.container = Console() if os.path.isdir('/tmp/startupmount'): self.ContainterFallback() else: os.mkdir('/tmp/startupmount') self.container.ePopen( 'mount /dev/%sp1 /tmp/startupmount' % SystemInfo["canMultiBoot"][2], self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot = self.currentSelected[0][1] model = HardwareInfo().get_machine_name() if SystemInfo["canMultiBoot"][3]: shutil.copyfile("/tmp/startupmount/STARTUP_%s" % slot, "/tmp/startupmount/STARTUP") else: if slot < 12: startupFileContents = "boot emmcflash0.kernel%s 'root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=1'\n" % ( slot, slot * 2 + 1, model) else: slot -= 12 startupFileContents = "boot emmcflash0.kernel%s 'brcm_cma=520M@248M brcm_cma=%s@768M root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=12'\n" % ( slot, SystemInfo["canMode12"], slot * 2 + 1, model) open('/tmp/startupmount/STARTUP', 'w').write(startupFileContents) from Screens.Standby import TryQuitMainloop self.session.open(TryQuitMainloop, 2) def selectionChanged(self): pass
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: self.slots = sorted(SystemInfo["canMultiBoot"].keys()) self.callback = callback self.imagelist = {} if not os.path.isdir(TMP_MOUNT): os.mkdir(TMP_MOUNT) self.container = Console() self.phase = self.MOUNT self.run() else: callback({}) def run(self): if self.phase == self.UNMOUNT: self.container.ePopen('umount %s' % TMP_MOUNT, self.appClosed) else: self.slot = self.slots.pop(0) self.container.ePopen( 'mount %s %s' % (SystemInfo["canMultiBoot"][self.slot]['device'], TMP_MOUNT), self.appClosed) def appClosed(self, data="", retval=0, extra_args=None): if retval: self.imagelist[self.slot] = {'imagename': _("Empty slot")} if retval == 0 and self.phase == self.MOUNT: imagedir = os.sep.join( filter(None, [ TMP_MOUNT, SystemInfo["canMultiBoot"][self.slot].get( 'rootsubdir', '') ])) if os.path.isfile(os.path.join(imagedir, 'usr/bin/enigma2')): try: from datetime import datetime date = datetime.fromtimestamp( os.stat(os.path.join( imagedir, "var/lib/opkg/status")).st_mtime).strftime( '%Y-%m-%d') if date.startswith("1970"): date = datetime.fromtimestamp( os.stat( os.path.join(imagedir, "usr/share/bootlogo.mvi" )).st_mtime).strftime('%Y-%m-%d') date = max( date, datetime.fromtimestamp( os.stat(os.path.join( imagedir, "usr/bin/enigma2")).st_mtime).strftime( '%Y-%m-%d')) except: date = _("Unknown") self.imagelist[self.slot] = { 'imagename': "%s (%s)" % (open(os.path.join(imagedir, "etc/issue")).readlines() [-2].capitalize().strip()[:-6], date) } else: self.imagelist[self.slot] = {'imagename': _("Empty slot")} if self.slots and SystemInfo["canMultiBoot"][ self.slot]['device'] == SystemInfo["canMultiBoot"][ self.slots[0]]['device']: self.slot = self.slots.pop(0) self.appClosed() else: self.phase = self.UNMOUNT self.run() elif self.slots: self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount(TMP_MOUNT): os.rmdir(TMP_MOUNT) self.callback(self.imagelist)
class MultiBoot(Screen): skin = """ <screen name="MultiBoot" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="labe14" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="labe15" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="200,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <eLabel position="20,200" size="6,40" backgroundColor="#00e61700" /> <!-- Should be a pixmap --> <eLabel position="190,200" size="6,40" backgroundColor="#0061e500" /> <!-- Should be a pixmap --> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "MultiBoot" screentitle = _("Multiboot Image Restart") self["key_red"] = StaticText(_("Cancel")) if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists( '/dev/%s4' % (SystemInfo["canMultiBoot"][2])): self["labe14"] = StaticText( _("Use the cursor keys to select an installed image and then Reboot button." )) else: self["labe14"] = StaticText( _("SDcard is not initialised for multiboot - Exit and use ViX MultiBoot Manager to initialise" )) self["labe15"] = StaticText(_(" ")) self["key_green"] = StaticText(_("Reboot")) if SystemInfo["canMode12"]: self["labe15"] = StaticText( _("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work." )) self["config"] = ChoiceList(list=[ ChoiceEntryComponent('', ( (_("Retrieving image slots - Please wait...")), "Queued")) ]) imagedict = [] self.mtdboot = "%s1" % SystemInfo["canMultiBoot"][2] if SystemInfo["canMultiBoot"][2] == "sda": self.mtdboot = "%s3" % getMachineMtdRoot()[0:8] self.getImageList = None self.title = screentitle if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists( '/dev/%s4' % (SystemInfo["canMultiBoot"][2])): self.startit() self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "red": boundFunction(self.close, None), "green": self.reboot, "ok": self.reboot, "cancel": boundFunction(self.close, None), "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def startit(self): self.getImageList = GetImagelist(self.ImageList) def ImageList(self, imagedict): list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() print "[MultiBoot Restart] reboot1 slot:\n", currentimageslot if SystemInfo["HasSDmmc"]: currentimageslot += 1 #allow for mmc as 1st slot, then SDCard slots print "[MultiBoot Restart] reboot2 slot:\n", currentimageslot if imagedict: if not SystemInfo["canMode12"]: for x in sorted(imagedict.keys()): if imagedict[x]["imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s -%s - %s (current image)") if x == currentimageslot else _("slot%s -%s- %s ")) % (x, imagedict[x]['part'][0:3], imagedict[x]['imagename']), x))) else: for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if imagedict[x]["imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagedict[x]['imagename']), x))) list.append(" ") list.append(" ") for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if SystemInfo["canMode12"] and imagedict[x][ "imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagedict[x]['imagename']), x + 12))) else: list.append( ChoiceEntryComponent('', ((_("No images found")), "Waiter"))) self["config"].setList(list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() if self.currentSelected[0][1] != "Queued": self.container = Console() if pathExists('/tmp/startupmount'): self.ContainterFallback() else: mkdir('/tmp/startupmount') if SystemInfo["HasRootSubdir"]: if fileExists("/dev/block/by-name/bootoptions"): print "[MultiBoot Restart] bootoptions" self.container.ePopen( 'mount /dev/block/by-name/bootoptions /tmp/startupmount', self.ContainterFallback) elif fileExists("/dev/block/by-name/boot"): print "[MultiBoot Restart] by-name/boot" self.container.ePopen( 'mount /dev/block/by-name/boot /tmp/startupmount', self.ContainterFallback) else: print "[MultiBoot Restart] mtdboot" self.container.ePopen( 'mount /dev/%s /tmp/startupmount' % self.mtdboot, self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot12 = 1 slot = self.currentSelected[0][1] Startup = False print "[MultiBoot Restart] reboot3 slot:", slot if pathExists("/tmp/startupmount/STARTUP"): if fileExists("/tmp/startupmount/STARTUP_1"): if slot < 12: Startup = "/tmp/startupmount/STARTUP_%s" % slot else: slot12 = slot # BOXMODE OE-A STARTUP_1 -> STARTUP_n slot -= 12 Startup = "/tmp/startupmount/STARTUP_%s" % slot f = open('%s' % Startup, 'r').read().replace( "boxmode=1'", "boxmode=12'").replace( "%s" % SystemInfo["canMode12"][0], "%s" % SystemInfo["canMode12"][1]) print "[MultiBoot Restart] reboot4 mode12:", f open('/tmp/startupmount/STARTUP', 'w').write(f) elif fileExists("/tmp/startupmount/STARTUP_LINUX_4"): Startup = "/tmp/startupmount/STARTUP_LINUX_%s" % slot elif fileExists("/tmp/startupmount/STARTUP_LINUX_4_BOXMODE_1"): if slot < 12: Startup = "/tmp/startupmount/STARTUP_LINUX_%s_BOXMODE_1" % slot else: slot -= 12 Startup = "/tmp/startupmount/STARTUP_LINUX_%s_BOXMODE_12" % slot if Startup == False: self.session.open( MessageBox, _("Multiboot ERROR! - invalid STARTUP in boot partition."), MessageBox.TYPE_INFO, timeout=20) else: if slot12 < 12: copyfile("%s" % Startup, "/tmp/startupmount/STARTUP") self.session.open(TryQuitMainloop, 2) else: self.session.open( MessageBox, _("Multiboot ERROR! - no STARTUP in boot partition."), MessageBox.TYPE_INFO, timeout=20) def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
class EPGSelection(Screen): EMPTY = 0 ADD_TIMER = 1 REMOVE_TIMER = 2 ZAP = 1 def __init__(self, session, service, zapFunc=None, eventid=None, bouquetChangeCB=None, serviceChangeCB=None, parent=None): Screen.__init__(self, session) self.bouquetChangeCB = bouquetChangeCB self.serviceChangeCB = serviceChangeCB self.ask_time = -1 #now self["key_red"] = StaticText("") self.closeRecursive = False self.saved_title = None self["Service"] = ServiceEvent() self["Event"] = Event() self.session = session self.Console = Console() if isinstance(service, str) and eventid is not None: self.type = EPG_TYPE_SIMILAR self.setTitle(_("Similar EPG")) self["key_yellow"] = StaticText() self["key_blue"] = StaticText() self["key_red"] = StaticText() self.currentService = service self.eventid = eventid self.zapFunc = None elif isinstance(service, eServiceReference) or isinstance( service, str): self.setTitle(_("Single EPG")) self.type = EPG_TYPE_SINGLE self["key_yellow"] = StaticText() self["key_blue"] = StaticText(_("Select Channel")) self.currentService = ServiceReference(service) self.zapFunc = zapFunc self.sort_type = 0 self.setSortDescription() else: self.setTitle(_("Multi EPG")) self.skinName = "EPGSelectionMulti" self.type = EPG_TYPE_MULTI if self.bouquetChangeCB == StaticText: self["key_yellow"] = StaticText( pgettext("button label, 'previous screen'", "Prev")) self["key_blue"] = StaticText( pgettext("button label, 'next screen'", "Next")) else: self["key_yellow"] = Button( pgettext("button label, 'previous screen'", "Prev")) self["key_blue"] = Button( pgettext("button label, 'next screen'", "Next")) self["now_button"] = Pixmap() self["next_button"] = Pixmap() self["more_button"] = Pixmap() self["now_button_sel"] = Pixmap() self["next_button_sel"] = Pixmap() self["more_button_sel"] = Pixmap() self["now_text"] = Label() self["next_text"] = Label() self["more_text"] = Label() self["date"] = Label() self.services = service self.zapFunc = zapFunc self.parent = parent if self.bouquetChangeCB == StaticText: self["key_green"] = StaticText(_("Add timer")) else: self["key_green"] = Button(_("Add timer")) self.key_green_choice = self.ADD_TIMER self.key_red_choice = self.EMPTY self["list"] = EPGList(type=self.type, selChangedCB=self.onSelectionChanged, timer=session.nav.RecordTimer) self["actions"] = ActionMap( ["EPGSelectActions", "OkCancelActions"], { "cancel": self.closeScreen, "ok": self.eventSelected, "timerAdd": self.timerAdd, "yellow": self.yellowButtonPressed, "blue": self.blueButtonPressed, "info": self.infoKeyPressed, "menu": self.furtherOptions, "nextBouquet": self.nextBouquet, # just used in multi epg yet "prevBouquet": self.prevBouquet, # just used in multi epg yet "nextService": self.nextService, # just used in single epg yet "prevService": self.prevService, # just used in single epg yet "preview": self.eventPreview, }) self['colouractions'] = HelpableActionMap( self, ["ColorActions"], {"red": (self.GoToTmbd, _("Search event in TMBD"))}) self.isTMBD = fileExists( resolveFilename(SCOPE_PLUGINS, "Extensions/TMBD/plugin.pyo")) or fileExists( resolveFilename(SCOPE_PLUGINS, "Extensions/TMBD/plugin.py")) if self.isTMBD: self["key_red"] = Button(_("Search TMBD")) self.select = True if not self.isTMBD: self["key_red"] = Button(_("TMBD Not Installed")) self.select = False try: from Plugins.Extensions.YTTrailer.plugin import baseEPGSelection__init__ description = _("Search yt-trailer for event") except ImportError as ie: pass else: if baseEPGSelection__init__ is not None: self["trailerActions"] = ActionMap( ["InfobarActions", "InfobarTeletextActions"], { "showTv": self.showTrailer, "showRadio": self.showTrailerList, "startTeletext": self.showConfig }) self["actions"].csel = self if parent and hasattr(parent, "fallbackTimer"): self.fallbackTimer = parent.fallbackTimer self.onLayoutFinish.append(self.onCreate) else: self.fallbackTimer = FallbackTimerList(self, self.onCreate) def GoToTmbd(self): if fileExists( resolveFilename(SCOPE_PLUGINS, "Extensions/TMBD/plugin.pyo")) or fileExists( resolveFilename( SCOPE_PLUGINS, "Extensions/TMBD/plugin.py")): self.runTMBD() if not fileExists( resolveFilename(SCOPE_PLUGINS, "Extensions/TMBD/plugin.pyo") ) and not fileExists( resolveFilename(SCOPE_PLUGINS, "Extensions/TMBD/plugin.py")): self.session.openWithCallback( self.doInstall, MessageBox, _('The TMBD plugin is not installed!\nDo you want to install it?' ), MessageBox.TYPE_YESNO) def runTMBD(self): if fileExists( resolveFilename(SCOPE_PLUGINS, "Extensions/TMBD/plugin.pyo")) or fileExists( resolveFilename( SCOPE_PLUGINS, "Extensions/TMBD/plugin.py")): from Plugins.Extensions.TMBD.plugin import TMBD description = _("TMBD Details") description = _("TMBD details for event") description = _("Query details from the Internet Movie Database") cur = self["list"].getCurrent() if cur[0] is not None: name2 = cur[0].getEventName() or '' name3 = name2.split("(")[0].strip() eventname = name3.replace('"', '').replace('', '').replace('.', '') eventname = eventname.replace('', '') try: tmbdsearch = config.plugins.tmbd.profile.value except: tmbdsearch = None if tmbdsearch is not None: if config.plugins.tmbd.profile.value == "0": self.session.open(TMBD, eventname, False) else: try: from Plugins.Extensions.TMBD.plugin import KinoRu self.session.open(KinoRu, eventname, False) except: pass else: self.session.open(TMBD, eventname, False) def doInstall(self, val): if val: self.message = self.session.open(MessageBox, _("Please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Installing TMBD')) self.Console.ePopen( 'opkg update && opkg install enigma2-plugin-extensions-tmbd', self.installComplete) else: self.close() def installComplete(self, str, retval, extra_args): if 'Collected errors' in str: self.session.openWithCallback( self.close, MessageBox, _("Seems internet connection down, Or TMBD Plugin not on feed." ), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) self.message.close() else: self.message.close() self.close() def nextBouquet(self): if self.type == EPG_TYPE_SINGLE: self.session.openWithCallback( self.channelSelectionCallback, ChannelSelection.SimpleChannelSelection, _("Select channel"), True, True, self.currentService.ref, self.parent and self.parent.epg_bouquet) if self.bouquetChangeCB: self.bouquetChangeCB(1, self) def prevBouquet(self): if self.type == EPG_TYPE_SINGLE: self.session.openWithCallback( self.channelSelectionCallback, ChannelSelection.SimpleChannelSelection, _("Select channel"), True, True, self.currentService.ref, self.parent and self.parent.epg_bouquet) if self.bouquetChangeCB: self.bouquetChangeCB(-1, self) def nextService(self): if self.serviceChangeCB: self.serviceChangeCB(1, self) def prevService(self): if self.serviceChangeCB: self.serviceChangeCB(-1, self) def enterDateTime(self): if self.type == EPG_TYPE_MULTI: global mepg_config_initialized if not mepg_config_initialized: config.misc.prev_mepg_time = ConfigClock(default=time()) mepg_config_initialized = True self.session.openWithCallback(self.onDateTimeInputClosed, TimeDateInput, config.misc.prev_mepg_time) def furtherOptions(self): menu = [] text = _("Select action") event = self["list"].getCurrent()[0] if event: if PY2: menu = [(p.name, boundFunction(self.runPlugin, p)) for p in plugins.getPlugins( where=PluginDescriptor.WHERE_EVENTINFO) if 'selectedevent' in p.__call__.func_code.co_varnames] else: menu = [(p.name, boundFunction(self.runPlugin, p)) for p in plugins.getPlugins( where=PluginDescriptor.WHERE_EVENTINFO) if 'selectedevent' in p.__call__.__code__.co_varnames] if menu: text += ": %s" % event.getEventName() if self.type == EPG_TYPE_MULTI: menu.append((_("Goto specific date/time"), self.enterDateTime)) menu.append((_("Timer Overview"), self.openTimerOverview)) if len(menu) == 1: menu and menu[0][1]() elif len(menu) > 1: def boxAction(choice): if choice: choice[1]() self.session.openWithCallback(boxAction, ChoiceBox, title=text, list=menu, windowTitle=_("Further options")) def runPlugin(self, plugin): event = self["list"].getCurrent() plugin.__call__(session=self.session, selectedevent=event) def openTimerOverview(self): self.session.open(TimerEditList) def onDateTimeInputClosed(self, ret): if len(ret) > 1: if ret[0]: self.ask_time = ret[1] self["list"].fillMultiEPG(self.services, ret[1]) def closeScreen(self): if self.zapFunc: self.zapFunc(None, zapback=True) self.close(self.closeRecursive) def infoKeyPressed(self): cur = self["list"].getCurrent() event = cur[0] service = cur[1] if event is not None: if self.type != EPG_TYPE_SIMILAR: self.session.open(EventViewSimple, event, service, self.eventViewCallback, self.openSimilarList, parent=self.parent) else: self.session.open(EventViewSimple, event, service, self.eventViewCallback, parent=self.parent) def openSimilarList(self, eventid, refstr): self.session.open(EPGSelection, refstr, None, eventid) def setServices(self, services): self.services = services self.onCreate() def setService(self, service): self.currentService = service self.onCreate() #just used in multipeg def onCreate(self): l = self["list"] l.recalcEntrySize() if self.type == EPG_TYPE_MULTI: l.fillMultiEPG(self.services, self.ask_time) l.moveToService( Screens.InfoBar.InfoBar.instance and Screens.InfoBar.InfoBar. instance.servicelist.getCurrentSelection() or self.session.nav.getCurrentlyPlayingServiceOrGroup()) elif self.type == EPG_TYPE_SINGLE: service = self.currentService self["Service"].newService(service.ref) if not self.saved_title: self.saved_title = self.instance.getTitle() self.setTitle(self.saved_title + ' - ' + service.getServiceName()) l.fillSingleEPG(service) else: l.fillSimilarList(self.currentService, self.eventid) def eventViewCallback(self, setEvent, setService, val): l = self["list"] old = l.getCurrent() if val == -1: self.moveUp() elif val == +1: self.moveDown() cur = l.getCurrent() if self.type == EPG_TYPE_MULTI and cur[0] is None and cur[ 1].ref != old[1].ref: self.eventViewCallback(setEvent, setService, val) else: setService(cur[1]) setEvent(cur[0]) def zapTo(self): if self.key_red_choice == self.ZAP and self.zapFunc: self.closeRecursive = True from Components.ServiceEventTracker import InfoBarCount if InfoBarCount > 1: self.eventPreview() else: self.zapSelectedService() self.close(self.closeRecursive) def zapSelectedService(self, prev=False): lst = self["list"] count = lst.getCurrentChangeCount() if count == 0: ref = lst.getCurrent()[1] if ref is not None: self.zapFunc(ref.ref, preview=prev) def eventPreview(self): if self.zapFunc: # if enabled, then closed whole EPG with EXIT: # self.closeRecursive = True self.zapSelectedService(True) def eventSelected(self): if self.skinName == "EPGSelectionMulti": cur = self["list"].getCurrent() event = cur[0] ref = cur[1] and cur[1].ref.toString() if ref and event: self.session.open(EPGSelection, ref) else: self.infoKeyPressed() def yellowButtonPressed(self): if self.type == EPG_TYPE_MULTI: self["list"].updateMultiEPG(-1) elif self.type == EPG_TYPE_SINGLE: if self.sort_type == 0: self.sort_type = 1 else: self.sort_type = 0 self["list"].sortSingleEPG(self.sort_type) self.setSortDescription() def setSortDescription(self): if self.sort_type == 1: # TRANSLATORS: This must fit into the header button in the EPG-List self["key_yellow"].setText(_("Sort time")) else: # TRANSLATORS: This must fit into the header button in the EPG-List self["key_yellow"].setText(_("Sort A-Z")) def blueButtonPressed(self): if self.type == EPG_TYPE_MULTI: self["list"].updateMultiEPG(1) if self.type == EPG_TYPE_SINGLE: self.session.openWithCallback( self.channelSelectionCallback, ChannelSelection.SimpleChannelSelection, _("Select channel"), True, True, self.currentService.ref, self.parent and self.parent.epg_bouquet) def channelSelectionCallback(self, *args): if args and len(args) == 2: serviceref, bouquetref = args[:2] if self.parent: self.parent.selectBouquet(bouquetref, self) self.setService(ServiceReference(serviceref)) def removeTimer(self, timer): if timer.external: self.fallbackTimer.removeTimer(timer, self.onSelectionChanged) else: timer.afterEvent = AFTEREVENT.NONE self.session.nav.RecordTimer.removeEntry(timer) self["key_green"].setText(_("Add timer")) self.key_green_choice = self.ADD_TIMER def disableTimer(self, timer, state, repeat=False, record=False): if repeat: if record: title_text = _( "Repeating event currently recording.\nWhat do you want to do?" ) menu = [(_("Stop current event but not coming events"), "stoponlycurrent"), (_("Stop current event and disable coming events"), "stopall")] if not timer.disabled: menu.append((_( "Don't stop current event but disable coming events"), "stoponlycoming")) else: title_text = _( "Attention, this is repeated timer!\nWhat do you want to do?" ) menu = [(_("Disable current event but not coming events"), "nextonlystop"), (_("Disable timer"), "simplestop")] self.session.openWithCallback(boundFunction( self.runningEventCallback, timer, state), ChoiceBox, title=title_text, list=menu) elif timer.state == state: if timer.external: self.fallbackTimer.toggleTimer(timer, self.onSelectionChanged) else: timer.disable() self.session.nav.RecordTimer.timeChanged(timer) self["key_green"].setText(_("Add timer")) self.key_green_choice = self.ADD_TIMER def runningEventCallback(self, t, state, result): if result is not None and t.state == state: findNextRunningEvent = True findEventNext = False if result[1] == "nextonlystop": findEventNext = True t.disable() self.session.nav.RecordTimer.timeChanged(t) t.processRepeated(findNextEvent=True) t.enable() if result[1] in ("stoponlycurrent", "stopall"): findNextRunningEvent = False t.enable() t.processRepeated(findRunningEvent=False) self.session.nav.RecordTimer.doActivate(t) if result[1] in ("stoponlycoming", "stopall", "simplestop"): findNextRunningEvent = True t.disable() self.session.nav.RecordTimer.timeChanged(t) t.findRunningEvent = findNextRunningEvent t.findNextEvent = findEventNext if result[1] in ("stoponlycurrent", "stopall", "simplestop", "nextonlystop"): self["key_green"].setText(_("Add timer")) self.key_green_choice = self.ADD_TIMER def timerAdd(self): cur = self["list"].getCurrent() event = cur[0] if event is None: return serviceref = cur[1] isRecordEvent = isRepeat = firstNextRepeatEvent = isRunning = False eventid = event.getEventId() begin = event.getBeginTime() end = begin + event.getDuration() refstr = ':'.join(serviceref.ref.toString().split(':')[:11]) for timer in self.session.nav.RecordTimer.getAllTimersList(): needed_ref = ':'.join( timer.service_ref.ref.toString().split(':')[:11]) == refstr if needed_ref and timer.eit == eventid and ( begin < timer.begin <= end or timer.begin <= begin <= timer.end): isRecordEvent = True break elif needed_ref and timer.repeated and self.session.nav.RecordTimer.isInRepeatTimer( timer, event): isRecordEvent = True break if isRecordEvent: isRepeat = timer.repeated prev_state = timer.state isRunning = prev_state in (1, 2) title_text = isRepeat and _( "Attention, this is repeated timer!\n") or "" firstNextRepeatEvent = isRepeat and ( begin < timer.begin <= end or timer.begin <= begin <= timer.end) and not timer.justplay menu = [(_("Delete timer"), "delete"), (_("Edit timer"), "edit")] buttons = ["red", "green"] if not isRunning: if firstNextRepeatEvent and timer.isFindRunningEvent( ) and not timer.isFindNextEvent(): menu.append((_("Options disable timer"), "disablerepeat")) else: menu.append((_("Disable timer"), "disable")) buttons.append("yellow") elif prev_state == 2 and firstNextRepeatEvent: menu.append( (_("Options disable timer"), "disablerepeatrunning")) buttons.append("yellow") menu.append((_("Timer Overview"), "timereditlist")) def timerAction(choice): if choice is not None: if choice[1] == "delete": self.removeTimer(timer) elif choice[1] == "edit": self.session.openWithCallback(self.finishedEdit, TimerEntry, timer) elif choice[1] == "disable": self.disableTimer(timer, prev_state) elif choice[1] == "timereditlist": self.session.open(TimerEditList) elif choice[1] == "disablerepeatrunning": self.disableTimer(timer, prev_state, repeat=True, record=True) elif choice[1] == "disablerepeat": self.disableTimer(timer, prev_state, repeat=True) self.session.openWithCallback( timerAction, ChoiceBox, title=title_text + _("Select action for timer '%s'.") % timer.name, list=menu, keys=buttons) else: newEntry = RecordTimerEntry(serviceref, checkOldTimers=True, dirname=preferredTimerPath(), *parseEvent(event)) newEntry.justplay = config.recording.timer_default_type.value == "zap" newEntry.always_zap = config.recording.timer_default_type.value == "zap+record" self.session.openWithCallback(self.finishedAdd, TimerEntry, newEntry) def finishedEdit(self, answer): if answer[0]: entry = answer[1] if entry.external_prev != entry.external: def removeEditTimer(): entry.service_ref, entry.begin, entry.end, entry.external = entry.service_ref_prev, entry.begin_prev, entry.end_prev, entry.external_prev self.removeTimer(entry) def moveEditTimerError(): entry.external = entry.external_prev self.onSelectionChanged() if entry.external: self.fallbackTimer.addTimer(entry, removeEditTimer, moveEditTimerError) else: newentry = createRecordTimerEntry(entry) entry.service_ref, entry.begin, entry.end = entry.service_ref_prev, entry.begin_prev, entry.end_prev self.fallbackTimer.removeTimer( entry, boundFunction(self.finishedAdd, (True, newentry)), moveEditTimerError) elif entry.external: self.fallbackTimer.editTimer(entry, self.onSelectionChanged) else: simulTimerList = self.session.nav.RecordTimer.record(entry) if simulTimerList is not None: for x in simulTimerList: if x.setAutoincreaseEnd(entry): self.session.nav.RecordTimer.timeChanged(x) simulTimerList = self.session.nav.RecordTimer.record(entry) if simulTimerList is not None: self.session.openWithCallback( boundFunction(self.finishedEdit, service_ref, begin, end), TimerSanityConflict, simulTimerList) return else: self.session.nav.RecordTimer.timeChanged(entry) self.onSelectionChanged() def finishedAdd(self, answer): print("[EpgSelection] finished add") if answer[0]: entry = answer[1] if entry.external: self.fallbackTimer.addTimer(entry, self.onSelectionChanged) else: simulTimerList = self.session.nav.RecordTimer.record(entry) if simulTimerList is not None: for x in simulTimerList: if x.setAutoincreaseEnd(entry): self.session.nav.RecordTimer.timeChanged(x) simulTimerList = self.session.nav.RecordTimer.record(entry) if simulTimerList is not None: if not entry.repeated and not config.recording.margin_before.value and not config.recording.margin_after.value and len( simulTimerList) > 1: change_time = False conflict_begin = simulTimerList[1].begin conflict_end = simulTimerList[1].end if conflict_begin == entry.end: entry.end -= 30 change_time = True elif entry.begin == conflict_end: entry.begin += 30 change_time = True elif entry.begin == conflict_begin and ( entry.service_ref and entry.service_ref.ref and entry.service_ref.ref.flags & eServiceReference.isGroup): entry.begin += 30 change_time = True if change_time: simulTimerList = self.session.nav.RecordTimer.record( entry) if simulTimerList is not None: self.session.openWithCallback( self.finishSanityCorrection, TimerSanityConflict, simulTimerList) return cur = self["list"].getCurrent() event = cur and cur[0] if event: begin = event.getBeginTime() end = begin + event.getDuration() if begin < entry.begin <= end or entry.begin <= begin <= entry.end: self["key_green"].setText(_("Change timer")) self.key_green_choice = self.REMOVE_TIMER else: self["key_green"].setText(_("Add timer")) self.key_green_choice = self.ADD_TIMER print("[EpgSelection] Timeredit aborted") def finishSanityCorrection(self, answer): self.finishedAdd(answer) def moveUp(self): self["list"].moveUp() def moveDown(self): self["list"].moveDown() def applyButtonState(self, state): if state == 0: self["now_button"].hide() self["now_button_sel"].hide() self["next_button"].hide() self["next_button_sel"].hide() self["more_button"].hide() self["more_button_sel"].hide() self["now_text"].hide() self["next_text"].hide() self["more_text"].hide() self["key_red"].setText("") else: if state == 1: self["now_button_sel"].show() self["now_button"].hide() else: self["now_button"].show() self["now_button_sel"].hide() if state == 2: self["next_button_sel"].show() self["next_button"].hide() else: self["next_button"].show() self["next_button_sel"].hide() if state == 3: self["more_button_sel"].show() self["more_button"].hide() else: self["more_button"].show() self["more_button_sel"].hide() def onSelectionChanged(self): cur = self["list"].getCurrent() if cur is None: if self.key_green_choice != self.EMPTY: self["key_green"].setText("") self.key_green_choice = self.EMPTY return event = cur[0] self["Event"].newEvent(event) if self.type == EPG_TYPE_MULTI: count = self["list"].getCurrentChangeCount() if self.ask_time != -1: self.applyButtonState(0) elif count > 1: self.applyButtonState(3) elif count > 0: self.applyButtonState(2) else: self.applyButtonState(1) days = [ _("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun") ] datestr = "" if event is not None: now = time() beg = event.getBeginTime() nowTime = localtime(now) begTime = localtime(beg) if nowTime[2] != begTime[2]: datestr = strftime(config.usage.date.dayshort.value, begTime) else: datestr = '%s' % _('Today') self["date"].setText(datestr) if cur[1] is None: self["Service"].newService(None) else: self["Service"].newService(cur[1].ref) if cur[1] is None or cur[1].getServiceName() == "": if self.key_green_choice != self.EMPTY: self["key_green"].setText("") self.key_green_choice = self.EMPTY return if event is None: if self.key_green_choice != self.EMPTY: self["key_green"].setText("") self.key_green_choice = self.EMPTY return serviceref = cur[1] eventid = event.getEventId() begin = event.getBeginTime() end = begin + event.getDuration() refstr = ':'.join(serviceref.ref.toString().split(':')[:11]) isRecordEvent = False for timer in self.session.nav.RecordTimer.getAllTimersList(): needed_ref = ':'.join( timer.service_ref.ref.toString().split(':')[:11]) == refstr if needed_ref and (timer.eit == eventid and (begin < timer.begin <= end or timer.begin <= begin <= timer.end) or timer.repeated and self.session.nav.RecordTimer.isInRepeatTimer( timer, event)): isRecordEvent = True break if isRecordEvent and self.key_green_choice != self.REMOVE_TIMER: self["key_green"].setText(_("Change timer")) self.key_green_choice = self.REMOVE_TIMER elif not isRecordEvent and self.key_green_choice != self.ADD_TIMER: self["key_green"].setText(_("Add timer")) self.key_green_choice = self.ADD_TIMER if self.parent and eventid and hasattr(self.parent, "setEvent"): self.parent.setEvent(serviceref, eventid) self["list"].l.invalidate()
class FEconf(Screen): skin = """<screen position="center,center" size="640,160" title="%s"> <widget name="list" position="5,5" size="630,150" /> </screen>""" % (_("choose device to FlashExpander")) def __init__(self, session): Screen.__init__(self, session) self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.Exit, "ok": self.Ok }, -1) #Blocklaufwerke list = [] for x in listdir("/sys/block"): if x[0:2] == 'sd' or x[0:2] == 'hd': print("[FlashExpander] device", x) devices = Harddisk(x) for y in range(devices.numPartitions()): fstype = self.__getPartitionType( devices.partitionPath(str(y + 1))) if fstype == False: fstype = self.__getPartitionType( devices.partitionPath(str(y + 1))) try: bustype = devices.bus_type() except: bustype = _("unknown") if fstype in ("ext2", "ext3", "ext4", "xfs"): list.append(("%s (%s) - Partition %d (%s)" % (devices.model(), bustype, y + 1, fstype), (devices, y + 1, fstype))) #Netzlaufwerke try: for x in getMountP(): entry = x.split(' ') if len(entry) > 3 and entry[2] == "nfs": server = entry[0].split(':') if len(server) == 2: print("[FlashExpander] server", server) list.append(("Server (%s) - Path (%s)" % (server[0], server[1]), server)) except: print("[FlashExpander] <getMountPoints>") if len(list) == 0: list.append((_( "No HDD-, SSD- or USB-Device found. Please first initialized." ), None)) self["list"] = MenuList(list=list) self.Console = Console() def Ok(self): sel = self["list"].getCurrent() if sel and sel[1]: if len(sel[1]) == 3: #Device tstr = _( "Are you sure want to create FlashExpander on\n%s\nPartition %d" ) % (sel[1][0].model(), sel[1][1]) self.session.openWithCallback( boundFunction(self.__startFE_device, sel[1]), MessageBox, tstr) if len(sel[1]) == 2: #Server tstr = _( "Are you sure want to create FlashExpander on \nServer: %s\nPath: %s" ) % (sel[1][0], sel[1][1]) self.session.openWithCallback( boundFunction(self.__startFE_server, sel[1]), MessageBox, tstr) def __getPartitionType(self, device): fstype = None try: if path.exists("/lib/udev/vol_id"): val = os_popen("/lib/udev/vol_id --type " + device) fstype = val.read().strip() elif path.exists("/sbin/blkid"): for line in os_popen("/sbin/blkid " + device).read().split('\n'): if not line.startswith(device): continue fstobj = re.search(r' TYPE="((?:[^"\\]|\\.)*)"', line) if fstobj: fstype = fstobj.group(1) except: print("[FlashExpander] <error get fstype>") return False return fstype def __getPartitionUUID(self, device): try: if path.exists("/dev/disk/by-uuid"): for uuid in listdir("/dev/disk/by-uuid/"): if not path.exists("/dev/disk/by-uuid/" + uuid): return None if path.realpath("/dev/disk/by-uuid/" + uuid) == device: return "/dev/disk/by-uuid/" + uuid else: #Topfi begin (use more reliable UUID mount on boxes without /dev/disk/by-uuid) p = Popen(["blkid", "-o", "udev", device], stdout=PIPE, stderr=PIPE, stdin=PIPE) txtUUID = p.stdout.read() start = txtUUID.find("ID_FS_UUID=") if start > -1: txtUUID = txtUUID[start + 11:] end = txtUUID.find("\n") if end > -1: txtUUID = txtUUID[:end] return "UUID=" + txtUUID #Topfi end return device except: print("[FlashExpander] <error get UUID>") return None def __startFE_device(self, val, result): if result: partitionPath = val[0].partitionPath(str(val[1])) uuidPath = self.__getPartitionUUID(partitionPath) fstype = val[2] print("[FlashExpander]", partitionPath, uuidPath, fstype) if uuidPath == None: self.session.open(MessageBox, _("read UUID"), MessageBox.TYPE_ERROR, timeout=5) return mountpoint = ismounted(uuidPath, "") if mountpoint == False: mountpoint = ismounted(partitionPath, "") if mountpoint == False: if self.__mount(uuidPath, "/media/FEtmp") == 0: mountpoint = "/media/FEtmp" self.__copyFlash(mountpoint, (partitionPath, uuidPath, fstype)) #if self.__checkMountPoint(mountpoint): # cmd = "rm -rf %s/* && cp -a /usr/* %s/" % (mountpoint, mountpoint) # self.Console.ePopen(cmd, self.__CopyFinished) # self.__message = self.session.openWithCallback(boundFunction(self.__EndCB,(partitionPath,uuidPath,fstype)), MessageBox, _("Please wait, Flash memory will be copied."), MessageBox.TYPE_INFO,enable_input=False) def __startFE_server(self, val, result): if result: server = val[0] path = val[1] print("[FlashExpander]", server, path) mountpoint = ismounted("%s:%s" % (server, path), "") self.__copyFlash(mountpoint, ("%s:%s" % (server, path), None, "nfs")) #if self.__checkMountPoint(mountpoint): # cmd = "rm -rf %s/* && cp -a /usr/* %s/" % (mountpoint, mountpoint) # self.Console.ePopen(cmd, self.__CopyFinished) # self.__message = self.session.openWithCallback(boundFunction(self.__EndCB,("%s:%s" %(server,path),None,"nfs")), MessageBox, _("Please wait, Flash memory will be copied."), MessageBox.TYPE_INFO,enable_input=False) def __copyFlash(self, mp, data): if self.__checkMountPoint(mp): cmd = "cp -af /usr/* %s/" % (mp) self.Console.ePopen(cmd, self.__CopyFinished) self.__message = self.session.openWithCallback( boundFunction(self.__EndCB, data), MessageBox, _("Please wait, Flash memory will be copied."), MessageBox.TYPE_INFO, enable_input=False) def __mount(self, dev, mp): if path.exists(mp) == False: createDir(mp, True) cmd = "mount " + dev + " " + mp #print("[FlashExpander]",cmd) res = Console().ePopen(cmd) return (res >> 8) def __checkMountPoint(self, mp): if mp == False: self.session.open(MessageBox, _("Mount failed (%s)") % fstype, MessageBox.TYPE_ERROR, timeout=5) return False if getFreeSize(mp) < 180: self.session.open( MessageBox, _("Too little free space < 180MB or wrong Filesystem!"), MessageBox.TYPE_ERROR, timeout=5) return False return True def __CopyFinished(self, result, retval, extra_args=None): if retval == 0: self.__message.close(True) else: self.__message.close(False) def __EndCB(self, val, retval): if retval == True: try: devPath = val[0] uuidPath = val[1] fstype = val[2] #fstab editieren mounts = open('/etc/fstab').read().split('\n') newlines = [] for x in mounts: if x.startswith(devPath): continue if uuidPath and x.startswith(uuidPath): continue if len(x) > 1 and x[0] != '#': newlines.append(x) if fstype == "nfs": newlines.append( "%s\t/usr\t%s\trw,nolock,timeo=14,intr\t0 0" % (devPath, fstype)) else: newlines.append("%s\t/usr\tauto\tdefaults\t0 0" % (uuidPath)) fp = open("/etc/fstab", 'w') fp.write("#automatically edited by FlashExpander\n") for x in newlines: fp.write(x + "\n") fp.close() print("[FlashExpander] write new /etc/fstab") self.session.openWithCallback( self.Exit, MessageBox, _("Do you want to reboot your STB_BOX?")) except: self.session.open(MessageBox, _("error adding fstab entry for: %s") % (devPath), MessageBox.TYPE_ERROR, timeout=5) return else: self.session.open(MessageBox, _("error copy flash memory"), MessageBox.TYPE_ERROR, timeout=10) def Exit(self, data=False): self.close(data)
class SystemMemoryInfo(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Memory Information")) #self.skinName = ["SystemMemoryInfo", "About"] self.skinName = ["About"] OpenNFRVersion = _("OpenNFR %s") % about.getImageVersionString() self["OpenNFRVersion"] = Label(OpenNFRVersion) self["AboutScrollLabel"] = ScrollLabel() self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "cancel": self.close, "ok": self.close, }) out_lines = open("/proc/meminfo").readlines() self.AboutText = _("RAM") + '\n\n' RamTotal = "-" RamFree = "-" for lidx in list(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): result = six.ensure_str(result) 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, })
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)
class Devices(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Device Information")) self.skinName = ["SystemDevicesInfo", "About"] OpenNFRVersion = _("OpenNFR %s") % about.getImageVersionString() self["OpenNFRVersion"] = Label(OpenNFRVersion) self.AboutText = "" self["AboutScrollLabel"] = ScrollLabel(self.AboutText) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.populate2) self.populate() self["actions"] = ActionMap( [ "SetupActions", "ColorActions", "TimerEditActions", "DirectionActions" ], { "cancel": self.close, "ok": self.close, "up": self["AboutScrollLabel"].pageUp, "down": self["AboutScrollLabel"].pageDown }) def populate(self): scanning = _("Wait please while scanning for devices...") self["AboutScrollLabel"].setText(scanning) self.activityTimer.start(10) def populate2(self): self.activityTimer.stop() self.Console = Console() self.AboutText = _("Model:\t%s %s\n") % (getMachineBrand(), getMachineName()) self.AboutText += "\n" + _("Detected NIMs:") + "\n" nims = nimmanager.nimList() for count in list(range(len(nims))): if count < 4: self["Tuner" + str(count)] = StaticText(nims[count]) else: self["Tuner" + str(count)] = StaticText("") self.AboutText += nims[count] + "\n" self.AboutText += "\n" + _("Detected HDD:") + "\n" self.list = [] list2 = [] 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): continue if device in list2: continue mount = '/dev/' + device f = open('/proc/mounts', 'r') for line in f.readlines(): if device in line: parts = line.strip().split() mount = str(parts[1]) break f.close() if not mount.startswith('/dev/'): size = Harddisk(device).diskSize() free = Harddisk(device).free() if ((float(size) / 1024) / 1024) >= 1: sizeline = _("Size: ") + str( round( ((float(size) / 1024) / 1024), 2)) + " " + _("TB") elif (size / 1024) >= 1: sizeline = _("Size: ") + str(round( (float(size) / 1024), 2)) + " " + _("GB") elif size >= 1: sizeline = _("Size: ") + str(size) + " " + _("MB") else: sizeline = _("Size: ") + _("unavailable") 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") else: freeline = _("Free: ") + _("full") self.list.append(mount + '\t' + sizeline + ' \t' + freeline) else: self.list.append(mount + '\t' + _('Not mounted')) list2.append(device) self.list = '\n'.join(self.list) self.AboutText += self.list + "\n" self.AboutText += "\n" + _("Network Servers:") + "\n" #self.mountinfo = _("none") self.Console.ePopen("df -mh | grep -v '^Filesystem'", self.Stage1Complete) #self.AboutText +=self.mountinfo #self["AboutScrollLabel"].setText(self.AboutText) def Stage1Complete(self, result, retval, extra_args=None): result = six.ensure_str(result) 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 self.mountinfo: self.mountinfo += "\n" else: self.mountinfo += (_('none')) try: self.AboutText += self.mountinfo + "\n" except: pass self["AboutScrollLabel"].setText(self.AboutText)
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "killing self.WlanConsole" self.WlanConsole = None def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface self.WlanConsole.ePopen(cmd, self.iwconfigFinished, [iface, callback]) def iwconfigFinished(self, result, retval, extra_args): (iface, callback) = extra_args data = { 'essid': False, 'frequency': False, 'acesspoint': 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 = _("No Connection") else: tmpssid = (line[line.index('ESSID') + 7:len(line) - 1]) if tmpssid == '': ssid = _("Hidden networkname") elif tmpssid == ' ': ssid = _("Hidden networkname") else: ssid = tmpssid #print "SSID->",ssid if ssid is not None: data['essid'] = ssid if 'Frequency' in line: frequency = line[line.index('Frequency') + 10:line.index(' GHz')] #print "Frequency",frequency if frequency is not None: data['frequency'] = frequency if "Access Point" in line: ap = line[line.index('Access Point') + 14:len(line)] #print "AP",ap if ap is not None: data['acesspoint'] = ap if ap == "Not-Associated": data['essid'] = _("No Connection") if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate') + 9:line.index(' kb/s')] if br == '0': br = _("Unsupported") else: br += " Mb/s" else: br = line[line.index('Bit Rate') + 9:line.index(' Mb/s')] + " Mb/s" #print "Bitrate",br if br is not None: data['bitrate'] = br if 'Encryption key' in line: if ":off" in line: if data['acesspoint'] is not "Not-Associated": enc = _("Unsupported") else: enc = _("Disabled") else: enc = line[line.index('Encryption key') + 15:line.index(' Security')] if enc is not None: enc = _("Enabled") #print "Encryption key",enc if enc is not None: data['encryption'] = enc if 'Quality' in line: if "/100" in line: qual = line[line.index('Quality') + 8:line.index('/100')] else: qual = line[line.index('Quality') + 8:line.index('Sig')] #print "Quality",qual if qual is not None: data['quality'] = qual if 'Signal level' in line: if "dBm" in line: signal = line[line.index('Signal level') + 14:line.index(' dBm')] signal += " dBm" elif "/100" in line: signal = line[line.index('Signal level') + 13:line.index('/100 Noise')] signal += "%" else: signal = line[line.index('Signal level') + 13:line.index(' Noise')] signal += "%" #print "Signal level",signal 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 "self.wlaniface after loading:", self.wlaniface if callback is not None: callback(True, self.wlaniface) def getAdapterAttribute(self, iface, attribute): print "im getAdapterAttribute" self.iface = iface if self.wlaniface.has_key(self.iface): print "self.wlaniface.has_key", self.iface if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None
class Cpart(Screen): PA_TYPE_USE = 1 PA_TYPE_LAST = 2 PA_TYPE_FREE = 4 skin = """<screen position="center,center" size="670,200" title="eParted"> <widget source="list" render="Listbox" position="0,0" size="670,160" scrollbarMode="showOnDemand" enableWrapAround="on"> <convert type="TemplatedMultiContent"> {"template": [ MultiContentEntryText(pos = (0,5), size = (50, 30), font=0, flags = RT_HALIGN_LEFT, text=0), MultiContentEntryText(pos = (60,5), size = (150, 30), font=0, flags = RT_HALIGN_LEFT, text=1), MultiContentEntryText(pos = (210,5), size = (150, 30), font=0, flags = RT_HALIGN_LEFT, text=2), MultiContentEntryText(pos = (360,5), size = (150, 30), font=0, flags = RT_HALIGN_LEFT, text=3), MultiContentEntryText(pos = (510,5), size = (160, 30), font=0, flags = RT_HALIGN_LEFT, text=4) ], "fonts": [gFont("Regular", 20)], "itemHeight": 35 } </convert> </widget> <widget name="PixmapRed" position="25,170" size="15,16" pixmaps="skin_default/buttons/button_red_off.png,skin_default/buttons/button_red.png" transparent="1" alphatest="on" /> <widget name="LabelRed" position="50,160" size="150,40" font="Regular;19" valign="center" /> <widget name="PixmapGreen" position="225,170" size="15,16" pixmaps="skin_default/buttons/button_green_off.png,skin_default/buttons/button_green.png" transparent="1" alphatest="on" /> <widget name="LabelGreen" position="250,160" size="150,40" font="Regular;19" valign="center" /> <widget name="PixmapBlue" position="425,170" size="15,16" pixmaps="skin_default/buttons/button_blue_off.png,skin_default/buttons/button_blue.png" transparent="1" alphatest="on" /> <widget name="LabelBlue" position="450,160" size="150,40" font="Regular;19" valign="center" /> </screen>""" def __init__(self, session, entry): Screen.__init__(self, session) self["actions"] = ActionMap( ["OkCancelActions", "ColorActions"], { "cancel": self.Exit, "green": self.KeyGreen, "blue": self.KeyBlue, "red": self.KeyRed }, -1) self["list"] = List(list=[]) self["list"].onSelectionChanged.append(self.__SetLabels) self["PixmapRed"] = MultiPixmap() self["PixmapGreen"] = MultiPixmap() self["PixmapBlue"] = MultiPixmap() self["LabelRed"] = Label() self["LabelGreen"] = Label() self["LabelBlue"] = Label() self.__devpath = entry[DEV_PATH] self.__fullsize = 0 self.__old_part_list = [] self.__new_part_list = [] self.__comlist = [] self.__unit = entry[2][len(entry[2]) - 2:] self.Console = Console() self.__getPartInfo() def Exit(self): self.Console.killAll() self.close() def __getPartInfo(self, val=None): self.Console.ePopen( "parted -m %s unit %s print" % (self.__devpath, self.__unit), self.__FinishedConsole) def __Filllist(self): list = [] index = self["list"].getIndex() for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: #print x p0 = "%s: %s" % (_("Nr"), x[PA_NR]) p1 = "%s: %d%s" % (_("Start"), x[PA_START], self.__unit) p2 = "%s: %d%s" % (_("End"), x[PA_END], self.__unit) p3 = "%s: %d%s" % (_("Size"), x[PA_SIZE], self.__unit) p4 = "%s: %s" % (_("Type"), x[PA_FS]) list.append((p0, p1, p2, p3, p4, x)) self["list"].setList(list) self["list"].setIndex(index) self.__createCommandList() def __SetLabels(self): sel = self["list"].getCurrent() self["LabelGreen"].setText("") self["LabelRed"].setText("") if sel and sel[5]: if sel[5][PA_TYPE] & self.PA_TYPE_FREE and len( self.__new_part_list) < 6: self["PixmapGreen"].setPixmapNum(1) self["LabelGreen"].setText(_("add")) else: self["PixmapGreen"].setPixmapNum(0) if sel[5][PA_TYPE] & self.PA_TYPE_LAST and bool( sel[5][PA_TYPE] & self.PA_TYPE_FREE) == False: self["PixmapRed"].setPixmapNum(1) self["LabelRed"].setText(_("delete")) else: self["PixmapRed"].setPixmapNum(0) def __addFreePart(self, plist, lastPartEnd): x = [ LIST_TYPE_PAR, str(len(plist)), lastPartEnd, self.__fullsize, 0, _("free"), (self.PA_TYPE_FREE | self.PA_TYPE_LAST), ";" ] plist.append(x) def __FinishedConsole(self, result, retval, extra_args=None): if retval == 0 and '\n' in result: tlist = parseCmd(result) if len(tlist): self.__old_part_list = tlist[0][:] self.__new_part_list = tlist[0][:] lastPartEnd = 0 count = 2 for x in self.__old_part_list: if x[LIST_TYPE] == LIST_TYPE_DEV: self.__fullsize = getInt_epart(x[DEV_SIZE]) name = x[DEV_NAME] if len(name) == 0: name = x[DEV_PATH] name += " (%s)" % x[DEV_SIZE] self.setTitle(name) else: lastPartEnd = x[PA_END] x[PA_TYPE] = self.PA_TYPE_USE if count == len(self.__old_part_list): #is letzte part x[PA_TYPE] |= self.PA_TYPE_LAST count += 1 if lastPartEnd < self.__fullsize: #Wenn noch Frei, Part erstellen self.__addFreePart(self.__old_part_list, lastPartEnd) self.__addFreePart(self.__new_part_list, lastPartEnd) self.__Filllist() def KeyBlue(self): if len(self.__comlist): self.session.openWithCallback(self.__getPartInfo, Cpartexe, self.__comlist) def KeyRed(self): sel = self["list"].getCurrent() if sel and sel[1] and sel[5][PA_TYPE] & self.PA_TYPE_LAST and bool( sel[5][PA_TYPE] & self.PA_TYPE_FREE) == False: try: self.__new_part_list.remove(sel[5]) #aktuelle part löschen for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: if x[PA_TYPE] & self.PA_TYPE_FREE: #letzte Freie suchen und auch löschen self.__new_part_list.remove(x) break else: x[PA_TYPE] = self.PA_TYPE_USE lastPartEnd = 0 if len(self.__new_part_list ) > 1: #von letzter Part, TYp setzen und Ende ermitteln self.__new_part_list[ len(self.__new_part_list) - 1][PA_TYPE] = self.PA_TYPE_USE | self.PA_TYPE_LAST lastPartEnd = self.__new_part_list[ len(self.__new_part_list) - 1][PA_END] if lastPartEnd < self.__fullsize: #Wenn noch Frei, Part erstellen self.__addFreePart(self.__new_part_list, lastPartEnd) #for x in self.__new_part_list: # if x[LIST_TYPE]==LIST_TYPE_PAR: # print x except: print "[eParted] <remove part>" self.__Filllist() def KeyGreen(self): sel = self["list"].getCurrent() if sel and sel[5] and sel[5][PA_TYPE] & self.PA_TYPE_FREE and sel[5][ PA_START] < sel[5][PA_END] and len(self.__new_part_list) < 6: self.session.openWithCallback(self.__CallbackAddPart, AddPart, sel[5][PA_END] - sel[5][PA_START], self.__unit, len(self.__new_part_list) - 1) def __CallbackAddPart(self, val=None): if val: for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: if x[PA_TYPE] & self.PA_TYPE_FREE: x[PA_SIZE] = val[0] x[PA_FS] = val[1] x[PA_END] = x[PA_START] + x[PA_SIZE] x[PA_TYPE] = self.PA_TYPE_USE | self.PA_TYPE_LAST if x[PA_END] < self.__fullsize: #Wenn noch Frei, Part erstellen self.__addFreePart(self.__new_part_list, x[PA_END]) break else: x[PA_TYPE] = self.PA_TYPE_USE self.__Filllist() def __addPart2Comlist(self, list, val, mkpart=True): #print val partnr = val[PA_NR] if mkpart: fs = val[PA_FS] com = "parted -s -a optimal %s mkpart primary %s %s%s %s%s | sleep 35 | echo -e y" % ( self.__devpath, fs, val[PA_START], self.__unit, val[PA_END], self.__unit) list.append((com, _("create partition %s") % partnr, None)) mountdev = None if val[PA_FS] == "linux-swap": mkfs = "/sbin/mkswap" elif val[PA_FS] == "fat16": mkfs = "/usr/sbin/mkfs.msdos -F 16" elif val[PA_FS] == "fat32": mkfs = "/sbin/mkfs.vfat" else: mkfs = "/sbin/mkfs." + val[PA_FS] mountdev = self.__devpath + partnr if val[PA_FS] == "xfs": mkfs += " -f" com = "%s %s%s | sleep 35 | echo -e y" % (mkfs, self.__devpath, partnr) list.append( (com, _("make filesystem '%s' on partition %s (%d %s)") % (val[PA_FS], partnr, val[PA_SIZE], self.__unit), mountdev)) def __delPart2Comlist(self, list, val): partnr = val[PA_NR] dev = "%s%s" % (self.__devpath, partnr) mp = ismounted(dev) if mp is not None: if myExecute("umount %s" % mp, self.session): return list.insert(0, ("parted -s -a none %s rm %s" % (self.__devpath, partnr), _("delete partition %s") % partnr, None)) def __createCommandList(self): self.__comlist = [] #welche parts sollen gelöscht werden for x in range(len(self.__old_part_list)): if self.__old_part_list[x][LIST_TYPE] == LIST_TYPE_PAR: if bool(self.__old_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if len(self.__new_part_list) > x: if self.__old_part_list[x][ PA_SIZE] != self.__new_part_list[x][PA_SIZE]: #print self.__old_part_list[x], self.__new_part_list[x] self.__delPart2Comlist(self.__comlist, self.__old_part_list[x]) else: self.__delPart2Comlist(self.__comlist, self.__old_part_list[x]) #welche parts sollen erstellt werden for x in range(len(self.__new_part_list)): if self.__new_part_list[x][LIST_TYPE] == LIST_TYPE_PAR: if bool(self.__new_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if len(self.__old_part_list) > x and bool( self.__old_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if self.__new_part_list[x][ PA_SIZE] != self.__old_part_list[x][PA_SIZE]: #print self.__new_part_list[x], self.__old_part_list[x] self.__addPart2Comlist(self.__comlist, self.__new_part_list[x]) else: if self.__new_part_list[x][ PA_FS] != self.__old_part_list[x][PA_FS]: self.__addPart2Comlist(self.__comlist, self.__new_part_list[x], False) else: self.__addPart2Comlist(self.__comlist, self.__new_part_list[x]) #for x in self.__comlist: print "[eParted] com =",x if len(self.__comlist): self["PixmapBlue"].setPixmapNum(1) self["LabelBlue"].setText(_("execute")) else: self["PixmapBlue"].setPixmapNum(0) self["LabelBlue"].setText("")
class Devices(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Device Information")) self["TunerHeader"] = StaticText(_("Detected NIMs:")) self["HDDHeader"] = StaticText(_("Detected Devices:")) self["MountsHeader"] = StaticText(_("Network Servers:")) self["nims"] = StaticText() self["hdd"] = StaticText() self["mounts"] = StaticText() self.list = [] self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.populate2) self["actions"] = ActionMap( ["SetupActions", "ColorActions", "TimerEditActions"], { "cancel": self.close, "ok": self.close, }) self.onLayoutFinish.append(self.populate) def populate(self): self.mountinfo = '' self["actions"].setEnabled(False) scanning = _("Wait please while scanning for devices...") self["nims"].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.nimList() for count in range(len(nims)): if niminfo: niminfo += "\n" niminfo += nims[count] self["nims"].setText(niminfo) self.list = [] list2 = [] 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): continue if device in list2: continue mount = '/dev/' + device f = open('/proc/mounts', 'r') for line in f.readlines(): if device in line: parts = line.strip().split() mount = str(parts[1]) break f.close() if not mount.startswith('/dev/'): size = Harddisk(device).diskSize() free = Harddisk(device).free() if ((float(size) / 1024) / 1024) >= 1: sizeline = _("Size: ") + str( round(((float(size) / 1024) / 1024), 2)) + _("TB") elif (size / 1024) >= 1: sizeline = _("Size: ") + str(round( (float(size) / 1024), 2)) + _("GB") elif size >= 1: sizeline = _("Size: ") + str(size) + _("MB") else: sizeline = _("Size: ") + _("unavailable") 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") else: freeline = _("Free: ") + _("full") self.list.append(mount + '\t' + sizeline + ' \t' + freeline) else: self.list.append(mount + '\t' + _('Not mounted')) list2.append(device) 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 self.mountinfo: self["mounts"].setText(self.mountinfo) else: self["mounts"].setText(_('none')) self["actions"].setEnabled(True) def createSummary(self): return AboutSummary
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 AltCamManager(Screen): skin = """ <screen position="center,center" size="630,370" title="SoftCam manager"> <eLabel position="5,0" size="620,2" backgroundColor="#aaaaaa" /> <widget source="list" render="Listbox" position="10,15" size="340,300" \ scrollbarMode="showOnDemand"> <convert type="TemplatedMultiContent"> {"template": [ MultiContentEntryPixmapAlphaTest(pos = (5, 5), size = (51, 40), png = 1), MultiContentEntryText(pos = (65, 10), size = (275, 40), font=0, \ flags = RT_HALIGN_LEFT, text = 0), MultiContentEntryText(pos = (5, 25), size = (51, 16), font=1, \ flags = RT_HALIGN_CENTER, text = 2), ], "fonts": [gFont("Regular", 26),gFont("Regular", 12)], "itemHeight": 50 } </convert> </widget> <eLabel halign="center" position="390,10" size="210,35" font="Regular;20" \ text="Ecm info" transparent="1" /> <widget name="status" position="360,50" size="320,300" font="Regular;16" \ halign="left" noWrap="1" /> <eLabel position="12,358" size="148,2" backgroundColor="#00ff2525" /> <eLabel position="165,358" size="148,2" backgroundColor="#00389416" /> <eLabel position="318,358" size="148,2" backgroundColor="#00baa329" /> <eLabel position="471,358" size="148,2" backgroundColor="#006565ff" /> <widget name="key_red" position="12,328" zPosition="2" size="148,30" \ valign="center" halign="center" font="Regular;22" transparent="1" /> <widget name="key_green" position="165,328" zPosition="2" size="148,30" \ valign="center" halign="center" font="Regular;22" transparent="1" /> <widget name="key_yellow" position="318,328" zPosition="2" size="148,30" \ valign="center" halign="center" font="Regular;22" transparent="1" /> <widget name="key_blue" position="471,328" zPosition="2" size="148,30" \ valign="center" halign="center" font="Regular;22" transparent="1" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) self.Console = Console() self["key_red"] = Label(_("Stop")) self["key_green"] = Label(_("Start")) self["key_yellow"] = Label(_("Restart")) self["key_blue"] = Label(_("Setup")) self["actions"] = ActionMap( ["OkCancelActions", "ColorActions"], { "cancel": self.cancel, "ok": self.ok, "green": self.start, "red": self.stop, "yellow": self.restart, "blue": self.setup }, -1) self["status"] = ScrollLabel() self["list"] = List([]) self.actcam = config.plugins.AltSoftcam.actcam.value self.camstartcmd = "" self.CreateInfo() self.Timer = eTimer() self.Timer.callback.append(self.listecminfo) self.Timer.start(1000 * 4, False) def CreateInfo(self): global AltSoftcamConfigError if not AltSoftcamConfigError: self.StartCreateCamlist() self.listecminfo() def listecminfo(self): listecm = "" try: ecmfiles = open("/tmp/ecm.info", "r") for line in ecmfiles: if line[32:]: linebreak = line[23:].find(' ') + 23 listecm += line[0:linebreak] listecm += "\n" + line[linebreak + 1:] else: listecm += line self["status"].setText(listecm) ecmfiles.close() except: self["status"].setText("") def StartCreateCamlist(self): self.Console.ePopen("ls %s" % config.plugins.AltSoftcam.camdir.value, self.CamListStart) def CamListStart(self, result, retval, extra_args): if not result.startswith('ls: '): self.softcamlist = result self.Console.ePopen("chmod 755 %s/*" % config.plugins.AltSoftcam.camdir.value) self.Console.ePopen("pidof %s" % self.actcam, self.CamActive) def CamActive(self, result, retval, extra_args): if result.strip(): self.CreateCamList() else: for line in self.softcamlist.splitlines(): if line != self.actcam: self.Console.ePopen("pidof %s" % line, self.CamActiveFromList, line) self.Console.ePopen("echo 1", self.CamActiveFromList, "none") def CamActiveFromList(self, result, retval, extra_args): if result.strip(): self.actcam = extra_args self.CreateCamList() def CreateCamList(self): self.list = [] try: test = self.actcam except: self.actcam = "none" if self.actcam != "none": try: softpng = LoadPixmap( cached=True, path=resolveFilename( SCOPE_PLUGINS, "Extensions/AlternativeSoftCamManager/images/actcam.png" )) self.list.append( (self.actcam, softpng, self.checkcam(self.actcam))) except: pass try: softpng = LoadPixmap( cached=True, path=resolveFilename( SCOPE_PLUGINS, "Extensions/AlternativeSoftCamManager/images/defcam.png")) for line in self.softcamlist.splitlines(): if line != self.actcam: self.list.append((line, softpng, self.checkcam(line))) except: pass self["list"].setList(self.list) def checkcam(self, cam): cam = cam.lower() if "oscam" in cam: return "Oscam" elif "mgcamd" in cam: return "Mgcamd" elif "wicard" in cam: return "Wicard" elif "camd3" in cam: return "Camd3" elif "mcas" in cam: return "Mcas" elif "cccam" in cam: return "CCcam" elif "gbox" in cam: return "Gbox" elif "ufs910camd" in cam: return "Ufs910" elif "incubuscamd" in cam: return "Incubus" elif "mpcs" in cam: return "Mpcs" elif "mbox" in cam: return "Mbox" elif "newcs" in cam: return "Newcs" elif "vizcam" in cam: return "Vizcam" elif "sh4cam" in cam: return "Sh4CAM" elif "rucam" in cam: return "Rucam" else: return cam[0:6] def start(self): global AltSoftcamConfigError if not AltSoftcamConfigError: self.camstart = self["list"].getCurrent()[0] if self.camstart != self.actcam: print "[Alternative SoftCam Manager] Start SoftCam" self.camstartcmd = getcamcmd(self.camstart) msg = _("Starting %s") % self.camstart self.mbox = self.session.open(MessageBox, msg, MessageBox.TYPE_INFO) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.Stopping) self.activityTimer.start(100, False) def stop(self): if self.actcam != "none": self.Console.ePopen("killall -9 %s" % self.actcam) print "[Alternative SoftCam Manager] stop ", self.actcam try: remove("/tmp/ecm.info") except: pass msg = _("Stopping %s") % self.actcam self.actcam = "none" self.mbox = self.session.open(MessageBox, msg, MessageBox.TYPE_INFO) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.closestop) self.activityTimer.start(1000, False) def closestop(self): self.activityTimer.stop() self.mbox.close() self.CreateInfo() def restart(self): global AltSoftcamConfigError if not AltSoftcamConfigError: print "[Alternative SoftCam Manager] restart SoftCam" self.camstart = self.actcam if self.camstartcmd == "": self.camstartcmd = getcamcmd(self.camstart) msg = _("Restarting %s") % self.actcam self.mbox = self.session.open(MessageBox, msg, MessageBox.TYPE_INFO) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.Stopping) self.activityTimer.start(100, False) def Stopping(self): self.activityTimer.stop() self.Console.ePopen("killall -9 %s" % self.actcam) print "[Alternative SoftCam Manager] stopping ", self.actcam try: remove("/tmp/ecm.info") except: pass self.actcam = self.camstart service = self.session.nav.getCurrentlyPlayingServiceReference() if service: self.session.nav.stopService() self.Console.ePopen(self.camstartcmd) print "[Alternative SoftCam Manager] ", self.camstartcmd if self.mbox: self.mbox.close() if service: self.session.nav.playService(service) self.CreateInfo() def ok(self): if self["list"].getCurrent()[0] != self.actcam: self.start() else: self.restart() def cancel(self): if config.plugins.AltSoftcam.actcam.value != self.actcam: config.plugins.AltSoftcam.actcam.value = self.actcam config.plugins.AltSoftcam.actcam.save() self.close() def setup(self): self.session.openWithCallback(self.CreateInfo, ConfigEdit)