All files / web/src/hooks useRemoteCameraSession.ts

93.46% Statements 143/153
65.21% Branches 15/23
100% Functions 1/1
93.46% Lines 143/153

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 1541x 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 24x 24x 24x 24x 24x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 1x 1x 1x 1x 5x 5x 5x 24x 24x 24x 5x 5x 5x 5x 5x 5x 5x 4x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 1x 1x 5x 5x 5x 24x 24x 24x 1x 1x 24x 24x 24x 2x 1x 1x 2x 1x 1x 1x 1x 1x 1x 2x               2x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x  
'use client'
 
import { useCallback, useState } from 'react'
 
interface RemoteCameraSession {
  sessionId: string
  expiresAt: string
  phoneConnected?: boolean
}
 
interface UseRemoteCameraSessionReturn {
  /** Current session data */
  session: RemoteCameraSession | null
  /** Whether a session is being created or validated */
  isCreating: boolean
  /** Error message if session creation failed */
  error: string | null
  /** Create a new remote camera session */
  createSession: () => Promise<RemoteCameraSession | null>
  /** Validate and set an existing session ID (returns true if valid, false if expired) */
  validateAndSetSession: (sessionId: string) => Promise<boolean>
  /** Clear the current session */
  clearSession: () => void
  /** Get the URL for the phone to scan */
  getPhoneUrl: () => string | null
}
 
/**
 * Hook for managing remote camera sessions
 *
 * Used by the desktop to create sessions and generate QR codes
 * for phones to scan.
 */
export function useRemoteCameraSession(): UseRemoteCameraSessionReturn {
  const [session, setSession] = useState<RemoteCameraSession | null>(null)
  const [isCreating, setIsCreating] = useState(false)
  const [error, setError] = useState<string | null>(null)
 
  const createSession = useCallback(async (): Promise<RemoteCameraSession | null> => {
    setIsCreating(true)
    setError(null)
 
    try {
      const response = await fetch('/api/remote-camera', {
        method: 'POST',
      })
 
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.error || 'Failed to create session')
      }
 
      const data = await response.json()
      const newSession: RemoteCameraSession = {
        sessionId: data.sessionId,
        expiresAt: data.expiresAt,
        phoneConnected: false,
      }
 
      setSession(newSession)
      return newSession
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to create session'
      setError(message)
      console.error('Failed to create remote camera session:', err)
      return null
    } finally {
      setIsCreating(false)
    }
  }, [])
 
  const validateAndSetSession = useCallback(async (sessionId: string): Promise<boolean> => {
    // Validate the session exists on the server before using it
    // This prevents using stale session IDs from localStorage after server restart or expiration
    setIsCreating(true)
    setError(null)
 
    try {
      const response = await fetch(`/api/remote-camera?sessionId=${encodeURIComponent(sessionId)}`)
 
      if (response.ok) {
        const data = await response.json()
        setSession({
          sessionId: data.sessionId,
          expiresAt: data.expiresAt,
          phoneConnected: data.phoneConnected ?? false,
        })
        return true
      } else {
        // Session expired or invalid - caller should create a new one
        console.log(
          '[useRemoteCameraSession] Session validation failed, session expired or invalid'
        )
        return false
      }
    } catch (err) {
      console.error('[useRemoteCameraSession] Failed to validate session:', err)
      return false
    } finally {
      setIsCreating(false)
    }
  }, [])
 
  const clearSession = useCallback(() => {
    setSession(null)
    setError(null)
  }, [])
 
  const getPhoneUrl = useCallback((): string | null => {
    if (!session) return null
 
    // Get the base URL - prefer LAN host for phone access
    if (typeof window === 'undefined') return null
 
    // Use NEXT_PUBLIC_LAN_HOST if set, otherwise construct from current location
    // This allows phones on the same network to reach the server
    let baseUrl: string
 
    const lanHost = process.env.NEXT_PUBLIC_LAN_HOST
    if (lanHost) {
      // If just hostname/IP provided, use current protocol and port
      if (lanHost.includes('://')) {
        baseUrl = lanHost
      } else {
        const port = window.location.port ? `:${window.location.port}` : ''
        baseUrl = `${window.location.protocol}//${lanHost}${port}`
      }
    } else {
      // Fallback: replace localhost with local IP if possible
      const hostname = window.location.hostname
      if (hostname === 'localhost' || hostname === '127.0.0.1') {
        // Try to use the page's own hostname as-is (might already be LAN address)
        // For true localhost, user needs to set NEXT_PUBLIC_LAN_HOST
        baseUrl = window.location.origin
      } else {
        // Already using a non-localhost address (e.g., LAN IP, domain)
        baseUrl = window.location.origin
      }
    }
 
    return `${baseUrl}/remote-camera/${session.sessionId}`
  }, [session])
 
  return {
    session,
    isCreating,
    error,
    createSession,
    validateAndSetSession,
    clearSession,
    getPhoneUrl,
  }
}