コード例 #1
0
ファイル: InstallWizard.py プロジェクト: OpenESI/Gui
	def __init__(self, session, args = None):
		Screen.__init__(self, session)

		self.index = args
		self.list = []
		ConfigListScreen.__init__(self, self.list)

		if self.index == self.STATE_UPDATE:
			config.misc.installwizard.hasnetwork.value = False
			config.misc.installwizard.ipkgloaded.value = False
			modes = {0: " "}
			self.enabled = ConfigSelection(choices = modes, default = 0)
			self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			is_found = False
			for x in self.adapters:
				if x[1] == 'eth0' or x[1] == 'eth1':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
			if is_found is False:
				self.createMenu()
		elif self.index == self.STATE_CHOISE_CHANNELLIST:
			self.enabled = ConfigYesNo(default = True)
			modes = {"ESI": "ESI default(13e-19e)", "19e": "Astra 1", "23e": "Astra 3", "19e-23e": "Astra 1 Astra 3", "19e-23e-28e": "Astra 1 Astra 2 Astra 3", "13e-19e-23e-28e": "Astra 1 Astra 2 Astra 3 Hotbird"}
			self.channellist_type = ConfigSelection(choices = modes, default = "ESI")
			self.createMenu()
コード例 #2
0
	def __init__(self, session, args = None):
		Screen.__init__(self, session)

		self.index = args
		self.list = []
		ConfigListScreen.__init__(self, self.list)

		if self.index is self.STATE_UPDATE:
			config.misc.installwizard.hasnetwork.value = False
			config.misc.installwizard.ipkgloaded.value = False
			modes = {0: " "}
			self.enabled = ConfigSelection(choices = modes, default = 0)
			self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			is_found = False
			for x in self.adapters:
				if x[1] == 'eth0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
			if is_found is False:
				self.createMenu()
		elif self.index is self.STATE_CHOISE_CHANNELLIST:
			self.enabled = ConfigYesNo(default = True)
			modes = {"19e-23e-basis": "Astra1 Astra3 basis", "19e-23e": "Astra 1 Astra 3", "19e-23e-28e": "Astra 1 Astra 2 Astra 3", "13e-19e-23e-28e": "Astra 1 Astra 2 Astra 3 Hotbird", "kabelnl": "Kabel-NL"}
			self.channellist_type = ConfigSelection(choices = modes, default = "19e-23e-basis")
			self.createMenu()
		elif self.index is self.STATE_CHOISE_SOFTCAM:
			self.enabled = ConfigYesNo(default = True)
			modes = {"wicardd": _("default") + " (Wicard)", "oscam-ymod": "Oscam-Ymod", "mgcamd": "Mgcamd", "cccam": "Cccam"}
			self.softcam_type = ConfigSelection(choices = modes, default = "wicardd")
			self.createMenu()
コード例 #3
0
def getAllNetworks():
	tempaddrs = []
	# Get all IP networks
	if fileExists('/proc/net/if_inet6'):
		if has_ipv6 and version.major >= 12:
			proc = '/proc/net/if_inet6'
			for line in file(proc).readlines():
				# Skip localhost
				if line.startswith('00000000000000000000000000000001'):
					continue

				tmp = line.split()
				tmpaddr = str(ipaddress.ip_address(int(tmp[0], 16)))
				if tmp[2].lower() != "ff":
					tmpaddr = "%s/%s" % (tmpaddr, int(tmp[2].lower(), 16))
					tmpaddr = str(ipaddress.IPv6Network(unicode(tmpaddr), strict=False))

				tempaddrs.append(tmpaddr)
	# Crappy legacy IPv4 has no proc entry with clean addresses
	ifaces = iNetwork.getConfiguredAdapters()
	for iface in ifaces:
		# IPv4 and old fashioned netmask are served as silly arrays
		crap = iNetwork.getAdapterAttribute(iface, "ip")
		if not crap or len(crap) != 4:
			continue
		ip = '.'.join(str(x) for x in crap)
		netmask = str(sum([bin(int(x)).count('1') for x in iNetwork.getAdapterAttribute(iface, "netmask")]))
		ip = ip + "/" + netmask
		tmpaddr = str(ipaddress.IPv4Network(unicode(ip), strict=False))
		tempaddrs.append(tmpaddr)

	if tempaddrs == []:
		return None
	else:
		return tempaddrs
コード例 #4
0
	def __init__(self, session, args = None):
		Screen.__init__(self, session)

		self.index = args
		self.list = []
		ConfigListScreen.__init__(self, self.list)

		if self.index == self.STATE_UPDATE:
			config.misc.installwizard.hasnetwork.value = False
			config.misc.installwizard.ipkgloaded.value = False
			modes = {0: " "}
			self.enabled = ConfigSelection(choices = modes, default = 0)
			self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			is_found = False
			for x in self.adapters:
				if x[1] == 'eth0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
			if is_found is False:
				self.createMenu()
		elif self.index == self.STATE_CHOISE_CHANNELLIST:
			self.enabled = ConfigYesNo(default = True)
			modes = {"19e": "SAT: 19e", "19e-13e": "SAT: 19e 13e", "19e-13e-5e-75e": "SAT: 19e 13e 5e 75e", "19e-16e-13e": "SAT: 19e 13e 16e", "42e-19e-13e-7e": "SAT: 42e 19e 13e 7e"}
			self.channellist_type = ConfigSelection(choices = modes, default = "19e")
			self.createMenu()
		elif self.index == self.STATE_CHOISE_SOFTCAM:
			self.enabled = ConfigYesNo(default = True)
			modes = {"oscam": _("default") + " (Oscam)", "cccam": "CCcam", "scam": "scam"}
			self.softcam_type = ConfigSelection(choices = modes, default = "oscam")
			self.createMenu()
コード例 #5
0
ファイル: TestMenu.py プロジェクト: pli3/enigma2-git
	def checkNetworkCB(self,data):
		try:
			if iNetwork.getAdapterAttribute(self.iface, "up") is True:
				if self.LinkState is True:
					if data <= 2:
						ip = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0]).getText()
						if ip == "0.0.0.0":
							self.networkMonitor.stop()
							self.restartLan()
							self["lan_s"].setText(_(" Getting..."))
							self["lan_s"].setForegroundColorNum(0)
							return

						self["lan_s"].setText(_(" %s") % ip)
						self["lan_s"].setForegroundColorNum(1)
					else:
						self["lan_s"].setText(_(" N/A"))
						self["lan_s"].setForegroundColorNum(0)
				else:
					self["lan_s"].setText(_(" N/A"))
					self["lan_s"].setForegroundColorNum(0)
			else:
				self["lan_s"].setText(_(" N/A"))
				self["lan_s"].setForegroundColorNum(0)
			self.networkMonitor.start(1000, True)
		except:
			pass
コード例 #6
0
ファイル: InstallWizard.py プロジェクト: trunca/novale-viejo
	def __init__(self, session, args = None):
		Screen.__init__(self, session)

		self.index = args
		self.list = []
		ConfigListScreen.__init__(self, self.list)

		if self.index == self.STATE_UPDATE:
			config.misc.installwizard.hasnetwork.value = False
			config.misc.installwizard.ipkgloaded.value = False
			modes = {0: " "}
			self.enabled = ConfigSelection(choices = modes, default = 0)
			self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			is_found = False
			for x in self.adapters:
				if x[1] == 'eth0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
			if is_found is False:
				self.createMenu()
		elif self.index == self.STATE_CHOISE_CHANNELLIST:
			self.enabled = ConfigYesNo(default = True)
			modes = {"sfteam": "Astra 19e", "23e": "Astra 3", "19e-23e": "Astra 1 Astra 3", "19e-23e-28e": "Astra 1 Astra 2 Astra 3", "13e-19e-23e-28e": "Astra 1 Astra 2 Astra 3 Hotbird"}
			self.channellist_type = ConfigSelection(choices = modes, default = "sfteam")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_PICONS:
			self.enabled = ConfigYesNo(default = True)
			modes = {"220x132.black-white": "Astra 19e - Black White 220x132", "220x132.white-black": "Astra 19e - White Black 220x132", "220x132.blue-black": "Astra 19e - Blue Black 220x132", "220x132.reflection-black": "Astra 19e - Reflection Black 220x132", "220x132.transparent-black": "Astra 19e - Transparent Black 220x132", "220x132.transparent-white": "Astra 19e - Transparent White 220x132"}
			self.picons_type = ConfigSelection(choices = modes, default = "220x132.black-white")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_SOFTCAM:
			self.enabled = ConfigYesNo(default = True)
			modes = {"cccam230": "CCcam 2.3.0", "cccam221": "CCcam 2.2.1","cccam214": "CCcam 2.1.4","mgcamd": "MGcamd 1.30d","evocamd": "Evocamd 2.1.7","rqcamd": "RQcamd 1.3.1","scam": "Scam 3.5.3",}
			self.softcam_type = ConfigSelection(choices = modes, default = "cccam230")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_CARDSERVER:
			self.enabled = ConfigYesNo(default = True)
			modes = {"oscam": "OScam","newcs167": "NewCS 1.6.7"}
			self.cardserver_type = ConfigSelection(choices = modes, default = "oscam")
			self.createMenu()
			
		elif self.index == self.STATE_CHOISE_MBOOT:
			self.enabled = ConfigYesNo(default = True)
			modes = {"openmultiboot": "OpenMultiBoot"}
			self.cache_type = ConfigSelection(choices = modes, default = "openmultiboot")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_HBBTV:
			self.enabled = ConfigYesNo(default = True)
			modes = {"browser": "Install"}
			self.hbbtv_type = ConfigSelection(choices = modes, default = "browser")
			self.createMenu()
コード例 #7
0
ファイル: InstallWizard.py プロジェクト: vega123/enigma2
	def __init__(self, session, args = None):
		Screen.__init__(self, session)

		self.index = args
		self.list = []
		ConfigListScreen.__init__(self, self.list)

		if self.index == self.STATE_UPDATE:
			config.misc.installwizard.hasnetwork.value = False
			config.misc.installwizard.ipkgloaded.value = False
			modes = {0: " "}
			self.enabled = ConfigSelection(choices = modes, default = 0)
			self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			is_found = False
			for x in self.adapters:
				if x[1] == 'eth0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
			if is_found is False:
				self.createMenu()
		elif self.index == self.STATE_CHOISE_CHANNELLIST:
			self.enabled = ConfigYesNo(default = True)
			modes = {"19e": "Astra 1", "23e": "Astra 3", "19e-23e": "Astra 1 Astra 3", "19e-23e-28e": "Astra 1 Astra 2 Astra 3", "13e-19e-23e-28e": "Astra 1 Astra 2 Astra 3 Hotbird"}
			self.channellist_type = ConfigSelection(choices = modes, default = "19e")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_PICONS:
			self.enabled = ConfigYesNo(default = True)
			modes = {"19e": "Astra 19e", "23e": "Astra 3", "19e-23e": "Astra 1 Astra 3", "19e-23e-28e": "Astra 1 Astra 2 Astra 3", "13e-19e-23e-28e": "Astra 1 Astra 2 Astra 3 Hotbird"}
			self.picons_type = ConfigSelection(choices = modes, default = "19e")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_EPG:
			self.enabled = ConfigYesNo(default = True)
			modes = {"xmltvimport": "Xmltvimport", "crossepg": "CrossEPG"}
			self.epg_type = ConfigSelection(choices = modes, default = "xmltvimport")
			self.createMenu()
			
		elif self.index == self.STATE_CHOISE_TDT:
			self.enabled = ConfigYesNo(default = True)
			modes = {"siano": "Siano", "Volar Black": "Hauppauge"}
			self.tdt_type = ConfigSelection(choices = modes, default = "siano")
			self.createMenu()

		elif self.index == self.STATE_CHOISE_SOFTCAM:
			self.enabled = ConfigYesNo(default = True)
			modes = {"cccam": "CCcam", "oscam": "Oscam"}
			self.softcam_type = ConfigSelection(choices = modes, default = "cccam")
			self.createMenu()
			
		elif self.index == self.STATE_CHOISE_CACHE:
			self.enabled = ConfigYesNo(default = True)
			modes = {"multics": "MultiCS"}
			self.cache_type = ConfigSelection(choices = modes, default = "multics")
			self.createMenu()
コード例 #8
0
ファイル: About.py プロジェクト: 4doe/e2plugins
	def command(self):
		def ConvertIP(list):
			if len(list) == 4:
				retstr = "%s.%s.%s.%s" % (list[0], list[1], list[2], list[3])
			else:
				retstr = "0.0.0.0"
			return retstr

		list = []

		if iNetwork.getNumberOfAdapters > 0:
			iface = iNetwork.getAdapterList()[0]
			print "[WebComponents.About] iface: %s" % iface
			list.extend((
				iNetwork.getAdapterAttribute(iface, "mac"),
				iNetwork.getAdapterAttribute(iface, "dhcp"),
				ConvertIP(iNetwork.getAdapterAttribute(iface, "ip")),
				ConvertIP(iNetwork.getAdapterAttribute(iface, "netmask")),
				ConvertIP(iNetwork.getAdapterAttribute(iface, "gateway")),
			))
		else:
			print "[WebComponents.About] no network iface configured!"
			list.extend((
				"N/A",
				"N/A",
				"N/A",
				"N/A",
				"N/A",
			))

		return (list,)
コード例 #9
0
ファイル: Wlan.py プロジェクト: OUARGLA86/enigma2
    def getNetworkList(self):
        if self.oldInterfaceState is None:
            self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
        if self.oldInterfaceState is False:
            if iNetwork.getAdapterAttribute(self.iface, "up") is False:
                iNetwork.setAdapterAttribute(self.iface, "up", True)
                system("ifconfig " + self.iface + " up")

        ifobj = Wireless(self.iface)  # a Wireless NIC Object

        try:
            scanresults = ifobj.scan()
        except:
            scanresults = None
            print "[Wlan.py] No wireless networks could be found"
        aps = {}
        if scanresults is not None:
            (num_channels, frequencies) = ifobj.getChannelInfo()
            index = 1
            for result in scanresults:
                bssid = result.bssid

                if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
                    encryption = False
                elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
                    encryption = True
                else:
                    encryption = None

                signal = str(result.quality.siglevel - 0x100) + " dBm"
                quality = "%s/%s" % (result.quality.quality, ifobj.getQualityMax().quality)

                extra = []
                for element in result.custom:
                    element = element.encode()
                    extra.append(strip(self.asciify(element)))
                for element in extra:
                    if "SignalStrength" in element:
                        signal = element[element.index("SignalStrength") + 15 : element.index(",L")]
                    if "LinkQuality" in element:
                        quality = element[element.index("LinkQuality") + 12 : len(element)]

                        # noinspection PyProtectedMember
                aps[bssid] = {
                    "active": True,
                    "bssid": result.bssid,
                    "channel": frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
                    "encrypted": encryption,
                    "essid": strip(self.asciify(result.essid)),
                    "iface": self.iface,
                    "maxrate": ifobj._formatBitrate(result.rate[-1][-1]),
                    "noise": "",  # result.quality.nlevel-0x100,
                    "quality": str(quality),
                    "signal": str(signal),
                    "custom": extra,
                }

                index += 1
        return aps
コード例 #10
0
ファイル: Wlan.py プロジェクト: dazulrich/dvbapp
	def getNetworkList(self):
		if self.oldInterfaceState is None:
			self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
		if self.oldInterfaceState is False:
			if iNetwork.getAdapterAttribute(self.iface, "up") is False:
				iNetwork.setAdapterAttribute(self.iface, "up", True)
				enigma.eConsoleAppContainer().execute("ifconfig %s up" % self.iface)

		ifobj = Wireless(self.iface) # a Wireless NIC Object

		try:
			scanresults = ifobj.scan()
		except:
			scanresults = None
			print "[Wlan.py] No wireless networks could be found"
		aps = {}
		if scanresults is not None:
			(num_channels, frequencies) = ifobj.getChannelInfo()
			index = 1
			for result in scanresults:
				bssid = result.bssid

				if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
					encryption = False
				elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
					encryption = True
				else:
					encryption = None

				signal = str(result.quality.siglevel-0x100) + " dBm"
				quality = "%s/%s" % (result.quality.quality,ifobj.getQualityMax().quality)

				extra = []
				for element in result.custom:
					element = element.encode()
					extra.append( strip(self.asciify(element)) )
				for element in extra:
					if 'SignalStrength' in element:
						signal = element[element.index('SignalStrength')+15:element.index(',L')]
					if 'LinkQuality' in element:
						quality = element[element.index('LinkQuality')+12:len(element)]

				# noinspection PyProtectedMember
				aps[bssid] = {
					'active' : True,
					'bssid': result.bssid,
					'channel': frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
					'encrypted': encryption,
					'essid': strip(self.asciify(result.essid)),
					'iface': self.iface,
					'maxrate' : ifobj._formatBitrate(result.rate[-1][-1]),
					'noise' : '',#result.quality.nlevel-0x100,
					'quality' : str(quality),
					'signal' : str(signal),
					'custom' : extra,
				}

				index += 1
		return aps
コード例 #11
0
	def makeStrIP(self):
		self.IP = iNetwork.getAdapterAttribute(self.iface, "ip")
		self.netmask = iNetwork.getAdapterAttribute(self.iface, "netmask")
		if self.IP and self.netmask and len(self.IP) == 4 and len(self.netmask) == 4 and sum(self.IP) and sum(self.netmask):
			strCIDR = str(sum((bin(x).count('1') for x in self.netmask)))
			strIP = '.'.join((str(ip & mask) for ip, mask in zip(self.IP, self.netmask))) + "/" + strCIDR
			return strIP
		return None
コード例 #12
0
ファイル: plugin.py プロジェクト: CompoUK/E2-OpenPlugins
	def getValue(self, oid, storage):
		oidstring = bisectoidstore.sortableToOID(oid)
		if oidstring == self.SYSTEMDESCRIPTION_OID:
			return v1.OctetString(str(config.plugins.SnmpAgent.systemdescription.value))
		elif oidstring == self.SYSUPTIME_OID:
			return self.getSysUpTime()
		elif oidstring == self.SUPPORTADDRESS_OID:
			return v1.OctetString(str(config.plugins.SnmpAgent.supportaddress.value))
		elif oidstring == self.SYSTEMNAME_OID:
			return v1.OctetString(str(config.plugins.SnmpAgent.systemname.value))
		elif oidstring == self.LOCATION_OID:
			return v1.OctetString(str(config.plugins.SnmpAgent.location.value))
		elif oidstring == self.BER_OID:
			return self.getBER()
		elif oidstring == self.AGC_OID:
			return self.getACG()
		elif oidstring == self.SNR_OID:
			return self.getSNR()
		elif oidstring == self.HASPICTURE_OID:
			return self.haspicture
		elif oidstring == self.VIDEO_BITRATE_OID:
			if self.bitrate:
				return self.bitrate.vcur
			else:
				return 0
		elif oidstring == self.AUDIO_BITRATE_OID:
			if self.bitrate:
				return self.bitrate.acur
			else:
				return 0
		elif oidstring == self.CHANNELNAME_OID:
			return v1.OctetString(self.getChannelName())
		elif oidstring == self.SERVICESTRING_OID:
			return v1.OctetString(self.getServiceString())
		elif oidstring == self.FASTSCANSTRING_OID:
			return v1.OctetString('')
		elif oidstring == self.SERVICEPARAMS_OID:
			return v1.OctetString(self.getServiceParams())
		elif oidstring == self.MANAGERIP_OID:
			return v1.OctetString(str(config.plugins.SnmpAgent.managerip.value))
		elif oidstring == self.ENABLE_BITRATE_OID:
			return config.plugins.SnmpAgent.measurebitrate.value
		elif oidstring == self.IP_OID:
			value = "%d.%d.%d.%d" % tuple(iNetwork.getAdapterAttribute(self.iface, "ip"))
			return v1.IpAddress(value)
		elif oidstring == self.NETMASK_OID:
			value = "%d.%d.%d.%d" % tuple(iNetwork.getAdapterAttribute(self.iface, "netmask"))
			return v1.IpAddress(value)
		elif oidstring == self.GATEWAY_OID:
			value = "%d.%d.%d.%d" % tuple(iNetwork.getAdapterAttribute(self.iface, "gateway"))
			return v1.IpAddress(value)
		elif oidstring == self.ENABLE_EMM_OID:
			return config.plugins.SnmpAgent.checkemm.value
		elif oidstring == self.EMM_OID:
			if self.emm:
				return v1.OctetString(self.emm.pids)
			else:
				return v1.OctetString('')
