Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

dream-alpha / enigma2-plugin-extensions-vpnmanager   deb

Repository URL to install this package:

Version: 1.2.1 

/ usr / lib / enigma2 / python / Plugins / Extensions / VpnManager / plugin.py

# -*- coding: utf-8 -*-
from Components.ActionMap import ActionMap, NumberActionMap
from Plugins.Plugin import PluginDescriptor
from Components.Label import Label
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.ConfigList import ConfigListScreen
from Components.config import config, ConfigInteger, ConfigIP, ConfigSelection, getConfigListEntry, ConfigText, \
    ConfigDirectory, \
    ConfigYesNo, configfile, ConfigSelection, ConfigSubsection, ConfigPIN, NoSave, ConfigNothing, ConfigPassword
from Components.FileList import FileList
from enigma import gFont, addFont, eNetworkManager, eNetworkService, eTimer, getDesktop, eListboxPythonMultiContent, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, \
    RT_HALIGN_CENTER, RT_VALIGN_CENTER, \
    RT_VALIGN_TOP, RT_WRAP, eListbox, gPixmapPtr, ePicLoad, loadPNG
from Components.MenuList import MenuList
from Components.Pixmap import Pixmap
from Tools.LoadPixmap import LoadPixmap
from Components.MultiContent import MultiContentEntryText
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Components.Network import NetworkInterface
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_LANGUAGE, SCOPE_PLUGINS
import threading
from twisted.internet import threads


import shutil
import time
import subprocess
import os
import re
import glob
import ast
import ssl

from .myScrollBar import my_scroll_bar
from .infoHelper import infoHelper
from .ipinfo import get_ip_info
from .readFreeVpnBook import VpnBook
from .readFreeVpnMe import VpnMe

import gettext
from os import environ

lang = language.getLanguage()
environ["LANGUAGE"] = lang[:2]
gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANGUAGE))
gettext.textdomain("enigma2")
gettext.bindtextdomain("VpnManager", "%s%s" % (resolveFilename(SCOPE_PLUGINS), "Extensions/VpnManager/locale/"))


def _(txt):
    t = gettext.dgettext("VpnManager", txt)
    if t == txt:
        t = gettext.gettext(txt)
    return t


try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context


PLUGINVERSION = "1.2.1"
INFO = "Package: enigma2-plugin-extensions-vpnmanager\nVersion: " + PLUGINVERSION + "\nDescription: Manage your VPN connections\nMaintainer: murxer <support@boxpirates.to>"


damnPanels = ["GoldenPanel", "SatVenusPanel", "GoldenFeed", "PersianDreambox", "DreamOSatDownloader"]
for damnPanel in damnPanels:
    if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/" + damnPanel + "/plugin.pyo"):
        os.remove("/usr/lib/enigma2/python/Plugins/Extensions/" + damnPanel + "/plugin.pyo")
    if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/" + damnPanel + "/plugin.py"):
        os.remove("/usr/lib/enigma2/python/Plugins/Extensions/" + damnPanel + "/plugin.py")

RESOLVCONF = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/resolv/update-resolv-conf"
SPINNERDIR = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/spinner/"
ISVPN = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/is_vpn.png"
NOVPN = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/no_vpn.png"

VPNDNS = "/etc/openvpn/vpn_dns"
VPNAUTHFILES = ["/media/usb/openvpnauth", "/media/hdd/openvpnauth"]

config.vpnmanager = ConfigSubsection()
config.vpnmanager.directory = ConfigText(default="/media/hdd/vpn/", fixed_size=False)
config.vpnmanager.directory_wireguard = ConfigText(default="/media/hdd/WireGuard/", fixed_size=False)
config.vpnmanager.active = ConfigText(default=" ", fixed_size=False)
config.vpnmanager.one_folder = ConfigYesNo(default=False)
config.vpnmanager.autostart = ConfigYesNo(default=False)
config.vpnmanager.resolv = ConfigYesNo(default=True)
config.vpnmanager.dns = ConfigIP(default=[0, 0, 0, 0], auto_jump=True)
config.vpnmanager.username = ConfigText(default="Username", fixed_size=False)
config.vpnmanager.password = ConfigText(default="Password", fixed_size=False)

config.vpnmanager.type = ConfigSelection(choices=[("vpn", "OpenVPN"), ("wireguard", "WireGuard")], default="vpn")

config.vpnmanager.vpnresolv = ConfigYesNo(default=False)
config.vpnmanager.vpndns1 = ConfigIP(default=[0, 0, 0, 0], auto_jump=True)
config.vpnmanager.vpndns2 = ConfigIP(default=[0, 0, 0, 0], auto_jump=True)

config.vpnmanager.free_mode = ConfigYesNo(default=False)
config.vpnmanager.free_mode_type = ConfigSelection(choices=[("me", "VpnMe"), ("book", "VpnBook")], default="book")

# Desktop
DESKTOPSIZE = getDesktop(0).size()
if DESKTOPSIZE.width() >= 1920:
    desksize = "_1920"
    VPN_PNG = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/openvpn_logo_1920.png"
    WIREGUARD_PNG = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/wireguard_logo_1920.png"
else:
    desksize = "_1280"
    VPN_PNG = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/openvpn_logo_1280.png"
    WIREGUARD_PNG = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/wireguard_logo_1280.png"


