Ejemplo n.º 1
0
def main():
    """
    The script's main function.
    """

    # Sets up exception hook
    sys.excepthook = fail

    # Gets script arguments
    args = get_args()

    # If the "version" argument is present, prints version and exit
    if (args.version):
        version()

    # Attempts to connect to the bus specified via command line arguments
    if (args.system):
        bus = pydbus.SystemBus()
    elif (args.session):
        bus = pydbus.SessionBus()
    else:
        bus = pydbus.connect(args.bus)

    # Request bus name, register object and run loop
    loop = GObject.MainLoop()
    bus.request_name(args.name)
    bus.register_object('/org/mpris/MediaPlayer2', MediaPlayer2(args.identity),
                        MediaPlayer2.__doc__)
    vprint('Registered object to the message bus.')
    loop.run()
Ejemplo n.º 2
0
    def get_new_connection(self):
        """Get an Anaconda bus connection."""
        if DBUS_ANACONDA_SESSION_ADDRESS in os.environ:
            bus_address = os.environ.get(DBUS_ANACONDA_SESSION_ADDRESS)
        elif os.path.exists(ANACONDA_BUS_ADDR_FILE):
            with open(ANACONDA_BUS_ADDR_FILE, 'rt') as f:
                bus_address = f.read().strip()
        else:
            raise ConnectionError("Can't find Anaconda bus address!")

        log.info("Connecting to an Anaconda bus at %s.", bus_address)
        return pydbus.connect(bus_address)
Ejemplo n.º 3
0
    def get_new_connection(self):
        """Get an Anaconda bus connection."""
        if DBUS_ANACONDA_SESSION_ADDRESS in os.environ:
            bus_address = os.environ.get(DBUS_ANACONDA_SESSION_ADDRESS)
        elif os.path.exists(ANACONDA_BUS_ADDR_FILE):
            with open(ANACONDA_BUS_ADDR_FILE, 'rt') as f:
                bus_address = f.read().strip()
        else:
            raise ConnectionError("Can't find Anaconda bus address!")

        log.info("Connecting to an Anaconda bus at %s.", bus_address)
        return pydbus.connect(bus_address)
Ejemplo n.º 4
0
    def __enter__(self):

        # SIGTERMs should also lead to __exit__() being called. Note that
        # SIGINTs/KeyboardInterrupts are already handled by GLib.MainLoop
        signal.signal(signal.SIGTERM, self._sigterm_handler)

        if self._config['bus'] == 'session' or self._config['bus'] is None:
            self._bus = SessionBus()
        elif self.args.bus == 'system':
            self._bus = SystemBus()
        else:
            self._bus = connect(self._config['bus'])

        if self._mocker:
            self._signal = self._bus.get('org.signalbot.signalclidbusmock')
        else:
            self._signal = self._bus.get('org.asamk.Signal')
        self._signal.onMessageReceived = self._triagemessage

        # Actively discourage chdir in plugins, see _triagemessage
        self._fakecwd = TemporaryDirectory()
        Path(self._fakecwd.name).chmod(S_IEXEC)
        chdir(self._fakecwd.name)

        try:
            self._plugin_routers = {}
            self._chats = Chats(bot=self)
            for plugin in self._config['plugins']:
                self._init_plugin(plugin)
            for plugin in self._config['testing_plugins']:
                self._init_plugin(plugin, test=True)

            self._loop = GLib.MainLoop()
            self._thread = Thread(daemon=True, target=self._loop.run)
            self._thread.start()

            if self._config['startup_notification']:
                for master in self._config['master']:
                    master_chat_id = Chats.get_id_from_sender_and_group_id(
                        master)
                    master_chat = self._chats.get(master_chat_id, store=True)
                    self.send_success('Always at your service!', [],
                                      master_chat)

        except Exception as e:
            # Try not to leave empty temporary directories behind when e.g. a
            # plugin fails to load
            Path(self._fakecwd.name).chmod(S_IREAD)
            self._fakecwd.cleanup()
            raise e

        return self
Ejemplo n.º 5
0
    def get_new_connection(self):
        """Get a default bus connection.

        Connect to the bus specified by the environmental variable
        DBUS_STARTER_ADDRESS. If it is not specified, connect to
        the Anaconda bus.
        """
        if DBUS_STARTER_ADDRESS in os.environ:
            bus_address = os.environ.get(DBUS_STARTER_ADDRESS)
            log.info("Connecting to a default bus at %s.", bus_address)
            return pydbus.connect(bus_address)

        return super().get_new_connection()
