Compare commits

...

2 Commits

Author SHA1 Message Date
9e7e06d477 Agregar botones de eventos Frigate al visor de streams
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 2m46s
- Nuevo composable useFrigateEvents.ts para crear eventos en Frigate
- Boton "Evento Rapido" crea eventoWhisper de 1 minuto
- Boton de configuracion abre modal con campos personalizables
- Modal permite editar: label, sub_label, duration, include_recording
- API: POST camaras.nucleoriofrio.com/api/events/{camera}/create
2025-12-30 02:42:58 -06:00
d780fd962f Agregar reproductor de streams con seleccion de tipo
- Nuevo composable useStreams.ts para gestionar streams de go2rtc
- Componente StreamPlayer.vue para reproduccion (iframe/video/img)
- Componente StreamViewer.vue con dropdowns de seleccion
- Integrado en app.vue despues del card de grabacion
- Soporta WebRTC, MSE, MP4, HLS y MJPEG
2025-12-30 02:40:51 -06:00
5 changed files with 683 additions and 0 deletions

View File

@@ -84,6 +84,9 @@
</div> </div>
</UCard> </UCard>
<!-- Visor de Streams -->
<StreamsStreamViewer />
<!-- Resultado de transcripción --> <!-- Resultado de transcripción -->
<UCard v-if="transcription || error"> <UCard v-if="transcription || error">
<template #header> <template #header>

View File

@@ -0,0 +1,98 @@
<template>
<div class="stream-player w-full">
<!-- Loading State -->
<div
v-if="isLoading"
class="flex items-center justify-center h-64 bg-gray-100 dark:bg-gray-800 rounded-lg"
>
<div class="text-center">
<UIcon name="i-heroicons-arrow-path" class="w-8 h-8 animate-spin text-green-500" />
<p class="mt-2 text-gray-600 dark:text-gray-400">Cargando stream...</p>
</div>
</div>
<!-- No Stream Selected -->
<div
v-else-if="!streamUrl"
class="flex items-center justify-center h-64 bg-gray-100 dark:bg-gray-800 rounded-lg"
>
<div class="text-center">
<UIcon name="i-heroicons-video-camera-slash" class="w-12 h-12 text-gray-400" />
<p class="mt-2 text-gray-600 dark:text-gray-400">Selecciona un stream para visualizar</p>
</div>
</div>
<!-- Iframe Player (WebRTC/MSE) -->
<iframe
v-else-if="useIframe"
:src="streamUrl"
:key="streamUrl"
class="w-full aspect-video rounded-lg border-0 bg-black"
allow="autoplay; fullscreen"
allowfullscreen
@load="handleLoad"
@error="handleError"
/>
<!-- MJPEG usa img -->
<img
v-else-if="streamType === 'mjpeg'"
:src="streamUrl"
:key="streamUrl"
class="w-full aspect-video rounded-lg object-contain bg-black"
alt="Stream MJPEG"
@load="handleLoad"
@error="handleError"
/>
<!-- Video nativo para MP4 y HLS -->
<video
v-else
ref="videoRef"
:src="streamUrl"
:key="streamUrl"
class="w-full aspect-video rounded-lg bg-black"
controls
autoplay
muted
playsinline
@loadeddata="handleLoad"
@error="handleError"
/>
</div>
</template>
<script setup lang="ts">
import type { StreamType } from '~/composables/useStreams'
const props = defineProps<{
streamUrl: string | null
useIframe: boolean
streamType: StreamType
isLoading?: boolean
}>()
const emit = defineEmits<{
(e: 'loaded'): void
(e: 'error', message: string): void
}>()
const videoRef = ref<HTMLVideoElement | null>(null)
const handleLoad = () => {
emit('loaded')
}
const handleError = () => {
emit('error', 'Error al cargar el stream')
}
</script>
<style scoped>
.stream-player iframe,
.stream-player video,
.stream-player img {
min-height: 200px;
max-height: 400px;
}
</style>

View File