class VpnManagerScreen(Screen, my_scroll_bar, infoHelper):
    def __init__(self, session):
        try:
            addFont("/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/font/OpenSans-Regular.ttf", "Vpn", 100, False)
        except Exception as error:
            addFont("/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/font/OpenSans-Regular.ttf", "Vpn", 100, False,
                    0)
        if DESKTOPSIZE.width() > 1920:
            self.skin = """<screen name="VpnManagerScreen" backgroundColor="#00ffffff" position="center,center" size="2560,1440" title="VpnManagerScreen" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="3,3" size="2555,1435" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="103,3" size="1357,396" alphatest="blend" zPosition="2" />
                        <eLabel name="line1" position="37,399" size="1488,1013" zPosition="1" backgroundColor="#00ffffff" />
                        <eLabel name="line2" position="1496,401" size="27,1008" zPosition="2" backgroundColor="#002a2a2a" />
                        <widget name="vpnlist" position="40,401" size="1453,1008" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" />
                        <widget name="myScrollBar" position="1496,401" size="27,1008" transparent="0" backgroundColor="#002a2a2a" zPosition="3" itemHeight="1008"  enableWrapAround="1" />
                        <eLabel name="line3" position="1584,51" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line5" position="1584,464" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="1584,1363" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="1584,1409" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="1584,51" size="3,1359" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="2517,51" size="3,1359" zPosition="2" backgroundColor="#00ffffff" />
                        <widget name="hop1_png" position="1587,67" size="171,171" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/no_vpn.png" alphatest="blend" zPosition="2" />
                        <widget name="hop1" position="1771,53" size="744,400" foregroundColor="#00ffffff"  backgroundColor="#002a2a2a" font="Vpn; 36" valign="top" halign="left"  zPosition="2" transparent="0" />
                        <widget name="myInfoLabel" position="1587,467" size="925,896" transparent="0" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" itemHeight="56"  enableWrapAround="1" />
                        <eLabel name="line10" position="1587,1363" size="267,3" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel text=""" + '"' + _("Stop VPN") + '"' + """ position="1587,1365" size="267,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line10" position="1587,1409" size="267,3" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line10" position="1853,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1856,1363" size="267,3" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel text=""" + '"' + _("Start VPN") + '"' + """ position="1856,1365" size="267,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line10" position="1856,1409" size="267,3" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel name="line11" position="2123,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text=""" + '"' + _("Menu") + '"' + """ position="2125,1365" size="133,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line12" position="2259,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="2261,1365" size="113,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line13" position="2375,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="2377,1365" size="140,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        </screen>"""
        elif DESKTOPSIZE.width() == 1920:
            self.skin = """
                        <screen name="VpnManagerScreen" backgroundColor="#00ffffff" position="center,center" size="1920,1080" title="VpnManagerScreen" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="2,2" size="1916,1076" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="77,2" size="1018,297" alphatest="blend" zPosition="2" />          
                        <eLabel name="line1" position="28,299" size="1116,760" zPosition="1" backgroundColor="#00ffffff" />
                        <eLabel name="line2" position="1122,301" size="20,756" zPosition="2" backgroundColor="#002a2a2a" />
                        <widget name="vpnlist" position="30,301" size="1090,756" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" />
                        <widget name="myScrollBar" position="1122,301" size="20,756" transparent="0" backgroundColor="#002a2a2a" zPosition="3" itemHeight="756"  enableWrapAround="1" />
                        <eLabel name="line3" position="1188,38" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line5" position="1188,348" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="1188,1022" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="1188,1057" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="1188,38" size="2,1019" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="1888,38" size="2,1019" zPosition="2" backgroundColor="#00ffffff" />
                        <widget name="hop1_png" position="1190,50" size="128,128" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/no_vpn.png" alphatest="blend" zPosition="2" />
                        <widget name="hop1" position="1328,40" size="558,300" foregroundColor="#00ffffff"  backgroundColor="#002a2a2a" font="Vpn; 27" valign="top" halign="left"  zPosition="2" transparent="0" />
                        <widget name="myInfoLabel" position="1190,350" size="694,672" transparent="0" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" itemHeight="42"  enableWrapAround="1" />
                        <eLabel name="line10" position="1190,1022" size="200,2" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel text=""" + '"' + _("Stop VPN") + '"' + """ position="1190,1024" size="200,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        <eLabel name="line10" position="1190,1057" size="200,2" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line10" position="1390,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1392,1022" size="200,2" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel text=""" + '"' + _("Start VPN") + '"' + """ position="1392,1024" size="200,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" /> 
                        <eLabel name="line10" position="1392,1057" size="200,2" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel name="line11" position="1592,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text=""" + '"' + _("Menu") + '"' + """ position="1594,1024" size="100,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" /> 
                        <eLabel name="line12" position="1694,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="1696,1024" size="85,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        <eLabel name="line13" position="1781,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="1783,1024" size="105,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        </screen>
                        """
        else:
            self.skin = """
                        <screen name="VpnManagerScreen" backgroundColor="#00ffffff" position="center,center" size="1280,720" title="VpnManagerScreen" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="1,1" size="1277,717" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="51,1" size="678,198" alphatest="blend" zPosition="2" />
                        <eLabel name="line1" position="18,199" size="744,506" zPosition="1" backgroundColor="#00ffffff" />
                        <eLabel name="line2" position="748,200" size="13,504" zPosition="2" backgroundColor="#002a2a2a" />
                        <widget name="vpnlist" position="20,200" size="726,504" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" />
                        <widget name="myScrollBar" position="748,200" size="13,504" transparent="0" backgroundColor="#002a2a2a" zPosition="3" itemHeight="504"  enableWrapAround="1" />
                        <eLabel name="line3" position="792,25" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line5" position="792,232" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="792,681" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="792,704" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="792,25" size="1,679" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="1258,25" size="1,679" zPosition="2" backgroundColor="#00ffffff" />
                        <widget name="hop1_png" position="793,33" size="85,85" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/no_vpn.png" alphatest="blend" zPosition="2" />
                        <widget name="hop1" position="885,26" size="372,200" foregroundColor="#00ffffff"  backgroundColor="#002a2a2a" font="Vpn; 18" valign="top" halign="left"  zPosition="2" transparent="0" />
                        <widget name="myInfoLabel" position="793,233" size="462,448" transparent="0" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" itemHeight="28"  enableWrapAround="1" />
                        <eLabel name="line10" position="793,681" size="133,1" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel text=""" + '"' + _("Stop VPN") + '"' + """ position="793,682" size="133,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line10" position="793,704" size="133,1" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line10" position="926,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="928,681" size="133,1" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel text=""" + '"' + _("Start VPN") + '"' + """ position="928,682" size="133,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line10" position="928,704" size="133,1" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel name="line11" position="1061,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text=""" + '"' + _("Menu") + '"' + """ position="1062,682" size="66,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line12" position="1129,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="1130,682" size="56,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line13" position="1187,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="1188,682" size="70,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        </screen>
                        """
        Screen.__init__(self, session)

        self["actions"] = ActionMap(["OpenVPN_Actions"], {
            "ok": self.keyOK,
            "up": self.keyUp,
            "down": self.keyDown,
            "right": self.keyRight,
            "left": self.keyLeft,
            "red": self.keyRed,
            "green": self.keyGreen,
            "menu": self.keyMenu,
            "cancel": self.keyCancel,
            "info": self.keyInfo,
            "0": self.keyExit
        }, -1)

        self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent)
        self.chooseMenuList.l.setFont(0, gFont('Vpn', skinValueCalculate(29)))
        self.chooseMenuList.l.setItemHeight(skinValueCalculate(42))

        my_scroll_bar.__init__(self, skinValueCalculate(756), skinValueCalculate(42))
        infoHelper.__init__(self)

        # Pixmap
        self["logo"] = Pixmap()
        self["hop1_png"] = Pixmap()
        # Label
        self["hop1"] = Label("")
        self['vpnlist'] = self.chooseMenuList

        self.is_vpn = False

        # OpenVpn Status Check Timer
        self.StatusTimerCheckOpenVpn = eTimer()
        self.StatusCheckOpenVpnTimer = 0
        self.StatusTimerCheckOpenVpn_conn = self.StatusTimerCheckOpenVpn.timeout.connect(self.checkOpenVpn)

        # Wireguard Status Check Timer
        self.StatusTimerCheckWireguard = eTimer()
        self.StatusCheckWireguardTimer = 0
        self.StatusTimerCheckWireguard_conn = self.StatusTimerCheckWireguard.timeout.connect(self.checkWireguard)

        if not isWireGuardInstalled():
            config.vpnmanager.type.value = "vpn"
            config.vpnmanager.type.save()
            configfile.save()

        # Free mode
        self.freeVpnBook = VpnBook()
        self.freeVpnMe = VpnMe()

        # Spinner Timer
        self.StatusTimerSpinner = eTimer()
        self.StatusSpinner = False
        self.StatusSpinnerTimer = 1
        self.StatusTimerSpinner_conn = self.StatusTimerSpinner.timeout.connect(self.loadSpinner)

        self.listVpn = []
        self.onLayoutFinish.append(self.saveDefaultResolv)
        self.onLayoutFinish.append(self.setTypeLogo)
        self.onLayoutFinish.append(self.setList)

    def setList(self, reload=None):
        self.listVpn = []
        self.is_vpn = statusTun() if config.vpnmanager.type.value == "vpn" else statusWireguard()
        config_destination = config.vpnmanager.directory.value if config.vpnmanager.type.value == "vpn" else config.vpnmanager.directory_wireguard.value
        if not config.vpnmanager.free_mode.value or config.vpnmanager.type.value == "wireguard":
            if os.path.exists(config_destination):
                if not config.vpnmanager.one_folder.value:
                    for directory in os.listdir(config_destination):
                        if os.path.isdir(config_destination + "/" + directory):
                            if config.vpnmanager.active.value == directory:
                                is_connect = True
                                png = 1 if self.is_vpn else 2
                            else:
                                is_connect = False
                                png = 3
                            self.listVpn.append(
                                (directory, config_destination + "/" + directory, is_connect, png))
                else:
                    for conf in os.listdir(config_destination):
                        if os.path.isfile(config_destination + "/" + conf):
                            if conf.endswith("conf") or conf.endswith("ovpn"):
                                if config.vpnmanager.active.value == conf.replace(".conf", "").replace(".ovpn", ""):
                                    is_connect = True
                                    png = 1 if self.is_vpn else 2
                                else:
                                    is_connect = False
                                    png = 3
                                self.listVpn.append(
                                    (conf.replace(".conf", "").replace(".ovpn", ""),
                                     config_destination + "/" + conf, is_connect, png))
        else:
            if config.vpnmanager.free_mode_type.value == "book":
                self.listVpn = self.freeVpnBook.get_config_data(self.is_vpn)
            else:
                self.listVpn = self.freeVpnMe.get_config_data(self.is_vpn)

        if self.listVpn:
            self.listVpn.sort()
            x = 0
            s = 0
            for title, directory_destination, is_connect, png in self.listVpn:
                if is_connect:
                    s = x
                    break
                x = x + 1
            self.chooseMenuList.setList(list(map(enterListEntry, self.listVpn, )))
            self.chooseMenuList.moveToIndex(s)
            self.loadScrollbar(index=s, max_items=len(self.listVpn))
        self.readIP()
        self.load_info()

    def keyOK(self):
        if not self.StatusSpinner and self.listVpn:
            city = self["vpnlist"].getCurrent()[0][0]
            conf_destination = self["vpnlist"].getCurrent()[0][1]

            config.vpnmanager.active.value = city
            config.vpnmanager.active.save()
            configfile.save()

            if config.vpnmanager.type.value == "wireguard":
                # stop wireguard
                if runningWireGuard():
                    stop_wireguard()
                # del old Config
                if os.path.exists("/etc/wireguard"):
                    os.system("rm -R /etc/wireguard/*")
                new_config = "/etc/wireguard/Wg0.conf"

                conf_file = ""
                if not config.vpnmanager.one_folder.value:
                    if os.path.isdir(conf_destination):
                        data = os.listdir(conf_destination)
                        for file in data:
                            if file.endswith("conf"):
                                conf_file = conf_destination + "/" + file
                else:
                    conf_file = conf_destination
                if conf_file:
                    os.system("cp %s %s" % (conf_file, new_config))
                    os.system("chmod 600 /etc/wireguard/Wg0.conf")

                if not runningWireGuard():
                    self["hop1"].setText(_("Connecting..."))
                    start_wireguard()
                    set_auto_start()
                    self.StatusSpinner = True
                    self.loadSpinner()
                    self.StatusTimerCheckWireguard.start(3000, True)
                else:
                    self.session.open(MessageBox, "WireGuard Stop Error: WireGuard running!", MessageBox.TYPE_ERROR, timeout=10)

            else:
                version = checkVpnVersion()
                if version is not None:
                    self.session.open(MessageBox, version, MessageBox.TYPE_INFO, timeout=10)
                # stop openvpn
                if runningOpenVPN():
                    stop_vpn()
                if statusTunOff():
                    self.setDefaultDns()
                # del old Config
                if os.path.exists("/etc/openvpn"):
                    os.system("rm -R /etc/openvpn/*")
                # write new Config
                new_config = "/etc/openvpn/%s.conf" % city.replace(" ", "_").replace("/", "_")
                new_conf_write = open(new_config, "a")

                conf_file = ""
                if not config.vpnmanager.one_folder.value:
                    if os.path.isdir(conf_destination):
                        data = os.listdir(conf_destination)
                        for file in data:
                            if file.endswith("conf") or file.endswith("ovpn"):
                                conf_file = conf_destination + "/" + file
                            else:
                                shutil.copy2(conf_destination + "/" + file, "/etc/openvpn/" + file)
                                os.system("chmod 600 /etc/openvpn/%s" % file)
                else:
                    conf_file = conf_destination
                    data = os.listdir(config.vpnmanager.directory.value)
                    for file in data:
                        file_destination = config.vpnmanager.directory.value + "/" + file
                        if os.path.isfile(file_destination):
                            if not file.endswith("conf"):
                                if not file.endswith("ovpn"):
                                    shutil.copy2(file_destination, "/etc/openvpn/" + file)
                                    os.system("chmod 600 /etc/openvpn/%s" % file)

                if os.path.isfile(conf_file):
                    with open(conf_file, "r") as data:
                        resolv = False
                        security = False
                        for line in data:
                            if re.search("auth-user-pass", line):
                                new_line = "auth-user-pass /etc/openvpn/pass.file\n" \
                                           "log /etc/openvpn/openvpn.log\n" \
                                           "status /etc/openvpn/openvpn.stat 10\n"
                                new_conf_write.write(new_line)
                            elif re.search("up\\s+/etc/openvpn/update-resolv-conf", line):
                                resolv = True
                                if config.vpnmanager.resolv.value:
                                    new_line = "setenv PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n" \
                                               "up /etc/openvpn/update-resolv-conf\n"
                                    new_conf_write.write(new_line)
                            elif re.search("down\\s+/etc/openvpn/update-resolv-conf", line):
                                if config.vpnmanager.resolv.value:
                                    new_line = "down /etc/openvpn/update-resolv-conf\ndown-pre\n"
                                    new_conf_write.write(new_line)
                            elif re.search("route-delay", line) or re.search("route-method", line):
                                pass
                            elif re.search("script-security", line):
                                security = True
                                new_conf_write.write(line)
                            elif line[:3] == "dev":
                                new_line = "dev tun\n"
                                new_conf_write.write(new_line)
                            else:
                                new_conf_write.write(line)
                        if not security:
                            new_line = "\nscript-security 2\n"
                            new_conf_write.write(new_line)

                        if not resolv and config.vpnmanager.resolv.value:
                            new_line = "setenv PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n" \
                                       "up /etc/openvpn/update-resolv-conf\n"
                            new_conf_write.write(new_line)

                            new_line = "down /etc/openvpn/update-resolv-conf\ndown-pre\n"
                            new_conf_write.write(new_line)

                # set pass.conf
                if not os.path.isfile("/etc/openvpn/pass.file"):
                    pass_file = "/etc/openvpn/pass.file"
                    pass_file_write = open(pass_file, "w")
                    pass_file_write.write("%s\n%s" % (config.vpnmanager.username.value, config.vpnmanager.password.value))
                    pass_file_write.close()

                # close
                new_conf_write.close()

                if os.path.exists("/etc/openvpn"):
                    if config.vpnmanager.resolv.value:
                        if config.vpnmanager.vpnresolv.value:
                            dns1 = '%d.%d.%d.%d' % tuple(config.vpnmanager.vpndns1.value)
                            dns2 = '%d.%d.%d.%d' % tuple(config.vpnmanager.vpndns2.value)
                            vpn_dns = open(VPNDNS, "w")
                            vpn_dns.write("nameserver %s\n" % dns1)
                            if not dns2 == "0.0.0.0":
                                vpn_dns.write("nameserver %s\n" % dns2)
                            vpn_dns.close()
                        try:
                            shutil.copyfile(RESOLVCONF, "/etc/openvpn/update-resolv-conf")
                        except shutil.Error as e:
                            print(e)
                        os.system("chmod 755 /etc/openvpn/update-resolv-conf")
                    os.system("chmod 600 /etc/openvpn/*.conf")
                    os.system("chmod 600 /etc/openvpn/pass.file")

                if not runningOpenVPN():
                    self["hop1"].setText(_("Connecting..."))
                    start_vpn()
                    set_auto_start()
                    self.StatusSpinner = True
                    self.loadSpinner()
                    self.checkOpenVpn()
                else:
                    self.session.open(MessageBox, "Open Vpn Stop Error: OpenVpn running!", MessageBox.TYPE_ERROR, timeout=10)

    def keyUp(self):
        if self.listVpn:
            if not self.StatusSpinner:
                self['vpnlist'].up()
                index = self['vpnlist'].getSelectionIndex()
                self.loadScrollbar(index=index, max_items=len(self.listVpn))

    def keyDown(self):
        if self.listVpn:
            if not self.StatusSpinner:
                self['vpnlist'].down()
                index = self['vpnlist'].getSelectionIndex()
                self.loadScrollbar(index=index, max_items=len(self.listVpn))

    def keyRight(self):
        if self.listVpn:
            if not self.StatusSpinner:
                self['vpnlist'].pageDown()
                index = self['vpnlist'].getSelectionIndex()
                self.loadScrollbar(index=index, max_items=len(self.listVpn))

    def keyLeft(self):
        if self.listVpn:
            if not self.StatusSpinner:
                self['vpnlist'].pageUp()
                index = self['vpnlist'].getSelectionIndex()
                self.loadScrollbar(index=index, max_items=len(self.listVpn))

    def keyMenu(self):
        if not self.StatusSpinner:
            self.session.openWithCallback(self.Exit, VpnManagerConfigScreen)

    def keyGreen(self):
        # start openvpn
        if not self.StatusSpinner:
            if config.vpnmanager.type.value == "vpn":
                if runningOpenVPN():
                    stop_vpn()
                    if statusTunOff():
                        self.setDefaultDns()

                if statusTunOff():
                    rm_file = ["/etc/openvpn/openvpn.log", "/etc/openvpn/openvpn.stat"]
                    for log in rm_file:
                        if os.path.isfile(log):
                            os.system("rm %s" % log)
                    start_vpn()
                self["hop1"].setText(_("Connecting..."))
                self.StatusSpinner = True
                self.loadSpinner()
                self.checkOpenVpn()
            else:
                if runningWireGuard():
                    stop_wireguard()
                if statusWg0Off():
                    start_wireguard()
                self["hop1"].setText(_("Connecting..."))
                self.StatusSpinner = True
                self.loadSpinner()
                self.StatusTimerCheckWireguard.start(3000, True)

    def keyRed(self):
        # stop openvpn
        if not self.StatusSpinner:
            if config.vpnmanager.type.value == "vpn":
                if runningOpenVPN():
                    stop_vpn()
                    rm_file = ["/etc/openvpn/openvpn.log", "/etc/openvpn/openvpn.stat"]
                    for log in rm_file:
                        if os.path.isfile(log):
                            os.system("rm %s" % log)
                if statusTunOff():
                    self.setDefaultDns()
                    text = "OpenVpn Stop"
                    self.session.openWithCallback(self.setList, MessageBox, text, MessageBox.TYPE_INFO, timeout=10)
                else:
                    text = "OpenVpn Error: OpenVpn is Running"
                    self.session.openWithCallback(self.setList, MessageBox, text, MessageBox.TYPE_ERROR, timeout=10)
            else:
                if runningWireGuard():
                    stop_wireguard()
                if statusWg0Off():
                    text = "WireGuard Stop"
                    self.session.openWithCallback(self.setList, MessageBox, text, MessageBox.TYPE_INFO, timeout=10)
                else:
                    text = "WireGuard Error: WireGuard is Running"
                    self.session.openWithCallback(self.setList, MessageBox, text, MessageBox.TYPE_ERROR, timeout=10)

    def saveDefaultResolv(self):
        if not statusTun():
            default_dns = '%d.%d.%d.%d' % tuple(config.vpnmanager.dns.value)
            if default_dns == "0.0.0.0":
                nm = eNetworkManager.getInstance()
                gw = ""
                for service in nm.getServices():
                    if service.connected():
                        net = NetworkInterface(service)
                        ip4 = net.getIpv4()
                        ip6 = net.getIpv6()
                        if ip4.method != eNetworkService.METHOD_OFF:
                            gw = ip4.gateway
                        if ip6.method != eNetworkService.METHOD_OFF:
                            gw = ip6.gateway
                        if len(service.nameservers()) > 0:
                            dns1 = service.nameservers()[0]
                        else:
                            dns1 = gw
                        if ":" not in dns1:
                            config.vpnmanager.dns.value = [ast.literal_eval(x) for x in dns1.split('.')]

            config.vpnmanager.dns.save()
            configfile.save()

    def setDefaultDns(self):
        default_dns = '%d.%d.%d.%d' % tuple(config.vpnmanager.dns.value)
        if not default_dns == "0.0.0.0":
            files = glob.glob('/var/lib/connman/*ethernet*cable*')
            for file in files:
                conn = os.path.basename(file)
                p = subprocess.Popen(['connmanctl', 'config', conn, '--nameservers', default_dns])
                p.wait()

            files = glob.glob('/var/lib/connman/wifi*')
            for file in files:
                conn = os.path.basename(file)
                p = subprocess.Popen(['connmanctl', 'config', conn, '--nameservers', default_dns])
                p.wait()
        self.saveDefaultResolv()

    def checkWireguard(self):
        if self.StatusCheckWireguardTimer is not 8:
            if statusWireguard():
                self.StatusCheckWireguardTimer = 0
                self.StatusSpinner = False
                time.sleep(2)
                self.setList()
            else:
                self.StatusCheckWireguardTimer += 1
                self.StatusTimerCheckWireguard.start(3000, True)
        else:
            self.StatusCheckWireguardTimer = 0
            self.StatusSpinner = False
            self.setList()

    def checkOpenVpn(self):
        if os.path.isfile("/etc/openvpn/openvpn.log"):
            error = None
            read_log = open("/etc/openvpn/openvpn.log", "r")
            for line in read_log:
                if re.search("AUTH: Received control message: AUTH_FAILED", line):
                    error = "Login Error: AUTH_FAILED"
                    stop_vpn()
                    rm_file = ["/etc/openvpn/openvpn.log", "/etc/openvpn/openvpn.stat"]
                    for log in rm_file:
                        if os.path.isfile(log):
                            os.system("rm %s" % log)
                    break
                elif re.search("VERIFY ERROR", line):
                    error = "Login Error: VERIFY ERROR"
                    stop_vpn()
                    rm_file = ["/etc/openvpn/openvpn.log", "/etc/openvpn/openvpn.stat"]
                    for log in rm_file:
                        if os.path.isfile(log):
                            os.system("rm %s" % log)
                    break
            if error:
                self.StatusCheckOpenVpnTimer = 0
                self.StatusSpinner = False
                self.session.open(MessageBox, error, MessageBox.TYPE_ERROR, timeout=10)
                self.setList()
                read_log.close()
                return

            if self.StatusCheckOpenVpnTimer is not 8:
                if statusTun():
                    self.StatusCheckOpenVpnTimer = 0
                    self.StatusSpinner = False
                    time.sleep(2)
                    self.setList()
                else:
                    self.StatusCheckOpenVpnTimer += 1
                    self.StatusTimerCheckOpenVpn.start(3000, True)
            else:
                self.StatusCheckOpenVpnTimer = 0
                self.StatusSpinner = False
                if statusTunOn():
                    time.sleep(2)
                self.setList()
            read_log.close()
        else:
            if statusTunOn():
                time.sleep(2)
            self.StatusSpinner = False
            self.setList()

    def readIP(self):
        self["hop1"].setText(_("Load IP data ..."))
        status = statusTun() if config.vpnmanager.type.value == "vpn" else statusWireguard()
        threads.deferToThread(get_ip_info, tun=status, callback=self.callbackReadIP)

    def callbackReadIP(self, info):
        status = statusTun() if config.vpnmanager.type.value == "vpn" else statusWireguard()
        png = ISVPN if status else NOVPN
        self["hop1"].setText(info)
        self.showVpnConnect(png)

    def loadSpinner(self):
        if self.StatusSpinner:
            png = "%s%s.png" % (SPINNERDIR, str(self.StatusSpinnerTimer))
            self.showVpnConnect(png)

    def showVpnConnect(self, png):
        self["hop1_png"].instance.setPixmapFromFile(png)
        if self.StatusSpinner:
            if self.StatusSpinnerTimer is not 5:
                self.StatusSpinnerTimer += 1
            else:
                self.StatusSpinnerTimer = 1
            self.StatusTimerSpinner.start(200, True)

    def setTypeLogo(self):
        png = VPN_PNG if config.vpnmanager.type.value == "vpn" else WIREGUARD_PNG
        self["logo"].instance.setPixmapFromFile(png)

    def keyExit(self):
        self.close(self.session, True)

    def Exit(self):
        self.close(self.session, False)

    def keyCancel(self):
        if not self.StatusSpinner:
            self.close(self.session, True)

    def keyInfo(self):
        self.session.open(MessageBox, windowTitle="VPN-Manager Info", text=INFO, type=MessageBox.TYPE_INFO)


