Compare commits
7 Commits
dev_mtls
...
89c44d2979
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89c44d2979 | ||
|
|
f59883315d | ||
|
|
af7c659bef | ||
|
|
40b7e590a3 | ||
|
|
bdb89f0966 | ||
|
|
2895c6afdd | ||
|
|
ee210e847e |
@@ -44,9 +44,9 @@ services:
|
||||
args:
|
||||
APP_DIR: ${API_APP_DIR:-./cmd/api}
|
||||
environment:
|
||||
VAULT_ADDR: "http://vault:8200"
|
||||
VAULT_TOKEN: "root"
|
||||
VAULT_KV_PATH: "kv/data/snoop"
|
||||
VAULT_ADDR: "http://host.docker.internal:8200"
|
||||
VAULT_TOKEN: "hvs.tZ4eh9P18sCZ5c1PZIz59EmH"
|
||||
# VAULT_KV_PATH: "kv/data/snoop"
|
||||
MINIO_ENDPOINT: "http://minio:9000"
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
env_file:
|
||||
|
||||
7
management-ui/package-lock.json
generated
7
management-ui/package-lock.json
generated
@@ -14,6 +14,7 @@
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"hls.js": "^1.6.13",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-vue-next": "^0.525.0",
|
||||
"reka-ui": "^2.5.0",
|
||||
@@ -2006,6 +2007,12 @@
|
||||
"he": "bin/he"
|
||||
}
|
||||
},
|
||||
"node_modules/hls.js": {
|
||||
"version": "1.6.13",
|
||||
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.13.tgz",
|
||||
"integrity": "sha512-hNEzjZNHf5bFrUNvdS4/1RjIanuJ6szpWNfTaX5I6WfGynWXGT7K/YQLYtemSvFExzeMdgdE4SsyVLJbd5PcZA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/jiti": {
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.5.1.tgz",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"hls.js": "^1.6.13",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-vue-next": "^0.525.0",
|
||||
"reka-ui": "^2.5.0",
|
||||
|
||||
@@ -74,15 +74,6 @@ function onSelect(ev: CustomEvent) {
|
||||
// When parent switches between external/internal data at runtime, refetch if needed.
|
||||
watch(() => props.allUsers, () => { if (!usingExternal.value) loadUsers() })
|
||||
|
||||
// Debug: whenever modelValue changes (from dialog)
|
||||
watch(() => props.modelValue, (v) => {
|
||||
console.log('[AssignDevice:props.modelValue]', v)
|
||||
}, { immediate: true })
|
||||
|
||||
// Debug: when effective users list is ready
|
||||
watch(() => effectiveUsers.value, (v) => {
|
||||
console.log('[AssignDevice:effectiveUsers]', v?.length, 'items')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
124
management-ui/src/customcompometns/DataTableNoCheckboxScroll.vue
Normal file
124
management-ui/src/customcompometns/DataTableNoCheckboxScroll.vue
Normal file
@@ -0,0 +1,124 @@
|
||||
<script setup lang="ts" generic="TData, TValue">
|
||||
import { defineProps } from 'vue'
|
||||
import type { DefineComponent } from 'vue'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import {
|
||||
useVueTable,
|
||||
getCoreRowModel,
|
||||
FlexRender,
|
||||
} from '@tanstack/vue-table'
|
||||
|
||||
import {
|
||||
Table, TableHeader, TableRow, TableHead, TableBody, TableCell,
|
||||
} from '@/components/ui/table'
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area' // <-- add ScrollBar
|
||||
|
||||
const props = defineProps<{
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
dropdownComponent?: DefineComponent<{ row: TData }, any, any>
|
||||
dropdownProps?: Record<string, any>
|
||||
/** Optional tailwind class to control min table width for horizontal scrolling */
|
||||
minTableWidth?: string
|
||||
}>()
|
||||
|
||||
const table = useVueTable({
|
||||
get data() { return props.data },
|
||||
get columns() { return props.columns },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'row-updated', row: TData, payload: any): void
|
||||
(e: 'row-deleted', row: TData): void
|
||||
}>()
|
||||
|
||||
const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-full h-full border rounded-md flex flex-col">
|
||||
<!-- Both-direction scroll area -->
|
||||
<ScrollArea class="flex-1 w-full">
|
||||
<!-- The min-width container enables horizontal scroll on small displays -->
|
||||
<div :class="['w-full', minWidthClass]">
|
||||
<Table class="w-full">
|
||||
<!-- header -->
|
||||
<TableHeader>
|
||||
<TableRow
|
||||
v-for="headerGroup in table.getHeaderGroups()"
|
||||
:key="headerGroup.id"
|
||||
>
|
||||
<TableHead
|
||||
v-for="header in headerGroup.headers"
|
||||
:key="header.id"
|
||||
class="sticky top-0 bg-background z-10 whitespace-nowrap"
|
||||
>
|
||||
<FlexRender
|
||||
v-if="!header.isPlaceholder"
|
||||
:render="header.column.columnDef.header"
|
||||
:props="header.getContext()"
|
||||
/>
|
||||
</TableHead>
|
||||
|
||||
<!-- extra empty head for dropdown column -->
|
||||
<TableHead
|
||||
v-if="props.dropdownComponent"
|
||||
class="sticky top-0 bg-background z-10 w-12"
|
||||
/>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
||||
<!-- body -->
|
||||
<TableBody>
|
||||
<template v-if="table.getRowModel().rows.length">
|
||||
<TableRow
|
||||
v-for="row in table.getRowModel().rows"
|
||||
:key="row.id"
|
||||
class="whitespace-nowrap"
|
||||
>
|
||||
<!-- data cells -->
|
||||
<TableCell
|
||||
v-for="cell in row.getVisibleCells()"
|
||||
:key="cell.id"
|
||||
>
|
||||
<FlexRender
|
||||
:render="cell.column.columnDef.cell"
|
||||
:props="cell.getContext()"
|
||||
/>
|
||||
</TableCell>
|
||||
|
||||
<!-- dropdown cell -->
|
||||
<TableCell v-if="props.dropdownComponent" class="text-right">
|
||||
<component
|
||||
:is="props.dropdownComponent"
|
||||
:row="row.original"
|
||||
v-bind="props.dropdownProps"
|
||||
@updated="(payload: any) => emit('row-updated', row.original, payload)"
|
||||
@deleted="() => emit('row-deleted', row.original)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
|
||||
<!-- no-data row -->
|
||||
<template v-else>
|
||||
<TableRow>
|
||||
<TableCell
|
||||
:colspan="props.columns.length + (props.dropdownComponent ? 1 : 0)"
|
||||
class="h-24 text-center"
|
||||
>
|
||||
No data.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<!-- Scrollbars -->
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<ScrollBar orientation="vertical" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -8,41 +8,124 @@ import {
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { Device } from '@/lib/interfaces';
|
||||
import type { PropType } from 'vue';
|
||||
|
||||
import type { Device } from '@/lib/interfaces'
|
||||
import type { PropType } from 'vue'
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
device: { type: Object as PropType<Device>, required: false },
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm'): void
|
||||
}>()
|
||||
|
||||
function onSave() {
|
||||
emit('confirm')
|
||||
// close the dialog
|
||||
// --- DTOs from backend ---
|
||||
type DeviceCertDto = {
|
||||
id: number
|
||||
deviceGuid: string
|
||||
serialHex: string
|
||||
issuerCN: string
|
||||
subjectDN: string
|
||||
notBefore: string // ISO timestamps as strings when serialized
|
||||
notAfter: string
|
||||
createdAt: string
|
||||
}
|
||||
type DeviceCertListDto = { certs: DeviceCertDto[] }
|
||||
|
||||
// --- local state ---
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const certs = ref<DeviceCertDto[]>([])
|
||||
|
||||
const guid = computed(() => props.device?.guid ?? '')
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const columns: ColumnDef<DeviceCertDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
{ accessorKey: 'serialHex', header: 'Serial (hex)' },
|
||||
{ accessorKey: 'issuerCN', header: 'Issuer CN' },
|
||||
{ accessorKey: 'subjectDN', header: 'Subject DN' },
|
||||
{ accessorKey: 'notBefore', header: 'Not Before', cell: ({ row }) => fmt(row.original.notBefore) },
|
||||
{ accessorKey: 'notAfter', header: 'Not After', cell: ({ row }) => fmt(row.original.notAfter) },
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
]
|
||||
|
||||
async function loadCerts() {
|
||||
if (!guid.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const { data } = await api.get<DeviceCertListDto>(`/device/${encodeURIComponent(guid.value)}/certs`)
|
||||
certs.value = Array.isArray(data?.certs) ? data.certs : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
error.value = e?.response?.data?.message ?? e?.message ?? 'Failed to load certificates.'
|
||||
certs.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// open → fetch
|
||||
watch(() => props.modelValue, (open) => {
|
||||
if (open) loadCerts()
|
||||
})
|
||||
|
||||
// guid changes while open → refetch
|
||||
watch(guid, (g, prev) => {
|
||||
if (props.modelValue && g && g !== prev) loadCerts()
|
||||
})
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v:boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[800px]">
|
||||
<DialogContent class="sm:min-w-[1000px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>List of certificates</DialogTitle>
|
||||
<DialogDescription>
|
||||
{{ props.device?.guid }}
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<DialogTitle>Device certificates</DialogTitle>
|
||||
<DialogDescription class="mt-1 break-all">
|
||||
GUID: {{ guid || '—' }}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" :disabled="loading || !guid" @click="loadCerts">
|
||||
{{ loading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="error" class="text-sm text-red-600 mb-3">{{ error }}</div>
|
||||
|
||||
<div v-if="loading" class="text-sm text-muted-foreground py-6 text-center">
|
||||
Loading certificates…
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<DataTableNoCheckboxScroll
|
||||
:columns="columns"
|
||||
:data="certs"
|
||||
minTableWidth="min-w-[900px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="onSave">Close</Button>
|
||||
<Button @click="close">Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,41 +1,226 @@
|
||||
<script setup lang="ts">
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import DeviceDashboard from './DeviceDashboard.vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import DeviceRecordings from './DeviceRecordings.vue';
|
||||
import { type PropType } from 'vue';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import DeviceDashboard from './DeviceDashboard.vue'
|
||||
import DeviceRecordings from './DeviceRecordings.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ref, onBeforeUnmount, type PropType } from 'vue'
|
||||
import type { Task } from '@/lib/interfaces'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// NOTE: hls.js default import (see type stub note above)
|
||||
import Hls from 'hls.js'
|
||||
|
||||
type PublishTokenResp = { hlsUrl: string } | { HLS: string } // accept either key casing
|
||||
|
||||
const props = defineProps({
|
||||
guid: { type: String as PropType<string>, required: true },
|
||||
})
|
||||
|
||||
/** UI state */
|
||||
const sending = ref(false)
|
||||
const streamError = ref<string | null>(null)
|
||||
const hlsUrl = ref<string | null>(null)
|
||||
const playing = ref(false)
|
||||
|
||||
/** Player bits */
|
||||
const audioEl = ref<HTMLAudioElement | null>(null)
|
||||
const hls = ref<any | null>(null)
|
||||
|
||||
/** Resolve server token → URL */
|
||||
async function fetchHlsUrl(): Promise<string> {
|
||||
// Adjust payload to what your server expects; common patterns:
|
||||
// - empty body
|
||||
// - { guid: props.guid }
|
||||
// - { path: `/hls/live/${props.guid}/index.m3u8` }
|
||||
const body = { guid: props.guid }
|
||||
|
||||
const { data } = await api.post<PublishTokenResp>('/mediamtx/token/read', body)
|
||||
// server DTO example: { HLS: "https://.../index.m3u8?token=..." }
|
||||
// normalize both HLS / hlsUrl spellings
|
||||
const url = (data as any).HLS ?? (data as any).hlsUrl
|
||||
if (!url || typeof url !== 'string') throw new Error('No HLS url in token response')
|
||||
return url
|
||||
}
|
||||
|
||||
/** Attach HLS to the <audio> element and start playing */
|
||||
async function attachAndPlay(url: string) {
|
||||
streamError.value = null
|
||||
hlsUrl.value = url
|
||||
|
||||
// Ensure previous instance is gone
|
||||
teardownHls()
|
||||
|
||||
const el = audioEl.value
|
||||
if (!el) {
|
||||
streamError.value = 'Audio element is not available.'
|
||||
return
|
||||
}
|
||||
|
||||
// Some UX niceties
|
||||
el.controls = true
|
||||
el.autoplay = true
|
||||
|
||||
// If hls.js is supported (all modern non-Safari browsers)
|
||||
if (Hls && typeof (Hls as any).isSupported === 'function' && Hls.isSupported()) {
|
||||
const instance = new (Hls as any)({
|
||||
// a few sensible defaults; tweak if you want retries:
|
||||
enableWorker: true,
|
||||
lowLatencyMode: true,
|
||||
backBufferLength: 60,
|
||||
})
|
||||
hls.value = instance
|
||||
|
||||
instance.on(Hls.Events.ERROR, (_evt: any, data: any) => {
|
||||
// Only surface fatal errors to the UI
|
||||
if (data?.fatal) {
|
||||
streamError.value = `HLS fatal error: ${data?.details || 'unknown'}`
|
||||
teardownHls()
|
||||
}
|
||||
})
|
||||
|
||||
instance.loadSource(url)
|
||||
instance.attachMedia(el)
|
||||
instance.on(Hls.Events.MANIFEST_PARSED, async () => {
|
||||
try {
|
||||
await el.play()
|
||||
playing.value = true
|
||||
} catch (err: any) {
|
||||
streamError.value = err?.message ?? 'Autoplay was blocked'
|
||||
playing.value = false
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// Safari (and some iOS WebKit) supports HLS natively
|
||||
if (el.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
el.src = url
|
||||
try {
|
||||
await el.play()
|
||||
playing.value = true
|
||||
} catch (err: any) {
|
||||
streamError.value = err?.message ?? 'Autoplay was blocked'
|
||||
playing.value = false
|
||||
}
|
||||
} else {
|
||||
streamError.value = 'HLS is not supported in this browser.'
|
||||
playing.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Start streaming flow:
|
||||
* 1) tell the device to start_stream
|
||||
* 2) fetch a fresh HLS token URL
|
||||
* 3) attach & play
|
||||
*/
|
||||
async function startStreaming() {
|
||||
streamError.value = null
|
||||
sending.value = true
|
||||
try {
|
||||
const dto: Task = { type: 'start_stream', payload: '' }
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
|
||||
const url = await fetchHlsUrl()
|
||||
await attachAndPlay(url)
|
||||
} catch (e: any) {
|
||||
console.error('Start streaming error', e)
|
||||
streamError.value = e?.response?.data?.message || e?.message || 'Failed to start streaming'
|
||||
playing.value = false
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop streaming flow:
|
||||
* 1) tell the device to stop_stream
|
||||
* 2) teardown player
|
||||
*/
|
||||
async function stopStreaming() {
|
||||
streamError.value = null
|
||||
sending.value = true
|
||||
try {
|
||||
const dto: Task = { type: 'stop_stream', payload: '' }
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} catch (e: any) {
|
||||
console.error('Stop streaming error', e)
|
||||
// non-fatal for UI; still tear down locally
|
||||
} finally {
|
||||
sending.value = false
|
||||
teardownHls()
|
||||
}
|
||||
}
|
||||
|
||||
/** Cleanup helper */
|
||||
function teardownHls() {
|
||||
try {
|
||||
if (hls.value) {
|
||||
try { hls.value.stopLoad?.() } catch {}
|
||||
try { hls.value.detachMedia?.() } catch {}
|
||||
try { hls.value.destroy?.() } catch {}
|
||||
}
|
||||
} catch {}
|
||||
hls.value = null
|
||||
|
||||
if (audioEl.value) {
|
||||
audioEl.value.pause?.()
|
||||
audioEl.value.removeAttribute('src')
|
||||
try { audioEl.value.load?.() } catch {}
|
||||
}
|
||||
playing.value = false
|
||||
hlsUrl.value = null
|
||||
}
|
||||
|
||||
// Make sure we clean up when leaving the page
|
||||
onBeforeUnmount(teardownHls)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Tabs default-value="records">
|
||||
<TabsList class="space-x-8">
|
||||
<TabsTrigger value="dashboard">
|
||||
Dashboard
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="records">
|
||||
Records
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="livestream">
|
||||
Livestream
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="dashboard">Dashboard</TabsTrigger>
|
||||
<TabsTrigger value="records">Records</TabsTrigger>
|
||||
<TabsTrigger value="livestream">Livestream</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="dashboard">
|
||||
<DeviceDashboard/>
|
||||
<DeviceDashboard :guid="guid" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="records">
|
||||
<DeviceRecordings :guid="guid" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="livestream">
|
||||
<Button>
|
||||
Start streaming
|
||||
<div class="flex flex-col gap-4 pt-2">
|
||||
<div class="flex gap-3">
|
||||
<Button :disabled="sending" @click="startStreaming">
|
||||
{{ sending ? 'Starting…' : 'Start streaming' }}
|
||||
</Button>
|
||||
<Button>
|
||||
Stop streaming
|
||||
<Button :disabled="sending" @click="stopStreaming">
|
||||
{{ sending ? 'Stopping…' : 'Stop streaming' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="streamError" class="text-sm text-red-600">
|
||||
{{ streamError }}
|
||||
</div>
|
||||
|
||||
<!-- The player -->
|
||||
<div class="mt-2">
|
||||
<!-- Show URL for debugging/dev, hide in production if you like -->
|
||||
<p v-if="hlsUrl" class="text-xs text-muted-foreground break-all">
|
||||
HLS: {{ hlsUrl }}
|
||||
</p>
|
||||
<audio
|
||||
ref="audioEl"
|
||||
class="w-full mt-2"
|
||||
preload="none"
|
||||
controls
|
||||
/>
|
||||
<p v-if="!hlsUrl && !playing" class="text-sm text-muted-foreground mt-2">
|
||||
Press “Start streaming” to begin live audio.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
@@ -1,15 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
Card, CardContent, CardFooter, CardHeader, CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
@@ -17,74 +12,278 @@ import {
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/components/ui/number-field'
|
||||
import AssignDevice from "./AssignDevice.vue";
|
||||
import { ref } from "vue";
|
||||
import Separator from "@/components/ui/separator/Separator.vue";
|
||||
import DataRangePicker from "./DataRangePicker.vue";
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
const usrIDs = selectedUserIds.value
|
||||
|
||||
import { h, ref, watch, computed, type PropType } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// Table bits for tasks
|
||||
import type { Task, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
|
||||
const props = defineProps({
|
||||
guid: { type: String as PropType<string>, required: true },
|
||||
})
|
||||
|
||||
/** -------------------- Config (left card) -------------------- **/
|
||||
type DeviceConfigDto = {
|
||||
m_guid: string
|
||||
m_recordingDuration: number
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const cfgLoading = ref(false)
|
||||
const cfgError = ref<string | null>(null)
|
||||
const savingCfg = ref(false)
|
||||
|
||||
const baseUrl = ref<string>('')
|
||||
const duration = ref<number>(240)
|
||||
const polling = ref<number>(60)
|
||||
const jitter = ref<number>(10)
|
||||
|
||||
async function loadConfig() {
|
||||
if (!props.guid) return
|
||||
cfgLoading.value = true
|
||||
cfgError.value = null
|
||||
try {
|
||||
const { data } = await api.get<DeviceConfigDto>(`/device/${encodeURIComponent(props.guid)}/config`)
|
||||
// map DTO → UI state
|
||||
baseUrl.value = data.m_baseUrl ?? ''
|
||||
duration.value = Number.isFinite(data.m_recordingDuration) ? data.m_recordingDuration : 240
|
||||
polling.value = Number.isFinite(data.m_polling) ? data.m_polling : 60
|
||||
jitter.value = Number.isFinite(data.m_jitter) ? data.m_jitter : 10
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
cfgError.value = e?.message ?? 'Failed to load config'
|
||||
} finally {
|
||||
cfgLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUpdateConfigTask() {
|
||||
if (!props.guid) return
|
||||
savingCfg.value = true
|
||||
cfgError.value = null
|
||||
|
||||
// Build config DTO exactly as backend expects
|
||||
const cfgBody = {
|
||||
m_recordingDuration: Number(duration.value),
|
||||
m_baseUrl: String(baseUrl.value || ''),
|
||||
m_polling: Number(polling.value), // <-- FIXED (was duration)
|
||||
m_jitter: Number(jitter.value),
|
||||
}
|
||||
|
||||
try {
|
||||
// 1) Update DB config first (send as object; Axios sets JSON header)
|
||||
await api.put(`/device/${encodeURIComponent(props.guid)}/config`, cfgBody)
|
||||
|
||||
// 2) Push live config to device via task (matches C++ handler: duration/sleep/jitter/endpoint)
|
||||
const taskPayload = {
|
||||
duration: Number(duration.value),
|
||||
sleep: Number(polling.value),
|
||||
jitter: Number(jitter.value),
|
||||
endpoint: String(baseUrl.value || ''),
|
||||
}
|
||||
|
||||
const dto: Task = {
|
||||
type: 'update_config',
|
||||
payload: JSON.stringify(taskPayload),
|
||||
}
|
||||
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
|
||||
// 3) Re-load from server to reflect DB state
|
||||
await loadConfig()
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
cfgError.value = e?.response?.data?.message ?? 'Failed to update config'
|
||||
} finally {
|
||||
savingCfg.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Optional quick actions */
|
||||
const sending = ref(false)
|
||||
async function startRecording() {
|
||||
if (!props.guid) return
|
||||
const dto: Task = { type: 'start_recording', payload: '' }
|
||||
try {
|
||||
sending.value = true
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
async function stopRecording() {
|
||||
if (!props.guid) return
|
||||
const dto: Task = { type: 'stop_recording', payload: '' }
|
||||
try {
|
||||
sending.value = true
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** -------------------- Tasks (right card) -------------------- **/
|
||||
const tasks = ref<TaskDto[]>([])
|
||||
const tasksLoading = ref(false)
|
||||
const tasksError = ref<string | null>(null)
|
||||
|
||||
async function fetchTasks() {
|
||||
if (!props.guid) return
|
||||
tasksLoading.value = true
|
||||
tasksError.value = null
|
||||
try {
|
||||
const { data } = await api.get<TaskListResp>(`/device/${encodeURIComponent(props.guid)}/tasks`)
|
||||
tasks.value = Array.isArray(data?.tasks) ? data.tasks : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
tasksError.value = e?.message ?? 'Failed to load tasks'
|
||||
tasks.value = []
|
||||
} finally {
|
||||
tasksLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const task_columns: ColumnDef<TaskDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
{ accessorKey: 'type', header: 'Task' },
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status
|
||||
const cls =
|
||||
s === 'finished' ? 'px-2 py-0.5 rounded text-xs text-green-700 bg-green-100'
|
||||
: s === 'running' ? 'px-2 py-0.5 rounded text-xs text-blue-700 bg-blue-100'
|
||||
: s === 'error' ? 'px-2 py-0.5 rounded text-xs text-red-700 bg-red-100'
|
||||
: 'px-2 py-0.5 rounded text-xs text-amber-700 bg-amber-100'
|
||||
return h('span', { class: cls }, s)
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
{ accessorKey: 'startedAt', header: 'Started', cell: ({ row }) => fmt(row.original.startedAt) },
|
||||
{ accessorKey: 'finishedAt', header: 'Finished', cell: ({ row }) => fmt(row.original.finishedAt) },
|
||||
]
|
||||
|
||||
/** -------------------- lifecycle -------------------- **/
|
||||
watch(() => props.guid, (g) => {
|
||||
if (g) {
|
||||
loadConfig()
|
||||
fetchTasks()
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card class="flex w-full max-w-4xl mx-auto">
|
||||
<CardHeader class="pb-4">
|
||||
<CardTitle>
|
||||
Dashboard
|
||||
</CardTitle>
|
||||
<!-- Two columns, full available height -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-6rem)]">
|
||||
<!-- LEFT: Config card -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>Device {{ props.guid }}</CardTitle>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" :disabled="cfgLoading" @click="loadConfig">
|
||||
{{ cfgLoading ? 'Loading…' : 'Refresh config' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent class="flex-1 grid gap-4 py-4">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid space-y-2 grid-cols-4 items-center">
|
||||
<Label for="users">Allowed users</Label>
|
||||
<AssignDevice v-model="usrIDs" class="col-span-3 w-full"></AssignDevice>
|
||||
</div>
|
||||
|
||||
<CardContent class="flex-1 grid gap-5">
|
||||
<div class="flex gap-2">
|
||||
<Button :disabled="sending" @click="startRecording">
|
||||
{{ sending ? 'Starting…' : 'Start recording' }}
|
||||
</Button>
|
||||
<Button :disabled="sending" @click="stopRecording">
|
||||
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex space-x-4 pt-2 gap-4">
|
||||
<Button>Start recording</Button>
|
||||
<Button>Stop recording</Button>
|
||||
</div>
|
||||
<div class="space-y-2 gap-4">
|
||||
<NumberField id="duration" :default-value="120" :min="30">
|
||||
<Label for="duration"> Record duration in seconds</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
<div v-if="cfgError" class="text-sm text-red-600">{{ cfgError }}</div>
|
||||
|
||||
<!-- Base URL -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="baseurl" class="col-span-3 w-full" placeholder="https://host" v-model="baseUrl"
|
||||
:disabled="cfgLoading || savingCfg" />
|
||||
</div>
|
||||
|
||||
<Separator class="my-6">Communication settings</Separator>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<!-- Row 1: duration (full width) -->
|
||||
<div class="space-y-2">
|
||||
<NumberField id="polling" :default-value="60" :min="30">
|
||||
<Label for="polling"> Timeout interwal in seconds </Label>
|
||||
<NumberField id="duration" v-model="duration" :min="30" :step="1">
|
||||
<Label for="duration">Record duration (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
|
||||
<!-- Row 2: polling + jitter (two columns) -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
|
||||
<NumberField id="jitter" :default-value="10" :min="5">
|
||||
<Label for="jitter"> Jitter in seconds </Label>
|
||||
<NumberField id="polling" v-model="polling" :min="30" :step="1">
|
||||
<Label for="polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<NumberField id="jitter" v-model="jitter" :min="5" :step="1">
|
||||
<Label for="jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
</div>
|
||||
<Separator></Separator>
|
||||
<div class="space-y-2 gap-4">
|
||||
<Label for="sleepdate">Date/time to sleep</Label>
|
||||
<DataRangePicker id="sleepdate"></DataRangePicker>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button :disabled="savingCfg || cfgLoading" @click="saveUpdateConfigTask">
|
||||
{{ savingCfg ? 'Saving…' : 'Update config (task)' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
<!-- RIGHT: Tasks card -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader class="pb-0">
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>Tasks</CardTitle>
|
||||
<Button variant="outline" :disabled="tasksLoading || !props.guid" @click="fetchTasks">
|
||||
{{ tasksLoading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1 pt-4">
|
||||
<div v-if="tasksError" class="text-sm text-red-600 mb-3">{{ tasksError }}</div>
|
||||
|
||||
<div v-if="tasksLoading" class="text-sm text-muted-foreground py-8 text-center">
|
||||
Loading tasks…
|
||||
</div>
|
||||
<div v-else class="h-full">
|
||||
<DataTableNoCheckboxScroll :columns="task_columns" :data="tasks" minTableWidth="min-w-[800px]" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,47 +1,129 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { Device } from '@/lib/interfaces';
|
||||
import type { PropType } from 'vue';
|
||||
import type { Device, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||
import type { PropType } from 'vue'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import DataTableNoCheckbox from './DataTableNoCheckbox.vue'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
import { ref, watch, h } from 'vue' // <-- import h
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
device: { type: Object as PropType<Device>, required: false },
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm'): void
|
||||
}>()
|
||||
|
||||
function onSave() {
|
||||
const tasks = ref<TaskDto[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
async function fetchTasks() {
|
||||
if (!props.device?.guid) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const { data } = await api.get<TaskListResp>(`/device/${encodeURIComponent(props.device.guid)}/tasks`)
|
||||
// server returns { limit, offset, total, tasks: [...] }
|
||||
tasks.value = Array.isArray(data?.tasks) ? data.tasks : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
error.value = e?.message ?? 'Failed to load tasks'
|
||||
tasks.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (open) => { if (open) fetchTasks() })
|
||||
watch(() => props.device?.guid, (n, o) => {
|
||||
if (props.modelValue && n && n !== o) fetchTasks()
|
||||
})
|
||||
|
||||
function onClose() {
|
||||
emit('confirm')
|
||||
// close the dialog
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const task_columns: ColumnDef<TaskDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
// { accessorKey: 'deviceGuid', header: 'GUID' },
|
||||
{ accessorKey: 'type', header: 'Task' },
|
||||
{
|
||||
accessorKey: 'payload',
|
||||
header: 'Command',
|
||||
cell: ({ row }) => {
|
||||
const p = row.original.payload ?? ''
|
||||
return p.length > 80 ? `${p.slice(0, 80)}…` : p
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
// Return a VNode, not an HTML string
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status
|
||||
const cls =
|
||||
s === 'finished' ? 'px-2 py-0.5 rounded text-xs text-green-700 bg-green-100'
|
||||
: s === 'running' ? 'px-2 py-0.5 rounded text-xs text-blue-700 bg-blue-100'
|
||||
: s === 'error' ? 'px-2 py-0.5 rounded text-xs text-red-700 bg-red-100'
|
||||
: 'px-2 py-0.5 rounded text-xs text-amber-700 bg-amber-100'
|
||||
return h('span', { class: cls }, s)
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'error', header: 'Error', cell: ({ row }) => row.original.error ?? '' },
|
||||
{
|
||||
accessorKey: 'result',
|
||||
header: 'Result',
|
||||
cell: ({ row }) => {
|
||||
const r = row.original.result ?? ''
|
||||
return r.length > 80 ? `${r.slice(0, 80)}…` : r
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
{ accessorKey: 'startedAt', header: 'Started', cell: ({ row }) => fmt(row.original.startedAt) },
|
||||
{ accessorKey: 'finishedAt', header: 'Finished', cell: ({ row }) => fmt(row.original.finishedAt) },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[800px]">
|
||||
<DialogHeader>
|
||||
<DialogContent class="sm:min-w-[1000px]">
|
||||
<DialogHeader class="flex flex-row items-center justify-between gap-4">
|
||||
<div>
|
||||
<DialogTitle>Tasks</DialogTitle>
|
||||
<DialogDescription>
|
||||
{{ props.device?.guid }}
|
||||
</DialogDescription>
|
||||
<DialogDescription>{{ props.device?.guid }}</DialogDescription>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" :disabled="loading || !props.device?.guid" @click="fetchTasks">
|
||||
{{ loading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="error" class="text-sm text-red-600 mb-3">{{ error }}</div>
|
||||
|
||||
<div v-if="loading" class="text-sm text-muted-foreground py-8 text-center">
|
||||
Loading tasks…
|
||||
</div>
|
||||
<div v-else>
|
||||
<DataTableNoCheckboxScroll :columns="task_columns" :data="tasks" minTableWidth="min-w-[800px]"/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="onSave">Close</Button>
|
||||
<Button @click="onClose">Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -9,3 +9,39 @@ export interface Users {
|
||||
username: string,
|
||||
role: string
|
||||
}
|
||||
|
||||
export type DeviceTaskType =
|
||||
| 'start_stream'
|
||||
| 'stop_stream'
|
||||
| 'start_recording'
|
||||
| 'stop_recording'
|
||||
| 'update_config'
|
||||
| 'set_deep_sleep'
|
||||
|
||||
export interface Task {
|
||||
type: DeviceTaskType
|
||||
/** Raw JSON string (e.g. '{"sleepTimeout":5}') */
|
||||
payload: string
|
||||
}
|
||||
|
||||
export type TaskStatus = 'pending' | 'running' | 'finished' | 'error'
|
||||
|
||||
export interface TaskDto {
|
||||
id: number
|
||||
deviceGuid: string
|
||||
type: DeviceTaskType
|
||||
payload: string // raw JSON string
|
||||
status: TaskStatus
|
||||
error?: string // from `ErrorMsg` -> `error`
|
||||
result?: string
|
||||
createdAt: string // ISO string from API
|
||||
startedAt?: string | null // ISO string or null
|
||||
finishedAt?: string | null
|
||||
}
|
||||
|
||||
export interface TaskListResp {
|
||||
limit: number
|
||||
offset: number
|
||||
total: number
|
||||
tasks: TaskDto[]
|
||||
}
|
||||
@@ -5,47 +5,61 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
||||
import Navbar from '@/customcompometns/Navbar.vue'
|
||||
import { useColorMode } from '@vueuse/core'
|
||||
import Navbar from '@/customcompometns/Navbar.vue';
|
||||
import type { PropType } from 'vue';
|
||||
import { defineProps, defineEmits, reactive, watch, ref, computed } from 'vue';
|
||||
import { defineProps, reactive, watch, ref, computed, type PropType } from 'vue'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// shadcn-vue number field parts
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/components/ui/number-field'
|
||||
|
||||
const mode = useColorMode()
|
||||
const router = useRouter()
|
||||
|
||||
type CreateDevicePayload = {
|
||||
guid: string
|
||||
name: string
|
||||
userIds: number[]
|
||||
}
|
||||
|
||||
type CreateUserPayload = {
|
||||
username: string
|
||||
password: string
|
||||
role: string // 'admin' | 'user'
|
||||
}
|
||||
|
||||
type CreateTrackerPayload = {
|
||||
guid: string
|
||||
name: string
|
||||
userIds: number[]
|
||||
type CreateDeviceConfigDto = {
|
||||
m_recordingDuration: number
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
type CreateTrackerConfigDto = {
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
})
|
||||
|
||||
// local form state
|
||||
// ------------------------ Local form state ------------------------
|
||||
const device_form = reactive({
|
||||
guid: uuidv4(), // default fresh UUID
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
// config fields
|
||||
baseUrl: '',
|
||||
duration: 240,
|
||||
polling: 60,
|
||||
jitter: 10,
|
||||
})
|
||||
|
||||
const user_form = reactive({
|
||||
@@ -57,31 +71,50 @@ const user_form = reactive({
|
||||
const tracker_form = reactive({
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
// config fields
|
||||
baseUrl: '',
|
||||
polling: 60,
|
||||
jitter: 10,
|
||||
})
|
||||
|
||||
// userIds from AssignDevice (expects v-model of string[] ids)
|
||||
// Selected user IDs for both forms (split if you want separate sets)
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(val) => {
|
||||
if (val) {
|
||||
// reset device
|
||||
device_form.guid = uuidv4()
|
||||
device_form.name = ''
|
||||
device_form.baseUrl = ''
|
||||
device_form.duration = 240
|
||||
device_form.polling = 60
|
||||
device_form.jitter = 10
|
||||
|
||||
// reset tracker
|
||||
tracker_form.guid = uuidv4()
|
||||
tracker_form.name = ''
|
||||
tracker_form.baseUrl = ''
|
||||
tracker_form.polling = 60
|
||||
tracker_form.jitter = 10
|
||||
|
||||
// reset users + user form
|
||||
selectedUserIds.value = []
|
||||
user_form.username = ''
|
||||
user_form.password = ''
|
||||
user_form.isAdmin = false
|
||||
|
||||
userError.value = null
|
||||
userSubmitting.value = false
|
||||
userSuccess.value = null
|
||||
// tracker_form.guid = uuidv4()
|
||||
// tracker_form.name = ''
|
||||
errorMsg.value = null
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// simple UUIDv4 check (best-effort)
|
||||
// ------------------------ Validation / helpers ------------------------
|
||||
const uuidV4Re = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
const submitting = ref(false)
|
||||
const errorMsg = ref<string | null>(null)
|
||||
@@ -91,19 +124,58 @@ const userError = ref<string | null>(null)
|
||||
const userSuccess = ref<string | null>(null)
|
||||
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
return (
|
||||
const canSubmitDevice = computed(() =>
|
||||
!!device_form.guid &&
|
||||
uuidV4Re.test(device_form.guid) &&
|
||||
!!device_form.name.trim() &&
|
||||
!!device_form.baseUrl.trim() &&
|
||||
Number.isFinite(device_form.duration) &&
|
||||
Number.isFinite(device_form.polling) &&
|
||||
Number.isFinite(device_form.jitter) &&
|
||||
!submitting.value
|
||||
)
|
||||
})
|
||||
|
||||
const canSubmitTracker = computed(() =>
|
||||
!!tracker_form.guid &&
|
||||
uuidV4Re.test(tracker_form.guid) &&
|
||||
!!tracker_form.name.trim() &&
|
||||
!!tracker_form.baseUrl.trim() &&
|
||||
Number.isFinite(tracker_form.polling) &&
|
||||
Number.isFinite(tracker_form.jitter) &&
|
||||
!submitting.value
|
||||
)
|
||||
|
||||
const canSubmitUser = computed(() =>
|
||||
user_form.username.trim().length >= 3 &&
|
||||
user_form.password.length >= 8 &&
|
||||
!userSubmitting.value
|
||||
)
|
||||
|
||||
const canDownloadDeviceConfig = computed(() =>
|
||||
!!device_form.guid && uuidV4Re.test(device_form.guid) && !!device_form.baseUrl.trim()
|
||||
)
|
||||
const canDownloadTrackerConfig = computed(() =>
|
||||
!!tracker_form.guid && uuidV4Re.test(tracker_form.guid) && !!tracker_form.baseUrl.trim()
|
||||
)
|
||||
|
||||
// Save a config.json file to the browser
|
||||
function downloadConfig(filename: string, data: unknown) {
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
// ------------------------ Submit handlers ------------------------
|
||||
async function submitDevice() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmit.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
||||
if (!canSubmitDevice.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||
return
|
||||
}
|
||||
|
||||
@@ -117,25 +189,90 @@ async function submitDevice() {
|
||||
userIds,
|
||||
}
|
||||
|
||||
const config: CreateDeviceConfigDto = {
|
||||
m_recordingDuration: Number(device_form.duration),
|
||||
m_baseUrl: device_form.baseUrl.trim(),
|
||||
m_polling: Number(device_form.polling),
|
||||
m_jitter: Number(device_form.jitter),
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1) create device
|
||||
await api.post('/devices/create', payload)
|
||||
|
||||
// 2) send config to device
|
||||
await api.post(`/device/${encodeURIComponent(device_form.guid)}/config`, config)
|
||||
|
||||
// 3) download config.json example
|
||||
// downloadConfig(
|
||||
// 'config.json',
|
||||
// {
|
||||
// m_guid: device_form.guid,
|
||||
// m_recordingDuration: config.m_recordingDuration,
|
||||
// m_baseUrl: config.m_baseUrl,
|
||||
// m_polling: config.m_polling,
|
||||
// m_jitter: config.m_jitter,
|
||||
// }
|
||||
// )
|
||||
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
// keep client error generic
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device or send config.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const canSubmitUser = computed(() => {
|
||||
return (
|
||||
user_form.username.trim().length >= 3 &&
|
||||
user_form.password.length >= 8 && // basic client-side check; real policy enforced server-side
|
||||
!userSubmitting.value
|
||||
)
|
||||
})
|
||||
async function submitTracker() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmitTracker.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||
return
|
||||
}
|
||||
|
||||
const userIds: number[] = selectedUserIds.value
|
||||
.map((s) => Number(s))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
||||
|
||||
const payload: CreateDevicePayload = {
|
||||
guid: tracker_form.guid,
|
||||
name: tracker_form.name.trim(),
|
||||
userIds,
|
||||
}
|
||||
|
||||
const config: CreateTrackerConfigDto = {
|
||||
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||
m_polling: Number(tracker_form.polling),
|
||||
m_jitter: Number(tracker_form.jitter),
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1) create tracker (your API already uses /trackers/create)
|
||||
await api.post('/trackers/create', payload)
|
||||
|
||||
// 2) send config; assuming symmetrical tracker endpoint:
|
||||
// await api.post(`/trackers/${encodeURIComponent(tracker_form.guid)}/config`, config)
|
||||
|
||||
// 3) download config.json
|
||||
// downloadConfig(
|
||||
// 'config.json',
|
||||
// {
|
||||
// m_guid: tracker_form.guid,
|
||||
// m_baseUrl: config.m_baseUrl,
|
||||
// m_polling: config.m_polling,
|
||||
// m_jitter: config.m_jitter,
|
||||
// }
|
||||
// )
|
||||
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create tracker or send config.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitUser() {
|
||||
userError.value = null
|
||||
@@ -148,7 +285,7 @@ async function submitUser() {
|
||||
|
||||
const payload: CreateUserPayload = {
|
||||
username: user_form.username.trim(),
|
||||
password: user_form.password, // do not trim passwords
|
||||
password: user_form.password,
|
||||
role: userRole.value,
|
||||
}
|
||||
|
||||
@@ -164,33 +301,25 @@ async function submitUser() {
|
||||
}
|
||||
}
|
||||
|
||||
async function submitTracker() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmit.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
||||
return
|
||||
function downloadDeviceConfig() {
|
||||
const payload = {
|
||||
m_guid: device_form.guid,
|
||||
m_recordingDuration: Number(device_form.duration),
|
||||
m_baseUrl: device_form.baseUrl.trim(),
|
||||
m_polling: Number(device_form.polling),
|
||||
m_jitter: Number(device_form.jitter),
|
||||
}
|
||||
downloadConfig(`config-${device_form.guid}.json`, payload)
|
||||
}
|
||||
|
||||
const userIds: number[] = selectedUserIds.value
|
||||
.map((s) => Number(s))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
||||
|
||||
const payload: CreateDevicePayload = {
|
||||
guid: device_form.guid,
|
||||
name: device_form.name.trim(),
|
||||
userIds,
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await api.post('/trackers/create', payload)
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
// keep client error generic
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
function downloadTrackerConfig() {
|
||||
const payload = {
|
||||
m_guid: tracker_form.guid,
|
||||
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||
m_polling: Number(tracker_form.polling),
|
||||
m_jitter: Number(tracker_form.jitter),
|
||||
}
|
||||
downloadConfig(`config-${tracker_form.guid}.json`, payload)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -198,40 +327,75 @@ async function submitTracker() {
|
||||
<Navbar>
|
||||
<div class="w-full py-8">
|
||||
<div class="mx-auto">
|
||||
<!-- Horizontal cards with gap -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
||||
|
||||
<!-- Create device -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create device</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<!-- add vertical spacing between rows -->
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
<Label for="d-guid" class="text-right">GUID</Label>
|
||||
<Input id="d-guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="d-name" class="text-right">Name</Label>
|
||||
<Input id="d-name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
</div>
|
||||
|
||||
<!-- Config -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
<Label for="d-baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="d-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||
v-model="device_form.baseUrl" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<!-- make the component span and fill -->
|
||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<NumberField id="d-duration" v-model="device_form.duration" :min="30" :step="1">
|
||||
<Label for="d-duration">Record duration (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
|
||||
<NumberField id="d-polling" v-model="device_form.polling" :min="30" :step="1">
|
||||
<Label for="d-polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
|
||||
<NumberField id="d-jitter" v-model="device_form.jitter" :min="5" :step="1">
|
||||
<Label for="d-jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ errorMsg }}
|
||||
</p>
|
||||
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="d-users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="d-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
|
||||
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmit" @click="submitDevice">
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button variant="outline" @click="downloadDeviceConfig"
|
||||
:disabled="!canDownloadDeviceConfig">
|
||||
Download config
|
||||
</Button>
|
||||
<Button :disabled="!canSubmitDevice" @click="submitDevice">
|
||||
{{ submitting ? 'Saving…' : 'Save' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
@@ -242,38 +406,30 @@ async function submitTracker() {
|
||||
<CardHeader>
|
||||
<CardTitle>Create user</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="username" class="text-right">Username</Label>
|
||||
<Input id="username" class="col-span-3 w-full" v-model="user_form.username" />
|
||||
<Label for="u-user" class="text-right">Username</Label>
|
||||
<Input id="u-user" class="col-span-3 w-full" v-model="user_form.username" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="password" class="text-right">Password</Label>
|
||||
<Input id="password" type="password" class="col-span-3 w-full"
|
||||
<Label for="u-pass" class="text-right">Password</Label>
|
||||
<Input id="u-pass" type="password" class="col-span-3 w-full"
|
||||
v-model="user_form.password" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="isAdmin" class="text-right">Make admin</Label>
|
||||
<Label for="u-admin" class="text-right">Make admin</Label>
|
||||
<div class="col-span-3">
|
||||
<Switch id="isAdmin" v-model:checked="user_form.isAdmin"
|
||||
<Switch id="u-admin" v-model:checked="user_form.isAdmin"
|
||||
v-model="user_form.isAdmin"
|
||||
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
||||
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="userError" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ userError }}
|
||||
</p>
|
||||
<p v-if="userSuccess" class="text-sm text-green-600" aria-live="polite">
|
||||
{{ userSuccess }}
|
||||
</p>
|
||||
<p v-if="userError" class="text-sm text-red-600">{{ userError }}</p>
|
||||
<p v-if="userSuccess" class="text-sm text-green-600">{{ userSuccess }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmitUser" @click="submitUser">
|
||||
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
||||
@@ -281,37 +437,66 @@ async function submitTracker() {
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
<!-- Create tracker -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create tracker</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<!-- add vertical spacing between rows -->
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
<Label for="t-guid" class="text-right">GUID</Label>
|
||||
<Input id="t-guid" class="col-span-3 w-full" v-model="tracker_form.guid" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-name" class="text-right">Name</Label>
|
||||
<Input id="t-name" class="col-span-3 w-full" v-model="tracker_form.name" />
|
||||
</div>
|
||||
|
||||
<!-- Config -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="t-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||
v-model="tracker_form.baseUrl" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="space-y-2">
|
||||
<NumberField id="t-polling" v-model="tracker_form.polling" :min="30">
|
||||
<Label for="t-polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<NumberField id="t-jitter" v-model="tracker_form.jitter" :min="5">
|
||||
<Label for="t-jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
<Label for="t-users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="t-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<!-- make the component span and fill -->
|
||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ errorMsg }}
|
||||
</p>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmit" @click="submitTracker">
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button variant="outline" @click="downloadTrackerConfig"
|
||||
:disabled="!canDownloadTrackerConfig">
|
||||
Download config
|
||||
</Button>
|
||||
<Button :disabled="!canSubmitTracker" @click="submitTracker">
|
||||
{{ submitting ? 'Saving…' : 'Save' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
|
||||
4
management-ui/src/types/hlsjs.d.ts
vendored
Normal file
4
management-ui/src/types/hlsjs.d.ts
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
declare module 'hls.js' {
|
||||
const Hls: any
|
||||
export default Hls
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
"@/*": ["./src/*","src/types/**/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,23 @@ map $http_upgrade $connection_upgrade {
|
||||
# Helpful for larger uploads via API (tweak as you wish)
|
||||
client_max_body_size 400m;
|
||||
|
||||
log_format mtls_debug '
|
||||
[$time_local] $remote_addr:$remote_port → $server_name:$server_port
|
||||
"$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
|
||||
TLS=$ssl_protocol/$ssl_cipher
|
||||
ClientVerify=$ssl_client_verify
|
||||
ClientSerial=$ssl_client_serial
|
||||
ClientSubject="$ssl_client_s_dn"
|
||||
ClientIssuer="$ssl_client_i_dn"
|
||||
RequestTime=$request_time
|
||||
ProxyUpstreamAddr=$upstream_addr
|
||||
ProxyStatus=$upstream_status
|
||||
';
|
||||
|
||||
# Default access & error logs for both 80 and 443 servers
|
||||
access_log /var/log/nginx/access.log mtls_debug;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
@@ -60,6 +77,9 @@ server {
|
||||
listen 443 ssl http2;
|
||||
server_name _;
|
||||
|
||||
access_log /var/log/nginx/access.log mtls_debug;
|
||||
error_log /var/log/nginx/error.log info;
|
||||
|
||||
ssl_certificate /etc/nginx/ssl/certs/fullchain.pem;
|
||||
ssl_certificate_key /etc/nginx/ssl/certs/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
@@ -98,43 +118,50 @@ server {
|
||||
}
|
||||
|
||||
# ---- mTLS-protected paths ----
|
||||
location ^~ /records {
|
||||
location ^~ /api/records/upload {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
location ^~ /tasks {
|
||||
location ^~ /api/tasks {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
location ^~ /renew {
|
||||
location ^~ /api/renew {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
# MediaMTX HLS
|
||||
location ^~ /hls/ {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
# if ($ssl_client_verify != SUCCESS) {
|
||||
# return 495;
|
||||
# }
|
||||
proxy_pass http://mediamtx:8888/;
|
||||
}
|
||||
|
||||
# MediaMTX WebRTC (WHIP/WHEP/test)
|
||||
location ^~ /webrtc/ {
|
||||
location ^~ /whip/ {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://mediamtx:8889/;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_pass http://mediamtx:8889;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_request_buffering off;
|
||||
client_max_body_size 35m;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
|
||||
# MQTT WS entry points (guarded by mTLS)
|
||||
@@ -158,4 +185,19 @@ server {
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
location ^~ /api/ {
|
||||
proxy_pass http://snoop-api:8080/; # trailing slash strips /api
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# (Optional) WS/SSE friendly defaults
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,5 +22,6 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&models.DEviceTask{},
|
||||
&models.DeviceCertificate{},
|
||||
&models.RevokedSerial{},
|
||||
&models.DeviceConfig{},
|
||||
)
|
||||
}
|
||||
|
||||
36
server/internal/dto/cert.go
Normal file
36
server/internal/dto/cert.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"smoop-api/internal/models"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DeviceCertDto struct {
|
||||
ID uint `json:"id"`
|
||||
DeviceGUID string `json:"deviceGuid"`
|
||||
SerialHex string `json:"serialHex"`
|
||||
IssuerCN string `json:"issuerCN"`
|
||||
SubjectDN string `json:"subjectDN"`
|
||||
NotBefore time.Time `json:"notBefore"`
|
||||
NotAfter time.Time `json:"notAfter"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// PemCert is sensitive/noisy; expose only if you really need it:
|
||||
// PemCert string `json:"pemCert,omitempty"`
|
||||
}
|
||||
|
||||
type DeviceCertListDto struct {
|
||||
Certs []DeviceCertDto `json:"certs"`
|
||||
}
|
||||
|
||||
func MapDeviceCert(c models.DeviceCertificate) DeviceCertDto {
|
||||
return DeviceCertDto{
|
||||
ID: c.ID,
|
||||
DeviceGUID: c.DeviceGUID,
|
||||
SerialHex: c.SerialHex,
|
||||
IssuerCN: c.IssuerCN,
|
||||
SubjectDN: c.SubjectDN,
|
||||
NotBefore: c.NotBefore,
|
||||
NotAfter: c.NotAfter,
|
||||
CreatedAt: c.CreatedAt,
|
||||
}
|
||||
}
|
||||
35
server/internal/dto/device_config.go
Normal file
35
server/internal/dto/device_config.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package dto
|
||||
|
||||
import "smoop-api/internal/models"
|
||||
|
||||
type DeviceConfigDto struct {
|
||||
MGuid string `json:"m_guid"`
|
||||
MRecordingDuration int `json:"m_recordingDuration"`
|
||||
MBaseURL string `json:"m_baseUrl"`
|
||||
MPolling int `json:"m_polling"`
|
||||
MJitter int `json:"m_jitter"`
|
||||
}
|
||||
|
||||
type CreateDeviceConfigDto struct {
|
||||
MRecordingDuration int `json:"m_recordingDuration" binding:"required"`
|
||||
MBaseURL string `json:"m_baseUrl" binding:"required"`
|
||||
MPolling int `json:"m_polling" binding:"required"`
|
||||
MJitter int `json:"m_jitter" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateDeviceConfigDto struct {
|
||||
MRecordingDuration *int `json:"m_recordingDuration,omitempty"`
|
||||
MBaseURL *string `json:"m_baseUrl,omitempty"`
|
||||
MPolling *int `json:"m_polling,omitempty"`
|
||||
MJitter *int `json:"m_jitter,omitempty"`
|
||||
}
|
||||
|
||||
func MapDeviceConfig(cfg models.DeviceConfig) DeviceConfigDto {
|
||||
return DeviceConfigDto{
|
||||
MGuid: cfg.MGuid,
|
||||
MRecordingDuration: cfg.MRecordingDuration,
|
||||
MBaseURL: cfg.MBaseURL,
|
||||
MPolling: cfg.MPolling,
|
||||
MJitter: cfg.MJitter,
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ type PublishTokenReq struct {
|
||||
}
|
||||
|
||||
type PublishTokenResp struct {
|
||||
WHIP string `json:"whipUrl"` // http://mediamtx:8889/whip/live/<guid>?token=...
|
||||
HLS string `json:"hlsUrl"` // https://<public>/hls/live/<guid>/index.m3u8?token=...
|
||||
}
|
||||
|
||||
type ReadTokenReq struct {
|
||||
|
||||
@@ -38,7 +38,7 @@ type CreateTaskDto struct {
|
||||
Type models.DeviceTaskType `json:"type" binding:"required,oneof=start_stream stop_stream start_recording stop_recording update_config set_deep_sleep"`
|
||||
// Pass raw JSON string as payload (e.g. {"sleepTimeout":5,"jitterMs":50,"recordingDurationSec":60})
|
||||
// Keep it string to let device/server evolve freely.
|
||||
Payload string `json:"payload" binding:"required"`
|
||||
Payload string `json:"payload"`
|
||||
}
|
||||
|
||||
// Device polls: single next task
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -108,7 +109,7 @@ func (h *CertsHandler) Enroll(c *gin.Context) {
|
||||
defer cancel()
|
||||
sign, err := h.pki.SignCSR(ctx, csr, "urn:device:"+guid, h.ttl)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "vault sign failed"})
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": fmt.Sprintf("vault sign failed: %s", err)})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -302,5 +303,147 @@ func (h *DevicesHandler) ListCertsByDevice(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"certs": list})
|
||||
out := make([]dto.DeviceCertDto, 0, len(list))
|
||||
for _, it := range list {
|
||||
out = append(out, dto.MapDeviceCert(it))
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.DeviceCertListDto{Certs: out})
|
||||
}
|
||||
|
||||
// GET /device/:guid/config (admin or assigned user — choose policy; here adminOnly for symmetry with certs)
|
||||
func (h *DevicesHandler) GetDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
// Ensure device exists
|
||||
var d models.Device
|
||||
if err := h.db.Where("guid = ?", guid).First(&d).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var cfg models.DeviceConfig
|
||||
if err := h.db.Where("device_guid = ?", guid).First(&cfg).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "config not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
// POST /device/:guid/config (create)
|
||||
func (h *DevicesHandler) CreateDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
var d models.Device
|
||||
if err := h.db.Where("guid = ?", guid).First(&d).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure not exists
|
||||
var exists int64
|
||||
_ = h.db.Model(&models.DeviceConfig{}).Where("device_guid = ?", guid).Count(&exists).Error
|
||||
if exists > 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "config already exists"})
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateDeviceConfigDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
cfg := models.DeviceConfig{
|
||||
DeviceGUID: guid,
|
||||
MGuid: guid,
|
||||
MRecordingDuration: req.MRecordingDuration,
|
||||
MBaseURL: req.MBaseURL,
|
||||
MPolling: req.MPolling,
|
||||
MJitter: req.MJitter,
|
||||
}
|
||||
if err := h.db.Create(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
// PUT /device/:guid/config (partial update)
|
||||
func (h *DevicesHandler) UpdateDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
var req dto.UpdateDeviceConfigDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var cfg models.DeviceConfig
|
||||
err := h.db.Where("device_guid = ?", guid).First(&cfg).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// Create-on-update behavior
|
||||
// m_baseUrl is required to create (NOT NULL constraint in model)
|
||||
if req.MBaseURL == nil || strings.TrimSpace(*req.MBaseURL) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "m_baseUrl is required to create config"})
|
||||
return
|
||||
}
|
||||
|
||||
// Defaults
|
||||
recDur := 240
|
||||
if req.MRecordingDuration != nil {
|
||||
recDur = *req.MRecordingDuration
|
||||
}
|
||||
poll := 30
|
||||
if req.MPolling != nil {
|
||||
poll = *req.MPolling
|
||||
}
|
||||
jitter := 10
|
||||
if req.MJitter != nil {
|
||||
jitter = *req.MJitter
|
||||
}
|
||||
|
||||
cfg = models.DeviceConfig{
|
||||
DeviceGUID: guid,
|
||||
MGuid: guid,
|
||||
MRecordingDuration: recDur,
|
||||
MBaseURL: strings.TrimSpace(*req.MBaseURL),
|
||||
MPolling: poll,
|
||||
MJitter: jitter,
|
||||
}
|
||||
if err := h.db.Create(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapDeviceConfig(cfg))
|
||||
return
|
||||
}
|
||||
// Other DB error
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Patch only provided fields
|
||||
if req.MRecordingDuration != nil {
|
||||
cfg.MRecordingDuration = *req.MRecordingDuration
|
||||
}
|
||||
if req.MBaseURL != nil {
|
||||
cfg.MBaseURL = strings.TrimSpace(*req.MBaseURL)
|
||||
}
|
||||
if req.MPolling != nil {
|
||||
cfg.MPolling = *req.MPolling
|
||||
}
|
||||
if req.MJitter != nil {
|
||||
cfg.MJitter = *req.MJitter
|
||||
}
|
||||
|
||||
if err := h.db.Save(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "save failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"smoop-api/internal/config"
|
||||
@@ -10,6 +12,7 @@ import (
|
||||
"smoop-api/internal/dto"
|
||||
"smoop-api/internal/models"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
@@ -29,6 +32,10 @@ func NewMediaMTXHandler(db *gorm.DB, jwt *crypto.JWTManager, c config.MediaMTXCo
|
||||
// POST /mediamtx/auth
|
||||
func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
||||
var req dto.MediaMTXAuthReq
|
||||
body, _ := c.GetRawData()
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(body))
|
||||
|
||||
c.Writer.WriteString(fmt.Sprintf("DEBUG BODY:\n%s\n", string(body)))
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad auth body"})
|
||||
return
|
||||
@@ -36,52 +43,19 @@ func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
||||
|
||||
// token can come from Authorization: Bearer or from query (?token=)
|
||||
tok := extractBearer(c.GetHeader("Authorization"))
|
||||
|
||||
if tok == "" && req.Query != "" {
|
||||
tok = tokenFromQuery(req.Query) // Parse "token=" from the raw query string
|
||||
}
|
||||
|
||||
if tok == "" {
|
||||
tok = tokenFromQuery(req.Query)
|
||||
tok = strings.TrimSpace(req.Token)
|
||||
}
|
||||
if tok == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
return
|
||||
}
|
||||
|
||||
// parse & validate media token
|
||||
// parsed, err := h.jwtMgr.Parse(tok)
|
||||
// if err != nil || !parsed.Valid {
|
||||
// c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
// return
|
||||
// }
|
||||
// var mc dto.MediaClaims
|
||||
// if err := jwt.MapClaims(parsed.Claims.(jwt.MapClaims)).Decode(&mc); err != nil {
|
||||
// c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid claims"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// // enforce act/path
|
||||
// if mc.Act != req.Action {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "action mismatch"})
|
||||
// return
|
||||
// }
|
||||
// if mc.Path != req.Path {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "path mismatch"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// // Optional: permission checks by role/device
|
||||
// // READ: admins can read anything; users only devices assigned
|
||||
// // PUBLISH: allow devices (sub=0 or special) or admins
|
||||
// switch req.Action {
|
||||
// case "read":
|
||||
// if !h.canRead(mc.Subject, req.Path) {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "no read permission"})
|
||||
// return
|
||||
// }
|
||||
// case "publish":
|
||||
// if !h.canPublish(mc.Subject, req.Path) {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "no publish permission"})
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
|
||||
// parse & validate media token
|
||||
mc, err := h.jwtMgr.ParseMedia(tok)
|
||||
if err != nil {
|
||||
@@ -126,7 +100,8 @@ func tokenFromQuery(raw string) string {
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
q, _ := url.ParseQuery(raw)
|
||||
s := strings.TrimPrefix(raw, "?")
|
||||
q, _ := url.ParseQuery(s)
|
||||
return q.Get("token")
|
||||
}
|
||||
|
||||
@@ -153,6 +128,9 @@ func (h *MediaMTXHandler) canRead(sub, path string) bool {
|
||||
}
|
||||
func (h *MediaMTXHandler) canPublish(sub, path string) bool {
|
||||
// For devices you may use sub=0 or map to a device row; here: allow admins only
|
||||
if sub == "0" {
|
||||
return true
|
||||
}
|
||||
var u models.User
|
||||
if err := h.db.Where("id = ?", sub).First(&u).Error; err == nil && u.Role == models.RoleAdmin {
|
||||
return true
|
||||
@@ -163,15 +141,46 @@ func (h *MediaMTXHandler) canPublish(sub, path string) bool {
|
||||
// --- 3.2 Mint publish token (device flow) -> returns WHIP URL
|
||||
// POST /mediamtx/token/publish {guid}
|
||||
func (h *MediaMTXHandler) MintPublish(c *gin.Context) {
|
||||
user, ok := GetUserContext(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
var req dto.PublishTokenReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
||||
return
|
||||
}
|
||||
|
||||
// Permission check (admin or assigned)
|
||||
if user.Role != models.RoleAdmin {
|
||||
var count int64
|
||||
_ = h.db.Table("user_devices").
|
||||
Where("user_id = ? AND device_guid = ?", user.ID, req.GUID).
|
||||
Count(&count).Error
|
||||
if count == 0 {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "not allowed for this device"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
path := "live/" + req.GUID
|
||||
tok, _ := h.jwtMgr.GenerateMediaToken(0, "publish", path, h.cfg.TokenTTL) // sub=0 (device)
|
||||
whip := fmt.Sprintf("%s/whip/%s?token=%s", strings.TrimRight(h.cfg.WebRTCBaseURL, "/"), path, url.QueryEscape(tok))
|
||||
c.JSON(http.StatusCreated, dto.PublishTokenResp{WHIP: whip})
|
||||
|
||||
// We mint a *read* token for the browser to consume HLS.
|
||||
tok, err := h.jwtMgr.GenerateMediaToken(user.ID, "read", path, h.cfg.TokenTTL)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "token error"})
|
||||
return
|
||||
}
|
||||
|
||||
pub := strings.TrimRight(h.cfg.PublicBaseURL, "/")
|
||||
hls := fmt.Sprintf("%s/hls/%s/index.m3u8?token=%s",
|
||||
pub,
|
||||
path,
|
||||
url.QueryEscape(tok),
|
||||
)
|
||||
|
||||
c.JSON(http.StatusCreated, dto.PublishTokenResp{HLS: hls})
|
||||
}
|
||||
|
||||
// --- 3.3 Mint read token (user flow) -> returns HLS + WHEP URLs
|
||||
@@ -254,3 +263,80 @@ func (h *MediaMTXHandler) KickWebRTC(c *gin.Context) {
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *MediaMTXHandler) StartStreamPayload(guid string) (string, error) {
|
||||
path := "live/" + guid
|
||||
ttl := time.Duration(h.cfg.TokenTTL) * time.Second
|
||||
|
||||
tok, err := h.jwtMgr.GenerateMediaToken(0, "publish", path, ttl) // sub=0 = device
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
whip := fmt.Sprintf("%s/whip/%s?token=%s",
|
||||
strings.TrimRight(h.cfg.PublicBaseURL, "/"),
|
||||
path,
|
||||
url.QueryEscape(tok),
|
||||
)
|
||||
|
||||
payload := map[string]any{
|
||||
"whipUrl": whip,
|
||||
"path": path,
|
||||
"tokenTTL_s": h.cfg.TokenTTL,
|
||||
}
|
||||
b, _ := json.Marshal(payload)
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
type webrtcSession struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type webrtcListRes struct {
|
||||
Items []webrtcSession `json:"items"`
|
||||
}
|
||||
|
||||
// KickWebRTCSessionsByPath lists and kicks webrtc sessions for a given path.
|
||||
func (h *MediaMTXHandler) KickWebRTCSessionsByPath(path string) error {
|
||||
listURL := strings.TrimRight(h.cfg.APIBase, "/") + "/v3/webrtcsessions/list"
|
||||
|
||||
resp, err := http.Get(listURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get list: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("mtx list failed: %s", resp.Status)
|
||||
}
|
||||
|
||||
var l webrtcListRes
|
||||
if err := json.NewDecoder(resp.Body).Decode(&l); err != nil {
|
||||
return fmt.Errorf("decode error: %w", err)
|
||||
}
|
||||
|
||||
for _, it := range l.Items {
|
||||
if it.Path == path && it.ID != "" {
|
||||
kickURL := strings.TrimRight(h.cfg.APIBase, "/") +
|
||||
"/v3/webrtcsessions/kick/" + url.PathEscape(it.ID)
|
||||
|
||||
kresp, err := http.Post(kickURL, "application/json", nil)
|
||||
if err != nil {
|
||||
// log and continue
|
||||
continue
|
||||
}
|
||||
kresp.Body.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func BodyLogger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method == "POST" && strings.Contains(c.Request.URL.Path, "/mediamtx/auth") {
|
||||
body, _ := c.GetRawData()
|
||||
fmt.Fprintf(gin.DefaultWriter, "[MTX-AUTH] %s\n", string(body))
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -15,9 +16,15 @@ import (
|
||||
|
||||
type TasksHandler struct {
|
||||
db *gorm.DB
|
||||
mtxH *MediaMTXHandler
|
||||
}
|
||||
|
||||
func NewTasksHandler(db *gorm.DB) *TasksHandler { return &TasksHandler{db: db} }
|
||||
func NewTasksHandler(db *gorm.DB, mtxH *MediaMTXHandler) *TasksHandler {
|
||||
return &TasksHandler{
|
||||
db: db,
|
||||
mtxH: mtxH,
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 1) Device heartbeat + fetch next task
|
||||
@@ -151,6 +158,22 @@ func (h *TasksHandler) CreateTask(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
switch req.Type {
|
||||
case models.TaskTypeStartStream:
|
||||
payload, err := h.mtxH.StartStreamPayload(guid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "failed to build whip url"})
|
||||
return
|
||||
}
|
||||
req.Payload = payload
|
||||
|
||||
case models.TaskTypeStopStream:
|
||||
// best-effort server-side stop (kick publishers/readers on that path)
|
||||
_ = h.mtxH.KickWebRTCSessionsByPath("live/" + guid)
|
||||
if strings.TrimSpace(req.Payload) == "" {
|
||||
req.Payload = `{"reason":"server_stop"}`
|
||||
}
|
||||
}
|
||||
|
||||
task := models.DEviceTask{
|
||||
DeviceGUID: guid,
|
||||
|
||||
@@ -13,6 +13,7 @@ type DeviceCertificate struct {
|
||||
NotAfter time.Time
|
||||
PemCert string `gorm:"type:text"` // PEM of leaf cert
|
||||
CreatedAt time.Time
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
|
||||
// “Instant kill” list checked by the mTLS guard before allowing access.
|
||||
|
||||
@@ -7,6 +7,10 @@ type Device struct {
|
||||
Name string `gorm:"size:255;not null"`
|
||||
Users []User `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
|
||||
Records []Record `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
Tasks []DEviceTask `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
Certs []DeviceCertificate `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
Config *DeviceConfig `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
}
|
||||
|
||||
19
server/internal/models/device_config.go
Normal file
19
server/internal/models/device_config.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// One-to-one config bound to a device GUID.
|
||||
type DeviceConfig struct {
|
||||
DeviceGUID string `gorm:"primaryKey;size:64"` // 1:1 with Device.GUID
|
||||
// Fields reflect your device JSON keys (m_*)
|
||||
MGuid string `gorm:"size:64;not null"` // duplicate for device FW convenience
|
||||
MRecordingDuration int `gorm:"not null;default:240"`
|
||||
MBaseURL string `gorm:"size:512;not null"`
|
||||
MPolling int `gorm:"not null;default:30"`
|
||||
MJitter int `gorm:"not null;default:10"`
|
||||
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
@@ -48,4 +48,5 @@ type DEviceTask struct {
|
||||
|
||||
// Optional: small attempt/lease system if you ever need retries/timeouts
|
||||
// Attempts int `gorm:"not null;default:0"`
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
|
||||
@@ -15,7 +15,10 @@ import (
|
||||
)
|
||||
|
||||
func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r := gin.Default()
|
||||
// r := gin.Default()
|
||||
|
||||
r := gin.New()
|
||||
r.Use(handlers.BodyLogger(), gin.Logger(), gin.Recovery())
|
||||
|
||||
jwtMgr := crypto.NewJWT(cfg.JWTSecret)
|
||||
|
||||
@@ -32,7 +35,7 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
/// --- GPS tracker handler
|
||||
trackersH := handlers.NewTrackersHandler(db)
|
||||
|
||||
tasksH := handlers.NewTasksHandler(db)
|
||||
tasksH := handlers.NewTasksHandler(db, mediamtxH)
|
||||
certsH := handlers.NewCertsHandler(db, &cfg.PkiIot, "720h")
|
||||
certsAdminH := handlers.NewCertsAdminHandler(db, &cfg.PkiIot)
|
||||
// --- Public auth
|
||||
@@ -62,6 +65,9 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r.GET("/device/:guid/tasks", authMW, middleware.DeviceAccessFilter(), tasksH.ListDeviceTasks)
|
||||
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
||||
r.POST("/certs/revoke", authMW, adminOnly, certsAdminH.Revoke)
|
||||
r.GET("/device/:guid/config", authMW, middleware.DeviceAccessFilter(), devH.GetDeviceConfig)
|
||||
r.POST("/device/:guid/config", authMW, adminOnly, devH.CreateDeviceConfig)
|
||||
r.PUT("/device/:guid/config", authMW, middleware.DeviceAccessFilter(), devH.UpdateDeviceConfig)
|
||||
|
||||
r.POST("/records/upload", middleware.MTLSGuardUpload(db), recH.Upload)
|
||||
r.GET("/records", authMW, recH.List)
|
||||
@@ -78,7 +84,7 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r.POST("/mediamtx/auth", mediamtxH.Auth)
|
||||
// Token minting for device/user flows
|
||||
r.POST("/mediamtx/token/publish", mediamtxH.MintPublish)
|
||||
r.POST("/mediamtx/token/read", authMW, mediamtxH.MintRead)
|
||||
r.POST("/mediamtx/token/read", authMW, middleware.DeviceAccessFilter(), mediamtxH.MintRead)
|
||||
// Admin controls
|
||||
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
|
||||
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)
|
||||
|
||||
Reference in New Issue
Block a user