381 lines
14 KiB
Python
381 lines
14 KiB
Python
"""One connection to a Mumble server, on the shared asyncio loop.
|
|
|
|
Everything here runs on the loop thread (`airplay.loop.AsyncLoop` — the same
|
|
kind of daemon loop; Mumble gets its own instance). The connection keeps the
|
|
server's channel tree and user list current from the messages it reads, and
|
|
reports changes through plain callbacks, which the controller turns into Qt
|
|
signals for the GUI thread.
|
|
|
|
**Following**: the person to follow is matched by the name they use on the
|
|
server (from Mumble's own URL, or the saved server). While following, every
|
|
move of theirs moves the bot after them; a room picked by hand pins it there
|
|
instead.
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
import ssl
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
|
|
from lintunes.mumble import certs, proto
|
|
|
|
log = logging.getLogger("lintunes.mumble")
|
|
|
|
CONNECT_TIMEOUT_S = 10.0
|
|
PING_INTERVAL_S = 15.0
|
|
|
|
|
|
class MumbleError(ConnectionError):
|
|
pass
|
|
|
|
|
|
@dataclass
|
|
class Channel:
|
|
channel_id: int
|
|
name: str = ""
|
|
parent: int | None = None
|
|
position: int = 0
|
|
|
|
|
|
@dataclass
|
|
class User:
|
|
session: int
|
|
name: str = ""
|
|
channel_id: int = 0
|
|
suppressed: bool = False
|
|
mute: bool = False # by an admin
|
|
self_mute: bool = False
|
|
|
|
@property
|
|
def muted(self) -> bool:
|
|
return self.mute or self.self_mute
|
|
|
|
|
|
@dataclass
|
|
class ServerState:
|
|
session: int = 0
|
|
max_bandwidth: int = 0
|
|
welcome: str = ""
|
|
channels: dict[int, Channel] = field(default_factory=dict)
|
|
users: dict[int, User] = field(default_factory=dict)
|
|
|
|
def path_of(self, channel_id: int) -> list[str]:
|
|
path, seen = [], set()
|
|
channel = self.channels.get(channel_id)
|
|
while channel is not None and channel.parent is not None \
|
|
and channel.channel_id not in seen:
|
|
seen.add(channel.channel_id)
|
|
path.insert(0, channel.name)
|
|
channel = self.channels.get(channel.parent)
|
|
return path
|
|
|
|
def channel_by_path(self, path: list[str]) -> int | None:
|
|
"""The channel at ``Room/Sub-room`` (root's children first)."""
|
|
current = self.root_id()
|
|
if current is None:
|
|
return None
|
|
for name in path:
|
|
child = next((c.channel_id for c in self.channels.values()
|
|
if c.parent == current and c.name == name), None)
|
|
if child is None:
|
|
return None
|
|
current = child
|
|
return current
|
|
|
|
def root_id(self) -> int | None:
|
|
if 0 in self.channels:
|
|
return 0
|
|
return next((c.channel_id for c in self.channels.values()
|
|
if c.parent is None), None)
|
|
|
|
def tree(self) -> list[tuple[int, int, str]]:
|
|
"""[(channel id, depth, name)] in Mumble's own order: by position,
|
|
then by name, depth first."""
|
|
children: dict[int | None, list[Channel]] = {}
|
|
for c in self.channels.values():
|
|
children.setdefault(c.parent, []).append(c)
|
|
out = []
|
|
|
|
def walk(parent, depth):
|
|
for c in sorted(children.get(parent, []),
|
|
key=lambda c: (c.position, c.name.lower())):
|
|
out.append((c.channel_id, depth, c.name))
|
|
if c.channel_id != parent:
|
|
walk(c.channel_id, depth + 1)
|
|
root = self.root_id()
|
|
if root is None:
|
|
return out
|
|
out.append((root, 0, self.channels[root].name or "Root"))
|
|
walk(root, 1)
|
|
return out
|
|
|
|
def find_user(self, name: str, besides: int = 0) -> User | None:
|
|
if not name:
|
|
return None
|
|
folded = name.casefold()
|
|
return next((u for u in self.users.values()
|
|
if u.session != besides and u.name.casefold() == folded),
|
|
None)
|
|
|
|
def me(self) -> User | None:
|
|
return self.users.get(self.session)
|
|
|
|
|
|
class Connection:
|
|
"""A bot's session. ``on_event(kind, detail)`` is called on the loop
|
|
thread for: "channels", "moved" (the bot's channel changed), "suppressed"
|
|
(bool), "denied" (str), "lost" (str)."""
|
|
|
|
def __init__(self, on_event=None):
|
|
self.state = ServerState()
|
|
self.trust = ""
|
|
self._on_event = on_event or (lambda kind, detail: None)
|
|
self._reader = None
|
|
self._writer = None
|
|
self._tasks: list[asyncio.Task] = []
|
|
self._closed = False
|
|
self.follow_name = ""
|
|
self.pinned_channel: int | None = None
|
|
self._last_suppressed = None
|
|
|
|
# ---- connecting ----
|
|
|
|
async def connect(self, host: str, port: int, name: str, password: str,
|
|
certfile=None, keyfile=None, mumble_digest=None,
|
|
target_path=None):
|
|
try:
|
|
await asyncio.wait_for(self._open(host, port, certfile, keyfile,
|
|
mumble_digest),
|
|
CONNECT_TIMEOUT_S)
|
|
except asyncio.TimeoutError:
|
|
raise MumbleError(f"{host} didn't answer") from None
|
|
except certs.CertificateError as e:
|
|
raise MumbleError(str(e)) from None
|
|
except ConnectionResetError:
|
|
# What a server's flood protection looks like from here, too:
|
|
# too many connects from one address in two minutes is a ban.
|
|
raise MumbleError(f"{host} closed the connection straight away "
|
|
"(it may be refusing this computer for a "
|
|
"while after many connects)") from None
|
|
except OSError as e:
|
|
raise MumbleError(e.strerror or str(e)
|
|
or type(e).__name__) from None
|
|
self._writer.write(proto.version_message()
|
|
+ proto.authenticate_message(name, password))
|
|
await self._writer.drain()
|
|
try:
|
|
await asyncio.wait_for(self._handshake(), CONNECT_TIMEOUT_S)
|
|
except asyncio.TimeoutError:
|
|
await self.close()
|
|
raise MumbleError(f"{host} didn't let LinTunes in") from None
|
|
except BaseException:
|
|
await self.close()
|
|
raise
|
|
self._tasks = [asyncio.ensure_future(self._read_forever()),
|
|
asyncio.ensure_future(self._ping_forever())]
|
|
# Where to go first: the followed person's room, else the room the
|
|
# URL named, else wherever the server put us.
|
|
followed = self.state.find_user(self.follow_name, self.state.session)
|
|
target = followed.channel_id if followed else None
|
|
if target is None and target_path:
|
|
target = self.state.channel_by_path(target_path)
|
|
if target is not None:
|
|
self.move_to(target)
|
|
|
|
async def _open(self, host, port, certfile, keyfile, mumble_digest):
|
|
verified = ssl.create_default_context()
|
|
if certfile:
|
|
verified.load_cert_chain(certfile, keyfile)
|
|
try:
|
|
self._reader, self._writer = await asyncio.open_connection(
|
|
host, port, ssl=verified, server_hostname=host)
|
|
self.trust = "CA"
|
|
return
|
|
except ssl.SSLCertVerificationError:
|
|
pass
|
|
# Self-signed, as most Mumble servers are: connect without the CA
|
|
# check and accept it only on its digest (certs.check_self_signed).
|
|
loose = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
loose.check_hostname = False
|
|
loose.verify_mode = ssl.CERT_NONE
|
|
loose.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
if certfile:
|
|
loose.load_cert_chain(certfile, keyfile)
|
|
self._reader, self._writer = await asyncio.open_connection(
|
|
host, port, ssl=loose, server_hostname=host)
|
|
der = self._writer.get_extra_info("ssl_object").getpeercert(True)
|
|
try:
|
|
self.trust = certs.check_self_signed(host, port, der or b"",
|
|
mumble_digest)
|
|
except certs.CertificateError:
|
|
self._writer.close()
|
|
raise
|
|
|
|
async def _handshake(self):
|
|
frames = proto.FrameReader()
|
|
while True:
|
|
data = await self._reader.read(65536)
|
|
if not data:
|
|
raise MumbleError("the server closed the connection")
|
|
for kind, payload in frames.feed(data):
|
|
if kind == proto.REJECT:
|
|
fields = proto.decode(payload)
|
|
reason = proto.text(fields, 2) or proto.REJECT_REASONS.get(
|
|
proto.first(fields, 1, 0), "the server refused")
|
|
raise MumbleError(reason)
|
|
self._handle(kind, payload, quiet=True)
|
|
if kind == proto.SERVER_SYNC:
|
|
self._frames = frames
|
|
return
|
|
|
|
# ---- reading ----
|
|
|
|
async def _read_forever(self):
|
|
reason = "the server closed the connection"
|
|
try:
|
|
while True:
|
|
data = await self._reader.read(65536)
|
|
if not data:
|
|
break
|
|
for kind, payload in self._frames.feed(data):
|
|
self._handle(kind, payload)
|
|
except asyncio.CancelledError:
|
|
return
|
|
except (OSError, ValueError) as e:
|
|
reason = str(e) or type(e).__name__
|
|
if not self._closed:
|
|
self._closed = True
|
|
self._on_event("lost", reason)
|
|
|
|
def _handle(self, kind: int, payload: bytes, quiet: bool = False):
|
|
if kind in (proto.UDP_TUNNEL, proto.PING, proto.CRYPT_SETUP):
|
|
return # voice from others, ping replies, UDP keys
|
|
fields = proto.decode(payload)
|
|
state = self.state
|
|
if kind == proto.SERVER_SYNC:
|
|
state.session = proto.first(fields, 1, 0)
|
|
state.max_bandwidth = proto.first(fields, 2, state.max_bandwidth)
|
|
state.welcome = proto.text(fields, 3)
|
|
elif kind == proto.SERVER_CONFIG:
|
|
state.max_bandwidth = proto.first(fields, 1, state.max_bandwidth)
|
|
elif kind == proto.CHANNEL_STATE:
|
|
cid = proto.first(fields, 1, 0)
|
|
channel = state.channels.setdefault(cid, Channel(cid))
|
|
if 2 in fields:
|
|
channel.parent = proto.first(fields, 2)
|
|
if 3 in fields:
|
|
channel.name = proto.text(fields, 3)
|
|
if 9 in fields:
|
|
position = proto.first(fields, 9, 0)
|
|
channel.position = position - (1 << 64) \
|
|
if position >= 1 << 63 else position
|
|
if not quiet:
|
|
self._on_event("channels", None)
|
|
elif kind == proto.CHANNEL_REMOVE:
|
|
state.channels.pop(proto.first(fields, 1, -1), None)
|
|
if not quiet:
|
|
self._on_event("channels", None)
|
|
elif kind == proto.USER_STATE:
|
|
self._user_state(fields, quiet)
|
|
elif kind == proto.USER_REMOVE:
|
|
session = proto.first(fields, 1, 0)
|
|
state.users.pop(session, None)
|
|
if session == state.session and state.session and not quiet:
|
|
self._closed = True
|
|
why = proto.text(fields, 3)
|
|
self._on_event("lost", "LinTunes was removed from the server"
|
|
+ (f": {why}" if why else ""))
|
|
elif kind == proto.PERMISSION_DENIED and not quiet:
|
|
reason = proto.text(fields, 4)
|
|
self._on_event("denied", reason or
|
|
"the server didn't allow that")
|
|
|
|
def _user_state(self, fields: dict, quiet: bool):
|
|
state = self.state
|
|
session = proto.first(fields, 1, 0)
|
|
existing = state.users.get(session)
|
|
old_channel = existing.channel_id if existing is not None else None
|
|
user = state.users.setdefault(session, User(session))
|
|
if 3 in fields:
|
|
user.name = proto.text(fields, 3)
|
|
moved = 5 in fields
|
|
if moved:
|
|
user.channel_id = proto.first(fields, 5, 0)
|
|
if 8 in fields:
|
|
user.suppressed = bool(proto.first(fields, 8))
|
|
if 6 in fields:
|
|
user.mute = bool(proto.first(fields, 6))
|
|
if 9 in fields:
|
|
user.self_mute = bool(proto.first(fields, 9))
|
|
if quiet:
|
|
return
|
|
if session == state.session:
|
|
if moved:
|
|
self._on_event("moved", user.channel_id)
|
|
silenced = user.suppressed or user.muted
|
|
if silenced != self._last_suppressed:
|
|
self._last_suppressed = silenced
|
|
self._on_event("suppressed", silenced)
|
|
return
|
|
if (moved and self.pinned_channel is None and self.follow_name
|
|
and user.name.casefold() == self.follow_name.casefold()
|
|
and user.channel_id != old_channel):
|
|
me = state.me()
|
|
if me is not None and me.channel_id != user.channel_id:
|
|
self.move_to(user.channel_id)
|
|
|
|
# ---- writing ----
|
|
|
|
def send(self, data: bytes):
|
|
if self._writer is not None and not self._closed:
|
|
self._writer.write(data)
|
|
|
|
async def drain(self):
|
|
if self._writer is not None and not self._closed:
|
|
await self._writer.drain()
|
|
|
|
def move_to(self, channel_id: int):
|
|
if self.state.session:
|
|
self.send(proto.move_message(self.state.session, channel_id))
|
|
|
|
def set_comment(self, comment: str):
|
|
if self.state.session:
|
|
self.send(proto.comment_message(self.state.session, comment))
|
|
|
|
def set_follow(self, name: str, pinned_channel: int | None):
|
|
"""Follow `name` (pinned_channel None), or stay in pinned_channel."""
|
|
self.follow_name = name
|
|
self.pinned_channel = pinned_channel
|
|
if pinned_channel is not None:
|
|
self.move_to(pinned_channel)
|
|
return
|
|
followed = self.state.find_user(name, self.state.session)
|
|
if followed is not None:
|
|
self.move_to(followed.channel_id)
|
|
|
|
async def _ping_forever(self):
|
|
try:
|
|
while not self._closed:
|
|
await asyncio.sleep(PING_INTERVAL_S)
|
|
self.send(proto.ping_message(int(time.time() * 1000)))
|
|
await self.drain()
|
|
except asyncio.CancelledError:
|
|
pass
|
|
except OSError:
|
|
pass # the reader reports the loss
|
|
|
|
async def close(self):
|
|
self._closed = True
|
|
current = asyncio.current_task()
|
|
for task in self._tasks:
|
|
if task is not current:
|
|
task.cancel()
|
|
writer, self._writer = self._writer, None
|
|
if writer is not None:
|
|
try:
|
|
writer.close()
|
|
await asyncio.wait_for(writer.wait_closed(), 2.0)
|
|
except Exception: # noqa: BLE001 — closing is best effort
|
|
pass
|