Exemple #1
0
def main():
    dialog = Dialog()
    dialog.add_persistent_args(
        ["--backtitle",
         "ZiNC is Not a Cloud. v%s" % __version__])
    repos = settings.repos
    process_repos(dialog, repos)
def reloadPluginList():
    try:
        file_name = config["paths"]["userPath"] + "/.pluginstore/index.ini"
        link = "https://turbowafflz.azurewebsites.net/iicalc/plugins/index"
        #display progress box of updating index
        d = Dialog(dialog="dialog")
        d.add_persistent_args(["--title", "Reloading Plugin List..."])
        d.gauge_start(
            text=
            "This may take a while if the server hasn\'t been pinged in a while",
            height=None,
            width=None,
            percent=0)

        #download actual index from site
        with open(file_name, "wb") as f:
            try:
                response = requests.get(link, stream=True)
            except requests.exceptions.ConnectionError:
                d.gauge_stop()
                if d.yesno(
                        "No Connection. Would you like to continue without a connection?"
                ) == d.OK:
                    store(False)
                else:
                    raise ValueError("Exited")
            total_length = response.headers.get('content-length')

            if total_length is None:  # no content length header
                f.write(response.content)
            else:
                dl = 0
                total_length = int(total_length)
                olddone = 0
                for data in response.iter_content(chunk_size=4096):
                    dl += len(data)
                    f.write(data)
                    done = int(100 * dl / total_length)
                    if done > 100:
                        done = 100
                    if olddone != done:
                        olddone = done

                        d.gauge_update(done)
        d.gauge_stop()
        return True
    except KeyboardInterrupt:
        try:
            #Stop gague if it's started
            d.gauge_stop()
        except:
            pass
        with open(config["paths"]["userPath"] +
                  "/.pluginstore/index.ini") as index:
            if index.read().strip("\n") == "#" or index.read().strip(
                    "\n") == "":
                return False
            else:
                return True
def store(reload=True):
    try:
        #reload index
        if reload == True:
            if reloadPluginList() == False:
                clear()
                print("Please reload the plugin index to continue.")
                return
        try:
            index.read(config["paths"]["userPath"] + "/.pluginstore/index.ini")
        except configparser.MissingSectionHeaderError:
            clear()
            print(
                "The index is temporarily unavailable due to a Microsoft Azure outage. Please try again later or use store.store(False) to enter the store without reloading the index."
            )
            return
        d = Dialog(dialog="dialog")
        d.add_persistent_args(["--title", "Browse", "--cancel-label", "Quit"])
        #default options
        choices = [("Search", "Search for plugins"),
                   ("Updates", "Check for Updates"),
                   ("Installed", "View Your Installed Plugins"), ("", "")]
        #add all plugins to result
        for key in index.sections():
            choices.append((key, index[key]["summary"]))
        #display menu
        while True:
            mainmenu = d.menu("",
                              height=None,
                              width=None,
                              menu_height=None,
                              choices=choices)
            if mainmenu[0] == d.CANCEL:
                clear()
                break
            elif mainmenu[1] == "Search":
                search()
            elif mainmenu[1] == "Updates":
                updateMenu()
            elif mainmenu[1] == "":
                pass
            elif mainmenu[1] == "Installed":
                pluginmenu()
            else:
                pluginpage(mainmenu[1])
    except KeyboardInterrupt:
        clear()
        return
    except ExecutableNotFound:
        print(
            theme["styles"]["error"] +
            "Dialog Execeutable Not Found. (Try installing \'dialog\' with your package manager)"
            + theme["styles"]["normal"])
        return
def pluginmenu():
		choices = []
		d = Dialog()
		#append installed plugins to list
		for key in installed.sections():
			choices.append((key, installed[key]["summary"]))
		if len(choices) == 0:
			choices.append(("No Installed Plugins", ""))
		else:
			#display all installed plugins
			d.add_persistent_args(["--ok-label", "View Page"])
		x = d.menu("Installed Plugins", choices=choices, cancel_label="Back")
		if x[0] == d.OK and x[1] != "No Installed Plugins":
			pluginpage(x[1])
