dbus-fast 2.45.1__cp311-cp311-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dbus-fast might be problematic. Click here for more details.

Files changed (51) hide show
  1. dbus_fast/__init__.py +82 -0
  2. dbus_fast/__version__.py +10 -0
  3. dbus_fast/_private/__init__.py +1 -0
  4. dbus_fast/_private/_cython_compat.py +14 -0
  5. dbus_fast/_private/address.cpython-311-darwin.so +0 -0
  6. dbus_fast/_private/address.pxd +15 -0
  7. dbus_fast/_private/address.py +117 -0
  8. dbus_fast/_private/constants.py +20 -0
  9. dbus_fast/_private/marshaller.cpython-311-darwin.so +0 -0
  10. dbus_fast/_private/marshaller.pxd +110 -0
  11. dbus_fast/_private/marshaller.py +228 -0
  12. dbus_fast/_private/unmarshaller.cpython-311-darwin.so +0 -0
  13. dbus_fast/_private/unmarshaller.pxd +261 -0
  14. dbus_fast/_private/unmarshaller.py +902 -0
  15. dbus_fast/_private/util.py +176 -0
  16. dbus_fast/aio/__init__.py +5 -0
  17. dbus_fast/aio/message_bus.py +578 -0
  18. dbus_fast/aio/message_reader.cpython-311-darwin.so +0 -0
  19. dbus_fast/aio/message_reader.pxd +13 -0
  20. dbus_fast/aio/message_reader.py +49 -0
  21. dbus_fast/aio/proxy_object.py +207 -0
  22. dbus_fast/auth.py +126 -0
  23. dbus_fast/constants.py +152 -0
  24. dbus_fast/errors.py +84 -0
  25. dbus_fast/glib/__init__.py +3 -0
  26. dbus_fast/glib/message_bus.py +515 -0
  27. dbus_fast/glib/proxy_object.py +319 -0
  28. dbus_fast/introspection.py +683 -0
  29. dbus_fast/message.cpython-311-darwin.so +0 -0
  30. dbus_fast/message.pxd +76 -0
  31. dbus_fast/message.py +387 -0
  32. dbus_fast/message_bus.cpython-311-darwin.so +0 -0
  33. dbus_fast/message_bus.pxd +75 -0
  34. dbus_fast/message_bus.py +1310 -0
  35. dbus_fast/proxy_object.py +358 -0
  36. dbus_fast/py.typed +0 -0
  37. dbus_fast/send_reply.py +61 -0
  38. dbus_fast/service.cpython-311-darwin.so +0 -0
  39. dbus_fast/service.pxd +50 -0
  40. dbus_fast/service.py +686 -0
  41. dbus_fast/signature.cpython-311-darwin.so +0 -0
  42. dbus_fast/signature.pxd +31 -0
  43. dbus_fast/signature.py +481 -0
  44. dbus_fast/unpack.cpython-311-darwin.so +0 -0
  45. dbus_fast/unpack.pxd +13 -0
  46. dbus_fast/unpack.py +24 -0
  47. dbus_fast/validators.py +199 -0
  48. dbus_fast-2.45.1.dist-info/METADATA +263 -0
  49. dbus_fast-2.45.1.dist-info/RECORD +51 -0
  50. dbus_fast-2.45.1.dist-info/WHEEL +6 -0
  51. dbus_fast-2.45.1.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,358 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import inspect
