Пример #1
0
def get_unit_status(unit_name: str) -> Dict[str, Any]:
    bus = SystemBus()
    systemd = bus.get('org.freedesktop.systemd1')
    path = systemd.GetUnit(unit_name)
    unit = bus.get('org.freedesktop.systemd1', path)
    properties = dict_from_attributes(unit['org.freedesktop.systemd1.Unit'],
                                      unit_properties)
    if unit_name.endswith('.service'):
        properties.update(dict_from_attributes(
            unit['org.freedesktop.systemd1.Service'], service_properties))
    elif unit_name.endswith('.timer'):
        properties.update(dict_from_attributes(
            unit['org.freedesktop.systemd1.Timer'], timer_properties))
    return properties
Пример #2
0
Файл: btk.py Проект: Somepig/btk
def loop():
    bus = SystemBus()
    bus.own_name('net.lvht.btk')
    obj_path = '/net/lvht/btk/HIDProfile'

    sock = bt.BluetoothSocket(bt.L2CAP)
    sock.setblocking(False)
    try:
        sock.bind(('', PSM_INTR))
    except:
        print("For bluez5 add --noplugin=input to the bluetoothd commandline")
        print("Else there is another application running that has it open.")
        sys.exit(errno.EACCES)
    sock.listen(1)

    profile = HIDProfile(bus.con, obj_path, sock)

    opts = {
        "PSM": GLib.Variant.new_uint16(PSM_CTRL),
        "ServiceRecord": GLib.Variant.new_string(open('./sdp_record.xml', 'r').read()),
        "RequireAuthentication": GLib.Variant.new_boolean(True),
        "RequireAuthorization": GLib.Variant.new_boolean(False),
    }
    manager = bus.get('org.bluez')['.ProfileManager1']
    manager.RegisterProfile(obj_path, str(uuid.uuid4()), opts)

    profile.run()
Пример #3
0
def quit(bus=None):
    if bus is None:
        bus = SystemBus()

    try:
        bts = bus.get(BTSDBusService.interface_name)
        bts.Quit()
    except GLib.Error:
        return -1
Пример #4
0
    def _start_loop(self):
        """Starts main event handler loop, run in handler thread t."""
        # Create our main loop, get our bus, and add the signal handler
        loop = GObject.MainLoop()
        bus = SystemBus()
        manager = bus.get(".NetworkManager")
        manager.onPropertiesChanged = self._vpn_signal_handler

        # Loop forever
        loop.run()
Пример #5
0
def inject(mail, bus=None):
    if bus is None:
        bus = SystemBus()

    mail = base64.b64encode(mail).decode('ascii')
    try:
        bts = bus.get(BTSDBusService.interface_name)
        return bts.Inject(mail)
    except GLib.Error:
        return -1
Пример #6
0
 def _get_vpn_status(self):
     """Returns None if no VPN active, Id if active."""
     # Sleep for a bit to let any changes in state finish
     sleep(0.3)
     # Check if any active connections are a VPN
     bus = SystemBus()
     for name in self.active:
         conn = bus.get(".NetworkManager", name)
         if conn.Vpn:
             return conn.Id
     # No active VPN
     return None
Пример #7
0
def dbus_main():
    global sysbus, avahi, dbus_loop

    dbg('Connecting to system DBus')
    sysbus = SystemBus()

    dbg('Subscribing to .Avahi.RecordBrowser signals')
    sysbus.con.signal_subscribe('org.freedesktop.Avahi',
        'org.freedesktop.Avahi.RecordBrowser',
        None, None, None, 0, signal_dispatcher)

    avahi = sysbus.get('.Avahi', '/')

    dbg("Connected to Avahi Daemon: %s (API %s) [%s]"
             % (avahi.GetVersionString(), avahi.GetAPIVersion(), avahi.GetHostNameFqdn()))

    dbg('Starting DBus main loop')
    dbus_loop = GLib.MainLoop()
    dbus_loop.run()
Пример #8
0
class MediaDeviceThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self) 
        self.bus = SystemBus()
        try:
            self.dev = self.bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/drives/TSSTcorp_CDDVDW_SE_S084C_SATASLIM00003008cae')
            #self.dev = self.bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks/devices/sr0')
        except KeyError:
            print "CD LW not connected"
            quit()
        self.media = self.dev.MediaAvailable

    def _print(*a):
        print a

    def run(self):
        with self.dev.PropertiesChanged.connect(self._print) as d:
            if self.media:
                print "Media still inserted..."
		# self.dev.Eject()
            GObject.MainLoop().run()
Пример #9
0
class WelcomedClient(GObject.GObject):
    _name = 'com.antergos.welcome'
    _object_path = '/com/antergos/welcome'
    _interface_name = 'com.antergos.welcome'

    __gsignals__ = {
        'command-finished': (GObject.SignalFlags.RUN_FIRST, None,
                             (str, str, GObject.TYPE_PYOBJECT))
    }

    def __init__(self):
        GObject.GObject.__init__(self)
        self.interface = None
        self.welcomed_ok = False
        try:
            self.bus = SystemBus()
            self.dbus_proxy = self.bus.get(WelcomedClient._name,
                                           WelcomedClient._object_path)

            if not self.dbus_proxy:
                self.welcomed_ok = False
            else:
                self.dbus_proxy.PropertiesChanged.connect(
                    self.on_properties_changed)
                self.welcomed_ok = self.dbus_proxy.is_alpm_on()
        except Exception as err:
            print(err)
        finally:
            if not self.welcomed_ok:
                msg = _(
                    "Can't find Welcome d-bus service. Is it really installed?"
                )
                Notify.init("antergos-welcome")
                Notify.Notification.new(_("ERROR!"), msg,
                                        'dialog-error').show()

    def refresh(self):
        """ pacman -Sy """
        return self.dbus_proxy.refresh_alpm()

    def on_properties_changed(self, *params):
        """ A d-bus server property has changed """
        (sender, prop, not_used) = params
        # print("PARAMS:", params)
        if sender == WelcomedClient._name and 'command_finished' in prop.keys(
        ):
            (uid, command, pkgs) = prop['command_finished']
            self.emit("command-finished", uid, command, pkgs)

    def install_package(self, pkg):
        """ pacman -S pkg """
        return self.dbus_proxy.install_package(pkgs)

    def install_packages(self, pkgs):
        """ pacman -S pkgs """
        return self.dbus_proxy.install_packages(pkgs)

    def remove_package(self, package):
        """ pacman -R pkg """
        return self.dbus_proxy.remove_package(package)

    def remove_packages(self, pkgs):
        """ pacman -R pkgs """
        for pkg in pkgs:
            self.remove_package(pkg)

    def check_updates(self):
        return self.dbus_proxy.check_updates()

    def system_upgrade(self):
        return self.dbus_proxy.system_upgrade()
