Ejemplo n.º 1
0
class AutoMountEdit(Screen, ConfigListScreen):
	skin = """
		<screen name="AutoMountEdit" position="center,center" size="560,450" title="MountEdit">
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget name="config" position="5,50" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="skin_default/div-h.png" position="0,420" zPosition="1" size="560,2" />
			<widget source="introduction" render="Label" position="10,430" size="540,21" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1"/>
			<widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="10,430" zPosition="10" size="35,25" transparent="1" alphatest="on" />
			<widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="160,350" zPosition="1" size="1,1" transparent="1" alphatest="on" />
		</screen>"""

	def __init__(self, session, plugin_path, mountinfo = None ):
		self.skin_path = plugin_path
		self.session = session
		Screen.__init__(self, self.session)

		self.onChangedEntry = [ ]
		self.mountinfo = mountinfo
		if self.mountinfo is None:
			#Initialize blank mount enty
			self.mountinfo = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype' : False, 'options' : False, 'hdd_replacement' : False }

		self.applyConfigRef = None
		self.updateConfigRef = None
		self.mounts = iAutoMount.getMountsList()
		self.createConfig()

		self["actions"] = NumberActionMap(["SetupActions", "ColorActions"],
		{
			"ok": self.ok,
			"back": self.close,
			"cancel": self.close,
			"red": self.close,
			"green": self.ok,
		}, -2)

		self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"],
		{
			"showVirtualKeyboard": self.KeyText,
		}, -2)

		self.list = []
		ConfigListScreen.__init__(self, self.list,session = self.session)
		self.createSetup()
		self.onLayoutFinish.append(self.layoutFinished)
		# Initialize Buttons
		self["VKeyIcon"] = Pixmap()
		self["HelpWindow"] = Pixmap()
		self["introduction"] = StaticText(_("Press OK to activate the settings."))
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("Save"))
		self.selectionChanged()

	# for summary:
	def changedEntry(self):
		for x in self.onChangedEntry:
			x()

	def getCurrentEntry(self):
		return self["config"].getCurrent()[0]

	def getCurrentValue(self):
		return str(self["config"].getCurrent()[1].getText())

	def createSummary(self):
		from Screens.Setup import SetupSummary
		return SetupSummary

	def layoutFinished(self):
		self.setup_title = _("Mounts editor")
		Screen.setTitle(self, _(self.setup_title))
		self["VKeyIcon"].hide()
		self["VirtualKB"].setEnabled(False)
		self["HelpWindow"].hide()

	# helper function to convert ips from a sring to a list of ints
	def convertIP(self, ip):
		strIP = ip.split('.')
		ip = []
		for x in strIP:
			ip.append(int(x))
		return ip

	def exit(self):
		self.close()

	def createConfig(self):
		self.mountusingEntry = None
		self.sharenameEntry = None
		self.mounttypeEntry = None
		self.activeEntry = None
		self.ipEntry = None
		self.sharedirEntry = None
		self.optionsEntry = None
		self.usernameEntry = None
		self.passwordEntry = None
		self.hdd_replacementEntry = None

		self.mountusing = []
		self.mountusing.append(("autofs", _("AUTOFS (mount as needed)")))
		self.mountusing.append(("fstab", _("FSTAB (mount at boot)")))
		self.mountusing.append(("enigma2", _("Enigma2 (mount using enigma2)")))
		self.mountusing.append(("old_enigma2", _("Enigma2 old format (mount using linux)")))

		self.sharetypelist = []
		self.sharetypelist.append(("nfs", _("NFS share")))
		self.sharetypelist.append(("cifs", _("CIFS share")))

		if self.mountinfo.has_key('mountusing'):
			mountusing = self.mountinfo['mountusing']
			if mountusing is False:
				mountusing = "fstab"
		else:
			mountusing = "fstab"

		if self.mountinfo.has_key('mounttype'):
			mounttype = self.mountinfo['mounttype']
			if mounttype is False:
				mounttype = "nfs"
		else:
			mounttype = "nfs"

		if self.mountinfo.has_key('active'):
			active = self.mountinfo['active']
			if active == 'True':
				active = True
			if active == 'False':
				active = False
		else:
			active = True
		if self.mountinfo.has_key('ip'):
			if self.mountinfo['ip'] is False:
				ip = [192, 168, 0, 0]
			else:
				ip = self.convertIP(self.mountinfo['ip'])
		else:
			ip = [192, 168, 0, 0]

		if mounttype == "nfs":
			defaultOptions = "rw,nolock,tcp"
		else:
			defaultOptions = "rw,utf8"
		if self.mountinfo['sharename'] and self.mountinfo.has_key('sharename'):
			sharename = re_sub("\W", "", self.mountinfo['sharename'])
		else:
			sharename = "Sharename"
		if self.mountinfo.has_key('sharedir'):
			sharedir = self.mountinfo['sharedir']
		else:
			sharedir = "/export/hdd"
		if self.mountinfo.has_key('options'):
			options = self.mountinfo['options']
		else:
			options = defaultOptions
		if self.mountinfo.has_key('username'):
			username = self.mountinfo['username']
		else:
			username = ""
		if self.mountinfo.has_key('password'):
			password = self.mountinfo['password']
		else:
			password = ""
		if self.mountinfo.has_key('hdd_replacement'):
			hdd_replacement = self.mountinfo['hdd_replacement']
			if hdd_replacement == 'True':
				hdd_replacement = True
			if hdd_replacement == 'False':
				hdd_replacement = False
		else:
			hdd_replacement = False
		if sharename is False:
			sharename = "Sharename"
		if sharedir is False:
			sharedir = "/export/hdd"
		if username is False:
			username = ""
		if password is False:
			password = ""

		self.old_sharename = sharename
		self.old_sharedir = sharedir
		self.mountusingConfigEntry = NoSave(ConfigSelection(self.mountusing, default = mountusing ))
		self.activeConfigEntry = NoSave(ConfigEnableDisable(default = active))
		self.ipConfigEntry = NoSave(ConfigIP(default = ip))
		self.sharenameConfigEntry = NoSave(ConfigText(default = sharename, visible_width = 50, fixed_size = False))
		self.sharedirConfigEntry = NoSave(ConfigText(default = sharedir, visible_width = 50, fixed_size = False))
		self.optionsConfigEntry = NoSave(ConfigText(default = defaultOptions, visible_width = 50, fixed_size = False))
		if options is not False:
			self.optionsConfigEntry.value = options
		self.usernameConfigEntry = NoSave(ConfigText(default = username, visible_width = 50, fixed_size = False))
		self.passwordConfigEntry = NoSave(ConfigPassword(default = password, visible_width = 50, fixed_size = False))
		self.mounttypeConfigEntry = NoSave(ConfigSelection(self.sharetypelist, default = mounttype ))
		self.hdd_replacementConfigEntry = NoSave(ConfigYesNo(default = hdd_replacement))

	def createSetup(self):
		self.list = []
		self.mountusingEntry = getConfigListEntry(_("Mount using"), self.mountusingConfigEntry)
		self.list.append(self.mountusingEntry)
		self.activeEntry = getConfigListEntry(_("Active"), self.activeConfigEntry)
		self.list.append(self.activeEntry)
		self.sharenameEntry = getConfigListEntry(_("Local share name"), self.sharenameConfigEntry)
		self.list.append(self.sharenameEntry)
		self.mounttypeEntry = getConfigListEntry(_("Mount type"), self.mounttypeConfigEntry)
		self.list.append(self.mounttypeEntry)
		self.ipEntry = getConfigListEntry(_("Server IP"), self.ipConfigEntry)
		self.list.append(self.ipEntry)
		self.sharedirEntry = getConfigListEntry(_("Server share"), self.sharedirConfigEntry)
		self.list.append(self.sharedirEntry)
		self.hdd_replacementEntry = getConfigListEntry(_("use as HDD replacement"), self.hdd_replacementConfigEntry)
		self.list.append(self.hdd_replacementEntry)
		self.optionsEntry = getConfigListEntry(_("Mount options"), self.optionsConfigEntry)
		self.list.append(self.optionsEntry)
		if self.mounttypeConfigEntry.value == "cifs":
			self.usernameEntry = getConfigListEntry(_("Username"), self.usernameConfigEntry)
			self.list.append(self.usernameEntry)
			self.passwordEntry = getConfigListEntry(_("Password"), self.passwordConfigEntry)
			self.list.append(self.passwordEntry)

		self["config"].list = self.list
		self["config"].l.setList(self.list)
		self["config"].onSelectionChanged.append(self.selectionChanged)

	def newConfig(self):
		if self["config"].getCurrent() == self.mounttypeEntry:
			if self.mounttypeConfigEntry.value == "nfs":
				defaultOptions = "rw,nolock,tcp"
			else:
				defaultOptions = "rw,utf8"
			if self.mountinfo.has_key('options'):
				options = self.mountinfo['options']
			else:
				options = defaultOptions
			self.optionsConfigEntry = NoSave(ConfigText(default = defaultOptions, visible_width = 50, fixed_size = False))
			if options is not False:
				self.optionsConfigEntry.value = options
			self.createSetup()

	def KeyText(self):
		print "Green Pressed"
		if self["config"].getCurrent() == self.sharenameEntry:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'sharename'), VirtualKeyBoard, title = (_("Enter share name:")), text = self.sharenameConfigEntry.value)
		if self["config"].getCurrent() == self.sharedirEntry:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'sharedir'), VirtualKeyBoard, title = (_("Enter share directory:")), text = self.sharedirConfigEntry.value)
		if self["config"].getCurrent() == self.optionsEntry:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'options'), VirtualKeyBoard, title = (_("Enter options:")), text = self.optionsConfigEntry.value)
		if self["config"].getCurrent() == self.usernameEntry:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'username'), VirtualKeyBoard, title = (_("Enter username:"******"config"].getCurrent() == self.passwordEntry:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'password'), VirtualKeyBoard, title = (_("Enter password:"******"config"].invalidate(self.sharenameConfigEntry)
			if entry == 'sharedir':
				self.sharedirConfigEntry.setValue(callback)
				self["config"].invalidate(self.sharedirConfigEntry)
			if entry == 'options':
				self.optionsConfigEntry.setValue(callback)
				self["config"].invalidate(self.optionsConfigEntry)
			if entry == 'username':
				self.usernameConfigEntry.setValue(callback)
				self["config"].invalidate(self.usernameConfigEntry)
			if entry == 'password':
				self.passwordConfigEntry.setValue(callback)
				self["config"].invalidate(self.passwordConfigEntry)

	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()

	def selectionChanged(self):
		current = self["config"].getCurrent()
		if current == self.mountusingEntry or current == self.activeEntry or current == self.ipEntry or current == self.mounttypeEntry or current == self.hdd_replacementEntry:
			self["VKeyIcon"].hide()
			self["VirtualKB"].setEnabled(False)
		else:
			helpwindowpos = self["HelpWindow"].getPosition()
			if current[1].help_window.instance is not None:
				current[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
				self["VKeyIcon"].show()
				self["VirtualKB"].setEnabled(True)

	def ok(self):
		current = self["config"].getCurrent()
		if current == self.sharenameEntry or current == self.sharedirEntry or current == self.sharedirEntry or current == self.optionsEntry or current == self.usernameEntry or current == self.passwordEntry:
			if current[1].help_window.instance is not None:
				current[1].help_window.instance.hide()

		sharename = re_sub("\W", "", self.sharenameConfigEntry.value)
		if self.sharedirConfigEntry.value.startswith("/"):
			sharedir = self.sharedirConfigEntry.value[1:]
		else:
			sharedir = self.sharedirConfigEntry.value

		sharexists = False
		for data in self.mounts:
			if self.mounts[data]['sharename'] == self.old_sharename:
					sharexists = True
					break

		if self.old_sharename != self.sharenameConfigEntry.value:
			self.session.openWithCallback(self.updateConfig, MessageBox, _("You have changed the share name!\nUpdate existing entry and continue?\n"), default=False )
		elif self.old_sharename == self.sharenameConfigEntry.value and sharexists:
			self.session.openWithCallback(self.updateConfig, MessageBox, _("A mount entry with this name already exists!\nUpdate existing entry and continue?\n"), default=False )
		else:
			self.session.openWithCallback(self.applyConfig, MessageBox, _("Are you sure you want to save this network mount?\n\n") )

	def updateConfig(self, ret = False):
		if (ret == True):
			sharedir = None
			if self.old_sharename != self.sharenameConfigEntry.value:
				xml_sharename = self.old_sharename
			else:
				xml_sharename = self.sharenameConfigEntry.value

			if self.sharedirConfigEntry.value.startswith("/"):
				sharedir = self.sharedirConfigEntry.value[1:]
			else:
				sharedir = self.sharedirConfigEntry.value
			iAutoMount.setMountsAttribute(xml_sharename, "mountusing", self.mountusingConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "sharename", self.sharenameConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "active", self.activeConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "ip", self.ipConfigEntry.getText())
			iAutoMount.setMountsAttribute(xml_sharename, "sharedir", sharedir)
			iAutoMount.setMountsAttribute(xml_sharename, "mounttype", self.mounttypeConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "options", self.optionsConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "username", self.usernameConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "password", self.passwordConfigEntry.value)
			iAutoMount.setMountsAttribute(xml_sharename, "hdd_replacement", self.hdd_replacementConfigEntry.value)

			self.updateConfigRef = None
			self.updateConfigRef = self.session.openWithCallback(self.updateConfigfinishedCB, MessageBox, _("Please wait while updating your network mount..."), type = MessageBox.TYPE_INFO, enable_input = False)
			iAutoMount.writeMountsConfig()
			iAutoMount.getAutoMountPoints(self.updateConfigDataAvail, True)
		else:
			self.close()

	def updateConfigDataAvail(self, data):
		if data is True:
			self.updateConfigRef.close(True)

	def updateConfigfinishedCB(self,data):
		if data is True:
			self.session.openWithCallback(self.Updatefinished, MessageBox, _("Your network mount has been updated."), type = MessageBox.TYPE_INFO, timeout = 10)

	def Updatefinished(self,data):
		if data is not None:
			if data is True:
				self.close()

	def applyConfig(self, ret = False):
		if (ret == True):
			data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, \
					'username': False, 'password': False, 'mounttype' : False, 'options' : False, 'hdd_replacement' : False }
			data['mountusing'] = self.mountusingConfigEntry.value
			data['active'] = self.activeConfigEntry.value
			data['ip'] = self.ipConfigEntry.getText()
			data['sharename'] = re_sub("\W", "", self.sharenameConfigEntry.value)
			# "\W" matches everything that is "not numbers, letters, or underscores",where the alphabet defaults to ASCII.
			if self.sharedirConfigEntry.value.startswith("/"):
				data['sharedir'] = self.sharedirConfigEntry.value[1:]
			else:
				data['sharedir'] = self.sharedirConfigEntry.value
			data['options'] =  self.optionsConfigEntry.value
			data['mounttype'] = self.mounttypeConfigEntry.value
			data['username'] = self.usernameConfigEntry.value
			data['password'] = self.passwordConfigEntry.value
			data['hdd_replacement'] = self.hdd_replacementConfigEntry.value
			self.applyConfigRef = None
			self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait for activation of your network mount..."), type = MessageBox.TYPE_INFO, enable_input = False)
			iAutoMount.automounts[self.sharenameConfigEntry.value] = data
			iAutoMount.writeMountsConfig()
			iAutoMount.getAutoMountPoints(self.applyConfigDataAvail, True)
		else:
			self.close()

	def applyConfigDataAvail(self, data):
		if data is True:
			self.applyConfigRef.close(True)

	def applyConfigfinishedCB(self,data):
		if data is True:
			self.session.openWithCallback(self.applyfinished, MessageBox, _("Your network mount has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)

	def applyfinished(self,data):
		if data is not None:
			if data is True:
				self.close()
Ejemplo n.º 2
0
class AutoMountEdit(Screen, ConfigListScreen):
    skin = """
		<screen name="AutoMountEdit" position="center,center" size="560,450" title="MountEdit">
			<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget name="config" position="5,50" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="div-h.png" position="0,420" zPosition="1" size="560,2" />
			<widget source="introduction" render="Label" position="10,430" size="540,21" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1"/>
			<widget source="VKeyIcon" render="Pixmap" pixmap="buttons/key_text.png" position="10,430" zPosition="10" size="35,25" transparent="1" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="HelpWindow" pixmap="vkey_icon.png" position="160,350" zPosition="1" size="1,1" transparent="1" alphatest="on" />	
		</screen>"""

    def __init__(self, session, plugin_path, mountinfo=None):
        self.skin_path = plugin_path
        self.session = session
        Screen.__init__(self, self.session)

        self.mountinfo = mountinfo
        if self.mountinfo is None:
            #Initialize blank mount enty
            self.mountinfo = {
                'isMounted': False,
                'active': False,
                'ip': False,
                'sharename': False,
                'sharedir': False,
                'username': False,
                'password': False,
                'mounttype': False,
                'options': False,
                'hdd_replacement': False
            }

        self.applyConfigRef = None
        self.updateConfigRef = None
        self.mounts = iAutoMount.getMountsList()
        self.createConfig()

        self["actions"] = NumberActionMap(
            ["SetupActions"], {
                "ok": self.ok,
                "back": self.close,
                "cancel": self.close,
                "red": self.close,
            }, -2)

        self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"], {
            "showVirtualKeyboard": self.KeyText,
        }, -2)

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=self.session)
        self.createSetup()
        self.onLayoutFinish.append(self.layoutFinished)
        # Initialize Buttons
        self["VKeyIcon"] = Boolean(False)
        self["HelpWindow"] = Pixmap()
        self["introduction"] = StaticText(
            _("Press OK to activate the settings."))
        self["key_red"] = StaticText(_("Cancel"))

    def layoutFinished(self):
        self.setTitle(_("Mounts editor"))
        self["VKeyIcon"].boolean = False
        self["VirtualKB"].setEnabled(False)
        self["HelpWindow"].hide()

    # helper function to convert ips from a sring to a list of ints
    def convertIP(self, ip):
        strIP = ip.split('.')
        ip = []
        for x in strIP:
            ip.append(int(x))
        return ip

    def exit(self):
        self.close()

    def createConfig(self):
        self.sharenameEntry = None
        self.mounttypeEntry = None
        self.activeEntry = None
        self.ipEntry = None
        self.sharedirEntry = None
        self.optionsEntry = None
        self.usernameEntry = None
        self.passwordEntry = None
        self.hdd_replacementEntry = None
        self.sharetypelist = [("nfs", _("NFS share")),
                              ("cifs", _("CIFS share"))]

        if self.mountinfo.has_key('mounttype'):
            mounttype = self.mountinfo['mounttype']
            if not mounttype:
                mounttype = "nfs"
        else:
            mounttype = "nfs"

        if self.mountinfo.has_key('active'):
            active = self.mountinfo['active']
            if active == 'True':
                active = True
            if active == 'False':
                active = False
        else:
            active = True
        if self.mountinfo.has_key('ip'):
            if self.mountinfo['ip'] is False:
                ip = [192, 168, 0, 0]
            else:
                ip = self.convertIP(self.mountinfo['ip'])
        else:
            ip = [192, 168, 0, 0]
        if self.mountinfo.has_key('sharename'):
            sharename = self.mountinfo['sharename']
        else:
            sharename = "Sharename"
        if self.mountinfo.has_key('sharedir'):
            sharedir = self.mountinfo['sharedir']
        else:
            sharedir = "/export/hdd"
        if self.mountinfo.has_key('options'):
            options = self.mountinfo['options']
        else:
            options = "rw,nolock,soft"
        if self.mountinfo.has_key('username'):
            username = self.mountinfo['username']
        else:
            username = ""
        if self.mountinfo.has_key('password'):
            password = self.mountinfo['password']
        else:
            password = ""
        if self.mountinfo.has_key('hdd_replacement'):
            hdd_replacement = self.mountinfo['hdd_replacement']
            if hdd_replacement == 'True':
                hdd_replacement = True
            if hdd_replacement == 'False':
                hdd_replacement = False
        else:
            hdd_replacement = False
        if sharename is False:
            sharename = "Sharename"
        if sharedir is False:
            sharedir = "/export/hdd"
        if mounttype == "nfs":
            defaultOptions = "rw,nolock,soft"
        else:
            defaultOptions = "rw"
        if username is False:
            username = ""
        if password is False:
            password = ""

        self.activeConfigEntry = NoSave(ConfigEnableDisable(default=active))
        self.ipConfigEntry = NoSave(ConfigIP(default=ip))
        self.sharenameConfigEntry = NoSave(
            ConfigText(default=sharename, visible_width=50, fixed_size=False))
        self.sharedirConfigEntry = NoSave(
            ConfigText(default=sharedir, visible_width=50, fixed_size=False))
        self.optionsConfigEntry = NoSave(
            ConfigText(default=defaultOptions,
                       visible_width=50,
                       fixed_size=False))
        if options is not False:
            self.optionsConfigEntry.value = options
        self.usernameConfigEntry = NoSave(
            ConfigText(default=username, visible_width=50, fixed_size=False))
        self.passwordConfigEntry = NoSave(
            ConfigPassword(default=password,
                           visible_width=50,
                           fixed_size=False))
        self.mounttypeConfigEntry = NoSave(
            ConfigSelection(self.sharetypelist, default=mounttype))
        self.hdd_replacementConfigEntry = NoSave(
            ConfigYesNo(default=hdd_replacement))

    def createSetup(self):
        self.list = []
        self.activeEntry = getConfigListEntry(_("Active"),
                                              self.activeConfigEntry)
        self.list.append(self.activeEntry)
        self.sharenameEntry = getConfigListEntry(_("Local share name"),
                                                 self.sharenameConfigEntry)
        self.list.append(self.sharenameEntry)
        self.mounttypeEntry = getConfigListEntry(_("Mount type"),
                                                 self.mounttypeConfigEntry)
        self.list.append(self.mounttypeEntry)
        self.ipEntry = getConfigListEntry(_("Server IP"), self.ipConfigEntry)
        self.list.append(self.ipEntry)
        self.sharedirEntry = getConfigListEntry(_("Server share"),
                                                self.sharedirConfigEntry)
        self.list.append(self.sharedirEntry)
        self.hdd_replacementEntry = getConfigListEntry(
            _("use as HDD replacement"), self.hdd_replacementConfigEntry)
        self.list.append(self.hdd_replacementEntry)
        if self.optionsConfigEntry.value == self.optionsConfigEntry.default:
            if self.mounttypeConfigEntry.value == "cifs":
                self.optionsConfigEntry = NoSave(
                    ConfigText(default="rw",
                               visible_width=50,
                               fixed_size=False))
            else:
                self.optionsConfigEntry = NoSave(
                    ConfigText(default="rw,nolock,soft",
                               visible_width=50,
                               fixed_size=False))
        self.optionsEntry = getConfigListEntry(_("Mount options"),
                                               self.optionsConfigEntry)
        self.list.append(self.optionsEntry)
        if self.mounttypeConfigEntry.value == "cifs":
            self.usernameEntry = getConfigListEntry(_("Username"),
                                                    self.usernameConfigEntry)
            self.list.append(self.usernameEntry)
            self.passwordEntry = getConfigListEntry(_("Password"),
                                                    self.passwordConfigEntry)
            self.list.append(self.passwordEntry)

        self["config"].list = self.list
        self["config"].l.setList(self.list)
        self["config"].onSelectionChanged.append(self.selectionChanged)

    def newConfig(self):
        if self["config"].getCurrent() == self.mounttypeEntry:
            self.createSetup()

    def KeyText(self):
        print "Green Pressed"
        if self["config"].getCurrent() == self.sharenameEntry:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'sharename'),
                VirtualKeyBoard,
                title=(_("Enter share name:")),
                text=self.sharenameConfigEntry.value)
        if self["config"].getCurrent() == self.sharedirEntry:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'sharedir'),
                VirtualKeyBoard,
                title=(_("Enter share directory:")),
                text=self.sharedirConfigEntry.value)
        if self["config"].getCurrent() == self.optionsEntry:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'options'),
                VirtualKeyBoard,
                title=(_("Enter options:")),
                text=self.optionsConfigEntry.value)
        if self["config"].getCurrent() == self.usernameEntry:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'username'),
                VirtualKeyBoard,
                title=(_("Enter username:"******"config"].getCurrent() == self.passwordEntry:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'password'),
                VirtualKeyBoard,
                title=(_("Enter password:"******"config"].invalidate(self.sharenameConfigEntry)
            if entry == 'sharedir':
                self.sharedirConfigEntry.setValue(callback)
                self["config"].invalidate(self.sharedirConfigEntry)
            if entry == 'options':
                self.optionsConfigEntry.setValue(callback)
                self["config"].invalidate(self.optionsConfigEntry)
            if entry == 'username':
                self.usernameConfigEntry.setValue(callback)
                self["config"].invalidate(self.usernameConfigEntry)
            if entry == 'password':
                self.passwordConfigEntry.setValue(callback)
                self["config"].invalidate(self.passwordConfigEntry)

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def selectionChanged(self):
        current = self["config"].getCurrent()
        if current == self.activeEntry or current == self.ipEntry or current == self.mounttypeEntry or current == self.hdd_replacementEntry:
            self["VKeyIcon"].boolean = False
            self["VirtualKB"].setEnabled(False)
        else:
            helpwindowpos = self["HelpWindow"].getPosition()
            if current[1].help_window.instance is not None:
                current[1].help_window.instance.move(
                    ePoint(helpwindowpos[0], helpwindowpos[1]))
                self["VKeyIcon"].boolean = True
                self["VirtualKB"].setEnabled(True)

    def ok(self):
        current = self["config"].getCurrent()
        if current == self.sharenameEntry or current == self.sharedirEntry or current == self.sharedirEntry or current == self.optionsEntry or current == self.usernameEntry or current == self.passwordEntry:
            if current[1].help_window.instance is not None:
                current[1].help_window.instance.hide()
        sharename = self.sharenameConfigEntry.value

        if self.mounts.has_key(sharename) is True:
            self.session.openWithCallback(self.updateConfig, MessageBox, (_(
                "A mount entry with this name already exists!\nUpdate existing entry and continue?\n"
            )))
        else:
            self.session.openWithCallback(
                self.applyConfig, MessageBox,
                (_("Are you sure you want to save this network mount?\n\n")))

    def updateConfig(self, ret=False):
        if (ret == True):
            sharedir = None
            if self.sharedirConfigEntry.value.startswith("/"):
                sharedir = self.sharedirConfigEntry.value[1:]
            else:
                sharedir = self.sharedirConfigEntry.value
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "sharename",
                                          self.sharenameConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "active",
                                          self.activeConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "ip", self.ipConfigEntry.getText())
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "sharedir", sharedir)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "mounttype",
                                          self.mounttypeConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "options",
                                          self.optionsConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "username",
                                          self.usernameConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value,
                                          "password",
                                          self.passwordConfigEntry.value)
            iAutoMount.setMountsAttribute(
                self.sharenameConfigEntry.value, "hdd_replacement",
                self.hdd_replacementConfigEntry.value)

            self.updateConfigRef = None
            self.updateConfigRef = self.session.openWithCallback(
                self.updateConfigfinishedCB,
                MessageBox,
                _("Please wait while updating your network mount..."),
                type=MessageBox.TYPE_INFO,
                enable_input=False)
            iAutoMount.writeMountsConfig()
            iAutoMount.getAutoMountPoints(self.updateConfigDataAvail)
        else:
            self.close()

    def updateConfigDataAvail(self, data):
        if data is True:
            self.updateConfigRef.close(True)

    def updateConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(
                self.Updatefinished,
                MessageBox,
                _("Your network mount has been updated."),
                type=MessageBox.TYPE_INFO,
                timeout=10)

    def Updatefinished(self, data):
        if data is not None:
            if data is True:
                self.close()

    def applyConfig(self, ret=False):
        if (ret == True):
            data = { 'isMounted': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, \
              'username': False, 'password': False, 'mounttype' : False, 'options' : False, 'hdd_replacement' : False }
            data['active'] = self.activeConfigEntry.value
            data['ip'] = self.ipConfigEntry.getText()
            data['sharename'] = re_sub("\W", "",
                                       self.sharenameConfigEntry.value)
            # "\W" matches everything that is "not numbers, letters, or underscores",where the alphabet defaults to ASCII.
            if self.sharedirConfigEntry.value.startswith("/"):
                data['sharedir'] = self.sharedirConfigEntry.value[1:]
            else:
                data['sharedir'] = self.sharedirConfigEntry.value
            data['options'] = self.optionsConfigEntry.value
            data['mounttype'] = self.mounttypeConfigEntry.value
            data['username'] = self.usernameConfigEntry.value
            data['password'] = self.passwordConfigEntry.value
            data['hdd_replacement'] = self.hdd_replacementConfigEntry.value
            self.applyConfigRef = None
            self.applyConfigRef = self.session.openWithCallback(
                self.applyConfigfinishedCB,
                MessageBox,
                _("Please wait for activation of your network mount..."),
                type=MessageBox.TYPE_INFO,
                enable_input=False)
            iAutoMount.automounts[self.sharenameConfigEntry.value] = data
            iAutoMount.writeMountsConfig()
            iAutoMount.getAutoMountPoints(self.applyConfigDataAvail)
        else:
            self.close()

    def applyConfigDataAvail(self, data):
        if data is True:
            self.applyConfigRef.close(True)

    def applyConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(
                self.applyfinished,
                MessageBox,
                _("Your network mount has been activated."),
                type=MessageBox.TYPE_INFO,
                timeout=10)

    def applyfinished(self, data):
        if data is not None:
            if data is True:
                self.close()
