All files / web/src/lib/remote-camera session-manager.ts

76.72% Statements 244/318
72.97% Branches 27/37
91.66% Functions 11/12
76.72% Lines 244/318

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 3191x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 70x 70x 1x 1x 1x 1x 1x 1x 1x 70x 70x 1x                     1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x     18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 9x   9x 6x 6x 6x 6x 6x 1x 1x 1x 1x 6x 6x 6x 6x                       6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x                         4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 22x 22x 22x 22x 22x 22x                           22x 22x 22x 22x 14x 14x 22x 2x 2x 2x 12x 12x 12x 1x 1x 1x 1x 6x 6x 6x 6x                     6x 6x 6x 6x 5x 5x 5x 5x 5x 1x 1x 1x 1x 2x 2x 2x 2x                   2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x       2x 2x 2x 1x 1x 1x 1x 4x 4x 4x 4x       4x 4x 4x  
/**
 * Remote Camera Session Manager
 *
 * Manages sessions for phone-to-desktop camera streaming.
 * Uses Redis when REDIS_URL is set (production), falls back to in-memory (dev).
 * Sessions have a 60-minute TTL but are renewed on activity.
 */
 
import { createId } from '@paralleldrive/cuid2'
import { getRedisClient } from '../redis'
 
export interface RemoteCameraSession {
  id: string
  createdAt: string // ISO string for JSON serialization
  expiresAt: string
  lastActivityAt: string
  phoneConnected: boolean
  /** Calibration data sent from desktop (persists for reconnects) */
  calibration?: {
    corners: {
      topLeft: { x: number; y: number }
      topRight: { x: number; y: number }
      bottomLeft: { x: number; y: number }
      bottomRight: { x: number; y: number }
    }
    columnCount?: number
  }
}
 
// In-memory session storage (fallback when Redis not available)
// Using globalThis to persist across hot reloads in development
declare global {
  // eslint-disable-next-line no-var
  var __remoteCameraSessions: Map<string, RemoteCameraSession> | undefined
  // eslint-disable-next-line no-var
  var __remoteCameraCleanupStarted: boolean | undefined
}
 
const SESSION_TTL_MS = 60 * 60 * 1000 // 60 minutes
const SESSION_TTL_SECONDS = 60 * 60 // 60 minutes (for Redis)
const CLEANUP_INTERVAL_MS = 60 * 1000 // 1 minute
const REDIS_KEY_PREFIX = 'remote-camera:session:'
 
function getMemorySessions(): Map<string, RemoteCameraSession> {
  if (!globalThis.__remoteCameraSessions) {
    globalThis.__remoteCameraSessions = new Map()
    // Start cleanup interval only once
    if (!globalThis.__remoteCameraCleanupStarted) {
      globalThis.__remoteCameraCleanupStarted = true
      setInterval(cleanupExpiredMemorySessions, CLEANUP_INTERVAL_MS)
    }
  }
  return globalThis.__remoteCameraSessions
}
 
function cleanupExpiredMemorySessions(): void {
  const sessions = getMemorySessions()
  const now = new Date().toISOString()

  for (const [id, session] of sessions) {
    if (now > session.expiresAt) {
      sessions.delete(id)
    }
  }
}
 
/**
 * Create a new remote camera session
 */
export async function createRemoteCameraSession(): Promise<RemoteCameraSession> {
  const now = new Date()
  const expiresAt = new Date(now.getTime() + SESSION_TTL_MS)
 
  const session: RemoteCameraSession = {
    id: createId(),
    createdAt: now.toISOString(),
    expiresAt: expiresAt.toISOString(),
    lastActivityAt: now.toISOString(),
    phoneConnected: false,
  }
 
  const redis = getRedisClient()
  if (redis) {
    await redis.setex(REDIS_KEY_PREFIX + session.id, SESSION_TTL_SECONDS, JSON.stringify(session))
    console.log(`[SessionManager] Created session ${session.id} in Redis`)
  } else {
    getMemorySessions().set(session.id, session)
    console.log(`[SessionManager] Created session ${session.id} in memory`)
  }
 
  return session
}
 
/**
 * Get or create a session by ID
 * If the session exists and isn't expired, returns it (renewed)
 * If the session doesn't exist, creates a new one with the given ID
 */
export async function getOrCreateSession(sessionId: string): Promise<RemoteCameraSession> {
  const existing = await getRemoteCameraSession(sessionId)
 
  if (existing) {
    // Renew TTL on access
    await renewSessionTTL(sessionId)
    return existing
  }
 
  // Create new session with provided ID
  const now = new Date()
  const expiresAt = new Date(now.getTime() + SESSION_TTL_MS)
 
  const session: RemoteCameraSession = {
    id: sessionId,
    createdAt: now.toISOString(),
    expiresAt: expiresAt.toISOString(),
    lastActivityAt: now.toISOString(),
    phoneConnected: false,
  }
 
  const redis = getRedisClient()
  if (redis) {
    await redis.setex(REDIS_KEY_PREFIX + session.id, SESSION_TTL_SECONDS, JSON.stringify(session))
  } else {
    getMemorySessions().set(session.id, session)
  }
 
  return session
}
 
/**
 * Renew session TTL (call on activity to keep session alive)
 */