def pluginpage(plugin, cache=None, uri=False):
	d = Dialog(dialog="dialog")
	if uri == True:
		index.read(config["paths"]["userPath"] + "/.pluginstore/index.ini")
	if len(index.sections()) == 0:
		d.msgbox("Index not available. Please connect to the internet and restart the store")
		store(False)
	d.add_persistent_args(["--yes-label", "Download", "--ok-label", "Download", "--title", plugin])
	x = []
	#processing to detect what labels to put on the buttons
	if index[plugin]["type"] == "plugins":
		filepath = pluginPath + index[plugin]["filename"]
	elif index[plugin]["type"] == "themes":
		filepath = themePath + index[plugin]["filename"]
	else:
		print("Invalid type: " + index[plugin]["type"])
	if os.path.isfile(filepath):
		try:
			if float(installed[plugin]["lastupdate"]) == float(index[plugin]["lastUpdate"]) and not installed[plugin]["verified"] == "false":
				x.append(d.yesno(index[plugin]["description"] + "\n\nVotes: " + index[plugin]["rating"] + "\nType: " + index[plugin]["type"][:-1].capitalize() + "\nVersion: " + index[plugin]["version"], height=0, width=0, no_label="Back", cancel_label="Back", extra_button=True, extra_label="Rate Plugin", yes_label="Uninstall", ok_label="Uninstall"))
				x.append("uninstall")
			else:
				 x.append(d.yesno(index[plugin]["description"] + "\n\nVotes: " + index[plugin]["rating"] + "\nType: " + index[plugin]["type"][:-1].capitalize() + "\nVersion: " + index[plugin]["version"], height=0, width=0, no_label="Back", cancel_label="Back", yes_label="Update", ok_label="Update", help_button=True, help_label="Uninstall"))
				 x.append("update")
		except KeyError:
			x.append(d.yesno(index[plugin]["description"] + "\n\nVotes: " + index[plugin]["rating"] + "\nType: " + index[plugin]["type"][:-1].capitalize() + "\nVersion: " + index[plugin]["version"], height=0, width=0, no_label="Back", cancel_label="Back"))
			x.append("download")
	else:
		x.append(d.yesno(index[plugin]["description"] + "\n\nVotes: " + index[plugin]["rating"] + "\nType: " + index[plugin]["type"][:-1].capitalize() + "\nVersion: " + index[plugin]["version"], height=0, width=0, no_label="Back", cancel_label="Back"))
		x.append("download")

	#processing to tell what to do when buttons are pressed
	if x[0] == d.OK:
		if x[1] == "download" or x[1] == "update":
			download(plugin)
		elif x[1] == "uninstall":
			uninstall(installed[plugin]["filename"], plugin)
	elif x[0] == d.EXTRA:
		ratePlugin(plugin)
	elif x[0] == d.HELP:
		uninstall(index[plugin]["filename"], plugin)
	elif x[0] == d.CANCEL and cache != None:
		search(True, cache[0])
	elif x[0] == d.CANCEL and cache == None:
		clear()
Exemple #6
0
#!/usr/bin/env python

import locale
import sys
from dialog import Dialog

import wifi_config_file
import wifi_list

# Set the locale
locale.setlocale(locale.LC_ALL, '')

# Our dialog
d = Dialog(dialog="dialog")
d.add_persistent_args(["--backtitle", "Wifi Config"])

# Defaults
DEFAULT_SSID = "robot"
DEFAULT_PASSWORD = "******"
DEFAULT_COUNTRY_CODE = "AU"
DEFAULT_CHANNEL = 0

DEFAULT_TEXTBOX_HEIGHT = 10
DEFAULT_TEXTBOX_WIDTH = 30

HW_MODE_G_CUTOFF_CHANNEL = 14

COUNTRIES = {'AU': 'Australia', 'CN': 'China', 'US': 'United States'}


def main_menu(dialog):
Exemple #7
0
import sys
import locale
from dialog import Dialog
sys.path.append('/opt/karmios-cli/lib')
from modules_info import GetModuleInfo

modules = GetModuleInfo()
opt = []

for module, description in modules.items():
    opt.append((module, description['description']))

#This is almost always a good thing to do at the beginning of your programs.
locale.setlocale(locale.LC_ALL, '')