Ejemplo n.º 3
0
class ChoiceBox(Screen):
#	def __init__(self, session, title = "", list = [], keys = None, selection = 0, skin_name = []):
	def __init__(self, session, title = "", list = [], keys = None, selection = 0, skin_name = [], extEntry = None):
		Screen.__init__(self, session)

		if isinstance(skin_name, str):
			skin_name = [skin_name]
		self.skinName = skin_name + ["ChoiceBox"] 
		if title:
			title = _(title)
# [iq
		try:
			if skin_name[0] == "ExtensionsList":
				from Components.Network import iNetwork
				from Components.config import ConfigIP, NoSave
				self.local_ip = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute("eth0", "ip")))

				if self.local_ip.getText() is not None:
					self["text"] = Label("IP: getting...\n" + "Local IP: " + self.local_ip.getText())
				else:
					self["text"] = Label("IP: getting...\n" + "Local IP: getting...")
			else:
				if len(title) < 55:
					Screen.setTitle(self, title)
					self["text"] = Label("")
				else:
					self["text"] = Label(title)
		except:
# iq]
			if len(title) < 55:
				Screen.setTitle(self, title)
				self["text"] = Label("")
			else:
				self["text"] = Label(title)
		self.list = []
		self.extEntry = extEntry		# [iq]
		self.summarylist = []
		if keys is None:
			self.__keys = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "red", "green", "yellow", "blue" ] + (len(list) - 10) * [""]
		else:
			self.__keys = keys + (len(list) - len(keys)) * [""]
			
		self.keymap = {}
		pos = 0
		for x in list:
			strpos = str(self.__keys[pos])
			self.list.append(ChoiceEntryComponent(key = strpos, text = x))
			if self.__keys[pos] != "":
				self.keymap[self.__keys[pos]] = list[pos]
			self.summarylist.append((self.__keys[pos],x[0]))
			pos += 1
		self["list"] = ChoiceList(list = self.list, selection = selection)
		self["summary_list"] = StaticText()
		self["summary_selection"] = StaticText()
		self.updateSummary(selection)
				
