Compare commits
7 Commits
dev_mtls
...
89c44d2979
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89c44d2979 | ||
|
|
f59883315d | ||
|
|
af7c659bef | ||
|
|
40b7e590a3 | ||
|
|
bdb89f0966 | ||
|
|
2895c6afdd | ||
|
|
ee210e847e |
@@ -44,9 +44,9 @@ services:
|
|||||||
args:
|
args:
|
||||||
APP_DIR: ${API_APP_DIR:-./cmd/api}
|
APP_DIR: ${API_APP_DIR:-./cmd/api}
|
||||||
environment:
|
environment:
|
||||||
VAULT_ADDR: "http://vault:8200"
|
VAULT_ADDR: "http://host.docker.internal:8200"
|
||||||
VAULT_TOKEN: "root"
|
VAULT_TOKEN: "hvs.tZ4eh9P18sCZ5c1PZIz59EmH"
|
||||||
VAULT_KV_PATH: "kv/data/snoop"
|
# VAULT_KV_PATH: "kv/data/snoop"
|
||||||
MINIO_ENDPOINT: "http://minio:9000"
|
MINIO_ENDPOINT: "http://minio:9000"
|
||||||
JWT_SECRET: ${JWT_SECRET}
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
env_file:
|
env_file:
|
||||||
|
|||||||
7
management-ui/package-lock.json
generated
7
management-ui/package-lock.json
generated
@@ -14,6 +14,7 @@
|
|||||||
"axios": "^1.11.0",
|
"axios": "^1.11.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"hls.js": "^1.6.13",
|
||||||
"leaflet": "^1.9.4",
|
"leaflet": "^1.9.4",
|
||||||
"lucide-vue-next": "^0.525.0",
|
"lucide-vue-next": "^0.525.0",
|
||||||
"reka-ui": "^2.5.0",
|
"reka-ui": "^2.5.0",
|
||||||
@@ -2006,6 +2007,12 @@
|
|||||||
"he": "bin/he"
|
"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": {
|
"node_modules/jiti": {
|
||||||
"version": "2.5.1",
|
"version": "2.5.1",
|
||||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.5.1.tgz",
|
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.5.1.tgz",
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
"axios": "^1.11.0",
|
"axios": "^1.11.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"hls.js": "^1.6.13",
|
||||||
"leaflet": "^1.9.4",
|
"leaflet": "^1.9.4",
|
||||||
"lucide-vue-next": "^0.525.0",
|
"lucide-vue-next": "^0.525.0",
|
||||||
"reka-ui": "^2.5.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.
|
// When parent switches between external/internal data at runtime, refetch if needed.
|
||||||
watch(() => props.allUsers, () => { if (!usingExternal.value) loadUsers() })
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<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>
|
||||||
@@ -1,49 +1,132 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/components/ui/dialog'
|
} from '@/components/ui/dialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import type { Device } from '@/lib/interfaces';
|
import type { Device } from '@/lib/interfaces'
|
||||||
import type { PropType } from 'vue';
|
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({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||||
type: Boolean as PropType<boolean>,
|
device: { type: Object as PropType<Device>, required: false },
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
device: { type: Object as PropType<Device>, required: false },
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'update:modelValue', v: boolean): void
|
(e: 'update:modelValue', v: boolean): void
|
||||||
(e: 'confirm'): void
|
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
function onSave() {
|
// --- DTOs from backend ---
|
||||||
emit('confirm')
|
type DeviceCertDto = {
|
||||||
// close the dialog
|
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)
|
emit('update:modelValue', false)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<template>
|
|
||||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
|
||||||
<DialogContent class="sm:min-w-[800px]">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>List of certificates</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
{{ props.device?.guid }}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<DialogFooter>
|
<template>
|
||||||
<Button @click="onSave">Close</Button>
|
<Dialog :open="props.modelValue" @update:open="(v:boolean) => emit('update:modelValue', v)">
|
||||||
</DialogFooter>
|
<DialogContent class="sm:min-w-[1000px]">
|
||||||
</DialogContent>
|
<DialogHeader>
|
||||||
</Dialog>
|
<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="close">Close</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,41 +1,226 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
import DeviceDashboard from './DeviceDashboard.vue';
|
import DeviceDashboard from './DeviceDashboard.vue'
|
||||||
import { Button } from '@/components/ui/button';
|
import DeviceRecordings from './DeviceRecordings.vue'
|
||||||
import DeviceRecordings from './DeviceRecordings.vue';
|
import { Button } from '@/components/ui/button'
|
||||||
import { type PropType } from 'vue';
|
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({
|
const props = defineProps({
|
||||||
guid: { type: String as PropType<string>, required: true },
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Tabs default-value="records">
|
<Tabs default-value="records">
|
||||||
<TabsList class="space-x-8">
|
<TabsList class="space-x-8">
|
||||||
<TabsTrigger value="dashboard">
|
<TabsTrigger value="dashboard">Dashboard</TabsTrigger>
|
||||||
Dashboard
|
<TabsTrigger value="records">Records</TabsTrigger>
|
||||||
</TabsTrigger>
|
<TabsTrigger value="livestream">Livestream</TabsTrigger>
|
||||||
<TabsTrigger value="records">
|
</TabsList>
|
||||||
Records
|
|
||||||
</TabsTrigger>
|
<TabsContent value="dashboard">
|
||||||
<TabsTrigger value="livestream">
|
<DeviceDashboard :guid="guid" />
|
||||||
Livestream
|
</TabsContent>
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
<TabsContent value="records">
|
||||||
<TabsContent value="dashboard">
|
<DeviceRecordings :guid="guid" />
|
||||||
<DeviceDashboard/>
|
</TabsContent>
|
||||||
</TabsContent>
|
|
||||||
<TabsContent value="records">
|
<TabsContent value="livestream">
|
||||||
<DeviceRecordings :guid="guid"/>
|
<div class="flex flex-col gap-4 pt-2">
|
||||||
</TabsContent>
|
<div class="flex gap-3">
|
||||||
<TabsContent value="livestream">
|
<Button :disabled="sending" @click="startStreaming">
|
||||||
<Button>
|
{{ sending ? 'Starting…' : 'Start streaming' }}
|
||||||
Start streaming
|
</Button>
|
||||||
</Button>
|
<Button :disabled="sending" @click="stopStreaming">
|
||||||
<Button>
|
{{ sending ? 'Stopping…' : 'Stop streaming' }}
|
||||||
Stop streaming
|
</Button>
|
||||||
</Button>
|
</div>
|
||||||
</TabsContent>
|
|
||||||
</Tabs>
|
<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>
|
</template>
|
||||||
@@ -1,15 +1,10 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
import {
|
||||||
Card,
|
Card, CardContent, CardFooter, CardHeader, CardTitle,
|
||||||
CardContent,
|
} from '@/components/ui/card'
|
||||||
CardDescription,
|
import { Input } from '@/components/ui/input'
|
||||||
CardFooter,
|
import { Label } from '@/components/ui/label'
|
||||||
CardHeader,
|
import { Button } from '@/components/ui/button'
|
||||||
CardTitle,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
import {
|
||||||
NumberField,
|
NumberField,
|
||||||
NumberFieldContent,
|
NumberFieldContent,
|
||||||
@@ -17,74 +12,278 @@ import {
|
|||||||
NumberFieldIncrement,
|
NumberFieldIncrement,
|
||||||
NumberFieldInput,
|
NumberFieldInput,
|
||||||
} from '@/components/ui/number-field'
|
} from '@/components/ui/number-field'
|
||||||
import AssignDevice from "./AssignDevice.vue";
|
|
||||||
import { ref } from "vue";
|
import { h, ref, watch, computed, type PropType } from 'vue'
|
||||||
import Separator from "@/components/ui/separator/Separator.vue";
|
import { api } from '@/lib/api'
|
||||||
import DataRangePicker from "./DataRangePicker.vue";
|
|
||||||
const selectedUserIds = ref<string[]>([])
|
// Table bits for tasks
|
||||||
const usrIDs = selectedUserIds.value
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Card class="flex w-full max-w-4xl mx-auto">
|
<!-- Two columns, full available height -->
|
||||||
<CardHeader class="pb-4">
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-6rem)]">
|
||||||
<CardTitle>
|
<!-- LEFT: Config card -->
|
||||||
Dashboard
|
<Card class="h-full flex flex-col">
|
||||||
</CardTitle>
|
<CardHeader>
|
||||||
</CardHeader>
|
<div class="flex items-center justify-between">
|
||||||
<CardContent class="flex-1 grid gap-4 py-4">
|
<CardTitle>Device {{ props.guid }}</CardTitle>
|
||||||
<div class="grid gap-5">
|
<div class="flex gap-2">
|
||||||
<div class="grid space-y-2 grid-cols-4 items-center">
|
<Button variant="outline" :disabled="cfgLoading" @click="loadConfig">
|
||||||
<Label for="users">Allowed users</Label>
|
{{ cfgLoading ? 'Loading…' : 'Refresh config' }}
|
||||||
<AssignDevice v-model="usrIDs" class="col-span-3 w-full"></AssignDevice>
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</CardHeader>
|
||||||
|
|
||||||
<div class="flex space-x-4 pt-2 gap-4">
|
<CardContent class="flex-1 grid gap-5">
|
||||||
<Button>Start recording</Button>
|
<div class="flex gap-2">
|
||||||
<Button>Stop recording</Button>
|
<Button :disabled="sending" @click="startRecording">
|
||||||
</div>
|
{{ sending ? 'Starting…' : 'Start recording' }}
|
||||||
<div class="space-y-2 gap-4">
|
</Button>
|
||||||
<NumberField id="duration" :default-value="120" :min="30">
|
<Button :disabled="sending" @click="stopRecording">
|
||||||
<Label for="duration"> Record duration in seconds</Label>
|
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
||||||
<NumberFieldContent>
|
</Button>
|
||||||
<NumberFieldDecrement></NumberFieldDecrement>
|
</div>
|
||||||
<NumberFieldInput></NumberFieldInput>
|
|
||||||
<NumberFieldIncrement></NumberFieldIncrement>
|
|
||||||
</NumberFieldContent>
|
|
||||||
</NumberField>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Separator class="my-6">Communication settings</Separator>
|
<div v-if="cfgError" class="text-sm text-red-600">{{ cfgError }}</div>
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
||||||
|
<!-- 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>
|
||||||
|
|
||||||
|
<!-- Row 1: duration (full width) -->
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
<NumberField id="polling" :default-value="60" :min="30">
|
<NumberField id="duration" v-model="duration" :min="30" :step="1">
|
||||||
<Label for="polling"> Timeout interwal in seconds </Label>
|
<Label for="duration">Record duration (sec)</Label>
|
||||||
<NumberFieldContent>
|
<NumberFieldContent>
|
||||||
<NumberFieldDecrement></NumberFieldDecrement>
|
<NumberFieldDecrement />
|
||||||
<NumberFieldInput></NumberFieldInput>
|
<NumberFieldInput />
|
||||||
<NumberFieldIncrement></NumberFieldIncrement>
|
<NumberFieldIncrement />
|
||||||
</NumberFieldContent>
|
</NumberFieldContent>
|
||||||
</NumberField>
|
</NumberField>
|
||||||
</div>
|
</div>
|
||||||
<div class="space-y-2">
|
|
||||||
|
|
||||||
<NumberField id="jitter" :default-value="10" :min="5">
|
<!-- Row 2: polling + jitter (two columns) -->
|
||||||
<Label for="jitter"> Jitter in seconds </Label>
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
<NumberFieldContent>
|
<div class="space-y-2">
|
||||||
<NumberFieldDecrement></NumberFieldDecrement>
|
<NumberField id="polling" v-model="polling" :min="30" :step="1">
|
||||||
<NumberFieldInput></NumberFieldInput>
|
<Label for="polling">Timeout interval (sec)</Label>
|
||||||
<NumberFieldIncrement></NumberFieldIncrement>
|
<NumberFieldContent>
|
||||||
</NumberFieldContent>
|
<NumberFieldDecrement />
|
||||||
</NumberField>
|
<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>
|
</div>
|
||||||
</div>
|
</CardContent>
|
||||||
<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">
|
||||||
</Card>
|
<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>
|
</template>
|
||||||
@@ -1,48 +1,130 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
} from '@/components/ui/dialog'
|
} from '@/components/ui/dialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import type { Device } from '@/lib/interfaces';
|
import type { Device, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||||
import type { PropType } from 'vue';
|
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({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||||
type: Boolean as PropType<boolean>,
|
device: { type: Object as PropType<Device>, required: false },
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
device: { type: Object as PropType<Device>, required: false },
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'update:modelValue', v: boolean): void
|
(e: 'update:modelValue', v: boolean): void
|
||||||
(e: 'confirm'): 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')
|
emit('confirm')
|
||||||
// close the dialog
|
|
||||||
emit('update:modelValue', false)
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
<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>
|
<DialogHeader class="flex flex-row items-center justify-between gap-4">
|
||||||
<DialogTitle>Tasks</DialogTitle>
|
<div>
|
||||||
<DialogDescription>
|
<DialogTitle>Tasks</DialogTitle>
|
||||||
{{ props.device?.guid }}
|
<DialogDescription>{{ props.device?.guid }}</DialogDescription>
|
||||||
</DialogDescription>
|
</div>
|
||||||
</DialogHeader>
|
<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>
|
||||||
|
|
||||||
<DialogFooter>
|
<div v-if="loading" class="text-sm text-muted-foreground py-8 text-center">
|
||||||
<Button @click="onSave">Close</Button>
|
Loading tasks…
|
||||||
</DialogFooter>
|
</div>
|
||||||
</DialogContent>
|
<div v-else>
|
||||||
</Dialog>
|
<DataTableNoCheckboxScroll :columns="task_columns" :data="tasks" minTableWidth="min-w-[800px]"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button @click="onClose">Close</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</template>
|
</template>
|
||||||
@@ -9,3 +9,39 @@ export interface Users {
|
|||||||
username: string,
|
username: string,
|
||||||
role: 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 { Label } from '@/components/ui/label'
|
||||||
import { Switch } from '@/components/ui/switch'
|
import { Switch } from '@/components/ui/switch'
|
||||||
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
||||||
|
import Navbar from '@/customcompometns/Navbar.vue'
|
||||||
import { useColorMode } from '@vueuse/core'
|
import { useColorMode } from '@vueuse/core'
|
||||||
import Navbar from '@/customcompometns/Navbar.vue';
|
import { defineProps, reactive, watch, ref, computed, type PropType } from 'vue'
|
||||||
import type { PropType } from 'vue';
|
|
||||||
import { defineProps, defineEmits, reactive, watch, ref, computed } from 'vue';
|
|
||||||
import { v4 as uuidv4 } from 'uuid'
|
import { v4 as uuidv4 } from 'uuid'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { api } from '@/lib/api'
|
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 mode = useColorMode()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
type CreateDevicePayload = {
|
type CreateDevicePayload = {
|
||||||
guid: string
|
guid: string
|
||||||
name: string
|
name: string
|
||||||
userIds: number[]
|
userIds: number[]
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserPayload = {
|
type CreateUserPayload = {
|
||||||
username: string
|
username: string
|
||||||
password: string
|
password: string
|
||||||
role: string // 'admin' | 'user'
|
role: string // 'admin' | 'user'
|
||||||
}
|
}
|
||||||
|
type CreateDeviceConfigDto = {
|
||||||
type CreateTrackerPayload = {
|
m_recordingDuration: number
|
||||||
guid: string
|
m_baseUrl: string
|
||||||
name: string
|
m_polling: number
|
||||||
userIds: number[]
|
m_jitter: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const router = useRouter()
|
type CreateTrackerConfigDto = {
|
||||||
|
m_baseUrl: string
|
||||||
|
m_polling: number
|
||||||
|
m_jitter: number
|
||||||
|
}
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||||
type: Boolean as PropType<boolean>,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// local form state
|
// ------------------------ Local form state ------------------------
|
||||||
const device_form = reactive({
|
const device_form = reactive({
|
||||||
guid: uuidv4(), // default fresh UUID
|
guid: uuidv4(),
|
||||||
name: '',
|
name: '',
|
||||||
|
// config fields
|
||||||
|
baseUrl: '',
|
||||||
|
duration: 240,
|
||||||
|
polling: 60,
|
||||||
|
jitter: 10,
|
||||||
})
|
})
|
||||||
|
|
||||||
const user_form = reactive({
|
const user_form = reactive({
|
||||||
@@ -57,31 +71,50 @@ const user_form = reactive({
|
|||||||
const tracker_form = reactive({
|
const tracker_form = reactive({
|
||||||
guid: uuidv4(),
|
guid: uuidv4(),
|
||||||
name: '',
|
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[]>([])
|
const selectedUserIds = ref<string[]>([])
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.modelValue,
|
() => props.modelValue,
|
||||||
(val) => {
|
(val) => {
|
||||||
if (val) {
|
if (val) {
|
||||||
|
// reset device
|
||||||
device_form.guid = uuidv4()
|
device_form.guid = uuidv4()
|
||||||
device_form.name = ''
|
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 = []
|
selectedUserIds.value = []
|
||||||
user_form.username = ''
|
user_form.username = ''
|
||||||
user_form.password = ''
|
user_form.password = ''
|
||||||
user_form.isAdmin = false
|
user_form.isAdmin = false
|
||||||
|
|
||||||
userError.value = null
|
userError.value = null
|
||||||
userSubmitting.value = false
|
userSubmitting.value = false
|
||||||
userSuccess.value = null
|
userSuccess.value = null
|
||||||
// tracker_form.guid = uuidv4()
|
errorMsg.value = null
|
||||||
// tracker_form.name = ''
|
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 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 submitting = ref(false)
|
||||||
const errorMsg = ref<string | null>(null)
|
const errorMsg = ref<string | null>(null)
|
||||||
@@ -91,19 +124,58 @@ const userError = ref<string | null>(null)
|
|||||||
const userSuccess = ref<string | null>(null)
|
const userSuccess = ref<string | null>(null)
|
||||||
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
||||||
|
|
||||||
const canSubmit = computed(() => {
|
const canSubmitDevice = computed(() =>
|
||||||
return (
|
!!device_form.guid &&
|
||||||
!!device_form.guid &&
|
uuidV4Re.test(device_form.guid) &&
|
||||||
uuidV4Re.test(device_form.guid) &&
|
!!device_form.name.trim() &&
|
||||||
!!device_form.name.trim() &&
|
!!device_form.baseUrl.trim() &&
|
||||||
!submitting.value
|
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() {
|
async function submitDevice() {
|
||||||
errorMsg.value = null
|
errorMsg.value = null
|
||||||
if (!canSubmit.value) {
|
if (!canSubmitDevice.value) {
|
||||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,25 +189,90 @@ async function submitDevice() {
|
|||||||
userIds,
|
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
|
submitting.value = true
|
||||||
try {
|
try {
|
||||||
|
// 1) create device
|
||||||
await api.post('/devices/create', payload)
|
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')
|
router.replace('/admin')
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
// keep client error generic
|
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device or send config.'
|
||||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
|
||||||
} finally {
|
} finally {
|
||||||
submitting.value = false
|
submitting.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const canSubmitUser = computed(() => {
|
async function submitTracker() {
|
||||||
return (
|
errorMsg.value = null
|
||||||
user_form.username.trim().length >= 3 &&
|
if (!canSubmitTracker.value) {
|
||||||
user_form.password.length >= 8 && // basic client-side check; real policy enforced server-side
|
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||||
!userSubmitting.value
|
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() {
|
async function submitUser() {
|
||||||
userError.value = null
|
userError.value = null
|
||||||
@@ -148,7 +285,7 @@ async function submitUser() {
|
|||||||
|
|
||||||
const payload: CreateUserPayload = {
|
const payload: CreateUserPayload = {
|
||||||
username: user_form.username.trim(),
|
username: user_form.username.trim(),
|
||||||
password: user_form.password, // do not trim passwords
|
password: user_form.password,
|
||||||
role: userRole.value,
|
role: userRole.value,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,33 +301,25 @@ async function submitUser() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitTracker() {
|
function downloadDeviceConfig() {
|
||||||
errorMsg.value = null
|
const payload = {
|
||||||
if (!canSubmit.value) {
|
m_guid: device_form.guid,
|
||||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
m_recordingDuration: Number(device_form.duration),
|
||||||
return
|
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
|
function downloadTrackerConfig() {
|
||||||
.map((s) => Number(s))
|
const payload = {
|
||||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
m_guid: tracker_form.guid,
|
||||||
|
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||||
const payload: CreateDevicePayload = {
|
m_polling: Number(tracker_form.polling),
|
||||||
guid: device_form.guid,
|
m_jitter: Number(tracker_form.jitter),
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
downloadConfig(`config-${tracker_form.guid}.json`, payload)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -198,40 +327,75 @@ async function submitTracker() {
|
|||||||
<Navbar>
|
<Navbar>
|
||||||
<div class="w-full py-8">
|
<div class="w-full py-8">
|
||||||
<div class="mx-auto">
|
<div class="mx-auto">
|
||||||
<!-- Horizontal cards with gap -->
|
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
||||||
|
|
||||||
<!-- Create device -->
|
<!-- Create device -->
|
||||||
<Card class="h-full flex flex-col">
|
<Card class="h-full flex flex-col">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create device</CardTitle>
|
<CardTitle>Create device</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent class="flex-1">
|
<CardContent class="flex-1">
|
||||||
<!-- add vertical spacing between rows -->
|
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="guid" class="text-right">GUID</Label>
|
<Label for="d-guid" class="text-right">GUID</Label>
|
||||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
<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>
|
</div>
|
||||||
|
|
||||||
|
<!-- Config -->
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="name" class="text-right">Name</Label>
|
<Label for="d-baseurl" class="text-right">Base URL</Label>
|
||||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
<Input id="d-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||||
|
v-model="device_form.baseUrl" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
<Label for="users" class="text-right">Allowed users</Label>
|
<NumberField id="d-duration" v-model="device_form.duration" :min="30" :step="1">
|
||||||
<!-- make the component span and fill -->
|
<Label for="d-duration">Record duration (sec)</Label>
|
||||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
<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>
|
</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>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
<CardFooter class="flex gap-2">
|
||||||
<CardFooter>
|
<Button variant="outline" @click="downloadDeviceConfig"
|
||||||
<Button :disabled="!canSubmit" @click="submitDevice">
|
:disabled="!canDownloadDeviceConfig">
|
||||||
|
Download config
|
||||||
|
</Button>
|
||||||
|
<Button :disabled="!canSubmitDevice" @click="submitDevice">
|
||||||
{{ submitting ? 'Saving…' : 'Save' }}
|
{{ submitting ? 'Saving…' : 'Save' }}
|
||||||
</Button>
|
</Button>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
@@ -242,38 +406,30 @@ async function submitTracker() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create user</CardTitle>
|
<CardTitle>Create user</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent class="flex-1">
|
<CardContent class="flex-1">
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="username" class="text-right">Username</Label>
|
<Label for="u-user" class="text-right">Username</Label>
|
||||||
<Input id="username" class="col-span-3 w-full" v-model="user_form.username" />
|
<Input id="u-user" class="col-span-3 w-full" v-model="user_form.username" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="password" class="text-right">Password</Label>
|
<Label for="u-pass" class="text-right">Password</Label>
|
||||||
<Input id="password" type="password" class="col-span-3 w-full"
|
<Input id="u-pass" type="password" class="col-span-3 w-full"
|
||||||
v-model="user_form.password" />
|
v-model="user_form.password" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<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">
|
<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"
|
v-model="user_form.isAdmin"
|
||||||
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
||||||
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="userError" class="text-sm text-red-600" aria-live="assertive">
|
<p v-if="userError" class="text-sm text-red-600">{{ userError }}</p>
|
||||||
{{ userError }}
|
<p v-if="userSuccess" class="text-sm text-green-600">{{ userSuccess }}</p>
|
||||||
</p>
|
|
||||||
<p v-if="userSuccess" class="text-sm text-green-600" aria-live="polite">
|
|
||||||
{{ userSuccess }}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
||||||
<CardFooter>
|
<CardFooter>
|
||||||
<Button :disabled="!canSubmitUser" @click="submitUser">
|
<Button :disabled="!canSubmitUser" @click="submitUser">
|
||||||
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
||||||
@@ -281,37 +437,66 @@ async function submitTracker() {
|
|||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<!-- Create tracker -->
|
||||||
<Card class="h-full flex flex-col">
|
<Card class="h-full flex flex-col">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create tracker</CardTitle>
|
<CardTitle>Create tracker</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent class="flex-1">
|
<CardContent class="flex-1">
|
||||||
<!-- add vertical spacing between rows -->
|
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="guid" class="text-right">GUID</Label>
|
<Label for="t-guid" class="text-right">GUID</Label>
|
||||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
<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>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="name" class="text-right">Name</Label>
|
<Label for="t-users" class="text-right">Allowed users</Label>
|
||||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
<AssignDevice id="t-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
<CardFooter class="flex gap-2">
|
||||||
<CardFooter>
|
<Button variant="outline" @click="downloadTrackerConfig"
|
||||||
<Button :disabled="!canSubmit" @click="submitTracker">
|
:disabled="!canDownloadTrackerConfig">
|
||||||
|
Download config
|
||||||
|
</Button>
|
||||||
|
<Button :disabled="!canSubmitTracker" @click="submitTracker">
|
||||||
{{ submitting ? 'Saving…' : 'Save' }}
|
{{ submitting ? 'Saving…' : 'Save' }}
|
||||||
</Button>
|
</Button>
|
||||||
</CardFooter>
|
</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": {
|
"compilerOptions": {
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["./src/*"]
|
"@/*": ["./src/*","src/types/**/*"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,23 @@ map $http_upgrade $connection_upgrade {
|
|||||||
# Helpful for larger uploads via API (tweak as you wish)
|
# Helpful for larger uploads via API (tweak as you wish)
|
||||||
client_max_body_size 400m;
|
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 {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
server_name _;
|
server_name _;
|
||||||
@@ -60,6 +77,9 @@ server {
|
|||||||
listen 443 ssl http2;
|
listen 443 ssl http2;
|
||||||
server_name _;
|
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 /etc/nginx/ssl/certs/fullchain.pem;
|
||||||
ssl_certificate_key /etc/nginx/ssl/certs/privkey.pem;
|
ssl_certificate_key /etc/nginx/ssl/certs/privkey.pem;
|
||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
@@ -98,43 +118,50 @@ server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# ---- mTLS-protected paths ----
|
# ---- mTLS-protected paths ----
|
||||||
location ^~ /records {
|
location ^~ /api/records/upload {
|
||||||
if ($ssl_client_verify != SUCCESS) {
|
if ($ssl_client_verify != SUCCESS) {
|
||||||
return 495;
|
return 495;
|
||||||
}
|
}
|
||||||
|
rewrite ^/api/(.*)$ /$1 break;
|
||||||
proxy_pass http://snoop-api:8080;
|
proxy_pass http://snoop-api:8080;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ^~ /tasks {
|
location ^~ /api/tasks {
|
||||||
if ($ssl_client_verify != SUCCESS) {
|
if ($ssl_client_verify != SUCCESS) {
|
||||||
return 495;
|
return 495;
|
||||||
}
|
}
|
||||||
|
rewrite ^/api/(.*)$ /$1 break;
|
||||||
proxy_pass http://snoop-api:8080;
|
proxy_pass http://snoop-api:8080;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ^~ /renew {
|
location ^~ /api/renew {
|
||||||
if ($ssl_client_verify != SUCCESS) {
|
if ($ssl_client_verify != SUCCESS) {
|
||||||
return 495;
|
return 495;
|
||||||
}
|
}
|
||||||
|
rewrite ^/api/(.*)$ /$1 break;
|
||||||
proxy_pass http://snoop-api:8080;
|
proxy_pass http://snoop-api:8080;
|
||||||
}
|
}
|
||||||
|
|
||||||
# MediaMTX HLS
|
# MediaMTX HLS
|
||||||
location ^~ /hls/ {
|
location ^~ /hls/ {
|
||||||
if ($ssl_client_verify != SUCCESS) {
|
# if ($ssl_client_verify != SUCCESS) {
|
||||||
return 495;
|
# return 495;
|
||||||
}
|
# }
|
||||||
proxy_pass http://mediamtx:8888/;
|
proxy_pass http://mediamtx:8888/;
|
||||||
}
|
}
|
||||||
|
|
||||||
# MediaMTX WebRTC (WHIP/WHEP/test)
|
# MediaMTX WebRTC (WHIP/WHEP/test)
|
||||||
location ^~ /webrtc/ {
|
location ^~ /whip/ {
|
||||||
if ($ssl_client_verify != SUCCESS) {
|
if ($ssl_client_verify != SUCCESS) {
|
||||||
return 495;
|
return 495;
|
||||||
}
|
}
|
||||||
proxy_pass http://mediamtx:8889/;
|
proxy_pass http://mediamtx:8889;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header Connection $connection_upgrade;
|
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)
|
# MQTT WS entry points (guarded by mTLS)
|
||||||
@@ -158,4 +185,19 @@ server {
|
|||||||
proxy_set_header Connection $connection_upgrade;
|
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.DEviceTask{},
|
||||||
&models.DeviceCertificate{},
|
&models.DeviceCertificate{},
|
||||||
&models.RevokedSerial{},
|
&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 {
|
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 {
|
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"`
|
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})
|
// Pass raw JSON string as payload (e.g. {"sleepTimeout":5,"jitterMs":50,"recordingDurationSec":60})
|
||||||
// Keep it string to let device/server evolve freely.
|
// Keep it string to let device/server evolve freely.
|
||||||
Payload string `json:"payload" binding:"required"`
|
Payload string `json:"payload"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Device polls: single next task
|
// Device polls: single next task
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -108,7 +109,7 @@ func (h *CertsHandler) Enroll(c *gin.Context) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
sign, err := h.pki.SignCSR(ctx, csr, "urn:device:"+guid, h.ttl)
|
sign, err := h.pki.SignCSR(ctx, csr, "urn:device:"+guid, h.ttl)
|
||||||
if err != nil {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -302,5 +303,147 @@ func (h *DevicesHandler) ListCertsByDevice(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||||
return
|
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
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"smoop-api/internal/config"
|
"smoop-api/internal/config"
|
||||||
@@ -10,6 +12,7 @@ import (
|
|||||||
"smoop-api/internal/dto"
|
"smoop-api/internal/dto"
|
||||||
"smoop-api/internal/models"
|
"smoop-api/internal/models"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -29,6 +32,10 @@ func NewMediaMTXHandler(db *gorm.DB, jwt *crypto.JWTManager, c config.MediaMTXCo
|
|||||||
// POST /mediamtx/auth
|
// POST /mediamtx/auth
|
||||||
func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
||||||
var req dto.MediaMTXAuthReq
|
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 {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad auth body"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "bad auth body"})
|
||||||
return
|
return
|
||||||
@@ -36,52 +43,19 @@ func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
|||||||
|
|
||||||
// token can come from Authorization: Bearer or from query (?token=)
|
// token can come from Authorization: Bearer or from query (?token=)
|
||||||
tok := extractBearer(c.GetHeader("Authorization"))
|
tok := extractBearer(c.GetHeader("Authorization"))
|
||||||
|
|
||||||
|
if tok == "" && req.Query != "" {
|
||||||
|
tok = tokenFromQuery(req.Query) // Parse "token=" from the raw query string
|
||||||
|
}
|
||||||
|
|
||||||
if tok == "" {
|
if tok == "" {
|
||||||
tok = tokenFromQuery(req.Query)
|
tok = strings.TrimSpace(req.Token)
|
||||||
}
|
}
|
||||||
if tok == "" {
|
if tok == "" {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||||
return
|
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
|
// parse & validate media token
|
||||||
mc, err := h.jwtMgr.ParseMedia(tok)
|
mc, err := h.jwtMgr.ParseMedia(tok)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -126,7 +100,8 @@ func tokenFromQuery(raw string) string {
|
|||||||
if raw == "" {
|
if raw == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
q, _ := url.ParseQuery(raw)
|
s := strings.TrimPrefix(raw, "?")
|
||||||
|
q, _ := url.ParseQuery(s)
|
||||||
return q.Get("token")
|
return q.Get("token")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,6 +128,9 @@ func (h *MediaMTXHandler) canRead(sub, path string) bool {
|
|||||||
}
|
}
|
||||||
func (h *MediaMTXHandler) canPublish(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
|
// 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
|
var u models.User
|
||||||
if err := h.db.Where("id = ?", sub).First(&u).Error; err == nil && u.Role == models.RoleAdmin {
|
if err := h.db.Where("id = ?", sub).First(&u).Error; err == nil && u.Role == models.RoleAdmin {
|
||||||
return true
|
return true
|
||||||
@@ -163,15 +141,46 @@ func (h *MediaMTXHandler) canPublish(sub, path string) bool {
|
|||||||
// --- 3.2 Mint publish token (device flow) -> returns WHIP URL
|
// --- 3.2 Mint publish token (device flow) -> returns WHIP URL
|
||||||
// POST /mediamtx/token/publish {guid}
|
// POST /mediamtx/token/publish {guid}
|
||||||
func (h *MediaMTXHandler) MintPublish(c *gin.Context) {
|
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
|
var req dto.PublishTokenReq
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
||||||
return
|
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
|
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))
|
// We mint a *read* token for the browser to consume HLS.
|
||||||
c.JSON(http.StatusCreated, dto.PublishTokenResp{WHIP: whip})
|
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
|
// --- 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)
|
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"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -14,10 +15,16 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type TasksHandler struct {
|
type TasksHandler struct {
|
||||||
db *gorm.DB
|
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
|
// 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"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||||
return
|
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{
|
task := models.DEviceTask{
|
||||||
DeviceGUID: guid,
|
DeviceGUID: guid,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ type DeviceCertificate struct {
|
|||||||
NotAfter time.Time
|
NotAfter time.Time
|
||||||
PemCert string `gorm:"type:text"` // PEM of leaf cert
|
PemCert string `gorm:"type:text"` // PEM of leaf cert
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
|
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// “Instant kill” list checked by the mTLS guard before allowing access.
|
// “Instant kill” list checked by the mTLS guard before allowing access.
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ package models
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type Device struct {
|
type Device struct {
|
||||||
GUID string `gorm:"primaryKey"`
|
GUID string `gorm:"primaryKey"`
|
||||||
Name string `gorm:"size:255;not null"`
|
Name string `gorm:"size:255;not null"`
|
||||||
Users []User `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
|
Users []User `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
|
||||||
Records []Record `gorm:"foreignKey:DeviceGUID;references:GUID;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
|
CreatedAt time.Time
|
||||||
UpdatedAt 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
|
// Optional: small attempt/lease system if you ever need retries/timeouts
|
||||||
// Attempts int `gorm:"not null;default:0"`
|
// 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 {
|
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)
|
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
|
/// --- GPS tracker handler
|
||||||
trackersH := handlers.NewTrackersHandler(db)
|
trackersH := handlers.NewTrackersHandler(db)
|
||||||
|
|
||||||
tasksH := handlers.NewTasksHandler(db)
|
tasksH := handlers.NewTasksHandler(db, mediamtxH)
|
||||||
certsH := handlers.NewCertsHandler(db, &cfg.PkiIot, "720h")
|
certsH := handlers.NewCertsHandler(db, &cfg.PkiIot, "720h")
|
||||||
certsAdminH := handlers.NewCertsAdminHandler(db, &cfg.PkiIot)
|
certsAdminH := handlers.NewCertsAdminHandler(db, &cfg.PkiIot)
|
||||||
// --- Public auth
|
// --- 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/tasks", authMW, middleware.DeviceAccessFilter(), tasksH.ListDeviceTasks)
|
||||||
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
||||||
r.POST("/certs/revoke", authMW, adminOnly, certsAdminH.Revoke)
|
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.POST("/records/upload", middleware.MTLSGuardUpload(db), recH.Upload)
|
||||||
r.GET("/records", authMW, recH.List)
|
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)
|
r.POST("/mediamtx/auth", mediamtxH.Auth)
|
||||||
// Token minting for device/user flows
|
// Token minting for device/user flows
|
||||||
r.POST("/mediamtx/token/publish", mediamtxH.MintPublish)
|
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
|
// Admin controls
|
||||||
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
|
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
|
||||||
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)
|
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)
|
||||||
|
|||||||
Reference in New Issue
Block a user