# You may want to use 'autowidgetsize=True' here (requires pythondialog >= 3.1)
d = Dialog(dialog="dialog")
d.add_persistent_args(["--backtitle", "KarmiOS-CLI Admin Center"])
d.add_persistent_args(["--title", "KarmiOS-CLI"])
d.add_persistent_args(["--clear"])

smodule = code, tag = d.menu("Please Select an Option:", choices=opt)
SmodulePath = "/opt/karmios-cli/modules/" + str(smodule[1]) + "/bin"
#print(SmodulePath)   #Debug

if str(smodule[0]) == "cancel":
    sys.exit(0)

#Llamando al main_gui del modulo
sys.path.append(SmodulePath)
import main_gui
Exemple #8
0
class MainApp(object):
    """
    Main App class

    """
    def __init__(self):
        self.dialog = Dialog(autowidgetsize=True)
        self.dialog.add_persistent_args(['--no-mouse'])
        self.dialog.set_background_title(
            'Python vSphere Client version {}'.format(__version__))
        self.agent = None

    def about(self):
        welcome = ('Welcome to the Python vSphere Client version {}.\n\n'
                   'PVC is hosted on Github. Please contribute by reporting '
                   'issues, suggesting features and sending patches using '
                   'pull requests.\n\n'
                   'https://github.com/dnaeon/pvc')

        self.dialog.msgbox(title='Welcome', text=welcome.format(__version__))

    def login(self):
        """
        Login to the VMware vSphere host

        Returns:
            True on successful connect, False otherwise

        """
        form_text = ('Enter IP address or DNS name '
                     'of the VMware vSphere host you wish '
                     'to connect to.\n')

        elements = [
            pvc.widget.form.FormElement(label='Hostname'),
            pvc.widget.form.FormElement(label='Username'),
            pvc.widget.form.FormElement(label='Password', attributes=0x1),
        ]

        form = pvc.widget.form.Form(
            dialog=self.dialog,
            form_elements=elements,
            mixed_form=True,
            title='Login Details',
            text=form_text,
        )

        while True:
            code, fields = form.display()
            if code in (self.dialog.CANCEL, self.dialog.ESC):
                return False

            if not all(fields.values()):
                self.dialog.msgbox(
                    title='Error',
                    text='Invalid login details, please try again.\n')
                continue

            self.dialog.infobox(
                title='Establishing Connection',
                text='Connecting to {} ...'.format(fields['Hostname']),
            )

            self.agent = VConnector(
                host=fields['Hostname'],
                user=fields['Username'],
                pwd=fields['Password'],
            )

            try:
                self.agent.connect()
                text = '{} - {} - Python vSphere Client version {}'
                background_title = text.format(
                    self.agent.host, self.agent.si.content.about.fullName,
                    __version__)
                self.dialog.set_background_title(background_title)
                return True
            except Exception as e:
                if isinstance(e, pyVmomi.vim.MethodFault):
                    msg = e.msg
                else:
                    msg = e

                self.dialog.msgbox(title='Login failed',
                                   text='Failed to login to {}\n\n{}\n'.format(
                                       self.agent.host, msg))

    def disconnect(self):
        """
        Disconnect from the remote vSphere host

        """
        if not self.agent:
            return

        self.dialog.infobox(title='Disconnecting Connection',
                            text='Disconnecting from {} ...'.format(
                                self.agent.host))
        self.agent.disconnect()

    def run(self):
        try:
            self.about()
            if not self.login():
                return

            home = pvc.widget.home.HomeWidget(agent=self.agent,
                                              dialog=self.dialog)
            home.display()
        except KeyboardInterrupt:
            pass
        finally:
            self.disconnect()
