Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202import { EventEmitter } from 'node:events'import { env } from './env.ts'import { xrpcGet } from './atproto/identity.ts'import type { ActivityRef } from '../shared/schemas.ts'import { ACTIVITY_LABELS } from '../shared/format.ts'
export interface ProfileViewBasic { did: string handle: string displayName?: string avatar?: string}
export interface ChatMessageView { uri: string cid: string author: ProfileViewBasic record: { text: string streamer: string createdAt: string reply?: { root: { uri: string; cid: string }; parent: { uri: string; cid: string } } facets?: { index: { byteStart: number; byteEnd: number }; features: { $type: string; uri?: string; did?: string }[] }[] } indexedAt: string chatProfile?: { color?: { red: number; green: number; blue: number }; selfLabels?: string[] } badges?: { badgeType: string; issuer: string; recipient: string }[] deleted?: boolean}
export interface LivestreamRecord { title: string createdAt: string endedAt?: string | null lastSeenAt?: string activity?: { $type: string; uri?: string; name?: string; label?: string } tags?: string[] canonicalUrl?: string}
export interface LivestreamView { uri: string cid: string author: ProfileViewBasic record: LivestreamRecord indexedAt: string viewerCount?: { count: number }}
export function activityFromRecord(a: LivestreamRecord['activity']): ActivityRef | null { if (!a) return null if (a.$type?.endsWith('#activityGame') && a.uri) return { kind: 'game', id: a.uri, name: a.name ?? 'Unknown game' } if (a.$type?.endsWith('#activityLabel') && a.label) return { kind: 'label', id: a.label, name: ACTIVITY_LABELS[a.label] ?? a.label } return null}
/** Streams the node considers live right now. */export async function getLiveUsers(): Promise<LivestreamView[]> { const out: LivestreamView[] = [] let before: string | undefined for (let page = 0; page < 5; page++) { const res = await xrpcGet<{ streams: LivestreamView[] }>(env.streamplaceUrl, 'place.stream.live.getLiveUsers', { limit: 100, before }) out.push(...res.streams) if (res.streams.length < 100) break before = res.streams[res.streams.length - 1].record.createdAt } return out}
export interface GameResult { uri: string name: string coverUrl?: string}
export async function searchGames(q: string): Promise<GameResult[]> { const res = await xrpcGet<{ results: { $type?: string; uri?: string; name?: string; title?: string; coverUrl?: string; cover?: string }[] }>( env.streamplaceUrl, 'place.stream.game.search', { q, limit: 10 }, ) return res.results .filter((r) => (r.$type ?? '').includes('gameSummaryView') || r.name) .map((r) => ({ uri: r.uri ?? '', name: r.name ?? r.title ?? 'Unknown', coverUrl: r.coverUrl ?? r.cover })) .filter((r) => r.uri)}
export interface TeleportInfo { uri: string source: ProfileViewBasic viewers: number}
type SocketEvents = { message: [ChatMessageView] history: [ChatMessageView] livestream: [LivestreamView] viewers: [number] teleport: [TeleportInfo] block: [{ subject: string }] status: ['connected' | 'disconnected']}
/** * One websocket per channel to the Streamplace node. Replayed history on * connect is emitted as `history`; everything after that as `message`. */export class ChatSocket extends EventEmitter<SocketEvents> { readonly did: string private ws: WebSocket | null = null private closed = false private backoff = 1000 private connectedAt = 0 private seen = new Set<string>() private watchdog: NodeJS.Timeout | null = null
constructor(did: string) { super() this.did = did }
start() { this.closed = false this.connect() }
stop() { this.closed = true if (this.watchdog) clearInterval(this.watchdog) this.ws?.close() this.ws = null }
private connect() { if (this.closed) return const url = `${env.streamplaceUrl.replace(/^http/, 'ws')}/api/websocket/${this.did}` const ws = new WebSocket(url) this.ws = ws let lastFrame = Date.now() ws.onopen = () => { this.connectedAt = Date.now() this.backoff = 1000 this.emit('status', 'connected') } ws.onmessage = (ev) => { lastFrame = Date.now() try { this.handle(JSON.parse(String(ev.data))) } catch (err) { console.warn(`[ws ${this.did}] bad frame`, err) } } ws.onclose = () => { if (this.watchdog) clearInterval(this.watchdog) this.emit('status', 'disconnected') if (this.closed) return setTimeout(() => this.connect(), this.backoff) this.backoff = Math.min(this.backoff * 2, 60_000) } ws.onerror = () => ws.close() // The node sends segments and viewer counts every few seconds while live, // and pings otherwise. Reconnect if the socket goes completely silent. if (this.watchdog) clearInterval(this.watchdog) this.watchdog = setInterval(() => { if (Date.now() - lastFrame > 5 * 60_000) ws.close() }, 60_000) }
private handle(frame: { $type?: string } & Record<string, unknown>) { switch (frame.$type) { case 'place.stream.chat.defs#messageView': { const msg = frame as unknown as ChatMessageView if (msg.deleted) return if (this.seen.has(msg.uri)) return this.seen.add(msg.uri) if (this.seen.size > 2000) this.seen.delete(this.seen.values().next().value!) const indexed = Date.parse(msg.indexedAt) // Replayed history arrives in the first moments after connecting and predates it. if (indexed < this.connectedAt - 2000) this.emit('history', msg) else this.emit('message', msg) return } case 'place.stream.livestream#livestreamView': this.emit('livestream', frame as unknown as LivestreamView) return case 'place.stream.livestream#viewerCount': this.emit('viewers', Number(frame.count) || 0) return case 'place.stream.livestream#teleportArrival': { const source = frame.source as ProfileViewBasic this.emit('teleport', { uri: String(frame.teleportUri), source, viewers: Number(frame.viewerCount) || 0 }) return } case 'place.stream.defs#blockView': { const record = frame.record as { subject?: string } if (record?.subject) this.emit('block', { subject: record.subject }) return } } }}