93 lines
2.4 KiB
JavaScript
93 lines
2.4 KiB
JavaScript
import { closeRouter, getProducer, getTransport } from './mediasoup.js'
|
|
|
|
const TTL_MS = 60_000
|
|
const sessions = new Map()
|
|
|
|
export const createSession = (userId, label = '') => {
|
|
const id = crypto.randomUUID()
|
|
const session = {
|
|
id,
|
|
userId,
|
|
label: (label || 'Live').trim() || 'Live',
|
|
lat: 0,
|
|
lng: 0,
|
|
updatedAt: Date.now(),
|
|
routerId: null,
|
|
producerId: null,
|
|
transportId: null,
|
|
}
|
|
sessions.set(id, session)
|
|
return session
|
|
}
|
|
|
|
export const getLiveSession = (id) => sessions.get(id)
|
|
|
|
export const getActiveSessionByUserId = (userId) => {
|
|
const now = Date.now()
|
|
for (const s of sessions.values()) {
|
|
if (s.userId === userId && now - s.updatedAt <= TTL_MS) return s
|
|
}
|
|
}
|
|
|
|
export const updateLiveSession = (id, updates) => {
|
|
const session = sessions.get(id)
|
|
if (!session) return
|
|
const now = Date.now()
|
|
if (Number.isFinite(updates.lat)) session.lat = updates.lat
|
|
if (Number.isFinite(updates.lng)) session.lng = updates.lng
|
|
if (updates.routerId !== undefined) session.routerId = updates.routerId
|
|
if (updates.producerId !== undefined) session.producerId = updates.producerId
|
|
if (updates.transportId !== undefined) session.transportId = updates.transportId
|
|
session.updatedAt = now
|
|
}
|
|
|
|
export const deleteLiveSession = (id) => sessions.delete(id)
|
|
|
|
export const clearSessions = () => sessions.clear()
|
|
|
|
const cleanupSession = async (session) => {
|
|
if (session.producerId) {
|
|
const producer = getProducer(session.producerId)
|
|
producer?.close()
|
|
}
|
|
if (session.transportId) {
|
|
const transport = getTransport(session.transportId)
|
|
transport?.close()
|
|
}
|
|
if (session.routerId) {
|
|
await closeRouter(session.id).catch((err) => {
|
|
console.error(`[liveSessions] Error closing router for expired session ${session.id}:`, err)
|
|
})
|
|
}
|
|
}
|
|
|
|
export const getActiveSessions = async () => {
|
|
const now = Date.now()
|
|
const active = []
|
|
const expired = []
|
|
|
|
for (const session of sessions.values()) {
|
|
if (now - session.updatedAt <= TTL_MS) {
|
|
active.push({
|
|
id: session.id,
|
|
userId: session.userId,
|
|
label: session.label,
|
|
lat: session.lat,
|
|
lng: session.lng,
|
|
updatedAt: session.updatedAt,
|
|
hasStream: Boolean(session.producerId),
|
|
})
|
|
}
|
|
else {
|
|
expired.push(session)
|
|
}
|
|
}
|
|
|
|
for (const session of expired) {
|
|
await cleanupSession(session)
|
|
sessions.delete(session.id)
|
|
}
|
|
|
|
return active
|
|
}
|