def download(plugin_name, bulk=False):
    link = index[plugin_name]["download"]
    if index[plugin_name]["type"] == "plugins":
        file_name = pluginPath + index[plugin_name]["filename"]
    elif index[plugin_name]["type"] == "themes":
        file_name = themePath + index[plugin_name]["filename"]
    else:
        print("Invalid type: " + index[plugin_name]["type"])
    d = Dialog(dialog="dialog")
    d.add_persistent_args(["--title", "Downloading " + plugin_name])
    #Progress gauge
    d.gauge_start(text="Installing " + plugin_name,
                  height=None,
                  width=None,
                  percent=0)
    #Actual downloading of file
    with open(file_name, "wb") as f:
        response = requests.get(link, stream=True)
        total_length = response.headers.get('content-length')

        if total_length is None:  # no content length header
            f.write(response.content)
        else:
            dl = 0
            total_length = int(total_length)
            olddone = 0
            for data in response.iter_content(chunk_size=4096):
                dl += len(data)
                f.write(data)
                done = int(100 * dl / total_length)
                if done > 100:
                    done = 100
                if olddone != done:
                    olddone = done

                    d.gauge_update(done)
    #verify plugin
    failed = False
    if pm.verify(plugin_name) == False:
        d.msgbox("The plugin " + plugin_name +
                 " did not download correctly. Please redownload this plugin")
        failed = True

    #add plugin to installed
    try:
        installed.add_section(plugin_name)
    except:
        pass
    installed[plugin_name] = index[plugin_name]
    if failed == True:
        installed[plugin_name]["verified"] = "false"
    else:
        installed[plugin_name]["verified"] = "true"

    #write to installed file
    with open(config["paths"]["userPath"] + "/.pluginstore/installed.ini",
              "r+") as f:
        installed.write(f)

    dependencies = True
    try:
        depends = index[plugin_name]["depends"]
    except:
        dependencies = False
    if dependencies == True:
        depends = depends.split(",")
        for i in range(len(depends)):
            if depends[i].startswith("pypi:"):
                d.gauge_update(100,
                               text="Installing Dependency " + depends[i][5:],
                               update_text=True)
                process = subprocess.Popen(
                    [sys.executable, "-m", "pip", "install", depends[i][5:]],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT)
                text = ""
                for c in iter(lambda: process.stdout.read(1), b''):
                    text += c.decode("utf-8")
                    if text.endswith("\n"):
                        d.gauge_update(100,
                                       text="Installing Dependency " +
                                       depends[i][5:] + "\n" + text.strip(),
                                       update_text=True)
                        text = ""

            else:
                download(depends[i], True)
    d.gauge_stop()
    if bulk == False and failed == False:
        d.msgbox("Successfully downloaded " + plugin_name,
                 height=None,
                 width=None)
Exemple #10
0
#!/usr/bin/env python

import locale
import sys
from dialog import Dialog

import wifi_config_file
import wifi_list

# Set the locale
locale.setlocale(locale.LC_ALL, '')

# Our dialog
d = Dialog(dialog="dialog")
d.add_persistent_args(["--backtitle", "Wifi Config"])

# Defaults
DEFAULT_SSID="robot"
DEFAULT_PASSWORD="******"
DEFAULT_COUNTRY_CODE="AU"
DEFAULT_CHANNEL=0

DEFAULT_TEXTBOX_HEIGHT=10
DEFAULT_TEXTBOX_WIDTH=30

HW_MODE_G_CUTOFF_CHANNEL=14

COUNTRIES = {'AU': 'Australia',
             'CN': 'China',
             'US': 'United States'}
Exemple #11
0
def main():
    dialog = Dialog()
    dialog.add_persistent_args(["--backtitle", "ZiNC is Not a Cloud. v%s" % __version__])
    repos = settings.repos
    process_repos(dialog, repos)
Exemple #12
0
#!/usr/bin/python3

import sys
import locale
from dialog import Dialog

opt = [("1", "Install New NSID"), ("2", "Uninstall NSID"),
       ("3", "Check NSID Conectivity")]

#This is almost always a good thing to do at the beginning of your programs.
locale.setlocale(locale.LC_ALL, '')

# You may want to use 'autowidgetsize=True' here (requires pythondialog >= 3.1)
d = Dialog(dialog="dialog")
d.add_persistent_args(["--backtitle", "KarmiOS-CLI Admin Center"])
d.add_persistent_args(["--title", "NSID Settings"])
d.add_persistent_args(["--clear"])
d.add_persistent_args(["--cancel-label", "Return"])

opt = code, tag = d.menu("Please Select an Option:", choices=opt)