5
+ import logging
6
+ import re
7
+ import xml.etree.ElementTree as ET
8
+ from collections.abc import Coroutine
9
+ from dataclasses import dataclass
10
+ from functools import lru_cache
11
+ from typing import Callable
12
+
13
+ from . import introspection as intr
14
+ from . import message_bus
15
+ from ._private.util import replace_idx_with_fds
16
+ from .constants import ErrorType, MessageType
17
+ from .errors import DBusError, InterfaceNotFoundError
18
+ from .message import Message
19
+ from .unpack import unpack_variants as unpack
20
+ from .validators import assert_bus_name_valid, assert_object_path_valid
21
+
22
+ _LOGGER = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass
26
+ class SignalHandler:
27
+ """Signal handler."""
28
+
29
+ fn: Callable | Coroutine
30
+ unpack_variants: bool
31
+
32
+
33
+ class BaseProxyInterface:
34
+ """An abstract class representing a proxy to an interface exported on the bus by another client.
35
+
36
+ Implementations of this class are not meant to be constructed directly by
37
+ users. Use :func:`BaseProxyObject.get_interface` to get a proxy interface.
38
+ Each message bus implementation provides its own proxy interface
39
+ implementation that will be returned by that method.
40
+
41
+ Proxy interfaces can be used to call methods, get properties, and listen to
42
+ signals on the interface. Proxy interfaces are created dynamically with a
43
+ family of methods for each of these operations based on what members the
44
+ interface exposes. Each proxy interface implementation exposes these
45
+ members in a different way depending on the features of the backend. See
46
+ the documentation of the proxy interface implementation you use for more
47
+ details.
48
+
49
+ :ivar bus_name: The name of the bus this interface is exported on.
50
+ :vartype bus_name: str
51
+ :ivar path: The object path exported on the client that owns the bus name.
52
+ :vartype path: str
53
+ :ivar introspection: Parsed introspection data for the proxy interface.
54
+ :vartype introspection: :class:`Node <dbus_fast.introspection.Interface>`
55
+ :ivar bus: The message bus this proxy interface is connected to.
56
+ :vartype bus: :class:`BaseMessageBus <dbus_fast.message_bus.BaseMessageBus>`
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ bus_name: str,
62
+ path: str,
63
+ introspection: intr.Interface,
64
+ bus: message_bus.BaseMessageBus,
65
+ ) -> None:
66
+ self.bus_name = bus_name
67
+ self.path = path
68
+ self.introspection = introspection
69
+ self.bus = bus
70
+ self._signal_handlers: dict[str, list[SignalHandler]] = {}
71
+ self._signal_match_rule = f"type='signal',sender={bus_name},interface={introspection.name},path={path}"
72
+ self._background_tasks: set[asyncio.Task] = set()
73
+
74
+ _underscorer1 = re.compile(r"(.)([A-Z][a-z]+)")
75
+ _underscorer2 = re.compile(r"([a-z0-9])([A-Z])")
76
+
77
+ @staticmethod
78
+ @lru_cache(maxsize=128)
79
+ def _to_snake_case(member: str) -> str:
80
+ subbed = BaseProxyInterface._underscorer1.sub(r"\1_\2", member)
81
+ return BaseProxyInterface._underscorer2.sub(r"\1_\2", subbed).lower()
82
+
83
+ @staticmethod
84
+ def _check_method_return(msg: Message, signature: str | None = None):
85
+ if msg.message_type == MessageType.ERROR:
86
+ raise DBusError._from_message(msg)
87
+ if msg.message_type != MessageType.METHOD_RETURN:
88
+ raise DBusError(
89
+ ErrorType.CLIENT_ERROR, "method call didnt return a method return", msg
90
+ )
91
+ if signature is not None and msg.signature != signature:
92
+ raise DBusError(
93
+ ErrorType.CLIENT_ERROR,
94
+ f'method call returned unexpected signature: "{msg.signature}"',
95
+ msg,
96
+ )
97
+
98
+ def _add_method(self, intr_method: intr.Method) -> None:
99
+ raise NotImplementedError("this must be implemented in the inheriting class")
100
+
101
+ def _add_property(self, intr_property: intr.Property) -> None:
102
+ raise NotImplementedError("this must be implemented in the inheriting class")
103
+
104
+ def _message_handler(self, msg: Message) -> None:
105
+ if (
106
+ msg.message_type != MessageType.SIGNAL
107
+ or msg.interface != self.introspection.name
108
+ or msg.path != self.path
109
+ or msg.member not in self._signal_handlers
110
+ ):
111
+ return
112
+
113
+ if (
114
+ msg.sender != self.bus_name
115
+ and self.bus._name_owners.get(self.bus_name, "") != msg.sender
116
+ ):
117
+ # The sender is always a unique name, but the bus name given might
118
+ # be a well known name. If the sender isn't an exact match, check
119
+ # to see if it owns the bus_name we were given from the cache kept
120
+ # on the bus for this purpose.
121
+ return
122
+
123
+ match = [s for s in self.introspection.signals if s.name == msg.member]
124
+ if not match:
125
+ return
126
+ intr_signal = match[0]
127
+ if intr_signal.signature != msg.signature:
128
+ _LOGGER.warning(
129
+ f'got signal "{self.introspection.name}.{msg.member}" with unexpected signature "{msg.signature}"'
130
+ )
131
+ return
132
+
133
+ body = replace_idx_with_fds(msg.signature, msg.body, msg.unix_fds)
134
+ no_sig = None
135
+ for handler in self._signal_handlers[msg.member]:
136
+ if handler.unpack_variants:
137
+ if not no_sig:
138
+ no_sig = unpack(body)
139
+ data = no_sig
140
+ else:
141
+ data = body
142
+
143
+ cb_result = handler.fn(*data)
144
+ if isinstance(cb_result, Coroutine):
145
+ # Save a strong reference to the task so it doesn't get garbage
146
+ # collected before it finishes.
147
+ task = asyncio.create_task(cb_result)
148
+ self._background_tasks.add(task)
149
+ task.add_done_callback(self._background_tasks.remove)
150
+
151
+ def _add_signal(self, intr_signal: intr.Signal, interface: intr.Interface) -> None:
152
+ def on_signal_fn(fn: Callable | Coroutine, *, unpack_variants: bool = False):
153
+ fn_signature = inspect.signature(fn)
154
+ if (
155
+ len(
156
+ [
157
+ par
158
+ for par in fn_signature.parameters.values()
159
+ if par.kind == inspect.Parameter.KEYWORD_ONLY
160
+ and par.default == inspect.Parameter.empty
161
+ ]
162
+ )
163
+ > 0
164
+ ):
165
+ raise TypeError(
166
+ "reply_notify cannot have required keyword only parameters"
167
+ )
168
+
169
+ positional_params = [
170
+ par.kind
171
+ for par in fn_signature.parameters.values()
172
+ if par.kind
173
+ not in [inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.VAR_KEYWORD]
174
+ ]
175
+ if len(positional_params) != len(intr_signal.args) and (
176
+ inspect.Parameter.VAR_POSITIONAL not in positional_params
177
+ or len(positional_params) - 1 > len(intr_signal.args)
178
+ ):
179
+ raise TypeError(
180
+ f"reply_notify must be a function with {len(intr_signal.args)} positional parameters"
181
+ )
182
+
183
+ if not self._signal_handlers:
184
+ self.bus._add_match_rule(self._signal_match_rule)
185
+ self.bus.add_message_handler(self._message_handler)
186
+
187
+ if intr_signal.name not in self._signal_handlers:
188
+ self._signal_handlers[intr_signal.name] = []
189
+
190
+ self._signal_handlers[intr_signal.name].append(
191
+ SignalHandler(fn, unpack_variants)
192
+ )
193
+
194
+ def off_signal_fn(
195
+ fn: Callable | Coroutine, *, unpack_variants: bool = False
196
+ ) -> None:
197
+ try:
198
+ i = self._signal_handlers[intr_signal.name].index(
199
+ SignalHandler(fn, unpack_variants)
200
+ )
201
+ del self._signal_handlers[intr_signal.name][i]
202
+ if not self._signal_handlers[intr_signal.name]:
203
+ del self._signal_handlers[intr_signal.name]
204
+ except (KeyError, ValueError):
205
+ return
206
+
207
+ if not self._signal_handlers:
208
+ self.bus._remove_match_rule(self._signal_match_rule)
209
+ self.bus.remove_message_handler(self._message_handler)
210
+
211
+ snake_case = BaseProxyInterface._to_snake_case(intr_signal.name)
212
+ setattr(interface, f"on_{snake_case}", on_signal_fn)
213
+ setattr(interface, f"off_{snake_case}", off_signal_fn)
214
+
215
+
216
+ class BaseProxyObject:
217
+ """An abstract class representing a proxy to an object exported on the bus by another client.
218
+
219
+ Implementations of this class are not meant to be constructed directly. Use
220
+ :func:`BaseMessageBus.get_proxy_object()
221
+ <dbus_fast.message_bus.BaseMessageBus.get_proxy_object>` to get a proxy
222
+ object. Each message bus implementation provides its own proxy object
223
+ implementation that will be returned by that method.
224
+
225
+ The primary use of the proxy object is to select a proxy interface to act
226
+ on. Information on what interfaces are available is provided by
227
+ introspection data provided to this class. This introspection data can
228
+ either be included in your project as an XML file (recommended) or
229
+ retrieved from the ``org.freedesktop.DBus.Introspectable`` interface at
230
+ runtime.
231
+
232
+ :ivar bus_name: The name of the bus this object is exported on.
233
+ :vartype bus_name: str
234
+ :ivar path: The object path exported on the client that owns the bus name.
235
+ :vartype path: str
236
+ :ivar introspection: Parsed introspection data for the proxy object.
237
+ :vartype introspection: :class:`Node <dbus_fast.introspection.Node>`
238
+ :ivar bus: The message bus this proxy object is connected to.
239
+ :vartype bus: :class:`BaseMessageBus <dbus_fast.message_bus.BaseMessageBus>`
240
+ :ivar ~.ProxyInterface: The proxy interface class this proxy object uses.
241
+ :vartype ~.ProxyInterface: Type[:class:`BaseProxyInterface <dbus_fast.proxy_object.BaseProxyObject>`]
242
+ :ivar child_paths: A list of absolute object paths of the children of this object.
243
+ :vartype child_paths: list(str)
244
+
245
+ :raises:
246
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
247
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
248
+ - :class:`InvalidIntrospectionError <dbus_fast.InvalidIntrospectionError>` - If the introspection data for the node is not valid.
249
+ """
250
+
251
+ def __init__(
252
+ self,
253
+ bus_name: str,
254
+ path: str,
255
+ introspection: intr.Node | str | ET.Element,
256
+ bus: message_bus.BaseMessageBus,
257
+ ProxyInterface: type[BaseProxyInterface],
258
+ ) -> None:
259
+ assert_object_path_valid(path)
260
+ assert_bus_name_valid(bus_name)
261
+
262
+ if not isinstance(bus, message_bus.BaseMessageBus):
263
+ raise TypeError("bus must be an instance of BaseMessageBus")
264
+ if not issubclass(ProxyInterface, BaseProxyInterface):
265
+ raise TypeError("ProxyInterface must be an instance of BaseProxyInterface")
266
+
267
+ if type(introspection) is intr.Node:
268
+ self.introspection = introspection
269
+ elif type(introspection) is str:
270
+ self.introspection = intr.Node.parse(introspection)
271
+ elif type(introspection) is ET.Element:
272
+ self.introspection = intr.Node.from_xml(introspection)
273
+ else:
274
+ raise TypeError(
275
+ "introspection must be xml node introspection or introspection.Node class"
276
+ )
277
+
278
+ self.bus_name = bus_name
279
+ self.path = path
280
+ self.bus = bus
281
+ self.ProxyInterface = ProxyInterface
282
+ self.child_paths = [f"{path}/{n.name}" for n in self.introspection.nodes]
283
+
284
+ self._interfaces = {}
285
+
286
+ # lazy loaded by get_children()
287
+ self._children = None
288
+
289
+ def get_interface(self, name: str) -> BaseProxyInterface:
290
+ """Get an interface exported on this proxy object and connect it to the bus.
291
+
292
+ :param name: The name of the interface to retrieve.
293
+ :type name: str
294
+
295
+ :raises:
296
+ - :class:`InterfaceNotFoundError <dbus_fast.InterfaceNotFoundError>` - If there is no interface by this name exported on the bus.
297
+ """
298
+ if name in self._interfaces:
299
+ return self._interfaces[name]
300
+
301
+ try:
302
+ intr_interface = next(
303
+ i for i in self.introspection.interfaces if i.name == name
304
+ )
305
+ except StopIteration as ex:
306
+ raise InterfaceNotFoundError(
307
+ f"interface not found on this object: {name}"
308
+ ) from ex
309
+
310
+ interface = self.ProxyInterface(
311
+ self.bus_name, self.path, intr_interface, self.bus
312
+ )
313
+
314
+ for intr_method in intr_interface.methods:
315
+ interface._add_method(intr_method)
316
+ for intr_property in intr_interface.properties:
317
+ interface._add_property(intr_property)
318
+ for intr_signal in intr_interface.signals:
319
+ interface._add_signal(intr_signal, interface)
320
+
321
+ def get_owner_notify(msg: Message, err: Exception | None) -> None:
322
+ if err:
323
+ _LOGGER.error(f'getting name owner for "{name}" failed, {err}')
324
+ return
325
+ if msg.message_type == MessageType.ERROR:
326
+ if msg.error_name != ErrorType.NAME_HAS_NO_OWNER.value:
327
+ _LOGGER.error(
328
+ f'getting name owner for "{name}" failed, {msg.body[0]}'
329
+ )
330
+ return
331
+
332
+ self.bus._name_owners[self.bus_name] = msg.body[0]
333
+
334
+ if self.bus_name[0] != ":" and not self.bus._name_owners.get(self.bus_name, ""):
335
+ self.bus._call(
336
+ Message(
337
+ destination="org.freedesktop.DBus",
338
+ interface="org.freedesktop.DBus",
339
+ path="/org/freedesktop/DBus",
340
+ member="GetNameOwner",
341
+ signature="s",
342
+ body=[self.bus_name],
343
+ ),
344
+ get_owner_notify,
345
+ )
346
+
347
+ self._interfaces[name] = interface
348
+ return interface
349
+
350
+ def get_children(self) -> list[BaseProxyObject]:
351
+ """Get the child nodes of this proxy object according to the introspection data."""
352
+ if self._children is None:
353
+ self._children = [
354
+ self.__class__(self.bus_name, self.path, child, self.bus)
355
+ for child in self.introspection.nodes
356
+ ]
357
+
358
+ return self._children
dbus_fast/py.typed ADDED
File without changes
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ import traceback
4
+ from types import TracebackType
5
+ from typing import TYPE_CHECKING
6
+
7
+ from .constants import ErrorType
8
+ from .errors import DBusError
9
+ from .message import Message
10
+
11
+ if TYPE_CHECKING:
12
+ from .message_bus import BaseMessageBus
13
+
14
+
15
+ class SendReply:
16
+ """A context manager to send a reply to a message."""
17
+
18
+ __slots__ = ("_bus", "_msg")
19
+
20
+ def __init__(self, bus: BaseMessageBus, msg: Message) -> None:
21
+ """Create a new reply context manager."""
22
+ self._bus = bus
23
+ self._msg = msg
24
+
25
+ def __enter__(self) -> SendReply:
26
+ return self
27
+
28
+ def __call__(self, reply: Message) -> None:
29
+ self._bus.send(reply)
30
+
31
+ def _exit(
32
+ self,
33
+ exc_type: type[Exception] | None,
34
+ exc_value: Exception | None,
35
+ tb: TracebackType | None,
36
+ ) -> bool:
37
+ if exc_value:
38
+ if isinstance(exc_value, DBusError):
39
+ self(exc_value._as_message(self._msg))
40
+ else:
41
+ self(
42
+ Message.new_error(
43
+ self._msg,
44
+ ErrorType.SERVICE_ERROR,
45
+ f"The service interface raised an error: {exc_value}.\n{traceback.format_tb(tb)}",
46
+ )
47
+ )
48
+ return True
49
+
50
+ return False
51
+
52
+ def __exit__(
53
+ self,
54
+ exc_type: type[Exception] | None,
55
+ exc_value: Exception | None,
56
+ tb: TracebackType | None,
57
+ ) -> bool:
58
+ return self._exit(exc_type, exc_value, tb)
59
+
60
+ def send_error(self, exc: Exception) -> None:
61
+ self._exit(exc.__class__, exc, exc.__traceback__)
Binary file
dbus_fast/service.pxd ADDED
@@ -0,0 +1,50 @@
1
+ """cdefs for service.py"""
2
+
3
+ import cython
4
+
5
+ from .message cimport Message
6
+ from .signature cimport SignatureTree
7
+
8
+
9
+ cdef class _Method:
10
+
11
+ cdef public str name
12
+ cdef public object fn
13
+ cdef public bint disabled
14
+ cdef public object introspection
15
+ cdef public str in_signature
16
+ cdef public str out_signature
17
+ cdef public SignatureTree in_signature_tree
18
+ cdef public SignatureTree out_signature_tree
19
+
20
+
21
+
22
+ cdef tuple _real_fn_result_to_body(
23
+ object result,
24
+ SignatureTree signature_tree,
25
+ bint replace_fds
26
+ )
27
+
28
+ cdef class ServiceInterface:
29
+
30
+ cdef public str name
31
+ cdef list __methods
32
+ cdef list __properties
33
+ cdef list __signals
34
+ cdef set __buses
35
+ cdef dict __handlers
36
+ cdef dict __handlers_by_name_signature
37
+
38
+ @cython.locals(handlers=dict,in_signature=str,method=_Method)
39
+ @staticmethod
40
+ cdef object _get_enabled_handler_by_name_signature(ServiceInterface interface, object bus, object name, object signature)
41
+
42
+ @staticmethod
43
+ cdef list _c_msg_body_to_args(Message msg)
44
+
45
+ @staticmethod
46
+ cdef tuple _c_fn_result_to_body(
47
+ object result,
48
+ SignatureTree signature_tree,
49
+ bint replace_fds,
50
+ )