Пример #10
0
class WelcomedClient(GObject.GObject):
    _name = 'com.antergos.welcome'
    _object_path = '/com/antergos/welcome'
    _interface_name = 'com.antergos.welcome'

    __gsignals__ = {
        'command-finished': (GObject.SignalFlags.RUN_FIRST, None,
                             (str, str, GObject.TYPE_PYOBJECT))
    }

    def __init__(self):
        GObject.GObject.__init__(self)
        self.interface = None
        self.welcomed_ok = False
        try:
            self.bus = SystemBus()
            self.dbus_proxy = self.bus.get(
                WelcomedClient._name,
                WelcomedClient._object_path)

            if not self.dbus_proxy:
                self.welcomed_ok = False
            else:
                self.dbus_proxy.PropertiesChanged.connect(
                    self.on_properties_changed)
                self.welcomed_ok = self.dbus_proxy.is_alpm_on()
        except Exception as err:
            print(err)
        finally:
            if not self.welcomed_ok:
                msg = _("Can't find Welcome d-bus service. Is it really installed?")
                Notify.init("antergos-welcome")
                Notify.Notification.new(
                    _("ERROR!"), msg, 'dialog-error').show()

    def refresh(self):
        """ pacman -Sy """
        return self.dbus_proxy.refresh_alpm()

    def on_properties_changed(self, *params):
        """ A d-bus server property has changed """
        (sender, prop, not_used) = params
        # print("PARAMS:", params)
        if sender == WelcomedClient._name and 'command_finished' in prop.keys():
            (uid, command, pkgs) = prop['command_finished']
            self.emit("command-finished", uid, command, pkgs)

    def install_package(self, pkg):
        """ pacman -S pkg """
        return self.dbus_proxy.install_package(pkgs)

    def install_packages(self, pkgs):
        """ pacman -S pkgs """
        return self.dbus_proxy.install_packages(pkgs)

    def remove_package(self, package):
        """ pacman -R pkg """
        return self.dbus_proxy.remove_package(package)

    def remove_packages(self, pkgs):
        """ pacman -R pkgs """
        for pkg in pkgs:
            self.remove_package(pkg)

    def check_updates(self):
        return self.dbus_proxy.check_updates()

    def system_upgrade(self):
        return self.dbus_proxy.system_upgrade()
Пример #11
0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from time import sleep
from command import Thuisbezorgd, LaatsteNieuws, Screenshot, Weersverwachting, Bieraanbieding, Fap
from selenium.webdriver.chrome.options import Options
from pydbus import SystemBus
import re

bus = SystemBus()
signal = bus.get('org.asamk.Signal')

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

class Bot:
    last_message = None

    def __init__(self):
        self.driver = webdriver.Firefox()
        # self.driver = webdriver.Chrome(executable_path='/Users/oscar/Github/WhatsApp-Web-Bot/chromedriver')
        # self.driver.maximize_window()

    def get_qr(self):
        """
        Waits for the QR-code to be scanned.

        :return: void
        """
        self.driver.get('https://web.whatsapp.com/')
Пример #12
0
from pydbus import SystemBus

bus = SystemBus()

systemd = bus.get(".systemd1")
#systemd = bus.get("org.freedesktop.systemd1")

manager = systemd[".Manager"]
#manager = systemd["org.freedesktop.systemd1.Manager"]
#manager = systemd # works but may break if systemd adds another interface

import sys

try:
	if len(sys.argv) < 2:
		for unit in manager.ListUnits():
			print(unit)
	else:
		if sys.argv[1] == "--help":
			help(manager)
		else:
			command = sys.argv[1]
			command = "".join(x.capitalize() for x in command.split("-"))
			result = getattr(manager, command)(*sys.argv[2:])

			for var in result:
				if type(var) == list:
					for line in var:
						print(line)
				else:
					print(var)
