SPB Git

Repository Public

hub.ts 2.5 KB 68 lines typescript

1import type { WebSocket } from "ws"2import { sql } from "./db.js"34type Conn = { ws: WebSocket; userId: string; deviceId: string | null; sessionId: string; alive: boolean }5const byUser = new Map<string, Set<Conn>>()67export const hub = {8  add(c: Conn) {9    let s = byUser.get(c.userId)10    if (!s) byUser.set(c.userId, (s = new Set()))11    s.add(c)12  },13  remove(c: Conn) {14    const s = byUser.get(c.userId)15    if (!s) return16    s.delete(c)17    if (!s.size) byUser.delete(c.userId)18  },19  online(userId: string) {20    return byUser.has(userId)21  },22  connections() {23    let n = 024    for (const s of byUser.values()) n += s.size25    return n26  },27  toUser(userId: string, msg: unknown, exceptDevice?: string | null) {28    const s = byUser.get(userId)29    if (!s) return30    const text = JSON.stringify(msg)31    for (const c of s) if (!exceptDevice || c.deviceId !== exceptDevice) if (c.ws.readyState === 1) c.ws.send(text)32  },33  toUsers(userIds: Iterable<string>, msg: unknown, exceptDevice?: string | null) {34    for (const u of userIds) hub.toUser(u, msg, exceptDevice)35  },36  toDevice(userId: string, deviceId: string, msg: unknown) {37    const s = byUser.get(userId)38    if (!s) return39    const text = JSON.stringify(msg)40    for (const c of s) if (c.deviceId === deviceId && c.ws.readyState === 1) c.ws.send(text)41  },42  closeSession(sessionId: string) {43    for (const s of byUser.values()) for (const c of s) if (c.sessionId === sessionId) c.ws.close(4001, "session revoked")44  },45  closeUser(userId: string) {46    const s = byUser.get(userId)47    if (s) for (const c of s) c.ws.close(4001, "session revoked")48  },49  bindDevice(sessionId: string, deviceId: string) {50    for (const s of byUser.values()) for (const c of s) if (c.sessionId === sessionId) c.deviceId = deviceId51  },52}53export type { Conn }5455export async function memberIds(conversationId: string): Promise<string[]> {56  const rows = await sql`select user_id from conversation_members where conversation_id = ${conversationId} and left_at is null`57  return rows.map((r) => r.user_id as string)58}5960/** Users who share at least one conversation with `userId` (used for presence and directory events). */61export async function peersOf(userId: string): Promise<string[]> {62  const rows = await sql`63    select distinct m2.user_id from conversation_members m164    join conversation_members m2 on m2.conversation_id = m1.conversation_id and m2.left_at is null65    where m1.user_id = ${userId} and m1.left_at is null`66  return rows.map((r) => r.user_id as string)67}68
Files main
Menu

Theme