Compare commits

...

10 Commits

38 changed files with 1262 additions and 195 deletions

72
certs/vault_install.sh Normal file
View File

@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# -------------------------------------------------------
# HashiCorp Vault Installation and Configuration Script
# -------------------------------------------------------
set -e
# -------------------------------------------------------
# 1. Install Vault
# -------------------------------------------------------
# yum install -y yum-utils
# yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
# yum -y install vault
# echo "[+] Vault installed successfully."
# -------------------------------------------------------
# 2. Create directories and set permissions
# -------------------------------------------------------
useradd --system --home /opt/vault --shell /bin/false vault
mkdir -p /opt/vault/data
chown -R vault:vault /opt/vault
mkdir -p /etc/vault
chown -R vault:vault /etc/vault
echo "[+] Directories and permissions set."
# -------------------------------------------------------
# 3. Create Vault configuration file
# -------------------------------------------------------
cat > /etc/vault/config.hcl <<'EOF'
storage "file" {
path = "/opt/vault/data"
}
listener "tcp" {
address = "127.0.0.1:8200"
tls_disable = 1
}
disable_mlock = true
ui = true
EOF
echo "[+] Vault configuration file created at /etc/vault/config.hcl."
# -------------------------------------------------------
# 4. Create systemd service file
# -------------------------------------------------------
cat > /etc/systemd/system/vault.service <<'EOF'
[Unit]
Description=HashiCorp Vault
After=network-online.target
Wants=network-online.target
[Service]
User=vault
Group=vault
ExecStart=/usr/bin/vault server -config=/etc/vault/config.hcl
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
echo "[+] Vault systemd service file created at /etc/systemd/system/vault.service."
# -------------------------------------------------------
# 5. Enable and start Vault service
# -------------------------------------------------------
restorecon -v /usr/bin/vault
systemctl daemon-reload
systemctl enable vault
systemctl start vault
echo "[+] Vault service started and enabled."
# -------------------------------------------------------
# 6. Final status
# -------------------------------------------------------
systemctl --no-pager status vault | grep "Active:" || echo "[+] Vault service may need manual check."

View File

@@ -45,7 +45,7 @@ services:
APP_DIR: ${API_APP_DIR:-./cmd/api}
environment:
VAULT_ADDR: "http://host.docker.internal:8200"
VAULT_TOKEN: "hvs.tZ4eh9P18sCZ5c1PZIz59EmH"
VAULT_TOKEN: "hvs.rKzgIc5aaucOCtlJNsUdZuEH"
# VAULT_KV_PATH: "kv/data/snoop"
MINIO_ENDPOINT: "http://minio:9000"
JWT_SECRET: ${JWT_SECRET}
@@ -91,9 +91,10 @@ services:
- proxy
mediamtx:
image: bluenviron/mediamtx:latest
# restart: unless-stopped
# Expose default listeners for all common protocols
build:
context: ./mediamtx
dockerfile: Dockerfile
restart: unless-stopped
ports:
- "8554:8554" # RTSP
- "1935:1935" # RTMP
@@ -105,13 +106,6 @@ services:
volumes:
- ./mediamtx/mediamtx.yml:/mediamtx.yml:ro,Z
- mediamtx-recordings:/recordings
networks:
- proxy
- snoopBack
rclone:
image: rclone/rclone:latest
command: rcd --rc-addr=:5572 --rc-no-auth
environment:
RCLONE_CONFIG_MINIO_TYPE: s3
RCLONE_CONFIG_MINIO_PROVIDER: Minio
@@ -120,11 +114,10 @@ services:
RCLONE_CONFIG_MINIO_SECRET_ACCESS_KEY: minioadmin
RCLONE_CONFIG_MINIO_REGION: us-east-1
RCLONE_CONFIG_MINIO_FORCE_PATH_STYLE: "true"
volumes:
- mediamtx-recordings:/recordings
networks:
- snoopBack
- proxy
- snoopBack
# NEW: EMQX MQTT broker
emqx:

View File

@@ -14,10 +14,11 @@
"axios": "^1.11.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"event-source-polyfill": "^1.0.31",
"hls.js": "^1.6.13",
"leaflet": "^1.9.4",
"lucide-vue-next": "^0.525.0",
"reka-ui": "^2.5.0",
"reka-ui": "^2.6.1",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.11",
"tw-animate-css": "^1.3.6",
@@ -30,6 +31,7 @@
"devDependencies": {
"@iconify-json/radix-icons": "^1.2.2",
"@iconify/vue": "^5.0.0",
"@types/event-source-polyfill": "^1.0.5",
"@types/leaflet": "^1.9.20",
"@types/node": "^24.1.0",
"@vitejs/plugin-vue": "^6.0.0",
@@ -1276,6 +1278,13 @@
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
"license": "MIT"
},
"node_modules/@types/event-source-polyfill": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@types/event-source-polyfill/-/event-source-polyfill-1.0.5.tgz",
"integrity": "sha512-iaiDuDI2aIFft7XkcwMzDWLqo7LVDixd2sR6B4wxJut9xcp/Ev9bO4EFg4rm6S9QxATLBj5OPxdeocgmhjwKaw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
@@ -1830,6 +1839,12 @@
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
"license": "MIT"
},
"node_modules/event-source-polyfill": {
"version": "1.0.31",
"resolved": "https://registry.npmjs.org/event-source-polyfill/-/event-source-polyfill-1.0.31.tgz",
"integrity": "sha512-4IJSItgS/41IxN5UVAVuAyczwZF7ZIEsM1XAoUzIHA6A+xzusEZUutdXz2Nr+MQPLxfTiCvqE79/C8HT8fKFvA==",
"license": "MIT"
},
"node_modules/fdir": {
"version": "6.4.6",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
@@ -2447,9 +2462,9 @@
"license": "MIT"
},
"node_modules/reka-ui": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.5.0.tgz",
"integrity": "sha512-81aMAmJeVCy2k0E6x7n1kypDY6aM1ldLis5+zcdV1/JtoAlSDck5OBsyLRJU9CfgbrQp1ImnRnBSmC4fZ2fkZQ==",
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.1.tgz",
"integrity": "sha512-XK7cJDQoNuGXfCNzBBo/81Yg/OgjPwvbabnlzXG2VsdSgNsT6iIkuPBPr+C0Shs+3bb0x0lbPvgQAhMSCKm5Ww==",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.6.13",

View File