Пример #13
0
class Py3status:
    """
    """

    # available configuration parameters
    cache_timeout = 5
    format = (
        "\?color=state WW: [\?if=state_name=connected "
        "({signal_quality_0}% at {m3gpp_operator_name}) "
        "[{format_ipv4}[\?soft  ]{format_ipv6}]"
        "|{state_name}][ SMS {messages} [{format_message}]]"
    )
    format_ipv4 = u"[{address}]"
    format_ipv6 = u"[{address}]"
    format_message = u"\?if=index<2 {number} [\?max_length=10 {text}...]"
    format_message_separator = u" "
    format_notification = None
    format_stats = u"{duration_hms}"
    modem = None
    thresholds = [(0, "bad"), (11, "good")]

    def post_config_hook(self):
        modem_manager = ["ModemManager", "/usr/sbin/ModemManager"]
        network_manager = ["NetworkManager", "/usr/sbin/NetworkManager"]
        for command in (modem_manager, network_manager):
            if not self.py3.check_commands(command):
                raise Exception("%s %s" % (command[0], STRING_NOT_INSTALLED))

        # search: modemmanager flags and enumerations
        # enum 1: #MMModemState
        # enum 2: #MMModemAccessTechnology
        # enum 3: #MMModem3gppRegistrationState
        # enum 4: #MMModemBand

        # enum 1: network states
        self.network_states = {
            -1: "failed",
            0: "unknown",
            1: "initializing",
            2: "locked",
            3: "disabled",
            4: "disabling",
            5: "enabling",
            6: "enabled",
            7: "searching",
            8: "registered",
            9: "disconnecting",
            10: "connecting",
            11: "connected",
        }
        # enum 2: network speed
        self.network_speed = {
            0: "Unknown",
            1 << 0: "POTS",  # 2
            1 << 1: "GSM",
            1 << 2: "GSM Compact",
            1 << 3: "GPRS",
            1 << 4: "EDGE",
            1 << 5: "UMTS",  # 32
            1 << 6: "HSDPA",
            1 << 7: "HSUPA",
            1 << 8: "HSPA",
            1 << 9: "HSPA+",  # 512
            1 << 10: "1XRTT",
            1 << 11: "EVDO0",
            1 << 12: "EVDOA",
            1 << 13: "EVDOB",
            1 << 14: "LTE",  # 16384
        }
        # enum 3: network registration state
        self.registration_states = {
            0: "IDLE",
            1: "HOME",
            2: "SEARCHING",
            3: "DENIED",
            4: "UNKNOWN",
            5: "ROAMING",
        }
        # enum 4: modem bands
        self.modem_bands = {
            0: "Unknown or invalid band",
            1: "GSM/GPRS/EDGE 900 MHz",
            2: "GSM/GPRS/EDGE 1800 MHz",
            3: "GSM/GPRS/EDGE 1900 MHz",
            4: "GSM/GPRS/EDGE 850 MHz",
            5: "WCDMA 2100 MHz (Class I)",
            6: "WCDMA 3GPP 1800 MHz (Class III)",
            7: "WCDMA 3GPP AWS 1700/2100 MHz (Class IV)",
            8: "WCDMA 3GPP UMTS 800 MHz (Class VI)",
            9: "WCDMA 3GPP UMTS 850 MHz (Class V)",
            10: "WCDMA 3GPP UMTS 900 MHz (Class VIII)",
            11: "WCDMA 3GPP UMTS 1700 MHz (Class IX)",
            12: "WCDMA 3GPP UMTS 1900 MHz (Class II)",
            13: "WCDMA 3GPP UMTS 2600 MHz (Class VII, internal)",
            31: "E-UTRAN band I",
            32: "E-UTRAN band II",
            33: "E-UTRAN band III",
            34: "E-UTRAN band IV",
            35: "E-UTRAN band V",
            36: "E-UTRAN band VI",
            37: "E-UTRAN band VII",
            38: "E-UTRAN band VIII",
            39: "E-UTRAN band IX",
            40: "E-UTRAN band X",
            41: "E-UTRAN band XI",
            42: "E-UTRAN band XII",
            43: "E-UTRAN band XIII",
            44: "E-UTRAN band XIV",
            47: "E-UTRAN band XVII",
            48: "E-UTRAN band XVIII",
            49: "E-UTRAN band XIX",
            50: "E-UTRAN band XX",
            51: "E-UTRAN band XXI",
            52: "E-UTRAN band XXII",
            53: "E-UTRAN band XXIII",
            54: "E-UTRAN band XXIV",
            55: "E-UTRAN band XXV",
            56: "E-UTRAN band XXVI",
            63: "E-UTRAN band XXXIII",
            64: "E-UTRAN band XXXIV",
            65: "E-UTRAN band XXXV",
            66: "E-UTRAN band XXXVI",
            67: "E-UTRAN band XXXVII",
            68: "E-UTRAN band XXXVIII",
            69: "E-UTRAN band XXXIX",
            70: "E-UTRAN band XL",
            71: "E-UTRAN band XLI",
            72: "E-UTRAN band XLII",
            73: "E-UTRAN band XLIII",
            128: "CDMA Band Class 0 (US Cellular 850MHz)",
            129: "CDMA Band Class 1 (US PCS 1900MHz)",
            130: "CDMA Band Class 2 (UK TACS 900MHz)",
            131: "CDMA Band Class 3 (Japanese TACS)",
            132: "CDMA Band Class 4 (Korean PCS)",
            134: "CDMA Band Class 5 (NMT 450MHz)",
            135: "CDMA Band Class 6 (IMT2000 2100MHz)",
            136: "CDMA Band Class 7 (Cellular 700MHz)",
            137: "CDMA Band Class 8 (1800MHz)",
            138: "CDMA Band Class 9 (900MHz)",
            139: "CDMA Band Class 10 (US Secondary 800)",
            140: "CDMA Band Class 11 (European PAMR 400MHz)",
            141: "CDMA Band Class 12 (PAMR 800MHz)",
            142: "CDMA Band Class 13 (IMT2000 2500MHz Expansion)",
            143: "CDMA Band Class 14 (More US PCS 1900MHz)",
            144: "CDMA Band Class 15 (AWS 1700MHz)",
            145: "CDMA Band Class 16 (US 2500MHz)",
            146: "CDMA Band Class 17 (US 2500MHz Forward Link Only)",
            147: "CDMA Band Class 18 (US 700MHz Public Safety)",
            148: "CDMA Band Class 19 (US Lower 700MHz)",
            256: "auto",
        }

        self.bus = SystemBus()
        self.init = {
            "ip": [],
            "sms_message": [],
            "thresholds": self.py3.get_color_names_list(self.format),
        }
        self.last_messages = 0
        self.last_notification = self.py3.storage_get("notification")

        names = [
            "current_bands_name",
            "access_technologies_name",
            "m3gpp_registration_name",
            "interface_name",
            "ipv4",
            "ipv6",
            "stats",
            "format_message",
            "message",
        ]
        placeholders = [
            "current_bands_name",
            "access_technologies_name",
            "m3gpp_registration_name",
            "interface_name",
            "format_ipv4",
            "format_ipv6",
            "format_stats",
            "format_message",
            "message*",
        ]

        # init methods
        format_strings = [self.format, self.format_notification]
        for name, placeholder in zip(names, placeholders):
            self.init[name] = []
            for format_string in format_strings:
                if format_string:  # fails on None, [], '', etc
                    if self.py3.format_contains(format_string, placeholder):
                        self.init[name].append(format_string)
                        if name in ["ipv4", "ipv6"]:
                            if name not in self.init["ip"]:
                                self.init["ip"].append(name)
                        if name in ["message", "format_message"]:
                            if name not in self.init["sms_message"]:
                                self.init["sms_message"].append(name)

    def _get_modem_proxy(self):
        modemmanager_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS)
        modems = modemmanager_proxy.GetManagedObjects()

        for objects in modems.items():
            modem_path = objects[0]
            modem_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, modem_path)
            eqid = modem_proxy.EquipmentIdentifier

            if self.modem is None or self.modem == eqid:
                return modem_proxy
        else:
            return {}

    def _get_modem_status_data(self, modem_proxy):
        modem_data = {}
        try:
            modem_data = modem_proxy.GetStatus()
        except:  # noqa e722
            pass
        return modem_data

    def _get_bearer(self, modem_proxy):
        bearer = {}
        try:
            bearer = modem_proxy.Bearers[0]
        except:  # noqa e722
            pass
        return bearer

    def _get_interface(self, bearer):
        return self.bus.get(STRING_MODEMMANAGER_DBUS, bearer).Interface

    def _get_message_data(self, modem_proxy):
        message_data = {}
        try:
            message_data = modem_proxy.Messages
        except:  # noqa e722
            pass
        return message_data

    def _count_messages(self, message_data):
        count_messages = len(message_data)
        count_message = max(0, count_messages - self.last_messages)
        self.last_messages = count_messages
        return count_message, count_messages

    def _manipulate_message(self, data):
        new_message = []
        for index, msg in sorted(enumerate(data, 1), reverse=True):
            try:
                sms_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, msg)
                new_message.append(
                    self.py3.safe_format(
                        self.format_message,
                        {
                            "index": index,
                            "number": sms_proxy.Number,
                            "text": sms_proxy.Text,
                        },
                    )
                )
            except:  # noqa e722
                break

        format_message_separator = self.py3.safe_format(self.format_message_separator)
        format_message = self.py3.composite_join(format_message_separator, new_message)

        return format_message

    def _get_network_config(self, bearer):
        bearer_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, bearer)
        return {"ipv4": bearer_proxy.Ip4Config, "ipv6": bearer_proxy.Ip6Config}

    def _get_stats(self, bearer):
        return self.bus.get(STRING_MODEMMANAGER_DBUS, bearer).Stats

    def _organize(self, data):
        new_data = {}
        for key, value in data.items():
            key = key.lower().replace("-", "_")
            if isinstance(value, (list, tuple)):
                if len(value) > 1:
                    for i, v in enumerate(value):
                        new_data["%s_%s" % (key, i)] = v
                elif len(value) == 1:
                    new_data[key] = value[0]
                else:
                    new_data[key] = None
            else:
                new_data[key] = value
        return new_data

    def wwan(self):
        urgent = False
        name = "_name"

        # get wwan data
        modem_proxy = self._get_modem_proxy()
        wwan_data = self._get_modem_status_data(modem_proxy)
        wwan_data = self._organize(wwan_data)

        # state and name
        key = "state"
        wwan_data[key] = wwan_data.get(key, 0)
        wwan_data[key + name] = self.network_states[wwan_data[key]]

        # if state is -1, modem failed. stop here. report error.
        # if state is less than 8, we are not connected. skip.
        # if state is 8 or more, we are connected. start work.
        if wwan_data[key] == -1:
            self.py3.error(STRING_MODEM_ERROR)
        elif wwan_data[key] < 8:
            pass
        else:
            # access technologies and name
            if self.init["access_technologies_name"]:
                key = "access_technologies"
                if wwan_data[key]:
                    bit = 1 << (wwan_data[key].bit_length() - 1)
                else:
                    bit = 0
                wwan_data[key + name] = self.network_speed[bit]

            # modem band
            if self.init["current_bands_name"]:
                key = "current_bands"
                wwan_data[key + name] = self.modem_bands[wwan_data[key]]

            # registration state and name
            if self.init["m3gpp_registration_name"]:
                key = "m3gpp_registration_state"
                new_key = key + name
                wwan_data[new_key] = self.registration_states[wwan_data[key]]

            # get bearer
            bearer = self._get_bearer(modem_proxy)
            if bearer:
                # interface name
                if self.init["interface_name"]:
                    wwan_data["interface_name"] = self._get_interface(bearer)

                # ipv4 and ipv6 network config
                if self.init["ip"]:
                    network_config = self._get_network_config(bearer)
                    format_ip = {"ipv4": self.format_ipv4, "ipv6": self.format_ipv6}
                    for ip in self.init["ip"]:
                        wwan_data["format_" + ip] = self.py3.safe_format(
                            format_ip[ip], network_config.get(ip, {})
                        )

                # network connection statistics
                if self.init["stats"]:
                    stats = self._organize(self._get_stats(bearer))
                    if stats:
                        stats["duration_hms"] = format(
                            timedelta(seconds=stats["duration"])
                        )
                    wwan_data["format_stats"] = self.py3.safe_format(
                        self.format_stats, stats
                    )

        # message and format message
        if self.init["sms_message"]:
            if wwan_data["state"] >= 1:
                message_data = self._get_message_data(modem_proxy)
                # count messages
                keys = ["message", "messages"]
                wwan_data.update(zip(keys, self._count_messages(message_data)))
                if wwan_data["message"]:
                    urgent = True

                # format sms messages
                if self.init["format_message"]:
                    wwan_data["format_message"] = self._manipulate_message(message_data)

        # thresholds
        for x in self.init["thresholds"]:
            if x in wwan_data:
                self.py3.threshold_get_color(wwan_data[x], x)

        # notifications
        if self.format_notification:

            # get a notification
            format_notification = self.py3.safe_format(
                self.format_notification, wwan_data
            )
            notification = self.py3.get_composite_string(format_notification)

            if notification and notification != self.last_notification:
                self.last_notification = notification
                self.py3.storage_set("notification", notification)
                self.py3.notify_user(notification)

        response = {
            "cached_until": self.py3.time_in(self.cache_timeout),
            "full_text": self.py3.safe_format(self.format, wwan_data),
        }
        if urgent:
            response["urgent"] = True
        return response
