Compare commits
17 Commits
dev_mtls
...
d0da7962e2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0da7962e2 | ||
|
|
1284c1c4c1 | ||
|
|
50850897c0 | ||
|
|
f8f099cccc | ||
|
|
50acf14fe1 | ||
|
|
2ba75d0e87 | ||
|
|
d0cece3001 | ||
|
|
e92194f739 | ||
|
|
ad0fe7b09a | ||
|
|
6d2719faeb | ||
|
|
89c44d2979 | ||
|
|
f59883315d | ||
|
|
af7c659bef | ||
|
|
40b7e590a3 | ||
|
|
bdb89f0966 | ||
|
|
2895c6afdd | ||
|
|
ee210e847e |
72
certs/vault_install.sh
Normal file
72
certs/vault_install.sh
Normal 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."
|
||||||
@@ -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.rKzgIc5aaucOCtlJNsUdZuEH"
|
||||||
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:
|
||||||
@@ -91,9 +91,10 @@ services:
|
|||||||
- proxy
|
- proxy
|
||||||
|
|
||||||
mediamtx:
|
mediamtx:
|
||||||
image: bluenviron/mediamtx:latest
|
build:
|
||||||
# restart: unless-stopped
|
context: ./mediamtx
|
||||||
# Expose default listeners for all common protocols
|
dockerfile: Dockerfile
|
||||||
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "8554:8554" # RTSP
|
- "8554:8554" # RTSP
|
||||||
- "1935:1935" # RTMP
|
- "1935:1935" # RTMP
|
||||||
@@ -105,13 +106,6 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./mediamtx/mediamtx.yml:/mediamtx.yml:ro,Z
|
- ./mediamtx/mediamtx.yml:/mediamtx.yml:ro,Z
|
||||||
- mediamtx-recordings:/recordings
|
- mediamtx-recordings:/recordings
|
||||||
networks:
|
|
||||||
- proxy
|
|
||||||
- snoopBack
|
|
||||||
|
|
||||||
rclone:
|
|
||||||
image: rclone/rclone:latest
|
|
||||||
command: rcd --rc-addr=:5572 --rc-no-auth
|
|
||||||
environment:
|
environment:
|
||||||
RCLONE_CONFIG_MINIO_TYPE: s3
|
RCLONE_CONFIG_MINIO_TYPE: s3
|
||||||
RCLONE_CONFIG_MINIO_PROVIDER: Minio
|
RCLONE_CONFIG_MINIO_PROVIDER: Minio
|
||||||
@@ -120,11 +114,10 @@ services:
|
|||||||
RCLONE_CONFIG_MINIO_SECRET_ACCESS_KEY: minioadmin
|
RCLONE_CONFIG_MINIO_SECRET_ACCESS_KEY: minioadmin
|
||||||
RCLONE_CONFIG_MINIO_REGION: us-east-1
|
RCLONE_CONFIG_MINIO_REGION: us-east-1
|
||||||
RCLONE_CONFIG_MINIO_FORCE_PATH_STYLE: "true"
|
RCLONE_CONFIG_MINIO_FORCE_PATH_STYLE: "true"
|
||||||
volumes:
|
|
||||||
- mediamtx-recordings:/recordings
|
|
||||||
networks:
|
networks:
|
||||||
- snoopBack
|
|
||||||
- proxy
|
- proxy
|
||||||
|
- snoopBack
|
||||||
|
|
||||||
|
|
||||||
# NEW: EMQX MQTT broker
|
# NEW: EMQX MQTT broker
|
||||||
emqx:
|
emqx:
|
||||||
|
|||||||
30
management-ui/package-lock.json
generated
30
management-ui/package-lock.json
generated
@@ -14,9 +14,11 @@
|
|||||||
"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",
|
||||||
|
"event-source-polyfill": "^1.0.31",
|
||||||
|
"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.6.1",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss": "^4.1.11",
|
"tailwindcss": "^4.1.11",
|
||||||
"tw-animate-css": "^1.3.6",
|
"tw-animate-css": "^1.3.6",
|
||||||
@@ -29,6 +31,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify-json/radix-icons": "^1.2.2",
|
"@iconify-json/radix-icons": "^1.2.2",
|
||||||
"@iconify/vue": "^5.0.0",
|
"@iconify/vue": "^5.0.0",
|
||||||
|
"@types/event-source-polyfill": "^1.0.5",
|
||||||
"@types/leaflet": "^1.9.20",
|
"@types/leaflet": "^1.9.20",
|
||||||
"@types/node": "^24.1.0",
|
"@types/node": "^24.1.0",
|
||||||
"@vitejs/plugin-vue": "^6.0.0",
|
"@vitejs/plugin-vue": "^6.0.0",
|
||||||
@@ -1275,6 +1278,13 @@
|
|||||||
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
|
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/@types/geojson": {
|
||||||
"version": "7946.0.16",
|
"version": "7946.0.16",
|
||||||
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
|
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
|
||||||
@@ -1829,6 +1839,12 @@
|
|||||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/fdir": {
|
||||||
"version": "6.4.6",
|
"version": "6.4.6",
|
||||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||||
@@ -2006,6 +2022,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",
|
||||||
@@ -2440,9 +2462,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/reka-ui": {
|
"node_modules/reka-ui": {
|
||||||
"version": "2.5.0",
|
"version": "2.6.1",
|
||||||
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.1.tgz",
|
||||||
"integrity": "sha512-81aMAmJeVCy2k0E6x7n1kypDY6aM1ldLis5+zcdV1/JtoAlSDck5OBsyLRJU9CfgbrQp1ImnRnBSmC4fZ2fkZQ==",
|
"integrity": "sha512-XK7cJDQoNuGXfCNzBBo/81Yg/OgjPwvbabnlzXG2VsdSgNsT6iIkuPBPr+C0Shs+3bb0x0lbPvgQAhMSCKm5Ww==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@floating-ui/dom": "^1.6.13",
|
"@floating-ui/dom": "^1.6.13",
|
||||||
|
|||||||
@@ -15,9 +15,11 @@
|
|||||||
"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",
|
||||||
|
"event-source-polyfill": "^1.0.31",
|
||||||
|
"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.6.1",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss": "^4.1.11",
|
"tailwindcss": "^4.1.11",
|
||||||
"tw-animate-css": "^1.3.6",
|
"tw-animate-css": "^1.3.6",
|
||||||
@@ -30,6 +32,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify-json/radix-icons": "^1.2.2",
|
"@iconify-json/radix-icons": "^1.2.2",
|
||||||
"@iconify/vue": "^5.0.0",
|
"@iconify/vue": "^5.0.0",
|
||||||
|
"@types/event-source-polyfill": "^1.0.5",
|
||||||
"@types/leaflet": "^1.9.20",
|
"@types/leaflet": "^1.9.20",
|
||||||
"@types/node": "^24.1.0",
|
"@types/node": "^24.1.0",
|
||||||
"@vitejs/plugin-vue": "^6.0.0",
|
"@vitejs/plugin-vue": "^6.0.0",
|
||||||
|
|||||||
@@ -9,22 +9,24 @@ export const buttonVariants = cva(
|
|||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default:
|
default:
|
||||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
"bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
destructive:
|
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:
|
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",
|
"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:
|
secondary:
|
||||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
ghost:
|
ghost:
|
||||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
"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",
|
"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",
|
"lg": "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
icon: "size-9",
|
"icon": "size-9",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
@@ -33,5 +35,4 @@ export const buttonVariants = cva(
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
export type ButtonVariants = VariantProps<typeof buttonVariants>
|
export type ButtonVariants = VariantProps<typeof buttonVariants>
|
||||||
|
|||||||
26
management-ui/src/components/ui/pagination/Pagination.vue
Normal file
26
management-ui/src/components/ui/pagination/Pagination.vue
Normal 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>
|
||||||
@@ -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>
|
||||||
@@ -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>
|
||||||
@@ -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>
|
||||||
@@ -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>
|
||||||
@@ -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>
|
||||||
@@ -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>
|
||||||
@@ -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>
|
||||||
8
management-ui/src/components/ui/pagination/index.ts
Normal file
8
management-ui/src/components/ui/pagination/index.ts
Normal 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"
|
||||||
@@ -14,11 +14,13 @@ const props = defineProps<{ row: Users }>() // ← accept full row
|
|||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'deleted', id: string): void
|
(e: 'deleted', id: string): void
|
||||||
(e: 'error', err: unknown): void
|
(e: 'error', err: unknown): void
|
||||||
|
(e: 'updated', payload: { id: string; username: string; role: 'admin' | 'user' }): void
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const isEditOpen = ref(false)
|
const isEditOpen = ref(false)
|
||||||
const isDeleteOpen = ref(false)
|
const isDeleteOpen = ref(false)
|
||||||
const deleting = ref(false)
|
const deleting = ref(false)
|
||||||
|
const updating = ref(false)
|
||||||
|
|
||||||
async function onDeleteConfirmed() {
|
async function onDeleteConfirmed() {
|
||||||
try {
|
try {
|
||||||
@@ -34,8 +36,50 @@ async function onDeleteConfirmed() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function onEditConfirm() {
|
async function onEditConfirm(payload: { username: string; password?: string; role: 'admin' | 'user' }) {
|
||||||
isEditOpen.value = false
|
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>
|
</script>
|
||||||
|
|
||||||
@@ -55,6 +99,6 @@ function onEditConfirm() {
|
|||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</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" />
|
<DeleteUserDialog v-model:modelValue="isDeleteOpen" :loading="deleting" @confirm="onDeleteConfirmed" />
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -52,6 +52,24 @@ function usernamesFromIds(ids: string[]): string {
|
|||||||
return ids.map(id => idToName.value.get(String(id))).filter(Boolean).join(', ')
|
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 ----------------
|
// ---------------- Devices ----------------
|
||||||
type ApiDeviceUser = { id: number; username: string; role: string }
|
type ApiDeviceUser = { id: number; username: string; role: string }
|
||||||
type ApiDevice = { guid: string; name: string; users?: ApiDeviceUser[] }
|
type ApiDevice = { guid: string; name: string; users?: ApiDeviceUser[] }
|
||||||
@@ -201,6 +219,8 @@ onBeforeUnmount(() => {
|
|||||||
:columns="user_columns"
|
:columns="user_columns"
|
||||||
:data="user_data"
|
:data="user_data"
|
||||||
:dropdownComponent="AdminUserDropdonw"
|
:dropdownComponent="AdminUserDropdonw"
|
||||||
|
@row-updated="handleUserUpdated"
|
||||||
|
@row-deleted="handleUserDeleted"
|
||||||
/>
|
/>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
110
management-ui/src/customcompometns/DataTableNoCheckboxScroll.vue
Normal file
110
management-ui/src/customcompometns/DataTableNoCheckboxScroll.vue
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
<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>
|
||||||
|
<!-- 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]">
|
||||||
|
<!-- 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">
|
||||||
|
<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>
|
||||||
|
<TableHead
|
||||||
|
v-if="props.dropdownComponent"
|
||||||
|
class="sticky top-0 bg-background z-10 w-12"
|
||||||
|
/>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
|
||||||
|
<TableBody>
|
||||||
|
<template v-if="table.getRowModel().rows.length">
|
||||||
|
<TableRow
|
||||||
|
v-for="row in table.getRowModel().rows"
|
||||||
|
:key="row.id"
|
||||||
|
class="whitespace-nowrap"
|
||||||
|
>
|
||||||
|
<TableCell v-for="cell in row.getVisibleCells()" :key="cell.id">
|
||||||
|
<FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />
|
||||||
|
</TableCell>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<!-- Always show both scrollbars when needed -->
|
||||||
|
<ScrollBar orientation="horizontal" />
|
||||||
|
<ScrollBar orientation="vertical" />
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,49 +1,134 @@
|
|||||||
<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 pt-8">
|
||||||
|
<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>
|
||||||
|
<div class="flex-1 min-h-0 pb-2">
|
||||||
|
<DataTableNoCheckboxScroll
|
||||||
|
:columns="columns"
|
||||||
|
:data="certs"
|
||||||
|
minTableWidth="min-w-[900px]" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button @click="close">Close</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,41 +1,285 @@
|
|||||||
<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'
|
||||||
|
import { EventSourcePolyfill } from 'event-source-polyfill'
|
||||||
|
|
||||||
|
// hls.js for non-Safari browsers
|
||||||
|
import Hls from 'hls.js'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
|
||||||
|
type PublishTokenResp = { hlsUrl: string } | { HLS: string }
|
||||||
|
|
||||||
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 waitingLive = ref(false)
|
||||||
|
const hlsUrl = ref<string | null>(null)
|
||||||
|
const playing = ref(false)
|
||||||
|
|
||||||
|
/** Player bits **/
|
||||||
|
const audioEl = ref<HTMLAudioElement | null>(null)
|
||||||
|
const hls = ref<any | null>(null)
|
||||||
|
|
||||||
|
/** 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)
|
||||||
|
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 player and play **/
|
||||||
|
async function attachAndPlay(url: string) {
|
||||||
|
streamError.value = null
|
||||||
|
hlsUrl.value = url
|
||||||
|
teardownHls()
|
||||||
|
|
||||||
|
const el = audioEl.value
|
||||||
|
if (!el) {
|
||||||
|
streamError.value = 'Audio element is not available.'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
el.controls = true
|
||||||
|
el.autoplay = true
|
||||||
|
|
||||||
|
// Non-Safari: hls.js
|
||||||
|
if (Hls && typeof (Hls as any).isSupported === 'function' && Hls.isSupported()) {
|
||||||
|
const instance = new (Hls as any)({
|
||||||
|
enableWorker: true,
|
||||||
|
lowLatencyMode: true,
|
||||||
|
backBufferLength: 60,
|
||||||
|
})
|
||||||
|
hls.value = instance
|
||||||
|
|
||||||
|
instance.on(Hls.Events.ERROR, (_evt: any, data: any) => {
|
||||||
|
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 / iOS (native HLS)
|
||||||
|
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:
|
||||||
|
* 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)
|
||||||
|
|
||||||
|
// 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'
|
||||||
|
playing.value = false
|
||||||
|
} finally {
|
||||||
|
sending.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
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)
|
||||||
|
} finally {
|
||||||
|
sending.value = false
|
||||||
|
closeEventSource()
|
||||||
|
teardownHls()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cleanup
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
closeEventSource()
|
||||||
|
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 items-center">
|
||||||
<TabsContent value="livestream">
|
<Button :disabled="sending || waitingLive" @click="startStreaming">
|
||||||
<Button>
|
<span v-if="waitingLive">Waiting live…</span>
|
||||||
Start streaming
|
<span v-else>{{ sending ? 'Starting…' : 'Start streaming' }}</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button>
|
<Button :disabled="sending" @click="stopStreaming">
|
||||||
Stop streaming
|
{{ sending ? 'Stopping…' : 'Stop streaming' }}
|
||||||
</Button>
|
</Button>
|
||||||
</TabsContent>
|
</div>
|
||||||
</Tabs>
|
|
||||||
|
<div v-if="streamError" class="text-sm text-red-600">
|
||||||
|
{{ streamError }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Player -->
|
||||||
|
<div class="mt-2">
|
||||||
|
<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 && !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>
|
||||||
|
</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,141 @@
|
|||||||
<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>
|
||||||
<DialogTitle>Tasks</DialogTitle>
|
<div class="flex items-center justify-between">
|
||||||
<DialogDescription>
|
<div>
|
||||||
{{ props.device?.guid }}
|
<DialogTitle>Tasks</DialogTitle>
|
||||||
</DialogDescription>
|
<DialogDescription class="mt-1 break-all">
|
||||||
</DialogHeader>
|
{{ 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>
|
||||||
|
|
||||||
<DialogFooter>
|
<div v-if="error" class="text-sm text-red-600 mb-3">{{ error }}</div>
|
||||||
<Button @click="onSave">Close</Button>
|
|
||||||
</DialogFooter>
|
<div v-if="loading" class="text-sm text-muted-foreground py-8 text-center">
|
||||||
</DialogContent>
|
Loading tasks…
|
||||||
</Dialog>
|
</div>
|
||||||
|
<div v-else>
|
||||||
|
<!-- 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>
|
||||||
|
<Button @click="onClose">Close</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</template>
|
</template>
|
||||||
@@ -11,8 +11,9 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { Input } from '@/components/ui/input'
|
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 { defineProps, defineEmits } from 'vue'
|
import { defineProps, defineEmits, reactive, watch } from 'vue'
|
||||||
import type { PropType } from 'vue'
|
import type { PropType } from 'vue'
|
||||||
|
import type { Users } from '@/lib/interfaces'
|
||||||
|
|
||||||
// 1) runtime props so Vue + TS agree
|
// 1) runtime props so Vue + TS agree
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
@@ -20,26 +21,58 @@ const props = defineProps({
|
|||||||
type: Boolean as PropType<boolean>,
|
type: Boolean as PropType<boolean>,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
user: {
|
||||||
|
type: Object as PropType<Users>,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// 2) two emits: v-model and confirm
|
// 2) two emits: v-model and confirm
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
|
(
|
||||||
|
e: 'confirm',
|
||||||
|
payload: { username: string; password?: string; role: 'admin' | 'user' }
|
||||||
|
): void
|
||||||
(e: 'update:modelValue', v: boolean): 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() {
|
function onSave() {
|
||||||
emit('confirm')
|
const payload: { username: string; password?: string; role: 'admin' | 'user' } = {
|
||||||
// close the dialog
|
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)
|
emit('update:modelValue', false)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Dialog
|
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||||
:open="props.modelValue"
|
|
||||||
@update:open="(v: boolean) => emit('update:modelValue', v)"
|
|
||||||
>
|
|
||||||
<DialogContent class="sm:max-w-[425px]">
|
<DialogContent class="sm:max-w-[425px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Edit profile</DialogTitle>
|
<DialogTitle>Edit profile</DialogTitle>
|
||||||
@@ -51,15 +84,15 @@ function onSave() {
|
|||||||
<div class="grid gap-4 py-4">
|
<div class="grid gap-4 py-4">
|
||||||
<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="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>
|
||||||
<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="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>
|
||||||
<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="isAdmin" class="text-right">Make admin</Label>
|
||||||
<Switch id="isAdmin"/>
|
<Switch id="isAdmin" :default-value="form.isAdmin" v-model:checked="form.isAdmin"/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,13 @@ import {
|
|||||||
DropdownMenu, DropdownMenuContent,
|
DropdownMenu, DropdownMenuContent,
|
||||||
DropdownMenuTrigger, DropdownMenuSeparator,
|
DropdownMenuTrigger, DropdownMenuSeparator,
|
||||||
DropdownMenuItem, DropdownMenuLabel
|
DropdownMenuItem, DropdownMenuLabel
|
||||||
} from '@/components/ui/dropdown-menu'
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils';
|
||||||
import { Settings } from 'lucide-vue-next'
|
import { Settings } from 'lucide-vue-next';
|
||||||
import { RouterLink, useRoute } from 'vue-router'
|
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 }>()
|
const { customComponent } = defineProps<{ customComponent?: any }>()
|
||||||
|
|
||||||
@@ -24,6 +27,17 @@ function navLinkClass(prefix: string) {
|
|||||||
isActive(prefix) ? 'text-primary' : 'text-muted-foreground hover:text-primary'
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -60,7 +74,7 @@ function navLinkClass(prefix: string) {
|
|||||||
</button>
|
</button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent class="w-48">
|
<DropdownMenuContent class="w-48">
|
||||||
<DropdownMenuLabel>Admin</DropdownMenuLabel>
|
<DropdownMenuLabel>{{ username }}</DropdownMenuLabel>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<RouterLink to="/settings">
|
<RouterLink to="/settings">
|
||||||
<DropdownMenuItem>Settings</DropdownMenuItem>
|
<DropdownMenuItem>Settings</DropdownMenuItem>
|
||||||
|
|||||||
@@ -3,33 +3,149 @@ import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/componen
|
|||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Label } from '@/components/ui/label'
|
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>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<div class="w-full h-full flex items-center justify-center px-4">
|
<div class="w-full h-full flex items-center justify-center px-4">
|
||||||
<Card class="flex w-[600px]">
|
<Card class="flex w-[600px]">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>
|
<div class="flex items-center justify-between">
|
||||||
Settings
|
<CardTitle>
|
||||||
</CardTitle>
|
Settings
|
||||||
|
</CardTitle>
|
||||||
|
<Button variant="ghost" class="w-auto px-4" @click="goBack">
|
||||||
|
<X/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<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">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="username" class="text-right">Username</Label>
|
<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>
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="current_password" class="text-right">Current password</Label>
|
<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>
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="new_password" class="text-right">New password</Label>
|
<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>
|
<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>
|
</CardContent>
|
||||||
<CardFooter>
|
<CardFooter>
|
||||||
<Button type="submit">Save changes</Button>
|
<Button type="submit" :disabled="submitting">
|
||||||
|
{{ submitting ? 'Saving…' : 'Save changes' }}
|
||||||
|
</Button>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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 Admin from '@/pages/Admin.vue';
|
||||||
import Login from '@/pages/Login.vue';
|
import Login from '@/pages/Login.vue';
|
||||||
@@ -19,7 +19,7 @@ declare module 'vue-router' {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const routes = [
|
const routes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
path: '/login',
|
path: '/login',
|
||||||
name: 'Login',
|
name: 'Login',
|
||||||
@@ -80,6 +80,17 @@ const routes = [
|
|||||||
props: true, // so `guid` shows up as a prop
|
props: true, // so `guid` shows up as a prop
|
||||||
meta: { requiresAuth: true }
|
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({
|
const router = createRouter({
|
||||||
|
|||||||
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/*"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
19
mediamtx/Dockerfile
Normal file
19
mediamtx/Dockerfile
Normal 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"]
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
logLevel: info
|
# logLevel: info
|
||||||
|
|
||||||
|
logLevel: debug
|
||||||
|
|
||||||
# Enable Control API (useful for debugging; bound to localhost by default)
|
# Enable Control API (useful for debugging; bound to localhost by default)
|
||||||
api: yes
|
api: yes
|
||||||
@@ -16,7 +18,12 @@ hlsVariant: lowLatency
|
|||||||
# WebRTC (browser-friendly)
|
# WebRTC (browser-friendly)
|
||||||
webrtc: yes
|
webrtc: yes
|
||||||
webrtcAddress: :8889
|
webrtcAddress: :8889
|
||||||
|
# whip: yes
|
||||||
webrtcLocalUDPAddress: :8189
|
webrtcLocalUDPAddress: :8189
|
||||||
|
webrtcIPsFromInterfaces: yes
|
||||||
|
webrtcIPsFromInterfacesList: []
|
||||||
|
webrtcAdditionalHosts:
|
||||||
|
- 192.168.205.130
|
||||||
# Optional: add a STUN server if behind NAT
|
# Optional: add a STUN server if behind NAT
|
||||||
# webrtcICEServers2:
|
# webrtcICEServers2:
|
||||||
# - url: stun:stun.l.google.com:19302
|
# - url: stun:stun.l.google.com:19302
|
||||||
@@ -52,14 +59,16 @@ pathDefaults:
|
|||||||
# \"dstFs\":\"minio:livestream\",
|
# \"dstFs\":\"minio:livestream\",
|
||||||
# \"dstRemote\":\"$MTX_PATH/$f\"}"'
|
# \"dstRemote\":\"$MTX_PATH/$f\"}"'
|
||||||
|
|
||||||
runOnRecordSegmentCreate: >
|
# runOnRecordSegmentCreate: >
|
||||||
sh -c 'd="$(dirname "$MTX_SEGMENT_PATH")";
|
# sh -c 'd="$(dirname "$MTX_SEGMENT_PATH")";
|
||||||
f="$(basename "$MTX_SEGMENT_PATH")";
|
# f="$(basename "$MTX_SEGMENT_PATH")";
|
||||||
curl -s -H "Content-Type: application/json"
|
# curl -s -H "Content-Type: application/json"
|
||||||
-X POST "http://rclone:5572/operations/copyfile?_async=true"
|
# -X POST "http://rclone:5572/operations/copyfile?_async=true"
|
||||||
-d "{\"srcFs\":\"$d\",\"srcRemote\":\"$f\",
|
# -d "{\"srcFs\":\"$d\",\"srcRemote\":\"$f\",
|
||||||
\"dstFs\":\"minio:livestream\",
|
# \"dstFs\":\"minio:livestream\",
|
||||||
\"dstRemote\":\"$MTX_PATH/$f\"}"'
|
# \"dstRemote\":\"$MTX_PATH/$f\"}"'
|
||||||
|
|
||||||
|
runOnRecordSegmentCreate: rclone copy "$MTX_SEGMENT_PATH" "minio:livestream/${MTX_SEGMENT_PATH#/recordings/whip/live/}" --progress
|
||||||
|
|
||||||
authInternalUsers:
|
authInternalUsers:
|
||||||
- user: any
|
- user: any
|
||||||
|
|||||||
@@ -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 _;
|
||||||
@@ -57,9 +74,13 @@ server {
|
|||||||
# HTTPS :443 — mTLS enforced only on listed paths
|
# HTTPS :443 — mTLS enforced only on listed paths
|
||||||
# ==============================================
|
# ==============================================
|
||||||
server {
|
server {
|
||||||
listen 443 ssl http2;
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
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 +119,49 @@ 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) {
|
|
||||||
return 495;
|
|
||||||
}
|
|
||||||
proxy_pass http://mediamtx:8888/;
|
proxy_pass http://mediamtx:8888/;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
}
|
}
|
||||||
|
|
||||||
# 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
readme.md
22
readme.md
@@ -1,5 +1,21 @@
|
|||||||
# Vault setup
|
# 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
|
```bash
|
||||||
export VAULT_ADDR=http://localhost:8200
|
export VAULT_ADDR=http://localhost:8200
|
||||||
export VAULT_TOKEN=root
|
export VAULT_TOKEN=root
|
||||||
@@ -20,10 +36,10 @@ vault kv put kv/snoop \
|
|||||||
minio_presign_ttl_seconds="900"
|
minio_presign_ttl_seconds="900"
|
||||||
```
|
```
|
||||||
|
|
||||||
Unseal Key 1: XdERN+/hxR9RjLC/S8c+y0omToYvB7Qs1jaUenZQvphD
|
Unseal Key 1: AMLVUGoP2hlEd02nWWghAiVYT4jtiXv50WsZyQ2MbpP/
|
||||||
Unseal Key 2: VBhPBtYcq1GAk7ByPfAsamxV4tJOZ49chAYxxOvc49Oj
|
Unseal Key 2: OtaDsNoGE2EF6UfrQUkU0NoDVxPK/KwBFg9cUfQuhBs+
|
||||||
|
|
||||||
Initial Root Token: hvs.tZ4eh9P18sCZ5c1PZIz59EmH
|
Initial Root Token: hvs.rKzgIc5aaucOCtlJNsUdZuEH
|
||||||
|
|
||||||
|
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -22,5 +22,8 @@ func AutoMigrate(db *gorm.DB) error {
|
|||||||
&models.DEviceTask{},
|
&models.DEviceTask{},
|
||||||
&models.DeviceCertificate{},
|
&models.DeviceCertificate{},
|
||||||
&models.RevokedSerial{},
|
&models.RevokedSerial{},
|
||||||
|
&models.DeviceConfig{},
|
||||||
|
&models.MQTTMsg{},
|
||||||
|
&models.EmqxClientEvent{},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
38
server/internal/dto/cert.go
Normal file
38
server/internal/dto/cert.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
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"`
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
Limit int `json:"limit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ type CreateUserDto struct {
|
|||||||
Role string `json:"role" binding:"required,oneof=admin user"`
|
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 {
|
func MapUser(u models.User) UserDto {
|
||||||
return UserDto{
|
return UserDto{
|
||||||
ID: u.ID,
|
ID: u.ID,
|
||||||
|
|||||||
48
server/internal/handlers/broker.go
Normal file
48
server/internal/handlers/broker.go
Normal 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:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,11 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
"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 +13,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"
|
||||||
@@ -19,16 +23,21 @@ type MediaMTXHandler struct {
|
|||||||
jwtMgr *crypto.JWTManager
|
jwtMgr *crypto.JWTManager
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
cfg config.MediaMTXConfig
|
cfg config.MediaMTXConfig
|
||||||
|
bus *Broker
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMediaMTXHandler(db *gorm.DB, jwt *crypto.JWTManager, c config.MediaMTXConfig) *MediaMTXHandler {
|
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
|
// --- 3.1 External auth endpoint called by MediaMTX
|
||||||
// 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 +45,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 {
|
||||||
@@ -112,7 +88,18 @@ func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// allowed
|
// 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)
|
c.Status(http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,7 +113,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 +141,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 +154,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 +276,229 @@ 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 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
|
||||||
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -121,3 +121,98 @@ func (h *UsersHandler) Delete(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
c.Status(http.StatusNoContent)
|
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))
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
"smoop-api/internal/handlers"
|
"smoop-api/internal/handlers"
|
||||||
"smoop-api/internal/models"
|
"smoop-api/internal/models"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/golang-jwt/jwt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeviceAccessFilter middleware sets filtering context for device access
|
// DeviceAccessFilter middleware sets filtering context for device access
|
||||||
@@ -64,3 +67,48 @@ func TrackerAccessFilter() gin.HandlerFunc {
|
|||||||
c.Next()
|
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"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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"`
|
||||||
|
}
|
||||||
31
server/internal/models/emqx.go
Normal file
31
server/internal/models/emqx.go
Normal 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"
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -47,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.POST("/auth/change_password", authMW, authH.ChangePassword)
|
||||||
|
|
||||||
r.GET("/users/profile", authMW, usersH.Profile)
|
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.GET("/users", authMW, adminOnly, usersH.List)
|
||||||
r.POST("/users/create", authMW, adminOnly, usersH.Create)
|
r.POST("/users/create", authMW, adminOnly, usersH.Create)
|
||||||
r.DELETE("/users/:id", authMW, adminOnly, usersH.Delete)
|
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.GET("/devices", authMW, middleware.DeviceAccessFilter(), devH.List)
|
||||||
r.POST("/devices/create", authMW, adminOnly, devH.Create)
|
r.POST("/devices/create", authMW, adminOnly, devH.Create)
|
||||||
@@ -62,6 +66,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,10 +85,12 @@ 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)
|
||||||
|
// 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.GET("/trackers", authMW, middleware.TrackerAccessFilter(), trackersH.List)
|
||||||
r.POST("/trackers/create", authMW, trackersH.Create)
|
r.POST("/trackers/create", authMW, trackersH.Create)
|
||||||
|
|||||||
Reference in New Issue
Block a user