Compare commits
7 Commits
9e7e06d477
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 600ef5c96b | |||
| adce97f193 | |||
| 8e555b543d | |||
| 6ddd339c3d | |||
| 9140272940 | |||
| 9608d00484 | |||
| 8cc88c3dc4 |
@@ -13,9 +13,7 @@
|
||||
variant="ghost"
|
||||
:loading="isLoading"
|
||||
@click="refreshStreams"
|
||||
>
|
||||
Actualizar
|
||||
</UButton>
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -66,18 +64,113 @@
|
||||
:items="streamTypeOptions"
|
||||
value-key="value"
|
||||
class="w-full"
|
||||
:disabled="viewMode === 'event'"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reproductor -->
|
||||
<StreamsStreamPlayer
|
||||
:stream-url="getStreamUrl"
|
||||
:use-iframe="useIframe"
|
||||
:stream-type="selectedType"
|
||||
:is-loading="isLoading"
|
||||
@error="handlePlayerError"
|
||||
/>
|
||||
<!-- Toggle Live/Eventos -->
|
||||
<div v-if="selectedStream" class="mb-4">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<UButton
|
||||
:color="viewMode === 'live' ? 'primary' : 'neutral'"
|
||||
:variant="viewMode === 'live' ? 'solid' : 'ghost'"
|
||||
size="sm"
|
||||
icon="i-heroicons-signal"
|
||||
@click="viewMode = 'live'; selectedEventId = null"
|
||||
>
|
||||
En Vivo
|
||||
</UButton>
|
||||
<UButton
|
||||
:color="viewMode === 'event' ? 'primary' : 'neutral'"
|
||||
:variant="viewMode === 'event' ? 'solid' : 'ghost'"
|
||||
size="sm"
|
||||
icon="i-heroicons-film"
|
||||
:loading="isLoadingEvents"
|
||||
@click="viewMode = 'event'"
|
||||
>
|
||||
Eventos ({{ events.length }})
|
||||
</UButton>
|
||||
</div>
|
||||
|
||||
<!-- Selector de Eventos -->
|
||||
<div v-if="viewMode === 'event'" class="mt-2">
|
||||
<USelect
|
||||
v-model="selectedEventId"
|
||||
:items="eventOptions"
|
||||
placeholder="Seleccionar evento..."
|
||||
:loading="isLoadingEvents"
|
||||
:disabled="events.length === 0"
|
||||
value-key="value"
|
||||
class="w-full"
|
||||
/>
|
||||
<p v-if="events.length === 0 && !isLoadingEvents" class="text-sm text-gray-500 mt-1">
|
||||
No hay eventos recientes para esta camara
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Banner de conexión -->
|
||||
<div
|
||||
v-if="!isStreamSessionActive"
|
||||
class="mb-4 p-4 bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-200 dark:border-blue-800 rounded-lg"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="p-2 bg-blue-500/20 rounded-full">
|
||||
<UIcon name="i-heroicons-lock-closed" class="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-gray-800 dark:text-gray-200">Conexion requerida</p>
|
||||
<p class="text-sm text-gray-500">Inicia sesion en Streams para ver el video</p>
|
||||
</div>
|
||||
</div>
|
||||
<UButton
|
||||
icon="i-heroicons-arrow-top-right-on-square"
|
||||
color="primary"
|
||||
:loading="isConnecting"
|
||||
@click="connectToStreams"
|
||||
>
|
||||
Iniciar Sesion
|
||||
</UButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reproductor (solo si hay sesión activa) -->
|
||||
<template v-if="isStreamSessionActive">
|
||||
<!-- Reproductor Live -->
|
||||
<StreamsStreamPlayer
|
||||
v-if="viewMode === 'live'"
|
||||
:key="streamPlayerKey"
|
||||
:stream-url="getStreamUrl"
|
||||
:use-iframe="useIframe"
|
||||
:stream-type="selectedType"
|
||||
:is-loading="isLoading"
|
||||
@error="handlePlayerError"
|
||||
/>
|
||||
|
||||
<!-- Reproductor de Evento -->
|
||||
<div v-else-if="viewMode === 'event'" class="relative aspect-video bg-black rounded-lg overflow-hidden">
|
||||
<video
|
||||
v-if="selectedEventUrl"
|
||||
:key="selectedEventId"
|
||||
:src="selectedEventUrl"
|
||||
controls
|
||||
autoplay
|
||||
class="w-full h-full object-contain"
|
||||
@error="handlePlayerError('Error al cargar el clip del evento')"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="absolute inset-0 flex items-center justify-center text-gray-400"
|
||||
>
|
||||
<div class="text-center">
|
||||
<UIcon name="i-heroicons-film" class="w-12 h-12 mb-2" />
|
||||
<p>Selecciona un evento para reproducir</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Botones de Eventos -->
|
||||
<div v-if="selectedStream" class="mt-4 flex items-center gap-2">
|
||||
@@ -219,7 +312,13 @@ const {
|
||||
|
||||
const {
|
||||
isCreating: isCreatingEvent,
|
||||
isLoadingEvents,
|
||||
error: eventError,
|
||||
events,
|
||||
fetchEvents,
|
||||
getEventClipUrl,
|
||||
getEventSnapshotUrl,
|
||||
formatEventTime,
|
||||
createEvent,
|
||||
createQuickEvent,
|
||||
clearError: clearEventError
|
||||
@@ -230,6 +329,78 @@ const toast = useToast()
|
||||
// Modal state
|
||||
const showEventModal = ref(false)
|
||||
|
||||
// View mode: 'live' or 'event'
|
||||
const viewMode = ref<'live' | 'event'>('live')
|
||||
const selectedEventId = ref<string | null>(null)
|
||||
|
||||
// Estado de conexión a streams
|
||||
const isConnecting = ref(false)
|
||||
const isStreamSessionActive = ref(false)
|
||||
const streamPlayerKey = ref(0) // Para forzar refresh del player
|
||||
|
||||
/**
|
||||
* Abre popup para autenticarse en streams.nucleoriofrio.com
|
||||
* El popup se cierra automáticamente después de cargar
|
||||
*/
|
||||
const connectToStreams = () => {
|
||||
isConnecting.value = true
|
||||
|
||||
const popup = window.open(
|
||||
'https://streams.nucleoriofrio.com/api',
|
||||
'streams_auth',
|
||||
'width=500,height=400,menubar=no,toolbar=no,location=no,status=no'
|
||||
)
|
||||
|
||||
// Verificar cuando el popup carga y cerrarlo
|
||||
const checkPopup = setInterval(() => {
|
||||
try {
|
||||
// Si el popup se cerró manualmente
|
||||
if (!popup || popup.closed) {
|
||||
clearInterval(checkPopup)
|
||||
isConnecting.value = false
|
||||
isStreamSessionActive.value = true
|
||||
streamPlayerKey.value++ // Forzar refresh del player
|
||||
toast.add({
|
||||
title: 'Conectado',
|
||||
description: 'Sesion de streams establecida',
|
||||
icon: 'i-heroicons-check-circle',
|
||||
color: 'success'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Intentar acceder al contenido (solo funciona si ya autenticó)
|
||||
if (popup.document && popup.document.body) {
|
||||
// Cerrar después de 1 segundo para asegurar que la cookie se guardó
|
||||
setTimeout(() => {
|
||||
popup.close()
|
||||
clearInterval(checkPopup)
|
||||
isConnecting.value = false
|
||||
isStreamSessionActive.value = true
|
||||
streamPlayerKey.value++ // Forzar refresh del player
|
||||
toast.add({
|
||||
title: 'Conectado',
|
||||
description: 'Sesion de streams establecida',
|
||||
icon: 'i-heroicons-check-circle',
|
||||
color: 'success'
|
||||
})
|
||||
}, 1000)
|
||||
}
|
||||
} catch {
|
||||
// Error de CORS significa que está en Authentik (aún autenticando)
|
||||
}
|
||||
}, 500)
|
||||
|
||||
// Timeout máximo de 60 segundos
|
||||
setTimeout(() => {
|
||||
clearInterval(checkPopup)
|
||||
isConnecting.value = false
|
||||
if (popup && !popup.closed) {
|
||||
popup.close()
|
||||
}
|
||||
}, 60000)
|
||||
}
|
||||
|
||||
// Form state
|
||||
const eventForm = reactive({
|
||||
label: 'eventoWhisper',
|
||||
@@ -244,6 +415,30 @@ const currentTypeDescription = computed(() => {
|
||||
return type?.description || ''
|
||||
})
|
||||
|
||||
// Opciones para el dropdown de eventos
|
||||
const eventOptions = computed(() => {
|
||||
return events.value.map(e => ({
|
||||
value: e.id,
|
||||
label: `${formatEventTime(e.start_time)} - ${e.label}${e.sub_label ? ` (${e.sub_label})` : ''}`
|
||||
}))
|
||||
})
|
||||
|
||||
// URL del evento seleccionado
|
||||
const selectedEventUrl = computed(() => {
|
||||
if (!selectedEventId.value) return null
|
||||
return getEventClipUrl(selectedEventId.value)
|
||||
})
|
||||
|
||||
// Cargar eventos cuando cambia la cámara
|
||||
watch(() => selectedStream.value, async (newStream) => {
|
||||
if (newStream) {
|
||||
await fetchEvents(newStream, 10)
|
||||
// Reset event selection when camera changes
|
||||
selectedEventId.value = null
|
||||
viewMode.value = 'live'
|
||||
}
|
||||
})
|
||||
|
||||
// Cargar streams al montar el componente
|
||||
onMounted(() => {
|
||||
fetchStreams()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Composable para gestionar eventos de Frigate
|
||||
* API: https://camaras.nucleoriofrio.com/api/events/{camera}/create
|
||||
* Usa proxy backend para evitar problemas de CORS/cookies entre subdominios
|
||||
* API Proxy: /api/frigate/event, /api/frigate/events
|
||||
*/
|
||||
|
||||
export interface FrigateEventParams {
|
||||
@@ -23,15 +24,84 @@ export interface FrigateEventResponse {
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface FrigateEvent {
|
||||
id: string
|
||||
label: string
|
||||
sub_label?: string
|
||||
camera: string
|
||||
start_time: number
|
||||
end_time?: number
|
||||
has_clip: boolean
|
||||
has_snapshot: boolean
|
||||
zones: string[]
|
||||
}
|
||||
|
||||
export const useFrigateEvents = () => {
|
||||
const BASE_URL = 'https://camaras.nucleoriofrio.com'
|
||||
// Ya no usamos URL publica, todo va por proxy interno
|
||||
|
||||
const isCreating = useState<boolean>('frigate_creating', () => false)
|
||||
const isLoadingEvents = useState<boolean>('frigate_loading_events', () => false)
|
||||
const error = useState<string | null>('frigate_error', () => null)
|
||||
const lastEventId = useState<string | null>('frigate_last_event', () => null)
|
||||
const events = useState<FrigateEvent[]>('frigate_events', () => [])
|
||||
|
||||
/**
|
||||
* Crea un evento en Frigate para una camara especifica
|
||||
* Obtiene los eventos recientes de una camara
|
||||
*/
|
||||
const fetchEvents = async (camera?: string, limit: number = 10): Promise<FrigateEvent[]> => {
|
||||
isLoadingEvents.value = true
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
if (camera) {
|
||||
params.set('camera', camera)
|
||||
}
|
||||
params.set('limit', limit.toString())
|
||||
|
||||
const response = await $fetch<FrigateEvent[]>(`/api/frigate/events?${params.toString()}`)
|
||||
|
||||
events.value = response
|
||||
return response
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = (err as Error)?.message || 'Error al obtener eventos'
|
||||
error.value = errorMessage
|
||||
console.error('[Frigate] Error fetching events:', err)
|
||||
return []
|
||||
} finally {
|
||||
isLoadingEvents.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera la URL del clip de un evento (via proxy interno)
|
||||
*/
|
||||
const getEventClipUrl = (eventId: string): string => {
|
||||
return `/api/frigate/events/${eventId}/clip`
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera la URL del snapshot de un evento (via proxy interno)
|
||||
*/
|
||||
const getEventSnapshotUrl = (eventId: string): string => {
|
||||
return `/api/frigate/events/${eventId}/snapshot`
|
||||
}
|
||||
|
||||
/**
|
||||
* Formatea la fecha de un evento
|
||||
*/
|
||||
const formatEventTime = (timestamp: number): string => {
|
||||
const date = new Date(timestamp * 1000)
|
||||
return date.toLocaleString('es-ES', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Crea un evento en Frigate para una camara especifica via proxy
|
||||
*/
|
||||
const createEvent = async (
|
||||
camera: string,
|
||||
@@ -41,17 +111,13 @@ export const useFrigateEvents = () => {
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
// Extraer el nombre base de la camara (sin _main o _sub)
|
||||
const cameraName = camera.replace(/_main$|_sub$/, '')
|
||||
|
||||
const response = await $fetch<FrigateEventResponse>(
|
||||
`${BASE_URL}/api/events/${cameraName}/create`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: params
|
||||
const response = await $fetch<FrigateEventResponse>('/api/frigate/event', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
camera,
|
||||
...params
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
if (response.event_id) {
|
||||
lastEventId.value = response.event_id
|
||||
@@ -87,9 +153,18 @@ export const useFrigateEvents = () => {
|
||||
}
|
||||
|
||||
return {
|
||||
// Estado
|
||||
isCreating: readonly(isCreating),
|
||||
isLoadingEvents: readonly(isLoadingEvents),
|
||||
error: readonly(error),
|
||||
lastEventId: readonly(lastEventId),
|
||||
events: readonly(events),
|
||||
|
||||
// Métodos
|
||||
fetchEvents,
|
||||
getEventClipUrl,
|
||||
getEventSnapshotUrl,
|
||||
formatEventTime,
|
||||
createEvent,
|
||||
createQuickEvent,
|
||||
clearError
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* Composable para gestionar streams de video desde go2rtc
|
||||
* API: https://streams.nucleoriofrio.com/api/streams
|
||||
* Usa proxy backend para evitar problemas de CORS/cookies entre subdominios
|
||||
* API Proxy: /api/streams/list
|
||||
* Streaming: https://streams.nucleoriofrio.com (iframe con sesion propia)
|
||||
*/
|
||||
|
||||
export type StreamType = 'webrtc' | 'mse' | 'mp4' | 'hls' | 'mjpeg'
|
||||
@@ -56,16 +58,15 @@ export const useStreams = () => {
|
||||
const error = useState<string | null>('streams_error', () => null)
|
||||
|
||||
/**
|
||||
* Obtiene la lista de streams disponibles desde la API
|
||||
* Obtiene la lista de streams disponibles via proxy backend
|
||||
*/
|
||||
const fetchStreams = async (): Promise<void> => {
|
||||
isLoading.value = true
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
const response = await $fetch<Record<string, unknown>>(`${BASE_URL}/api/streams`, {
|
||||
credentials: 'include'
|
||||
})
|
||||
// Usar proxy backend para evitar CORS/cookies issues
|
||||
const response = await $fetch<Record<string, unknown>>('/api/streams/list')
|
||||
|
||||
// Extraer nombres de streams del objeto
|
||||
streams.value = Object.keys(response).sort()
|
||||
|
||||
102
nuxt4/server/api/frigate/event.post.ts
Normal file
102
nuxt4/server/api/frigate/event.post.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Proxy endpoint para crear eventos en Frigate
|
||||
* POST /api/frigate/event
|
||||
* Body: { camera: string, label: string, sub_label?: string, duration?: number, include_recording?: boolean }
|
||||
* Usa URL interna del servidor Frigate
|
||||
*/
|
||||
|
||||
interface EventRequestBody {
|
||||
camera: string
|
||||
label: string
|
||||
sub_label?: string
|
||||
duration?: number
|
||||
include_recording?: boolean
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Verificar autenticación via headers de Authentik
|
||||
const headers = getRequestHeaders(event)
|
||||
const username = headers['x-authentik-username']
|
||||
|
||||
if (!username) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: 'No autenticado'
|
||||
})
|
||||
}
|
||||
|
||||
// Leer body
|
||||
const body = await readBody<EventRequestBody>(event)
|
||||
|
||||
if (!body.camera || !body.label) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: 'Se requiere camera y label'
|
||||
})
|
||||
}
|
||||
|
||||
// Extraer nombre base de la cámara (sin _main o _sub)
|
||||
const cameraName = body.camera.replace(/_main$|_sub$/, '')
|
||||
|
||||
// Preparar payload para Frigate
|
||||
const frigatePayload: Record<string, unknown> = {}
|
||||
|
||||
if (body.sub_label) {
|
||||
frigatePayload.sub_label = body.sub_label
|
||||
}
|
||||
|
||||
if (body.duration) {
|
||||
frigatePayload.duration = body.duration
|
||||
}
|
||||
|
||||
if (body.include_recording !== undefined) {
|
||||
frigatePayload.include_recording = body.include_recording
|
||||
}
|
||||
|
||||
// URL interna de Frigate (sin pasar por Traefik/Authentik)
|
||||
const FRIGATE_URL = process.env.FRIGATE_URL || 'http://192.168.87.29:5000'
|
||||
|
||||
try {
|
||||
// API: POST /api/events/:camera_name/:label/create
|
||||
const response = await fetch(
|
||||
`${FRIGATE_URL}/api/events/${cameraName}/${body.label}/create`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(frigatePayload)
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
console.error('[Frigate Proxy] Error response:', errorText)
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
message: `Error al crear evento: ${response.statusText}`
|
||||
})
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
console.log(`[Frigate Proxy] Evento creado por ${username}: ${body.label} en ${cameraName}`)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...data
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error('[Frigate Proxy] Error:', error)
|
||||
|
||||
if ((error as any).statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: (error as Error)?.message || 'Error al crear evento'
|
||||
})
|
||||
}
|
||||
})
|
||||
68
nuxt4/server/api/frigate/events.get.ts
Normal file
68
nuxt4/server/api/frigate/events.get.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Proxy endpoint para obtener eventos de Frigate
|
||||
* GET /api/frigate/events?camera=X&limit=10
|
||||
*/
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Verificar autenticación via headers de Authentik
|
||||
const headers = getRequestHeaders(event)
|
||||
const username = headers['x-authentik-username']
|
||||
|
||||
if (!username) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: 'No autenticado'
|
||||
})
|
||||
}
|
||||
|
||||
// Leer query params
|
||||
const query = getQuery(event)
|
||||
const camera = query.camera as string | undefined
|
||||
const limit = query.limit ? parseInt(query.limit as string) : 10
|
||||
|
||||
// URL interna de Frigate
|
||||
const FRIGATE_URL = process.env.FRIGATE_URL || 'http://192.168.87.29:5000'
|
||||
|
||||
// Construir URL con filtros
|
||||
const params = new URLSearchParams()
|
||||
if (camera) {
|
||||
// Extraer nombre base de la cámara (sin _main o _sub)
|
||||
params.set('camera', camera.replace(/_main$|_sub$/, ''))
|
||||
}
|
||||
params.set('limit', limit.toString())
|
||||
params.set('has_clip', '1') // Solo eventos con clip (1 = true)
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${FRIGATE_URL}/api/events?${params.toString()}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
message: `Error al obtener eventos: ${response.statusText}`
|
||||
})
|
||||
}
|
||||
|
||||
const events = await response.json()
|
||||
|
||||
return events
|
||||
} catch (error: unknown) {
|
||||
console.error('[Frigate Events] Error:', error)
|
||||
|
||||
if ((error as any).statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: (error as Error)?.message || 'Error al obtener eventos'
|
||||
})
|
||||
}
|
||||
})
|
||||
95
nuxt4/server/api/frigate/events/[eventId]/clip.get.ts
Normal file
95
nuxt4/server/api/frigate/events/[eventId]/clip.get.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Proxy endpoint para obtener clips de eventos de Frigate
|
||||
* GET /api/frigate/events/:eventId/clip
|
||||
* Soporta range requests para seeking en video
|
||||
*/
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Verificar autenticación via headers de Authentik
|
||||
const headers = getRequestHeaders(event)
|
||||
const username = headers['x-authentik-username']
|
||||
|
||||
if (!username) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: 'No autenticado'
|
||||
})
|
||||
}
|
||||
|
||||
const eventId = getRouterParam(event, 'eventId')
|
||||
|
||||
if (!eventId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: 'Se requiere eventId'
|
||||
})
|
||||
}
|
||||
|
||||
// URL interna de Frigate
|
||||
const FRIGATE_URL = process.env.FRIGATE_URL || 'http://192.168.87.29:5000'
|
||||
|
||||
try {
|
||||
// Pasar headers de range si existen (para seeking)
|
||||
const requestHeaders: Record<string, string> = {
|
||||
'Accept': 'video/mp4'
|
||||
}
|
||||
|
||||
const rangeHeader = headers['range']
|
||||
if (rangeHeader) {
|
||||
requestHeaders['Range'] = rangeHeader
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${FRIGATE_URL}/api/events/${eventId}/clip.mp4`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: requestHeaders
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok && response.status !== 206) {
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
message: `Error al obtener clip: ${response.statusText}`
|
||||
})
|
||||
}
|
||||
|
||||
// Configurar headers de respuesta
|
||||
const responseHeaders: Record<string, string> = {
|
||||
'Content-Type': 'video/mp4',
|
||||
'Accept-Ranges': 'bytes'
|
||||
}
|
||||
|
||||
const contentLength = response.headers.get('content-length')
|
||||
if (contentLength) {
|
||||
responseHeaders['Content-Length'] = contentLength
|
||||
}
|
||||
|
||||
const contentRange = response.headers.get('content-range')
|
||||
if (contentRange) {
|
||||
responseHeaders['Content-Range'] = contentRange
|
||||
}
|
||||
|
||||
// Establecer headers
|
||||
for (const [key, value] of Object.entries(responseHeaders)) {
|
||||
setResponseHeader(event, key, value)
|
||||
}
|
||||
|
||||
// Establecer status code (200 o 206 para partial content)
|
||||
setResponseStatus(event, response.status)
|
||||
|
||||
// Retornar el stream del video
|
||||
return response.body
|
||||
} catch (error: unknown) {
|
||||
console.error('[Frigate Clip Proxy] Error:', error)
|
||||
|
||||
if ((error as any).statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: (error as Error)?.message || 'Error al obtener clip'
|
||||
})
|
||||
}
|
||||
})
|
||||
73
nuxt4/server/api/frigate/events/[eventId]/snapshot.get.ts
Normal file
73
nuxt4/server/api/frigate/events/[eventId]/snapshot.get.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Proxy endpoint para obtener snapshots de eventos de Frigate
|
||||
* GET /api/frigate/events/:eventId/snapshot
|
||||
*/
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Verificar autenticación via headers de Authentik
|
||||
const headers = getRequestHeaders(event)
|
||||
const username = headers['x-authentik-username']
|
||||
|
||||
if (!username) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: 'No autenticado'
|
||||
})
|
||||
}
|
||||
|
||||
const eventId = getRouterParam(event, 'eventId')
|
||||
|
||||
if (!eventId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: 'Se requiere eventId'
|
||||
})
|
||||
}
|
||||
|
||||
// URL interna de Frigate
|
||||
const FRIGATE_URL = process.env.FRIGATE_URL || 'http://192.168.87.29:5000'
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${FRIGATE_URL}/api/events/${eventId}/snapshot.jpg`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'image/jpeg'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
message: `Error al obtener snapshot: ${response.statusText}`
|
||||
})
|
||||
}
|
||||
|
||||
// Configurar headers de respuesta
|
||||
setResponseHeader(event, 'Content-Type', 'image/jpeg')
|
||||
|
||||
const contentLength = response.headers.get('content-length')
|
||||
if (contentLength) {
|
||||
setResponseHeader(event, 'Content-Length', contentLength)
|
||||
}
|
||||
|
||||
// Cache por 5 minutos (los snapshots no cambian)
|
||||
setResponseHeader(event, 'Cache-Control', 'public, max-age=300')
|
||||
|
||||
// Retornar el stream de la imagen
|
||||
return response.body
|
||||
} catch (error: unknown) {
|
||||
console.error('[Frigate Snapshot Proxy] Error:', error)
|
||||
|
||||
if ((error as any).statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: (error as Error)?.message || 'Error al obtener snapshot'
|
||||
})
|
||||
}
|
||||
})
|
||||
52
nuxt4/server/api/streams/list.get.ts
Normal file
52
nuxt4/server/api/streams/list.get.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Proxy endpoint para obtener la lista de streams de go2rtc
|
||||
* Evita problemas de CORS/cookies entre subdominios
|
||||
* Usa URL interna del servidor go2rtc
|
||||
*/
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Verificar autenticación via headers de Authentik
|
||||
const headers = getRequestHeaders(event)
|
||||
const username = headers['x-authentik-username']
|
||||
|
||||
if (!username) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: 'No autenticado'
|
||||
})
|
||||
}
|
||||
|
||||
// URL interna de go2rtc (sin pasar por Traefik/Authentik)
|
||||
const GO2RTC_URL = process.env.GO2RTC_URL || 'http://192.168.87.29:1984'
|
||||
|
||||
try {
|
||||
const response = await fetch(`${GO2RTC_URL}/api/streams`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
message: `Error al obtener streams: ${response.statusText}`
|
||||
})
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
return data
|
||||
} catch (error: unknown) {
|
||||
console.error('[Streams Proxy] Error:', error)
|
||||
|
||||
if ((error as any).statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: (error as Error)?.message || 'Error al obtener streams'
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user