Exemplo n.º 1
0
def test_object_method_call(dbus_service):
    """
    Register and call methods on a dbus object.
    """
    def str_response(body=''):
        return 's', (body, )

    interface = 'com.example.interface1'
    add0 = DBusAddress('/path', dbus_service.name)
    add1 = DBusAddress('/path/subpath', dbus_service.name)
    add2 = DBusAddress('/path', dbus_service.name, interface=interface)
    add3 = DBusAddress('/path/subpath', dbus_service.name, interface=interface)

    hello0 = partial(str_response, body='Hello0')
    hello1 = partial(str_response, body='Hello1')
    hello2 = partial(str_response, body='Hello2')
    hello3 = partial(str_response, body='Hello3')

    dbus_service.set_handler(add0.object_path, 'hello0', hello0)
    dbus_service.set_handler(add1.object_path, 'hello1', hello1)
    dbus_service.set_handler(add2.object_path, 'hello2', hello2, interface)
    dbus_service.set_handler(add3.object_path, 'hello3', hello3, interface)

    dbus_service.listen()
    conn = connect_and_authenticate()

    response = conn.send_and_get_reply(new_method_call(add0, 'hello0'))
    assert response == ('Hello0', )
    response = conn.send_and_get_reply(new_method_call(add1, 'hello1'))
    assert response == ('Hello1', )
    response = conn.send_and_get_reply(new_method_call(add2, 'hello2'))
    assert response == ('Hello2', )
    response = conn.send_and_get_reply(new_method_call(add3, 'hello3'))
    assert response == ('Hello3', )
Exemplo n.º 2
0
    def __init__(self):
        from jeepney import DBusAddress, Properties, new_method_call
        # Prefer desktop portal interface here since it can theoretically
        # work with network management solutions other than NetworkManager
        # and is controlled by the current desktop session
        #
        # There is no difference in terms of “features” provided between
        # the two APIs from our point of view.
        self.xdp_call = lambda: new_method_call(
            DBusAddress('/org/freedesktop/portal/desktop',
                        bus_name='org.freedesktop.portal.Desktop',
                        interface="org.freedesktop.portal.NetworkMonitor"),
            'GetConnectivity')
        self.nm_call = lambda: Properties(
            DBusAddress('/org/freedesktop/NetworkManager',
                        bus_name='org.freedesktop.NetworkManager',
                        interface="org.freedesktop.NetworkManager")).get(
                            'Connectivity')

        if self.xdp() is not None:
            self.get_connectivity = self.xdp
        elif self.nm() is not None:
            self.get_connectivity = self.nm
        else:
            self.get_connectivity = lambda: 4
Exemplo n.º 3
0
def get_info_mpris2(name):
    """
    Get the current playing song from an mpris2 compliant player.
    """
    # qdbus org.mpris.MediaPlayer2.<name> /org/mpris/MediaPlayer2\
    # org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadat
    bus_name = 'org.mpris.MediaPlayer2.' + name
    path = '/org/mpris/MediaPlayer2'
    interface = 'org.mpris.MediaPlayer2.Player'
    address = DBusAddress(path, bus_name=bus_name, interface=interface)
    msg = Properties(address).get('Metadata')
    connection = connect_and_authenticate()
    response = connection.send_and_get_reply(msg)
    metadata = dict(response[0][1])
    keys = ['album', 'title', 'artist', 'albumartist']

    info = {}
    metadata = {k: v for k, v in metadata.items() if 'xesam:' in k}
    for key, value in metadata.items():
        name = key.split(':')[1].lower()
        value = value[1]
        if name not in keys or name in info:
            continue
        if isinstance(value, list):
            value = value[0]
        info[name] = value

    if 'albumartist' in info:
        info['artist'] = info['albumartist']
        del info['albumartist']

    return Song(**info)