@@ -0,0 +1,319 @@
<template>
<UCard>
<template #header>
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<UIcon name="i-heroicons-video-camera" class="w-5 h-5 text-green-500" />
<h3 class="text-lg font-semibold">Streams de Video</h3>
</div>
<UButton
icon="i-heroicons-arrow-path"
size="sm"
color="neutral"
variant="ghost"
:loading="isLoading"
@click="refreshStreams"
>
Actualizar
</UButton>
</div>
</template>
<!-- Error State -->
<div
v-if="error || eventError"
class="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"
>
<div class="flex items-center gap-2 text-red-600 dark:text-red-400">
<UIcon name="i-heroicons-exclamation-triangle" class="w-5 h-5" />
<span>{{ error || eventError }}</span>
<UButton
size="xs"
color="error"
variant="soft"
@click="handleClearError"
>
Cerrar
</UButton>
</div>
</div>
<!-- Selectores -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
<!-- Selector de Stream -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Stream
</label>
<USelect
v-model="selectedStream"
:items="streamOptions"
placeholder="Seleccionar stream..."
:loading="isLoading"
:disabled="streams.length === 0"
value-key="value"
class="w-full"
/>
</div>
<!-- Selector de Tipo -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Tipo de reproduccion
</label>
<USelect
v-model="selectedType"
:items="streamTypeOptions"
value-key="value"
class="w-full"
/>
</div>
</div>
<!-- Reproductor -->
<StreamsStreamPlayer
:stream-url="getStreamUrl"
:use-iframe="useIframe"
:stream-type="selectedType"
:is-loading="isLoading"
@error="handlePlayerError"
/>
<!-- Botones de Eventos -->
<div v-if="selectedStream" class="mt-4 flex items-center gap-2">
<UButton
icon="i-heroicons-bolt"
color="primary"
:loading="isCreatingEvent"
:disabled="!selectedStream"
@click="handleQuickEvent"
>
Evento Rapido
</UButton>
<UButton
icon="i-heroicons-cog-6-tooth"
color="neutral"
variant="soft"
size="sm"
:disabled="!selectedStream"
@click="showEventModal = true"
/>
</div>
<!-- Info del stream actual -->
<template #footer v-if="selectedStream">
<div class="flex items-center justify-between text-sm text-gray-500">
<span>
<UIcon name="i-heroicons-signal" class="w-4 h-4 inline mr-1" />
{{ selectedStream }}
</span>
<span class="flex items-center gap-1">
<UIcon name="i-heroicons-play-circle" class="w-4 h-4" />
{{ currentTypeDescription }}
</span>
</div>
</template>
</UCard>
<!-- Modal de Evento Personalizado -->
<UModal v-model:open="showEventModal">
<template #content>
<UCard>
<template #header>
<div class="flex items-center gap-2">
<UIcon name="i-heroicons-bolt" class="w-5 h-5 text-primary-500" />
<h3 class="text-lg font-semibold">Crear Evento</h3>
</div>
</template>
<div class="space-y-4">
<!-- Label -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Label *
</label>
<UInput
v-model="eventForm.label"
placeholder="Ej: person, car, eventoWhisper"
/>
</div>
<!-- Sub Label -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Sub Label
</label>
<UInput
v-model="eventForm.sub_label"
placeholder="Etiqueta secundaria (opcional)"
/>
</div>
<!-- Duration -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Duracion (segundos)
</label>
<UInput
v-model.number="eventForm.duration"
type="number"
min="1"
max="3600"
placeholder="60"
/>
</div>
<!-- Include Recording -->
<div class="flex items-center gap-2">
<UCheckbox
v-model="eventForm.include_recording"
label="Incluir grabacion"
/>
</div>
<!-- Camera Info -->
<div class="text-sm text-gray-500 bg-gray-50 dark:bg-gray-800 p-2 rounded">
<span class="font-medium">Camara:</span> {{ selectedStream?.replace(/_main$|_sub$/, '') }}
</div>
</div>
<template #footer>
<div class="flex justify-end gap-2">
<UButton
color="neutral"
variant="ghost"
@click="showEventModal = false"
>
Cancelar
</UButton>
<UButton
color="primary"
:loading="isCreatingEvent"
:disabled="!eventForm.label"
@click="handleCustomEvent"
>
Crear Evento
</UButton>
</div>
</template>
</UCard>
</template>
</UModal>
</template>
<script setup lang="ts">
const {
streams,
selectedStream,
selectedType,
isLoading,
error,
getStreamUrl,
useIframe,
streamTypeOptions,
streamOptions,
fetchStreams,
clearError,
STREAM_TYPES
} = useStreams()
const {
isCreating: isCreatingEvent,
error: eventError,
createEvent,
createQuickEvent,
clearError: clearEventError
} = useFrigateEvents()
const toast = useToast()
// Modal state
const showEventModal = ref(false)
// Form state
const eventForm = reactive({
label: 'eventoWhisper',
sub_label: '',
duration: 60,
include_recording: true
})
// Descripcion del tipo actual
const currentTypeDescription = computed(() => {
const type = STREAM_TYPES.find(t => t.value === selectedType.value)
return type?.description || ''
})
// Cargar streams al montar el componente
onMounted(() => {
fetchStreams()
})
const refreshStreams = () => {
fetchStreams()
}
const handleClearError = () => {
clearError()
clearEventError()
}
const handlePlayerError = (message: string) => {
toast.add({
title: 'Error de reproduccion',
description: message,
icon: 'i-heroicons-exclamation-circle',
color: 'error'
})
}
const handleQuickEvent = async () => {
if (!selectedStream.value) return
const result = await createQuickEvent(selectedStream.value)
if (result.success) {
toast.add({
title: 'Evento creado',
description: 'eventoWhisper (1 minuto)',
icon: 'i-heroicons-check-circle',
color: 'success'
})
} else {
toast.add({
title: 'Error',
description: result.message || 'No se pudo crear el evento',
icon: 'i-heroicons-x-circle',
color: 'error'
})
}
}
const handleCustomEvent = async () => {
if (!selectedStream.value || !eventForm.label) return
const result = await createEvent(selectedStream.value, {
label: eventForm.label,
sub_label: eventForm.sub_label || undefined,
duration: eventForm.duration || 60,
include_recording: eventForm.include_recording
})
if (result.success) {
toast.add({
title: 'Evento creado',
description: `${eventForm.label} (${eventForm.duration}s)`,
icon: 'i-heroicons-check-circle',
color: 'success'
})
showEventModal.value = false
} else {
toast.add({
title: 'Error',
description: result.message || 'No se pudo crear el evento',
icon: 'i-heroicons-x-circle',
color: 'error'
})
}
}
</script>