Ejemplo n.º 6
0
    def get_new_connection(self):
        """Get a default bus connection.

        Connect to the bus specified by the environmental variable
        DBUS_STARTER_ADDRESS. If it is not specified, connect to
        the Anaconda bus.
        """
        if DBUS_STARTER_ADDRESS in os.environ:
            bus_address = os.environ.get(DBUS_STARTER_ADDRESS)
            log.info("Connecting to a default bus at %s.", bus_address)
            return pydbus.connect(bus_address)

        return super().get_new_connection()
Ejemplo n.º 7
0
def get_bus():
    """Get a DBUS bus connection corresponding to the current environment.

    During normal usage this function should return connection to the system bus,
    but during testing/development a custom bus might be used.
    So just always connect to the bus specified by the DBUS_STARTER_ADDRESS
    environmental variable.
    """
    bus_address = os.environ.get("DBUS_STARTER_ADDRESS")
    if bus_address:
        return pydbus.connect(os.environ["DBUS_STARTER_ADDRESS"])
    else:
        log.critical("DBUS_STARTER_ADDRESS not defined, can't use DBUS!")
        raise RuntimeError("DBUS_STARTER_ADDRESS not defined in environment")
Ejemplo n.º 8
0
def get_bus(request, get_environment, create_session_bus):
    """
    Provide the session bus instance.

    Adapted from: https://github.com/martinpitt/python-dbusmock/blob/master/dbusmock/testcase.py#L137  # noqa
    """
    # Fixture finalization / executing teardown code pytest
    # supports execution of fixture specific finalization code
    # when the fixture goes out of scope.
    # By using a yield statement instead of return,
    # all the code after the yield
    # statement serves as the teardown code.:
    # if os.environ.get('DBUS_SESSION_BUS_ADDRESS'):
    if get_environment["DBUS_SESSION_BUS_ADDRESS"]:
        print("[get_bus] inside if environment['DBUS_SESSION_BUS_ADDRESS']")
        bus = connect(get_environment["DBUS_SESSION_BUS_ADDRESS"])
        # yield bus
        # print("teardown new session bus")
        # return dbus.bus.BusConnection(os.environ['DBUS_SESSION_BUS_ADDRESS'])
    else:
        print("\n[get_bus] default SessionBus")
        bus = SessionBus()

    def teardown():
        """
        As historical note, another way to write teardown code is by
        accepting a request object into your fixture function and can
        call its request.addfinalizer one or multiple times:
        """
        # NOTE: # SessionBus() and SystemBus() are not closed automatically, so this should work
        # source: https://github.com/xZise/pydbus/blob/addf3913368cdc7225039525f3e53ab62b2a0f70/pydbus/bus.py#L31
        # NOTE: bus.dbus = @property from pydbus bus object.
        # NOTE: When you try to grab the property and it doesn't exist,
        # NOTE: it assigns a dbus connection again via: self._dbus = self.get(".DBus")[""]
        # NOTE: That's why we delete it each time
        # print("running: bus.con.close()")
        # bus.con.close()

        print("running: del bus._dbus")
        del bus._dbus

    # The finalizer is called after all of the tests that use the fixture.
    # If you’ve used parameterized fixtures,
    # the finalizer is called between instances of the parameterized fixture changes.
    request.addfinalizer(teardown)

    bus.dbus

    return bus
Ejemplo n.º 9
0
    def get_new_connection(self):
        """Get a default bus connection.

        Connect to the bus specified by the environmental variable
        DBUS_STARTER_ADDRESS. If it is not specified, connect to
        the session bus.
        """
        if DBUS_STARTER_ADDRESS in os.environ:
            bus_address = os.environ.get(DBUS_STARTER_ADDRESS)
        elif DBUS_ANACONDA_SESSION_ADDRESS in os.environ:
            bus_address = os.environ.get(DBUS_ANACONDA_SESSION_ADDRESS)
        else:
            raise ConnectionError("Can't find usable bus address!")

        log.info("Connecting to a default bus at %s.", bus_address)
        return pydbus.connect(bus_address)
Ejemplo n.º 10
0
    def get_new_connection():
        """Get a DBus connection.

        You shouldn't create new connections unless there is a good
        reason for it. Use DBus.get_connection instead.

        Normally this method should return a connection to the system
        bus, but during testing/development a custom bus might be used.
        So just always connect to the bus specified by the environmental
        variable DBUS_STARTER_ADDRESS.
        """
        bus_address = os.environ.get("DBUS_STARTER_ADDRESS")

        if bus_address:
            log.info("Connecting to DBus at %s.", bus_address)
            return pydbus.connect(bus_address)

        log.info("Connecting to system DBus.")
        return pydbus.SystemBus()