#Me devuelvo
if str(opt[0]) == "cancel":
    sys.path.append('/opt/karmios-cli/bin')
    import karmios_control_center_gui

if opt[1] == "1":
    import new_nsid_gui

elif opt[1] == "2":
    import del_nsid_gui
Exemple #13
0
import sys
import textwrap

from jinja2 import Template

from dialog import (
    Dialog, )

dialog = Dialog()
dialog.add_persistent_args(["--backtitle", "Custom CA Creation Helper"])


def yesno(message):
    return dialog.yesno(message)


def msgbox(message):
    content = textwrap.wrap(message, width=40)
    height = len(content) + 4
    dialog.msgbox("\n".join(content), height=height, width=46)


def error_and_exit(message):
    content = textwrap.wrap(message, width=40)
    height = len(content) + 4
    dialog.msgbox("\n".join(content), height=height, width=46)
    sys.exit(1)


def dialog_input(message, initial=None):
    if initial:
def guiStoreInfo():
    d = Dialog()
    d.add_persistent_args(["--title", "Generate Store Info"])
    #Get plugin
    choices = []
    pluginlist = plugins(False, True)
    for i in range(len(pluginlist)):
        choices.append((pluginlist[i], ""))
    if len(choices) == 0:
        choices = [("No Plugins Are Installed", "")]
    resp = d.menu("Choose plugin", choices=choices)
    if resp[0] == d.OK:
        if resp[1] == "No Plugins Are Installed":
            clear()
            return
        else:
            #Continue Asking
            name = ""
            while name == "":
                name = d.inputbox("Plugin Name (No Spaces)")[1].replace(
                    " ", "_")

            if resp[1].endswith(".iitheme"):
                type = "themes"
            elif resp[1].endswith(".py"):
                type = "plugins"

            description = "\n"
            while description == "\n":
                description = d.editbox_str(
                    "", title="Plugin Description")[1].rstrip()

            version = ""
            while version == "":
                version = d.inputbox("Plugin Version")[1]

            maintainer = ""
            while maintainer == "":
                maintainer = d.inputbox("Maintainer Email Address")[1]

            link = ""
            while link == "":
                link = d.inputbox(
                    "Direct Download Link (Please use GitHub or GitLab for hosting)"
                )[1]

            summary = ""
            while summary == "":
                summary = d.inputbox("Plugin Summary")[1]

            if type == "plugins":
                reqs = getReqs(resp[1])
                depends = d.editbox_str(
                    reqs,
                    title=
                    "Dependancies separated by line breaks. Start PiPI dependancies with \'pipy:\'"
                )[1]
            depends = depends.replace("\n", ",")
            depends = depends.rstrip(",")

            lastUpdate = time.time()
            hash = hs.fileChecksum(type + "/" + resp[1], "sha256")

            clear()

            print("[" + name + "]")
            print("description = " + description)
            print("maintainer = " + maintainer)
            print("version = " + version)
            print("download = " + link)
            print("hash = " + hash)
            print("lastupdate = " + str(time.time()))
            print("summary = " + summary)
            print("filename = " + resp[1])
            if not depends == "":
                print("depends = " + depends)
            print("rating = 5")
            print("ratings = 0")
            print("type = " + type)

    else:
        clear()
        return
