mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
M002: harden session lifecycle and directory sync
This commit is contained in:
1 parent
4a5d1ca0da
commit
8c7a940de5
11 files changed
+615
-153
No files matched your search
@@ -0,0 +1,77 @@
|
||||
import type { ClientInfo } from "@honeybbq/teamspeak-client";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
| { type: "clientEnter"; info: ClientInfo }
|
||||
| { type: "clientLeave"; id: number }
|
||||
| { type: "clientMoved"; id: number; channelID: bigint };
|
||||
|
||||
/**
|
||||
* Merges the welcome snapshot with events received while that snapshot is in
|
||||
* flight. Each TeamSpeak connection owns its own instance, so no directory
|
||||
* event can leak into another browser session.
|
||||
*/
|
||||
export class DirectorySynchronizer {
|
||||
private snapshot: TSDirectorySnapshot | null = null;
|
||||
private clients = new Map<number, ClientInfo>();
|
||||
private pending: DirectoryDelta[] = [];
|
||||
|
||||
get ready(): boolean {
|
||||
return this.snapshot !== null;
|
||||
}
|
||||
|
||||
applySnapshot(snapshot: TSDirectorySnapshot): void {
|
||||
this.snapshot = { channels: snapshot.channels.slice(), clients: [] };
|
||||
this.clients.clear();
|
||||
for (const client of snapshot.clients) this.clients.set(client.id, client);
|
||||
const pending = this.pending.splice(0);
|
||||
for (const delta of pending) this.applyDelta(delta);
|
||||
}
|
||||
|
||||
applyClientEnter(info: ClientInfo): void {
|
||||
this.applyOrQueue({ type: "clientEnter", info });
|
||||
}
|
||||
|
||||
applyClientLeave(id: number): void {
|
||||
this.applyOrQueue({ type: "clientLeave", id });
|
||||
}
|
||||
|
||||
applyClientMoved(id: number, channelID: bigint): void {
|
||||
this.applyOrQueue({ type: "clientMoved", id, channelID });
|
||||
}
|
||||
|
||||
getSnapshot(): TSDirectorySnapshot | null {
|
||||
if (!this.snapshot) return null;
|
||||
return {
|
||||
channels: this.snapshot.channels.slice(),
|
||||
clients: [...this.clients.values()],
|
||||
};
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.snapshot = null;
|
||||
this.clients.clear();
|
||||
this.pending = [];
|
||||
}
|
||||
|
||||
private applyOrQueue(delta: DirectoryDelta): void {
|
||||
if (!this.snapshot) {
|
||||
if (this.pending.length < 4096) this.pending.push(delta);
|
||||
return;
|
||||
}
|
||||
this.applyDelta(delta);
|
||||
}
|
||||
|
||||
private applyDelta(delta: DirectoryDelta): void {
|
||||
if (delta.type === "clientEnter") {
|
||||
this.clients.set(delta.info.id, delta.info);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientLeave") {
|
||||
this.clients.delete(delta.id);
|
||||
return;
|
||||
}
|
||||
const current = this.clients.get(delta.id);
|
||||
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user