56 lines
1.8 KiB
TypeScript
56 lines
1.8 KiB
TypeScript
import { broadcast } from "./bus";
|
|
|
|
export interface PresenceParticipant {
|
|
id: number;
|
|
name: string;
|
|
lastSeen: string;
|
|
}
|
|
|
|
interface PresenceRecord extends PresenceParticipant {
|
|
expiresAt: number;
|
|
}
|
|
|
|
export const PRESENCE_TTL_MS = 45_000;
|
|
const channels = new Map<string, Map<number, PresenceRecord>>();
|
|
|
|
function prune(channel: string, now = Date.now()): void {
|
|
const entries = channels.get(channel);
|
|
if (!entries) return;
|
|
for (const [id, entry] of entries) {
|
|
if (entry.expiresAt <= now) {
|
|
entries.delete(id);
|
|
broadcast("presence", { channel, action: "leave", participantId: id });
|
|
}
|
|
}
|
|
if (entries.size === 0) channels.delete(channel);
|
|
}
|
|
|
|
export function getPresence(channel: string): PresenceParticipant[] {
|
|
prune(channel);
|
|
return [...(channels.get(channel)?.values() ?? [])].map(({ id, name, lastSeen }) => ({ id, name, lastSeen }));
|
|
}
|
|
|
|
export function touchPresence(channel: string, participant: Omit<PresenceParticipant, "lastSeen">): void {
|
|
const now = Date.now();
|
|
prune(channel, now);
|
|
let entries = channels.get(channel);
|
|
if (!entries) {
|
|
entries = new Map();
|
|
channels.set(channel, entries);
|
|
}
|
|
const wasPresent = entries.has(participant.id);
|
|
const record = { ...participant, lastSeen: new Date(now).toISOString(), expiresAt: now + PRESENCE_TTL_MS };
|
|
entries.set(participant.id, record);
|
|
broadcast("presence", {
|
|
channel,
|
|
action: wasPresent ? "update" : "join",
|
|
participant: { id: record.id, name: record.name, lastSeen: record.lastSeen },
|
|
});
|
|
}
|
|
|
|
export function removePresence(channel: string, id: number): void {
|
|
const entries = channels.get(channel);
|
|
if (!entries?.delete(id)) return;
|
|
if (entries.size === 0) channels.delete(channel);
|
|
broadcast("presence", { channel, action: "leave", participantId: id });
|
|
}
|