Exemplo n.º 4
0
def read_from_fd():
    name = "io.gitlab.takluyver.jeepney.tests.read_from_fd"
    addr = DBusAddress(bus_name=name, object_path='/')

    with open_dbus_connection(bus='SESSION', enable_fds=True) as conn:
        with DBusRouter(conn) as router:
            status, = Proxy(message_bus, router).RequestName(name)
        assert status == 1  # DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER

        def _reply_once():
            while True:
                msg = conn.receive()
                if msg.header.message_type is MessageType.method_call:
                    if msg.header.fields[HeaderFields.member] == 'ReadFD':
                        with msg.body[0].to_file('rb') as f:
                            f.seek(0)
                            b = f.read()
                        conn.send(new_method_return(msg, 'ay', (b, )))
                        return
                    else:
                        conn.send(new_error(msg, 'NoMethod'))

        reply_thread = threading.Thread(target=_reply_once, daemon=True)
        reply_thread.start()
        yield addr

    reply_thread.join()
Exemplo n.º 5
0
def dbus_get_metadata(path, bus_name, interface=None):
    address = DBusAddress(path, bus_name, interface)
    conn = connect_and_authenticate()
    metadata = conn.send_and_get_reply(new_method_call(address, 'GetMetadata'))
    metadata = dict(metadata[0])
    keys = ['artist', 'title', 'album']
    metadata = {k: v[1] for k, v in metadata.items() if k in keys}
    return Song(**metadata)
Exemplo n.º 6
0
    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)

        address = DBusAddress(
            "/org/gnome/Mutter/IdleMonitor/Core",
            bus_name="org.gnome.Mutter.IdleMonitor",
            interface="org.gnome.Mutter.IdleMonitor",
        )
        self.connection = connect_and_authenticate(bus="SESSION")
        self.message = new_method_call(address, "GetIdletime")
Exemplo n.º 7
0
    def initialize_fdo(self):
        from jeepney import DBusAddress, MessageType, new_method_call
        self.address = DBusAddress('/org/freedesktop/Notifications',
                                   bus_name='org.freedesktop.Notifications',
                                   interface='org.freedesktop.Notifications')

        msg = new_method_call(self.address, 'GetCapabilities')
        reply = self.connection.send_and_get_reply(msg)
        return bool(reply
                    and reply.header.message_type is MessageType.method_return)
Exemplo n.º 8
0
def test_object_wrong_property(dbus_service):
    """
    Try to get an inexistent property and verify that an error is returned.
    """
    interface = 'com.example.interface1'
    addr = DBusAddress('/path', dbus_service.name, interface=interface)

    dbus_service.listen()
    conn = connect_and_authenticate()
    with pytest.raises(DBusErrorResponse):
        conn.send_and_get_reply(Properties(addr).get('prop'))
Exemplo n.º 9
0
def test_object_get_property(dbus_service):
    """
    Set and get properties from a dbus object.
    """
    interface = 'com.example.interface1'
    add0 = DBusAddress('/path', dbus_service.name, interface=interface)
    add1 = DBusAddress('/path/subpath', dbus_service.name, interface=interface)

    dbus_service.set_property(add0.object_path, 'prop0', 's', ('hello0',),
                              add0.interface)
    dbus_service.set_property(add1.object_path, 'prop1', 's', ('hello1',),
                              add1.interface)

    dbus_service.listen()
    conn = connect_and_authenticate()

    response = conn.send_and_get_reply(Properties(add0).get('prop0'))
    assert response == ('hello0', )
    response = conn.send_and_get_reply(Properties(add1).get('prop1'))
    assert response == ('hello1', )
Exemplo n.º 10
0
def test_object_wrong_method_call(dbus_service):
    """
    Try to call an inexistent method and verify that an error is returned.
    """
    object_path = 'com.example.object'
    addr = DBusAddress('/path', object_path)

    dbus_service.listen()
    conn = connect_and_authenticate()
    with pytest.raises(DBusErrorResponse):
        conn.send_and_get_reply(new_method_call(addr, 'some_method'))
Exemplo n.º 11
0
 def initialize_portal(self):
     from jeepney import DBusAddress, MessageType, Properties
     self.address = DBusAddress(
         '/org/freedesktop/portal/desktop',
         bus_name='org.freedesktop.portal.Desktop',
         interface='org.freedesktop.portal.Notification')
     p = Properties(self.address)
     msg = p.get('version')
     reply = self.connection.send_and_get_reply(msg)
     return bool(reply
                 and reply.header.message_type is MessageType.method_return
                 and reply.body[0][1] >= 1)