class VpnManagerConfigScreen(Screen, ConfigListScreen):
    def __init__(self, session):
        if DESKTOPSIZE.width() > 1920:
            self.skin = """
                        <screen name="VpnManger" backgroundColor="#00ffffff" position="center,center" size="2560,1440" title="VpnManager" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="3,3" size="2555,1435" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="103,3" size="1357,396" alphatest="blend" zPosition="2" />
                        <widget name="PwLogo" position="1783,733" size="533,69" alphatest="blend" zPosition="4" />
                        <eLabel name="line1" position="37,399" size="1488,1013" zPosition="1" backgroundColor="#00ffffff" />
                        <eLabel name="line2" position="1496,401" size="27,1008" zPosition="2" backgroundColor="#002a2a2a" />
                        <widget name="config" position="40,401" size="1453,1008" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" />
                        <eLabel name="line3" position="1584,51" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="1584,1363" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="1584,1409" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="1584,51" size="3,1359" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1587,1363" size="267,3" zPosition="4" backgroundColor="#00ff0000" />
                        <widget name="myInfoLabel" position="1587,53" size="925,1163" transparent="0" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" font="Vpn; 37" valign="center" halign="center"/>
                        <eLabel text=""" + '"' + _("Set default DNS") + '"' + """ position="1587,1365" size="267,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line10" position="1587,1409" size="267,3" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line9" position="2517,51" size="3,1359" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1853,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line11" position="2123,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line12" position="2259,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="2261,1365" size="113,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line13" position="2375,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="2377,1365" size="140,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        </screen>"""
        elif DESKTOPSIZE.width() == 1920:
            self.skin = """
                        <screen name="VpnManger" backgroundColor="#00ffffff" position="center,center" size="1920,1080" title="VpnManager" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="2,2" size="1916,1076" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="77,2" size="1018,297" alphatest="blend" zPosition="2" />  
                        <widget name="PwLogo" position="1337,550" size="400,52" alphatest="blend" zPosition="4" />         
                        <eLabel name="line1" position="28,299" size="1116,760" zPosition="1" backgroundColor="#00ffffff" />
                        <eLabel name="line2" position="1122,301" size="20,756" zPosition="2" backgroundColor="#002a2a2a" />
                        <widget name="config" position="30,301" size="1090,756" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" />
                        <eLabel name="line3" position="1188,38" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="1188,1022" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="1188,1057" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="1188,38" size="2,1019" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1190,1022" size="200,2" zPosition="4" backgroundColor="#00ff0000" />
                        <widget name="myInfoLabel" position="1190,40" size="694,872" transparent="0" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" font="Vpn; 28" valign="center" halign="center"/>
                        <eLabel text=""" + '"' + _("Set default DNS") + '"' + """ position="1190,1024" size="200,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        <eLabel name="line10" position="1190,1057" size="200,2" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line9" position="1888,38" size="2,1019" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1390,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line11" position="1592,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line12" position="1694,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="1696,1024" size="85,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        <eLabel name="line13" position="1781,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="1783,1024" size="105,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        </screen>
                        """
        else:
            self.skin = """
                        <screen name="VpnManager" backgroundColor="#00ffffff" position="center,center" size="1280,720" title="VpnManager" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="1,1" size="1277,717" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="51,1" size="678,198" alphatest="blend" zPosition="2" />
                        <widget name="PwLogo" position="891,366" size="266,34" alphatest="blend" zPosition="4" />
                        <eLabel name="line1" position="18,199" size="744,506" zPosition="1" backgroundColor="#00ffffff" />
                        <eLabel name="line2" position="748,200" size="13,504" zPosition="2" backgroundColor="#002a2a2a" />
                        <widget name="config" position="20,200" size="726,504" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0"/>
                        <eLabel name="line3" position="792,25" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="792,681" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="792,704" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="792,25" size="1,679" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="1258,25" size="1,679" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="926,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="793,681" size="133,1" zPosition="4" backgroundColor="#00ff0000" />
                        <widget name="myInfoLabel" position="793,26" size="462,581" transparent="0" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" font="Vpn; 18" valign="center" halign="center"/>
                        <eLabel text=""" + '"' + _("Set default DNS") + '"' + """ position="793,682" size="133,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line10" position="793,704" size="133,1" zPosition="4" backgroundColor="#00ff0000" /><eLabel name="line11" position="1061,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line12" position="1129,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="1130,682" size="56,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line13" position="1187,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="1188,682" size="70,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        </screen>
                        """

        Screen.__init__(self, session)
        self.session = session

        self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"], {
            "ok": self.keyOK,
            "red": self.keyRed,
            "left": self.keyLeft,
            "right": self.keyRight,
            "up": self.keyUp,
            "down": self.keyDown,
            "cancel": self.keyCancel
        }, -1)

        self["myNumberActions"] = NumberActionMap(["InputActions"], {
            "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
        }, -1)

        self["logo"] = Pixmap()
        self["PwLogo"] = Pixmap()
        self["PwLogo"].hide()
        self["myInfoLabel"] = Label("")
        self.list = []
        self.createConfigList()
        ConfigListScreen.__init__(self, self.list, on_change=self.setInfoTxt)

        # Free mode
        self.freeVpnBook = VpnBook()
        self.freeVpnMe = VpnMe()
        self.freeModeProvider = config.vpnmanager.free_mode_type.value

        for file_destination in VPNAUTHFILES:
            if os.path.isfile(file_destination):
                with open(file_destination, "r") as auth_file:
                    data = auth_file.readlines()
                    if len(data) > 1:
                        config.vpnmanager.username.value = data[0].replace("\n", "").strip()
                        config.vpnmanager.password.value = data[1].replace("\n", "").strip()
                        config.vpnmanager.username.save()
                        config.vpnmanager.password.save()
                        configfile.save()
                        break
        self.onLayoutFinish.append(self.setInfoTxt)
        self.onLayoutFinish.append(self.setTypeLogo)

    def createConfigList(self):
        self.list = []
        if isWireGuardInstalled():
            self.list.append(getConfigListEntry(_("Select connection type:"), config.vpnmanager.type))
        if config.vpnmanager.type.value == "vpn":
            self.list.append(getConfigListEntry(_("VPN free mode:"), config.vpnmanager.free_mode))
            if not config.vpnmanager.free_mode.value:
                self.list.append(getConfigListEntry(_("All config's in one folder:"), config.vpnmanager.one_folder))
                config_destination = config.vpnmanager.directory
                self.list.append(getConfigListEntry(_("Storage location for config files:"), config_destination))
            else:
                self.list.append(getConfigListEntry(_("Provider:"), config.vpnmanager.free_mode_type))
        elif config.vpnmanager.type.value == "wireguard":
            self.list.append(getConfigListEntry(_("All config's in one folder:"), config.vpnmanager.one_folder))
            config_destination = config.vpnmanager.directory_wireguard
            self.list.append(getConfigListEntry(_("Storage location for config files:"), config_destination))
        self.list.append(getConfigListEntry(_("Default DNS 1:"), config.vpnmanager.dns))
        self.list.append(getConfigListEntry("Autostart:", config.vpnmanager.autostart))
        if config.vpnmanager.type.value == "vpn":
            self.list.append(getConfigListEntry("resolv:", config.vpnmanager.resolv))
            if config.vpnmanager.resolv.value:
                self.list.append(getConfigListEntry(_("Set optional DNS server:"), config.vpnmanager.vpnresolv))
                if config.vpnmanager.vpnresolv.value:
                    self.list.append(getConfigListEntry("DNS 1:", config.vpnmanager.vpndns1))
                    self.list.append(getConfigListEntry("DNS 2:", config.vpnmanager.vpndns2))
            self.list.append(getConfigListEntry(_("OpenVpn username:"), config.vpnmanager.username))
            self.list.append(getConfigListEntry(_("OpenVpn password:"), config.vpnmanager.password))

    def keyNumberGlobal(self, number):
        if self['config'].getCurrent()[1] == config.vpnmanager.username or self['config'].getCurrent()[1] == config.vpnmanager.password:
            if config.vpnmanager.free_mode.value:
                ConfigListScreen.keyNumberGlobal(self, number)
            else:
                title = self['config'].getCurrent()[0]
                text = self['config'].getCurrent()[1].value
                self.session.openWithCallback(self.set_config_value, VirtualKeyBoard, title=title, text=text)
        elif self['config'].getCurrent()[1] == config.vpnmanager.directory or self['config'].getCurrent()[1] == config.vpnmanager.directory_wireguard:
            config_value = config.vpnmanager.directory.value if config.vpnmanager.type.value == "vpn" else config.vpnmanager.directory_wireguard.value
            self.session.openWithCallback(self.createConfigList, FolderScreen, config_value)
        else:
            ConfigListScreen.keyNumberGlobal(self, number)

    def set_config_value(self, callback):
        if callback != None:
            config_value = self["config"].getCurrent()[1]
            config_value.value = callback
            config_value.save()
            configfile.save()
            self.changedEntry()

    def changedEntry(self):
        if self['config'].getCurrent()[1] == config.vpnmanager.type:
            self.setTypeLogo()
        self.createConfigList()
        self["config"].setList(self.list)

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

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

    def keyUp(self):
        self["config"].instance.moveSelection(self["config"].instance.moveUp)
        self.setInfoTxt()

    def keyDown(self):
        if self["config"].getCurrentIndex() < len(self["config"].getList()) - 1:
            self["config"].instance.moveSelection(self["config"].instance.moveDown)
        self.setInfoTxt()

    def keyOK(self):
        if self['config'].getCurrent()[1] == config.vpnmanager.directory or self['config'].getCurrent()[1] == config.vpnmanager.directory_wireguard:
            config_value = config.vpnmanager.directory.value if config.vpnmanager.type.value == "vpn" else config.vpnmanager.directory_wireguard.value
            self.session.openWithCallback(self.createConfigList, FolderScreen, config_value)
        elif self['config'].getCurrent()[1] == config.vpnmanager.username or self['config'].getCurrent()[1] == config.vpnmanager.password:
            if not config.vpnmanager.free_mode.value:
                title = self['config'].getCurrent()[0]
                text = self['config'].getCurrent()[1].value
                self.session.openWithCallback(self.set_config_value, VirtualKeyBoard, title=title, text=text)
        else:
            if config.vpnmanager.free_mode.value and config.vpnmanager.type.value == "vpn":
                if config.vpnmanager.free_mode_type.value == "book":
                    if not self.freeVpnBook.update:
                        self.session.openWithCallback(self.loadNewConfig, MessageBox, _("No new configs have been loaded yet!\nDownload configs?"), MessageBox.TYPE_YESNO, default=True)
                        return
                else:
                    if not self.freeVpnMe.update:
                        self.session.openWithCallback(self.loadNewConfig, MessageBox, _("No new configs have been loaded yet!\nDownload configs?"), MessageBox.TYPE_YESNO, default=True)
                        return
            self.saveExit()

    def keyRed(self):
        default_dns = '%d.%d.%d.%d' % tuple(config.vpnmanager.dns.value)
        if not default_dns == "0.0.0.0":
            try:
                resolv = "/var/run/connman/resolv.conf"
                if os.path.isfile(resolv):
                    os.system("sed -i '/nameserver/d' %s" % resolv)
                    os.system("echo nameserver %s >> %s" % (default_dns, resolv))
            except OSError as e:
                print(e)
            files = glob.glob('/var/lib/connman/*ethernet*cable*')
            for file in files:
                conn = os.path.basename(file)
                p = subprocess.Popen(['connmanctl', 'config', conn, '--nameservers', default_dns])
                p.wait()

            files = glob.glob('/var/lib/connman/wifi*')
            for file in files:
                conn = os.path.basename(file)
                p = subprocess.Popen(['connmanctl', 'config', conn, '--nameservers', default_dns])
                p.wait()
            self.session.open(MessageBox, _("Default DNS enabled"), MessageBox.TYPE_INFO, timeout=10)

    def keyCancel(self):
        if config.vpnmanager.free_mode.value:
            if config.vpnmanager.free_mode_type.value == "book":
                if not self.freeVpnBook.update:
                    self.session.openWithCallback(self.loadNewConfig, MessageBox, _("No new configs have been loaded yet!\nDownload configs?"), MessageBox.TYPE_YESNO, default=True)
                    return
            else:
                if not self.freeVpnMe.update:
                    self.session.openWithCallback(self.loadNewConfig, MessageBox, _("No new configs have been loaded yet!\nDownload configs?"), MessageBox.TYPE_YESNO, default=True)
                    return
        self.saveExit()

    def loadNewConfig(self, answer):
        if answer:
            if config.vpnmanager.free_mode_type.value == "book":
                self.freeVpnBook.get_free_vpn()
                self.freeModeProvider = "book"
            else:
                self.freeModeProvider = "me"
                self.freeVpnMe.get_free_vpn()
            self.changedEntry()
        else:
            self.saveExit()

    def saveExit(self):
        if config.vpnmanager.free_mode.value and config.vpnmanager.type.value == "vpn":
            if not self.freeModeProvider == config.vpnmanager.free_mode_type.value:
                os.system("rm -R %s" % self.freeVpnBook.CONF_DIRECTORY)
                os.system("mkdir %s" % self.freeVpnBook.CONF_DIRECTORY)
            config.vpnmanager.directory.value = self.freeVpnBook.CONF_DIRECTORY
            config.vpnmanager.directory.save()
            config.vpnmanager.one_folder.value = True
        elif config.vpnmanager.type.value == "vpn":
            config.vpnmanager.directory.value = config.vpnmanager.directory.value
            config.vpnmanager.directory.save()
        elif config.vpnmanager.type.value == "wireguard":
            config.vpnmanager.directory.value = config.vpnmanager.directory_wireguard.value
            config.vpnmanager.directory.save()
        config.vpnmanager.free_mode.save()
        config.vpnmanager.free_mode_type.save()
        config.vpnmanager.one_folder.save()
        config.vpnmanager.username.save()
        config.vpnmanager.password.save()
        config.vpnmanager.resolv.save()
        config.vpnmanager.autostart.save()
        config.vpnmanager.vpnresolv.save()
        config.vpnmanager.vpndns1.save()
        config.vpnmanager.vpndns2.save()
        config.vpnmanager.dns.save()
        config.vpnmanager.type.save()
        configfile.save()
        set_auto_start()
        if config.vpnmanager.type.value == "vpn":
            if runningWireGuard():
                stop_wireguard()
        else:
            if runningOpenVPN():
                stop_vpn()
            rm_file = ["/etc/openvpn/openvpn.log", "/etc/openvpn/openvpn.stat"]
            for log in rm_file:
                if os.path.isfile(log):
                    os.system("rm %s" % log)
        self.close()

    def setTypeLogo(self):
        png = VPN_PNG if config.vpnmanager.type.value == "vpn" else WIREGUARD_PNG
        self["logo"].instance.setPixmapFromFile(png)

    def showPwPng(self):
        png = self.freeVpnBook.PW_PNG
        if os.path.isfile(png):
            self["PwLogo"].instance.setPixmapFromFile(png)
            self["PwLogo"].show()
        else:
            txt = _("Sorry the password image was not found!")
            self["myInfoLabel"].setText(txt)

    def setInfoTxt(self):
        txt = ""
        show = False
        if self['config'].getCurrent()[1] == config.vpnmanager.type:
            if config.vpnmanager.type.value == "vpn":
                txt = _("OpenVPN is a virtual private network (VPN) system that implements techniques to create secure point-to-point or site-to-site connections in routed or bridged configurations and remote access facilities. It implements both client and server applications.")
            else:
                txt = _("WireGuard is a free and open-source software application and communication protocol that implements virtual private network (VPN) techniques to create secure point-to-point connections in routed or bridged configurations. It is run as a module inside the Linux kernel, and aims for better performance and more power saving than the IPsec and OpenVPN tunneling protocols.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.one_folder:
            txt = _("If all configs are in one folder, please activate this function.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.directory or self['config'].getCurrent()[1] == config.vpnmanager.directory_wireguard:
            txt = _("Here you can specify the storage location for the configs.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.dns:
            txt = _("Here you can change the standard DNS.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.autostart:
            txt = _("Here you can activate the autostart.\nThus, a VPN connection is started automatically after booting.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.resolv:
            txt = _("If you disable resolvconf, the standard DNS servers are used. This creates a security hole.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.vpnresolv:
            txt = _("Please only activate if you do not want to use the DNS server of the VPN provider.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.free_mode:
            txt = _("This allows you to use free VPN connections.")
        elif self['config'].getCurrent()[1] == config.vpnmanager.free_mode_type:
            txt = _("Here you can choose between different providers.\n\nhttps://www.vpnbook.com/freevpn\nhttps://www.freeopenvpn.me/")
        elif self['config'].getCurrent()[1] == config.vpnmanager.username or self['config'].getCurrent()[1] == config.vpnmanager.password:
            if config.vpnmanager.free_mode.value and self['config'].getCurrent()[1] == config.vpnmanager.username:
                txt = _("Username is set automatically.")
            elif config.vpnmanager.free_mode.value and self['config'].getCurrent()[1] == config.vpnmanager.password:
                txt = _("Please enter the password from the picture.")
                show = True
            else:
                txt = _("1 variant:\nEnter login data\n\n2 variant:\ncreates a text file in /media/hdd or/media/usb, this must be openvpnauth. This openvpnauth file should only consist of 2 lines, these are\nusername\npassword\nIf you now open the settings again, these access data will also be used.\n\n3 variant:\nAdd a file to the configs with the name pass.file. The content of the file consists of 2 lines, like the openvpnauth.")
        if show:
            self.showPwPng()
        else:
            self["PwLogo"].hide()
        self["myInfoLabel"].setText(txt)


class FolderScreen(Screen):
    def __init__(self, session, initDir, plugin_path=None):
        if DESKTOPSIZE.width() > 1920:
            self.skin = """
                        <screen name="VpnManagerScreen" backgroundColor="#00ffffff" position="center,center" size="2560,1440" title="VpnManagerScreen" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="3,3" size="2555,1435" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="103,3" size="1357,396" alphatest="blend" zPosition="2" />
                        <widget name="media" position="40,405" size="1480,49" foregroundColor="#00ffffff"  backgroundColor="#002a2a2a" font="Vpn; 36" valign="top" halign="left"  zPosition="2" transparent="0" />
                        <eLabel name="line1" position="37,403" size="1485,1007" zPosition="1" backgroundColor="#00ffffff" />
                        <widget name="folderlist" scrollbarMode="showOnDemand" position="40,457" size="1480,949" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" itemHeight="56"/>
                        <eLabel name="line3" position="1584,51" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line5" position="1584,464" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="1584,1363" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="1584,1409" size="933,3" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="1584,51" size="3,1359" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="2517,51" size="3,1359" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1587,1363" size="267,3" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel text="Exit" position="1587,1365" size="267,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line10" position="1587,1409" size="267,3" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line10" position="1853,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1856,1363" size="267,3" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel text="Save" position="1856,1365" size="267,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line10" position="1856,1409" size="267,3" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel name="line11" position="2123,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line12" position="2259,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="2261,1365" size="113,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        <eLabel name="line13" position="2375,1363" size="3,49" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="2377,1365" size="140,44" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 32" valign="top" halign="center" />
                        </screen>
                        """
        elif DESKTOPSIZE.width() == 1920:
            self.skin = """
                        <screen name="VpnManagerScreen" backgroundColor="#00ffffff" position="center,center" size="1920,1080" title="VpnManagerScreen" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="2,2" size="1916,1076" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="77,2" size="1018,297" alphatest="blend" zPosition="2" />          
                        <widget name="media" position="30,304" size="1110,37" foregroundColor="#00ffffff"  backgroundColor="#002a2a2a" font="Vpn; 27" valign="top" halign="left"  zPosition="2" transparent="0" />
                        <eLabel name="line1" position="28,302" size="1114,755" zPosition="1" backgroundColor="#00ffffff" />
                        <widget name="folderlist" scrollbarMode="showOnDemand" position="30,343" size="1110,712" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" itemHeight="42"/>
                        <eLabel name="line3" position="1188,38" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line5" position="1188,348" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="1188,1022" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="1188,1057" size="700,2" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="1188,38" size="2,1019" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="1888,38" size="2,1019" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1190,1022" size="200,2" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel text="Exit" position="1190,1024" size="200,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        <eLabel name="line10" position="1190,1057" size="200,2" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line10" position="1390,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="1392,1022" size="200,2" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel text="Save" position="1392,1024" size="200,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" /> 
                        <eLabel name="line10" position="1392,1057" size="200,2" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel name="line11" position="1592,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line12" position="1694,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="1696,1024" size="85,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        <eLabel name="line13" position="1781,1022" size="2,37" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="1783,1024" size="105,33" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 24" valign="top" halign="center" />
                        </screen>
                        """
        else:
            self.skin = """
                        <screen name="VpnManagerScreen" backgroundColor="#00ffffff" position="center,center" size="1280,720" title="VpnManagerScreen" flags="wfNoBorder">
                        <eLabel name="BackgroundColor" position="1,1" size="1277,717" zPosition="1" backgroundColor="#002a2a2a" />
                        <widget name="logo" position="51,1" size="678,198" alphatest="blend" zPosition="2" />
                        <widget name="media" position="20,202" size="740,24" foregroundColor="#00ffffff"  backgroundColor="#002a2a2a" font="Vpn; 18" valign="top" halign="left"  zPosition="2" transparent="0" />
                        <eLabel name="line1" position="18,201" size="744,503" zPosition="1" backgroundColor="#00ffffff" />
                        <widget name="folderlist" scrollbarMode="showOnDemand" position="20,228" size="740,474" backgroundColorSelected="#002f4665" foregroundColorSelected="#00ffffff" foregroundColor="#00ffffff" backgroundColor="#002a2a2a" zPosition="3" transparent="0" itemHeight="28"/>
                        <eLabel name="line3" position="792,25" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line5" position="792,232" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line6" position="792,681" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line7" position="792,704" size="466,1" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line8" position="792,25" size="1,679" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line9" position="1258,25" size="1,679" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="793,681" size="133,1" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel text="Exit" position="793,682" size="133,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line10" position="793,704" size="133,1" zPosition="4" backgroundColor="#00ff0000" />
                        <eLabel name="line10" position="926,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line10" position="928,681" size="133,1" zPosition="4" backgroundColor="#0000ff00" />
                        <eLabel text="Save" position="928,682" size="133,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line10" position="928,704" size="133,1" zPosition="4" backgroundColor="#0000ff00" /><eLabel name="line11" position="1061,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel name="line12" position="1129,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="OK" position="1130,682" size="56,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        <eLabel name="line13" position="1187,681" size="1,24" zPosition="2" backgroundColor="#00ffffff" />
                        <eLabel text="V """ + PLUGINVERSION + """" position="1188,682" size="70,22" backgroundColor="#002a2a2a" transparent="0" foregroundColor="#00ffffff" zPosition="3" font="Vpn; 16" valign="top" halign="center" />
                        </screen>
                        """
        Screen.__init__(self, session)

        directory_data = initDir[:-1].split("/")
        directory = re.sub("/" + directory_data[len(directory_data) - 1], "", initDir) if len(
            directory_data) > 1 else initDir
        if not os.path.isdir(directory):
            directory = "/"

        self["folderlist"] = FileList(directory, inhibitMounts=False, inhibitDirs=False, showMountpoints=False,
                                      showFiles=False)

        self["logo"] = Pixmap()
        self["media"] = Label(directory)
        self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "SetupActions"], {
            "cancel": self.cancel,
            "left": self.left,
            "right": self.right,
            "up": self.up,
            "down": self.down,
            "ok": self.OK,
            "green": self.green,
            "red": self.cancel
        }, -1)
        self.onLayoutFinish.append(self.setTypeLogo)

    def cancel(self):
        self.close()

    def green(self):
        config_item = config.vpnmanager.directory if config.vpnmanager.type.value == "vpn" else config.vpnmanager.directory_wireguard
        config_item.value = self["folderlist"].getSelection()[0]
        config_item.save()
        configfile.save()
        self.close()

    def up(self):
        self["folderlist"].up()
        self.updateFile()

    def down(self):
        self["folderlist"].down()
        self.updateFile()

    def left(self):
        self["folderlist"].pageUp()
        self.updateFile()

    def right(self):
        self["folderlist"].pageDown()
        self.updateFile()

    def OK(self):
        if self["folderlist"].canDescent():
            self["folderlist"].descent()

    def updateFile(self):
        currFolder = self["folderlist"].getSelection()[0]
        self["media"].setText(currFolder)

    def setTypeLogo(self):
        png = VPN_PNG if config.vpnmanager.type.value == "vpn" else WIREGUARD_PNG
        self["logo"].instance.setPixmapFromFile(png)


# to get consolen-output with timeout-function
class Command(object):
    def __init__(self, cmd):
        self.cmd = cmd
        self.process = None
        self.out = ""
        self.err = ""

    def run(self, timeout):
        def target():
            self.process = subprocess.Popen(self.cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            (self.out, self.err) = self.process.communicate()

        thread = threading.Thread(target=target)
        thread.start()
        self.timeout = False

        thread.join(float(timeout))
        if thread.is_alive():
            self.process.terminate()
            self.timeout = True
            self.process = None
            thread = None
            return


def enterListEntry(entry):
    res = [entry]
    if entry[3] == 1:
        png_connect = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/is_connect%s.png" % desksize
    elif entry[3] == 2:
        png_connect = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/error_connect%s.png" % desksize
    else:
        png_connect = "/usr/lib/enigma2/python/Plugins/Extensions/VpnManager/image/no_connect%s.png" % desksize

    # City
    res.append((eListboxPythonMultiContent.TYPE_TEXT, skinValueCalculate(20), 0, skinValueCalculate(950),
                skinValueCalculate(38), 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, entry[0]))

    png_connect = LoadPixmap(png_connect)
    res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, skinValueCalculate(1039), 1, skinValueCalculate(38),
                skinValueCalculate(38), png_connect))

    res.append(MultiContentEntryText(pos=(0, skinValueCalculate(41)), size=(skinValueCalculate(1090), 1),
                                     font=0,
                                     flags=0 | 0 | 0,
                                     text="",
                                     backcolor=0xffffff))
    return res


def get_device():
    dev_device = "tun0"
    try:
        if os.path.exists("/etc/openvpn"):
            for i in os.listdir("/etc/openvpn"):
                if i.split('.')[-1] == 'conf':
                    f = open("/etc/openvpn/%s" % i, "r").readlines()
                    for line in f:
                        if "dev" in line:
                            if not "#" == line[0]:
                                dev_device = line[4:].strip() + "0"
                                break
    except:
        dev_device = "tun0"
    return dev_device


def statusTunOn():
    x = 0
    while x < 30:
        status = statusTun()
        if status:
            time.sleep(5)
            return True
        time.sleep(1)
        x += 1
    else:
        return False


def statusTunOff():
    x = 0
    while x < 15:
        status = statusTun()
        if not status:
            return True
        time.sleep(1)
        x += 1
    else:
        return False


def statusWg0Off():
    x = 0
    while x < 15:
        status = statusWireguard()
        if not status:
            return True
        time.sleep(1)
        x += 1
    else:
        return False


def checkVpnVersion():
    version = None
    command = Command("apt list --installed *openvpn*")
    command.run(timeout=3)
    cmd_out = command.out
    v = re.findall("(\d.\d).\d", cmd_out, re.M)
    if v:
        version_installed = int(v[0].replace(".", ""))
        if version_installed < 24:
            version = _('Installed VPN version is outdated, please install a version from 2.4.x!')
    return version


def isWireGuardInstalled():
    # WireGuard
    wireGuard = os.popen("opkg list-installed | grep wireguard-tools")
    wireGuard = wireGuard.read()
    if "wireguard-tools" not in wireGuard:
        return False
    return True


def runningOpenVPN():
    command = Command("systemctl status vpn_openvpn.service")
    command.run(timeout=3)
    cmd_out = command.out
    if "Active: active" in cmd_out:
        return True
    return False


def runningWireGuard():
    command = Command("systemctl status wg-quick@Wg0.service")
    command.run(timeout=3)
    cmd_out = command.out
    if "Active: active" in cmd_out:
        return True
    return False


def statusTun():
    tun_status = os.listdir("/sys/devices/virtual/net")
    return True if get_device() in str(tun_status) else False


def statusWireguard():
    wg0_status = os.listdir("/sys/devices/virtual/net")
    return True if "Wg0" in str(wg0_status) else False


def stop_wireguard():
    open_vpn_stop = subprocess.Popen(['systemctl', 'stop', 'wg-quick@Wg0.service'])
    open_vpn_stop.wait()


def start_wireguard():
    open_vpn_start = subprocess.Popen(['systemctl', 'start', 'wg-quick@Wg0.service'])
    open_vpn_start.wait()


def stop_vpn():
    open_vpn_stop = subprocess.Popen(['systemctl', 'stop', 'vpn_openvpn.service'])
    open_vpn_stop.wait()
    open_vpn_stop = subprocess.Popen(['killall', 'openvpn'])
    open_vpn_stop.wait()


def start_vpn():
    open_vpn_start = subprocess.Popen(['systemctl', 'start', 'vpn_openvpn.service'])
    open_vpn_start.wait()


def set_auto_start():
    if config.vpnmanager.autostart.value:
        if config.vpnmanager.type.value == "vpn":
            command = Command("systemctl status wg-quick@Wg0.service")
            command.run(timeout=3)
            cmd_out = command.out
            if "enabled;" in cmd_out:
                openvpn_autostart = subprocess.Popen(['systemctl', 'disable', 'wg-quick@Wg0.service'])
                openvpn_autostart.wait()

            if not glob.glob('/etc/rc3.d/*vpn_openvpn'):
                openvpn_autostart = subprocess.Popen(['systemctl', 'enable', 'vpn_openvpn.service'])
                openvpn_autostart.wait()
        else:
            if glob.glob('/etc/rc3.d/*vpn_openvpn'):
                openvpn_autostart = subprocess.Popen(['systemctl', 'disable', 'vpn_openvpn.service'])
                openvpn_autostart.wait()

            command = Command("systemctl status wg-quick@Wg0.service")
            command.run(timeout=3)
            cmd_out = command.out
            if "enabled;" not in cmd_out:
                openvpn_autostart = subprocess.Popen(['systemctl', 'enable', 'wg-quick@Wg0.service'])
                openvpn_autostart.wait()
    else:
        if glob.glob('/etc/rc3.d/*vpn_openvpn'):
            openvpn_autostart = subprocess.Popen(['systemctl', 'disable', 'vpn_openvpn.service'])
            openvpn_autostart.wait()

        command = Command("systemctl status wg-quick@Wg0.service")
        command.run(timeout=3)
        cmd_out = command.out
        if "enabled;" in cmd_out:
            openvpn_autostart = subprocess.Popen(['systemctl', 'disable', 'wg-quick@Wg0.service'])
            openvpn_autostart.wait()


def skinValueCalculate(value):
    if DESKTOPSIZE.width() > 1920:
        # 2560x1440
        skinFactor = 1.33333333333
        skinMultiply = True
    elif DESKTOPSIZE.width() == 1920:
        # 1920x1080
        skinFactor = 1
        skinMultiply = False
    else:
        # 1280x720
        skinFactor = 1.5
        skinMultiply = False
    if skinMultiply:
        return int(float(round(value * skinFactor)))
    else:
        return int(value / skinFactor)


def exit(session, result):
    if not result:
        session.openWithCallback(exit, VpnManagerScreen)


def main(session, **kwargs):
    session.openWithCallback(exit, VpnManagerScreen)


def Plugins(**kwargs):
    return [PluginDescriptor(name=_("Vpn Manager"), description="Manage your VPN connections",
                             where=PluginDescriptor.WHERE_PLUGINMENU, icon="plugin.png", fnc=main),
            PluginDescriptor(name=_("Vpn Manager"), description="Manage your VPN connections",
                             where=PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)]