#		self["actions"] = NumberActionMap(["WizardActions", "InputActions", "ColorActions", "DirectionActions"], 
		self["actions"] = NumberActionMap(["WizardActions", "InputActions", "ColorActions", "DirectionActions", "InfobarChannelSelection"], 
		{
			"ok": self.go,
			"back": self.cancel,
			"1": self.keyNumberGlobal,
			"2": self.keyNumberGlobal,
			"3": self.keyNumberGlobal,
			"4": self.keyNumberGlobal,
			"5": self.keyNumberGlobal,
			"6": self.keyNumberGlobal,
			"7": self.keyNumberGlobal,
			"8": self.keyNumberGlobal,
			"9": self.keyNumberGlobal,
			"0": self.keyNumberGlobal,
			"red": self.keyRed,
			"green": self.keyGreen,
			"yellow": self.keyYellow,
			"blue": self.keyBlue,
			"up": self.up,
			"down": self.down,
# [iq
			"openSatellites": self.extEntryReady,
			"menu": self.extEntryGo,
# iq]
		}, -1)

# [iq
		self.extEntryExecuted = -1

		try:
			if skin_name[0] == "ExtensionsList":
				self.StaticIPTimer = enigma.eTimer()
				self.StaticIPTimer.callback.append(self.iptimeout)
				self.iptimeout()
		except:
			pass

	def extEntryReady(self):
		if self.extEntry is not None:
			if self.extEntryExecuted == 1 :
				self.extEntryExecuted = 2
			else:
				self.extEntryExecuted = -1
	def extEntryGo(self):
		if self.extEntry is not None:
			if self.extEntryExecuted == 2 and self.extEntry is not None:
				self.close(("extEntry", self.extEntry[0][0]))
			self.extEntryExecuted = 1
# iq]
	def autoResize(self):
		orgwidth = self.instance.size().width()
		orgpos = self.instance.position()
#		textsize = self["text"].getSize()
		textsize = (textsize[0] + 50, textsize[1])		# [iq]
		count = len(self.list)
		if count > 10:
			count = 10
		offset = 25 * count
		wsizex = textsize[0] + 60
		wsizey = textsize[1] + offset
		if (520 > wsizex):
			wsizex = 520
		wsize = (wsizex, wsizey)
		# resize
		self.instance.resize(enigma.eSize(*wsize))
		# resize label
		self["text"].instance.resize(enigma.eSize(*textsize))
		# move list
		listsize = (wsizex, 25 * count)
		self["list"].instance.move(enigma.ePoint(0, textsize[1]))
		self["list"].instance.resize(enigma.eSize(*listsize))
		# center window
		newwidth = wsize[0]
		self.instance.move(enigma.ePoint((720-wsizex)/2, (576-wsizey)/(count > 7 and 2 or 3)))

	def keyLeft(self):
		pass
	
	def keyRight(self):
		pass
	
	def up(self):
		if len(self["list"].list) > 0:
			while 1:
				self["list"].instance.moveSelection(self["list"].instance.moveUp)
				self.updateSummary(self["list"].l.getCurrentSelectionIndex())
				if self["list"].l.getCurrentSelection()[0][0] != "--" or self["list"].l.getCurrentSelectionIndex() == 0:
					break

	def down(self):
		if len(self["list"].list) > 0:
			while 1:
				self["list"].instance.moveSelection(self["list"].instance.moveDown)
				self.updateSummary(self["list"].l.getCurrentSelectionIndex())
				if self["list"].l.getCurrentSelection()[0][0] != "--" or self["list"].l.getCurrentSelectionIndex() == len(self["list"].list) - 1:
					break

	# runs a number shortcut
	def keyNumberGlobal(self, number):
		self.goKey(str(number))

	# runs the current selected entry
	def go(self):
		cursel = self["list"].l.getCurrentSelection()
		if cursel:
			self.goEntry(cursel[0])
		else:
			self.cancel()

	# runs a specific entry
	def goEntry(self, entry):
		if len(entry) > 2 and isinstance(entry[1], str) and entry[1] == "CALLFUNC":
			# CALLFUNC wants to have the current selection as argument
			arg = self["list"].l.getCurrentSelection()[0]
			entry[2](arg)
		else:
			self.close(entry)

	# lookups a key in the keymap, then runs it
	def goKey(self, key):
		if self.keymap.has_key(key):
			entry = self.keymap[key]
			self.goEntry(entry)

	# runs a color shortcut
	def keyRed(self):
		self.goKey("red")

	def keyGreen(self):
		self.goKey("green")

	def keyYellow(self):
		self.goKey("yellow")

	def keyBlue(self):
		self.goKey("blue")

	def updateSummary(self, curpos=0):
		pos = 0
		summarytext = ""
		for entry in self.summarylist:
			if pos > curpos-2 and pos < curpos+5:
				if pos == curpos:
					summarytext += ">"
					self["summary_selection"].setText(entry[1])
				else:
					summarytext += entry[0]
				summarytext += ' ' + entry[1] + '\n'
			pos += 1
		self["summary_list"].setText(summarytext)

	def cancel(self):
		self.close(None)
# [iq
	def iptimeout(self):
		import os
		static_ip =urllib.urlopen('http://www.ilovehobbysite.com/iprequest.php').read()
#		if os.path.isfile("/tmp/extip"):
#			fp = file('/tmp/extip', 'r')
#			static_ip = fp.read()
#			fp.close()
		if static_ip=="":
#			conn.reqest("GET","/iprequest.php")
#			r1 = conn.getresponse()
#			static_ip = r1.read()
				#os.system("wget -O /tmp/extip -T 4 -t 1 http://en2.ath.cx/iprequest.php")
			print "NOK : ", static_ip
		else:
			print "OK : ", static_ip
			self.StaticIPTimer.stop()

			self["text"].setText("IP: " + static_ip + "\nLocal IP: " + self.local_ip.getText())
				
			self["text"].show()
			return
#		else:
#			conn.reqest("GET","/iprequest.php")
#			r1 = conn.getresponse()
#            data1 = r1.read()
#			static_ip = r1.read()
			#os.system("wget -O /tmp/extip -T 2 -t 1 http://en2.ath.cx/iprequest.php")

		self.StaticIPTimer.stop()
		self.StaticIPTimer.start(2000, True)	