Exemple #15
0
class MainApp(object):
    """
    Main App class

    """
    def __init__(self):
        self.dialog = Dialog(autowidgetsize=True)
        self.dialog.add_persistent_args(['--no-mouse'])
        self.dialog.set_background_title(
            'Python vSphere Client version {}'.format(__version__)
        )
        self.agent = None

    def about(self):
        welcome = (
            'Welcome to the Python vSphere Client version {}.\n\n'
            'PVC is hosted on Github. Please contribute by reporting '
            'issues, suggesting features and sending patches using '
            'pull requests.\n\n'
            'https://github.com/dnaeon/pvc'
        )

        self.dialog.msgbox(
            title='Welcome',
            text=welcome.format(__version__)
        )

    def login(self):
        """
        Login to the VMware vSphere host

        Returns:
            True on successful connect, False otherwise

        """
        form_text = (
            'Enter IP address or DNS name '
            'of the VMware vSphere host you wish '
            'to connect to.\n'
        )

        elements = [
            pvc.widget.form.FormElement(label='Hostname'),
            pvc.widget.form.FormElement(label='Username'),
            pvc.widget.form.FormElement(label='Password', attributes=0x1),
        ]

        form = pvc.widget.form.Form(
            dialog=self.dialog,
            form_elements=elements,
            mixed_form=True,
            title='Login Details',
            text=form_text,
        )

        while True:
            code, fields = form.display()
            if code in (self.dialog.CANCEL, self.dialog.ESC):
                return False

            if not all(fields.values()):
                self.dialog.msgbox(
                    title='Error',
                    text='Invalid login details, please try again.\n'
                )
                continue

            self.dialog.infobox(
                title='Establishing Connection',
                text='Connecting to {} ...'.format(fields['Hostname']),
            )

            self.agent = VConnector(
                host=fields['Hostname'],
                user=fields['Username'],
                pwd=fields['Password'],
            )

            try:
                self.agent.connect()
                text = '{} - {} - Python vSphere Client version {}'
                background_title = text.format(
                    self.agent.host,
                    self.agent.si.content.about.fullName,
                    __version__
                )
                self.dialog.set_background_title(background_title)
                return True
            except Exception as e:
                if isinstance(e, pyVmomi.vim.MethodFault):
                    msg = e.msg
                else:
                    msg = e

                self.dialog.msgbox(
                    title='Login failed',
                    text='Failed to login to {}\n\n{}\n'.format(self.agent.host, msg)
                )

    def disconnect(self):
        """
        Disconnect from the remote vSphere host

        """
        if not self.agent:
            return

        self.dialog.infobox(
            title='Disconnecting Connection',
            text='Disconnecting from {} ...'.format(self.agent.host)
        )
        self.agent.disconnect()

    def run(self):
        try:
            self.about()
            if not self.login():
                return

            home = pvc.widget.home.HomeWidget(
                agent=self.agent,
                dialog=self.dialog
            )
            home.display()
        except KeyboardInterrupt:
            pass
        finally:
            self.disconnect()
Exemple #16
0
#   |                 |_|_| |_| |_| .__/ \___/|_|   \__|                   |
#   |                             |_|                                      |
#   +----------------------------------------------------------------------+
#   |                                                                      |
#   '----------------------------------------------------------------------'

import os, sys, pprint, locale, dialog
from dialog import Dialog
sys.path.insert(0, './api')
locale.setlocale(locale.LC_ALL, '')
from base64 import b64encode, b64decode

config_dir = os.path.expanduser('~') + "/.always-backup/"

d = Dialog(dialog="dialog")
d.add_persistent_args(["--backtitle", "Always Backup Configuration"])
#.
#Source: https://gist.github.com/ldx/5005528
def decode_dropbox_key(key):
    key, secret = key.split('|')
    key = b64decode(key)
    key = [ord(x) for x in key]
    secret = b64decode(secret)

    s = range(256)
    y = 0
    for x in xrange(256):
        y = (y + s[len(key)] + key[x % len(key)]) % 256
        s[x], s[y] = s[y], s[x]

    x = y = 0