Exemplo n.º 12
0
def test_object_wrong_method_call(dbus_service):
    """
    Try to call an inexistent method and verify that an error is returned.
    """
    addr = DBusAddress('/path', dbus_service.name)

    dbus_service.listen()
    conn = connect_and_authenticate()
    with pytest.raises(DBusErrorResponse) as err:
        conn.send_and_get_reply(new_method_call(addr, 'some_method'))
    assert err.value.name == 'com.example.object.exceptions.KeyError'
    assert err.value.data == ("Unregistered method: 'some_method'",)
Exemplo n.º 13
0
def test_object_method_call_args(dbus_service):
    """
    Set a method handler that can take arguments and verify that we can call
    it.
    """
    def mirror(arg):
        return ('s', (arg,))

    path = '/path'
    dbus_service.set_handler(path, 'ping', mirror)
    dbus_service.listen()

    addr = DBusAddress('/path', dbus_service.name)
    conn = connect_and_authenticate()
    response = conn.send_and_get_reply(
        new_method_call(addr, 'ping', 's', ('Repeat after me',))
    )
    assert response == ('Repeat after me',)
Exemplo n.º 14
0
def suspend_with_dbus():
    suspend = DBusAddress('/org/freedesktop/login1',
                          bus_name='org.freedesktop.login1',
                          interface='org.freedesktop.login1.Manager')

    connection = connect_and_authenticate(bus='SYSTEM')

    # Construct a new D-Bus message. new_method_call takes the address, the
    # method name, the signature string, and a tuple of arguments.
    # 'signature string' is not documented well, it's bascally the argument types. More info here
    #    https://dbus.freedesktop.org/doc/dbus-specification.html#type-system
    msg = new_method_call(suspend, 'Suspend', 'b', (True, ))

    # Send the message and wait for the reply
    reply = connection.send_and_get_reply(msg)
    print('Reply: ', reply)

    connection.close()
Exemplo n.º 15
0
def test_object_get_all_properties(dbus_service):
    """
    Get all properties from a dbus object.
    """
    interface = 'com.example.interface1'
    addr = DBusAddress('/path', dbus_service.name, interface=interface)

    dbus_service.set_property(addr.object_path, 'prop0', 's', 'hello0',
                              addr.interface)
    dbus_service.set_property(addr.object_path, 'prop1', 's', 'hello1',
                              addr.interface)
    dbus_service.set_property(addr.object_path, 'prop2', 's', 'hello2',
                              addr.interface)

    dbus_service.listen()
    conn = connect_and_authenticate()

    response = conn.send_and_get_reply(Properties(addr).get_all())
    assert response == ([('prop0', ('s', 'hello0')),
                         ('prop1', ('s', 'hello1')),
                         ('prop2', ('s', 'hello2'))], )
Exemplo n.º 16
0
def test_object_set_readonly_property(dbus_service):
    """
    Try to set the value for a readonly property and check that a permissions
    error is returned.
    """
    name = 'someprop'
    value = ('somevalue',)
    path = '/'
    interface = 'some.interface'
    prop = DBusProperty(name, 's', value, access='read')
    dbus_service.interfaces[(path, interface)].properties[name] = prop
    dbus_service.listen()

    conn = connect_and_authenticate()
    addr = DBusAddress(path, dbus_service.name, interface)
    msg = Properties(addr).set(name, 's', 'anothervalue')
    with pytest.raises(DBusErrorResponse) as err:
        conn.send_and_get_reply(msg)
    assert err.value.name == 'com.example.object.exceptions.PermissionError'
    assert err.value.data == (f'{name}: Property not settable',)
    # check that the original property hasn't changed
    assert prop.value == value
Exemplo n.º 17
0
    def gps_to_dbus(dbusargs):
        if len(dbusargs) != 15:
            print(
                'tuple argument for gps_to_dbus was not valid. Expected 15 entries, got',
                len(dbusargs))
            return -1

        gps = DBusAddress('/org/gpsd', bus_name=None, interface='org.gpsd')

        connection = connect_and_authenticate(bus='SYSTEM')

        # Construct a new D-Bus message. new_method_call takes the address, the
        # method name, the signature string, and a tuple of arguments.
        # 'signature string' is not documented well, it's basically the argument types. More info here
        #    https://dbus.freedesktop.org/doc/dbus-specification.html#type-system
        msg = new_signal(gps, 'fix', 'didddddddddddds', dbusargs)

        # Send the message and wait for the reply
        reply = connection.send_message(msg)
        #print('Reply: ', reply)

        connection.close()