Ejemplo n.º 4
0
class AutoMountEdit(Screen, ConfigListScreen):
	skin = """
		<screen name="AutoMountEdit" position="center,120" size="820,520" title="MountEdit">
			<ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40" alphatest="on"/>
			<widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>
			<eLabel	position="10,50" size="800,1" backgroundColor="grey"/>
			<widget name="config" position="10,55" size="800,420" enableWrapAround="1" scrollbarMode="showOnDemand"/>
			<widget name="VKeyIcon" position="730,10" size="70,30" pixmap="skin_default/icons/text.png" alphatest="on"/>
			<widget name="HelpWindow" position="338,445" zPosition="1" size="1,1" transparent="1"/>
			<eLabel	position="10,480" size="800,1" backgroundColor="grey"/>
			<widget source="introduction" render="Label" position="10,488" size="800,25" font="Regular;22" halign="center" transparent="1"/>
		</screen>"""

	def __init__(self, session, plugin_path, mountinfo = None ):
		self.skin_path = plugin_path
		self.session = session
		Screen.__init__(self, self.session)
		ConfigListScreen.__init__(self, [],session = session)

		self.mountinfo = mountinfo
		if self.mountinfo is None:
			#Initialize default mount data (using nfs default options)
			self.mountinfo = iAutoMount.DEFAULT_OPTIONS_NFS

		self._applyConfigMsgBox = None
		self.updateConfigRef = None
		self.mounts = iAutoMount.getMounts()
		self.createConfig()

		self["actions"] = NumberActionMap(["SetupActions"],
		{
			"ok": self.ok,
			"back": self.close,
			"cancel": self.close,
			"red": self.close,
		}, -2)

		self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"],
		{
			"showVirtualKeyboard": self.KeyText,
		}, -2)

		self.createSetup()
		self.onLayoutFinish.append(self.layoutFinished)
		# Initialize Buttons
		self["VKeyIcon"] = Pixmap()
		self["HelpWindow"] = Pixmap()
		self["introduction"] = StaticText(_("Press OK to activate the settings."))
		self["key_red"] = StaticText(_("Cancel"))


	def layoutFinished(self):
		self.setTitle(_("Mounts editor"))
		self["VKeyIcon"].hide()
		self["VirtualKB"].setEnabled(False)
		self["HelpWindow"].hide()

	# helper function to convert ips from a sring to a list of ints
	def convertIP(self, ip):
		strIP = ip.split('.')
		ip = []
		for x in strIP:
			ip.append(int(x))
		return ip

	def exit(self):
		self.close()

	def createConfig(self):
		self.sharetypelist = []
		self.sharetypelist.append(("nfs", _("NFS share")))
		self.sharetypelist.append(("cifs", _("CIFS share")))

		mounttype = self.mountinfo['mounttype']
		active = self.mountinfo['active']
		ip = self.convertIP(self.mountinfo['ip'])
		sharename = self.mountinfo['sharename']
		sharedir = self.mountinfo['sharedir']
		options = self.mountinfo['options']
		username = self.mountinfo['username']
		password = self.mountinfo['password']
		hdd_replacement = self.mountinfo['hdd_replacement']
		if mounttype == "nfs":
			defaultOptions = iAutoMount.DEFAULT_OPTIONS_NFS['options']
		else:
			defaultOptions = iAutoMount.DEFAULT_OPTIONS_CIFS['options']

		self._cfgActive = NoSave(ConfigOnOff(default = active))
		self._cfgIp = NoSave(ConfigIP(default = ip))
		self._cfgSharename = NoSave(ConfigText(default = sharename, visible_width = 50, fixed_size = False))
		self._cfgSharedir = NoSave(ConfigText(default = sharedir, visible_width = 50, fixed_size = False))
		self._cfgOptions = NoSave(ConfigText(default = defaultOptions, visible_width = 50, fixed_size = False))
		if options is not False:
			self._cfgOptions.value = options
		self._cfgUsername = NoSave(ConfigText(default = username, visible_width = 50, fixed_size = False))
		self._cfgPassword = NoSave(ConfigPassword(default = password, visible_width = 50, fixed_size = False))
		self._cfgMounttype = NoSave(ConfigSelection(self.sharetypelist, default = mounttype ))
		self._cfgHddReplacement = NoSave(ConfigYesNo(default = hdd_replacement))

	def createSetup(self):
		if self._cfgOptions.value == self._cfgOptions.default:
			if self._cfgMounttype.value == "nfs":
				self._cfgOptions = NoSave(ConfigText(default = iAutoMount.DEFAULT_OPTIONS_NFS['options'], visible_width = 50, fixed_size = False))
			else:
				self._cfgOptions = NoSave(ConfigText(default = iAutoMount.DEFAULT_OPTIONS_CIFS['options'], visible_width = 50, fixed_size = False))
		optionsEntry = getConfigListEntry(_("Mount options"), self._cfgOptions)

		lst = [
			getConfigListEntry(_("Active"), self._cfgActive),
			getConfigListEntry(_("Local share name"), self._cfgSharename),
			getConfigListEntry(_("Mount type"), self._cfgMounttype),
			getConfigListEntry(_("Server IP"), self._cfgIp),
			getConfigListEntry(_("Server share"), self._cfgSharedir),
			getConfigListEntry(_("use as HDD replacement"), self._cfgHddReplacement),
			optionsEntry,
		]
		if self._cfgMounttype.value == "cifs":
			lst.extend([
				getConfigListEntry(_("Username"), self._cfgUsername),
				getConfigListEntry(_("Password"), self._cfgPassword)
			])
		self["config"].list = lst
		self["config"].onSelectionChanged.append(self.selectionChanged)

	def newConfig(self):
		if self["config"].getCurrent()[1] == self._cfgMounttype:
			self.createSetup()

	def KeyText(self):
		current = self["config"].getCurrent()[1]
		if current == self._cfgSharename:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'sharename'), VirtualKeyBoard, title = (_("Enter share name:")), text = self._cfgSharename.value)
		elif current == self._cfgSharedir:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'sharedir'), VirtualKeyBoard, title = (_("Enter share directory:")), text = self._cfgSharedir.value)
		elif current == self._cfgOptions:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'options'), VirtualKeyBoard, title = (_("Enter options:")), text = self._cfgOptions.value)
		elif current == self._cfgUsername:
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, 'username'), VirtualKeyBoard, title = (_("Enter username:"******"Enter password:"******"config"].invalidate(self._cfgSharename)
			elif entry == 'sharedir':
				self._cfgSharedir.setValue(callback)
				self["config"].invalidate(self._cfgSharedir)
			elif entry == 'options':
				self._cfgOptions.setValue(callback)
				self["config"].invalidate(self._cfgOptions)
			elif entry == 'username':
				self._cfgUsername.setValue(callback)
				self["config"].invalidate(self._cfgUsername)
			elif entry == 'password':
				self._cfgPassword.setValue(callback)
				self["config"].invalidate(self._cfgPassword)

	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()

	def selectionChanged(self):
		current = self["config"].getCurrent()[1]
		if current == self._cfgActive or current == self._cfgIp or current == self._cfgMounttype or current == self._cfgHddReplacement:
			self["VKeyIcon"].hide()
		else:
			self["VKeyIcon"].show()

	def ok(self):
		sharename = self._cfgSharename.value

		if self.mounts.has_key(sharename) is True:
			self.session.openWithCallback(self.updateConfig, MessageBox, (_("A mount entry with this name already exists!\nUpdate existing entry and continue?\n") ) )
		else:
			self.applyConfig(True)

	def updateConfig(self, ret = False):
		if ret == True:
			sharedir = None
			if self._cfgSharedir.value.startswith("/"):
				sharedir = self._cfgSharedir.value[1:]
			else:
				sharedir = self._cfgSharedir.value
			sharename = self._cfgSharename.value
			iAutoMount.setMountAttributes(sharename, {
				"sharename" : sharename,
				"active" :  self._cfgActive.value,
				"ip" :  self._cfgIp.getText(),
				"sharedir" :  sharedir,
				"mounttype" :  self._cfgMounttype.value,
				"options" :  self._cfgOptions.value,
				"username" :  self._cfgUsername.value,
				"password" :  self._cfgPassword.value,
				"hdd_replacement" :  self._cfgHddReplacement.value
			})
			self._applyConfigMsgBox = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait while updating your network mount..."), type = MessageBox.TYPE_INFO, enable_input = False)
			iAutoMount.save()
			iAutoMount.reload(self.applyConfigDataAvail)
		else:
			self.close()

	def applyConfig(self, ret = False):
		if ret:
			if self._cfgMounttype.value == 'nfs':
				data = iAutoMount.DEFAULT_OPTIONS_NFS
			else:
				data = iAutoMount.DEFAULT_OPTIONS_CIFS
			data['active'] = self._cfgActive.value
			data['ip'] = self._cfgIp.getText()
			data['sharename'] = re_sub("\W", "", self._cfgSharename.value)
			# "\W" matches everything that is "not numbers, letters, or underscores",where the alphabet defaults to ASCII.
			if self._cfgSharedir.value.startswith("/"):
				data['sharedir'] = self._cfgSharedir.value[1:]
			else:
				data['sharedir'] = self._cfgSharedir.value
			data['options'] =  self._cfgOptions.value
			data['mounttype'] = self._cfgMounttype.value
			data['username'] = self._cfgUsername.value
			data['password'] = self._cfgPassword.value
			data['hdd_replacement'] = self._cfgHddReplacement.value
			self._applyConfigMsgBox = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait while I'm saving your network mount..."), type = MessageBox.TYPE_INFO, enable_input = False)
			iAutoMount.mounts[self._cfgSharename.value] = data
			iAutoMount.save()
			iAutoMount.reload(self.applyConfigDataAvail)
		else:
			self.close()

	def applyConfigDataAvail(self, success):
		if success:
			self._applyConfigMsgBox.close(True)

	def applyConfigfinishedCB(self,data):
		if data is True:
			self.session.openWithCallback(self.applyfinished, MessageBox, _("Your network mount has been saved."), type = MessageBox.TYPE_INFO, timeout = 10)

	def applyfinished(self,data):
		if data is not None:
			if data is True:
				self.close()
Ejemplo n.º 5
0
class AutoMountEdit(Screen, ConfigListScreen):
	skin = """
		<screen name="AutoMountEdit" position="center,center" size="560,450" title="MountEdit">
			<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget name="config" position="5,50" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="div-h.png" position="0,420" zPosition="1" size="560,2" />
			<widget source="introduction" render="Label" position="10,430" size="540,21" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1"/>
			<widget name="VKeyIcon" pixmap="buttons/key_text.png" position="10,430" zPosition="10" size="35,25" transparent="1" alphatest="on" />
			<widget name="HelpWindow" pixmap="vkey_icon.png" position="160,350" zPosition="1" size="1,1" transparent="1" alphatest="on" />	
		</screen>"""

	def __init__(self, session, plugin_path, mountinfo = None ):
		self.skin_path = plugin_path
		self.session = session
		Screen.__init__(self, self.session)

		self.mountinfo = mountinfo
		if self.mountinfo is None:
			#Initialize blank mount enty
			self.mountinfo = { 'isMounted': False, 'active': False, 'ip': False, 'host': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype' : False, 'options' : False, 'hdd_replacement' : False }

		self.applyConfigRef = None
		self.updateConfigRef = None
		self.mounts = iAutoMount.getMountsList()
		self.createConfig()

		self["actions"] = NumberActionMap(["SetupActions"],
		{
			"ok": self.ok,
			"back": self.close,
			"cancel": self.close,
			"red": self.close,
		}, -2)

		self.list = []
		ConfigListScreen.__init__(self, self.list, session = self.session)
		self.createSetup()
		self.onLayoutFinish.append(self.layoutFinished)
		# Initialize Buttons
		self["VKeyIcon"] = Boolean(False)
		self["HelpWindow"] = Pixmap()
		self["HelpWindow"].hide()
		self["introduction"] = StaticText(_("Press OK to activate the settings."))
		self["key_red"] = StaticText(_("Cancel"))

	def layoutFinished(self):
		self.setTitle(_("Mounts editor"))

	def exit(self):
		self.close()

	def createConfig(self):
		self.sharenameEntry = None
		self.mounttypeEntry = None
		self.activeEntry = None
		self.ipEntry = None
		self.hostEntry = None
		self.sharedirEntry = None
		self.optionsEntry = None
		self.usernameEntry = None
		self.passwordEntry = None
		self.hdd_replacementEntry = None
		self.sharetypelist = [("nfs", _("NFS share")), ("cifs", _("CIFS share"))]

		mounttype = self.mountinfo.get('mounttype')
		if not mounttype:
			mounttype = "nfs"
		active = self.mountinfo.get('active', 'True') == 'True'
		# Not that "host" takes precedence over "ip"
		host = self.mountinfo.get('host', "")
		if not host:
			# In case host is something funky like False or None
			host = ''
		try:
			ip = convertIP(self.mountinfo['ip'])
		except Exception as ex:
			print("[NWB] Invalid IP", ex)
			ip = [0, 0, 0, 0]
		sharename = self.mountinfo.get('sharename', "Sharename")
		sharedir = self.mountinfo.get('sharedir', "/media/hdd")
		username = self.mountinfo.get('username', "")
		password = self.mountinfo.get('password', "")
		hdd_replacement = self.mountinfo.get('hdd_replacement', False)
		if hdd_replacement == 'True':
			hdd_replacement = True
		else:
			hdd_replacement = False
		if sharename is False:
			sharename = "Sharename"
		if sharedir is False:
			sharedir = "/media/hdd"
		if mounttype == "nfs":
			defaultOptions = "rw,nolock,tcp"
		else:
			defaultOptions = "rw,utf8,vers=3.0"
		if username is False:
			username = ""
		if password is False:
			password = ""
		options = self.mountinfo.get('options', defaultOptions)

		self.activeConfigEntry = NoSave(ConfigEnableDisable(default = active))
		self.ipConfigEntry = NoSave(ConfigIP(default = ip))
		self.hostConfigEntry = NoSave(ConfigText(default = host, visible_width = 50, fixed_size = False))
		self.sharenameConfigEntry = NoSave(ConfigText(default = sharename, visible_width = 50, fixed_size = False))
		self.sharedirConfigEntry = NoSave(ConfigText(default = sharedir, visible_width = 50, fixed_size = False))
		self.optionsConfigEntry = NoSave(ConfigText(default = defaultOptions, visible_width = 50, fixed_size = False))
		if options is not False:
			self.optionsConfigEntry.value = options
		self.usernameConfigEntry = NoSave(ConfigText(default = username, visible_width = 50, fixed_size = False))
		self.passwordConfigEntry = NoSave(ConfigPassword(default = password, visible_width = 50, fixed_size = False))
		self.mounttypeConfigEntry = NoSave(ConfigSelection(self.sharetypelist, default = mounttype ))
		self.hdd_replacementConfigEntry = NoSave(ConfigYesNo(default = hdd_replacement))

	def createSetup(self):
		self.list = []
		self.activeEntry = getConfigListEntry(_("Active"), self.activeConfigEntry)
		self.list.append(self.activeEntry)
		self.sharenameEntry = getConfigListEntry(_("Local mountpoint"), self.sharenameConfigEntry)
		self.list.append(self.sharenameEntry)
		self.mounttypeEntry = getConfigListEntry(_("Mount type"), self.mounttypeConfigEntry)
		self.list.append(self.mounttypeEntry)
		self.ipEntry = getConfigListEntry(_("Server IP"), self.ipConfigEntry)
		self.list.append(self.ipEntry)
		self.hostEntry = getConfigListEntry(_("Host name"), self.hostConfigEntry)
		self.list.append(self.hostEntry)
		self.sharedirEntry = getConfigListEntry(_("Server share"), self.sharedirConfigEntry)
		self.list.append(self.sharedirEntry)
		self.hdd_replacementEntry = getConfigListEntry(_("use as HDD replacement"), self.hdd_replacementConfigEntry)
		self.list.append(self.hdd_replacementEntry)
		if self.optionsConfigEntry.value == self.optionsConfigEntry.default:
			if self.mounttypeConfigEntry.value == "cifs":
				self.optionsConfigEntry = NoSave(ConfigText(default = "rw", visible_width = 50, fixed_size = False))
			else:
				self.optionsConfigEntry = NoSave(ConfigText(default = "rw,nolock,soft", visible_width = 50, fixed_size = False))
		self.optionsEntry = getConfigListEntry(_("Mount options"), self.optionsConfigEntry)
		self.list.append(self.optionsEntry)
		if self.mounttypeConfigEntry.value == "cifs":
			self.usernameEntry = getConfigListEntry(_("Username"), self.usernameConfigEntry)
			self.list.append(self.usernameEntry)
			self.passwordEntry = getConfigListEntry(_("Password"), self.passwordConfigEntry)
			self.list.append(self.passwordEntry)

		self["config"].list = self.list
		self["config"].l.setList(self.list)

	def newConfig(self):
		if self["config"].getCurrent() == self.mounttypeEntry:
			self.createSetup()

	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()

	def ok(self):
		current = self["config"].getCurrent()
		if current == self.sharenameEntry or current == self.sharedirEntry or current == self.sharedirEntry or current == self.optionsEntry or current == self.usernameEntry or current == self.passwordEntry:
			if current[1].help_window.instance is not None:
				current[1].help_window.instance.hide()
		sharename = self.sharenameConfigEntry.value
		if self.mounts.has_key(sharename):
			self.session.openWithCallback(self.updateConfig, MessageBox, (_("A mount entry with this name already exists!\nUpdate existing entry and continue?\n") ) )
		else:
			self.session.openWithCallback(self.applyConfig, MessageBox, (_("Are you sure you want to save this network mount?\n\n") ) )

	def updateConfig(self, ret = False):
		if (ret == True):
			sharedir = None
			if self.sharedirConfigEntry.value.startswith("/"):
				sharedir = self.sharedirConfigEntry.value[1:]
			else:
				sharedir = self.sharedirConfigEntry.value
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "sharename", self.sharenameConfigEntry.value)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "active", self.activeConfigEntry.value)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "host", self.hostConfigEntry.getText())
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "ip", self.ipConfigEntry.getText())
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "sharedir", sharedir)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "mounttype", self.mounttypeConfigEntry.value)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "options", self.optionsConfigEntry.value)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "username", self.usernameConfigEntry.value)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "password", self.passwordConfigEntry.value)
			iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, "hdd_replacement", self.hdd_replacementConfigEntry.value)

			self.updateConfigRef = None
			self.updateConfigRef = self.session.openWithCallback(self.updateConfigfinishedCB, MessageBox, _("Please wait while updating your network mount..."), type = MessageBox.TYPE_INFO, enable_input = False)
			iAutoMount.writeMountsConfig()
			iAutoMount.getAutoMountPoints(self.updateConfigDataAvail)
		else:
			self.close()

	def updateConfigDataAvail(self, data):
		if data is True:
			self.updateConfigRef.close(True)

	def updateConfigfinishedCB(self, data):
		if data is True:
			self.session.openWithCallback(self.Updatefinished, MessageBox, _("Your network mount has been updated."), type = MessageBox.TYPE_INFO, timeout = 10)

	def Updatefinished(self, data):
		if data is not None:
			if data is True:
				self.close()

	def applyConfig(self, ret = False):
		if (ret == True):
			data = { 'isMounted': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, \
					'username': False, 'password': False, 'mounttype' : False, 'options' : False, 'hdd_replacement' : False }
			data['active'] = self.activeConfigEntry.value
			data['host'] = self.hostConfigEntry.getText()
			data['ip'] = self.ipConfigEntry.getText()
			data['sharename'] = self.sharenameConfigEntry.value.strip()
			if self.sharedirConfigEntry.value.startswith("/"):
				data['sharedir'] = self.sharedirConfigEntry.value[1:]
			else:
				data['sharedir'] = self.sharedirConfigEntry.value
			data['options'] =  self.optionsConfigEntry.value
			data['mounttype'] = self.mounttypeConfigEntry.value
			data['username'] = self.usernameConfigEntry.value
			data['password'] = self.passwordConfigEntry.value
			data['hdd_replacement'] = self.hdd_replacementConfigEntry.value
			self.applyConfigRef = None
			self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait for activation of your network mount..."), type = MessageBox.TYPE_INFO, enable_input = False)
			iAutoMount.automounts[self.sharenameConfigEntry.value] = data
			iAutoMount.writeMountsConfig()
			iAutoMount.getAutoMountPoints(self.applyConfigDataAvail)
		else:
			self.close()

	def applyConfigDataAvail(self, data):
		if data is True:
			self.applyConfigRef.close(True)

	def applyConfigfinishedCB(self, data):
		if data is True:
			self.session.openWithCallback(self.applyfinished, MessageBox, _("Your network mount has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)

	def applyfinished(self, data):
		if data is True:
			self.close()
Ejemplo n.º 6
0
class AutoMountEdit(Screen, ConfigListScreen):
    skin = """
		<screen name="AutoMountEdit" position="center,center" size="560,450" title="MountEdit">
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget name="config" position="5,50" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="skin_default/div-h.png" position="0,420" zPosition="1" size="560,2" />
			<widget source="introduction" render="Label" position="10,430" size="540,21" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1"/>
			<widget source="VKeyIcon" render="Pixmap" pixmap="skin_default/buttons/key_text.png" position="10,430" zPosition="10" size="35,25" transparent="1" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="160,350" zPosition="1" size="1,1" transparent="1" alphatest="on" />
		</screen>"""

    def __init__(self, session, plugin_path, mountinfo=None, newmount=True):
        self.skin_path = plugin_path
        self.session = session
        Screen.__init__(self, self.session)

        self.onChangedEntry = []
        self.mountinfo = mountinfo
        self.newmount = newmount
        if self.mountinfo is None:
            #Initialize blank mount enty
            self.mountinfo = {
                'isMounted': False,
                'mountusing': False,
                'active': False,
                'ip': False,
                'sharename': False,
                'sharedir': False,
                'username': False,
                'password': False,
                'mounttype': False,
                'options': False,
                'hdd_replacement': False
            }

        self.applyConfigRef = None
        self.updateConfigRef = None
        self.mounts = iAutoMount.getMountsList()
        self.createConfig()

        self["actions"] = NumberActionMap(
            ["SetupActions", "ColorActions"], {
                "ok": self.ok,
                "back": self.close,
                "cancel": self.close,
                "red": self.close,
                "green": self.ok,
            }, -2)

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=self.session)
        self.createSetup()
        self.onLayoutFinish.append(self.layoutFinished)
        # Initialize Buttons
        self["VKeyIcon"] = Boolean(False)
        self["HelpWindow"] = Pixmap()
        self["introduction"] = StaticText(
            _("Press OK to activate the settings."))
        self["key_red"] = StaticText(_("Cancel"))
        self["key_green"] = StaticText(_("Save"))

    # for summary:
    def changedEntry(self):
        for x in self.onChangedEntry:
            x()

    def getCurrentEntry(self):
        return self["config"].getCurrent()[0]

    def getCurrentValue(self):
        return str(self["config"].getCurrent()[1].getText())

    def createSummary(self):
        from Screens.Setup import SetupSummary
        return SetupSummary

    def layoutFinished(self):
        self.setup_title = _("Mounts editor")
        Screen.setTitle(self, _(self.setup_title))
        self["VKeyIcon"].boolean = False
        self["VirtualKB"].setEnabled(False)
        self["HelpWindow"].hide()

    # helper function to convert ips from a sring to a list of ints
    def convertIP(self, ip):
        strIP = ip.split('.')
        ip = []
        for x in strIP:
            ip.append(int(x))
        return ip

    def cleanSharename(self, sharename):
        # "\W" matches everything that is "not numbers, letters, or underscores", where the alphabet defaults to ASCII.
        return re_sub("\W", "", sharename)

    def exit(self):
        self.close()

    def createConfig(self):
        self.mountusingEntry = None
        self.sharenameEntry = None
        self.mounttypeEntry = None
        self.activeEntry = None
        self.ipEntry = None
        self.sharedirEntry = None
        self.optionsEntry = None
        self.usernameEntry = None
        self.passwordEntry = None
        self.hdd_replacementEntry = None

        self.mountusing = []
        self.mountusing.append(("autofs", _("AUTOFS (mount as needed)")))
        self.mountusing.append(("fstab", _("FSTAB (mount at boot)")))
        self.mountusing.append(("enigma2", _("Enigma2 (mount using enigma2)")))

        self.sharetypelist = []
        self.sharetypelist.append(("cifs", _("CIFS share")))
        self.sharetypelist.append(("nfs", _("NFS share")))

        mountusing_default = "fstab"
        if getImageDistro() in ("openvix", "easy-gui-aus", "beyonwiz",
                                "openatv", "openhdf"):
            mountusing_default = "autofs"

        if 'mountusing' in self.mountinfo:
            mountusing = self.mountinfo['mountusing']
            if mountusing is False:
                mountusing = mountusing_default
        else:
            mountusing = mountusing_default

        if 'mounttype' in self.mountinfo:
            mounttype = self.mountinfo['mounttype']
            if mounttype is False:
                mounttype = "nfs"
        else:
            mounttype = "nfs"

        if 'active' in self.mountinfo:
            active = self.mountinfo['active']
            if active == 'True':
                active = True
            if active == 'False':
                active = False
        else:
            active = True
        if 'ip' in self.mountinfo:
            if self.mountinfo['ip'] is False:
                ip = [192, 168, 0, 0]
            else:
                ip = self.convertIP(self.mountinfo['ip'])
        else:
            ip = [192, 168, 0, 0]

        defaultOptions = default_mount_options[mounttype]
        if self.mountinfo.get('sharename'):
            sharename = self.cleanSharename(self.mountinfo['sharename'])
            self.old_sharename = self.mountinfo['sharename']

        else:
            sharename = ""
            self.old_sharename = None
        if 'sharedir' in self.mountinfo:
            sharedir = self.mountinfo['sharedir']
            self.old_sharedir = sharedir
        else:
            sharedir = ""
            self.old_sharedir = None
        if 'options' in self.mountinfo:
            options = self.mountinfo['options']
        else:
            options = defaultOptions
        if 'username' in self.mountinfo:
            username = self.mountinfo['username']
        else:
            username = ""
        if 'password' in self.mountinfo:
            password = self.mountinfo['password']
        else:
            password = ""
        if 'hdd_replacement' in self.mountinfo:
            hdd_replacement = self.mountinfo['hdd_replacement']
            if hdd_replacement == 'True':
                hdd_replacement = True
            if hdd_replacement == 'False':
                hdd_replacement = False
        else:
            hdd_replacement = False
        if sharename is False:
            sharename = ""
        if sharedir is False:
            sharedir = ""
        if username is False:
            username = ""
        if password is False:
            password = ""

        self.mountusingConfigEntry = NoSave(
            ConfigSelection(self.mountusing, default=mountusing))
        self.activeConfigEntry = NoSave(ConfigEnableDisable(default=active))
        self.ipConfigEntry = NoSave(ConfigIP(default=ip))
        self.sharenameConfigEntry = NoSave(
            ConfigText(default=sharename, visible_width=50, fixed_size=False))
        self.sharedirConfigEntry = NoSave(
            ConfigText(default=sharedir, visible_width=50, fixed_size=False))
        self.optionsConfigEntry = NoSave(
            ConfigText(default=defaultOptions,
                       visible_width=50,
                       fixed_size=False))
        if options is not False:
            self.optionsConfigEntry.value = options
        self.usernameConfigEntry = NoSave(
            ConfigText(default=username, visible_width=50, fixed_size=False))
        self.passwordConfigEntry = NoSave(
            ConfigPassword(default=password,
                           visible_width=50,
                           fixed_size=False))
        self.mounttypeConfigEntry = NoSave(
            ConfigSelection(self.sharetypelist, default=mounttype))
        self.hdd_replacementConfigEntry = NoSave(
            ConfigYesNo(default=hdd_replacement))

    def createSetup(self):
        self.list = []
        self.mountusingEntry = getConfigListEntry(_("Mount using"),
                                                  self.mountusingConfigEntry)
        self.list.append(self.mountusingEntry)
        self.activeEntry = getConfigListEntry(_("Active"),
                                              self.activeConfigEntry)
        self.list.append(self.activeEntry)
        self.sharenameEntry = getConfigListEntry(_("Local share name"),
                                                 self.sharenameConfigEntry)
        self.list.append(self.sharenameEntry)
        self.mounttypeEntry = getConfigListEntry(_("Mount type"),
                                                 self.mounttypeConfigEntry)
        self.list.append(self.mounttypeEntry)
        self.ipEntry = getConfigListEntry(_("Server IP"), self.ipConfigEntry)
        self.list.append(self.ipEntry)
        self.sharedirEntry = getConfigListEntry(_("Server share"),
                                                self.sharedirConfigEntry)
        self.list.append(self.sharedirEntry)
        self.hdd_replacementEntry = getConfigListEntry(
            _("Use as HDD replacement"), self.hdd_replacementConfigEntry)
        self.list.append(self.hdd_replacementEntry)
        self.optionsEntry = getConfigListEntry(_("Mount options"),
                                               self.optionsConfigEntry)
        self.list.append(self.optionsEntry)
        if self.mounttypeConfigEntry.value == "cifs":
            self.usernameEntry = getConfigListEntry(_("Username"),
                                                    self.usernameConfigEntry)
            self.list.append(self.usernameEntry)
            self.passwordEntry = getConfigListEntry(_("Password"),
                                                    self.passwordConfigEntry)
            self.list.append(self.passwordEntry)

        self["config"].list = self.list
        self["config"].l.setList(self.list)

        self.kbentries = {
            self.sharenameEntry: _("Enter share name:"),
            self.sharedirEntry: _("Enter share directory:"),
            self.optionsEntry: _("Enter options:"),
            self.usernameEntry: _("Enter username:"******"Enter password:"******"config"].getCurrent() == self.mounttypeEntry:
            defaultOptions = default_mount_options[
                self.mounttypeConfigEntry.value]

            if 'options' in self.mountinfo:
                options = self.mountinfo['options']
            else:
                options = defaultOptions
            self.optionsConfigEntry = NoSave(
                ConfigText(default=defaultOptions,
                           visible_width=50,
                           fixed_size=False))
            if options is not False:
                self.optionsConfigEntry.value = options
            self.createSetup()

    def KeyText(self):
        current = self["config"].getCurrent()
        if current in self.kbentries:
            self.HideHelp()
            self.session.openWithCallback(self.VirtualKeyBoardCallback,
                                          VirtualKeyBoard,
                                          title=self.kbentries[current],
                                          text=current[1].value)

    def VirtualKeyBoardCallback(self, callback=None):
        if callback is not None and len(callback):
            current = self["config"].getCurrent()[1]
            current.value = callback
            self["config"].invalidate(current)
        self.ShowHelp()

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def ok(self):
        current = self["config"].getCurrent()
        if current == self.sharenameEntry or current == self.sharedirEntry or current == self.sharedirEntry or current == self.optionsEntry or current == self.usernameEntry or current == self.passwordEntry:
            if current[1].help_window.instance is not None:
                current[1].help_window.instance.hide()

        sharename = self.cleanSharename(self.sharenameConfigEntry.value)
        if self.sharedirConfigEntry.value.startswith("/"):
            sharedir = self.sharedirConfigEntry.value[1:]
        else:
            sharedir = self.sharedirConfigEntry.value

        sharexists = False
        for data in self.mounts:
            if self.mounts[data]['sharename'] == self.old_sharename:
                sharexists = True
                break

        if not self.newmount and self.old_sharename and self.old_sharename != sharename:
            self.session.openWithCallback(
                self.updateConfig,
                MessageBox,
                _("You have changed the share name!\nUpdate existing entry and continue?\n"
                  ),
                default=False)
        elif not self.newmount and self.old_sharename and self.old_sharename == sharename and sharexists:
            self.session.openWithCallback(
                self.updateConfig,
                MessageBox,
                _("A mount entry with this name already exists!\nUpdate existing entry and continue?\n"
                  ),
                default=False)
        else:
            self.session.openWithCallback(
                self.applyConfig, MessageBox,
                _("Are you sure you want to save this network mount?\n\n"))

    def updateConfig(self, ret=False):
        if (ret == True):
            sharedir = None
            sharename = self.cleanSharename(self.sharenameConfigEntry.value)
            xml_sharename = self.old_sharename

            if self.sharedirConfigEntry.value.startswith("/"):
                sharedir = self.sharedirConfigEntry.value[1:]
            else:
                sharedir = self.sharedirConfigEntry.value
            iAutoMount.setMountsAttribute(xml_sharename, "mountusing",
                                          self.mountusingConfigEntry.value)
            iAutoMount.setMountsAttribute(xml_sharename, "sharename",
                                          sharename)
            iAutoMount.setMountsAttribute(xml_sharename, "active",
                                          self.activeConfigEntry.value)
            iAutoMount.setMountsAttribute(xml_sharename, "ip",
                                          self.ipConfigEntry.getText())
            iAutoMount.setMountsAttribute(xml_sharename, "sharedir", sharedir)
            iAutoMount.setMountsAttribute(xml_sharename, "mounttype",
                                          self.mounttypeConfigEntry.value)
            iAutoMount.setMountsAttribute(xml_sharename, "options",
                                          self.optionsConfigEntry.value)
            iAutoMount.setMountsAttribute(xml_sharename, "username",
                                          self.usernameConfigEntry.value)
            iAutoMount.setMountsAttribute(xml_sharename, "password",
                                          self.passwordConfigEntry.value)
            iAutoMount.setMountsAttribute(
                xml_sharename, "hdd_replacement",
                self.hdd_replacementConfigEntry.value)

            self.updateConfigRef = None
            self.updateConfigRef = self.session.openWithCallback(
                self.updateConfigfinishedCB,
                MessageBox,
                _("Please wait while updating your network mount..."),
                type=MessageBox.TYPE_INFO,
                enable_input=False)
            iAutoMount.writeMountsConfig()
            iAutoMount.getAutoMountPoints(self.updateConfigDataAvail, True)
        else:
            self.close()

    def updateConfigDataAvail(self, data):
        if data is True:
            self.updateConfigRef.close(True)

    def updateConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(
                self.Updatefinished,
                MessageBox,
                _("Your network mount has been updated."),
                type=MessageBox.TYPE_INFO,
                timeout=10)

    def Updatefinished(self, data):
        if data is not None:
            if data is True:
                self.close()

    def applyConfig(self, ret=False):
        if (ret == True):
            data = {
                'isMounted': False,
                'mountusing': False,
                'active': False,
                'ip': False,
                'sharename': False,
                'sharedir': False,
                'username': False,
                'password': False,
                'mounttype': False,
                'options': False,
                'hdd_replacement': False
            }
            data['mountusing'] = self.mountusingConfigEntry.value
            data['active'] = self.activeConfigEntry.value
            data['ip'] = self.ipConfigEntry.getText()
            data['sharename'] = self.cleanSharename(
                self.sharenameConfigEntry.value)

            if self.sharedirConfigEntry.value.startswith("/"):
                data['sharedir'] = self.sharedirConfigEntry.value[1:]
            else:
                data['sharedir'] = self.sharedirConfigEntry.value
            data['options'] = self.optionsConfigEntry.value
            data['mounttype'] = self.mounttypeConfigEntry.value
            data['username'] = self.usernameConfigEntry.value
            data['password'] = self.passwordConfigEntry.value
            data['hdd_replacement'] = self.hdd_replacementConfigEntry.value
            self.applyConfigRef = None
            self.applyConfigRef = self.session.openWithCallback(
                self.applyConfigfinishedCB,
                MessageBox,
                _("Please wait for activation of your network mount..."),
                type=MessageBox.TYPE_INFO,
                enable_input=False)
            iAutoMount.automounts[self.sharenameConfigEntry.value] = data
            iAutoMount.writeMountsConfig()
            iAutoMount.getAutoMountPoints(self.applyConfigDataAvail, True)
        else:
            self.close()

    def applyConfigDataAvail(self, data):
        if data is True:
            self.applyConfigRef.close(True)

    def applyConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(
                self.applyfinished,
                MessageBox,
                _("Your network mount has been activated."),
                type=MessageBox.TYPE_INFO,
                timeout=10)

    def applyfinished(self, data):
        if data is not None:
            if data is True:
                self.close()
Ejemplo n.º 7
0
class AutoMountEdit(Screen, ConfigListScreen):
    skin = """
                <screen name="AutoMountEdit" position="center,center" size="560,450" title="MountEdit">
                        <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
                        <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
                        <widget name="config" position="5,50" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />
                        <ePixmap pixmap="skin_default/div-h.png" position="0,420" zPosition="1" size="560,2" />
                        <widget source="introduction" render="Label" position="10,430" size="540,21" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1"/>
                        <widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="10,430" zPosition="10" size="35,25" transparent="1" alphatest="on" />
                        <widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="160,350" zPosition="1" size="1,1" transparent="1" alphatest="on" />
                </screen>"""

    def __init__(self, session, plugin_path, mountinfo=None):
        self.skin_path = plugin_path
        self.session = session
        Screen.__init__(self, self.session)
        ConfigListScreen.__init__(self, [], session=session)

        self.mountinfo = mountinfo
        if self.mountinfo is None:
            #Initialize default mount data (using nfs default options)
            self.mountinfo = iAutoMount.DEFAULT_OPTIONS_NFS

        self._applyConfigMsgBox = None
        self.updateConfigRef = None
        self.mounts = iAutoMount.getMounts()
        self.createConfig()

        self["actions"] = NumberActionMap(
            ["SetupActions"], {
                "ok": self.ok,
                "back": self.close,
                "cancel": self.close,
                "red": self.close,
            }, -2)

        self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"], {
            "showVirtualKeyboard": self.KeyText,
        }, -2)

        self.createSetup()
        self.onLayoutFinish.append(self.layoutFinished)
        # Initialize Buttons
        self["VKeyIcon"] = Pixmap()
        self["HelpWindow"] = Pixmap()
        self["introduction"] = StaticText(
            _("Press OK to activate the settings."))
        self["key_red"] = StaticText(_("Cancel"))

    def layoutFinished(self):
        self.setTitle(_("Mounts editor"))
        self["VKeyIcon"].hide()
        self["VirtualKB"].setEnabled(False)
        self["HelpWindow"].hide()

    # helper function to convert ips from a sring to a list of ints
    def convertIP(self, ip):
        strIP = ip.split('.')
        ip = []
        for x in strIP:
            ip.append(int(x))
        return ip

    def exit(self):
        self.close()

    def createConfig(self):
        self.sharetypelist = []
        self.sharetypelist.append(("nfs", _("NFS share")))
        self.sharetypelist.append(("cifs", _("CIFS share")))

        mounttype = self.mountinfo['mounttype']
        active = self.mountinfo['active']
        ip = self.convertIP(self.mountinfo['ip'])
        sharename = self.mountinfo['sharename']
        sharedir = self.mountinfo['sharedir']
        options = self.mountinfo['options']
        username = self.mountinfo['username']
        password = self.mountinfo['password']
        hdd_replacement = self.mountinfo['hdd_replacement']
        if mounttype == "nfs":
            defaultOptions = iAutoMount.DEFAULT_OPTIONS_NFS['options']
        else:
            defaultOptions = iAutoMount.DEFAULT_OPTIONS_CIFS['options']

        self._cfgActive = NoSave(ConfigOnOff(default=active))
        self._cfgIp = NoSave(ConfigIP(default=ip))
        self._cfgSharename = NoSave(
            ConfigText(default=sharename, visible_width=50, fixed_size=False))
        self._cfgSharedir = NoSave(
            ConfigText(default=sharedir, visible_width=50, fixed_size=False))
        self._cfgOptions = NoSave(
            ConfigText(default=defaultOptions,
                       visible_width=50,
                       fixed_size=False))
        if options is not False:
            self._cfgOptions.value = options
        self._cfgUsername = NoSave(
            ConfigText(default=username, visible_width=50, fixed_size=False))
        self._cfgPassword = NoSave(
            ConfigPassword(default=password,
                           visible_width=50,
                           fixed_size=False))
        self._cfgMounttype = NoSave(
            ConfigSelection(self.sharetypelist, default=mounttype))
        self._cfgHddReplacement = NoSave(ConfigYesNo(default=hdd_replacement))

    def createSetup(self):
        if self._cfgOptions.value == self._cfgOptions.default:
            if self._cfgMounttype.value == "nfs":
                self._cfgOptions = NoSave(
                    ConfigText(
                        default=iAutoMount.DEFAULT_OPTIONS_NFS['options'],
                        visible_width=50,
                        fixed_size=False))
            else:
                self._cfgOptions = NoSave(
                    ConfigText(
                        default=iAutoMount.DEFAULT_OPTIONS_CIFS['options'],
                        visible_width=50,
                        fixed_size=False))
        optionsEntry = getConfigListEntry(_("Mount options"), self._cfgOptions)

        lst = [
            getConfigListEntry(_("Active"), self._cfgActive),
            getConfigListEntry(_("Local share name"), self._cfgSharename),
            getConfigListEntry(_("Mount type"), self._cfgMounttype),
            getConfigListEntry(_("Server IP"), self._cfgIp),
            getConfigListEntry(_("Server share"), self._cfgSharedir),
            getConfigListEntry(_("use as HDD replacement"),
                               self._cfgHddReplacement),
            optionsEntry,
        ]
        if self._cfgMounttype.value == "cifs":
            lst.extend([
                getConfigListEntry(_("Username"), self._cfgUsername),
                getConfigListEntry(_("Password"), self._cfgPassword)
            ])
        self["config"].list = lst
        self["config"].onSelectionChanged.append(self.selectionChanged)

    def newConfig(self):
        if self["config"].getCurrent()[1] == self._cfgMounttype:
            self.createSetup()

    def KeyText(self):
        current = self["config"].getCurrent()[1]
        if current == self._cfgSharename:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'sharename'),
                VirtualKeyBoard,
                title=(_("Enter share name:")),
                text=self._cfgSharename.value)
        elif current == self._cfgSharedir:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'sharedir'),
                VirtualKeyBoard,
                title=(_("Enter share directory:")),
                text=self._cfgSharedir.value)
        elif current == self._cfgOptions:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'options'),
                VirtualKeyBoard,
                title=(_("Enter options:")),
                text=self._cfgOptions.value)
        elif current == self._cfgUsername:
            self.session.openWithCallback(
                lambda x: self.VirtualKeyBoardCallback(x, 'username'),
                VirtualKeyBoard,
                title=(_("Enter username:"******"Enter password:"******"config"].invalidate(self._cfgSharename)
            elif entry == 'sharedir':
                self._cfgSharedir.setValue(callback)
                self["config"].invalidate(self._cfgSharedir)
            elif entry == 'options':
                self._cfgOptions.setValue(callback)
                self["config"].invalidate(self._cfgOptions)
            elif entry == 'username':
                self._cfgUsername.setValue(callback)
                self["config"].invalidate(self._cfgUsername)
            elif entry == 'password':
                self._cfgPassword.setValue(callback)
                self["config"].invalidate(self._cfgPassword)

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def selectionChanged(self):
        current = self["config"].getCurrent()[1]
        if current == self._cfgActive or current == self._cfgIp or current == self._cfgMounttype or current == self._cfgHddReplacement:
            self["VKeyIcon"].hide()
        else:
            self["VKeyIcon"].show()

    def ok(self):
        sharename = self._cfgSharename.value

        if self.mounts.has_key(sharename) is True:
            self.session.openWithCallback(self.updateConfig, MessageBox, (_(
                "A mount entry with this name already exists!\nUpdate existing entry and continue?\n"
            )))
        else:
            self.session.openWithCallback(
                self.applyConfig, MessageBox,
                (_("Are you sure you want to save this network mount?\n\n")))

    def updateConfig(self, ret=False):
        if ret == True:
            sharedir = None
            if self._cfgSharedir.value.startswith("/"):
                sharedir = self._cfgSharedir.value[1:]
            else:
                sharedir = self._cfgSharedir.value
            sharename = self._cfgSharename.value
            iAutoMount.setMountAttributes(
                sharename, {
                    "sharename": sharename,
                    "active": self._cfgActive.value,
                    "ip": self._cfgIp.getText(),
                    "sharedir": sharedir,
                    "mounttype": self._cfgMounttype.value,
                    "options": self._cfgOptions.value,
                    "username": self._cfgUsername.value,
                    "password": self._cfgPassword.value,
                    "hdd_replacement": self._cfgHddReplacement.value
                })
            self._applyConfigMsgBox = self.session.openWithCallback(
                self.applyConfigfinishedCB,
                MessageBox,
                _("Please wait while updating your network mount..."),
                type=MessageBox.TYPE_INFO,
                enable_input=False)
            iAutoMount.save()
            iAutoMount.reload(self.applyConfigDataAvail)
        else:
            self.close()

    def applyConfig(self, ret=False):
        if ret == True:
            data = iAutoMount.DEFAULT_OPTIONS_NFS
            data['active'] = self._cfgActive.value
            data['ip'] = self._cfgIp.getText()
            data['sharename'] = re_sub("\W", "", self._cfgSharename.value)
            # "\W" matches everything that is "not numbers, letters, or underscores",where the alphabet defaults to ASCII.
            if self._cfgSharedir.value.startswith("/"):
                data['sharedir'] = self._cfgSharedir.value[1:]
            else:
                data['sharedir'] = self._cfgSharedir.value
            data['options'] = self._cfgOptions.value
            data['mounttype'] = self._cfgMounttype.value
            data['username'] = self._cfgUsername.value
            data['password'] = self._cfgPassword.value
            data['hdd_replacement'] = self._cfgHddReplacement.value
            self._applyConfigMsgBox = self.session.openWithCallback(
                self.applyConfigfinishedCB,
                MessageBox,
                _("Please wait while I'm saving your network mount..."),
                type=MessageBox.TYPE_INFO,
                enable_input=False)
            iAutoMount.mounts[self._cfgSharename.value] = data
            iAutoMount.save()
            iAutoMount.reload(self.applyConfigDataAvail)
        else:
            self.close()

    def applyConfigDataAvail(self, success):
        if success:
            self._applyConfigMsgBox.close(True)

    def applyConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(
                self.applyfinished,
                MessageBox,
                _("Your network mount has been saved."),
                type=MessageBox.TYPE_INFO,
                timeout=10)

    def applyfinished(self, data):
        if data is not None:
            if data is True:
                self.close()
Ejemplo n.º 8
0
class AutoMountEdit(Screen, ConfigListScreen):
    skin = '\n\t\t<screen name="AutoMountEdit" position="center,center" size="560,450" title="MountEdit">\n\t\t\t<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />\n\t\t\t<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />\n\t\t\t<widget name="config" position="5,50" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />\n\t\t\t<ePixmap pixmap="skin_default/div-h.png" position="0,420" zPosition="1" size="560,2" />\n\t\t\t<widget source="introduction" render="Label" position="10,430" size="540,21" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1"/>\n\t\t\t<widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="10,430" zPosition="10" size="35,25" transparent="1" alphatest="on" />\n\t\t\t<widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="160,350" zPosition="1" size="1,1" transparent="1" alphatest="on" />\n\t\t</screen>'

    def __init__(self, session, plugin_path, mountinfo = None):
        self.skin_path = plugin_path
        self.session = session
        Screen.__init__(self, self.session)
        self.onChangedEntry = []
        self.mountinfo = mountinfo
        if self.mountinfo is None:
            self.mountinfo = {'isMounted': False,
             'mountusing': False,
             'active': False,
             'ip': False,
             'sharename': False,
             'sharedir': False,
             'username': False,
             'password': False,
             'mounttype': False,
             'options': False,
             'hdd_replacement': False}
        self.applyConfigRef = None
        self.updateConfigRef = None
        self.mounts = iAutoMount.getMountsList()
        self.createConfig()
        self['actions'] = NumberActionMap(['SetupActions', 'ColorActions'], {'ok': self.ok,
         'back': self.close,
         'cancel': self.close,
         'red': self.close,
         'green': self.ok}, -2)
        self['VirtualKB'] = ActionMap(['VirtualKeyboardActions'], {'showVirtualKeyboard': self.KeyText}, -2)
        self.list = []
        ConfigListScreen.__init__(self, self.list, session=self.session)
        self.createSetup()
        self.onLayoutFinish.append(self.layoutFinished)
        self['VKeyIcon'] = Pixmap()
        self['HelpWindow'] = Pixmap()
        self['introduction'] = StaticText(_('Press OK to activate the settings.'))
        self['key_red'] = StaticText(_('Cancel'))
        self['key_green'] = StaticText(_('Save'))
        self.selectionChanged()



    def changedEntry(self):
        for x in self.onChangedEntry:
            x()




    def getCurrentEntry(self):
        return self['config'].getCurrent()[0]



    def getCurrentValue(self):
        return str(self['config'].getCurrent()[1].getText())



    def createSummary(self):
        from Screens.Setup import SetupSummary
        return SetupSummary



    def layoutFinished(self):
        self.setup_title = _('Mounts editor')
        Screen.setTitle(self, _(self.setup_title))
        self['VKeyIcon'].hide()
        self['VirtualKB'].setEnabled(False)
        self['HelpWindow'].hide()



    def convertIP(self, ip):
        strIP = ip.split('.')
        ip = []
        for x in strIP:
            ip.append(int(x))

        return ip



    def exit(self):
        self.close()



    def createConfig(self):
        self.mountusingEntry = None
        self.sharenameEntry = None
        self.mounttypeEntry = None
        self.activeEntry = None
        self.ipEntry = None
        self.sharedirEntry = None
        self.optionsEntry = None
        self.usernameEntry = None
        self.passwordEntry = None
        self.hdd_replacementEntry = None
        self.mountusing = []
        self.mountusing.append(('fstab', _('FSTAB (mount using linux)')))
        self.mountusing.append(('enigma2', _('Enigma2 (mount using enigma2)')))
        self.mountusing.append(('old_enigma2', _('Enigma2 old format (mount using linux)')))
        self.sharetypelist = []
        self.sharetypelist.append(('nfs', _('NFS share')))
        self.sharetypelist.append(('cifs', _('CIFS share')))
        if self.mountinfo.has_key('mountusing'):
            mountusing = self.mountinfo['mountusing']
            if mountusing is False:
                mountusing = 'fstab'
        else:
            mountusing = 'fstab'
        if self.mountinfo.has_key('mounttype'):
            mounttype = self.mountinfo['mounttype']
            if mounttype is False:
                mounttype = 'nfs'
        else:
            mounttype = 'nfs'
        if self.mountinfo.has_key('active'):
            active = self.mountinfo['active']
            if active == 'True':
                active = True
            if active == 'False':
                active = False
        else:
            active = True
        if self.mountinfo.has_key('ip'):
            if self.mountinfo['ip'] is False:
                ip = [192,
                 168,
                 0,
                 0]
            else:
                ip = self.convertIP(self.mountinfo['ip'])
        else:
            ip = [192,
             168,
             0,
             0]
        if mounttype == 'nfs':
            defaultOptions = 'rw,nolock,tcp'
        else:
            defaultOptions = 'rw,utf8'
        if self.mountinfo['sharename'] and self.mountinfo.has_key('sharename'):
            sharename = re_sub('\\W', '', self.mountinfo['sharename'])
        else:
            sharename = 'Sharename'
        if self.mountinfo.has_key('sharedir'):
            sharedir = self.mountinfo['sharedir']
        else:
            sharedir = '/export/hdd'
        if self.mountinfo.has_key('options'):
            options = self.mountinfo['options']
        else:
            options = defaultOptions
        if self.mountinfo.has_key('username'):
            username = self.mountinfo['username']
        else:
            username = ''
        if self.mountinfo.has_key('password'):
            password = self.mountinfo['password']
        else:
            password = ''
        if self.mountinfo.has_key('hdd_replacement'):
            hdd_replacement = self.mountinfo['hdd_replacement']
            if hdd_replacement == 'True':
                hdd_replacement = True
            if hdd_replacement == 'False':
                hdd_replacement = False
        else:
            hdd_replacement = False
        if sharename is False:
            sharename = 'Sharename'
        if sharedir is False:
            sharedir = '/export/hdd'
        if username is False:
            username = ''
        if password is False:
            password = ''
        self.mountusingConfigEntry = NoSave(ConfigSelection(self.mountusing, default=mountusing))
        self.activeConfigEntry = NoSave(ConfigEnableDisable(default=active))
        self.ipConfigEntry = NoSave(ConfigIP(default=ip))
        self.sharenameConfigEntry = NoSave(ConfigText(default=sharename, visible_width=50, fixed_size=False))
        self.sharedirConfigEntry = NoSave(ConfigText(default=sharedir, visible_width=50, fixed_size=False))
        self.optionsConfigEntry = NoSave(ConfigText(default=defaultOptions, visible_width=50, fixed_size=False))
        if options is not False:
            self.optionsConfigEntry.value = options
        self.usernameConfigEntry = NoSave(ConfigText(default=username, visible_width=50, fixed_size=False))
        self.passwordConfigEntry = NoSave(ConfigPassword(default=password, visible_width=50, fixed_size=False))
        self.mounttypeConfigEntry = NoSave(ConfigSelection(self.sharetypelist, default=mounttype))
        self.hdd_replacementConfigEntry = NoSave(ConfigYesNo(default=hdd_replacement))



    def createSetup(self):
        self.list = []
        self.mountusingEntry = getConfigListEntry(_('Mount using'), self.mountusingConfigEntry)
        self.list.append(self.mountusingEntry)
        self.activeEntry = getConfigListEntry(_('Active'), self.activeConfigEntry)
        self.list.append(self.activeEntry)
        self.sharenameEntry = getConfigListEntry(_('Local share name'), self.sharenameConfigEntry)
        self.list.append(self.sharenameEntry)
        self.mounttypeEntry = getConfigListEntry(_('Mount type'), self.mounttypeConfigEntry)
        self.list.append(self.mounttypeEntry)
        self.ipEntry = getConfigListEntry(_('Server IP'), self.ipConfigEntry)
        self.list.append(self.ipEntry)
        self.sharedirEntry = getConfigListEntry(_('Server share'), self.sharedirConfigEntry)
        self.list.append(self.sharedirEntry)
        self.hdd_replacementEntry = getConfigListEntry(_('use as HDD replacement'), self.hdd_replacementConfigEntry)
        self.list.append(self.hdd_replacementEntry)
        self.optionsEntry = getConfigListEntry(_('Mount options'), self.optionsConfigEntry)
        self.list.append(self.optionsEntry)
        if self.mounttypeConfigEntry.value == 'cifs':
            self.usernameEntry = getConfigListEntry(_('Username'), self.usernameConfigEntry)
            self.list.append(self.usernameEntry)
            self.passwordEntry = getConfigListEntry(_('Password'), self.passwordConfigEntry)
            self.list.append(self.passwordEntry)
        self['config'].list = self.list
        self['config'].l.setList(self.list)
        self['config'].onSelectionChanged.append(self.selectionChanged)



    def newConfig(self):
        if self['config'].getCurrent() == self.mounttypeEntry:
            if self.mounttypeConfigEntry.value == 'nfs':
                defaultOptions = 'rw,nolock,tcp'
            else:
                defaultOptions = 'rw,utf8'
            if self.mountinfo.has_key('options'):
                options = self.mountinfo['options']
            else:
                options = defaultOptions
            self.optionsConfigEntry = NoSave(ConfigText(default=defaultOptions, visible_width=50, fixed_size=False))
            if options is not False:
                self.optionsConfigEntry.value = options
            self.createSetup()



    def KeyText(self):
        print 'Green Pressed'
        if self['config'].getCurrent() == self.sharenameEntry:
            self.session.openWithCallback(lambda x: self.VirtualKeyBoardCallback(x, 'sharename'), VirtualKeyBoard, title=_('Enter share name:'), text=self.sharenameConfigEntry.value)
        if self['config'].getCurrent() == self.sharedirEntry:
            self.session.openWithCallback(lambda x: self.VirtualKeyBoardCallback(x, 'sharedir'), VirtualKeyBoard, title=_('Enter share directory:'), text=self.sharedirConfigEntry.value)
        if self['config'].getCurrent() == self.optionsEntry:
            self.session.openWithCallback(lambda x: self.VirtualKeyBoardCallback(x, 'options'), VirtualKeyBoard, title=_('Enter options:'), text=self.optionsConfigEntry.value)
        if self['config'].getCurrent() == self.usernameEntry:
            self.session.openWithCallback(lambda x: self.VirtualKeyBoardCallback(x, 'username'), VirtualKeyBoard, title=_('Enter username:'******'config'].getCurrent() == self.passwordEntry:
            self.session.openWithCallback(lambda x: self.VirtualKeyBoardCallback(x, 'password'), VirtualKeyBoard, title=_('Enter password:'******'sharename':
                self.sharenameConfigEntry.setValue(callback)
                self['config'].invalidate(self.sharenameConfigEntry)
            if entry == 'sharedir':
                self.sharedirConfigEntry.setValue(callback)
                self['config'].invalidate(self.sharedirConfigEntry)
            if entry == 'options':
                self.optionsConfigEntry.setValue(callback)
                self['config'].invalidate(self.optionsConfigEntry)
            if entry == 'username':
                self.usernameConfigEntry.setValue(callback)
                self['config'].invalidate(self.usernameConfigEntry)
            if entry == 'password':
                self.passwordConfigEntry.setValue(callback)
                self['config'].invalidate(self.passwordConfigEntry)



    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()



    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()



    def selectionChanged(self):
        current = self['config'].getCurrent()
        if current == self.mountusingEntry or current == self.activeEntry or current == self.ipEntry or current == self.mounttypeEntry or current == self.hdd_replacementEntry:
            self['VKeyIcon'].hide()
            self['VirtualKB'].setEnabled(False)
        else:
            helpwindowpos = self['HelpWindow'].getPosition()
            if current[1].help_window.instance is not None:
                current[1].help_window.instance.move(ePoint(helpwindowpos[0], helpwindowpos[1]))
                self['VKeyIcon'].show()
                self['VirtualKB'].setEnabled(True)



    def ok(self):
        current = self['config'].getCurrent()
        if current == self.sharenameEntry or current == self.sharedirEntry or current == self.sharedirEntry or current == self.optionsEntry or current == self.usernameEntry or current == self.passwordEntry:
            if current[1].help_window.instance is not None:
                current[1].help_window.instance.hide()
        sharename = re_sub('\\W', '', self.sharenameConfigEntry.value)
        if self.sharedirConfigEntry.value.startswith('/'):
            sharedir = self.sharedirConfigEntry.value[1:]
        else:
            sharedir = self.sharedirConfigEntry.value
        sharexists = False
        for data in self.mounts:
            if self.mounts[data]['sharename'] == sharename:
                if self.mounts[data]['sharedir'] != sharedir:
                    sharexists = True
                    break

        if sharexists:
            self.session.open(MessageBox, _('A mount entry with this name already exists!\nand is not this share folder, please use a different name.\n'), type=MessageBox.TYPE_INFO)
        elif self.mounts.has_key(sharename) is True:
            self.session.openWithCallback(self.updateConfig, MessageBox, _('A mount entry with this name already exists!\nUpdate existing entry and continue?\n'), default=False)
        else:
            self.session.openWithCallback(self.applyConfig, MessageBox, _('Are you sure you want to save this network mount?\n\n'))



    def updateConfig(self, ret = False):
        if ret == True:
            sharedir = None
            if self.sharedirConfigEntry.value.startswith('/'):
                sharedir = self.sharedirConfigEntry.value[1:]
            else:
                sharedir = self.sharedirConfigEntry.value
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'mountusing', self.mountusingConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'sharename', self.sharenameConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'active', self.activeConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'ip', self.ipConfigEntry.getText())
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'sharedir', sharedir)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'mounttype', self.mounttypeConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'options', self.optionsConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'username', self.usernameConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'password', self.passwordConfigEntry.value)
            iAutoMount.setMountsAttribute(self.sharenameConfigEntry.value, 'hdd_replacement', self.hdd_replacementConfigEntry.value)
            self.updateConfigRef = None
            self.updateConfigRef = self.session.openWithCallback(self.updateConfigfinishedCB, MessageBox, _('Please wait while updating your network mount...'), type=MessageBox.TYPE_INFO, enable_input=False)
            iAutoMount.writeMountsConfig()
            iAutoMount.getAutoMountPoints(self.updateConfigDataAvail)
        else:
            self.close()



    def updateConfigDataAvail(self, data):
        if data is True:
            self.updateConfigRef.close(True)



    def updateConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(self.Updatefinished, MessageBox, _('Your network mount has been updated.'), type=MessageBox.TYPE_INFO, timeout=10)



    def Updatefinished(self, data):
        if data is not None:
            if data is True:
                self.close()



    def applyConfig(self, ret = False):
        if ret == True:
            data = {'isMounted': False,
             'mountusing': False,
             'active': False,
             'ip': False,
             'sharename': False,
             'sharedir': False,
             'username': False,
             'password': False,
             'mounttype': False,
             'options': False,
             'hdd_replacement': False}
            data['mountusing'] = self.mountusingConfigEntry.value
            data['active'] = self.activeConfigEntry.value
            data['ip'] = self.ipConfigEntry.getText()
            data['sharename'] = re_sub('\\W', '', self.sharenameConfigEntry.value)
            if self.sharedirConfigEntry.value.startswith('/'):
                data['sharedir'] = self.sharedirConfigEntry.value[1:]
            else:
                data['sharedir'] = self.sharedirConfigEntry.value
            data['options'] = self.optionsConfigEntry.value
            data['mounttype'] = self.mounttypeConfigEntry.value
            data['username'] = self.usernameConfigEntry.value
            data['password'] = self.passwordConfigEntry.value
            data['hdd_replacement'] = self.hdd_replacementConfigEntry.value
            self.applyConfigRef = None
            self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _('Please wait for activation of your network mount...'), type=MessageBox.TYPE_INFO, enable_input=False)
            iAutoMount.automounts[self.sharenameConfigEntry.value] = data
            iAutoMount.writeMountsConfig()
            iAutoMount.getAutoMountPoints(self.applyConfigDataAvail)
        else:
            self.close()



    def applyConfigDataAvail(self, data):
        if data is True:
            self.applyConfigRef.close(True)



    def applyConfigfinishedCB(self, data):
        if data is True:
            self.session.openWithCallback(self.applyfinished, MessageBox, _('Your network mount has been activated.'), type=MessageBox.TYPE_INFO, timeout=10)



    def applyfinished(self, data):
        if data is not None:
            if data is True:
                self.close()
Ejemplo n.º 9
0
class ChoiceBox(Screen):
    #	def __init__(self, session, title = "", list = [], keys = None, selection = 0, skin_name = []):
    def __init__(self,
                 session,
                 title="",
                 list=[],
                 keys=None,
                 selection=0,
                 skin_name=[],
                 extEntry=None):
        Screen.__init__(self, session)

        if isinstance(skin_name, str):
            skin_name = [skin_name]
        self.skinName = skin_name + ["ChoiceBox"]
        if title:
            title = _(title)
# [iq
        try:
            if skin_name[0] == "ExtensionsList":
                from Components.Network import iNetwork
                from Components.config import ConfigIP, NoSave
                self.local_ip = NoSave(
                    ConfigIP(
                        default=iNetwork.getAdapterAttribute("eth0", "ip")))

                if self.local_ip.getText() is not None:
                    self["text"] = Label("IP: getting...\n" + "Local IP: " +
                                         self.local_ip.getText())
                else:
                    self["text"] = Label("IP: getting...\n" +
                                         "Local IP: getting...")
            else:
                if len(title) < 55:
                    Screen.setTitle(self, title)
                    self["text"] = Label("")
                else:
                    self["text"] = Label(title)
        except:
            # iq]
            if len(title) < 55:
                Screen.setTitle(self, title)
                self["text"] = Label("")
            else:
                self["text"] = Label(title)
        self.list = []
        self.extEntry = extEntry  # [iq]
        self.summarylist = []
        if keys is None:
            self.__keys = [
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "red",
                "green", "yellow", "blue"
            ] + (len(list) - 10) * [""]
        else:
            self.__keys = keys + (len(list) - len(keys)) * [""]

        self.keymap = {}
        pos = 0
        for x in list:
            strpos = str(self.__keys[pos])
            self.list.append(ChoiceEntryComponent(key=strpos, text=x))
            if self.__keys[pos] != "":
                self.keymap[self.__keys[pos]] = list[pos]
            self.summarylist.append((self.__keys[pos], x[0]))
            pos += 1
        self["list"] = ChoiceList(list=self.list, selection=selection)
        self["summary_list"] = StaticText()
        self["summary_selection"] = StaticText()
        self.updateSummary(selection)

        #		self["actions"] = NumberActionMap(["WizardActions", "InputActions", "ColorActions", "DirectionActions"],
        self["actions"] = NumberActionMap(
            [
                "WizardActions", "InputActions", "ColorActions",
                "DirectionActions", "InfobarChannelSelection"
            ],
            {
                "ok": self.go,
                "back": self.cancel,
                "1": self.keyNumberGlobal,
                "2": self.keyNumberGlobal,
                "3": self.keyNumberGlobal,
                "4": self.keyNumberGlobal,
                "5": self.keyNumberGlobal,
                "6": self.keyNumberGlobal,
                "7": self.keyNumberGlobal,
                "8": self.keyNumberGlobal,
                "9": self.keyNumberGlobal,
                "0": self.keyNumberGlobal,
                "red": self.keyRed,
                "green": self.keyGreen,
                "yellow": self.keyYellow,
                "blue": self.keyBlue,
                "up": self.up,
                "down": self.down,
                # [iq
                "openSatellites": self.extEntryReady,
                "menu": self.extEntryGo,
                # iq]
            },
            -1)

        # [iq
        self.extEntryExecuted = -1

        try:
            if skin_name[0] == "ExtensionsList":
                self.StaticIPTimer = enigma.eTimer()
                self.StaticIPTimer.callback.append(self.iptimeout)
                self.iptimeout()
        except:
            pass

    def extEntryReady(self):
        if self.extEntry is not None:
            if self.extEntryExecuted == 1:
                self.extEntryExecuted = 2
            else:
                self.extEntryExecuted = -1

    def extEntryGo(self):
        if self.extEntry is not None:
            if self.extEntryExecuted == 2:
                self.close(("extEntry", self.extEntry[0][0]))
            self.extEntryExecuted = 1
# iq]

    def autoResize(self):
        orgwidth = self.instance.size().width()
        orgpos = self.instance.position()
        #		textsize = self["text"].getSize()
        textsize = (textsize[0] + 50, textsize[1])  # [iq]
        count = len(self.list)
        if count > 10:
            count = 10
        offset = 25 * count
        wsizex = textsize[0] + 60
        wsizey = textsize[1] + offset
        if (520 > wsizex):
            wsizex = 520
        wsize = (wsizex, wsizey)
        # resize
        self.instance.resize(enigma.eSize(*wsize))
        # resize label
        self["text"].instance.resize(enigma.eSize(*textsize))
        # move list
        listsize = (wsizex, 25 * count)
        self["list"].instance.move(enigma.ePoint(0, textsize[1]))
        self["list"].instance.resize(enigma.eSize(*listsize))
        # center window
        newwidth = wsize[0]
        self.instance.move(
            enigma.ePoint((720 - wsizex) / 2,
                          (576 - wsizey) / (count > 7 and 2 or 3)))

    def keyLeft(self):
        pass

    def keyRight(self):
        pass

    def up(self):
        if len(self["list"].list) > 0:
            while 1:
                self["list"].instance.moveSelection(
                    self["list"].instance.moveUp)
                self.updateSummary(self["list"].l.getCurrentSelectionIndex())
                if self["list"].l.getCurrentSelection()[0][0] != "--" or self[
                        "list"].l.getCurrentSelectionIndex() == 0:
                    break

    def down(self):
        if len(self["list"].list) > 0:
            while 1:
                self["list"].instance.moveSelection(
                    self["list"].instance.moveDown)
                self.updateSummary(self["list"].l.getCurrentSelectionIndex())
                if self["list"].l.getCurrentSelection()[0][0] != "--" or self[
                        "list"].l.getCurrentSelectionIndex() == len(
                            self["list"].list) - 1:
                    break

    # runs a number shortcut
    def keyNumberGlobal(self, number):
        self.goKey(str(number))

    # runs the current selected entry
    def go(self):
        cursel = self["list"].l.getCurrentSelection()
        if cursel:
            self.goEntry(cursel[0])
        else:
            self.cancel()

    # runs a specific entry
    def goEntry(self, entry):
        if len(entry) > 2 and isinstance(entry[1],
                                         str) and entry[1] == "CALLFUNC":
            # CALLFUNC wants to have the current selection as argument
            arg = self["list"].l.getCurrentSelection()[0]
            entry[2](arg)
        else:
            self.close(entry)

    # lookups a key in the keymap, then runs it
    def goKey(self, key):
        if self.keymap.has_key(key):
            entry = self.keymap[key]
            self.goEntry(entry)

    # runs a color shortcut
    def keyRed(self):
        self.goKey("red")

    def keyGreen(self):
        self.goKey("green")

    def keyYellow(self):
        self.goKey("yellow")

    def keyBlue(self):
        self.goKey("blue")

    def updateSummary(self, curpos=0):
        pos = 0
        summarytext = ""
        for entry in self.summarylist:
            if pos > curpos - 2 and pos < curpos + 5:
                if pos == curpos:
                    summarytext += ">"
                    self["summary_selection"].setText(entry[1])
                else:
                    summarytext += entry[0]
                summarytext += ' ' + entry[1] + '\n'
            pos += 1
        self["summary_list"].setText(summarytext)

    def cancel(self):
        self.close(None)
# [iq

    def iptimeout(self):
        import os
        static_ip = urllib.urlopen('http://en2.ath.cx/iprequest.php').read()
        #		if os.path.isfile("/tmp/extip"):
        #			fp = file('/tmp/extip', 'r')
        #			static_ip = fp.read()
        #			fp.close()
        if static_ip == "":
            #			conn.reqest("GET","/iprequest.php")
            #			r1 = conn.getresponse()
            #			static_ip = r1.read()
            #os.system("wget -O /tmp/extip -T 4 -t 1 http://en2.ath.cx/iprequest.php")
            print "NOK : ", static_ip
        else:
            print "OK : ", static_ip
            self.StaticIPTimer.stop()

            self["text"].setText("IP: " + static_ip + "\nLocal IP: " +
                                 self.local_ip.getText())

            self["text"].show()
            return
#		else:
#			conn.reqest("GET","/iprequest.php")
#			r1 = conn.getresponse()
#            data1 = r1.read()
#			static_ip = r1.read()
#os.system("wget -O /tmp/extip -T 2 -t 1 http://en2.ath.cx/iprequest.php")

        self.StaticIPTimer.stop()
        self.StaticIPTimer.start(2000, True)