export async function renewSessionTTL(sessionId: string): Promise<boolean> {
  const redis = getRedisClient()
 
  if (redis) {
    const data = await redis.get(REDIS_KEY_PREFIX + sessionId)
    if (!data) return false

    const session: RemoteCameraSession = JSON.parse(data)
    const now = new Date()
    session.expiresAt = new Date(now.getTime() + SESSION_TTL_MS).toISOString()
    session.lastActivityAt = now.toISOString()

    await redis.setex(REDIS_KEY_PREFIX + sessionId, SESSION_TTL_SECONDS, JSON.stringify(session))
    return true
  }
 
  const sessions = getMemorySessions()
  const session = sessions.get(sessionId)
  if (!session) return false
 
  const now = new Date()
  session.expiresAt = new Date(now.getTime() + SESSION_TTL_MS).toISOString()
  session.lastActivityAt = now.toISOString()
  return true
}
 
/**
 * Store calibration data in session (persists for reconnects)
 */
export async function setSessionCalibration(
  sessionId: string,
  calibration: RemoteCameraSession['calibration']
): Promise<boolean> {
  const redis = getRedisClient()
 
  if (redis) {
    const data = await redis.get(REDIS_KEY_PREFIX + sessionId)
    if (!data) return false

    const session: RemoteCameraSession = JSON.parse(data)
    session.calibration = calibration
    const now = new Date()
    session.expiresAt = new Date(now.getTime() + SESSION_TTL_MS).toISOString()
    session.lastActivityAt = now.toISOString()

    await redis.setex(REDIS_KEY_PREFIX + sessionId, SESSION_TTL_SECONDS, JSON.stringify(session))
    return true
  }
 
  const sessions = getMemorySessions()
  const session = sessions.get(sessionId)
  if (!session) return false
 
  session.calibration = calibration
  const now = new Date()
  session.expiresAt = new Date(now.getTime() + SESSION_TTL_MS).toISOString()
  session.lastActivityAt = now.toISOString()
  return true
}
 
/**
 * Get calibration data from session
 */
export async function getSessionCalibration(
  sessionId: string
): Promise<RemoteCameraSession['calibration'] | null> {
  const session = await getRemoteCameraSession(sessionId)
  if (!session) return null
  return session.calibration || null
}
 
/**
 * Get a session by ID
 */
export async function getRemoteCameraSession(
  sessionId: string
): Promise<RemoteCameraSession | null> {
  const redis = getRedisClient()
 
  if (redis) {
    const data = await redis.get(REDIS_KEY_PREFIX + sessionId)
    if (!data) return null

    const session: RemoteCameraSession = JSON.parse(data)

    // Check if expired (Redis TTL should handle this, but double-check)
    if (new Date().toISOString() > session.expiresAt) {
      await redis.del(REDIS_KEY_PREFIX + sessionId)
      return null
    }

    return session
  }
 
  const sessions = getMemorySessions()
  const session = sessions.get(sessionId)
  if (!session) return null
 
  // Check if expired
  if (new Date().toISOString() > session.expiresAt) {
    sessions.delete(sessionId)
    return null
  }
 
  return session
}
 
/**
 * Mark a session as having a connected phone
 */
export async function markPhoneConnected(sessionId: string): Promise<boolean> {
  const redis = getRedisClient()
 
  if (redis) {
    const data = await redis.get(REDIS_KEY_PREFIX + sessionId)
    if (!data) return false

    const session: RemoteCameraSession = JSON.parse(data)
    session.phoneConnected = true
    session.expiresAt = new Date(Date.now() + SESSION_TTL_MS).toISOString()

    await redis.setex(REDIS_KEY_PREFIX + sessionId, SESSION_TTL_SECONDS, JSON.stringify(session))
    return true
  }
 
  const sessions = getMemorySessions()
  const session = sessions.get(sessionId)
  if (!session) return false
 
  session.phoneConnected = true
  session.expiresAt = new Date(Date.now() + SESSION_TTL_MS).toISOString()
  return true
}
 
/**
 * Mark a session as having the phone disconnected
 */
export async function markPhoneDisconnected(sessionId: string): Promise<boolean> {
  const redis = getRedisClient()
 
  if (redis) {
    const data = await redis.get(REDIS_KEY_PREFIX + sessionId)
    if (!data) return false

    const session: RemoteCameraSession = JSON.parse(data)
    session.phoneConnected = false

    await redis.setex(REDIS_KEY_PREFIX + sessionId, SESSION_TTL_SECONDS, JSON.stringify(session))
    return true
  }
 
  const sessions = getMemorySessions()
  const session = sessions.get(sessionId)
  if (!session) return false
 
  session.phoneConnected = false
  return true
}
 
/**
 * Delete a session
 */
export async function deleteRemoteCameraSession(sessionId: string): Promise<boolean> {
  const redis = getRedisClient()
 
  if (redis) {
    const result = await redis.del(REDIS_KEY_PREFIX + sessionId)
    return result > 0
  }
 
  return getMemorySessions().delete(sessionId)
}
 
/**
 * Get session count (for debugging)
 */
export async function getSessionCount(): Promise<number> {
  const redis = getRedisClient()
 
  if (redis) {
    const keys = await redis.keys(REDIS_KEY_PREFIX + '*')
    return keys.length
  }
 
  return getMemorySessions().size
}