"""Where to connect: the server trav's own Mumble is on, or one he saved. Two read-only sources, both the Mumble app's: * its D-Bus service (``net.sourceforge.mumble.mumble``), whose `getCurrentUrl` answers ``mumble://user@host:port/Room/Sub-room?version=…`` while it is connected — the server *and* the room trav is in, never the password; and * its database (`mumble.sqlite`): the saved servers (the Connect dialog's favourites, passwords included) and the certificate digests trav has accepted for self-signed servers, which is how LinTunes checks a server is the one Mumble already trusts. The database is opened read-only (``mode=ro``) and only those two tables are read. Nothing is ever written there. """ import sqlite3 from dataclasses import dataclass, field from pathlib import Path from urllib.parse import unquote, urlsplit DEFAULT_PORT = 64738 DBUS_SERVICE = "net.sourceforge.mumble.mumble" DBUS_PATH = "/" DBUS_INTERFACE = "net.sourceforge.mumble.Mumble" DBUS_TIMEOUT_MS = 2000 @dataclass class Server: host: str port: int = DEFAULT_PORT name: str = "" # the label trav gave it in Mumble username: str = "" # *trav's* name there, for following him password: str = "" channel_path: list[str] = field(default_factory=list) # trav's room current: bool = False # the server Mumble is connected to now @property def address(self) -> str: host = f"[{self.host}]" if ":" in self.host else self.host return host if self.port == DEFAULT_PORT else f"{host}:{self.port}" def label(self) -> str: if self.name and self.name != self.host: return f"{self.name} ({self.address})" return self.address def same_place(self, other: "Server") -> bool: return (self.host.lower() == other.host.lower() and self.port == other.port) def parse_url(url: str) -> Server | None: """A ``mumble://`` URL → Server, or None if it isn't one.""" if not url: return None try: parts = urlsplit(url.strip()) port = parts.port except ValueError: return None if parts.scheme.lower() != "mumble" or not parts.hostname: return None path = [unquote(p) for p in parts.path.split("/") if p] return Server(host=parts.hostname, port=port or DEFAULT_PORT, username=unquote(parts.username or ""), password=unquote(parts.password or ""), channel_path=path) def current_url() -> str | None: """The running Mumble's connection as a URL; None when Mumble isn't running or isn't connected (it answers that with a D-Bus error).""" try: from PyQt6.QtDBus import QDBusConnection, QDBusInterface, QDBusMessage except ImportError: return None bus = QDBusConnection.sessionBus() if not bus.isConnected(): return None interface = QDBusInterface(DBUS_SERVICE, DBUS_PATH, DBUS_INTERFACE, bus) if not interface.isValid(): return None interface.setTimeout(DBUS_TIMEOUT_MS) reply = interface.call("getCurrentUrl") if reply.type() != QDBusMessage.MessageType.ReplyMessage: return None arguments = reply.arguments() return str(arguments[0]) if arguments else None def current_server() -> Server | None: server = parse_url(current_url() or "") if server is not None: server.current = True return server def database_paths(home: Path | None = None) -> list[Path]: """Where each kind of Mumble install keeps mumble.sqlite, likeliest first: Flathub's, then a distro package's (1.4+), then 1.3's.""" home = home or Path.home() return [ home / ".var/app/info.mumble.Mumble/data/Mumble/Mumble/mumble.sqlite", home / ".local/share/Mumble/Mumble/mumble.sqlite", home / ".local/share/data/Mumble/Mumble/mumble.sqlite", home / "Library/Application Support/Mumble/Mumble/mumble.sqlite", ] def _open(path: Path): return sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=1.0) def find_database(home: Path | None = None) -> Path | None: return next((p for p in database_paths(home) if p.is_file()), None) def saved_servers(database: Path | None = None) -> list[Server]: """Mumble's favourites, in the order Mumble lists them (by name).""" database = database or find_database() if database is None: return [] try: with _open(database) as db: rows = db.execute( "SELECT name, hostname, port, username, password FROM servers" " ORDER BY name COLLATE NOCASE").fetchall() except sqlite3.Error: return [] servers = [] for name, host, port, username, password in rows: if not host: continue servers.append(Server(host=str(host), port=int(port or DEFAULT_PORT), name=str(name or ""), username=str(username or ""), password=str(password or ""))) return servers def accepted_digest(host: str, port: int, database: Path | None = None) -> str | None: """The SHA-1 (hex) of the certificate trav accepted for host:port in Mumble, if the server's certificate needed accepting.""" database = database or find_database() if database is None: return None try: with _open(database) as db: row = db.execute( "SELECT digest FROM cert WHERE lower(hostname) = lower(?)" " AND port = ?", (host, int(port))).fetchone() except sqlite3.Error: return None return str(row[0]).lower() if row and row[0] else None def choices(current: Server | None, saved: list[Server]) -> list[Server]: """What Connect to Mumble… offers: the server Mumble is on first, filled in from its favourite (the password lives only there), then the rest of the favourites.""" out = [] if current is not None: match = next((s for s in saved if s.same_place(current)), None) if match is not None: current.name = current.name or match.name current.password = current.password or match.password out.append(current) out += [s for s in saved if current is None or not s.same_place(current)] return out