View File

@@ -0,0 +1,97 @@
/**
* Composable para gestionar eventos de Frigate
* API: https://camaras.nucleoriofrio.com/api/events/{camera}/create
*/
export interface FrigateEventParams {
label: string
sub_label?: string
duration?: number
include_recording?: boolean
draw?: {
boxes?: Array<{
box: [number, number, number, number]
color?: [number, number, number]
score?: number
}>
}
}
export interface FrigateEventResponse {
success: boolean
event_id?: string
message?: string
}
export const useFrigateEvents = () => {
const BASE_URL = 'https://camaras.nucleoriofrio.com'
const isCreating = useState<boolean>('frigate_creating', () => false)
const error = useState<string | null>('frigate_error', () => null)
const lastEventId = useState<string | null>('frigate_last_event', () => null)
/**
* Crea un evento en Frigate para una camara especifica
*/
const createEvent = async (
camera: string,
params: FrigateEventParams
): Promise<FrigateEventResponse> => {
isCreating.value = true
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
}
)
if (response.event_id) {
lastEventId.value = response.event_id
}
return { success: true, ...response }
} catch (err: unknown) {
const errorMessage = (err as Error)?.message || 'Error al crear evento'
error.value = errorMessage
console.error('[Frigate] Error creating event:', err)
return { success: false, message: errorMessage }
} finally {
isCreating.value = false
}
}
/**
* Crea un evento rapido "eventoWhisper" de 1 minuto
*/
const createQuickEvent = async (camera: string): Promise<FrigateEventResponse> => {
return createEvent(camera, {
label: 'eventoWhisper',
duration: 60,
include_recording: true
})
}
/**
* Limpia el error
*/
const clearError = () => {
error.value = null
}
return {
isCreating: readonly(isCreating),
error: readonly(error),
lastEventId: readonly(lastEventId),
createEvent,
createQuickEvent,
clearError
}
}

