def test_dbus(self): from jeepney.io.blocking import open_dbus_connection if 'DBUS_SESSION_BUS_ADDRESS' in os.environ: bus = open_dbus_connection(bus='SYSTEM') bus.close() bus = open_dbus_connection(bus='SESSION') bus.close() del bus
def notify(title='title', body='text', icon='python'): """Notifier function.""" if PLT == "win32": toaster.show_toast(title, body, threaded=True, icon_path=path.join(path.dirname(__file__), 'data', '%s.ico' % icon)) elif PLT == "linux": reply = None with closing(open_dbus_connection(bus='SESSION')) as bus: msg = new_method_call(NOTIFIER, 'Notify', 'susssasa{sv}i', ( "routEar", NOTIF_ID or 0, 'file://%s' % path.join(path.dirname(__file__), 'data', '%s.png' % icon), title, body, [], {}, -1, )) reply = bus.send_and_get_reply(msg) globals()['NOTIF_ID'] = reply.body[0] if reply else None elif PLT == "darwin": pync.notify(f"{title} \n {body}", title="routEar") else: return False return True
def _enter(*, display: bool, app_name: str, reason: str) -> None: global _connection, _disposers, _interfaces, _interface_candidates if _connection is None: try: _connection = open_dbus_connection() except Exception: raise NotSupportedError( "Cannot establish connection to D-Bus") from None success = False try: for cls in _interface_candidates: interface = cls() try: (cookie, ) = Proxy(interface, _connection).inhibit(app_name, reason) success = True break except DBusErrorResponse: pass else: raise NotSupportedError( "No supported power management DBus interface is available") finally: if not success and not _disposers and _connection is not None: # connection is not needed any more _connection.close() _connection = None def disposer(bus: Any) -> None: Proxy(interface, bus).uninhibit(cookie) _disposers.append(disposer) _interfaces.append(interface)
def initialize(self): from jeepney.io.blocking import open_dbus_connection if self.initialized: return self.initialized = True self.ok = False try: self.connection = open_dbus_connection(bus='SESSION') except Exception: return with suppress(Exception): self.ok = self.initialize_fdo() if self.ok: self.notify = self.fdo_notify return if DEBUG: print('Failed to connect to FDO Notifications service', file=sys.stderr) with suppress(Exception): self.ok = self.initialize_portal() if self.ok: self.notify = self.portal_notify else: print('Failed to connect to Portal Notifications service', file=sys.stderr)
def test_recv_fd(respond_with_fd): getfd_call = new_method_call(respond_with_fd, 'GetFD') with open_dbus_connection(bus='SESSION', enable_fds=True) as conn: reply = conn.send_and_get_reply(getfd_call, timeout=5) assert reply.header.message_type is MessageType.method_return with reply.body[0].to_file('w+') as f: assert f.read() == 'readme'
def test_send_fd(temp_file_and_contents, read_from_fd): temp_file, data = temp_file_and_contents readfd_call = new_method_call(read_from_fd, 'ReadFD', 'h', (temp_file, )) with open_dbus_connection(bus='SESSION', enable_fds=True) as conn: reply = conn.send_and_get_reply(readfd_call, timeout=5) assert reply.header.message_type is MessageType.method_return assert reply.body[0] == data
def generate(path, name, output_file, bus='SESSION'): conn = open_dbus_connection(bus) introspectable = Proxy(Introspectable(path, name), conn) xml, = introspectable.Introspect() # print(xml) n_interfaces = code_from_xml(xml, path, name, output_file) print("Written {} interface wrappers to {}".format(n_interfaces, output_file))
def dbus_notify(title, body, timeout): global notif_id connection = open_dbus_connection(bus='SESSION') msg = new_method_call(notifier, 'Notify', 'susssasa{sv}i', ( APP_NAME, notif_id, 'dialog-information', title, body, [], {}, timeout, )) reply = connection.send_and_get_reply(msg) connection.close() notif_id = reply.body[0]
def _verify() -> bool: global _interfaces if not _interfaces: return False interface = _interfaces[-1] if hasattr(interface, "is_inhibited"): with closing(open_dbus_connection()) as bus: try: (result, ) = Proxy(interface, bus).is_inhibited() return result except DBusErrorResponse: pass global _disposers return bool(_disposers)
def grab_full_desktop() -> QtGui.QImage: """Capture rect of screen on gnome systems using wayland.""" logger.debug("Use capture method: DBUS portal") image = QtGui.QImage() _, temp_name = tempfile.mkstemp(prefix="normcap") try: connection = open_dbus_connection(bus="SESSION") token = f"normcap_{secrets.token_hex(8)}" sender_name = connection.unique_name[1:].replace(".", "_") handle = f"/org/freedesktop/portal/desktop/request/{sender_name}/{token}" response_rule = MatchRule(type="signal", interface="org.freedesktop.portal.Request", path=handle) Proxy(message_bus, connection).AddMatch(response_rule) with connection.filter(response_rule) as responses: msg = FreedesktopPortalScreenshot().grab("", { "handle_token": ("s", token), "interactive": ("b", False) }) connection.send_and_get_reply(msg) response = connection.recv_until_filtered(responses) response_code, response_body = response.body assert response_code == 0 and "uri" in response_body image = QtGui.QImage(urlparse(response_body["uri"][1]).path) except AssertionError as e: logger.warning("Couldn't take screenshot with DBUS. Got cancelled?") raise e from e except DBusErrorResponse as e: if "invalid params" in [d.lower() for d in e.data]: logger.info("ScreenShot with DBUS failed with 'invalid params'") else: logger.exception("ScreenShot with DBUS through exception") finally: Path(temp_name).unlink() return image
def dbus_init() -> DBusConnection: """Returns a new connection to the session bus, instance of jeepney's :class:`DBusConnection` class. This connection can then be passed to various SecretStorage functions, such as :func:`~secretstorage.collection.get_default_collection`. .. warning:: The D-Bus socket will not be closed automatically. You can close it manually using the :meth:`DBusConnection.close` method, or you can use the :class:`contextlib.closing` context manager: .. code-block:: python from contextlib import closing with closing(dbus_init()) as conn: collection = secretstorage.get_default_collection(conn) items = collection.search_items({'application': 'myapp'}) However, you will not be able to call any methods on the objects created within the context after you leave it. .. versionchanged:: 3.0 Before the port to Jeepney, this function returned an instance of :class:`dbus.SessionBus` class. .. versionchanged:: 3.1 This function no longer accepts any arguments. """ try: connection = open_dbus_connection() add_match_rules(connection) return connection except KeyError as ex: # os.environ['DBUS_SESSION_BUS_ADDRESS'] may raise it reason = "Environment variable {} is unset".format(ex.args[0]) raise SecretServiceNotAvailableException(reason) from ex except (ConnectionError, ValueError) as ex: raise SecretServiceNotAvailableException(str(ex)) from ex
logger.debug("Notifications enabled for categories: " f"{', '.join(sorted(enabled_categories))}") 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,
def __enter__(self): from jeepney.io.blocking import open_dbus_connection self.connection = open_dbus_connection(bus='SYSTEM') return self
def session_conn(): with open_dbus_connection(bus='SESSION') as conn: yield conn
def connect(self, which='SESSION'): from jeepney.io.blocking import open_dbus_connection if not hasattr(self, 'connection'): self.connection = open_dbus_connection(which)
def __init__(self): self.bus = open_dbus_connection('SYSTEM')
def run(self): items = [] visited = set() try: import dbus import secretstorage import datetime except ImportError as e: self.error('libsecret: {0}'.format(e)) return [] for uid, session in homes.sessions(): try: # List bus connection names bus = dbus.bus.BusConnection(session) if 'org.freedesktop.secrets' not in [ str(x) for x in bus.list_names() ]: continue except Exception: self.error(traceback.format_exc()) continue collections = None try: # Python 2.7 collections = list( secretstorage.collection.get_all_collections(bus)) except Exception: pass if not collections: try: # Python 3 from jeepney.io.blocking import open_dbus_connection make_auth_external.uid = uid bus = open_dbus_connection(session) collections = secretstorage.get_all_collections(bus) except Exception: self.error(traceback.format_exc()) continue for collection in collections: if collection.is_locked(): continue label = collection.get_label() if label in visited: continue visited.add(label) try: storage = collection.get_all_items() except Exception: self.error(traceback.format_exc()) continue for item in storage: values = { 'created': str(datetime.datetime.fromtimestamp( item.get_created())), 'modified': str( datetime.datetime.fromtimestamp( item.get_modified())), 'content-type': item.get_secret_content_type(), 'label': item.get_label(), 'Password': item.get_secret().decode('utf8'), 'collection': label, } # for k, v in item.get_attributes().iteritems(): # values[unicode(k)] = unicode(v) items.append(values) if item.get_label().endswith('Safe Storage'): constant.chrome_storage.append(item.get_secret()) try: bus.flush() bus.close() except Exception: pass return items