@@ -15,10 +15,11 @@
"axios": "^1.11.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"event-source-polyfill": "^1.0.31",
"hls.js": "^1.6.13",
"leaflet": "^1.9.4",
"lucide-vue-next": "^0.525.0",
"reka-ui": "^2.5.0",
"reka-ui": "^2.6.1",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.11",
"tw-animate-css": "^1.3.6",
@@ -31,6 +32,7 @@
"devDependencies": {
"@iconify-json/radix-icons": "^1.2.2",
"@iconify/vue": "^5.0.0",
"@types/event-source-polyfill": "^1.0.5",
"@types/leaflet": "^1.9.20",
"@types/node": "^24.1.0",
"@vitejs/plugin-vue": "^6.0.0",

View File

@@ -9,22 +9,24 @@ export const buttonVariants = cva(
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
"bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"default": "h-9 px-4 py-2 has-[>svg]:px-3",
"sm": "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
"lg": "h-10 rounded-md px-6 has-[>svg]:px-4",
"icon": "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
@@ -33,5 +35,4 @@ export const buttonVariants = cva(
},
},
)
export type ButtonVariants = VariantProps<typeof buttonVariants>

View File

@@ -0,0 +1,26 @@
<script setup lang="ts">
import type { PaginationRootEmits, PaginationRootProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { PaginationRoot, useForwardPropsEmits } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<PaginationRootProps & {
class?: HTMLAttributes["class"]
}>()
const emits = defineEmits<PaginationRootEmits>()
const delegatedProps = reactiveOmit(props, "class")
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<PaginationRoot
v-slot="slotProps"
data-slot="pagination"
v-bind="forwarded"
:class="cn('mx-auto flex w-full justify-center', props.class)"
>
<slot v-bind="slotProps" />
</PaginationRoot>
</template>

View File

@@ -0,0 +1,22 @@
<script setup lang="ts">
import type { PaginationListProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { PaginationList } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<PaginationListProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
</script>
<template>
<PaginationList
v-slot="slotProps"
data-slot="pagination-content"
v-bind="delegatedProps"
:class="cn('flex flex-row items-center gap-1', props.class)"
>
<slot v-bind="slotProps" />
</PaginationList>
</template>

View File

@@ -0,0 +1,25 @@
<script setup lang="ts">
import type { PaginationEllipsisProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { MoreHorizontal } from "lucide-vue-next"
import { PaginationEllipsis } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<PaginationEllipsisProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
</script>
<template>
<PaginationEllipsis
data-slot="pagination-ellipsis"
v-bind="delegatedProps"
:class="cn('flex size-9 items-center justify-center', props.class)"
>
<slot>
<MoreHorizontal class="size-4" />
<span class="sr-only">More pages</span>
</slot>
</PaginationEllipsis>
</template>

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import type { PaginationFirstProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import type { ButtonVariants } from '@/components/ui/button'
import { reactiveOmit } from "@vueuse/core"
import { ChevronLeftIcon } from "lucide-vue-next"
import { PaginationFirst, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from '@/components/ui/button'
const props = withDefaults(defineProps<PaginationFirstProps & {
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
}>(), {
size: "default",
})
const delegatedProps = reactiveOmit(props, "class", "size")
const forwarded = useForwardProps(delegatedProps)
</script>
<template>
<PaginationFirst
data-slot="pagination-first"
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
v-bind="forwarded"
>
<slot>
<ChevronLeftIcon />
<span class="hidden sm:block">First</span>
</slot>
</PaginationFirst>
</template>

View File

@@ -0,0 +1,34 @@
<script setup lang="ts">
import type { PaginationListItemProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import type { ButtonVariants } from '@/components/ui/button'
import { reactiveOmit } from "@vueuse/core"
import { PaginationListItem } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from '@/components/ui/button'
const props = withDefaults(defineProps<PaginationListItemProps & {
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
isActive?: boolean
}>(), {
size: "icon",
})
const delegatedProps = reactiveOmit(props, "class", "size", "isActive")
</script>
<template>
<PaginationListItem
data-slot="pagination-item"
v-bind="delegatedProps"
:class="cn(
buttonVariants({
variant: isActive ? 'outline' : 'ghost',
size,
}),
props.class)"
>
<slot />
</PaginationListItem>
</template>

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import type { PaginationLastProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import type { ButtonVariants } from '@/components/ui/button'
import { reactiveOmit } from "@vueuse/core"
import { ChevronRightIcon } from "lucide-vue-next"
import { PaginationLast, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from '@/components/ui/button'
const props = withDefaults(defineProps<PaginationLastProps & {
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
}>(), {
size: "default",
})
const delegatedProps = reactiveOmit(props, "class", "size")
const forwarded = useForwardProps(delegatedProps)
</script>
<template>
<PaginationLast
data-slot="pagination-last"
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
v-bind="forwarded"
>
<slot>
<span class="hidden sm:block">Last</span>
<ChevronRightIcon />
</slot>
</PaginationLast>
</template>

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import type { PaginationNextProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import type { ButtonVariants } from '@/components/ui/button'
import { reactiveOmit } from "@vueuse/core"
import { ChevronRightIcon } from "lucide-vue-next"
import { PaginationNext, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from '@/components/ui/button'
const props = withDefaults(defineProps<PaginationNextProps & {
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
}>(), {
size: "default",
})
const delegatedProps = reactiveOmit(props, "class", "size")
const forwarded = useForwardProps(delegatedProps)
</script>
<template>
<PaginationNext
data-slot="pagination-next"
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
v-bind="forwarded"
>
<slot>
<span class="hidden sm:block">Next</span>
<ChevronRightIcon />
</slot>
</PaginationNext>
</template>

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import type { PaginationPrevProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import type { ButtonVariants } from '@/components/ui/button'
import { reactiveOmit } from "@vueuse/core"
import { ChevronLeftIcon } from "lucide-vue-next"
import { PaginationPrev, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from '@/components/ui/button'
const props = withDefaults(defineProps<PaginationPrevProps & {
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
}>(), {
size: "default",
})
const delegatedProps = reactiveOmit(props, "class", "size")
const forwarded = useForwardProps(delegatedProps)
</script>
<template>
<PaginationPrev
data-slot="pagination-previous"
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
v-bind="forwarded"
>
<slot>
<ChevronLeftIcon />
<span class="hidden sm:block">Previous</span>
</slot>
</PaginationPrev>
</template>

View File

@@ -0,0 +1,8 @@
export { default as Pagination } from "./Pagination.vue"
export { default as PaginationContent } from "./PaginationContent.vue"
export { default as PaginationEllipsis } from "./PaginationEllipsis.vue"
export { default as PaginationFirst } from "./PaginationFirst.vue"
export { default as PaginationItem } from "./PaginationItem.vue"
export { default as PaginationLast } from "./PaginationLast.vue"
export { default as PaginationNext } from "./PaginationNext.vue"
export { default as PaginationPrevious } from "./PaginationPrevious.vue"

View File

@@ -14,11 +14,13 @@ const props = defineProps<{ row: Users }>() // ← accept full row
const emit = defineEmits<{
(e: 'deleted', id: string): void
(e: 'error', err: unknown): void
(e: 'updated', payload: { id: string; username: string; role: 'admin' | 'user' }): void
}>()
const isEditOpen = ref(false)
const isDeleteOpen = ref(false)
const deleting = ref(false)
const updating = ref(false)
async function onDeleteConfirmed() {
try {
@@ -34,8 +36,50 @@ async function onDeleteConfirmed() {
}
}
function onEditConfirm() {
isEditOpen.value = false
async function onEditConfirm(payload: { username: string; password?: string; role: 'admin' | 'user' }) {
try {
updating.value = true
// Build UpdateUserDto payload
const body: {
username?: string
password?: string
role?: 'admin' | 'user'
} = {}
// Only include fields that really changed / are provided
if (payload.username && payload.username !== props.row.username) {
body.username = payload.username
}
if (payload.password) {
body.password = payload.password
}
if (payload.role && payload.role !== props.row.role) {
body.role = payload.role
}
// If nothing changed, skip request
if (Object.keys(body).length === 0) {
return
}
await api.put(
`/users/${encodeURIComponent(String(props.row.id))}`,
body
)
emit('updated', {
id: String(props.row.id),
username: payload.username || props.row.username,
role: payload.role || (props.row.role as 'admin' | 'user'),
})
} catch (err) {
console.error(err)
emit('error', err)
} finally {
updating.value = false
// dialog is already closed in EditUserDialog via v-model update
}
}
</script>
@@ -55,6 +99,6 @@ function onEditConfirm() {
</DropdownMenuContent>
</DropdownMenu>
<EditUserDialog v-model:modelValue="isEditOpen" @confirm="onEditConfirm" />
<EditUserDialog v-model:modelValue="isEditOpen" :user="props.row" @confirm="onEditConfirm" />
<DeleteUserDialog v-model:modelValue="isDeleteOpen" :loading="deleting" @confirm="onDeleteConfirmed" />
</template>

View File

@@ -52,6 +52,24 @@ function usernamesFromIds(ids: string[]): string {
return ids.map(id => idToName.value.get(String(id))).filter(Boolean).join(', ')
}
// ---- NEW: immediate UI updates for Users table ----
function handleUserUpdated(
row: Users,
payload: { id: string; username: string; role: 'admin' | 'user' }
) {
const idNum = Number(payload.id || row.id)
user_data.value = user_data.value.map(u =>
u.id === idNum
? { ...u, username: payload.username, role: payload.role }
: u
)
}
function handleUserDeleted(row: Users) {
const idNum = row.id
user_data.value = user_data.value.filter(u => u.id !== idNum)
}
// ---------------- Devices ----------------
type ApiDeviceUser = { id: number; username: string; role: string }
type ApiDevice = { guid: string; name: string; users?: ApiDeviceUser[] }
@@ -201,6 +219,8 @@ onBeforeUnmount(() => {
:columns="user_columns"
:data="user_data"
:dropdownComponent="AdminUserDropdonw"
@row-updated="handleUserUpdated"
@row-deleted="handleUserDeleted"
/>
</TabsContent>

View File

@@ -37,18 +37,16 @@ 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 -->
<!-- Parent must not rely on h-full; use overflow-hidden to contain scrollbars -->
<div class="w-full max-h-full border rounded-md flex flex-col overflow-hidden">
<!-- This element grows and can scroll internally -->
<ScrollArea class="flex-1 min-h-0 w-full">
<!-- min-width keeps horizontal scroll available when needed -->
<div :class="['w-full', minWidthClass]">
<Table class="w-full">
<!-- header -->
<!-- separate borders help sticky headers render above rows -->
<Table class="w-full border-separate border-spacing-0">
<TableHeader>
<TableRow
v-for="headerGroup in table.getHeaderGroups()"
:key="headerGroup.id"
>
<TableRow v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
<TableHead
v-for="header in headerGroup.headers"
:key="header.id"
@@ -60,8 +58,6 @@ const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
: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"
@@ -69,7 +65,6 @@ const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
</TableRow>
</TableHeader>
<!-- body -->
<TableBody>
<template v-if="table.getRowModel().rows.length">
<TableRow
@@ -77,18 +72,10 @@ const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
: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 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"
@@ -101,7 +88,6 @@ const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
</TableRow>
</template>
<!-- no-data row -->
<template v-else>
<TableRow>
<TableCell
@@ -116,9 +102,9 @@ const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
</Table>
</div>
<!-- Scrollbars -->
<!-- Always show both scrollbars when needed -->
<ScrollBar orientation="horizontal" />
<ScrollBar orientation="vertical" />
</ScrollArea>
</div>
</template>
</template>

View File

@@ -17,7 +17,7 @@ import type { ColumnDef } from '@tanstack/vue-table'
const props = defineProps({
modelValue: { type: Boolean as PropType<boolean>, required: true },
device: { type: Object as PropType<Device>, required: false },
device: { type: Object as PropType<Device>, required: false },
})
const emit = defineEmits<{
@@ -39,8 +39,8 @@ type DeviceCertListDto = { certs: DeviceCertDto[] }
// --- local state ---
const loading = ref(false)
const error = ref<string | null>(null)
const certs = ref<DeviceCertDto[]>([])
const error = ref<string | null>(null)
const certs = ref<DeviceCertDto[]>([])
const guid = computed(() => props.device?.guid ?? '')
@@ -55,8 +55,8 @@ const columns: ColumnDef<DeviceCertDto, any>[] = [
{ 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) },
{ accessorKey: 'notAfter', header: 'Not After', cell: ({ row }) => fmt(row.original.notAfter) },
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
]
async function loadCerts() {
@@ -91,7 +91,7 @@ function close() {
</script>
<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-[1000px]">
<DialogHeader>
<div class="flex items-center justify-between">
@@ -102,7 +102,7 @@ function close() {
</DialogDescription>
</div>
<div class="flex gap-2">
<div class="flex gap-2 pt-8">
<Button variant="outline" :disabled="loading || !guid" @click="loadCerts">
{{ loading ? 'Loading' : 'Refresh' }}
</Button>
@@ -117,11 +117,13 @@ function close() {
</div>
<div v-else>
<DataTableNoCheckboxScroll
:columns="columns"
:data="certs"
minTableWidth="min-w-[900px]"
/>
<div class="flex-1 min-h-0 pb-2">
<DataTableNoCheckboxScroll
:columns="columns"
:data="certs"
minTableWidth="min-w-[900px]" />
</div>
</div>
<DialogFooter>

View File

@@ -6,48 +6,71 @@ import { Button } from '@/components/ui/button'
import { ref, onBeforeUnmount, type PropType } from 'vue'
import type { Task } from '@/lib/interfaces'
import { api } from '@/lib/api'
import { EventSourcePolyfill } from 'event-source-polyfill'
// NOTE: hls.js default import (see type stub note above)
// hls.js for non-Safari browsers
import Hls from 'hls.js'
import { auth } from '@/lib/auth'
type PublishTokenResp = { hlsUrl: string } | { HLS: string } // accept either key casing
type PublishTokenResp = { hlsUrl: string } | { HLS: string }
const props = defineProps({
guid: { type: String as PropType<string>, required: true },
})
/** UI state */
/** UI state **/
const sending = ref(false)
const streamError = ref<string | null>(null)
const waitingLive = ref(false)
const hlsUrl = ref<string | null>(null)
const playing = ref(false)
/** Player bits */
/** 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 }
/** SSE (wait-for-live) **/
const es = ref<EventSource | null>(null)
/** Helpers **/
function closeEventSource() {
try { es.value?.close() } catch { }
es.value = null
waitingLive.value = false
}
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
}
/** Get fresh read token → HLS URL **/
async function fetchHlsUrl(): Promise<string> {
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 */
/** Attach player and play **/
async function attachAndPlay(url: string) {
streamError.value = null
hlsUrl.value = url
// Ensure previous instance is gone
teardownHls()
const el = audioEl.value
@@ -56,14 +79,12 @@ async function attachAndPlay(url: string) {
return
}
// Some UX niceties
el.controls = true
el.autoplay = true
// If hls.js is supported (all modern non-Safari browsers)
// Non-Safari: hls.js
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,
@@ -71,7 +92,6 @@ async function attachAndPlay(url: string) {
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()
@@ -90,7 +110,7 @@ async function attachAndPlay(url: string) {
}
})
} else {
// Safari (and some iOS WebKit) supports HLS natively
// Safari / iOS (native HLS)
if (el.canPlayType('application/vnd.apple.mpegurl')) {
el.src = url
try {
@@ -107,20 +127,23 @@ async function attachAndPlay(url: string) {
}
}
/** Start streaming flow:
* 1) tell the device to start_stream
* 2) fetch a fresh HLS token URL
* 3) attach & play
/** Start streaming:
* 1) tell device to start_stream
* 2) wait via SSE for “live”
* 3) on live → fetch token → play
*/
async function startStreaming() {
streamError.value = null
sending.value = true
closeEventSource()
try {
// 1) ask device to start
const dto: Task = { type: 'start_stream', payload: '' }
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
const url = await fetchHlsUrl()
await attachAndPlay(url)
// 2) strictly wait for SSE “live”
await waitForLiveThenPlay()
} catch (e: any) {
console.error('Start streaming error', e)
streamError.value = e?.response?.data?.message || e?.message || 'Failed to start streaming'
@@ -130,9 +153,64 @@ async function startStreaming() {
}
}
/** Stop streaming flow:
* 1) tell the device to stop_stream
* 2) teardown player
/** Wait for server-sent event “live” from /mediamtx/:guid/wait, then fetch token and play **/
function waitForLiveThenPlay(): Promise<void> {
waitingLive.value = true
return new Promise<void>((resolve, reject) => {
try {
const url = `/api/mediamtx/${encodeURIComponent(props.guid)}/wait`
const source = new EventSourcePolyfill(url,
{
headers: { Authorization: `Bearer ${auth.token.value}` },
// NOTE: in browsers there's no way to bypass TLS validation here.
}
)
es.value = source
const cleanup = () => {
source.removeEventListener('live', onLive)
source.removeEventListener('timeout', onTimeout)
source.onerror = null
try { source.close() } catch { }
es.value = null
waitingLive.value = false
}
const onLive = async () => {
try {
cleanup()
const tokenUrl = await fetchHlsUrl()
await attachAndPlay(tokenUrl)
resolve()
} catch (err) {
reject(err)
}
}
const onTimeout = () => {
cleanup()
streamError.value = 'Stream did not become live in time. Try again.'
reject(new Error('SSE wait timeout'))
}
source.addEventListener('live', onLive)
source.addEventListener('timeout', onTimeout)
source.onerror = () => {
cleanup()
streamError.value = 'Live-wait connection ended. Try again.'
reject(new Error('SSE error'))
}
} catch (err) {
waitingLive.value = false
reject(err)
}
})
}
/** Stop streaming:
* 1) tell device to stop_stream
* 2) teardown player & close SSE
*/
async function stopStreaming() {
streamError.value = null
@@ -142,35 +220,18 @@ async function stopStreaming() {
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
closeEventSource()
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)
// Cleanup
onBeforeUnmount(() => {
closeEventSource()
teardownHls()
})
</script>
<template>
@@ -191,9 +252,10 @@ onBeforeUnmount(teardownHls)
<TabsContent value="livestream">
<div class="flex flex-col gap-4 pt-2">
<div class="flex gap-3">
<Button :disabled="sending" @click="startStreaming">
{{ sending ? 'Starting' : 'Start streaming' }}
<div class="flex gap-3 items-center">
<Button :disabled="sending || waitingLive" @click="startStreaming">
<span v-if="waitingLive">Waiting live</span>
<span v-else>{{ sending ? 'Starting' : 'Start streaming' }}</span>
</Button>
<Button :disabled="sending" @click="stopStreaming">
{{ sending ? 'Stopping' : 'Stop streaming' }}
@@ -204,21 +266,18 @@ onBeforeUnmount(teardownHls)
{{ streamError }}
</div>
<!-- The player -->
<!-- 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">
<audio ref="audioEl" class="w-full mt-2" preload="none" controls />
<p v-if="!hlsUrl && !playing && !waitingLive" class="text-sm text-muted-foreground mt-2">
Press Start streaming to begin live audio.
</p>
<p v-if="waitingLive" class="text-sm text-muted-foreground mt-2">
Waiting for the device to go live
</p>
</div>
</div>
</TabsContent>

View File

@@ -59,7 +59,7 @@ function fmt(ts?: string | null) {
const task_columns: ColumnDef<TaskDto, any>[] = [
{ accessorKey: 'id', header: 'ID' },
// { accessorKey: 'deviceGuid', header: 'GUID' },
// { accessorKey: 'deviceGuid', header: 'GUID' },
{ accessorKey: 'type', header: 'Task' },
{
accessorKey: 'payload',
@@ -77,9 +77,9 @@ const task_columns: ColumnDef<TaskDto, any>[] = [
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'
: 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)
},
},
@@ -101,16 +101,21 @@ const task_columns: ColumnDef<TaskDto, any>[] = [
<template>
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
<DialogContent class="sm:min-w-[1000px]">
<DialogHeader class="flex flex-row items-center justify-between gap-4">
<div>
<DialogTitle>Tasks</DialogTitle>
<DialogDescription>{{ props.device?.guid }}</DialogDescription>
</div>
<div class="flex gap-2">
<Button variant="outline" :disabled="loading || !props.device?.guid" @click="fetchTasks">
{{ loading ? 'Loading' : 'Refresh' }}
</Button>
<DialogHeader>
<div class="flex items-center justify-between">
<div>
<DialogTitle>Tasks</DialogTitle>
<DialogDescription class="mt-1 break-all">
{{ props.device?.guid }}
</DialogDescription>
</div>
<div class="flex gap-2 pt-8">
<Button variant="outline" :disabled="loading || !props.device?.guid" @click="fetchTasks">
{{ loading ? 'Loading' : 'Refresh' }}
</Button>
</div>
</div>
</DialogHeader>
<div v-if="error" class="text-sm text-red-600 mb-3">{{ error }}</div>
@@ -119,7 +124,13 @@ const task_columns: ColumnDef<TaskDto, any>[] = [
Loading tasks
</div>
<div v-else>
<DataTableNoCheckboxScroll :columns="task_columns" :data="tasks" minTableWidth="min-w-[800px]"/>
<!-- SCROLLABLE MIDDLE: flex-1 + min-h-0 so child can overflow -->
<div class="flex-1 min-h-0 pb-2">
<DataTableNoCheckboxScroll
:columns="task_columns"
:data="tasks"
minTableWidth="min-w-[900px]" />
</div>
</div>
<DialogFooter>

View File

@@ -11,8 +11,9 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { defineProps, defineEmits } from 'vue'
import { defineProps, defineEmits, reactive, watch } from 'vue'
import type { PropType } from 'vue'
import type { Users } from '@/lib/interfaces'
// 1) runtime props so Vue + TS agree
const props = defineProps({
@@ -20,26 +21,58 @@ const props = defineProps({
type: Boolean as PropType<boolean>,
required: true,
},
user: {
type: Object as PropType<Users>,
required: true,
},
})
// 2) two emits: v-model and confirm
const emit = defineEmits<{
(
e: 'confirm',
payload: { username: string; password?: string; role: 'admin' | 'user' }
): void
(e: 'update:modelValue', v: boolean): void
(e: 'confirm'): void
}>()
const form = reactive({
username: '',
password: '',
isAdmin: false,
})
// when dialog opens or user changes sync form with props.user
watch(
() => [props.modelValue, props.user],
() => {
if (props.modelValue && props.user) {
form.username = props.user.username
form.password = ''
form.isAdmin = props.user.role === 'admin'
}
},
{ immediate: true }
)
function onSave() {
emit('confirm')
// close the dialog
const payload: { username: string; password?: string; role: 'admin' | 'user' } = {
username: form.username,
role: form.isAdmin ? 'admin' : 'user',
}
// only send password if user entered something
if (form.password.trim() !== '') {
payload.password = form.password.trim()
}
emit('confirm', payload)
emit('update:modelValue', false)
}
</script>
<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:max-w-[425px]">
<DialogHeader>
<DialogTitle>Edit profile</DialogTitle>
@@ -51,15 +84,15 @@ function onSave() {
<div class="grid gap-4 py-4">
<div class="grid grid-cols-4 items-center gap-4">
<Label for="username" class="text-right">Username</Label>
<Input id="username" class="col-span-3" />
<Input id="username" class="col-span-3" v-model="form.username"/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="password" class="text-right">Password</Label>
<Input id="password" class="col-span-3" type="password" />
<Input id="password" class="col-span-3" type="password" v-model="form.password"/>
</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>
<Switch id="isAdmin"/>
<Switch id="isAdmin" :default-value="form.isAdmin" v-model:checked="form.isAdmin"/>
</div>
</div>

View File

@@ -3,10 +3,13 @@ import {
DropdownMenu, DropdownMenuContent,
DropdownMenuTrigger, DropdownMenuSeparator,
DropdownMenuItem, DropdownMenuLabel
} from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { Settings } from 'lucide-vue-next'
import { RouterLink, useRoute } from 'vue-router'
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
import { Settings } from 'lucide-vue-next';
import { RouterLink, useRoute } from 'vue-router';
import { api } from '@/lib/api';
import { onMounted, ref } from 'vue';
import type { Users } from '@/lib/interfaces';
const { customComponent } = defineProps<{ customComponent?: any }>()
@@ -24,6 +27,17 @@ function navLinkClass(prefix: string) {
isActive(prefix) ? 'text-primary' : 'text-muted-foreground hover:text-primary'
)
}
const username = ref<string | null>(null)
onMounted(async () => {
try {
const { data } = await api.get<Users>('/users/profile')
username.value = data?.username ?? null
} catch {
// 401s are already handled by interceptor; keep silent on others
}
})
</script>
<template>
@@ -60,7 +74,7 @@ function navLinkClass(prefix: string) {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent class="w-48">
<DropdownMenuLabel>Admin</DropdownMenuLabel>
<DropdownMenuLabel>{{ username }}</DropdownMenuLabel>
<DropdownMenuSeparator />
<RouterLink to="/settings">
<DropdownMenuItem>Settings</DropdownMenuItem>

View File

@@ -3,33 +3,149 @@ import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/componen
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Sun, Moon } from 'lucide-vue-next'
import { useColorMode } from '@vueuse/core';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import type { Users } from '@/lib/interfaces';
import { api } from '@/lib/api';
import { X } from 'lucide-vue-next';
const mode = useColorMode()
const modeLabel = computed(() => {
if (mode.value === 'auto') return 'System'
return mode.value === 'dark' ? 'Dark' : 'Light'
})
type ChangePasswordDto = {
userId?: number
oldPassword: string
newPassword: string
}
const router = useRouter()
// ---- State ----
const user = ref<Users | null>(null)
const loadingProfile = ref(false)
const oldPassword = ref('')
const newPassword = ref('')
const submitting = ref(false)
const errorMsg = ref<string | null>(null)
const successMsg = ref<string | null>(null)
onMounted(async () => {
loadingProfile.value = true
try {
const { data } = await api.get<Users>('/users/profile')
user.value = data
} catch (err: any) {
// 401 is handled by interceptor; still surface generic error if needed
errorMsg.value = err?.response?.data?.error || 'Failed to load profile.'
} finally {
loadingProfile.value = false
}
})
async function submitChangePassword() {
errorMsg.value = null
successMsg.value = null
if (!user.value) {
errorMsg.value = 'User profile not loaded.'
return
}
if (!newPassword.value) {
errorMsg.value = 'New password is required.'
return
}
const payload: ChangePasswordDto = {
userId: user.value.id, // optional in DTO, but we provide it
oldPassword: oldPassword.value,
newPassword: newPassword.value,
}
submitting.value = true
try {
await api.post('/auth/change_password', payload)
successMsg.value = 'Password changed successfully.'
// Clear inputs
oldPassword.value = ''
newPassword.value = ''
} catch (err: any) {
errorMsg.value =
err?.response?.data?.error ||
err?.response?.data?.message ||
'Failed to change password.'
} finally {
submitting.value = false
}
}
function goBack() {
router.back()
}
</script>
<template>
<div class="w-full h-full flex items-center justify-center px-4">
<Card class="flex w-[600px]">
<CardHeader>
<CardTitle>
Settings
</CardTitle>
<div class="flex items-center justify-between">
<CardTitle>
Settings
</CardTitle>
<Button variant="ghost" class="w-auto px-4" @click="goBack">
<X/>
</Button>
</div>
</CardHeader>
<CardContent>
<div class="grid gap-4 py-4">
<form class="grid gap-4 py-4" @submit.prevent="submitChangePassword">
<div class="grid grid-cols-4 items-center gap-4">
<Label for="username" class="text-right">Username</Label>
<Input id="username" class="col-span-3" />
<Input id="username" class="col-span-3"
:value="user?.username || (loadingProfile ? 'Loading…' : '')" disabled readonly />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="current_password" class="text-right">Current password</Label>
<Input id="current_password" class="col-span-3" type="password" />
<Input id="current_password" class="col-span-3" type="password" v-model="oldPassword"
autocomplete="current-password" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="new_password" class="text-right">New password</Label>
<Input id="new_password" class="col-span-3" type="password" />
<Input id="new_password" class="col-span-3" type="password" v-model="newPassword"
autocomplete="new-password" required />
</div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">Theme</Label>
<div class="col-span-3 flex items-center gap-3">
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button variant="outline" class="relative w-32 justify-start">
<Moon
class="h-[1.1rem] w-[1.1rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Sun
class="absolute h-[1.1rem] w-[1.1rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span class="ml-6 truncate">{{ modeLabel }}</span>
<span class="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem @click="mode = 'light'">Light</DropdownMenuItem>
<DropdownMenuItem @click="mode = 'dark'">Dark</DropdownMenuItem>
<DropdownMenuItem @click="mode = 'auto'">System</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div v-if="errorMsg" class="text-sm text-destructive">{{ errorMsg }}</div>
<div v-if="successMsg" class="text-sm text-green-600">{{ successMsg }}</div>
</form>
</CardContent>
<CardFooter>
<Button type="submit">Save changes</Button>
<Button type="submit" :disabled="submitting">
{{ submitting ? 'Saving…' : 'Save changes' }}
</Button>
</CardFooter>
</Card>
</div>

View File

@@ -1,4 +1,4 @@
import { createRouter, createWebHistory } from 'vue-router';
import { createRouter, createWebHistory, type NavigationGuard, type RouteLocationNormalized, type RouteRecordRaw } from 'vue-router';
import Admin from '@/pages/Admin.vue';
import Login from '@/pages/Login.vue';
@@ -19,7 +19,7 @@ declare module 'vue-router' {
}
}
const routes = [
const routes: RouteRecordRaw[] = [
{
path: '/login',
name: 'Login',
@@ -80,6 +80,17 @@ const routes = [
props: true, // so `guid` shows up as a prop
meta: { requiresAuth: true }
},
{
path: '/logout',
name: 'Logout',
meta: { requiresAuth: false },
redirect: { name: 'Login' },
beforeEnter(_to:RouteLocationNormalized, _from:RouteLocationNormalized, next) {
auth.clear()
next()
},
},
]
const router = createRouter({

View File

@@ -7,7 +7,7 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*","src/types/**/*"]
"@/*": ["./src/*","src/types/*"]
}
}
}

19
mediamtx/Dockerfile Normal file
View File

@@ -0,0 +1,19 @@
# ---- Stage 1: Build rclone ----
FROM alpine:3.20 AS rclone-builder
RUN apk add --no-cache curl unzip && \
curl -fsSL https://downloads.rclone.org/rclone-current-linux-amd64.zip -o /tmp/rclone.zip && \
unzip /tmp/rclone.zip -d /tmp && \
mv /tmp/rclone-*/rclone /usr/local/bin/rclone && \
chmod +x /usr/local/bin/rclone
# ---- Stage 2: Final image ----
FROM bluenviron/mediamtx:latest
# Copy only the rclone binary from the builder
COPY --from=rclone-builder /usr/local/bin/rclone /usr/local/bin/rclone
# Optional: verify installation (uncomment if debugging)
RUN ["/usr/local/bin/rclone", "version"]
ENTRYPOINT ["/mediamtx"]

View File

@@ -1,4 +1,6 @@
logLevel: info
# logLevel: info
logLevel: debug
# Enable Control API (useful for debugging; bound to localhost by default)
api: yes
@@ -16,7 +18,12 @@ hlsVariant: lowLatency
# WebRTC (browser-friendly)
webrtc: yes
webrtcAddress: :8889
# whip: yes
webrtcLocalUDPAddress: :8189
webrtcIPsFromInterfaces: yes
webrtcIPsFromInterfacesList: []
webrtcAdditionalHosts:
- 192.168.205.130
# Optional: add a STUN server if behind NAT
# webrtcICEServers2:
# - url: stun:stun.l.google.com:19302
@@ -52,14 +59,16 @@ pathDefaults:
# \"dstFs\":\"minio:livestream\",
# \"dstRemote\":\"$MTX_PATH/$f\"}"'
runOnRecordSegmentCreate: >
sh -c 'd="$(dirname "$MTX_SEGMENT_PATH")";
f="$(basename "$MTX_SEGMENT_PATH")";
curl -s -H "Content-Type: application/json"
-X POST "http://rclone:5572/operations/copyfile?_async=true"
-d "{\"srcFs\":\"$d\",\"srcRemote\":\"$f\",
\"dstFs\":\"minio:livestream\",
\"dstRemote\":\"$MTX_PATH/$f\"}"'
# runOnRecordSegmentCreate: >
# sh -c 'd="$(dirname "$MTX_SEGMENT_PATH")";
# f="$(basename "$MTX_SEGMENT_PATH")";
# curl -s -H "Content-Type: application/json"
# -X POST "http://rclone:5572/operations/copyfile?_async=true"
# -d "{\"srcFs\":\"$d\",\"srcRemote\":\"$f\",
# \"dstFs\":\"minio:livestream\",
# \"dstRemote\":\"$MTX_PATH/$f\"}"'
runOnRecordSegmentCreate: rclone copy "$MTX_SEGMENT_PATH" "minio:livestream/${MTX_SEGMENT_PATH#/recordings/whip/live/}" --progress
authInternalUsers:
- user: any

View File

@@ -74,7 +74,8 @@ server {
# HTTPS :443 — mTLS enforced only on listed paths
# ==============================================
server {
listen 443 ssl http2;
listen 443 ssl;
http2 on;
server_name _;
access_log /var/log/nginx/access.log mtls_debug;
@@ -144,10 +145,9 @@ server {
# MediaMTX HLS
location ^~ /hls/ {
# if ($ssl_client_verify != SUCCESS) {
# return 495;
# }
proxy_pass http://mediamtx:8888/;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
# MediaMTX WebRTC (WHIP/WHEP/test)

View File

@@ -1,5 +1,21 @@
# Vault setup
For proper connection from Docker/Podman containers, use this vault configuration and bind Vault interface to 0.0.0.0.
```hcl
storage "file" {
path = "/opt/vault/data"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_disable = 1
}
disable_mlock = true
ui = true
```
```bash
export VAULT_ADDR=http://localhost:8200
export VAULT_TOKEN=root
@@ -20,10 +36,10 @@ vault kv put kv/snoop \
minio_presign_ttl_seconds="900"
```
Unseal Key 1: XdERN+/hxR9RjLC/S8c+y0omToYvB7Qs1jaUenZQvphD
Unseal Key 2: VBhPBtYcq1GAk7ByPfAsamxV4tJOZ49chAYxxOvc49Oj
Unseal Key 1: AMLVUGoP2hlEd02nWWghAiVYT4jtiXv50WsZyQ2MbpP/
Unseal Key 2: OtaDsNoGE2EF6UfrQUkU0NoDVxPK/KwBFg9cUfQuhBs+
Initial Root Token: hvs.tZ4eh9P18sCZ5c1PZIz59EmH
Initial Root Token: hvs.rKzgIc5aaucOCtlJNsUdZuEH
{

View File

@@ -23,5 +23,7 @@ func AutoMigrate(db *gorm.DB) error {
&models.DeviceCertificate{},
&models.RevokedSerial{},
&models.DeviceConfig{},
&models.MQTTMsg{},
&models.EmqxClientEvent{},
)
}

View File

@@ -19,7 +19,9 @@ type DeviceCertDto struct {
}
type DeviceCertListDto struct {
Certs []DeviceCertDto `json:"certs"`
Certs []DeviceCertDto `json:"certs"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
func MapDeviceCert(c models.DeviceCertificate) DeviceCertDto {

View File

@@ -20,6 +20,12 @@ type CreateUserDto struct {
Role string `json:"role" binding:"required,oneof=admin user"`
}
type UpdateUserDto struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Role string `json:"role,omitempty"`
}
func MapUser(u models.User) UserDto {
return UserDto{
ID: u.ID,

View File

@@ -0,0 +1,48 @@
package handlers
import (
"sync"
)
type Broker struct {
mu sync.Mutex
subs map[string]map[chan struct{}]struct{} // key = path, val = set of channels
}
func NewBroker() *Broker {
return &Broker{subs: make(map[string]map[chan struct{}]struct{})}
}
func (b *Broker) Subscribe(path string) chan struct{} {
ch := make(chan struct{}, 1)
b.mu.Lock()
defer b.mu.Unlock()
if b.subs[path] == nil {
b.subs[path] = make(map[chan struct{}]struct{})
}
b.subs[path][ch] = struct{}{}
return ch
}
func (b *Broker) Unsubscribe(path string, ch chan struct{}) {
b.mu.Lock()
defer b.mu.Unlock()
if set, ok := b.subs[path]; ok {
delete(set, ch)
if len(set) == 0 {
delete(b.subs, path)
}
}
close(ch)
}
func (b *Broker) Publish(path string) {
b.mu.Lock()
defer b.mu.Unlock()
for ch := range b.subs[path] {
select {
case ch <- struct{}{}:
default:
}
}
}

View File

@@ -2,6 +2,7 @@ package handlers
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
@@ -22,10 +23,11 @@ type MediaMTXHandler struct {
jwtMgr *crypto.JWTManager
db *gorm.DB
cfg config.MediaMTXConfig
bus *Broker
}
func NewMediaMTXHandler(db *gorm.DB, jwt *crypto.JWTManager, c config.MediaMTXConfig) *MediaMTXHandler {
return &MediaMTXHandler{db: db, jwtMgr: jwt, cfg: c}
return &MediaMTXHandler{db: db, jwtMgr: jwt, cfg: c, bus: NewBroker()}
}
// --- 3.1 External auth endpoint called by MediaMTX
@@ -86,7 +88,18 @@ func (h *MediaMTXHandler) Auth(c *gin.Context) {
return
}
}
// allowed
if req.Action == "publish" {
if guid, ok := guidFromPath(req.Path); ok {
_ = guid // not used here, but available
// tell listeners this path is live (or at least authorized to start)
if h.bus != nil {
h.bus.Publish(req.Path)
}
}
}
c.Status(http.StatusOK)
}
@@ -340,3 +353,152 @@ func BodyLogger() gin.HandlerFunc {
c.Next()
}
}
// --- poll MediaMTX API until path is live ------------------------------------
func (h *MediaMTXHandler) WaitUntilLive(path string, timeout time.Duration) bool {
api := strings.TrimRight(h.cfg.APIBase, "/")
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
resp, err := http.Get(api + "/v3/paths/list")
if err == nil && resp.StatusCode == 200 {
var pl pathsListRes
_ = json.NewDecoder(resp.Body).Decode(&pl)
resp.Body.Close()
for _, it := range pl.Items {
if it.Name == path {
return true
}
}
} else if resp != nil {
resp.Body.Close()
}
time.Sleep(500 * time.Millisecond)
}
return false
}
func (h *MediaMTXHandler) expectedStartWait(guid string) time.Duration {
var cfg models.DeviceConfig
if err := h.db.Where("device_guid = ?", guid).First(&cfg).Error; err != nil {
return 60 * time.Second // fallback if no config row
}
poll := cfg.MPolling
jit := cfg.MJitter
if poll <= 0 {
poll = 60
}
if jit < 0 {
jit = 10
}
safety := 5 // seconds
return time.Duration(poll+jit+safety) * time.Second
}
// GET /streams/:guid/wait
func (h *MediaMTXHandler) WaitLiveSSE(c *gin.Context) {
guid := c.Param("guid")
if guid == "" {
c.Status(http.StatusBadRequest)
return
}
path := "live/" + guid
// Per-device max wait = MPolling + MJitter + safety
timeout := h.expectedStartWait(guid)
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
flush := func() {
if f, ok := c.Writer.(http.Flusher); ok {
f.Flush()
}
}
// If already live, notify immediately and exit.
if h.IsLive(path) {
fmt.Fprintf(c.Writer, "event: live\ndata: %s\n\n", path)
flush()
return
}
// Subscribe to bus for publish-auth events on this path
ch := h.bus.Subscribe(path)
defer h.bus.Unsubscribe(path, ch)
// Background short poller (safety net in case bus event is missed)
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
defer cancel()
pollDone := make(chan struct{})
go func() {
t := time.NewTicker(500 * time.Millisecond)
defer t.Stop()
defer close(pollDone)
for {
select {
case <-ctx.Done():
return
case <-t.C:
if h.IsLive(path) {
// Normalize through bus so waiter below handles it uniformly
h.bus.Publish(path)
return
}
}
}
}()
// Wait for either: bus event, timeout, or client disconnect.
select {
case <-ch:
fmt.Fprintf(c.Writer, "event: live\ndata: %s\n\n", path)
flush()
return
case <-ctx.Done():
// Optional: tell client we timed out so it can keep a gentle retry loop
fmt.Fprintf(c.Writer, "event: timeout\ndata: {\"path\":\"%s\"}\n\n", path)
flush()
return
case <-c.Request.Context().Done():
return
}
}
// --- helpers: path/guid ------------------------------------------------------
func guidFromPath(path string) (string, bool) {
parts := strings.SplitN(path, "/", 2)
if len(parts) != 2 || parts[0] != "live" || parts[1] == "" {
return "", false
}
return parts[1], true
}
// IsLive performs a single check against MTX API to see if the path exists now.
func (h *MediaMTXHandler) IsLive(path string) bool {
api := strings.TrimRight(h.cfg.APIBase, "/")
resp, err := http.Get(api + "/v3/paths/list")
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false
}
var pl pathsListRes
if err := json.NewDecoder(resp.Body).Decode(&pl); err != nil {
return false
}
for _, it := range pl.Items {
if it.Name == path {
return true
}
}
return false
}

View File

@@ -121,3 +121,98 @@ func (h *UsersHandler) Delete(c *gin.Context) {
}
c.Status(http.StatusNoContent)
}
// GET /users/:id — fetch any user's profile by id
func (h *UsersHandler) GetProfile(c *gin.Context) {
idStr := c.Param("id")
id, _ := strconv.Atoi(idStr)
if id <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
var u models.User
if err := h.db.First(&u, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
c.JSON(http.StatusOK, dto.MapUser(u))
}
// PUT /users/:id (admin) — update username, password and/or role
func (h *UsersHandler) Update(c *gin.Context) {
idStr := c.Param("id")
id, _ := strconv.Atoi(idStr)
if id <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
var u models.User
if err := h.db.First(&u, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
var req dto.UpdateUserDto
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
updated := false
// --- Update username ---
if strings.TrimSpace(req.Username) != "" {
name := strings.TrimSpace(req.Username)
if name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "username cannot be empty"})
return
}
u.Username = name
updated = true
}
// --- Update password ---
if req.Password != "" {
if len(req.Password) < 4 {
c.JSON(http.StatusBadRequest, gin.H{"error": "password too short"})
return
}
hash, err := crypto.Hash(req.Password, crypto.DefaultArgon2)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "hash error"})
return
}
u.Password = hash
updated = true
}
// --- Update role ---
if strings.TrimSpace(req.Role) != "" {
role := strings.ToLower(strings.TrimSpace(req.Role))
if role != "admin" && role != "user" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
return
}
u.Role = models.Role(role)
updated = true
}
if !updated {
c.JSON(http.StatusBadRequest, gin.H{"error": "nothing to update"})
return
}
if err := h.db.Save(&u).Error; err != nil {
// detect duplicate username
e := strings.ToLower(err.Error())
if strings.Contains(e, "duplicate") || strings.Contains(e, "unique") || strings.Contains(e, "exists") {
c.JSON(http.StatusBadRequest, gin.H{"error": "username already exists"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "update failed"})
return
}
c.JSON(http.StatusOK, dto.MapUser(u))
}

View File

@@ -1,10 +1,13 @@
package middleware
import (
"net/http"
"smoop-api/internal/handlers"
"smoop-api/internal/models"
"strconv"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
// DeviceAccessFilter middleware sets filtering context for device access
@@ -64,3 +67,48 @@ func TrackerAccessFilter() gin.HandlerFunc {
c.Next()
}
}
// UserSelfOrAdmin allows access to /users/:id for admins or the user itself.
// Works whether context has only "claims" (router.Auth) or both "user" and "claims" (handlers.Auth).
func UserSelfOrAdmin() gin.HandlerFunc {
return func(c *gin.Context) {
idStr := c.Param("id")
targetID, _ := strconv.Atoi(idStr)
if targetID <= 0 {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
// 1) Prefer JWT claims (compatible with router.Auth)
if v, ok := c.Get("claims"); ok {
if m, ok := v.(jwt.MapClaims); ok {
role, _ := m["role"].(string)
uid := 0
switch t := m["sub"].(type) {
case float64:
uid = int(t)
case int:
uid = t
case int64:
uid = int(t)
}
if role == "admin" || uid == targetID {
c.Next()
return
}
}
}
// 2) Fallback to user context (compatible with handlers.Auth)
if v, ok := c.Get("user"); ok {
if u, ok := v.(handlers.UserContext); ok {
if u.Role == models.RoleAdmin || int(u.ID) == targetID {
c.Next()
return
}
}
}
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
}
}

View File

@@ -0,0 +1,31 @@
package models
import "time"
// MQTTMsg maps to table t_mqtt_msg in emqx_data
type MQTTMsg struct {
ID uint `gorm:"primaryKey;column:id"`
MsgID string `gorm:"column:msgid;type:varchar(64)"`
Sender string `gorm:"column:sender;type:varchar(64)"`
Topic string `gorm:"column:topic;type:varchar(255)"`
QoS int `gorm:"column:qos"`
Retain int `gorm:"column:retain"`
Payload string `gorm:"column:payload;type:text"`
Arrived time.Time `gorm:"column:arrived"`
}
func (MQTTMsg) TableName() string {
return "t_mqtt_msg"
}
// EmqxClientEvent maps to table emqx_client_events in emqx_data
type EmqxClientEvent struct {
ID uint `gorm:"primaryKey;column:id"`
ClientID string `gorm:"column:clientid;type:varchar(255)"`
Event string `gorm:"column:event;type:varchar(255)"`
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime"`
}
func (EmqxClientEvent) TableName() string {
return "emqx_client_events"
}

View File

@@ -50,10 +50,11 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
r.POST("/auth/change_password", authMW, authH.ChangePassword)
r.GET("/users/profile", authMW, usersH.Profile)
r.POST("/users/:id/set_role", authMW, adminOnly, usersH.SetRole)
r.PUT("/users/:id", authMW, adminOnly, usersH.Update)
r.GET("/users", authMW, adminOnly, usersH.List)
r.POST("/users/create", authMW, adminOnly, usersH.Create)
r.DELETE("/users/:id", authMW, adminOnly, usersH.Delete)
r.GET("/users/:id", authMW, middleware.UserSelfOrAdmin(), usersH.GetProfile)
r.GET("/devices", authMW, middleware.DeviceAccessFilter(), devH.List)
r.POST("/devices/create", authMW, adminOnly, devH.Create)
@@ -88,6 +89,8 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
// Admin controls
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)
// SSE endpoint for audio stream UI
r.GET("/mediamtx/:guid/wait", authMW, middleware.DeviceAccessFilter(), mediamtxH.WaitLiveSSE)
r.GET("/trackers", authMW, middleware.TrackerAccessFilter(), trackersH.List)
r.POST("/trackers/create", authMW, trackersH.Create)