View File

@@ -0,0 +1,166 @@
/**
* Composable para gestionar streams de video desde go2rtc
* API: https://streams.nucleoriofrio.com/api/streams
*/
export type StreamType = 'webrtc' | 'mse' | 'mp4' | 'hls' | 'mjpeg'
export interface StreamTypeOption {
label: string
value: StreamType
description: string
useIframe: boolean
}
export const STREAM_TYPES: StreamTypeOption[] = [
{
label: 'WebRTC',
value: 'webrtc',
description: 'Menor latencia',
useIframe: true
},
{
label: 'MSE',
value: 'mse',
description: 'Media Source Extensions',
useIframe: true
},
{
label: 'MP4',
value: 'mp4',
description: 'Streaming MP4',
useIframe: false
},
{
label: 'HLS',
value: 'hls',
description: 'HTTP Live Streaming',
useIframe: false
},
{
label: 'MJPEG',
value: 'mjpeg',
description: 'Motion JPEG',
useIframe: false
}
]
export const useStreams = () => {
const BASE_URL = 'https://streams.nucleoriofrio.com'
// Estado reactivo
const streams = useState<string[]>('streams_list', () => [])
const selectedStream = useState<string | null>('streams_selected', () => null)
const selectedType = useState<StreamType>('streams_type', () => 'mse')
const isLoading = useState<boolean>('streams_loading', () => false)
const error = useState<string | null>('streams_error', () => null)
/**
* Obtiene la lista de streams disponibles desde la API
*/
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'
})
// Extraer nombres de streams del objeto
streams.value = Object.keys(response).sort()
// Seleccionar el primero si no hay ninguno seleccionado
if (streams.value.length > 0 && !selectedStream.value) {
selectedStream.value = streams.value[0]
}
} catch (err: unknown) {
const errorMessage = (err as Error)?.message || 'Error al cargar streams'
error.value = errorMessage
console.error('[Streams] Error fetching streams:', err)
} finally {
isLoading.value = false
}
}
/**
* Genera la URL del stream segun el tipo seleccionado
*/
const getStreamUrl = computed((): string | null => {
if (!selectedStream.value) return null
const streamName = encodeURIComponent(selectedStream.value)
switch (selectedType.value) {
case 'webrtc':
return `${BASE_URL}/stream.html?src=${streamName}`
case 'mse':
return `${BASE_URL}/stream.html?src=${streamName}&mode=mse`
case 'mp4':
return `${BASE_URL}/api/stream.mp4?src=${streamName}`
case 'hls':
return `${BASE_URL}/api/stream.m3u8?src=${streamName}`
case 'mjpeg':
return `${BASE_URL}/api/stream.mjpeg?src=${streamName}`
default:
return null
}
})
/**
* Determina si se debe usar iframe o video nativo
*/
const useIframe = computed((): boolean => {
const typeConfig = STREAM_TYPES.find(t => t.value === selectedType.value)
return typeConfig?.useIframe ?? true
})
/**
* Obtiene las opciones para el dropdown de tipos
*/
const streamTypeOptions = computed(() => {
return STREAM_TYPES.map(type => ({
label: type.label,
value: type.value
}))
})
/**
* Obtiene las opciones para el dropdown de streams
*/
const streamOptions = computed(() => {
return streams.value.map(name => ({
label: name.replace(/_/g, ' '),
value: name
}))
})
/**
* Limpia el error
*/
const clearError = () => {
error.value = null
}
return {
// Estado
streams: readonly(streams),
selectedStream,
selectedType,
isLoading: readonly(isLoading),
error: readonly(error),
// Computed
getStreamUrl,
useIframe,
streamTypeOptions,
streamOptions,
// Metodos
fetchStreams,
clearError,
// Constantes
STREAM_TYPES
}
}