コード例 #13
0
ファイル: Network.py プロジェクト: TitanNit/tdt
	def getInterface(self):
		iface = Interface(self.iface)
		iface.mac = iNetwork.getAdapterAttribute(self.iface, "mac")
		iface.dhcp = iNetwork.getAdapterAttribute(self.iface, "dhcp")
		iface.ip = self.ConvertIP(iNetwork.getAdapterAttribute(self.iface, "ip"))
		iface.netmask = self.ConvertIP(iNetwork.getAdapterAttribute(self.iface, "netmask"))
		iface.gateway = self.ConvertIP(iNetwork.getAdapterAttribute(self.iface, "gateway"))

		return iface
	def getBoolean(self):
		ret=False
		service = self.source.service
		info = service and service.info()
		if not info:
			return False

		if self.type == self.INETCONECTION:
			if not hayinet():
				ret=False
			else:	
				try:
					f = open("/tmp/testinet.txt", "r")
					texto =f.read().replace("\n","")
					f.close()
					if "1 packets transmitted, 1 packets received" in texto:
						ret=True
				except:
					pass
				try:
					system("ping -q -c 1 -s 6 -w 2 www.google.es >/tmp/testinet.txt &")
				except:
					pass
				
		elif self.type == self.NETCONECTION:
		
			try:
				adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			except:
				adapters = False
			if not adapters:
				ret=False
			else:
				puerta="0.0.0.0"
				for x in adapters:
					
					if iNetwork.getAdapterAttribute(x[1], 'up') is True:
						puerta=str(iNetwork.getAdapterAttribute(x[1], "gateway")).replace(",",".").replace("[","").replace(" ","").replace("]","")
						break;
				if puerta=="0.0.0.0":
					ret=False
				else:
					
					try:
						f = open("/tmp/testnet.txt", "r")
						texto =f.read().replace("\n","")
						f.close()
						if "1 packets transmitted, 1 packets received" in texto:
							ret=True
					except:
						pass
					try:
						system("ping -q -c 1 -s 6 -w 2 "+puerta+" >/tmp/testnet.txt &")
					except:
						pass
					# system("echo '"+puerta+"' >/tmp/gat.txt")
		return ret	
コード例 #15
0
    def getBoolean(self):
        ret = False
        service = self.source.service
        info = service and service.info()
        if not info:
            return False
        if self.type == self.INETCONECTION:
            if not hayinet():
                ret = False
            else:
                try:
                    f = open('/tmp/testinet.txt', 'r')
                    texto = f.read().replace('\n', '')
                    f.close()
                    if '1 packets transmitted, 1 packets received' in texto:
                        ret = True
                except:
                    pass

                try:
                    system('ping -q -c 1 -s 6 -w 2 www.google.com >/tmp/testinet.txt &')
                except:
                    pass

        elif self.type == self.NETCONECTION:
            try:
                adapters = [ (iNetwork.getFriendlyAdapterName(x), x) for x in iNetwork.getAdapterList() ]
            except:
                adapters = False

            if not adapters:
                ret = False
            else:
                puerta = '0.0.0.0'
                for x in adapters:
                    if iNetwork.getAdapterAttribute(x[1], 'up') is True:
                        puerta = str(iNetwork.getAdapterAttribute(x[1], 'gateway')).replace(',', '.').replace('[', '').replace(' ', '').replace(']', '')
                        break

                if puerta == '0.0.0.0':
                    ret = False
                else:
                    try:
                        f = open('/tmp/testnet.txt', 'r')
                        texto = f.read().replace('\n', '')
                        f.close()
                        if '1 packets transmitted, 1 packets received' in texto:
                            ret = True
                    except:
                        pass

                    try:
                        system('ping -q -c 1 -s 6 -w 2 ' + puerta + ' >/tmp/testnet.txt &')
                    except:
                        pass

        return ret
コード例 #16
0
	def getInstalledInterfaceCount(self):
		self.rescanTimer.stop()
		self.Adapterlist = iNetwork.getAdapterList()
		self.InstalledInterfaceCount = len(self.Adapterlist)
		if self.Adapterlist is not None:
			if self.InstalledInterfaceCount == 1 and self.selectedInterface is None:
					self.selectedInterface = self.Adapterlist[0]
		self.originalAth0State = iNetwork.getAdapterAttribute('ath0', 'up')
		self.originalEth0State = iNetwork.getAdapterAttribute('eth0', 'up')
		self.originalWlan0State = iNetwork.getAdapterAttribute('wlan0', 'up')
コード例 #17
0
ファイル: Network.py プロジェクト: TitanNit/tdt
	def getList(self):
		return [
			(
					ifname,
					iNetwork.getAdapterAttribute(ifname, "mac"),
					iNetwork.getAdapterAttribute(ifname, "dhcp"),
					self.ConvertIP(iNetwork.getAdapterAttribute(ifname, "ip")),
					self.ConvertIP(iNetwork.getAdapterAttribute(ifname, "netmask")),
					self.ConvertIP(iNetwork.getAdapterAttribute(ifname, "gateway"))
			)
			for ifname in iNetwork.getConfiguredAdapters()
		]
コード例 #18
0
    def __init__(self, session, args = None):
        Screen.__init__(self, session)
        self.index = args
        self.list = []
        ConfigListScreen.__init__(self, self.list)
        self.ipConfigEntry = ConfigIP(default=[0,
         0,
         0,
         0])
        self.interface = 'eth0'
        if self.index == self.STATE_UPDATE:
            config.misc.installwizard.hasnetwork.value = False
            config.misc.installwizard.ipkgloaded.value = False
            modes = {0: ' '}
            self.enabled = ConfigSelection(choices=modes, default=0)
            self.adapters = [ (iNetwork.getFriendlyAdapterName(x), x) for x in iNetwork.getAdapterList() ]
            is_found = False
            for x in self.adapters:
                if x[1] == 'eth0':
                    if iNetwork.getAdapterAttribute(x[1], 'up'):
                        self.ipConfigEntry = ConfigIP(default=iNetwork.getAdapterAttribute(x[1], 'ip'))
                        iNetwork.checkNetworkState(self.checkNetworkCB)
                        if_found = True
                        self.interface = x[1]
                    else:
                        iNetwork.restartNetwork(self.checkNetworkLinkCB)
                    break

            if is_found is False:
                self.createMenu()
        elif self.index == self.STATE_CHOISE_CHANNELLIST:
            self.enabled = ConfigYesNo(default=True)
            modes = {'henksat-19e': 'Astra 1',
             'henksat-23e': 'Astra 3',
             'henksat-19e-23e': 'Astra 1 Astra 3',
             'henksat-19e-23e-28e': 'Astra 1 Astra 2 Astra 3',
             'henksat-13e-19e-23e-28e': 'Astra 1 Astra 2 Astra 3 Hotbird'}
            self.channellist_type = ConfigSelection(choices=modes, default='henksat-13e-19e-23e-28e')
            self.createMenu()
        elif self.index == self.STATE_CHOISE_SOFTCAM:
            self.enabled = ConfigYesNo(default=True)
            modes = {'oscam': _('default') + ' OSCam',
             'cccam': 'CCcam',
             'gbox': 'GBox',
             'wicardd': 'Wicardd',
             'mgcamd': 'MGCamd'}
            if getBoxType() in 'vusolo4k':
                modes = {'oscam': _('default') + ' OSCam',
                 'wicardd': 'Wicardd'}
            if getBoxType() in 'wetekplay':
                modes = {'oscam': _('default') + ' OSCam'}
            self.softcam_type = ConfigSelection(choices=modes, default='oscam')
            self.createMenu()
コード例 #19
0
ファイル: NetworkBrowser.py プロジェクト: OUARGLA86/enigma2
 def getNetworkIPs(self):
     nwlist = []
     sharelist = []
     self.IP = iNetwork.getAdapterAttribute(self.iface, 'ip')
     print 'Current IP',
     print self.IP
     print 'EthIP',
     print iNetwork.getAdapterAttribute('eth0', 'ip')
     print 'WlanIP',
     print iNetwork.getAdapterAttribute('wlan0', 'ip')
     if len(self.IP):
         strIP = str(self.IP[0]) + '.' + str(self.IP[1]) + '.' + str(self.IP[2]) + '.0/24'
         nwlist.append(netscan.netzInfo(strIP))
     tmplist = nwlist[0]
     return tmplist
コード例 #20
0
	def doServStart(self):
		self.activityTimer.stop()
		if os.path.exists("/media/hdd/tuner"):
			rmtree("/media/hdd/tuner")
		ifaces = iNetwork.getConfiguredAdapters()
		for iface in ifaces:
			ip = iNetwork.getAdapterAttribute(iface, "ip")
			ipm = "%d.%d.%d.%d" % (ip[0], ip[1], ip[2], ip[3])
			if ipm != "0.0.0.0":
				self.ip = ipm

		os.mkdir("/media/hdd/tuner", 0755)
		s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
		serviceHandler = eServiceCenter.getInstance()
		services = serviceHandler.list(eServiceReference('%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet'%(s_type)))
		bouquets = services and services.getContent("SN", True)
		count = 1
		for bouquet in bouquets:
			self.poPulate(bouquet, count)
			count += 1

		mytext = "Server avaliable on ip %s\nTo access this box's tuners you can connect via Lan or UPnP.\n\n1) To connect via lan you have to mount the /media/hdd folder of this box in the client /media/hdd folder. Then you can access the tuners server channel list from the client Media player -> Harddisk -> tuner.\n2) To connect via UPnP you need an UPnP server that can manage .m3u files like Mediatomb." % (self.ip)
		self["lab1"].setText(_(mytext))
		self.session.open(MessageBox, _("Build Complete!"), MessageBox.TYPE_INFO)
		self.updateServ()
コード例 #21
0
	def doServStart(self):
		self.activityTimer.stop()
		if os.path.exists("/media/hdd/tuner"):
			rmtree("/media/hdd/tuner")
		ifaces = iNetwork.getConfiguredAdapters()
		for iface in ifaces:
			ip = iNetwork.getAdapterAttribute(iface, "ip")
			ipm = "%d.%d.%d.%d" % (ip[0], ip[1], ip[2], ip[3])
			if ipm != "0.0.0.0":
				self.ip = ipm

		os.mkdir("/media/hdd/tuner", 0755)
		s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
		serviceHandler = eServiceCenter.getInstance()
		services = serviceHandler.list(eServiceReference('%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet'%(s_type)))
		bouquets = services and services.getContent("SN", True)
		count = 1
		for bouquet in bouquets:
			self.poPulate(bouquet, count)
			count += 1

		mytext = "Servidor disponible en la ip %s\nPara acceder a este sevidor, puede conectar via LAN o UPnP.\n\n1) Para conectar a traves de LAN tiene que montar la carpeta /media/hdd de este decodificador en el cliente. A continuacion, puede acceder a la lista de canales del servidor de sintonizadores desde el reproductor de medios del cliente. -> /media/hdd -> tuner.\n2) Para conectar mediante UPnP que necesita un servidor UPnP que pueda manejar archivos .m3u. Como Xupnpd que ya viene preinstalado en Openplus." % (self.ip)
		self["lab1"].setText(_(mytext))
		self.session.open(MessageBox, _("Build Complete!"), MessageBox.TYPE_INFO)
		self.updateServ()