Exemplo n.º 18
0
    if sys.platform == 'win32':
        from win10toast import ToastNotifier
        toaster = ToastNotifier()
    elif sys.platform == 'darwin':
        import subprocess as sp
    else:
        try:
            from jeepney import DBusAddress, new_method_call
            from jeepney.io.blocking import open_dbus_connection
        except (ImportError, ModuleNotFoundError):
            import subprocess as sp
            notifier = None
        else:
            dbus_connection = open_dbus_connection(bus='SESSION')
            notifier = DBusAddress('/org/freedesktop/Notifications',
                                   bus_name='org.freedesktop.Notifications',
                                   interface='org.freedesktop.Notifications')


def dbus_notify(title, body, timeout):
    msg = new_method_call(notifier, 'Notify', 'susssasa{sv}i',
                          (
                              APP_NAME,
                              0,  # do not replace notif
                              'dialog-information',
                              title,
                              body,
                              [], {},  # actions, hints
                              timeout,
                          ))
    dbus_connection.send_and_get_reply(msg)
Exemplo n.º 19
0
from jeepney import DBusAddress, new_signal, new_method_call
from jeepney.bus_messages import MatchRule, message_bus

portal = DBusAddress(
    object_path='/org/freedesktop/portal/desktop',
    bus_name='org.freedesktop.portal.Desktop',
)
portal_req_iface = portal.with_interface('org.freedesktop.portal.Request')


def test_match_rule_simple():
    rule = MatchRule(
        type='signal',
        interface='org.freedesktop.portal.Request',
    )
    assert rule.matches(new_signal(portal_req_iface, 'Response'))

    # Wrong message type
    assert not rule.matches(new_method_call(portal_req_iface, 'Boo'))

    # Wrong interface
    assert not rule.matches(
        new_signal(portal.with_interface('org.freedesktop.portal.FileChooser'),
                   'Response'))


def test_match_rule_path_namespace():
    assert MatchRule(path_namespace='/org/freedesktop/portal').matches(
        new_signal(portal_req_iface, 'Response'))

    # Prefix but not a parent in the path hierarchy
Exemplo n.º 20
0
]


@pytest.fixture()
async def session_proto():
    transport, proto = await connect_and_authenticate(bus='SESSION')
    yield proto
    transport.close()


async def test_connect_old(session_proto):
    assert session_proto.unique_name.startswith(':')


bus_peer = DBusAddress(bus_name='org.freedesktop.DBus',
                       object_path='/org/freedesktop/DBus',
                       interface='org.freedesktop.DBus.Peer')


async def test_send_and_get_reply_old(session_proto):
    ping_call = new_method_call(bus_peer, 'Ping')
    reply_body = await asyncio.wait_for(session_proto.send_message(ping_call),
                                        timeout=5)
    assert reply_body == ()


async def test_proxy_old(session_proto):
    proxy = Proxy(message_bus, session_proto)
    name = "io.gitlab.takluyver.jeepney.examples.Server"
    res = await proxy.RequestName(name)
    assert res in {(1, ), (2, )}  # 1: got the name, 2: queued
Exemplo n.º 21
0
 def addr(self, path, interface):
     return DBusAddress(path, bus_name='org.freedesktop.Hal', interface=f'org.freedesktop.Hal.{interface}')
Exemplo n.º 22
0
 def __init__(self, path: str, interface: str,
              connection: DBusConnection) -> None:
     DBusAddress.__init__(self, path, BUS_NAME, interface)
     self._connection = connection
Exemplo n.º 23
0
 def address(self, path='', interface=None):
     from jeepney import DBusAddress
     path = os.path.join(self.PATH, path)
     return DBusAddress(path, bus_name=self.BUS_NAME, interface=interface)