Ejemplo n.º 11
0
    def start(self):

        # Load requested plugins
        self.plugins = [
            importlib.import_module('plugins.' + plugin).__plugin__(self)
            for plugin in self.args.plugins
        ]

        # Start listening for messages
        if self.args.bus == 'session' or self.args.bus is None:
            bus = SessionBus()
        elif self.args.bus == 'system':
            bus = SystemBus()
        else:
            bus = connect(self.args.bus)

        self.signal = bus.get('org.asamk.Signal')
        self.signal.onMessageReceived = self.receive

        loop = GLib.MainLoop()
        loop.run()
Ejemplo n.º 12
0
def main():
    """
    The script's main function.
    """

    # Sets up exception hook
    sys.excepthook = fail

    # Gets script arguments
    args = get_args()

    # If the "version" argument is present, prints version and exit
    if (args.version):
        version()

    # Creates a list for storing data on found players
    player_list = list()

    # Attempts to connect to the bus specified via command line arguments
    if (args.system):
        bus = pydbus.SystemBus()
    elif (args.session):
        bus = pydbus.SessionBus()
    else:
        bus = pydbus.connect(args.bus)

    # Gets names and proxy objects, and appends them to the list of found
    # players
    names = get_mpris_names(bus)
    for name in names:
        proxy = get_proxy_object(bus, name)
        player_list.append({'name': name, 'proxy': proxy})

    # Prints information about each player found
    for player in player_list:
        print_player_info(player, args.color)
Ejemplo n.º 13
0
from pydbus import SessionBus, connect
import os

DBUS_SESSION_BUS_ADDRESS = os.getenv("DBUS_SESSION_BUS_ADDRESS")

with connect(DBUS_SESSION_BUS_ADDRESS) as bus:
    bus.dbus

del bus._dbus
try:
    bus.dbus
    assert (False)
except RuntimeError:
    pass

with SessionBus() as bus:
    pass

# SessionBus() and SystemBus() are not closed automatically, so this should work:
bus.dbus

with bus.request_name("net.lew21.Test"):
    pass

with bus.request_name("net.lew21.Test"):
    pass

with bus.request_name("net.lew21.Test"):
    try:
        bus.request_name("net.lew21.Test")
        assert (False)
Ejemplo n.º 14
0
def new_bus(type_) -> Bus:
    return connect(Gio.dbus_address_get_for_bus_sync(type_))
Ejemplo n.º 15
0
 def get_new_connection(self):
     """Get a connection to a bus at the specified address."""
     log.info("Connecting to a bus at %s.", self._address)
     return pydbus.connect(self._address)
Ejemplo n.º 16
0
from pydbus import SessionBus, connect
import os

DBUS_SESSION_BUS_ADDRESS = os.getenv("DBUS_SESSION_BUS_ADDRESS")

with connect(DBUS_SESSION_BUS_ADDRESS) as bus:
	bus.dbus

del bus._dbus
try:
	bus.dbus
	assert(False)
except RuntimeError:
	pass

with SessionBus() as bus:
	pass

# SessionBus() and SystemBus() are not closed automatically, so this should work:
bus.dbus

with bus.request_name("net.lew21.Test"):
	pass

with bus.request_name("net.lew21.Test"):
	pass

with bus.request_name("net.lew21.Test"):
	try:
		bus.request_name("net.lew21.Test")
		assert(False)
Ejemplo n.º 17
0
 def get_new_connection(self):
     """Get a connection to a bus at the specified address."""
     log.info("Connecting to a bus at %s.", self._address)
     return pydbus.connect(self._address)
Ejemplo n.º 18
0
    target_file_path = os.path.join(temp_service_dir.name, filename)
    shutil.copy(file_path, target_file_path)

test_dbus = Gio.TestDBus()

# set service folder
test_dbus.add_service_dir(temp_service_dir.name)

try:
    # start the custom DBUS daemon
    print("starting custom dbus session")
    test_dbus.up()
    print(test_dbus.get_bus_address())

    # our custom bus is now running, connect to it
    test_dbus_connection = pydbus.connect(test_dbus.get_bus_address())

    print("starting Boss")
    test_dbus_connection.dbus.StartServiceByName(dbus_constants.DBUS_BOSS_NAME,
                                                 0)

    input("press any key to stop Boss and cleanup")

    print("stopping Boss")

    boss_object = test_dbus_connection.get(dbus_constants.DBUS_BOSS_NAME)
    boss_object.Quit()

    print("waiting a bit for module shutdown to happen")
    time.sleep(1)