Пример #14
0
class Py3status:
    """
    """
    # available configuration parameters
    cache_timeout = 5
    format = ('\?color=state WW: [\?if=state_name=connected '
              '({signal_quality_0}% at {m3gpp_operator_name}) '
              '[{format_ipv4}[\?soft  ]{format_ipv6}]'
              '|{state_name}][ SMS {messages} [{format_message}]]')
    format_ipv4 = u'[{address}]'
    format_ipv6 = u'[{address}]'
    format_message = u'\?if=index<2 {number} [\?max_length=10 {text}...]'
    format_message_separator = u' '
    format_notification = None
    format_stats = u'{duration_hms}'
    modem = None
    thresholds = [(0, 'bad'), (11, 'good')]

    def post_config_hook(self):
        modem_manager = ['ModemManager', '/usr/sbin/ModemManager']
        network_manager = ['NetworkManager', '/usr/sbin/NetworkManager']
        for command in (modem_manager, network_manager):
            if not self.py3.check_commands(command):
                raise Exception('%s %s' % (command[0], STRING_NOT_INSTALLED))

        # search: modemmanager flags and enumerations
        # enum 1: #MMModemState
        # enum 2: #MMModemAccessTechnology
        # enum 3: #MMModem3gppRegistrationState
        # enum 4: #MMModemBand

        # enum 1: network states
        self.network_states = {
            -1: 'failed',
            0: 'unknown',
            1: 'initializing',
            2: 'locked',
            3: 'disabled',
            4: 'disabling',
            5: 'enabling',
            6: 'enabled',
            7: 'searching',
            8: 'registered',
            9: 'disconnecting',
            10: 'connecting',
            11: 'connected'
        }
        # enum 2: network speed
        self.network_speed = {
            0: 'Unknown',
            1 << 0: 'POTS',  # 2
            1 << 1: 'GSM',
            1 << 2: 'GSM Compact',
            1 << 3: 'GPRS',
            1 << 4: 'EDGE',
            1 << 5: 'UMTS',  # 32
            1 << 6: 'HSDPA',
            1 << 7: 'HSUPA',
            1 << 8: 'HSPA',
            1 << 9: 'HSPA+',  # 512
            1 << 10: '1XRTT',
            1 << 11: 'EVDO0',
            1 << 12: 'EVDOA',
            1 << 13: 'EVDOB',
            1 << 14: 'LTE'  # 16384
        }
        # enum 3: network registration state
        self.registration_states = {
            0: 'IDLE',
            1: 'HOME',
            2: 'SEARCHING',
            3: 'DENIED',
            4: 'UNKNOWN',
            5: 'ROAMING'
        }
        # enum 4: modem bands
        self.modem_bands = {
            0: 'Unknown or invalid band',
            1: 'GSM/GPRS/EDGE 900 MHz',
            2: 'GSM/GPRS/EDGE 1800 MHz',
            3: 'GSM/GPRS/EDGE 1900 MHz',
            4: 'GSM/GPRS/EDGE 850 MHz',
            5: 'WCDMA 2100 MHz (Class I)',
            6: 'WCDMA 3GPP 1800 MHz (Class III)',
            7: 'WCDMA 3GPP AWS 1700/2100 MHz (Class IV)',
            8: 'WCDMA 3GPP UMTS 800 MHz (Class VI)',
            9: 'WCDMA 3GPP UMTS 850 MHz (Class V)',
            10: 'WCDMA 3GPP UMTS 900 MHz (Class VIII)',
            11: 'WCDMA 3GPP UMTS 1700 MHz (Class IX)',
            12: 'WCDMA 3GPP UMTS 1900 MHz (Class II)',
            13: 'WCDMA 3GPP UMTS 2600 MHz (Class VII, internal)',
            31: 'E-UTRAN band I',
            32: 'E-UTRAN band II',
            33: 'E-UTRAN band III',
            34: 'E-UTRAN band IV',
            35: 'E-UTRAN band V',
            36: 'E-UTRAN band VI',
            37: 'E-UTRAN band VII',
            38: 'E-UTRAN band VIII',
            39: 'E-UTRAN band IX',
            40: 'E-UTRAN band X',
            41: 'E-UTRAN band XI',
            42: 'E-UTRAN band XII',
            43: 'E-UTRAN band XIII',
            44: 'E-UTRAN band XIV',
            47: 'E-UTRAN band XVII',
            48: 'E-UTRAN band XVIII',
            49: 'E-UTRAN band XIX',
            50: 'E-UTRAN band XX',
            51: 'E-UTRAN band XXI',
            52: 'E-UTRAN band XXII',
            53: 'E-UTRAN band XXIII',
            54: 'E-UTRAN band XXIV',
            55: 'E-UTRAN band XXV',
            56: 'E-UTRAN band XXVI',
            63: 'E-UTRAN band XXXIII',
            64: 'E-UTRAN band XXXIV',
            65: 'E-UTRAN band XXXV',
            66: 'E-UTRAN band XXXVI',
            67: 'E-UTRAN band XXXVII',
            68: 'E-UTRAN band XXXVIII',
            69: 'E-UTRAN band XXXIX',
            70: 'E-UTRAN band XL',
            71: 'E-UTRAN band XLI',
            72: 'E-UTRAN band XLII',
            73: 'E-UTRAN band XLIII',
            128: 'CDMA Band Class 0 (US Cellular 850MHz)',
            129: 'CDMA Band Class 1 (US PCS 1900MHz)',
            130: 'CDMA Band Class 2 (UK TACS 900MHz)',
            131: 'CDMA Band Class 3 (Japanese TACS)',
            132: 'CDMA Band Class 4 (Korean PCS)',
            134: 'CDMA Band Class 5 (NMT 450MHz)',
            135: 'CDMA Band Class 6 (IMT2000 2100MHz)',
            136: 'CDMA Band Class 7 (Cellular 700MHz)',
            137: 'CDMA Band Class 8 (1800MHz)',
            138: 'CDMA Band Class 9 (900MHz)',
            139: 'CDMA Band Class 10 (US Secondary 800)',
            140: 'CDMA Band Class 11 (European PAMR 400MHz)',
            141: 'CDMA Band Class 12 (PAMR 800MHz)',
            142: 'CDMA Band Class 13 (IMT2000 2500MHz Expansion)',
            143: 'CDMA Band Class 14 (More US PCS 1900MHz)',
            144: 'CDMA Band Class 15 (AWS 1700MHz)',
            145: 'CDMA Band Class 16 (US 2500MHz)',
            146: 'CDMA Band Class 17 (US 2500MHz Forward Link Only)',
            147: 'CDMA Band Class 18 (US 700MHz Public Safety)',
            148: 'CDMA Band Class 19 (US Lower 700MHz)',
            256: 'auto'
        }

        self.bus = SystemBus()
        self.init = {
            'ip': [],
            'sms_message': [],
            'thresholds': self.py3.get_color_names_list(self.format),
        }
        self.last_messages = 0
        self.last_notification = self.py3.storage_get('notification')

        names = [
            'current_bands_name', 'access_technologies_name',
            'm3gpp_registration_name', 'interface_name', 'ipv4', 'ipv6',
            'stats', 'format_message', 'message'
        ]
        placeholders = [
            'current_bands_name', 'access_technologies_name',
            'm3gpp_registration_name', 'interface_name', 'format_ipv4',
            'format_ipv6', 'format_stats', 'format_message', 'message*'
        ]

        # init methods
        format_strings = [self.format, self.format_notification]
        for name, placeholder in zip(names, placeholders):
            self.init[name] = []
            for format_string in format_strings:
                if format_string:  # fails on None, [], '', etc
                    if self.py3.format_contains(format_string, placeholder):
                        self.init[name].append(format_string)
                        if name in ['ipv4', 'ipv6']:
                            if name not in self.init['ip']:
                                self.init['ip'].append(name)
                        if name in ['message', 'format_message']:
                            if name not in self.init['sms_message']:
                                self.init['sms_message'].append(name)

    def _get_modem_proxy(self):
        modemmanager_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS)
        modems = modemmanager_proxy.GetManagedObjects()

        for objects in modems.items():
            modem_path = objects[0]
            modem_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, modem_path)
            eqid = modem_proxy.EquipmentIdentifier

            if self.modem is None or self.modem == eqid:
                return modem_proxy
        else:
            return {}

    def _get_modem_status_data(self, modem_proxy):
        modem_data = {}
        try:
            modem_data = modem_proxy.GetStatus()
        except:  # noqa e722
            pass
        return modem_data

    def _get_bearer(self, modem_proxy):
        bearer = {}
        try:
            bearer = modem_proxy.Bearers[0]
        except:  # noqa e722
            pass
        return bearer

    def _get_interface(self, bearer):
        return self.bus.get(STRING_MODEMMANAGER_DBUS, bearer).Interface

    def _get_message_data(self, modem_proxy):
        message_data = {}
        try:
            message_data = modem_proxy.Messages
        except:  # noqa e722
            pass
        return message_data

    def _count_messages(self, message_data):
        count_messages = len(message_data)
        count_message = max(0, count_messages - self.last_messages)
        self.last_messages = count_messages
        return count_message, count_messages

    def _manipulate_message(self, data):
        new_message = []
        for index, msg in sorted(enumerate(data, 1), reverse=True):
            try:
                sms_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, msg)
                new_message.append(
                    self.py3.safe_format(
                        self.format_message, {
                            'index': index,
                            'number': sms_proxy.Number,
                            'text': sms_proxy.Text
                        }))
            except:  # noqa e722
                break

        format_message_separator = self.py3.safe_format(
            self.format_message_separator
        )
        format_message = self.py3.composite_join(
            format_message_separator, new_message
        )

        return format_message

    def _get_network_config(self, bearer):
        bearer_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, bearer)
        return {
            'ipv4': bearer_proxy.Ip4Config,
            'ipv6': bearer_proxy.Ip6Config,
        }

    def _get_stats(self, bearer):
        return self.bus.get(STRING_MODEMMANAGER_DBUS, bearer).Stats

    def _organize(self, data):
        new_data = {}
        for key, value in data.items():
            key = key.lower().replace('-', '_')
            if isinstance(value, (list, tuple)):
                if len(value) > 1:
                    for i, v in enumerate(value):
                        new_data['%s_%s' % (key, i)] = v
                elif len(value) == 1:
                    new_data[key] = value[0]
                else:
                    new_data[key] = None
            else:
                new_data[key] = value
        return new_data

    def wwan(self):
        urgent = False
        name = '_name'

        # get wwan data
        modem_proxy = self._get_modem_proxy()
        wwan_data = self._get_modem_status_data(modem_proxy)
        wwan_data = self._organize(wwan_data)

        # state and name
        key = 'state'
        wwan_data[key] = wwan_data.get(key, 0)
        wwan_data[key + name] = self.network_states[wwan_data[key]]

        # if state is -1, modem failed. stop here. report error.
        # if state is less than 8, we are not connected. skip.
        # if state is 8 or more, we are connected. start work.
        if wwan_data[key] == -1:
            self.py3.error(STRING_MODEM_ERROR)
        elif wwan_data[key] < 8:
            pass
        else:
            # access technologies and name
            if self.init['access_technologies_name']:
                key = 'access_technologies'
                if wwan_data[key]:
                    bit = 1 << (wwan_data[key].bit_length() - 1)
                else:
                    bit = 0
                wwan_data[key + name] = self.network_speed[bit]

            # modem band
            if self.init['current_bands_name']:
                key = 'current_bands'
                wwan_data[key + name] = self.modem_bands[wwan_data[key]]

            # registration state and name
            if self.init['m3gpp_registration_name']:
                key = 'm3gpp_registration_state'
                new_key = key + name
                wwan_data[new_key] = self.registration_states[wwan_data[key]]

            # get bearer
            bearer = self._get_bearer(modem_proxy)
            if bearer:
                # interface name
                if self.init['interface_name']:
                    wwan_data['interface_name'] = self._get_interface(bearer)

                # ipv4 and ipv6 network config
                if self.init['ip']:
                    network_config = self._get_network_config(bearer)
                    format_ip = {
                        'ipv4': self.format_ipv4,
                        'ipv6': self.format_ipv6,
                    }
                    for ip in self.init['ip']:
                        wwan_data['format_' + ip] = self.py3.safe_format(
                            format_ip[ip], network_config.get(ip, {}))

                # network connection statistics
                if self.init['stats']:
                    stats = self._organize(self._get_stats(bearer))
                    if stats:
                        stats['duration_hms'] = format(
                            timedelta(seconds=stats['duration'])
                        )
                    wwan_data['format_stats'] = self.py3.safe_format(
                        self.format_stats, stats
                    )

        # message and format message
        if self.init['sms_message']:
            if wwan_data['state'] >= 1:
                message_data = self._get_message_data(modem_proxy)
                # count messages
                keys = ['message', 'messages']
                wwan_data.update(zip(keys, self._count_messages(message_data)))
                if wwan_data['message']:
                    urgent = True

                # format sms messages
                if self.init['format_message']:
                    wwan_data['format_message'] = self._manipulate_message(
                        message_data
                    )

        # thresholds
        for x in self.init['thresholds']:
            if x in wwan_data:
                self.py3.threshold_get_color(wwan_data[x], x)

        # notifications
        if self.format_notification:

            # get a notification
            format_notification = self.py3.safe_format(
                self.format_notification, wwan_data
            )
            notification = self.py3.get_composite_string(
                format_notification
            )

            if notification and notification != self.last_notification:
                self.last_notification = notification
                self.py3.storage_set('notification', notification)
                self.py3.notify_user(notification)

        response = {
            'cached_until': self.py3.time_in(self.cache_timeout),
            'full_text': self.py3.safe_format(self.format, wwan_data)
        }
        if urgent:
            response['urgent'] = True
        return response
Пример #15
0
from pydbus import SystemBus
from gi.repository import GObject

def print_state(a, b, c):
    print a
    print b.keys()
    print c

bus = SystemBus()
dev = bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/drives/TSSTcorp_CDDVDW_SE_S084C_SATASLIM00003008cae')

dev.PropertiesChanged.connect(print_state)
GObject.MainLoop().run()
Пример #16
0
class Services():
    '''
    Services provides an easy access to systemd services
    '''

    def __init__(self):
        '''
        Services constructor
        '''
        self.include_static_services = False
        self._reload = True
        self._services = {}
        self._xinetd_services = {}
        self._bus = SystemBus()
        self._systemd = self._bus.get(".systemd1")
        self._manager = self._systemd[".Manager"]

    def check_permission(action, dbus_context):
        '''
        Check authorizations
        '''
        return dbus_context.is_authorized(action, {'polkit.icon_name': 'manatools.png',}, interactive=True)
    
    @property
    def service_info(self):
        '''
        A dictionary collecting all the service information.
        if include_static_services (default is false) is set also static
        services are included.
        '''
        if not self._reload:
            return self._services
        units = self._manager.ListUnits()
        self._services = {}
        self._reload = False

        for u in units:
            unitName = u[0]
            pos = unitName.find(".service")
            if pos != -1:
                try:
                    if unitName.find("@") == -1:
                        st = self._manager.GetUnitFileState(unitName)
                        name = unitName[0:pos]
                        if st and (self.include_static_services or st != 'static'):
                            self._services[name] = {
                                'name':        u[0],
                                'description': u[1],
                                'load_state':  u[2],
                                'active_state': u[3],
                                'sub_state':   u[4],
                                'unit_path':   u[6],
                                'enabled':   st == 'enabled',
                            }
                            # TODO if not st check unit files see Services.pm:167
                except:
                    pass

        unit_files = self._manager.ListUnitFiles()
        for u in unit_files:
            unitName = u[0]
            st = u[1]
            pos = unitName.find(".service")
            if pos != -1:
                name = os.path.basename(unitName)
                name = name[0:name.find(".service")]
                if (not name in self._services.keys()) and (name.find('@') == -1) \
                   and (os.path.isfile(unitName) or os.path.isfile("/etc/rc.d/init.d/"+name)) \
                   and not os.path.islink(unitName) and (st == "disabled" or st == "enabled"):
                    self._services[name] = {
                        'name':        name+".service",
                        # 'description': ####TODO get property,
                        'description': "---",
                        'enabled':   st == 'enabled',
                    }

        return self._services

    @property
    def xinetd_services(self):
        '''
        This function returns all the xinetd services in the system.
        NOTE that xinetd *must* be enable at boot to get this info
        '''
        try:
            service_info = self.service_info()['xinetd']
            if service_info['enabled']:
                env = {'LANGUAGE': 'C', 'PATH': "/usr/bin:/usr/sbin"}
                # TODO : Change to force root command
                try:
                    chkconf = subprocess.run(['/usr/sbin/chkconfig', '--list', '--type', 'xinetd'],
                                             env=env, timeout=120, check=True, capture_output=True, text=True)
                    for serv in chkconf.stdout.strip().split('\n'):
                        servT = serv.split()
                        try:
                            self._xinetd_services[servT[0].strip(":")] = servT[1] == 'on'
                        except IndexError:
                            continue
                except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
                    # TODO return an exception to the exterior
                    print("chkconfig error when trying to list xinetd services", stderr)
        except KeyError:
            return self._xinetd_services

    def _running_systemd(self):
        # TODO : Change to force root command
        try:
            return subprocess.run(['/usr/bin/mountpoint', '-q', '/sys/fs/cgroup/systemd'], env={'PATH': '/usr/bin:/usr/sbin'}, timeout=120).returncode == 0
        except subprocess.TimeoutExpired:
            # TODO : return an exception outside of the function
            print("moutnpoint error when checking systemd: timeout expired.\n")
            return False

    def _has_systemd(self):
        # TODO : Change to force root command
        try:
            return subprocess.run(['/usr/bin/rpm', '-q', 'systemd'], env={'PATH': '/usr/bin:/usr/sbin'}, timeout=120).returncode == 0
        except subprocess.TimeoutExpired:
            # TODO : return an exception outside of the function
            print("rpm error when checking systemd: timeout expired.\n")
            return False

    def set_service(self, service, enable):
        '''
        This function enable/disable at boot the given service
        '''
        # NOTE EnableUnitFiles and DisableUnitFiles don't work with legacy services
        #      and return file not found
        legacy = os.path.isfile("/etc/rc.d/init.d/{}".format(service))
        if service in self._xinetd_services.keys():
            env = {'LANGUAGE': 'C', 'PATH': "/usr/bin:/usr/sbin"}
#            if dbus_context.is_authorized('org.freeedesktop.policykit.exec', {'polkit.icon': 'abcd', 'aaaa': 'zzzz'}, interactive=True):
            #     try:
            #         chkconf = subprocess.run(['/usr/sbin/chkconfig', "-add" if enable else "--del",
            #                                   service], env=env, timeout=120, check=True, capture_output=True, text=True)
            #     except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            #         # TODO return an exception to the exterior
            #         print("chkconfig error when trying to add/delete service", stderr)
            # else:
            #     # TODO return an excpetion to the exterior
            #     print("You are not authorized to perform this action", stderr)

        elif not legacy and (self._running_systemd() or self._has_systemd()):
            service = "{}.service".format(service)
            if enable:
 #               if self.check_permission(self._manager.EnableUnitFiles(), dbus_context):
#                    self._manager.EnableUnitFiles([service.encode()], False, True)
                
Пример #17
0
#!/usr/bin/python3
# Based on http://stackoverflow.com/questions/22390064/use-dbus-to-just-send-a-message-in-python

# Python script to call the methods of the DBUS Test Server

from pydbus import SystemBus
import sys

#get the session bus
bus = SystemBus()

o2  = bus.get("org.freedesktop.DBus")


pat = "it.pook.DelcomClock."
if len(sys.argv) > 1:
    name = pat + sys.argv[1]
else:
    for n in o2.ListNames():
        if n.startswith("it.pook.DelcomClock."):
            name = n
            break
    else:
        sys.exit("no delcom")
print("anme", name)

#get the object
the_object = bus.get(name)

#call the methods and print the results
reply = the_object.Hello()
Пример #18
0
class BatteryApp:

  def __init__(self):
    self.prefix = 'B:'
    self.separator = '/'
    self.suffix = ' '
    self.tooltip_heading = 'Battery Status:\n'

    self.low_battery_alarm_threshold = 5
    self.low_battery_alarm_visible = False

    self.build_ui()

    self.dbus = SystemBus()
    self.upower = self.dbus.get('.UPower', '/org/freedesktop/UPower')
    self.battery_subscriptions = []
    self.upower.DeviceAdded.connect(lambda name, vals, a: self.get_upower_batteries())
    self.upower.DeviceRemoved.connect(lambda name, vals, a: self.get_upower_batteries())
    self.get_upower_batteries()
    self.start_signal_thread()

  def build_ui(self):
    self.tray = tray = Gtkti.TrayIcon()
    self.eventbox = eventbox = Gtk.EventBox()
    eventbox.set_tooltip_text(self.tooltip_heading+'Unknown')
    tray.add(eventbox)
    self.tray_label = tray_label = Gtk.Label(self.prefix+'?'+self.suffix)
    eventbox.add(tray_label)
    tray.show_all()

    menu = Gtk.Menu()
    item_quit = Gtk.MenuItem('Quit')
    def quit(menu_item):
      if sys.version_info < (3, 0):
        os.kill(os.getpid(), signal.SIGINT)
      else:
        Gtk.main_quit()
    item_quit.connect('activate', quit)
    menu.append(item_quit)
    menu.show_all()
    def button_pressed(eventbox, event, menu=menu):
      if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
        menu.popup(None, None, None, None, event.button, event.time)
    eventbox.connect('button-press-event', button_pressed)

  # Update the UI (thread-safe)
  def update_ui(self):
    GLib.idle_add(self.gtk_update_ui)

  # Update the UI (within the GTK main thread ; not thread-safe)
  def gtk_update_ui(self):
    display_str = ''
    tooltip_str = ''
    max_percentage = 0
    for battery in self.upower_batteries:
      if display_str:
        display_str += '/'
        tooltip_str += '\n'
      tooltip_str += battery.NativePath+': '
      state = battery.State
      if state == 1 or state == 5:
        tooltip_str += 'Charging ('+str(battery.Percentage)+'%)'
        display_str += str(int(battery.Percentage))+'+'
      elif state == 2 or state == 3 or state == 6:
        tooltip_str += 'Discharging ('+str(battery.Percentage)+'%)'
        display_str += str(int(battery.Percentage))+'-'
      elif state == 4:
        tooltip_str += 'Full ('+str(battery.Percentage)+'%)'
        display_str += str(int(battery.Percentage))
      else:
        tooltip_str += 'Unknown ('+str(battery.Percentage)+'%)'
        display_str += '?'
      if battery.TimeToFull:
        m, s = divmod(battery.TimeToFull, 60)
        h, m = divmod(m, 60)
        tooltip_str += ', Remaining Charge Time: '+('%dh %02dm %02ds' % (h, m, s))
      if battery.TimeToEmpty:
        m, s = divmod(battery.TimeToEmpty, 60)
        h, m = divmod(m, 60)
        tooltip_str += ', Remaining Discharge Time: '+('%dh %02dm %02ds' % (h, m, s))
      if battery.Percentage > max_percentage:
        max_percentage = battery.Percentage
    self.tray_label.set_text(self.prefix+display_str+self.suffix)
    self.eventbox.set_tooltip_text(self.tooltip_heading+tooltip_str)
    if max_percentage < self.low_battery_alarm_threshold and not self.low_battery_alarm_visible:
      self.low_battery_alarm_visible = True
      dialog = Gtk.Dialog()
      dialog.set_title('Warning')
      dialog.set_default_size(250, 100)
      label = Gtk.Label('Low Battery')
      dialog.get_content_area().add(label)
      dialog.add_button('_Close', -1)  # GTK_RESPONSE_NONE == -1
      def close_pressed(dialog, response_id, self=self):
        self.low_battery_alarm_visible = False
        dialog.destroy()
      dialog.connect('response', close_pressed)
      dialog.show_all()

    # Return false to unregister this method as a GLib idle handler
    return False

  def get_upower_batteries(self):
    paths = self.upower.EnumerateDevices()
    devices = map(lambda p: self.dbus.get('.UPower', p), paths)
    batteries = filter(lambda d: d.Type == 2, devices)
    for s in self.battery_subscriptions:
      s.disconnect()
    self.battery_subscriptions = []
    for battery in batteries:
      s = battery.PropertiesChanged.connect(lambda name, vals, a: self.update_ui())
      self.battery_subscriptions.append(s)
    self.upower_batteries = batteries
    self.update_ui()

  def start_signal_thread(self):
    thread = threading.Thread(target=GLib.MainLoop().run)
    thread.daemon = True
    thread.start()
Пример #19
0
class NetworkManager(EventDispatcher, Thread):

    connected_ssid = StringProperty()
    connection_type = OptionProperty("none", options=["none", "ethernet", "wireless"])

    def __init__(self, **kwargs):
        self.available = False
        super().__init__(**kwargs)

        self.loop = GLib.MainLoop()
        self.bus = SystemBus()

        # ID used to cancel the scan timer and to find out whether it is running
        # Will be None whenever the timer isn't running
        self.scan_timer_id = None
        self.new_connection_subscription = None
        self.access_points = []
        self.saved_ssids = []

        # Register kivy events
        self.register_event_type('on_access_points')
        self.register_event_type('on_connect_failed')

        # Get proxy objects
        try:
            self.nm = self.bus.get(_NM, "/org/freedesktop/NetworkManager")
        except GLib.GError as e:
            # Occurs when NetworkManager was not installed
            if "org.freedesktop.DBus.Error.ServiceUnknown" in e.message:
                return # Leaves self.available = False
            raise

        self.settings = self.bus.get(_NM, "/org/freedesktop/NetworkManager/Settings")
        devices = self.nm.Devices # Type: ao
        self.eth_dev = self.wifi_dev = None
        for dev in devices:
            dev_obj = self.bus.get(_NM, dev)
            if dev_obj.Capabilities & 0x1: # NetworkManager supports this device
                if dev_obj.DeviceType == 1: # a wired ethernet device
                    self.eth_dev = dev_obj
                elif dev_obj.DeviceType == 2: # an 802.11 Wi-Fi device
                    self.wifi_dev = dev_obj
        # For simplicity require both devices to be available
        if not(self.eth_dev and self.wifi_dev):
            return # Leaves self.available = False
        #UNUSED Does the wifi device support 5gGHz (flag 0x400)
        #self.freq_5ghz = bool(self.wifi_dev.WirelessCapabilities & 0x400)

        # Connect DBus signals to their callbacks
        # Pick out the .DBus.Properties interface because the .NetworkManager
        # interface overwrites that with a less functioning one.
        nm_prop = self.nm['org.freedesktop.DBus.Properties']
        nm_prop.PropertiesChanged.connect(self._handle_nm_props)
        wifi_prop = self.wifi_dev['org.freedesktop.DBus.Properties']
        wifi_prop.PropertiesChanged.connect(self._handle_wifi_dev_props)
        # Initiate the values handled by signal handlers by simply
        # sending all the properties that are being listened to.
        self._handle_nm_props(None, self.nm.GetAll('org.freedesktop.NetworkManager'), None)
        self._handle_wifi_dev_props(None, self.wifi_dev.GetAll(_NM + ".Device"), None)
        self._handle_wifi_dev_props(None, self.wifi_dev.GetAll(_NM + ".Device.Wireless"), None)

        self.available = True

    def run(self):
        """
        Executed by Thread.start(). This thread stops when this method finishes.
        Stop the loop by calling self.loop.quit().
        """
        self.loop.run()

    def stop(self):
        self.loop.quit()


    def _handle_nm_props(self, iface, props, inval):
        """Receives all property changes of self.nm"""
        if "PrimaryConnectionType" in props:
            # Connection Type changed
            con_type = props['PrimaryConnectionType']
            if con_type == '802-3-ethernet':
                self.connection_type = "ethernet"
            elif con_type == '802-11-wireless': # Wi-Fi connected
                self.connection_type = "wireless"
            else: # No active connection
                self.connection_type = "none"

    def _handle_wifi_dev_props(self, iface, props, inval):
        """
        Receives all property changes of self.wifi_dev and calls the
        appropriate methods.
        """
        if "LastScan" in props:
            self._handle_scan_complete()
        if "ActiveAccessPoint" in props:
            self._handle_connected_ssid(props['ActiveAccessPoint'])

    def _handle_new_connection(self, state, reason):
        """
        Receives state changes from newly added connections.
        Required to ensure everything went OK and to dispatch events
        in case it didn't.  The most important case would be a wrong
        password which isn't clearly identifiable from the reason.

        The signal subscription will be canceled when the connection
        was successfully activated.
        """
        if state > 2: # DEACTIVATING or DEACTIVATED
            self.dispatch('on_connect_failed')
        if state in (2, 4): # ACTIVATED or DEACTIVATED
            # done, no need to listen further
            self.new_connection_subscription.disconnect()

    def _handle_scan_complete(self):
        """
        Called on changes in wifi_dev.LastScan, which is changed whenever
        a scan completed.  Parses the access points into wrapper objects
        containing the relevant attributes and methods

        WARNING: Because of some DBus calls, this function can take
        from 0.5 up to 5 seconds to complete.
        """
        # Needed to accurately build AccessPoint objects
        self.saved_ssids = self.get_saved_ssids()
        access_points = []
        for path in self.wifi_dev.AccessPoints:
            try:
                ap = AccessPoint(self, path)
            except: # DBus sometimes throws a random error here
                continue
            # Ignore unnamed access points
            if ap.ssid:
                access_points.append(ap)
        # Sort by signal strength, frequency and then by 'in-use'
        access_points.sort(key=lambda x: x.signal, reverse=True)
        # We only really want to differentiate between 2.4 GHz and 5 GHz
        access_points.sort(key=lambda x: x.freq // 2000, reverse=True)
        access_points.sort(key=lambda x: x.in_use, reverse=True)

        # Filter out access points with duplicate ssids
        seen_ssids = set()
        unique_aps = []
        for ap in access_points:
            # Because access_points are already sorted most wanted first
            # we just add the first occurence of each ssid
            if ap.ssid not in seen_ssids:
                unique_aps.append(ap)
                seen_ssids.add(ap.ssid)
        self.access_points = unique_aps # update the property
        self.dispatch('on_access_points', self.access_points)

    def _handle_connected_ssid(self, active_path):
        """
        Called whenever the active wifi connection changes.
        Sets the ssid of the currently connected wifi connection.
        If no wifi connection currently exists, set "".

        active_path references the AccessPoint object currently in use.
        """
        if active_path == "/":
            # There is no wifi connection right now
            self.connected_ssid = ""
        else:
            active = self.bus.get(_NM, active_path)
            self.connected_ssid = _bytes_to_string(active.Ssid)


    def set_scan_frequency(self, freq):
        """
        Set the frequency at which to scan for wifi networks.
        freq is the frequency in seconds and should be an int.
        If freq is 0, the rescan clock is cancelled.
        """
        if freq == 0:
            if self.scan_timer_id:
                GLib.source_remove(self.scan_timer_id)
                self.scan_timer_id = None
        else:
            self.scan_timer_id = GLib.timeout_add_seconds(freq, self.wifi_scan)

    def wifi_scan(self):
        """
        Request a rescan on the wifi device.

        When finished, self._handle_scan_complete() is called.  In case
        the previous scan is still running a new scan isn't allowed and
        this method returns False, otherwise True.
        """
        try:
            # Provide empty dict to scan for all ssids
            self.wifi_dev.RequestScan({})
            return True
        except GLib.GError as e:
            if "org.freedesktop.NetworkManager.Device.NotAllowed" in e.message:
                return False
            raise

    def wifi_connect(self, ap, password=None):
        """
        From AccessPoint and password as plaintext string get all the
        information needed to either create and connect or just connect
        the connection.

        This method is likely to raise a ValueError or GLib.GError in
        AddAndActivateConnection.  Exception catching is advised.

        Returns path to the new connection (in settings)
        """
        if ap._path not in self.wifi_dev.AccessPoints:
            # Network got out of view since previous scan
            raise ValueError("Network " + ap.ssid + " is not in view.")
        if ap.encrypted:
            if not ap.supports_psk:
                raise Exception("Access Point " + ap.ssid + " doesn't support PSK verification")
            if password is None:
                raise ValueError("No password provided")
            password = GLib.Variant('s', password)
            connection_info = {'802-11-wireless-security': {'psk': password}} # Type: a{sa{sv}}
            con, act_path = self.nm.AddAndActivateConnection(
                connection_info, self.wifi_dev._path, ap._path)
        else:
            # Open network, no password needed
            con, act_path = self.nm.AddAndActivateConnection(
                {}, self.wifi_dev._path, ap._path)
        active = self.bus.get(_NM, act_path)
        self.new_connection_subscription = active.StateChanged.connect(self._handle_new_connection)
        self.wifi_scan()
        return con

    def wifi_up(self, ap):
        """Activate a connection that is already stored"""
        if not (ap._path in self.wifi_dev.AccessPoints and ap.saved):
            raise Exception("Can't activate connection " + ap.ssid)
        active = self.nm.ActivateConnection("/", self.wifi_dev._path, ap._path)
        active = self.bus.get(_NM, active)
        self.new_connection_subscription = active.StateChanged.connect(self._handle_new_connection)
        self.wifi_scan()

    def wifi_down(self):
        """Deactivate the currently active wifi connection, if any"""
        active = self.wifi_dev.ActiveConnection
        if active == "/":
            return False
        self.nm.DeactivateConnection(active)
        self.wifi_scan()
        return True

    def wifi_delete(self, ap):
        """Delete a saved connection"""
        connection_paths = self.settings.Connections # Type: ao
        for path in connection_paths:
            con = self.bus.get(_NM, path)
            settings = con.GetSettings() # Type: a{sa{sv}}
            if '802-11-wireless' in settings: # Only check wifi connections
                if ap.b_ssid == settings['802-11-wireless']['ssid']:
                    con.Delete()
                    self.wifi_scan()
                    return True
        return False

    def get_saved_ssids(self):
        """Return list of ssid bytearrays of all stored Wi-Fi connections"""
        connection_paths = self.settings.Connections # Type: ao
        ssids = []
        for path in connection_paths:
            con = self.bus.get(_NM, path)
            settings = con.GetSettings() # Type: a{sa{sv}}
            if '802-11-wireless' in settings: # Wired connections don't have ssids
                ssid_b = settings['802-11-wireless']['ssid']
                ssids.append(ssid_b)
        return ssids

    def get_ip4_address(self):
        """
        Return the IPv4 Address of the network device currently in use.
        Return None if there is no active connection.
        """
        active_path = self.nm.PrimaryConnection
        if active_path == "/":
            return None
        active = self.bus.get(_NM, active_path)
        config = self.bus.get(_NM, active.Ip4Config)
        return config.AddressData[0]['address'] # Type: aa{sv}

    def get_connection_strength(self):
        """
        Return the connection strength in percent of the currently connected
        wifi access point.  If no wifi connection currently exists, return None.
        """
        active_ap_path = self.wifi_dev.ActiveAccessPoint
        if active_ap_path == "/":
            # There is no wifi connection right now
            return None
        active_ap = self.bus.get(_NM, active_ap_path)
        return active_ap.Strength

    def on_access_points(self, aps):
        pass
    def on_connect_failed(self):
        pass
Пример #20
0
#!/usr/bin/python3
from pydbus import SessionBus,SystemBus

BATTERY_LEVELS = ""

CHARGING_FULL = ''
CHARGING = ''

sys = SystemBus()
power = sys.get('.UPower')

all_capacity = 0
all_rate = 0

charge_time = 0
bat_no = 0

percentages = []

all_full = True

for a in power.EnumerateDevices():
    dev = sys.get('.UPower', a)
    # check if battery
    if dev.Type == 2:
        # change all full, if not all fully charged
        if dev.State != 4:
            all_full = False
        # check if battery is charging
        if dev.State == 1:
            charge_time += (dev.EnergyFull - dev.Energy) / dev.EnergyRate
Пример #21
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Connects the interface applications (cli and gui) with the backend daemon.

See also :mod:`weresync.daemon.daemon`"""
from pydbus import SystemBus
from gi.repository import GLib
import threading
import gi.repository.GLib

try:
    bus = SystemBus()
    drive_copier = bus.get("net.manilas.weresync.DriveCopier")
    copy_drive = drive_copier.CopyDrive
    """A function which connects to :meth:`weresync.daemon.device.copy_drive`:.
    For arguments see that function's documentation. If False, WereSync failed
    to connect to dbus."""
    error = None
except gi.repository.GLib.Error as e:
    error = e
    """The error created by connecting to dbus. If no error, then None."""
    copy_drive = False


def _unthreaded_subscribe_to_signals(partition_status_callback,
                                     copy_status_callback,
                                     boot_status_callback):
    drive_copier.PartitionStatus.connect(partition_status_callback)
Пример #22
0
 def post_config_hook(self):
     bus = SystemBus()
     systemd = bus.get('org.freedesktop.systemd1')
     self.systemd_unit = bus.get('.systemd1', systemd.LoadUnit(self.unit))
Пример #23
0
#INITIALIZATION
app = Flask(__name__)
app.config.from_object(__name__)
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
login_manager = LoginManager()
login_manager.init_app(app)
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
mail = Mail(app)

bus = SystemBus()
bus.timeout = -1
sysd = bus.get("org.freedesktop.systemd1")
sysd.get_unit = types.MethodType(lambda self,name: self._bus.get('.systemd1',self.LoadUnit(name)[0]), sysd)

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    mail.send(msg)

#DATABASE MODEL
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(10), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey("roles.id"))