def download(plugin_name, bulk=False):
	link = index[plugin_name]["download"]
	if index[plugin_name]["type"] == "plugins":
		file_name = pluginPath + index[plugin_name]["filename"]
	elif index[plugin_name]["type"] == "themes":
		file_name = themePath + index[plugin_name]["filename"]
	else:
		print("Invalid type: " + index[plugin_name]["type"])

	# Calculator version testing for plugin compatibilities
	#Parse calcversion to find the operator and version
	calcversion = index[plugin_name]["calcversion"]
	#Get current calculator version
	with open(config["paths"]["systemPath"] + "/version.txt") as f:
		currentversion = f.read().strip()
	#check to see if the current version of the calculator satisfys plugin required version
	versiond = Dialog()
	if not currentversion in Requirement.parse("iicalc" + calcversion):
		if bulk == False:
			if versiond.yesno("The plugin " + plugin_name + " is meant for version " + calcversion + " but you\'re using version " + currentversion + " of the calculator so it may misbehave. Download anyway?", width=0, height=0) == versiond.CANCEL:
				return
		else:
			versiond.msgbox("The plugin " + plugin_name + " is meant for version " + calcversion + " but you\'re using version " + currentversion + " of the calculator so it may misbehave.")

	d = Dialog(dialog="dialog")
	d.add_persistent_args(["--title", "Downloading " + plugin_name])
	#Progress gauge
	d.gauge_start(text="Installing " + plugin_name, height=None, width=None, percent=0)
	#Actual downloading of file
	with open(file_name, "wb") as f:
		response = requests.get(link, stream=True)
		total_length = response.headers.get('content-length')

		if total_length is None: # no content length header
			f.write(response.content)
		else:
			dl = 0
			total_length = int(total_length)
			olddone=0
			for data in response.iter_content(chunk_size=4096):
				dl += len(data)
				f.write(data)
				done = int(100 * dl / total_length)
				if done > 100:
					done = 100
				if olddone != done:
					olddone = done

					d.gauge_update(done)
	#verify plugin
	failed = False
	if pm.verify(plugin_name) == False:
		d.msgbox("The plugin " + plugin_name + " did not download correctly. Please redownload this plugin")
		failed = True

	#add plugin to installed
	try:
		installed.add_section(plugin_name)
	except:
		pass
	installed[plugin_name] = index[plugin_name]
	if failed == True:
		installed[plugin_name]["verified"] = "false"
	else:
		installed[plugin_name]["verified"] = "true"

	#write to installed file
	with open(config["paths"]["userPath"] + "/.pluginstore/installed.ini", "r+") as f:
		installed.write(f)

	dependencies = True
	try:
		depends = index[plugin_name]["depends"]
	except:
		dependencies = False
	if dependencies == True:
		depends = depends.split(",")
		for i in range(len(depends)):
			if depends[i].startswith("pypi:"):
				d.gauge_update(100, text="Installing Dependency " + depends[i][5:], update_text=True)
				process = subprocess.Popen([sys.executable, "-m", "pip","install", depends[i][5:]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
				text = ""
				for c in iter(lambda: process.stdout.read(1), b''):
					text += c.decode("utf-8")
					if text.endswith("\n"):
						d.gauge_update(100, text="Installing Dependency " + depends[i][5:] + "\n" + text.strip(), update_text=True)
						text = ""


			else:
				download(depends[i], True)
	d.gauge_stop()
	if bulk == False and failed == False:
		d.msgbox("Successfully downloaded " + plugin_name, height=None, width=None)
Exemple #18
0
#!/usr/bin/env python3
#
# netem-conf - configure NETem parameter
#
import copy
import os
import subprocess
import json
from dialog import Dialog

# minimal config
config = { 'eth0_to_eth1': {}, 'symmetric': True }

# open dialog system
d = Dialog(dialog="dialog", autowidgetsize=True)
d.add_persistent_args(["--no-collapse"])


# configure NETem parameter in linux
def conf_netem(link, dev):
    # remove current config
    subprocess.call(['sudo', '-S', 'tc', 'qdisc', 'del', 'dev', dev, 'root'],
                    stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL)

    # base NETem command line
    netem_cmd = ['sudo', '-S', 'tc', 'qdisc', 'add', 'dev', dev]

    # configure bandwidth with htb
    if config[link].get('bandwidth') is not None:
        buffer = max(int(0.3*config[link]['bandwidth']+0.5), 1600)
Exemple #19
0
#!/usr/bin/env python3
#
# netem-conf - configure NETem parameter
#
import copy
import os
import subprocess
import json
from dialog import Dialog

# minimal config
config = {'eth0_to_eth1': {}, 'symmetric': True}

# open dialog system
d = Dialog(dialog="dialog", autowidgetsize=True)
d.add_persistent_args(["--no-collapse"])


# configure NETem parameter in linux
def conf_netem(link, dev):
    # remove current config
    subprocess.call(['sudo', '-S', 'tc', 'qdisc', 'del', 'dev', dev, 'root'],
                    stdin=subprocess.DEVNULL,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL)

    # base NETem command line
    netem_cmd = ['sudo', '-S', 'tc', 'qdisc', 'add', 'dev', dev]

    # configure bandwidth with htb
    if config[link].get('bandwidth') is not None: