Add Camera Wizard (#20461)
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
CI / AMD64 Build (push) Waiting to run

* fetch more from ffprobe

* add detailed param to ffprobe endpoint

* add dots variant to step indicator

* add classname

* tweak colors for dark mode to match figma

* add step 1 form

* add helper function for ffmpeg snapshot

* add go2rtc stream add and ffprobe snapshot endpoints

* add camera image and stream details on successful test

* step 1 tweaks

* step 2 and i18n

* types

* step 1 and 2 tweaks

* add wizard to camera settings view

* add data unit i18n keys

* restream tweak

* fix type

* implement rough idea for step 3

* add api endpoint to delete stream from go2rtc

* add main wizard dialog component

* extract logic for friendly_name and use in wizard

* add i18n and popover for brand url

* add camera name to top

* consolidate validation logic

* prevent dialog from closing when clicking outside

* center camera name on mobile

* add help/docs link popovers

* keep spaces in friendly name

* add stream details to overlay like stats in liveplayer

* add validation results pane to step 3

* ensure test is invalidated if stream is changed

* only display validation results and enable save button if all streams have been tested

* tweaks

* normalize camera name to lower case and improve hash generation

* move wizard to subfolder

* tweaks

* match look of camera edit form to wizard

* move wizard and edit form to its own component

* move enabled/disabled switch to management section

* clean up

* fixes

* fix mobile
This commit is contained in:
Josh Hawkins
2025-10-13 10:52:08 -06:00
committed by GitHub
parent 423693d14d
commit 9d85136f8f
19 changed files with 3571 additions and 429 deletions
+333 -122
View File
@@ -9,6 +9,7 @@ import {
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Card, CardContent } from "@/components/ui/card";
import Heading from "@/components/ui/heading";
import { Separator } from "@/components/ui/separator";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -22,20 +23,9 @@ import { LuTrash2, LuPlus } from "react-icons/lu";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
type ConfigSetBody = {
requires_restart: number;
// TODO: type this better
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config_data: any;
update_topic?: string;
};
const generateFixedHash = (name: string): string => {
const encoded = encodeURIComponent(name);
const base64 = btoa(encoded);
const cleanHash = base64.replace(/[^a-zA-Z0-9]/g, "").substring(0, 8);
return `cam_${cleanHash.toLowerCase()}`;
};
import { processCameraName } from "@/utils/cameraUtil";
import { Label } from "@/components/ui/label";
import { ConfigSetBody } from "@/types/cameraWizard";
const RoleEnum = z.enum(["audio", "detect", "record"]);
type Role = z.infer<typeof RoleEnum>;
@@ -60,22 +50,26 @@ export default function CameraEditForm({
z.object({
cameraName: z
.string()
.min(1, { message: t("camera.cameraConfig.nameRequired") }),
.min(1, { message: t("cameraManagement.cameraConfig.nameRequired") }),
enabled: z.boolean(),
ffmpeg: z.object({
inputs: z
.array(
z.object({
path: z.string().min(1, {
message: t("camera.cameraConfig.ffmpeg.pathRequired"),
message: t(
"cameraManagement.cameraConfig.ffmpeg.pathRequired",
),
}),
roles: z.array(RoleEnum).min(1, {
message: t("camera.cameraConfig.ffmpeg.rolesRequired"),
message: t(
"cameraManagement.cameraConfig.ffmpeg.rolesRequired",
),
}),
}),
)
.min(1, {
message: t("camera.cameraConfig.ffmpeg.inputsRequired"),
message: t("cameraManagement.cameraConfig.ffmpeg.inputsRequired"),
})
.refine(
(inputs) => {
@@ -93,11 +87,12 @@ export default function CameraEditForm({
);
},
{
message: t("camera.cameraConfig.ffmpeg.rolesUnique"),
message: t("cameraManagement.cameraConfig.ffmpeg.rolesUnique"),
path: ["inputs"],
},
),
}),
go2rtcStreams: z.record(z.string(), z.array(z.string())).optional(),
}),
[t],
);
@@ -110,6 +105,7 @@ export default function CameraEditForm({
friendly_name: undefined,
name: cameraName || "",
roles: new Set<Role>(),
go2rtcStreams: {},
};
}
@@ -120,10 +116,14 @@ export default function CameraEditForm({
input.roles.forEach((role) => roles.add(role as Role));
});
// Load existing go2rtc streams
const go2rtcStreams = config.go2rtc?.streams || {};
return {
friendly_name: camera?.friendly_name || cameraName,
name: cameraName,
roles,
go2rtcStreams,
};
}, [cameraName, config]);
@@ -138,6 +138,7 @@ export default function CameraEditForm({
},
],
},
go2rtcStreams: {},
};
// Load existing camera config if editing
@@ -150,6 +151,41 @@ export default function CameraEditForm({
roles: input.roles as Role[],
}))
: defaultValues.ffmpeg.inputs;
// Load go2rtc streams for this camera
const go2rtcStreams = config.go2rtc?.streams || {};
const cameraStreams: Record<string, string[]> = {};
// Find streams that match this camera's name pattern
Object.entries(go2rtcStreams).forEach(([streamName, urls]) => {
if (streamName.startsWith(cameraName) || streamName === cameraName) {
cameraStreams[streamName] = Array.isArray(urls) ? urls : [urls];
}
});
// Also deduce go2rtc streams from restream URLs in camera inputs
camera.ffmpeg?.inputs?.forEach((input, index) => {
const restreamMatch = input.path.match(
/^rtsp:\/\/127\.0\.0\.1:8554\/(.+)$/,
);
if (restreamMatch) {
const streamName = restreamMatch[1];
// Find the corresponding go2rtc stream
const go2rtcStream = Object.entries(go2rtcStreams).find(
([name]) =>
name === streamName ||
name === `${cameraName}_${index + 1}` ||
name === cameraName,
);
if (go2rtcStream) {
cameraStreams[go2rtcStream[0]] = Array.isArray(go2rtcStream[1])
? go2rtcStream[1]
: [go2rtcStream[1]];
}
}
});
defaultValues.go2rtcStreams = cameraStreams;
}
const form = useForm<FormValues>({
@@ -166,21 +202,20 @@ export default function CameraEditForm({
// Watch ffmpeg.inputs to track used roles
const watchedInputs = form.watch("ffmpeg.inputs");
// Watch go2rtc streams
const watchedGo2rtcStreams = form.watch("go2rtcStreams") || {};
const saveCameraConfig = (values: FormValues) => {
setIsLoading(true);
let finalCameraName = values.cameraName;
let friendly_name: string | undefined = undefined;
const isValidName = /^[a-zA-Z0-9_-]+$/.test(values.cameraName);
if (!isValidName) {
finalCameraName = generateFixedHash(finalCameraName);
friendly_name = values.cameraName;
}
const { finalCameraName, friendlyName } = processCameraName(
values.cameraName,
);
const configData: ConfigSetBody["config_data"] = {
cameras: {
[finalCameraName]: {
enabled: values.enabled,
...(friendly_name && { friendly_name }),
...(friendlyName && { friendly_name: friendlyName }),
ffmpeg: {
inputs: values.ffmpeg.inputs.map((input) => ({
path: input.path,
@@ -191,6 +226,13 @@ export default function CameraEditForm({
},
};
// Add go2rtc streams if provided
if (values.go2rtcStreams && Object.keys(values.go2rtcStreams).length > 0) {
configData.go2rtc = {
streams: values.go2rtcStreams,
};
}
const requestBody: ConfigSetBody = {
requires_restart: 1,
config_data: configData,
@@ -205,13 +247,36 @@ export default function CameraEditForm({
.put("config/set", requestBody)
.then((res) => {
if (res.status === 200) {
toast.success(
t("camera.cameraConfig.toast.success", {
cameraName: values.cameraName,
}),
{ position: "top-center" },
);
if (onSave) onSave();
// Update running go2rtc instance if streams were configured
if (
values.go2rtcStreams &&
Object.keys(values.go2rtcStreams).length > 0
) {
const updatePromises = Object.entries(values.go2rtcStreams).map(
([streamName, urls]) =>
axios.put(
`go2rtc/streams/${streamName}?src=${encodeURIComponent(urls[0])}`,
),
);
Promise.allSettled(updatePromises).then(() => {
toast.success(
t("cameraManagement.cameraConfig.toast.success", {
cameraName: values.cameraName,
}),
{ position: "top-center" },
);
if (onSave) onSave();
});
} else {
toast.success(
t("cameraManagement.cameraConfig.toast.success", {
cameraName: values.cameraName,
}),
{ position: "top-center" },
);
if (onSave) onSave();
}
} else {
throw new Error(res.statusText);
}
@@ -238,11 +303,11 @@ export default function CameraEditForm({
values.cameraName !== cameraInfo?.friendly_name
) {
// If camera name changed, delete old camera config
const deleteRequestBody: ConfigSetBody = {
const deleteRequestBody = {
requires_restart: 1,
config_data: {
cameras: {
[cameraName]: "",
[cameraName]: null,
},
},
update_topic: `config/cameras/${cameraName}/remove`,
@@ -289,15 +354,15 @@ export default function CameraEditForm({
};
return (
<>
<div className="scrollbar-container max-w-4xl overflow-y-auto md:mb-24">
<Toaster position="top-center" closeButton />
<Heading as="h3" className="my-2">
{cameraName
? t("camera.cameraConfig.edit")
: t("camera.cameraConfig.add")}
? t("cameraManagement.cameraConfig.edit")
: t("cameraManagement.cameraConfig.add")}
</Heading>
<div className="my-3 text-sm text-muted-foreground">
{t("camera.cameraConfig.description")}
{t("cameraManagement.cameraConfig.description")}
</div>
<Separator className="my-3 bg-secondary" />
@@ -308,10 +373,12 @@ export default function CameraEditForm({
name="cameraName"
render={({ field }) => (
<FormItem>
<FormLabel>{t("camera.cameraConfig.name")}</FormLabel>
<FormLabel>{t("cameraManagement.cameraConfig.name")}</FormLabel>
<FormControl>
<Input
placeholder={t("camera.cameraConfig.namePlaceholder")}
placeholder={t(
"cameraManagement.cameraConfig.namePlaceholder",
)}
{...field}
disabled={!!cameraName} // Prevent editing name for existing cameras
/>
@@ -332,107 +399,251 @@ export default function CameraEditForm({
onCheckedChange={field.onChange}
/>
</FormControl>
<FormLabel>{t("camera.cameraConfig.enabled")}</FormLabel>
<FormLabel>
{t("cameraManagement.cameraConfig.enabled")}
</FormLabel>
<FormMessage />
</FormItem>
)}
/>
<div>
<FormLabel>{t("camera.cameraConfig.ffmpeg.inputs")}</FormLabel>
<div className="space-y-4">
<Label className="text-sm font-medium">
{t("cameraManagement.cameraConfig.ffmpeg.inputs")}
</Label>
{fields.map((field, index) => (
<div
key={field.id}
className="mt-2 space-y-4 rounded-md border p-4"
>
<FormField
control={form.control}
name={`ffmpeg.inputs.${index}.path`}
render={({ field }) => (
<FormItem>
<FormLabel>
{t("camera.cameraConfig.ffmpeg.path")}
</FormLabel>
<FormControl>
<Input
placeholder={t(
"camera.cameraConfig.ffmpeg.pathPlaceholder",
)}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Card key={field.id} className="bg-secondary text-primary">
<CardContent className="space-y-4 p-4">
<div className="flex items-center justify-between">
<h4 className="font-medium">
{t("cameraWizard.step2.streamTitle", {
number: index + 1,
})}
</h4>
<Button
variant="ghost"
size="sm"
onClick={() => remove(index)}
disabled={fields.length === 1}
className="text-secondary-foreground hover:text-secondary-foreground"
>
<LuTrash2 className="size-5" />
</Button>
</div>
<FormField
control={form.control}
name={`ffmpeg.inputs.${index}.roles`}
render={({ field }) => (
<FormItem>
<FormLabel>
{t("camera.cameraConfig.ffmpeg.roles")}
</FormLabel>
<FormControl>
<div className="flex flex-wrap gap-2">
{(["audio", "detect", "record"] as const).map(
(role) => (
<label
<FormField
control={form.control}
name={`ffmpeg.inputs.${index}.path`}
render={({ field }) => (
<FormItem>
<FormLabel className="text-sm font-medium">
{t("cameraManagement.cameraConfig.ffmpeg.path")}
</FormLabel>
<FormControl>
<Input
className="h-8"
placeholder={t(
"cameraManagement.cameraConfig.ffmpeg.pathPlaceholder",
)}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-2">
<Label className="text-sm font-medium">
{t("cameraManagement.cameraConfig.ffmpeg.roles")}
</Label>
<div className="rounded-lg bg-background p-3">
<div className="flex flex-wrap gap-2">
{(["detect", "record", "audio"] as const).map(
(role) => {
const isUsedElsewhere =
getUsedRolesExcludingIndex(index).has(role);
const isChecked =
watchedInputs[index]?.roles?.includes(role) ||
false;
return (
<div
key={role}
className="flex items-center space-x-2"
className="flex w-full items-center justify-between"
>
<input
type="checkbox"
checked={field.value.includes(role)}
onChange={(e) => {
const updatedRoles = e.target.checked
? [...field.value, role]
: field.value.filter((r) => r !== role);
field.onChange(updatedRoles);
<span className="text-sm capitalize">
{role}
</span>
<Switch
checked={isChecked}
onCheckedChange={(checked) => {
const currentRoles =
watchedInputs[index]?.roles || [];
const updatedRoles = checked
? [...currentRoles, role]
: currentRoles.filter((r) => r !== role);
form.setValue(
`ffmpeg.inputs.${index}.roles`,
updatedRoles,
);
}}
disabled={
!field.value.includes(role) &&
getUsedRolesExcludingIndex(index).has(role)
}
disabled={!isChecked && isUsedElsewhere}
/>
<span>{role}</span>
</label>
),
)}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
variant="destructive"
size="sm"
onClick={() => remove(index)}
disabled={fields.length === 1}
>
<LuTrash2 className="mr-2 h-4 w-4" />
{t("camera.cameraConfig.ffmpeg.removeInput")}
</Button>
</div>
</div>
);
},
)}
</div>
</div>
</div>
</CardContent>
</Card>
))}
<FormMessage>
{form.formState.errors.ffmpeg?.inputs?.root &&
form.formState.errors.ffmpeg.inputs.root.message}
</FormMessage>
<Button
variant="outline"
size="sm"
className="mt-2"
type="button"
onClick={() => append({ path: "", roles: getAvailableRoles() })}
variant="outline"
className=""
>
<LuPlus className="mr-2 h-4 w-4" />
{t("camera.cameraConfig.ffmpeg.addInput")}
<LuPlus className="mr-2 size-4" />
{t("cameraManagement.cameraConfig.ffmpeg.addInput")}
</Button>
</div>
{/* go2rtc Streams Section */}
{Object.keys(watchedGo2rtcStreams).length > 0 && (
<div className="space-y-4">
<Label className="text-sm font-medium">
{t("cameraManagement.cameraConfig.go2rtcStreams")}
</Label>
{Object.entries(watchedGo2rtcStreams).map(
([streamName, urls]) => (
<Card key={streamName} className="bg-secondary text-primary">
<CardContent className="space-y-4 p-4">
<div className="flex items-center justify-between">
<h4 className="font-medium">{streamName}</h4>
<Button
variant="ghost"
size="sm"
onClick={() => {
const updatedStreams = { ...watchedGo2rtcStreams };
delete updatedStreams[streamName];
form.setValue("go2rtcStreams", updatedStreams);
}}
className="text-secondary-foreground hover:text-secondary-foreground"
>
<LuTrash2 className="size-5" />
</Button>
</div>
<div className="space-y-2">
<Label className="text-sm font-medium">
{t("cameraManagement.cameraConfig.streamUrls")}
</Label>
{(Array.isArray(urls) ? urls : [urls]).map(
(url, urlIndex) => (
<div
key={urlIndex}
className="flex items-center gap-2"
>
<Input
className="h-8 flex-1"
value={url}
onChange={(e) => {
const updatedStreams = {
...watchedGo2rtcStreams,
};
const currentUrls = Array.isArray(
updatedStreams[streamName],
)
? updatedStreams[streamName]
: [updatedStreams[streamName]];
currentUrls[urlIndex] = e.target.value;
updatedStreams[streamName] = currentUrls;
form.setValue(
"go2rtcStreams",
updatedStreams,
);
}}
placeholder="rtsp://username:password@host:port/path"
/>
{(Array.isArray(urls) ? urls : [urls]).length >
1 && (
<Button
variant="ghost"
size="sm"
onClick={() => {
const updatedStreams = {
...watchedGo2rtcStreams,
};
const currentUrls = Array.isArray(
updatedStreams[streamName],
)
? updatedStreams[streamName]
: [updatedStreams[streamName]];
currentUrls.splice(urlIndex, 1);
updatedStreams[streamName] = currentUrls;
form.setValue(
"go2rtcStreams",
updatedStreams,
);
}}
className="text-secondary-foreground hover:text-secondary-foreground"
>
<LuTrash2 className="size-4" />
</Button>
)}
</div>
),
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
const updatedStreams = { ...watchedGo2rtcStreams };
const currentUrls = Array.isArray(
updatedStreams[streamName],
)
? updatedStreams[streamName]
: [updatedStreams[streamName]];
currentUrls.push("");
updatedStreams[streamName] = currentUrls;
form.setValue("go2rtcStreams", updatedStreams);
}}
className="w-fit"
>
<LuPlus className="mr-2 size-4" />
{t("cameraManagement.cameraConfig.addUrl")}
</Button>
</div>
</CardContent>
</Card>
),
)}
<Button
type="button"
onClick={() => {
const streamName = `${cameraName}_stream_${Object.keys(watchedGo2rtcStreams).length + 1}`;
const updatedStreams = {
...watchedGo2rtcStreams,
[streamName]: [""],
};
form.setValue("go2rtcStreams", updatedStreams);
}}
variant="outline"
className=""
>
<LuPlus className="mr-2 size-4" />
{t("cameraManagement.cameraConfig.addGo2rtcStream")}
</Button>
</div>
)}
<div className="flex w-full flex-row items-center gap-2 pt-2 md:w-[50%]">
<Button
className="flex flex-1"
@@ -461,6 +672,6 @@ export default function CameraEditForm({
</div>
</form>
</Form>
</>
</div>
);
}