コード例 #22
0
ファイル: BhNet.py プロジェクト: kingvuplus/Bh-E2
    def doServStart(self):
        self.activityTimer.stop()
        ret = system('rm -rf /media/hdd/tuner')
        ifaces = iNetwork.getConfiguredAdapters()
        for iface in ifaces:
            ip = iNetwork.getAdapterAttribute(iface, 'ip')
            ipm = '%d.%d.%d.%d' % (ip[0],
             ip[1],
             ip[2],
             ip[3])
            if ipm != '0.0.0.0':
                self.ip = ipm

        ret = system('mkdir /media/hdd/tuner')
        chdir('/media/hdd/tuner')
        s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
        serviceHandler = eServiceCenter.getInstance()
        services = serviceHandler.list(eServiceReference('%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % s_type))
        bouquets = services and services.getContent('SN', True)
        count = 1
        for bouquet in bouquets:
            self.poPulate(bouquet, count)
            count += 1

        chdir('/home/root')
        mytext = _('Server avaliable on ip ' + self.ip + ' \n\n')
        mytext += _("To access this box's tuners you can connect via lan or UPnP.\n\n")
        mytext += _('1) To connect via lan you have to mount the /media/hdd folder of this box in the client /media/hdd folder. Then you can access the tuners server channel list from the client Media player -> Harddisk -> tuner.\n')
        mytext += _('2) To connect via UPnP you have to start Mediatomb on this box and then start Djmount on the client. Then you can access the tuners server channel list for the client Media Player -> DLNA -> MediaTomb -> playlists.\n\n')
        mytext += _('NOTE about UPnP: Because UPnP requires alot of memory, you should only use it if you need to access your box from a PS3 or other device that cannot be mounted via Lan. Also, After the server has been built we strongly suggest you delete the Bouquets directory that are not really needed BEFORE you start Mediatomb. This will save alot of memory and resources.')
        self['lab1'].setText(mytext)
        self.session.open(MessageBox, _('Build Complete.'), MessageBox.TYPE_INFO)
        self.updateServ()
コード例 #23
0
ファイル: InstallWizard.py プロジェクト: Antonio-Team/enigma2
	def createMenu(self):
		try:
			test = self.index
		except:
			return
		self.list = []
		if self.index == self.STATE_UPDATE:
			if config.misc.installwizard.hasnetwork.value:
				ip = ".".join([str(x) for x in iNetwork.getAdapterAttribute(self.adapter, "ip")])
				self.list.append(getConfigListEntry(_("Your internet connection is working (ip: %s)") % ip, self.enabled))
			else:
				self.list.append(getConfigListEntry(_("Your receiver does not have an internet connection"), self.enabled))
		elif self.index == self.STATE_CHOISE_CHANNELLIST:
			self.list.append(getConfigListEntry(_("Install channel list"), self.enabled))
			if self.enabled.value:
				self.list.append(getConfigListEntry(_("Channel list type"), self.channellist_type))
		elif self.index == self.INSTALL_PLUGINS:
			self.list.append(getConfigListEntry(_("No, I do not want to install plugins"), self.noplugins))
			self.list.append(getConfigListEntry(_("Yes, I do want to install plugins"), self.doplugins))
		elif self.index == self.SCAN:
			self.list.append(getConfigListEntry(_("I do not want to perform any service scans"), self.noscan))
			self.list.append(getConfigListEntry(_("Do an automatic service scan now"), self.autoscan))
			self.list.append(getConfigListEntry(_("Do a manual service scan now"), self.manualscan))
			self.list.append(getConfigListEntry(_("Do a fast service scan now"), self.fastscan))
			self.list.append(getConfigListEntry(_("Do a cable service scan now"), self.cablescan))
		self["config"].list = self.list
		self["config"].l.setList(self.list)
コード例 #24
0
ファイル: LdTunerServer.py プロジェクト: OpenLD/enigma2
	def doServStart(self):
		self.activityTimer.stop()
		if os.path.exists('/media/hdd/tuner'):
			rmtree('/media/hdd/tuner')
		ifaces = iNetwork.getConfiguredAdapters()
		for iface in ifaces:
			ip = iNetwork.getAdapterAttribute(iface, 'ip')
			ipm = '%d.%d.%d.%d' % (ip[0],
			 ip[1],
			 ip[2],
			 ip[3])
			if ipm != '0.0.0.0':
				self.ip = ipm

		os.mkdir('/media/hdd/tuner', 0755)
		s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
		serviceHandler = eServiceCenter.getInstance()
		services = serviceHandler.list(eServiceReference('%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % s_type))
		bouquets = services and services.getContent('SN', True)
		count = 1
		for bouquet in bouquets:
			self.poPulate(bouquet, count)
			count += 1

		if config.osd.language.value == 'es_ES':
			mytext = "Servidor disponible en IP %s\nPara acceder a los sintonizadores de este receptor puedes conectarte desde la LAN o UPnP.\n\n1) Para conectar desde la LAN tienes que montar el directorio /media/hdd de este receptor en el directorio del receptor cliente /media/hdd. Una vez realizado todo esto, ya puedes acceder a la lista de canales del servidor desde el receptor cliente en Media player -> Disco duro -> tuner.\n\n2) Para conectar via UPnP necesitas un servidor UPnP que pueda gestionar archivos .m3u como MediaTomb." % (self.ip)
			self['lab1'].setText(_(mytext))
		else:
			mytext = "Server avaliable on ip %s\nTo access this box's tuners you can connect via Lan or UPnP.\n\n1) To connect via lan you have to mount the /media/hdd folder of this box in the client /media/hdd folder. Then you can access the tuners server channel list from the client Media player -> Harddisk -> tuner.\n\n2) To connect via UPnP you need an UPnP server that can manage .m3u files like Mediatomb." % (self.ip)
			self['lab1'].setText(_(mytext))
		self.session.open(MessageBox, _('Build Complete!'), MessageBox.TYPE_INFO, timeout=5)
		self.updateServ()
コード例 #25
0
 def checkInterface(self, iface):
     self.stopScan()
     if self.Adapterlist is None:
         self.Adapterlist = iNetwork.getAdapterList()
     if self.NextStep is not "end":
         if len(self.Adapterlist) == 0:
             # Reset Network to defaults if network broken
             iNetwork.resetNetworkConfig("lan", self.resetNetworkConfigCB)
             self.resetRef = self.session.openWithCallback(
                 self.resetNetworkConfigFinished,
                 MessageBox,
                 _("Please wait while we prepare your network interfaces..."),
                 type=MessageBox.TYPE_INFO,
                 enable_input=False,
             )
         if iface in iNetwork.getInstalledAdapters():
             if iface in iNetwork.configuredNetworkAdapters and len(iNetwork.configuredNetworkAdapters) == 1:
                 if iNetwork.getAdapterAttribute(iface, "up") is True:
                     self.isInterfaceUp = True
                 else:
                     self.isInterfaceUp = False
                 self.currStep = self.getStepWithID(self.NextStep)
                 self.afterAsyncCode()
             else:
                 self.isInterfaceUp = iNetwork.checkforInterface(iface)
                 self.currStep = self.getStepWithID(self.NextStep)
                 self.afterAsyncCode()
     else:
         self.resetNetworkConfigFinished(False)
コード例 #26
0
ファイル: NetworkWizard.py プロジェクト: st7TEAM/dreambox
	def checkWlanStateCB(self,data,status):
		if data is not None:
			if data is True:
				if status is not None:
					text1 = _("Your Dreambox is now ready to use.\n\nYour internet connection is working now.\n\n")
					text2 = _("IP Address") + ":\t\t" + str('.'.join(["%d" % d for d in iNetwork.getAdapterAttribute(self.selectedInterface, 'ip')])) + "\n"
					text3 = _("Accesspoint") + ":\t\t" + str(status[self.selectedInterface]["accesspoint"]) + "\n"
					text4 = _("SSID") + ":\t\t" + str(status[self.selectedInterface]["essid"]) + "\n"
					text5 = _("Link Quality") + ":\t" + str(status[self.selectedInterface]["quality"])+ "\n"
					text6 = _("Signal Strength") + ":\t" + str(status[self.selectedInterface]["signal"]) + "\n"
					text7 = _("Bitrate") + ":\t\t" + str(status[self.selectedInterface]["bitrate"]) + "\n"

					encryption = _("Enabled")
					if str(status[self.selectedInterface]["encryption"]) == "off":
						encryption = _("Unsupported")
						if str(status[self.selectedInterface]["accesspoint"]) == "Not-Associated":
							encryption = _("Disabled")
						
					text8 = _("Encryption") + ":\t" + encryption + "\n\n"
					text9 = _("Please press OK to continue.")
					infotext = text1 + text2 + text3 + text4 + text5 + text7 + text8 + text9
					self.currStep = self.getStepWithID("checkWlanstatusend")
					self.Text = infotext
					if str(status[self.selectedInterface]["accesspoint"]) == "Not-Associated":
						self.InterfaceState = False
					self.afterAsyncCode()
コード例 #27
0
ファイル: NetworkWizard.py プロジェクト: st7TEAM/dreambox
	def getInterfacesReReadFinished(self, data):
		if data is True:
			if iNetwork.getAdapterAttribute(self.selectedInterface, 'up') is True:
				self.isInterfaceUp = True
			else:
				self.isInterfaceUp = False
		iNetwork.checkNetworkState(self.AdapterSetupEndFinished)
コード例 #28
0
	def process_NetworkIPs(self):
		self.inv_cache = 0
		self.vc = valid_cache(self.cache_file, self.cache_ttl)
		if self.cache_ttl > 0 and self.vc != 0:
			print '[Networkbrowser] Loading network cache from ',self.cache_file
			try:
				self.networklist = load_cache(self.cache_file)
			except:
				self.inv_cache = 1
		if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
			print '[Networkbrowser] Getting fresh network list'
			self.networklist = self.getNetworkIPs()
			if fileExists("/usr/bin/nmap"):
				nwlist = []
				sharelist = []
				self.IP = iNetwork.getAdapterAttribute(self.iface, "ip")
				if len(self.IP):
					strIP = str(self.IP[0]) + "." + str(self.IP[1]) + "." + str(self.IP[2]) + ".0/24"
					self.Console.ePopen("nmap -oX - " + strIP + ' -sP', self.Stage1SettingsComplete)
			else:
				write_cache(self.cache_file, self.networklist)
				if len(self.networklist) > 0:
					self.updateHostsList()
				self["shortcuts"].setEnabled(True)
		else:
			if len(self.networklist) > 0:
				self.updateHostsList()
			else:
				self.setStatus('error')
			self["shortcuts"].setEnabled(True)
コード例 #29
0
ファイル: plugin.py プロジェクト: noox-/stbgui-1
    def __init__(self, session, iface):
        Screen.__init__(self, session)
        self.session = session
        self.iface = iface
        self.skin_path = plugin_path
        self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
        self.APList = None
        self.newAPList = None
        self.WlanList = None
        self.cleanList = None
        self.oldlist = {}
        self.listLength = None
        self.rescanTimer = eTimer()
        self.rescanTimer.callback.append(self.rescanTimerFired)

        self["info"] = StaticText()

        self.list = []
        self["list"] = List(self.list)

        self["key_red"] = StaticText(_("Close"))
        self["key_green"] = StaticText(_("Connect"))
        self["key_yellow"] = StaticText()

        self["actions"] = NumberActionMap(
            ["WizardActions", "InputActions", "EPGSelectActions"], {"ok": self.select, "back": self.cancel}, -1
        )

        self["shortcuts"] = ActionMap(["ShortcutActions"], {"red": self.cancel, "green": self.select})
        iWlan.setInterface(self.iface)
        self.w = iWlan.getInterface()
        self.onLayoutFinish.append(self.layoutFinished)
        self.getAccessPoints(refresh=False)
コード例 #30
0
ファイル: base.py プロジェクト: rdamas/e2openplugin-OpenWebif
    def prepareMainTemplate(self):
        # here will be generated the dictionary for the main template
        ret = getCollapsedMenus()
        ret["remotegrabscreenshot"] = getRemoteGrabScreenshot()["remotegrabscreenshot"]
        ret["configsections"] = getConfigsSections()["sections"]
        ret["zapstream"] = getZapStream()["zapstream"]
        ret["showname"] = getShowName()["showname"]
        ret["customname"] = getCustomName()["customname"]
        ret["boxname"] = getBoxName()["boxname"]
        if not ret["boxname"] or not ret["customname"]:
            ret["boxname"] = getInfo()["brand"] + " " + getInfo()["model"]
        ret["box"] = getBoxType()
        ret["remote"] = remote
        from Components.config import config

        if hasattr(eEPGCache, "FULL_DESCRIPTION_SEARCH"):
            ret["epgsearchcaps"] = True
        else:
            ret["epgsearchcaps"] = False
            if config.OpenWebif.webcache.epg_desc_search.value:
                config.OpenWebif.webcache.epg_desc_search.value = False
                config.OpenWebif.webcache.epg_desc_search.save()
        ret["epgsearchtype"] = getEPGSearchType()["epgsearchtype"]
        extras = []
        extras.append({"key": "ajax/settings", "description": _("Settings")})
        if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/LCD4linux/WebSite.pyo")):
            lcd4linux_key = "lcd4linux/config"
            if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/WebInterface/plugin.pyo")):
                from Components.Network import iNetwork

                ifaces = iNetwork.getConfiguredAdapters()
                if len(ifaces):
                    ip_list = iNetwork.getAdapterAttribute(ifaces[0], "ip")  # use only the first configured interface
                    ip = "%d.%d.%d.%d" % (ip_list[0], ip_list[1], ip_list[2], ip_list[3])
                try:
                    lcd4linux_port = "http://" + ip + ":" + str(config.plugins.Webinterface.http.port.value) + "/"
                    lcd4linux_key = lcd4linux_port + "lcd4linux/config"
                except KeyError:
                    lcd4linux_key = None
            if lcd4linux_key:
                extras.append({"key": lcd4linux_key, "description": _("LCD4Linux Setup")})

        try:
            from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer

            extras.append({"key": "ajax/at", "description": _("AutoTimer")})
        except ImportError:
            pass
        if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/OpenWebif/controllers/views/ajax/bqe.tmpl")):
            extras.append({"key": "ajax/bqe", "description": _("BouquetEditor")})

        try:
            from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh

            extras.append({"key": "ajax/epgr", "description": _("EPGRefresh")})
        except ImportError:
            pass
        ret["extras"] = extras

        return ret
コード例 #31
0
 def AdapterSetupEndFinished(self, data):
     if data <= 2:
         config.misc.networkwizard.hasnetwork.value = True
         config.misc.networkwizard.save()
         self.InterfaceState = True
         self.AdapterRef.close(True)
     else:
         if iNetwork.getAdapterAttribute(
                 self.selectedInterface,
                 'up') is True and self.dhcpWaitTimerRunCount <= 2:
             #some wlan drivers need a long time to get an ip, lets wait max three times and retest network, if first pass didn't got a usable result.
             self.dhcpWaitTimer.startLongTimer(4)
         else:
             config.misc.networkwizard.hasnetwork.value = False
             config.misc.networkwizard.save()
             self.InterfaceState = False
             self.AdapterRef.close(True)
コード例 #32
0
 def checkNetworkCB(self, data):
     try:
         if iNetwork.getAdapterAttribute(self.iface, "up") is True:
             if self.LinkState is True:
                 if data <= 2:
                     self["statuspic"].setPixmapNum(0)
                 else:
                     self["statuspic"].setPixmapNum(1)
                 self["statuspic"].show()
             else:
                 self["statuspic"].setPixmapNum(1)
                 self["statuspic"].show()
         else:
             self["statuspic"].setPixmapNum(1)
             self["statuspic"].show()
     except:
         pass
コード例 #33
0
    def GetNetworkInterfaces(self):
        self.adapters = [(iNetwork.getFriendlyAdapterName(x), x)
                         for x in iNetwork.getAdapterList()]

        if not self.adapters:
            self.adapters = [(iNetwork.getFriendlyAdapterName(x), x)
                             for x in iNetwork.getConfiguredAdapters()]

        if len(self.adapters) == 0:
            self.adapters = [(iNetwork.getFriendlyAdapterName(x), x)
                             for x in iNetwork.getInstalledAdapters()]

        self.activeInterface = None

        for x in self.adapters:
            if iNetwork.getAdapterAttribute(x[1], 'up') is True:
                self.activeInterface = x[1]
                return
コード例 #34
0
ファイル: InstallWizard.py プロジェクト: postla/OpenNFR-E2
	def __init__(self, session, args = None):
		Screen.__init__(self, session)

		self.index = args
		self.list = []
		ConfigListScreen.__init__(self, self.list)

		if self.index == self.STATE_UPDATE:
			config.misc.installwizard.hasnetwork.value = False
			config.misc.installwizard.ipkgloaded.value = False
			modes = {0: " "}
			self.enabled = ConfigSelection(choices = modes, default = 0)
			self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
			is_found = False
			for x in self.adapters:
				if x[1] == 'eth0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
				elif x[1] == 'wlan0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
				elif x[1] == 'ra0':
					if iNetwork.getAdapterAttribute(x[1], 'up'):
						self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
						iNetwork.checkNetworkState(self.checkNetworkCB)
						if_found = True
					else:
						iNetwork.restartNetwork(self.checkNetworkLinkCB)
					break
			if is_found is False:
				self.createMenu()
		elif self.index == self.STATE_CHOISE_CHANNELLIST:
			self.enabled = ConfigYesNo(default = True)
			modes = {"default-ventonsupport": "Default Germany", "henksat-19e": "Astra 1", "henksat-23e": "Astra 3", "henksat-19e-23e": "Astra 1 Astra 3", "henksat-19e-23e-28e": "Astra 1 Astra 2 Astra 3", "henksat-13e-19e-23e-28e": "Astra 1 Astra 2 Astra 3 Hotbird"}
			self.channellist_type = ConfigSelection(choices = modes, default = "default-ventonsupport")
			self.createMenu()
		elif self.index == self.STATE_CHOISE_SOFTCAM:
			self.enabled = ConfigYesNo(default = True)
			modes = {"cccam": _("default") + " (CCcam)", "gbox": "GBox", "wicardd": "Wicardd"}
			self.softcam_type = ConfigSelection(choices = modes, default = "cccam")
			self.createMenu()
コード例 #35
0
ファイル: plugin.py プロジェクト: vuplus-git-mirror/dvbapp
	def UpdateConfigList(self):
		self.configlist = []
		if _flagSupportWol:
			macaddr = " "
			self.configlist.append(getConfigListEntry(_("WakeOnLan Enable"), config.plugins.wolconfig.activate))
			if config.plugins.wolconfig.activate.value:
				self.configlist.append(getConfigListEntry(_("Location"), config.plugins.wolconfig.location))
				if SystemInfo.get("WOWLSupport", False):
					if iNetwork.getAdapterAttribute(_ethDevice, 'up'):
						macaddr = "HWaddr of %s is %s" % (_ethDevice, NetTool.GetHardwareAddr(_ethDevice))
					else:
						macaddr = "Wireless lan is not activated."
				else:
					macaddr = "HWaddr of %s is %s" % (_ethDevice, NetTool.GetHardwareAddr(_ethDevice))
			else:	macaddr = "Wake on Lan disabled"
			self["introduction"].setText(macaddr)

		self["config"].list = self.configlist
		self["config"].l.setList(self.configlist)
コード例 #36
0
    def createMenu(self):
        try:
            test = self.index
        except:
            return
        self.list = []
        if self.index == self.STATE_UPDATE:
            if config.misc.installwizard.hasnetwork.value:
                ip = ".".join([
                    str(x)
                    for x in iNetwork.getAdapterAttribute(self.adapter, "ip")
                ])
                self.list.append(
                    getConfigListEntry(
                        _("Your internet connection is working (ip: %s)") % ip,
                        self.enabled))
            else:
                self.list.append(
                    getConfigListEntry(
                        _("Your receiver does not have an internet connection"
                          ), self.enabled))
        elif self.index == self.STATE_CHOISE_CHANNELLIST:
            self.list.append(
                getConfigListEntry(_("Install channel list"), self.enabled))
            if self.enabled.value:
                self.list.append(
                    getConfigListEntry(_("Channel list type"),
                                       self.channellist_type))
        elif self.index == self.INSTALL_PLUGINS:
            self.list.append(
                getConfigListEntry(_("Do you want to install plugins"),
                                   self.enabled))
        elif self.index == self.INSTALL_SKINS:
            self.list.append(
                getConfigListEntry(_("Do you want to change the default skin"),
                                   self.enabled))
#		elif self.index == self.STATE_CHOISE_SOFTCAM:
#			self.list.append(getConfigListEntry(_("Install softcam"), self.enabled))
#			if self.enabled.value:
#				self.list.append(getConfigListEntry(_("Softcam type"), self.softcam_type))
        self["config"].list = self.list
        self["config"].l.setList(self.list)
コード例 #37
0
ファイル: plugin.py プロジェクト: openhdf/enigma2
    def __init__(self, session, iface):
        Screen.__init__(self, session)
        self.session = session
        self.iface = iface
        self.skin_path = plugin_path
        self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
        self.APList = None
        self.newAPList = None
        self.WlanList = None
        self.cleanList = None
        self.oldlist = {}
        self.listLength = None
        self.divpng = LoadPixmap(
            path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))

        self.rescanTimer = eTimer()
        self.rescanTimer.callback.append(self.rescanTimerFired)

        self["info"] = StaticText()

        self.list = []
        self["list"] = List(self.list)

        self["key_red"] = StaticText(_("Close"))
        self["key_green"] = StaticText(_("Connect"))
        self["key_yellow"] = StaticText()

        self["actions"] = NumberActionMap(
            ["WizardActions", "InputActions", "EPGSelectActions"], {
                "ok": self.select,
                "back": self.cancel,
            }, -1)

        self["shortcuts"] = ActionMap(["ShortcutActions"], {
            "red": self.cancel,
            "green": self.select,
        })
        iWlan.setInterface(self.iface)
        self.w = iWlan.getInterface()
        self.onLayoutFinish.append(self.layoutFinished)
        self.getAccessPoints(refresh=False)
コード例 #38
0
ファイル: BhNet.py プロジェクト: popazerty/bh-gui
    def doServStart(self):
        self.activityTimer.stop()
        ret = system("rm -rf /media/hdd/tuner")
        ifaces = iNetwork.getConfiguredAdapters()
        for iface in ifaces:
            ip = iNetwork.getAdapterAttribute(iface, "ip")
            ipm = "%d.%d.%d.%d" % (ip[0], ip[1], ip[2], ip[3])
            if ipm != "0.0.0.0":
                self.ip = ipm

        ret = system("mkdir /media/hdd/tuner")
        chdir("/media/hdd/tuner")
        s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
        serviceHandler = eServiceCenter.getInstance()
        services = serviceHandler.list(
            eServiceReference(
                '%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % (s_type)))
        bouquets = services and services.getContent("SN", True)
        count = 1
        for bouquet in bouquets:
            self.poPulate(bouquet, count)
            count += 1

        chdir("/home/root")
        mytext = _("Server avaliable on ip " + self.ip + " \n\n")
        mytext += _(
            "To access this box's tuners you can connect via lan or UPnP.\n\n")
        mytext += _(
            "1) To connect via lan you have to mount the /media/hdd folder of this box in the client /media/hdd folder. Then you can access the tuners server channel list from the client Media player -> Harddisk -> tuner.\n"
        )
        mytext += _(
            "2) To connect via UPnP you have to start Mediatomb on this box and then start Djmount on the client. Then you can access the tuners server channel list for the client Media Player -> DLNA -> MediaTomb -> playlists.\n\n"
        )
        mytext += _(
            "NOTE about UPnP: Because UPnP requires alot of memory, you should only use it if you need to access your box from a PS3 or other device that cannot be mounted via Lan. Also, After the server has been built we strongly suggest you delete the Bouquets directory that are not really needed BEFORE you start Mediatomb. This will save alot of memory and resources."
        )

        self["lab1"].setText(mytext)
        self.session.open(MessageBox, _("Build Complete."),
                          MessageBox.TYPE_INFO)
        self.updateServ()
コード例 #39
0
 def getNetworkIPs(self):
     nwlist = []
     sharelist = []
     self.IP = iNetwork.getAdapterAttribute(self.iface, "ip")
     if len(self.IP):
         strIP = str(self.IP[0]) + "." + str(self.IP[1]) + "." + str(
             self.IP[2]) + ".0/24"
         nwlist.append(netscan.netzInfo(strIP))
     self.networklist = nwlist[0]
     if len(self.IP) and (self.IP[0] != 0 or self.IP[1] != 0
                          or self.IP[2] != 0):
         strIP = str(self.IP[0]) + "." + str(self.IP[1]) + "." + str(
             self.IP[2]) + ".0/24"
         self.Console.ePopen("nmap -oX - " + strIP + ' -sP',
                             self.Stage1SettingsComplete)
     else:
         write_cache(self.cache_file, self.networklist)
         if len(self.networklist) > 0:
             self.updateHostsList()
         else:
             self.setStatus('error')
コード例 #40
0
	def checkInterface(self,iface):
		self.stopScan()
		if self.Adapterlist is None:
			self.Adapterlist = iNetwork.getAdapterList()
		if self.NextStep is not 'end':
			if len(self.Adapterlist) == 0:
				#Reset Network to defaults if network broken
				iNetwork.resetNetworkConfig('lan', self.resetNetworkConfigCB)
				self.resetRef = self.session.openWithCallback(self.resetNetworkConfigFinished, MessageBox, _("Please wait while we prepare your network interfaces..."), type = MessageBox.TYPE_INFO, enable_input = False)
			if iface in iNetwork.getInstalledAdapters():
				if iface in iNetwork.configuredNetworkAdapters and len(iNetwork.configuredNetworkAdapters) == 1:
					if iNetwork.getAdapterAttribute(iface, 'up') is True:
						self.isInterfaceUp = True
					else:
						self.isInterfaceUp = False
					self.currStep = self.getStepWithID(self.NextStep)
					self.afterAsyncCode()
				else:
					self.isInterfaceUp = iNetwork.checkforInterface(iface)
					self.currStep = self.getStepWithID(self.NextStep)
					self.afterAsyncCode()
		else:
			self.resetNetworkConfigFinished(False)
コード例 #41
0
    def createMenu(self):
        self.list = []
        try:
            test = self.index
        except:
            return

        if self.index == self.STATE_UPDATE:
            if config.misc.installwizard.hasnetwork.value:
                self.ipConfigEntry = ConfigIP(default=iNetwork.getAdapterAttribute(self.interface, 'ip'))
                self.list.append(getConfigListEntry(_('Your internet connection is working (ip: %s)') % self.ipConfigEntry.getText(), self.enabled))
            else:
                self.list.append(getConfigListEntry(_('Your receiver does not have an internet connection'), self.enabled))
        elif self.index == self.STATE_CHOISE_CHANNELLIST:
            self.list.append(getConfigListEntry(_('Install channel list'), self.enabled))
            if self.enabled.value:
                self.list.append(getConfigListEntry(_('Channel list type'), self.channellist_type))
        elif self.index == self.STATE_CHOISE_SOFTCAM:
            self.list.append(getConfigListEntry(_('Install softcam'), self.enabled))
            if self.enabled.value:
                self.list.append(getConfigListEntry(_('Softcam type'), self.softcam_type))
        self['config'].list = self.list
        self['config'].l.setList(self.list)
コード例 #42
0
	def process_NetworkIPs(self):
		self.inv_cache = 0
		self.vc = valid_cache(self.cache_file, self.cache_ttl)
		if self.cache_ttl > 0 and self.vc != 0:
			print '[Networkbrowser] Loading network cache from ',self.cache_file
			try:
				self.networklist = load_cache(self.cache_file)
			except:
				self.inv_cache = 1
		if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
			print '[Networkbrowser] Getting fresh network list'
			self.networklist = self.getNetworkIPs()
			nwlist = []
			sharelist = []
			self.IP = iNetwork.getAdapterAttribute(self.iface, "ip")
			if len(self.IP):
				strIP = str(self.IP[0]) + "." + str(self.IP[1]) + "." + str(self.IP[2]) + ".0/24"
				self.Console.ePopen("nmap -oX - " + strIP + ' -sP', self.Stage1SettingsComplete)
		else:
			if len(self.networklist) > 0:
				self.updateHostsList()
			else:
				self.setStatus('error')
			self["shortcuts"].setEnabled(True)
コード例 #43
0
    def doServStart(self):
        self.activityTimer.stop()

        if os.path.ismount('/media/hdd'):
            folder = '/media/hdd/tuner'
        elif os.path.ismount('/media/usb'):
            folder = '/media/usb/tuner'
        elif os.path.exists('/usr/share/enigma2'):
            folder = '/usr/share/enigma2/tuner'

        if os.path.exists(folder):
            rmtree(folder)
        ifaces = iNetwork.getConfiguredAdapters()
        for iface in ifaces:
            ip = iNetwork.getAdapterAttribute(iface, 'ip')
            ipm = '%d.%d.%d.%d' % (ip[0], ip[1], ip[2], ip[3])
            if ipm != '0.0.0.0':
                self.ip = ipm

        os.mkdir(folder, 0755)
        s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
        serviceHandler = eServiceCenter.getInstance()
        services = serviceHandler.list(
            eServiceReference(
                '%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % s_type))
        bouquets = services and services.getContent('SN', True)
        count = 1
        for bouquet in bouquets:
            self.poPulate(bouquet, count, folder)
            count += 1

        mytext = "Server avaliable on ip %s\nTo access this box's tuners you can connect via Lan or UPnP.\n\n1) To connect via lan you have to mount the /media/hdd or /media/usb folder of this box in the client /media/hdd folder. Then you can access the tuners server channel list from the client Media player -> Harddisk -> tuner.\n2) To connect via UPnP you need an UPnP server that can manage .m3u files like Mediatomb." % self.ip
        self['lab1'].setText(_(mytext))
        self.session.open(MessageBox, _('Build Complete!'),
                          MessageBox.TYPE_INFO)
        self.updateServ()
コード例 #44
0
ファイル: LdTunerServer.py プロジェクト: Evil-Green/enigma2
    def doServStart(self):
        self.activityTimer.stop()
        if os.path.exists('/media/hdd/tuner'):
            rmtree('/media/hdd/tuner')
        ifaces = iNetwork.getConfiguredAdapters()
        for iface in ifaces:
            ip = iNetwork.getAdapterAttribute(iface, 'ip')
            ipm = '%d.%d.%d.%d' % (ip[0], ip[1], ip[2], ip[3])
            if ipm != '0.0.0.0':
                self.ip = ipm

        os.mkdir('/media/hdd/tuner', 0755)
        s_type = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'
        serviceHandler = eServiceCenter.getInstance()
        services = serviceHandler.list(
            eServiceReference(
                '%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % s_type))
        bouquets = services and services.getContent('SN', True)
        count = 1
        for bouquet in bouquets:
            self.poPulate(bouquet, count)
            count += 1

        if config.osd.language.value == 'es_ES':
            mytext = "Servidor disponible en IP %s\nPara acceder a los sintonizadores de este receptor puedes conectarte desde la LAN o UPnP.\n\n1) Para conectar desde la LAN tienes que montar el directorio /media/hdd de este receptor en el directorio del receptor cliente /media/hdd. Una vez realizado todo esto, ya puedes acceder a la lista de canales del servidor desde el receptor cliente en Media player -> Disco duro -> tuner.\n\n2) Para conectar via UPnP necesitas un servidor UPnP que pueda gestionar archivos .m3u como MediaTomb." % (
                self.ip)
            self['lab1'].setText(_(mytext))
        else:
            mytext = "Server avaliable on ip %s\nTo access this box's tuners you can connect via Lan or UPnP.\n\n1) To connect via lan you have to mount the /media/hdd folder of this box in the client /media/hdd folder. Then you can access the tuners server channel list from the client Media player -> Harddisk -> tuner.\n\n2) To connect via UPnP you need an UPnP server that can manage .m3u files like Mediatomb." % (
                self.ip)
            self['lab1'].setText(_(mytext))
        self.session.open(MessageBox,
                          _('Build Complete!'),
                          MessageBox.TYPE_INFO,
                          timeout=5)
        self.updateServ()
コード例 #45
0
ファイル: plugin.py プロジェクト: takitr/enigma2-plugins
    def updateStatus(self):
        print "[TVCharts] Status Update ..."
        self.DBStatusTimer.stop()

        if not config.plugins.tvcharts.enabled.value or Screens.Standby.inStandby:
            return

        # Get Channelname
        sref = self.session.nav.getCurrentlyPlayingServiceReference()
        if sref is not None:
            ref = eServiceReference(sref.toString())
            ref.setName("")
            serviceHandler = eServiceCenter.getInstance()
            info = serviceHandler.info(ref)
            channel_name = info and info.getName(ref).replace(
                '\xc2\x86', '').replace('\xc2\x87', '').decode(
                    "utf-8", "ignore").encode("utf-8") or ""
            self.serviceref = ref.toString()
        else:
            channel_name = ""
            self.serviceref = ""

        # Get Event Info
        service = self.session.nav.getCurrentService()
        info = service and service.info()
        event = info and info.getEvent(0)
        event_name = event and event.getEventName() or ""
        event_description = ""
        event_begin = 0

        if event is not None:
            curEvent = parseEvent(event)
            event_begin = int(
                curEvent[0]) + (config.recording.margin_before.getValue() * 60)
            event_description = event.getExtendedDescription()

        # Get Box Info
        self.BoxID = iNetwork.getAdapterAttribute("eth0", "mac")
        self.DeviceName = HardwareInfo().get_device_name()
        try:
            from enigma import getEnigmaVersionString
            from boxbranding import getImageVersion, getImageBuild
            self.EnigmaVersion = getEnigmaVersionString()
            self.ImageVersion = getImageVersion() + '.' + getImageBuild()
        except:
            self.EnigmaVersion = about.getEnigmaVersionString()
            self.ImageVersion = about.getVersionString()

        # Get TimerList
        self.timerlist = ""
        if config.plugins.tvcharts.submittimers.value and self.LastTimerlistUpdate <= (
                time() - 1800):
            self.LastTimerlistUpdate = time()
            try:
                for timer in self.recordtimer.timer_list:
                    if timer.disabled == 0 and timer.justplay == 0:
                        self.timerlist += "%s|%s|%s|%s|%s|%s|%s\n" % (
                            timer.eit,
                            str(
                                int(timer.begin) +
                                (config.recording.margin_before.getValue() *
                                 60)),
                            str(
                                int(timer.end) -
                                (config.recording.margin_after.getValue() *
                                 60)), str(timer.service_ref), timer.name,
                            timer.service_ref.getServiceName().replace(
                                '\xc2\x86', '').replace('\xc2\x87', '').decode(
                                    "utf-8",
                                    "ignore").encode("utf-8"), timer.repeated)
            except Exception:
                print "[TVCharts] Error loading timers!"

        # Get Pluginlist
        if config.plugins.tvcharts.submitplugins.value and self.pluginlist == "":
            try:
                os_system(
                    "opkg list_installed | grep enigma2-plugin- > /tmp/plugins.txt"
                )
                for plugin in open('/tmp/plugins.txt', 'r'):
                    self.pluginlist += plugin[0:plugin.find(' - ')] + "\n"
                os_system("rm -f /tmp/plugins.txt")
            except Exception:
                print "[TVCharts] Error loading plugins!"

        # Status Update
        getPage(
            url='http://www.dreambox-plugins.de/feeds/TVCharts/status.php',
            agent="Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)",
            timeout=60,
            method='POST',
            headers={
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            postdata=urlencode({
                'boxid': self.BoxID,
                'devicename': self.DeviceName,
                'imageversion': self.ImageVersion,
                'enigmaversion': self.EnigmaVersion,
                'lastchannel': channel_name,
                'lastevent': event_name,
                'eventdescr': event_description,
                'lastbegin': event_begin,
                'lastserviceref': self.serviceref,
                'timerlist': self.timerlist,
                'pluginlist': self.pluginlist
            })).addErrback(self.updateError)

        # Restart Timer
        self.DBStatusTimer.start(900000, True)
コード例 #46
0
ファイル: Wlan.py プロジェクト: linuxbox10/dvapp-sptest
    def getNetworkList(self):
        if self.oldInterfaceState is None:
            self.oldInterfaceState = iNetwork.getAdapterAttribute(
                self.iface, "up")
        if self.oldInterfaceState is False:
            if iNetwork.getAdapterAttribute(self.iface, "up") is False:
                iNetwork.setAdapterAttribute(self.iface, "up", True)
                system("ifconfig " + self.iface + " up")
                driver = iNetwork.detectWlanModule(self.iface)
                if driver in ('brcm-wl', ):
                    system("wl up")

        ifobj = Wireless(self.iface)  # a Wireless NIC Object

        try:
            scanresults = ifobj.scan()
        except:
            scanresults = None
            print "[Wlan.py] No wireless networks could be found"
        aps = {}
        if scanresults is not None:
            (num_channels, frequencies) = ifobj.getChannelInfo()
            index = 1
            for result in scanresults:
                bssid = result.bssid

                if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
                    encryption = False
                elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
                    encryption = True
                else:
                    encryption = None

                signal = str(result.quality.siglevel - 0x100) + " dBm"
                quality = "%s/%s" % (result.quality.quality,
                                     ifobj.getQualityMax().quality)

                extra = []
                for element in result.custom:
                    element = element.encode()
                    extra.append(strip(self.asciify(element)))
                for element in extra:
                    if 'SignalStrength' in element:
                        signal = element[element.index('SignalStrength') +
                                         15:element.index(',L')]
                    if 'LinkQuality' in element:
                        quality = element[element.index('LinkQuality') +
                                          12:len(element)]

                channel = "Unknown"
                try:
                    channel = frequencies.index(
                        ifobj._formatFrequency(
                            result.frequency.getFrequency())) + 1
                except:
                    channel = "Unknown"

                aps[bssid] = {
                    'active': True,
                    'bssid': result.bssid,
                    'channel': channel,
                    'encrypted': encryption,
                    'essid': result.essid and strip(self.asciify(result.essid))
                    or "",
                    'iface': self.iface,
                    'maxrate': ifobj._formatBitrate(result.rate[-1][-1]),
                    'noise': '',  #result.quality.nlevel-0x100,
                    'quality': str(quality),
                    'signal': str(signal),
                    'custom': extra,
                }

                index += 1
        return aps
コード例 #47
0
def getInfo():
    # TODO: get webif versione somewhere!
    info = {}

    brand = "Dream Multimedia"
    model = "unknown"
    chipset = "unknown"

    if fileExists("/proc/stb/info/hwmodel"):
        file = open("/proc/stb/info/hwmodel")
        model = file.read().strip().lower()
        file.close()
        if model == "tmtwinoe":
            model = "TM-TWIN-OE"
            brand = "Technomate"
        elif model == "tm2toe":
            model = "TM-2T-OE"
            brand = "Technomate"
        elif model == "tmsingle":
            model = "TM-SINGLE"
            brand = "Technomate"
        elif model == "tmnanooe":
            model = "TM-NANO-OE"
            brand = "Technomate"
        elif model == "ios100hd":
            model = "IOS-100HD"
            brand = "Iqon"
        elif model == "ios200hd":
            model = "IOS-200HD"
            brand = "Iqon"
        elif model == "ios300hd":
            model = "IOS-300HD"
            brand = "Iqon"
        elif model == "optimussos1":
            model = "Optimuss-OS1"
            brand = "Edision"
        elif model == "optimussos2":
            model = "Optimuss-OS2"
            brand = "Edision"
        elif model == "sogno-8800hd":
            brand = "Sogno"
            model = "Sogno 8800HD"
    elif fileExists("/proc/stb/info/boxtype"):
        file = open("/proc/stb/info/boxtype")
        model = file.read().strip().lower()
        file.close()
        if model == "gigablue":
            brand = "GigaBlue"
            if fileExists("/proc/stb/info/gbmodel"):
                file = open("/proc/stb/info/gbmodel")
                model = file.read().strip().lower()
                file.close()
        elif model.startswith("et"):
            brand = "Clarke-Xtrend"
            if model == "et9500":
                model = "et9x00"
        elif model.startswith("ini"):
            if model.endswith("sv"):
                brand = "MiracleBox"
                if model == "ini-5000sv":
                    model = "Premium Twin"
                elif model == "ini-1000sv":
                    model = "Premium Mini"
                else:
                    model
            elif model.endswith("de"):
                brand = "Golden Interstar"
                if model == "ini-1000de":
                    model = "Xpeed LX"
                elif model == "ini-9000de":
                    model = "Xpeed LX3"
                else:
                    model
            elif model.endswith("ru"):
                brand = "Sezam"
                if model == "ini-1000ru":
                    model = "Sezam 1000-HD"
                elif model == "ini-5000ru":
                    model = "Sezam 5000-HD"
                elif model == "ini-9000ru":
                    model = "Sezam Marvel"
                else:
                    model
            else:
                brand = "Venton"
        elif model == "enfinity":
            brand = "EVO"
            model = "ENfinity"
        elif model == "xp1000":
            brand = "XP-Series"
        elif model == "xp1000s":
            brand = "Octagon"
            model = "SF8 HD"
        elif model == "odinm9":
            brand = "Odin-Series"
        elif model == "odinm7":
            if getImageDistro() == 'axassupport':
                brand = "AXAS"
                model = "Class M"
            elif getBoxType() == 'odinm6':
                brand = "TELESTAR"
                model = "STARSAT LX"
            elif getMachineName() == 'AX-Odin':
                brand = "Opticum"
                model = "AX-Odin"
            else:
                brand = "Odin-Series"
        elif model == "e3hd":
            if getImageDistro() == 'axassupport':
                brand = "AXAS"
                model = "Class E"
            else:
                brand = "E3-Series"
        elif model == "ebox5000":
            brand = "MixOs-Series"
            model = "MixOs F5"
        elif model == "ebox5100":
            brand = "MixOs-Series"
            model = "MixOs F5mini"
        elif model == "ebox7358":
            brand = "MixOs-Series"
            model = "MixOs F7"
        elif model.startswith("ixuss"):
            brand = "Ixuss-Series"
            chipset = "BCM7405"
    elif fileExists("/proc/stb/info/azmodel"):
        brand = "AZBOX"
        file = open("/proc/stb/info/model")
        model = file.read().strip().lower()
        file.close()
        if model == "me":
            chipset = "SIGMA 8655"
        elif model == "minime":
            chipset = "SIGMA 8653"
        else:
            chipset = "SIGMA 8634"
    elif fileExists("/proc/stb/info/vumodel"):
        brand = "Vu Plus"
        file = open("/proc/stb/info/vumodel")
        model = file.read().strip().lower()
        file.close()
    else:
        file = open("/proc/stb/info/model")
        model = file.read().strip().lower()
        if model.startswith('spar'):
            brand = "Spark"
        file.close()

    info['brand'] = brand
    info['model'] = model

    if fileExists("/proc/stb/info/chipset"):
        f = open("/proc/stb/info/chipset", 'r')
        chipset = f.readline().strip()
        f.close()

    info['chipset'] = chipset

    memFree = 0
    file = open("/proc/meminfo", 'r')
    for line in file:
        parts = line.split(':')
        key = parts[0].strip()
        if key == "MemTotal":
            info['mem1'] = parts[1].strip()
        elif key in ("MemFree", "Buffers", "Cached"):
            memFree += int(parts[1].strip().split(' ', 1)[0])
    info['mem2'] = "%s kB" % memFree
    file.close()

    try:
        f = open("/proc/uptime", "rb")
        uptime = int(float(f.readline().split(' ', 2)[0].strip()))
        f.close()
        uptimetext = ''
        if uptime > 86400:
            d = uptime / 86400
            uptime = uptime % 86400
            uptimetext += '%dd ' % d
        uptimetext += "%d:%.2d" % (uptime / 3600, (uptime % 3600) / 60)
    except:
        uptimetext = "?"
    info['uptime'] = uptimetext

    info["webifver"] = getOpenWebifVer()
    info['imagedistro'] = getImageDistro()
    info['imagever'] = getImageVersion() + '.' + getImageBuild()
    info['enigmaver'] = getEnigmaVersionString()
    info['kernelver'] = about.getKernelVersionString()

    try:
        from Tools.StbHardware import getFPVersion
    except ImportError:
        from Tools.DreamboxHardware import getFPVersion

    info['fp_version'] = getFPVersion()

    info['tuners'] = []
    for i in range(0, nimmanager.getSlotCount()):
        info['tuners'].append({
            "name":
            nimmanager.getNim(i).getSlotName(),
            "type":
            nimmanager.getNimName(i) + " (" +
            nimmanager.getNim(i).getFriendlyType() + ")"
        })

    info['ifaces'] = []
    ifaces = iNetwork.getConfiguredAdapters()
    for iface in ifaces:
        info['ifaces'].append({
            "name":
            iNetwork.getAdapterName(iface),
            "mac":
            iNetwork.getAdapterAttribute(iface, "mac"),
            "dhcp":
            iNetwork.getAdapterAttribute(iface, "dhcp"),
            "ip":
            formatIp(iNetwork.getAdapterAttribute(iface, "ip")),
            "mask":
            formatIp(iNetwork.getAdapterAttribute(iface, "netmask")),
            "gw":
            formatIp(iNetwork.getAdapterAttribute(iface, "gateway"))
        })

    info['hdd'] = []
    for hdd in harddiskmanager.hdd:
        if hdd.free() <= 1024:
            free = "%i MB" % (hdd.free())
        else:
            free = float(hdd.free()) / float(1024)
            free = "%.3f GB" % free
        info['hdd'].append({
            "model": hdd.model(),
            "capacity": hdd.capacity(),
            "free": free
        })
    return info
コード例 #48
0
    def prepareMainTemplate(self, request):
        # here will be generated the dictionary for the main template
        ret = getCollapsedMenus()
        ret['configsections'] = getConfigsSections()['sections']
        ret['showname'] = getShowName()['showname']
        ret['customname'] = getCustomName()['customname']
        ret['boxname'] = getBoxName()['boxname']
        if not ret['boxname'] or not ret['customname']:
            ret['boxname'] = getInfo()['brand'] + " " + getInfo()['model']
        ret['box'] = getBoxType()
        ret["remote"] = remote
        from Components.config import config
        if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'):
            ret['epgsearchcaps'] = True
        else:
            ret['epgsearchcaps'] = False
        extras = []
        extras.append({'key': 'ajax/settings', 'description': _("Settings")})
        from Components.Network import iNetwork
        ifaces = iNetwork.getConfiguredAdapters()
        if len(ifaces):
            ip_list = iNetwork.getAdapterAttribute(
                ifaces[0], "ip")  # use only the first configured interface
            ip = "%d.%d.%d.%d" % (ip_list[0], ip_list[1], ip_list[2],
                                  ip_list[3])

        if fileExists(
                resolveFilename(SCOPE_PLUGINS,
                                "Extensions/LCD4linux/WebSite.pyo")):
            lcd4linux_key = "lcd4linux/config"
            if fileExists(
                    resolveFilename(SCOPE_PLUGINS,
                                    "Extensions/WebInterface/plugin.pyo")):
                try:
                    lcd4linux_port = "http://" + ip + ":" + str(
                        config.plugins.Webinterface.http.port.value) + "/"
                    lcd4linux_key = lcd4linux_port + 'lcd4linux/config'
                except KeyError:
                    lcd4linux_key = None
            if lcd4linux_key:
                extras.append({
                    'key': lcd4linux_key,
                    'description': _("LCD4Linux Setup"),
                    'nw': '1'
                })

        self.oscamconf = self.oscamconfPath()
        if self.oscamconf is not None:
            data = open(self.oscamconf, "r").readlines()
            proto = "http"
            port = None
            for i in data:
                if "httpport" in i.lower():
                    port = i.split("=")[1].strip()
                    if port[0] == '+':
                        proto = "https"
                        port = port[1:]
            if port is not None:
                url = "%s://%s:%s" % (proto, request.getRequestHostname(),
                                      port)
                extras.append({
                    'key': url,
                    'description': _("OSCam Webinterface"),
                    'nw': '1'
                })

        try:
            from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer
            extras.append({'key': 'ajax/at', 'description': _('AutoTimer')})
        except ImportError:
            pass

        if fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.tmpl")):
            extras.append({
                'key': 'ajax/bqe',
                'description': _('BouquetEditor')
            })

        try:
            from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh
            extras.append({'key': 'ajax/epgr', 'description': _('EPGRefresh')})
        except ImportError:
            pass

        try:
            # this will currenly only works if NO Webiterface plugin installed
            # TODO: test if webinterface AND openwebif installed
            from Plugins.Extensions.WebInterface.WebChilds.Toplevel import loaded_plugins
            for plugins in loaded_plugins:
                if plugins[0] in ["fancontrol", "iptvplayer"]:
                    try:
                        extras.append({
                            'key': plugins[0],
                            'description': plugins[2],
                            'nw': '2'
                        })
                    except KeyError:
                        pass
        except ImportError:
            pass

        if os.path.exists('/usr/bin/shellinaboxd') and (fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.tmpl"
                )
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.pyo")
        )):
            extras.append({
                'key': 'ajax/terminal',
                'description': _('Terminal')
            })

        ret['extras'] = extras
        theme = 'original'
        if config.OpenWebif.webcache.theme.value:
            theme = config.OpenWebif.webcache.theme.value
        if not os.path.exists(getPublicPath('themes')):
            if not (theme == 'original' or theme == 'clear'):
                theme = 'original'
                config.OpenWebif.webcache.theme.value = theme
                config.OpenWebif.webcache.theme.save()
        ret['theme'] = theme
        ret['webtv'] = os.path.exists(getPublicPath('webtv'))
        return ret
コード例 #49
0
ファイル: info.py プロジェクト: rommalyshev/PITERKADET-DEPO
def getInfo():
    # TODO: get webif versione somewhere!
    info = {}

    brand = "Dream Multimedia"
    model = "unknown"
    chipset = "unknown"

    if fileExists("/proc/stb/info/boxtype"):
        brand = "Clarke-Xtrend"
        f = open("/proc/stb/info/boxtype", 'r')
        model = f.readline().strip()
        if model == "ini-3000" or model == "ini-5000" or model == "ini-7000":
            brand = "INI-Series"
        f.close()
    elif fileExists("/proc/stb/info/vumodel"):
        brand = "Vuplus"
        f = open("/proc/stb/info/vumodel", 'r')
        model = f.readline().strip()
        f.close()
    elif fileExists("/proc/stb/info/azmodel"):
        brand = "AZBOX"
        f = open("/proc/stb/info/model", 'r')
        model = f.readline().strip()
        f.close()
        if model == "me":
            chipset = "SIGMA 8655"
        elif model == "minime":
            chipset = "SIGMA 8653"
        else:
            chipset = "SIGMA 8634"
    else:
        f = open("/proc/stb/info/model", 'r')
        model = f.readline().strip()
        if model == "spark" or model == "spark7162":
            brand = "AMIKO"
        f.close()

    info['brand'] = brand
    info['model'] = model

    if fileExists("/proc/stb/info/chipset"):
        f = open("/proc/stb/info/chipset", 'r')
        chipset = f.readline().strip()
        f.close()

    info['chipset'] = chipset

    memFree = 0
    for line in open("/proc/meminfo", 'r'):
        parts = line.split(':')
        key = parts[0].strip()
        if key == "MemTotal":
            info['mem1'] = parts[1].strip()
        elif key in ("MemFree", "Buffers", "Cached"):
            memFree += int(parts[1].strip().split(' ', 1)[0])
    info['mem2'] = "%s kB" % memFree

    try:
        f = open("/proc/uptime", "rb")
        uptime = int(float(f.readline().split(' ', 2)[0].strip()))
        f.close()
        uptimetext = ''
        if uptime > 86400:
            d = uptime / 86400
            uptime = uptime % 86400
            uptimetext += '%dd ' % d
        uptimetext += "%d:%.2d" % (uptime / 3600, (uptime % 3600) / 60)
    except:
        uptimetext = "?"
    info['uptime'] = uptimetext

    if fileExists("/etc/bhversion"):
        f = open("/etc/bhversion", 'r')
        imagever = f.readline().strip()
        f.close()
    elif fileExists("/etc/vtiversion.info"):
        f = open("/etc/vtiversion.info", 'r')
        imagever = f.readline().strip()
        f.close()
    else:
        imagever = about.getImageVersionString()

    info["webifver"] = getOpenWebifVer()
    info['imagever'] = imagever
    info['enigmaver'] = about.getEnigmaVersionString()
    info['kernelver'] = about.getKernelVersionString()

    try:
        from Tools.StbHardware import getFPVersion
    except ImportError:
        from Tools.DreamboxHardware import getFPVersion

    info['fp_version'] = getFPVersion()

    info['tuners'] = []
    for i in range(0, nimmanager.getSlotCount()):
        info['tuners'].append({
            "name":
            nimmanager.getNim(i).getSlotName(),
            "type":
            nimmanager.getNimName(i) + " (" +
            nimmanager.getNim(i).getFriendlyType() + ")"
        })

    info['ifaces'] = []
    ifaces = iNetwork.getConfiguredAdapters()
    for iface in ifaces:
        info['ifaces'].append({
            "name":
            iNetwork.getAdapterName(iface),
            "mac":
            iNetwork.getAdapterAttribute(iface, "mac"),
            "dhcp":
            iNetwork.getAdapterAttribute(iface, "dhcp"),
            "ip":
            formatIp(iNetwork.getAdapterAttribute(iface, "ip")),
            "mask":
            formatIp(iNetwork.getAdapterAttribute(iface, "netmask")),
            "gw":
            formatIp(iNetwork.getAdapterAttribute(iface, "gateway"))
        })

    info['hdd'] = []
    for hdd in harddiskmanager.hdd:
        if hdd.free() <= 1024:
            free = "%i MB" % (hdd.free())
        else:
            free = float(hdd.free()) / float(1024)
            free = "%.3f GB" % free
        info['hdd'].append({
            "model": hdd.model(),
            "capacity": hdd.capacity(),
            "free": free
        })
    return info
コード例 #50
0
	def populate(self):
		if isVTISkin:
			self["EnigmaVersion"] = StaticText(_("Version") + ": " + about.getEnigmaVersionString())
			self["ImageVersion"] = StaticText(_("Image") + ": " + about.getImageVersionString())

			self["TunerHeader"] = StaticText(_("Detected NIMs:"))

			fp_version = getFPVersion()
			if fp_version is None:
				fp_version = ""
			else:
				fp_version = _("Frontprocessor version: %s") % str(fp_version)

			self["FPVersion"] = StaticText(fp_version)

			nims = nimmanager.nimList()
			self.tuner_list = []
			if len(nims) <= 4 :
				for count in (0, 1, 2, 3, 4, 5, 6, 7):
					if count < len(nims):
						self["Tuner" + str(count)] = StaticText(nims[count])
						self.tuner_list.append((nims[count] + "\n"))
					else:
						self["Tuner" + str(count)] = StaticText("")
			else:
				desc_list = []
				count = 0
				cur_idx = -1
				while count < len(nims):
					data = nims[count].split(":")
					idx = data[0].strip('Tuner').strip()
					desc = data[1].strip()
					if desc_list and desc_list[cur_idx]['desc'] == desc:
						desc_list[cur_idx]['end'] = idx
					else:
						desc_list.append({'desc' : desc, 'start' : idx, 'end' : idx})
						cur_idx += 1
					count += 1

				for count in (0, 1, 2, 3, 4, 5, 6, 7):
					if count < len(desc_list):
						if desc_list[count]['start'] == desc_list[count]['end']:
							text = "Tuner %s: %s" % (desc_list[count]['start'], desc_list[count]['desc'])
						else:
							text = "Tuner %s-%s: %s" % (desc_list[count]['start'], desc_list[count]['end'], desc_list[count]['desc'])
					else:
						text = ""

					self["Tuner" + str(count)] = StaticText(text)
					if text != "":
						self.tuner_list.append(text + "\n")

			self["HDDHeader"] = StaticText(_("Detected HDD:"))
			hddlist = harddiskmanager.HDDList()
			hdd = hddlist and hddlist[0][1] or None
			if hdd is not None and hdd.model() != "":
				self["hddA"] = StaticText(_("%s\n(%s, %d MB free)") % (hdd.model(), hdd.capacity(),hdd.free()))
			else:
				self["hddA"] = StaticText(_("none"))


			self.enigma2_version = _("Version") + ": " + about.getEnigmaVersionString()
			self.image_version = _("Image") + ": " + about.getImageVersionString()
			cpu_info = parseLines("/proc/cpuinfo")
			cpu_name = "N/A"
			for line in cpu_info:
				if line.find('model') != -1:
					cpu_name = line.split(':')
					if len(cpu_name) >= 2:
						cpu_name = cpu_name[1].strip()
					break

			self.cpu = _("CPU") + ": " + cpu_name
			self.chipset = _("Chipset") + ": " + parseFile("/proc/stb/info/chipset")
			self.tuner_header = _("Detected NIMs:")
			self.hdd_header = _("Detected HDD:")
			self.hdd_list = []
			if len(hddlist):
				for hddX in hddlist:
					hdd = hddX[1]
					if hdd.model() != "":
						self.hdd_list.append((hdd.model() + "\n   %.2f GB - %.2f GB" % (hdd.diskSize()/1000.0, hdd.free()/1000.0) + " " + _("free") + "\n\n"))

			ifaces = iNetwork.getConfiguredAdapters()
			iface_list = []
			for iface in ifaces:
				iface_list.append((_("Interface") + " : " + iNetwork.getAdapterName(iface) + " ("+ iNetwork.getFriendlyAdapterName(iface) + ")\n"))
				iface_list.append((_("IP") + " : " + parse_ipv4(iNetwork.getAdapterAttribute(iface, "ip")) + "\n"))
				iface_list.append((_("Netmask") + " : " + parse_ipv4(iNetwork.getAdapterAttribute(iface, "netmask")) + "\n"))
				iface_list.append((_("Gateway") + " : " + parse_ipv4(iNetwork.getAdapterAttribute(iface, "gateway")) + "\n"))
				if iNetwork.getAdapterAttribute(iface, "dhcp"):
					iface_list.append((_("DHCP") + " : " + _("Yes") + "\n"))
				else:
					iface_list.append((_("DHCP") + " : " + _("No") + "\n"))
				iface_list.append((_("MAC") + " : " + iNetwork.getAdapterAttribute(iface, "mac") + "\n"))
				iface_list.append(("\n"))

			my_txt = self.enigma2_version + "\n"
			my_txt += self.image_version + "\n"
			my_txt += "\n"
			my_txt += self.cpu + "\n"
			my_txt += self.chipset + "\n"
			my_txt += "\n"
			my_txt += self.tuner_header + "\n"
			for x in self.tuner_list:
				my_txt += "   " + x
			my_txt += "\n"
			my_txt += _("Network") + ":\n"
			for x in iface_list:
				my_txt += "   " + x
			my_txt += self.hdd_header + "\n"
			for x in self.hdd_list:
				my_txt += "   " + x
			my_txt += "\n"

			self["FullAbout"] = ScrollLabel(my_txt)
		else:
			self["lab1"] = StaticText(_("openESI"))
			self["lab2"] = StaticText(_("By openESI Image Team"))
			self["lab3"] = StaticText(_("Support at") + " www.openesi.eu")
			model = None
			AboutText = getAboutText()[0]
			self["AboutScrollLabel"] = ScrollLabel(AboutText)
コード例 #51
0
ファイル: info.py プロジェクト: diglam/enigma2pc
def getInfo():
    # TODO: get webif versione somewhere!
    info = {}

    info['brand'] = getMachineBrand()
    info['model'] = getMachineName()
    info['boxtype'] = getBoxType()
    info['machinebuild'] = getMachineBuild()

    chipset = "unknown"
    if fileExists("/etc/.box"):
        f = open("/etc/.box", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model.startswith("ufs") or model.startswith("ufc"):
            if model in ("ufs910", "ufs922", "ufc960"):
                chipset = "SH4 @266MHz"
            else:
                chipset = "SH4 @450MHz"
        elif model in ("topf", "tf7700hdpvr"):
            chipset = "SH4 @266MHz"
        elif model.startswith("azbox"):
            f = open("/usr/local/e2/etc/stb/info/model", 'r')
            model = f.readline().strip().lower()
            f.close()
            if model == "me":
                chipset = "SIGMA 8655"
            elif model == "minime":
                chipset = "SIGMA 8653"
            else:
                chipset = "SIGMA 8634"
        elif model.startswith("spark"):
            if model == "spark7162":
                chipset = "SH4 @540MHz"
            else:
                chipset = "SH4 @450MHz"
    elif fileExists("/usr/local/e2/etc/stb/info/azmodel"):
        f = open("/usr/local/e2/etc/stb/info/model", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model == "me":
            chipset = "SIGMA 8655"
        elif model == "minime":
            chipset = "SIGMA 8653"
        else:
            chipset = "SIGMA 8634"
    else:
        f = open("/usr/local/e2/etc/stb/info/model", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model in ("esi88", "sagemcom88", "nbox"):
            if fileExists("/proc/boxtype"):
                f = open("/proc/boxtype", 'r')
                model = f.readline().strip().lower()
                f.close()
        if model == "tf7700hdpvr":
            chipset = "SH4 @266MHz"
        elif model in ("nbox", "bska", "bsla", "bxzb", "bzzb"):
            chipset = "SH4 @266MHz"
        elif model in ("adb2850", "adb2849"):
            chipset = "SH4 @450MHz"
        elif model in ("sagemcom88", "esi88", "uhd88", "dsi87"):
            chipset = "SH4 @450MHz"

    if fileExists("/usr/local/e2/etc/stb/info/chipset"):
        f = open("/usr/local/e2/etc/stb/info/chipset", 'r')
        chipset = f.readline().strip()
        f.close()

    info['chipset'] = chipset

    memFree = 0
    for line in open("/proc/meminfo", 'r'):
        parts = line.split(':')
        key = parts[0].strip()
        if key == "MemTotal":
            info['mem1'] = parts[1].strip()
        elif key in ("MemFree", "Buffers", "Cached"):
            memFree += int(parts[1].strip().split(' ', 1)[0])
    info['mem2'] = "%s kB" % memFree

    try:
        f = open("/proc/uptime", "rb")
        uptime = int(float(f.readline().split(' ', 2)[0].strip()))
        f.close()
        uptimetext = ''
        if uptime > 86400:
            d = uptime / 86400
            uptime = uptime % 86400
            uptimetext += '%dd ' % d
        uptimetext += "%d:%.2d" % (uptime / 3600, (uptime % 3600) / 60)
    except:
        uptimetext = "?"
    info['uptime'] = uptimetext

    info["webifver"] = getOpenWebifVer()
    info['imagedistro'] = getImageDistro()
    info['oever'] = getOEVersion()
    info['imagever'] = getImageVersion() + '.' + getImageBuild()
    info['enigmaver'] = getEnigmaVersionString()
    info['driverdate'] = getDriverDate()
    info['kernelver'] = about.getKernelVersionString()

    try:
        from Tools.StbHardware import getFPVersion
    except ImportError:
        from Tools.DreamboxHardware import getFPVersion

    info['fp_version'] = getFPVersion()

    info['tuners'] = []
    for i in range(0, nimmanager.getSlotCount()):
        info['tuners'].append({
            "name":
            nimmanager.getNim(i).getSlotName(),
            "type":
            nimmanager.getNimName(i) + " (" +
            nimmanager.getNim(i).getFriendlyType() + ")"
        })

    info['ifaces'] = []
    ifaces = iNetwork.getConfiguredAdapters()
    for iface in ifaces:
        info['ifaces'].append({
            "name":
            iNetwork.getAdapterName(iface),
            "mac":
            iNetwork.getAdapterAttribute(iface, "mac"),
            "dhcp":
            iNetwork.getAdapterAttribute(iface, "dhcp"),
            "ip":
            formatIp(iNetwork.getAdapterAttribute(iface, "ip")),
            "mask":
            formatIp(iNetwork.getAdapterAttribute(iface, "netmask")),
            "v4prefix":
            sum([
                bin(int(x)).count('1') for x in formatIp(
                    iNetwork.getAdapterAttribute(iface, "netmask")).split('.')
            ]),
            "gw":
            formatIp(iNetwork.getAdapterAttribute(iface, "gateway")),
            "ipv6":
            getAdapterIPv6(iface)['addr'],
            "firstpublic":
            getAdapterIPv6(iface)['firstpublic']
        })

    info['hdd'] = []
    for hdd in harddiskmanager.hdd:
        dev = hdd.findMount()
        if dev:
            stat = os.statvfs(dev)
            free = int((stat.f_bfree / 1024) * (stat.f_bsize / 1024))
        else:
            free = -1

        if free <= 1024:
            free = "%i MB" % free
        else:
            free = free / 1024.
            free = "%.3f GB" % free

        size = hdd.diskSize() * 1000000 / 1048576.
        if size > 1048576:
            size = "%.2f TB" % (size / 1048576.)
        elif size > 1024:
            size = "%.1f GB" % (size / 1024.)
        else:
            size = "%d MB" % size

        iecsize = hdd.diskSize()
        # Harddisks > 1000 decimal Gigabytes are labelled in TB
        if iecsize > 1000000:
            iecsize = (iecsize + 50000) // float(100000) / 10
            # Omit decimal fraction if it is 0
            if (iecsize % 1 > 0):
                iecsize = "%.1f TB" % iecsize
            else:
                iecsize = "%d TB" % iecsize
        # Round harddisk sizes beyond ~300GB to full tens: 320, 500, 640, 750GB
        elif iecsize > 300000:
            iecsize = "%d GB" % ((iecsize + 5000) // 10000 * 10)
        # ... be more precise for media < ~300GB (Sticks, SSDs, CF, MMC, ...): 1, 2, 4, 8, 16 ... 256GB
        elif iecsize > 1000:
            iecsize = "%d GB" % ((iecsize + 500) // 1000)
        else:
            iecsize = "%d MB" % iecsize

        info['hdd'].append({
            "model": hdd.model(),
            "capacity": size,
            "labelled_capacity": iecsize,
            "free": free
        })
    global STATICBOXINFO
    STATICBOXINFO = info
    return info
コード例 #52
0
def getInfo(session=None, need_fullinfo=False):
    # TODO: get webif versione somewhere!
    info = {}
    global STATICBOXINFO

    if not (STATICBOXINFO is None or need_fullinfo):
        return STATICBOXINFO

    info['brand'] = getMachineBrand()
    info['model'] = getMachineName()
    info['boxtype'] = getBoxType()
    info['machinebuild'] = getMachineBuild()

    chipset = "unknown"
    if fileExists("/etc/.box"):
        f = open("/etc/.box", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model.startswith("ufs") or model.startswith("ufc"):
            if model in ("ufs910", "ufs922", "ufc960"):
                chipset = "SH4 @266MHz"
            else:
                chipset = "SH4 @450MHz"
        elif model in ("topf", "tf7700hdpvr"):
            chipset = "SH4 @266MHz"
        elif model.startswith("azbox"):
            f = open("/proc/stb/info/model", 'r')
            model = f.readline().strip().lower()
            f.close()
            if model == "me":
                chipset = "SIGMA 8655"
            elif model == "minime":
                chipset = "SIGMA 8653"
            else:
                chipset = "SIGMA 8634"
        elif model.startswith("spark"):
            if model == "spark7162":
                chipset = "SH4 @540MHz"
            else:
                chipset = "SH4 @450MHz"
    elif fileExists("/proc/stb/info/azmodel"):
        f = open("/proc/stb/info/model", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model == "me":
            chipset = "SIGMA 8655"
        elif model == "minime":
            chipset = "SIGMA 8653"
        else:
            chipset = "SIGMA 8634"
    elif fileExists("/proc/stb/info/model"):
        f = open("/proc/stb/info/model", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model == "tf7700hdpvr":
            chipset = "SH4 @266MHz"
        elif model == "nbox":
            chipset = "STi7100 @266MHz"
        elif model == "arivalink200":
            chipset = "STi7109 @266MHz"
        elif model in ("adb2850", "adb2849", "dsi87"):
            chipset = "STi7111 @450MHz"
        elif model in ("sagemcom88", "esi88"):
            chipset = "STi7105 @450MHz"
        elif model.startswith("spark"):
            if model == "spark7162":
                chipset = "STi7162 @540MHz"
            else:
                chipset = "STi7111 @450MHz"

    if fileExists("/proc/stb/info/chipset"):
        f = open("/proc/stb/info/chipset", 'r')
        chipset = f.readline().strip()
        f.close()

    info['chipset'] = chipset

    memFree = 0
    for line in open("/proc/meminfo", 'r'):
        parts = line.split(':')
        key = parts[0].strip()
        if key == "MemTotal":
            info['mem1'] = parts[1].strip().replace("kB", _("kB"))
        elif key in ("MemFree", "Buffers", "Cached"):
            memFree += int(parts[1].strip().split(' ', 1)[0])
    info['mem2'] = "%s %s" % (memFree, _("kB"))
    info['mem3'] = _("%s free / %s total") % (info['mem2'], info['mem1'])

    try:
        f = open("/proc/uptime", "rb")
        uptime = int(float(f.readline().split(' ', 2)[0].strip()))
        f.close()
        uptimetext = ''
        if uptime > 86400:
            d = uptime / 86400
            uptime = uptime % 86400
            uptimetext += '%dd ' % d
        uptimetext += "%d:%.2d" % (uptime / 3600, (uptime % 3600) / 60)
    except:
        uptimetext = "?"
    info['uptime'] = uptimetext

    info["webifver"] = getOpenWebifVer()
    info['imagedistro'] = getImageDistro()
    info['friendlyimagedistro'] = getFriendlyImageDistro()
    info['oever'] = getOEVersion()
    info['imagever'] = getImageVersion()
    ib = getImageBuild()
    if ib:
        info['imagever'] = info['imagever'] + "." + ib
    info['enigmaver'] = getEnigmaVersionString()
    info['driverdate'] = getDriverDate()
    info['kernelver'] = about.getKernelVersionString()

    try:
        from Tools.StbHardware import getFPVersion
    except ImportError:
        from Tools.DreamboxHardware import getFPVersion

    try:
        info['fp_version'] = getFPVersion()
    except:
        info['fp_version'] = None

    friendlychipsetdescription = _("Chipset")
    friendlychipsettext = info['chipset'].replace("bcm", "Broadcom ")
    if friendlychipsettext in ("7335", "7356", "7362", "73625", "7424", "7425",
                               "7429"):
        friendlychipsettext = "Broadcom " + friendlychipsettext
    if not (info['fp_version'] is None or info['fp_version'] == 0):
        friendlychipsetdescription = friendlychipsetdescription + " (" + _(
            "Frontprocessor Version") + ")"
        friendlychipsettext = friendlychipsettext + " (" + str(
            info['fp_version']) + ")"

    info['friendlychipsetdescription'] = friendlychipsetdescription
    info['friendlychipsettext'] = friendlychipsettext

    info['tuners'] = []
    for i in range(0, nimmanager.getSlotCount()):
        print "[OpenWebif] -D- tuner '%d' '%s' '%s'" % (
            i, nimmanager.getNimName(i), nimmanager.getNim(i).getSlotName())
        info['tuners'].append({
            "name":
            nimmanager.getNim(i).getSlotName(),
            "type":
            nimmanager.getNimName(i) + " (" +
            nimmanager.getNim(i).getFriendlyType() + ")",
            "rec":
            "",
            "live":
            ""
        })

    info['ifaces'] = []
    ifaces = iNetwork.getConfiguredAdapters()
    for iface in ifaces:
        info['ifaces'].append({
            "name":
            iNetwork.getAdapterName(iface),
            "friendlynic":
            getFriendlyNICChipSet(iface),
            "linkspeed":
            getLinkSpeed(iface),
            "mac":
            iNetwork.getAdapterAttribute(iface, "mac"),
            "dhcp":
            iNetwork.getAdapterAttribute(iface, "dhcp"),
            "ipv4method":
            getIPv4Method(iface),
            "ip":
            formatIp(iNetwork.getAdapterAttribute(iface, "ip")),
            "mask":
            formatIp(iNetwork.getAdapterAttribute(iface, "netmask")),
            "v4prefix":
            sum([
                bin(int(x)).count('1') for x in formatIp(
                    iNetwork.getAdapterAttribute(iface, "netmask")).split('.')
            ]),
            "gw":
            formatIp(iNetwork.getAdapterAttribute(iface, "gateway")),
            "ipv6":
            getAdapterIPv6(iface)['addr'],
            "ipmethod":
            getIPMethod(iface),
            "firstpublic":
            getAdapterIPv6(iface)['firstpublic']
        })

    info['hdd'] = []
    for hdd in harddiskmanager.hdd:
        dev = hdd.findMount()
        if dev:
            stat = os.statvfs(dev)
            free = int((stat.f_bfree / 1024) * (stat.f_bsize / 1024))
        else:
            free = -1

        if free <= 1024:
            free = "%i %s" % (free, _("MB"))
        else:
            free = free / 1024.
            free = "%.1f %s" % (free, _("GB"))

        size = hdd.diskSize() * 1000000 / 1048576.
        if size > 1048576:
            size = "%.1f %s" % ((size / 1048576.), _("TB"))
        elif size > 1024:
            size = "%.1f %s" % ((size / 1024.), _("GB"))
        else:
            size = "%d %s" % (size, _("MB"))

        iecsize = hdd.diskSize()
        # Harddisks > 1000 decimal Gigabytes are labelled in TB
        if iecsize > 1000000:
            iecsize = (iecsize + 50000) // float(100000) / 10
            # Omit decimal fraction if it is 0
            if (iecsize % 1 > 0):
                iecsize = "%.1f %s" % (iecsize, _("TB"))
            else:
                iecsize = "%d %s" % (iecsize, _("TB"))
        # Round harddisk sizes beyond ~300GB to full tens: 320, 500, 640, 750GB
        elif iecsize > 300000:
            iecsize = "%d %s" % (((iecsize + 5000) // 10000 * 10), _("GB"))
        # ... be more precise for media < ~300GB (Sticks, SSDs, CF, MMC, ...): 1, 2, 4, 8, 16 ... 256GB
        elif iecsize > 1000:
            iecsize = "%d %s" % (((iecsize + 500) // 1000), _("GB"))
        else:
            iecsize = "%d %s" % (iecsize, _("MB"))

        info['hdd'].append({
            "model":
            hdd.model(),
            "capacity":
            size,
            "labelled_capacity":
            iecsize,
            "free":
            free,
            "mount":
            dev,
            "friendlycapacity":
            _("%s free / %s total") % (free, size + ' ("' + iecsize + '")')
        })

    info['shares'] = []
    autofiles = ('/etc/auto.network', '/etc/auto.network_vti')
    for autofs in autofiles:
        if fileExists(autofs):
            method = "autofs"
            for line in file(autofs).readlines():
                if not line.startswith('#'):
                    # Replace escaped spaces that can appear inside credentials with underscores
                    # Not elegant but we wouldn't want to expose credentials on the OWIF anyways
                    tmpline = line.replace("\ ", "_")
                    tmp = tmpline.split()
                    if not len(tmp) == 3:
                        continue
                    name = tmp[0].strip()
                    type = "unknown"
                    if "cifs" in tmp[1]:
                        # Linux still defaults to SMBv1
                        type = "SMBv1.0"
                        settings = tmp[1].split(",")
                        for setting in settings:
                            if setting.startswith("vers="):
                                type = setting.replace("vers=", "SMBv")
                    elif "nfs" in tmp[1]:
                        type = "NFS"

                    # Default is r/w
                    mode = _("r/w")
                    settings = tmp[1].split(",")
                    for setting in settings:
                        if setting == "ro":
                            mode = _("r/o")

                    uri = tmp[2]
                    parts = []
                    parts = tmp[2].split(':')
                    if parts[0] is "":
                        server = uri.split('/')[2]
                        uri = uri.strip()[1:]
                    else:
                        server = parts[0]

                    ipaddress = None
                    if server:
                        # Will fail on literal IPs
                        try:
                            # Try IPv6 first, as will Linux
                            if has_ipv6:
                                tmpaddress = None
                                tmpaddress = getaddrinfo(server, 0, AF_INET6)
                                if tmpaddress:
                                    ipaddress = "[" + list(
                                        tmpaddress)[0][4][0] + "]"
                            # Use IPv4 if IPv6 fails or is not present
                            if ipaddress is None:
                                tmpaddress = None
                                tmpaddress = getaddrinfo(server, 0, AF_INET)
                                if tmpaddress:
                                    ipaddress = list(tmpaddress)[0][4][0]
                        except:
                            pass

                    friendlyaddress = server
                    if ipaddress is not None and not ipaddress == server:
                        friendlyaddress = server + " (" + ipaddress + ")"
                    info['shares'].append({
                        "name": name,
                        "method": method,
                        "type": type,
                        "mode": mode,
                        "path": uri,
                        "host": server,
                        "ipaddress": ipaddress,
                        "friendlyaddress": friendlyaddress
                    })
    # TODO: fstab

    info['transcoding'] = False
    if (info['model'] in ("Uno4K", "Ultimo4K", "Solo4K", "Solo²", "Duo²",
                          "Solo SE", "Quad", "Quad Plus")
            or info['machinebuild']
            in ('inihdp', 'hd2400', 'et10000', 'et13000', 'sf5008', 'xpeedlx3',
                'ew7356', 'dags7356', 'dags7252', 'formuler1tc', 'gb7356',
                'gb7252', 'tiviaraplus', '8100s')):
        if os.path.exists(
                eEnv.resolve(
                    '${libdir}/enigma2/python/Plugins/SystemPlugins/TransCodingSetup/plugin.pyo'
                )
        ) or os.path.exists(
                eEnv.resolve(
                    '${libdir}/enigma2/python/Plugins/SystemPlugins/TranscodingSetup/plugin.pyo'
                )
        ) or os.path.exists(
                eEnv.resolve(
                    '${libdir}/enigma2/python/Plugins/SystemPlugins/MultiTransCodingSetup/plugin.pyo'
                )):
            info['transcoding'] = True

    info['kinopoisk'] = False
    lang = ['ru', 'uk', 'lv', 'lt', 'et']
    for l in lang:
        if l in language.getLanguage():
            info['kinopoisk'] = True

    info['EX'] = ''

    if session:
        try:
            recs = NavigationInstance.instance.getRecordings()
            if recs:
                # only one stream and only TV
                from Plugins.Extensions.OpenWebif.controllers.stream import streamList
                s_name = ''
                s_cip = ''

                print "[OpenWebif] -D- streamList count '%d'" % len(streamList)
                if len(streamList) == 1:
                    from Screens.ChannelSelection import service_types_tv
                    from enigma import eEPGCache
                    epgcache = eEPGCache.getInstance()
                    serviceHandler = eServiceCenter.getInstance()
                    services = serviceHandler.list(
                        eServiceReference('%s ORDER BY name' %
                                          (service_types_tv)))
                    channels = services and services.getContent("SN", True)
                    s = streamList[0]
                    srefs = s.ref.toString()
                    for channel in channels:
                        if srefs == channel[0]:
                            s_name = channel[1] + ' (' + s.clientIP + ')'
                            break
                print "[OpenWebif] -D- s_name '%s'" % s_name

                for stream in streamList:
                    srefs = stream.ref.toString()
                    print "[OpenWebif] -D- srefs '%s'" % srefs

                sname = ''
                timers = []
                for timer in NavigationInstance.instance.RecordTimer.timer_list:
                    if timer.isRunning() and not timer.justplay:
                        timers.append(
                            timer.service_ref.getServiceName().replace(
                                '\xc2\x86', '').replace('\xc2\x87', ''))
                        print "[OpenWebif] -D- timer '%s'" % timer.service_ref.getServiceName(
                        )
                # only one recording
                if len(timers) == 1:
                    sname = timers[0]

                if sname == '' and s_name != '':
                    sname = s_name

                print "[OpenWebif] -D- recs count '%d'" % len(recs)

                for rec in recs:
                    feinfo = rec.frontendInfo()
                    frontendData = feinfo and feinfo.getAll(True)
                    if frontendData is not None:
                        cur_info = feinfo.getTransponderData(True)
                        if cur_info:
                            nr = frontendData['tuner_number']
                            info['tuners'][nr]['rec'] = getOrbitalText(
                                cur_info) + ' / ' + sname

            service = session.nav.getCurrentService()
            if service is not None:
                sname = service.info().getName()
                feinfo = service.frontendInfo()
                frontendData = feinfo and feinfo.getAll(True)
                if frontendData is not None:
                    cur_info = feinfo.getTransponderData(True)
                    if cur_info:
                        nr = frontendData['tuner_number']
                        info['tuners'][nr]['live'] = getOrbitalText(
                            cur_info) + ' / ' + sname
        except Exception, error:
            info['EX'] = error
コード例 #53
0
    def prepareMainTemplate(self, request):
        # here will be generated the dictionary for the main template
        ret = getCollapsedMenus()
        ret['configsections'] = getConfigsSections()['sections']
        ret['showname'] = getShowName()['showname']
        ret['customname'] = getCustomName()['customname']
        ret['boxname'] = getBoxName()['boxname']
        if not ret['boxname'] or not ret['customname']:
            ret['boxname'] = getInfo()['brand'] + " " + getInfo()['model']
        ret['box'] = getBoxType()
        ret["remote"] = REMOTE
        if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'):
            ret['epgsearchcaps'] = True
        else:
            ret['epgsearchcaps'] = False
        extras = [{'key': 'ajax/settings', 'description': _("Settings")}]
        ifaces = iNetwork.getConfiguredAdapters()
        if len(ifaces):
            ip_list = iNetwork.getAdapterAttribute(
                ifaces[0], "ip")  # use only the first configured interface
            if ip_list:
                ip = "%d.%d.%d.%d" % (ip_list[0], ip_list[1], ip_list[2],
                                      ip_list[3])

                if fileExists(
                        resolveFilename(SCOPE_PLUGINS,
                                        "Extensions/LCD4linux/WebSite.pyo")):
                    lcd4linux_key = "lcd4linux/config"
                    if lcd4linux_key:
                        extras.append({
                            'key': lcd4linux_key,
                            'description': _("LCD4Linux Setup"),
                            'nw': '1'
                        })

        oscamwebif, port, oscamconf, variant = self.oscamconfPath()

        # Assume http until we know better ...
        proto = "http"

        # config file exists
        if oscamwebif and oscamconf is not None:
            # oscam defaults to NOT to start the web interface unless a section for it exists, so reset port to None until we find one
            port = None
            data = open(oscamconf, "r").readlines()
            for i in data:
                if "httpport" in i.lower():
                    port = i.split("=")[1].strip()
                    if port[0] == '+':
                        proto = "https"
                        port = port[1:]

        if oscamwebif and port is not None:
            url = "%s://%s:%s" % (proto, request.getRequestHostname(), port)
            if variant == "oscam":
                extras.append({
                    'key': url,
                    'description': _("OSCam Webinterface"),
                    'nw': '1'
                })
            elif variant == "ncam":
                extras.append({
                    'key': url,
                    'description': _("NCam Webinterface"),
                    'nw': '1'
                })

        try:
            from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer  # noqa: F401
            extras.append({'key': 'ajax/at', 'description': _('AutoTimer')})
        except ImportError as e:
            pass

        if fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.tmpl")
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.pyo")):
            extras.append({
                'key': 'ajax/bqe',
                'description': _('BouquetEditor')
            })

        try:
            from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh  # noqa: F401
            extras.append({'key': 'ajax/epgr', 'description': _('EPGRefresh')})
        except ImportError as e:
            pass

        try:
            # this will currenly only works if NO Webiterface plugin installed
            # TODO: test if webinterface AND openwebif installed

            # 'nw'='1' -> target _blank
            # 'nw'='2' -> target popup
            # 'nw'=None -> target _self

            # syntax
            # addExternalChild( (Link, Resource, Name, Version, HasGUI, WebTarget) )
            # example addExternalChild( ("webadmin", root, "WebAdmin", 1, True, "_self") )

            from Plugins.Extensions.OpenWebif.WebChilds.Toplevel import loaded_plugins
            for plugins in loaded_plugins:
                if plugins[0] in [
                        "fancontrol", "iptvplayer", "serienrecorderui"
                ]:
                    try:
                        extras.append({
                            'key': plugins[0],
                            'description': plugins[2],
                            'nw': '2'
                        })
                    except KeyError:
                        pass

                elif len(plugins) > 4:
                    if plugins[4] == True:
                        try:
                            if len(plugins) > 5 and plugins[5] == "_self":
                                extras.append({
                                    'key': plugins[0],
                                    'description': plugins[2]
                                })
                            else:
                                extras.append({
                                    'key': plugins[0],
                                    'description': plugins[2],
                                    'nw': '1'
                                })
                        except KeyError:
                            pass
        except ImportError as e:
            pass

        if os.path.exists('/usr/bin/shellinaboxd') and (fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.tmpl"
                )
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.pyo")
        )):
            extras.append({
                'key': 'ajax/terminal',
                'description': _('Terminal')
            })

        ret['extras'] = extras
        theme = 'original'
        if config.OpenWebif.webcache.theme.value:
            theme = config.OpenWebif.webcache.theme.value
        if not os.path.exists(getPublicPath('themes')):
            if not (theme == 'original' or theme == 'clear'):
                theme = 'original'
                config.OpenWebif.webcache.theme.value = theme
                config.OpenWebif.webcache.theme.save()
        ret['theme'] = theme
        moviedb = config.OpenWebif.webcache.moviedb.value if config.OpenWebif.webcache.moviedb.value else EXT_EVENT_INFO_SOURCE
        config.OpenWebif.webcache.moviedb.value = moviedb
        config.OpenWebif.webcache.moviedb.save()
        ret['moviedb'] = moviedb
        imagedistro = getInfo()['imagedistro']
        ret['vti'] = imagedistro in ("vti") and 1 or 0
        ret['webtv'] = os.path.exists(getPublicPath('webtv'))
        ret['stbLang'] = STB_LANG
        return ret
コード例 #54
0
    def getBoolean(self):
        ret = False
        service = self.source.service
        info = service and service.info()
        if not info:
            return False
        if self.type == self.INETCONECTION:
            if not hayinet():
                ret = False
            else:
                try:
                    f = open('/tmp/testinet.txt', 'r')
                    texto = f.read().replace('\n', '')
                    f.close()
                    if '1 packets transmitted, 1 packets received' in texto:
                        ret = True
                except:
                    pass

                try:
                    system(
                        'ping -q -c 1 -s 6 -w 2 www.google.com >/tmp/testinet.txt &'
                    )
                except:
                    pass

        elif self.type == self.NETCONECTION:
            try:
                adapters = [(iNetwork.getFriendlyAdapterName(x), x)
                            for x in iNetwork.getAdapterList()]
            except:
                adapters = False

            if not adapters:
                ret = False
            else:
                puerta = '0.0.0.0'
                for x in adapters:
                    if iNetwork.getAdapterAttribute(x[1], 'up') is True:
                        puerta = str(
                            iNetwork.getAdapterAttribute(
                                x[1], 'gateway')).replace(',', '.').replace(
                                    '[', '').replace(' ', '').replace(']', '')
                        break

                if puerta == '0.0.0.0':
                    ret = False
                else:
                    try:
                        f = open('/tmp/testnet.txt', 'r')
                        texto = f.read().replace('\n', '')
                        f.close()
                        if '1 packets transmitted, 1 packets received' in texto:
                            ret = True
                    except:
                        pass

                    try:
                        system('ping -q -c 1 -s 6 -w 2 ' + puerta +
                               ' >/tmp/testnet.txt &')
                    except:
                        pass

        return ret
コード例 #55
0
def RemountCallFunction(iface):
	if iNetwork.getAdapterAttribute(iface, "up"):
		return RemountMain
コード例 #56
0
def NetworkBrowserCallFunction(iface):
	interfaceState = iNetwork.getAdapterAttribute(iface, "up")
	if interfaceState is True:
		return NetworkBrowserMain
	else:
		return None
コード例 #57
0
def getInfo(session=None, need_fullinfo=False):
    # TODO: get webif versione somewhere!
    info = {}
    global STATICBOXINFO

    if not (STATICBOXINFO is None or need_fullinfo):
        return STATICBOXINFO

    info['brand'] = getBoxBrand()
    info['model'] = getBoxType()
    info['platform'] = boxbranding.getMachineBuild()

    try:
        info['procmodel'] = getBoxProc()
    except:  # noqa: E722
        info['procmodel'] = boxbranding.getMachineProcModel()

    try:
        info['procmodeltype'] = getBoxProcType()
    except:  # noqa: E722
        info['procmodeltype'] = None

    try:
        info['lcd'] = getLcd()
    except:  # noqa: E722
        info['lcd'] = 0

    try:
        info['grabpip'] = getGrabPip()
    except:  # noqa: E722
        info['grabpip'] = 0

    cpu = about.getCPUInfoString()
    info['chipset'] = cpu
    info['cpubrand'] = about.getCPUBrand()
    info['socfamily'] = boxbranding.getSoCFamily()
    info['cpuarch'] = about.getCPUArch()
    if config.OpenWebif.about_benchmark.value is True:
        info['cpubenchmark'] = about.getCPUBenchmark()
    else:
        info['cpubenchmark'] = _("Disabled in configuration")
    info['flashtype'] = about.getFlashType()

    memFree = 0
    for line in open("/proc/meminfo", 'r'):
        parts = line.split(':')
        key = parts[0].strip()
        if key == "MemTotal":
            info['mem1'] = parts[1].strip().replace("kB", _("kB"))
        elif key in ("MemFree", "Buffers", "Cached"):
            memFree += int(parts[1].strip().split(' ', 1)[0])
    info['mem2'] = "%s %s" % (memFree, _("kB"))
    info['mem3'] = _("%s free / %s total") % (info['mem2'], info['mem1'])

    info['uptime'] = about.getBoxUptime()

    info["webifver"] = OPENWEBIFVER
    info['imagedistro'] = boxbranding.getImageDistro()
    info['oever'] = boxbranding.getImageBuild()
    info['visionversion'] = boxbranding.getVisionVersion()
    info['visionrevision'] = boxbranding.getVisionRevision()
    info['visionmodule'] = about.getVisionModule()

    if fileExists("/etc/openvision/multiboot"):
        multibootflag = open("/etc/openvision/multiboot", "r").read().strip()
        if multibootflag == "1":
            info['multiboot'] = _("Yes")
        else:
            info['multiboot'] = _("No")
    else:
        info['multiboot'] = _("Yes")

    info['enigmaver'] = getEnigmaVersionString()
    info['driverdate'] = about.getDriverInstalledDate()
    info['kernelver'] = boxbranding.getKernelVersion()
    info['dvbapitype'] = about.getDVBAPI()
    info['gstreamerversion'] = about.getGStreamerVersionString(cpu)
    info['ffmpegversion'] = about.getFFmpegVersionString()
    info['pythonversion'] = about.getPythonVersionString()

    try:
        info['hwserial'] = getHWSerial()
    except:  # noqa: E722
        info['hwserial'] = None

    if (info['hwserial'] is None or info['hwserial'] == "unknown"):
        info['hwserial'] = about.getCPUSerial()

    try:
        info['boxrctype'] = getBoxRCType()
    except:  # noqa: E722
        info['boxrctype'] = None

    if (info['boxrctype'] is None or info['boxrctype'] == "unknown"):
        if fileExists("/usr/bin/remotecfg"):
            info['boxrctype'] = _("Amlogic remote")
        elif fileExists("/usr/sbin/lircd"):
            info['boxrctype'] = _("LIRC remote")

    info['ovrctype'] = boxbranding.getRCType()
    info['ovrcname'] = boxbranding.getRCName()
    info['ovrcidnum'] = boxbranding.getRCIDNum()

    info['transcoding'] = boxbranding.getHaveTranscoding()
    info['multitranscoding'] = boxbranding.getHaveMultiTranscoding()

    info['displaytype'] = boxbranding.getDisplayType()

    info['updatedatestring'] = about.getUpdateDateString()
    info['enigmadebuglvl'] = eGetEnigmaDebugLvl()

    info['imagearch'] = boxbranding.getImageArch()
    info['imagefolder'] = boxbranding.getImageFolder()
    info['imagefilesystem'] = boxbranding.getImageFileSystem()
    info['feedsurl'] = boxbranding.getFeedsUrl()
    info['developername'] = boxbranding.getDeveloperName()
    info['builddatestring'] = about.getBuildDateString()
    info['imagefpu'] = boxbranding.getImageFPU()
    info['havemultilib'] = boxbranding.getHaveMultiLib()

    try:
        info['fp_version'] = getFPVersion()
    except:  # noqa: E722
        info['fp_version'] = None

    info['tuners'] = []
    for i in list(range(0, nimmanager.getSlotCount())):
        print(
            "[OpenWebif] -D- tuner '%d' '%s' '%s'" %
            (i, nimmanager.getNimName(i), nimmanager.getNim(i).getSlotName()))
        info['tuners'].append({
            "name":
            nimmanager.getNim(i).getSlotName(),
            "type":
            nimmanager.getNimName(i) + " (" +
            nimmanager.getNim(i).getFriendlyType() + ")",
            "rec":
            "",
            "live":
            ""
        })

    info['ifaces'] = []
    ifaces = iNetwork.getConfiguredAdapters()
    for iface in ifaces:
        info['ifaces'].append({
            "name":
            iNetwork.getAdapterName(iface),
            "friendlynic":
            getFriendlyNICChipSet(iface),
            "linkspeed":
            getLinkSpeed(iface),
            "mac":
            iNetwork.getAdapterAttribute(iface, "mac"),
            "dhcp":
            iNetwork.getAdapterAttribute(iface, "dhcp"),
            "ipv4method":
            getIPv4Method(iface),
            "ip":
            formatIp(iNetwork.getAdapterAttribute(iface, "ip")),
            "mask":
            formatIp(iNetwork.getAdapterAttribute(iface, "netmask")),
            "v4prefix":
            sum([
                bin(int(x)).count('1') for x in formatIp(
                    iNetwork.getAdapterAttribute(iface, "netmask")).split('.')
            ]),
            "gw":
            formatIp(iNetwork.getAdapterAttribute(iface, "gateway")),
            "ipv6":
            getAdapterIPv6(iface)['addr'],
            "ipmethod":
            getIPMethod(iface),
            "firstpublic":
            getAdapterIPv6(iface)['firstpublic']
        })

    info['hdd'] = []
    for hdd in harddiskmanager.hdd:
        dev = hdd.findMount()
        if dev:
            stat = os.statvfs(dev)
            free = stat.f_bavail * stat.f_frsize / 1048576.
        else:
            free = -1

        if free <= 1024:
            free = "%i %s" % (free, _("MB"))
        else:
            free = free / 1024.
            free = "%.1f %s" % (free, _("GB"))

        size = hdd.diskSize() * 1000000 / 1048576.
        if size > 1048576:
            size = "%.1f %s" % ((size / 1048576.), _("TB"))
        elif size > 1024:
            size = "%.1f %s" % ((size / 1024.), _("GB"))
        else:
            size = "%d %s" % (size, _("MB"))

        iecsize = hdd.diskSize()
        # Harddisks > 1000 decimal Gigabytes are labelled in TB
        if iecsize > 1000000:
            iecsize = (iecsize + 50000) // float(100000) / 10
            # Omit decimal fraction if it is 0
            if (iecsize % 1 > 0):
                iecsize = "%.1f %s" % (iecsize, _("TB"))
            else:
                iecsize = "%d %s" % (iecsize, _("TB"))
        # Round harddisk sizes beyond ~300GB to full tens: 320, 500, 640, 750GB
        elif iecsize > 300000:
            iecsize = "%d %s" % (((iecsize + 5000) // 10000 * 10), _("GB"))
        # ... be more precise for media < ~300GB (Sticks, SSDs, CF, MMC, ...): 1, 2, 4, 8, 16 ... 256GB
        elif iecsize > 1000:
            iecsize = "%d %s" % (((iecsize + 500) // 1000), _("GB"))
        else:
            iecsize = "%d %s" % (iecsize, _("MB"))

        info['hdd'].append({
            "model":
            hdd.model(),
            "capacity":
            size,
            "labelled_capacity":
            iecsize,
            "free":
            free,
            "mount":
            dev,
            "friendlycapacity":
            _("%s free / %s total") % (free, size + ' ("' + iecsize + '")')
        })

    info['shares'] = []
    autofiles = ('/etc/auto.network', '/etc/auto.network_vti')
    for autofs in autofiles:
        if fileExists(autofs):
            method = "autofs"
            for line in open(autofs).readlines():
                if not line.startswith('#'):
                    # Replace escaped spaces that can appear inside credentials with underscores
                    # Not elegant but we wouldn't want to expose credentials on the OWIF anyways
                    tmpline = line.replace("\ ", "_")
                    tmp = tmpline.split()
                    if not len(tmp) == 3:
                        continue
                    name = tmp[0].strip()
                    type = "unknown"
                    if "cifs" in tmp[1]:
                        # Linux still defaults to SMBv1
                        type = "SMBv1.0"
                        settings = tmp[1].split(",")
                        for setting in settings:
                            if setting.startswith("vers="):
                                type = setting.replace("vers=", "SMBv")
                    elif "nfs" in tmp[1]:
                        type = "NFS"

                    # Default is r/w
                    mode = _("r/w")
                    settings = tmp[1].split(",")
                    for setting in settings:
                        if setting == "ro":
                            mode = _("r/o")

                    uri = tmp[2]
                    parts = []
                    parts = tmp[2].split(':')
                    if parts[0] == "":
                        server = uri.split('/')[2]
                        uri = uri.strip()[1:]
                    else:
                        server = parts[0]

                    ipaddress = None
                    if server:
                        # Will fail on literal IPs
                        try:
                            # Try IPv6 first, as will Linux
                            if has_ipv6:
                                tmpaddress = None
                                tmpaddress = getaddrinfo(server, 0, AF_INET6)
                                if tmpaddress:
                                    ipaddress = "[" + list(
                                        tmpaddress)[0][4][0] + "]"
                            # Use IPv4 if IPv6 fails or is not present
                            if ipaddress is None:
                                tmpaddress = None
                                tmpaddress = getaddrinfo(server, 0, AF_INET)
                                if tmpaddress:
                                    ipaddress = list(tmpaddress)[0][4][0]
                        except:  # noqa: E722
                            pass

                    friendlyaddress = server
                    if ipaddress is not None and not ipaddress == server:
                        friendlyaddress = server + " (" + ipaddress + ")"
                    info['shares'].append({
                        "name": name,
                        "method": method,
                        "type": type,
                        "mode": mode,
                        "path": uri,
                        "host": server,
                        "ipaddress": ipaddress,
                        "friendlyaddress": friendlyaddress
                    })
    # TODO: fstab

    info['EX'] = ''

    if session:
        try:
            #  gets all current stream clients for images using eStreamServer
            #  TODO: merge eStreamServer and streamList
            #  TODO: get tuner info for streams
            #  TODO: get recoding/timer info if more than one
            info['streams'] = []
            try:
                from enigma import eStreamServer
                streamServer = eStreamServer.getInstance()
                if streamServer is not None:
                    for x in streamServer.getConnectedClients():
                        servicename = ServiceReference(
                            x[1]).getServiceName() or "(unknown service)"
                        if int(x[2]) == 0:
                            strtype = "S"
                        else:
                            strtype = "T"
                        info['streams'].append({
                            "ref": x[1],
                            "name": servicename,
                            "ip": x[0],
                            "type": strtype
                        })
            except Exception as error:
                print("[OpenWebif] -D- no eStreamServer %s" % error)
            recs = NavigationInstance.instance.getRecordings()
            if recs:
                #  only one stream and only TV
                from Plugins.Extensions.OpenWebif.controllers.stream import streamList
                s_name = ''
                # s_cip = ''

                print("[OpenWebif] -D- streamList count '%d'" %
                      len(streamList))
                if len(streamList) == 1:
                    from Screens.ChannelSelection import service_types_tv
                    # from enigma import eEPGCache
                    # epgcache = eEPGCache.getInstance()
                    serviceHandler = eServiceCenter.getInstance()
                    services = serviceHandler.list(
                        eServiceReference('%s ORDER BY name' %
                                          (service_types_tv)))
                    channels = services and services.getContent("SN", True)
                    s = streamList[0]
                    srefs = s.ref.toString()
                    for channel in channels:
                        if srefs == channel[0]:
                            s_name = channel[1] + ' (' + s.clientIP + ')'
                            break
                print("[OpenWebif] -D- s_name '%s'" % s_name)

                # only for debug
                for stream in streamList:
                    srefs = stream.ref.toString()
                    print("[OpenWebif] -D- srefs '%s'" % srefs)

                sname = ''
                timers = []
                for timer in NavigationInstance.instance.RecordTimer.timer_list:
                    if timer.isRunning() and not timer.justplay:
                        timers.append(
                            removeBad(timer.service_ref.getServiceName()))
                        print("[OpenWebif] -D- timer '%s'" %
                              timer.service_ref.getServiceName())


# TODO: more than one recording
                if len(timers) == 1:
                    sname = timers[0]

                if sname == '' and s_name != '':
                    sname = s_name

                print("[OpenWebif] -D- recs count '%d'" % len(recs))

                for rec in recs:
                    feinfo = rec.frontendInfo()
                    frontendData = feinfo and feinfo.getAll(True)
                    if frontendData is not None:
                        cur_info = feinfo.getTransponderData(True)
                        if cur_info:
                            nr = frontendData['tuner_number']
                            info['tuners'][nr]['rec'] = getOrbitalText(
                                cur_info) + ' / ' + sname

            service = session.nav.getCurrentService()
            if service is not None:
                sname = service.info().getName()
                feinfo = service.frontendInfo()
                frontendData = feinfo and feinfo.getAll(True)
                if frontendData is not None:
                    cur_info = feinfo.getTransponderData(True)
                    if cur_info:
                        nr = frontendData['tuner_number']
                        info['tuners'][nr]['live'] = getOrbitalText(
                            cur_info) + ' / ' + sname
        except Exception as error:
            info['EX'] = error

    info['timerpipzap'] = False
    info['timerautoadjust'] = False

    try:
        timer = RecordTimerEntry('', 0, 0, '', '', 0)
        if hasattr(timer, "pipzap"):
            info['timerpipzap'] = True
        if hasattr(timer, "autoadjust"):
            info['timerautoadjust'] = True
    except Exception as error:
        print("[OpenWebif] -D- RecordTimerEntry check %s" % error)

    STATICBOXINFO = info
    return info
コード例 #58
0
 def getEthernetAddr(self):
     return self.formatAddr(iNetwork.getAdapterAttribute("eth0", "ip"))
コード例 #59
0
	def prepareMainTemplate(self):
		from Components.Network import iNetwork
		ifaces = iNetwork.getConfiguredAdapters()
		if len(ifaces):
				ip_list = iNetwork.getAdapterAttribute(ifaces[0], "ip") # use only the first configured interface
				ip = "%d.%d.%d.%d" % (ip_list[0], ip_list[1], ip_list[2], ip_list[3])
			
		ret = getCollapsedMenus()
		ret['remotegrabscreenshot'] = getRemoteGrabScreenshot()['remotegrabscreenshot']
		ret['configsections'] = getConfigsSections()['sections']
		ret['zapstream'] = getZapStream()['zapstream']
		ret['showname'] = getShowName()['showname']
		ret['customname'] = getCustomName()['customname']
		ret['boxname'] = getBoxName()['boxname']
		if not ret['boxname'] or not ret['customname']:
			ret['boxname'] = getInfo()['brand']+" "+getInfo()['model']
		ret['box'] = getBoxType()
		ret["remote"] = remote
		from Components.config import config
		if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'):
			ret['epgsearchcaps'] = True
		else:
			ret['epgsearchcaps'] = False
			if config.ModernWebif.webcache.epg_desc_search.value:
				config.ModernWebif.webcache.epg_desc_search.value = False
				config.ModernWebif.webcache.epg_desc_search.save()
		ret['epgsearchtype'] = getEPGSearchType()['epgsearchtype']
		extras = []
		extras.append({ 'key': 'ajax/settings','description': _("Settings")})
		if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/LCD4linux/WebSite.pyo")):
			lcd4linux_key = "lcd4linux/config"
			if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/WebInterface/plugin.pyo")):
				try:
					lcd4linux_port = "http://" + ip + ":" + str(config.plugins.Webinterface.http.port.value) + "/"
					lcd4linux_key = lcd4linux_port + 'lcd4linux/config'
				except KeyError:
					lcd4linux_key = None
			if lcd4linux_key:
				extras.append({ 'key': lcd4linux_key, 'description': _("LCD4Linux Setup")})
		
		if fileExists("/usr/keys/oscam_atv/oscam.conf"):
				oscam_atv_config = ConfigParser.ConfigParser()
				oscam_atv_config.readfp(open('/usr/keys/oscam_atv/oscam.conf'))
				oscam_port = oscam_atv_config.get("webif","httpport");
				oscam_link = "http://" + ip + ":" + oscam_port + "/"
				extras.append({ 'key': oscam_link, 'description': _("OSCam Webinterface")})
		
		try:
			from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer
			extras.append({ 'key': 'ajax/at','description': _('AutoTimer')})
		except ImportError:
			pass
		if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/ModernWebif/controllers/views/ajax/bqe.tmpl")):
			extras.append({ 'key': 'ajax/bqe','description': _('BouquetEditor')})
		
		try:
			from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh
			extras.append({ 'key': 'ajax/epgr','description': _('EPGRefresh')})
		except ImportError:
			pass
		ret['extras'] = extras

		return ret
コード例 #60
0
def getInfo(session=None, need_fullinfo=False):
    # TODO: get webif versione somewhere!
    info = {}
    global STATICBOXINFO

    if not (STATICBOXINFO is None or need_fullinfo):
        return STATICBOXINFO

    info['brand'] = getMachineBrand()
    info['model'] = getMachineName()
    info['boxtype'] = getBoxType()
    info['machinebuild'] = getMachineBuild()
    try:  # temporary due OE-A
        info['lcd'] = getLcd()
    except:  # nosec # noqa: E722
        info['lcd'] = 0
    try:  # temporary due OE-A
        info['grabpip'] = getGrabPip()
    except:  # nosec # noqa: E722
        info['grabpip'] = 0

    chipset = "unknown"
    if fileExists("/etc/.box"):
        f = open("/etc/.box", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model.startswith("ufs") or model.startswith("ufc"):
            if model in ("ufs910", "ufs922", "ufc960"):
                chipset = "SH4 @266MHz"
            else:
                chipset = "SH4 @450MHz"
        elif model in ("topf", "tf7700hdpvr"):
            chipset = "SH4 @266MHz"
        elif model.startswith("azbox"):
            f = open("/proc/stb/info/model", 'r')
            model = f.readline().strip().lower()
            f.close()
            if model == "me":
                chipset = "SIGMA 8655"
            elif model == "minime":
                chipset = "SIGMA 8653"
            else:
                chipset = "SIGMA 8634"
        elif model.startswith("spark"):
            if model == "spark7162":
                chipset = "SH4 @540MHz"
            else:
                chipset = "SH4 @450MHz"
    elif fileExists("/proc/stb/info/azmodel"):
        f = open("/proc/stb/info/model", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model == "me":
            chipset = "SIGMA 8655"
        elif model == "minime":
            chipset = "SIGMA 8653"
        else:
            chipset = "SIGMA 8634"
    elif fileExists("/proc/stb/info/model"):
        f = open("/proc/stb/info/model", 'r')
        model = f.readline().strip().lower()
        f.close()
        if model == "tf7700hdpvr":
            chipset = "SH4 @266MHz"
        elif model == "nbox":
            chipset = "STi7100 @266MHz"
        elif model == "arivalink200":
            chipset = "STi7109 @266MHz"
        elif model in ("adb2850", "adb2849", "dsi87"):
            chipset = "STi7111 @450MHz"
        elif model in ("sagemcom88", "esi88"):
            chipset = "STi7105 @450MHz"
        elif model.startswith("spark"):
            if model == "spark7162":
                chipset = "STi7162 @540MHz"
            else:
                chipset = "STi7111 @450MHz"
        elif model == "dm800":
            chipset = "bcm7401"
        elif model in ("dm800se", "dm500hd", "dm7020hd", "dm800sev2",
                       "dm500hdv2", "dm7020hdv2"):
            chipset = "bcm7405"
        elif model == "dm8000":
            chipset = "bcm7400"
        elif model in ("dm820", "dm7080"):
            chipset = "bcm7435"
        elif model in ("dm520", "dm525"):
            chipset = "bcm73625"
        elif model in ("dm900", "dm920"):
            chipset = "bcm7252S"

    if fileExists("/proc/stb/info/chipset"):
        f = open("/proc/stb/info/chipset", 'r')
        chipset = f.readline().strip()
        f.close()

    info['chipset'] = chipset

    memFree = 0
    for line in open("/proc/meminfo", 'r'):
        parts = line.split(':')
        key = parts[0].strip()
        if key == "MemTotal":
            info['mem1'] = parts[1].strip().replace("kB", _("kB"))
        elif key in ("MemFree", "Buffers", "Cached"):
            memFree += int(parts[1].strip().split(' ', 1)[0])
    info['mem2'] = "%s %s" % (memFree, _("kB"))
    info['mem3'] = _("%s free / %s total") % (info['mem2'], info['mem1'])

    try:
        f = open("/proc/uptime", "r")
        uptime = int(float(f.readline().split(' ', 2)[0].strip()))
        f.close()
        uptimetext = ''
        if uptime > 86400:
            d = uptime / 86400
            uptime = uptime % 86400
            uptimetext += '%dd ' % d
        uptimetext += "%d:%.2d" % (uptime / 3600, (uptime % 3600) / 60)
    except:  # nosec # noqa: E722
        uptimetext = "?"
    info['uptime'] = uptimetext

    info["webifver"] = OPENWEBIFVER
    info['imagedistro'] = getImageDistro()
    info['friendlyimagedistro'] = getFriendlyImageDistro()
    info['oever'] = getOEVersion()
    info['imagever'] = getImageVersion()
    ib = getImageBuild()
    if ib:
        info['imagever'] = info['imagever'] + "." + ib
    info['enigmaver'] = getEnigmaVersionString()
    info['driverdate'] = getDriverDate()
    info['kernelver'] = about.getKernelVersionString()

    try:
        from Tools.StbHardware import getFPVersion
    except ImportError:
        from Tools.DreamboxHardware import getFPVersion

    try:
        info['fp_version'] = getFPVersion()
    except:  # nosec # noqa: E722
        info['fp_version'] = None

    friendlychipsetdescription = _("Chipset")
    friendlychipsettext = info['chipset'].replace("bcm", "Broadcom ")
    if friendlychipsettext in ("7335", "7356", "7362", "73625", "7424", "7425",
                               "7429"):
        friendlychipsettext = "Broadcom " + friendlychipsettext
    if not (info['fp_version'] is None or info['fp_version'] == 0):
        friendlychipsetdescription = friendlychipsetdescription + " (" + _(
            "Front processor version") + ")"
        friendlychipsettext = friendlychipsettext + " (" + str(
            info['fp_version']) + ")"

    info['friendlychipsetdescription'] = friendlychipsetdescription
    info['friendlychipsettext'] = friendlychipsettext
    info['tuners'] = []
    for i in list(range(0, nimmanager.getSlotCount())):
        print(
            "[OpenWebif] -D- tuner '%d' '%s' '%s'" %
            (i, nimmanager.getNimName(i), nimmanager.getNim(i).getSlotName()))
        info['tuners'].append({
            "name":
            nimmanager.getNim(i).getSlotName(),
            "type":
            nimmanager.getNimName(i) + " (" +
            nimmanager.getNim(i).getFriendlyType() + ")",
            "rec":
            "",
            "live":
            ""
        })

    info['ifaces'] = []
    ifaces = iNetwork.getConfiguredAdapters()
    for iface in ifaces:
        info['ifaces'].append({
            "name":
            iNetwork.getAdapterName(iface),
            "friendlynic":
            getFriendlyNICChipSet(iface),
            "linkspeed":
            getLinkSpeed(iface),
            "mac":
            iNetwork.getAdapterAttribute(iface, "mac"),
            "dhcp":
            iNetwork.getAdapterAttribute(iface, "dhcp"),
            "ipv4method":
            getIPv4Method(iface),
            "ip":
            formatIp(iNetwork.getAdapterAttribute(iface, "ip")),
            "mask":
            formatIp(iNetwork.getAdapterAttribute(iface, "netmask")),
            "v4prefix":
            sum([
                bin(int(x)).count('1') for x in formatIp(
                    iNetwork.getAdapterAttribute(iface, "netmask")).split('.')
            ]),
            "gw":
            formatIp(iNetwork.getAdapterAttribute(iface, "gateway")),
            "ipv6":
            getAdapterIPv6(iface)['addr'],
            "ipmethod":
            getIPMethod(iface),
            "firstpublic":
            getAdapterIPv6(iface)['firstpublic']
        })

    info['hdd'] = []
    for hdd in harddiskmanager.hdd:
        dev = hdd.findMount()
        if dev:
            stat = os.statvfs(dev)
            free = stat.f_bavail * stat.f_frsize / 1048576.
        else:
            free = -1

        if free <= 1024:
            free = "%i %s" % (free, _("MB"))
        else:
            free = free / 1024.
            free = "%.1f %s" % (free, _("GB"))

        size = hdd.diskSize() * 1000000 / 1048576.
        if size > 1048576:
            size = "%.1f %s" % ((size / 1048576.), _("TB"))
        elif size > 1024:
            size = "%.1f %s" % ((size / 1024.), _("GB"))
        else:
            size = "%d %s" % (size, _("MB"))

        iecsize = hdd.diskSize()
        # Harddisks > 1000 decimal Gigabytes are labelled in TB
        if iecsize > 1000000:
            iecsize = (iecsize + 50000) // float(100000) / 10
            # Omit decimal fraction if it is 0
            if (iecsize % 1 > 0):
                iecsize = "%.1f %s" % (iecsize, _("TB"))
            else:
                iecsize = "%d %s" % (iecsize, _("TB"))
        # Round harddisk sizes beyond ~300GB to full tens: 320, 500, 640, 750GB
        elif iecsize > 300000:
            iecsize = "%d %s" % (((iecsize + 5000) // 10000 * 10), _("GB"))
        # ... be more precise for media < ~300GB (Sticks, SSDs, CF, MMC, ...): 1, 2, 4, 8, 16 ... 256GB
        elif iecsize > 1000:
            iecsize = "%d %s" % (((iecsize + 500) // 1000), _("GB"))
        else:
            iecsize = "%d %s" % (iecsize, _("MB"))

        info['hdd'].append({
            "model":
            hdd.model(),
            "capacity":
            size,
            "labelled_capacity":
            iecsize,
            "free":
            free,
            "mount":
            dev,
            "friendlycapacity":
            _("%s free / %s total") % (free, size + ' ("' + iecsize + '")')
        })

    info['shares'] = []
    autofiles = ('/etc/auto.network', '/etc/auto.network_vti')
    for autofs in autofiles:
        if fileExists(autofs):
            method = "autofs"
            for line in open(autofs).readlines():
                if not line.startswith('#'):
                    # Replace escaped spaces that can appear inside credentials with underscores
                    # Not elegant but we wouldn't want to expose credentials on the OWIF anyways
                    tmpline = line.replace("\ ", "_")
                    tmp = tmpline.split()
                    if not len(tmp) == 3:
                        continue
                    name = tmp[0].strip()
                    type = "unknown"
                    if "cifs" in tmp[1]:
                        # Linux still defaults to SMBv1
                        type = "SMBv1.0"
                        settings = tmp[1].split(",")
                        for setting in settings:
                            if setting.startswith("vers="):
                                type = setting.replace("vers=", "SMBv")
                    elif "nfs" in tmp[1]:
                        type = "NFS"

                    # Default is r/w
                    mode = _("r/w")
                    settings = tmp[1].split(",")
                    for setting in settings:
                        if setting == "ro":
                            mode = _("r/o")

                    uri = tmp[2]
                    parts = []
                    parts = tmp[2].split(':')
                    if parts[0] == "":
                        server = uri.split('/')[2]
                        uri = uri.strip()[1:]
                    else:
                        server = parts[0]

                    ipaddress = None
                    if server:
                        # Will fail on literal IPs
                        try:
                            # Try IPv6 first, as will Linux
                            if has_ipv6:
                                tmpaddress = None
                                tmpaddress = getaddrinfo(server, 0, AF_INET6)
                                if tmpaddress:
                                    ipaddress = "[" + list(
                                        tmpaddress)[0][4][0] + "]"
                            # Use IPv4 if IPv6 fails or is not present
                            if ipaddress is None:
                                tmpaddress = None
                                tmpaddress = getaddrinfo(server, 0, AF_INET)
                                if tmpaddress:
                                    ipaddress = list(tmpaddress)[0][4][0]
                        except:  # nosec # noqa: E722
                            pass

                    friendlyaddress = server
                    if ipaddress is not None and not ipaddress == server:
                        friendlyaddress = server + " (" + ipaddress + ")"
                    info['shares'].append({
                        "name": name,
                        "method": method,
                        "type": type,
                        "mode": mode,
                        "path": uri,
                        "host": server,
                        "ipaddress": ipaddress,
                        "friendlyaddress": friendlyaddress
                    })
    # TODO: fstab

    info['transcoding'] = TRANSCODING

    info['EX'] = ''

    if session:
        try:
            #  gets all current stream clients for images using eStreamServer
            #  TODO: get tuner info for streams
            #  TODO: get recoding/timer info if more than one
            info['streams'] = GetStreamInfo()

            recs = NavigationInstance.instance.getRecordings()
            if recs:
                #  only one stream
                s_name = ''
                if len(info['streams']) == 1:
                    sinfo = info['streams'][0]
                    s_name = sinfo["name"] + ' (' + sinfo["ip"] + ')'
                    print("[OpenWebif] -D- s_name '%s'" % s_name)

                sname = ''
                timers = []
                for timer in NavigationInstance.instance.RecordTimer.timer_list:
                    if timer.isRunning() and not timer.justplay:
                        timers.append(
                            removeBad(timer.service_ref.getServiceName()))
                        print("[OpenWebif] -D- timer '%s'" %
                              timer.service_ref.getServiceName())


# TODO: more than one recording
                if len(timers) == 1:
                    sname = timers[0]

                if sname == '' and s_name != '':
                    sname = s_name

                print("[OpenWebif] -D- recs count '%d'" % len(recs))

                for rec in recs:
                    feinfo = rec.frontendInfo()
                    frontendData = feinfo and feinfo.getAll(True)
                    if frontendData is not None:
                        cur_info = feinfo.getTransponderData(True)
                        if cur_info:
                            nr = frontendData['tuner_number']
                            info['tuners'][nr]['rec'] = getOrbitalText(
                                cur_info) + ' / ' + sname

            service = session.nav.getCurrentService()
            if service is not None:
                sname = service.info().getName()
                feinfo = service.frontendInfo()
                frontendData = feinfo and feinfo.getAll(True)
                if frontendData is not None:
                    cur_info = feinfo.getTransponderData(True)
                    if cur_info:
                        nr = frontendData['tuner_number']
                        info['tuners'][nr]['live'] = getOrbitalText(
                            cur_info) + ' / ' + sname
        except Exception as error:
            info['EX'] = error

    info['timerpipzap'] = False
    info['timerautoadjust'] = False

    try:
        timer = RecordTimerEntry(ServiceReference("1:0:1:0:0:0:0:0:0:0"), 0, 0,
                                 '', '', 0)
        if hasattr(timer, "pipzap"):
            info['timerpipzap'] = True
        if hasattr(timer, "autoadjust"):
            info['timerautoadjust'] = True
    except Exception as error:
        print("[OpenWebif] -D- RecordTimerEntry check %s" % error)

    STATICBOXINFO = info
    return info