Skip to content

Commit

Permalink
Ability to add, edit, and delete camera groups in the UI (#10296)
Browse files Browse the repository at this point in the history
* Add dialog for creating new camera group

* Support adding of camera groups and dynamically updating the config

* Support deleting and edit existing camera groups

* Don't show separator if user has no groups

* Formatting

* fix background
  • Loading branch information
NickM-27 authored Mar 7, 2024
1 parent 90db27e commit 3d90f50
Show file tree
Hide file tree
Showing 6 changed files with 282 additions and 38 deletions.
9 changes: 8 additions & 1 deletion frigate/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def config_set():
f.close()
# Validate the config schema
try:
FrigateConfig.parse_raw(new_raw_config)
config_obj = FrigateConfig.parse_raw(new_raw_config)
except Exception:
with open(config_file, "w") as f:
f.write(old_raw_config)
Expand All @@ -314,6 +314,13 @@ def config_set():
500,
)

json = request.get_json(silent=True) or {}

if json.get("requires_restart", 1) == 0:
current_app.frigate_config = FrigateConfig.runtime_config(
config_obj, current_app.plus_api
)

return make_response(
jsonify(
{
Expand Down
11 changes: 8 additions & 3 deletions frigate/util/builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,17 +204,22 @@ def update_yaml_from_url(file_path, url):
key_path.pop(i - 1)
except ValueError:
pass
new_value = new_value_list[0]
update_yaml_file(file_path, key_path, new_value)

if len(new_value_list) > 1:
update_yaml_file(file_path, key_path, new_value_list)
else:
update_yaml_file(file_path, key_path, new_value_list[0])


def update_yaml_file(file_path, key_path, new_value):
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
with open(file_path, "r") as f:
data = yaml.load(f)

data = update_yaml(data, key_path, new_value)

with open("/config/test.yaml", "w") as f:
yaml.dump(data, f)
with open(file_path, "w") as f:
yaml.dump(data, f)

Expand Down
232 changes: 230 additions & 2 deletions web/src/components/filter/CameraGroupSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { FrigateConfig } from "@/types/frigateConfig";
import {
CameraGroupConfig,
FrigateConfig,
GROUP_ICONS,
} from "@/types/frigateConfig";
import { isDesktop } from "react-device-detect";
import useSWR from "swr";
import { MdHome } from "react-icons/md";
Expand All @@ -8,6 +12,19 @@ import { useNavigate } from "react-router-dom";
import { useCallback, useMemo, useState } from "react";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { getIconForGroup } from "@/utils/iconUtil";
import { LuPencil, LuPlus, LuTrash } from "react-icons/lu";
import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
import { Input } from "../ui/input";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import FilterCheckBox from "./FilterCheckBox";
import axios from "axios";

type CameraGroupSelectorProps = {
className?: string;
Expand Down Expand Up @@ -49,10 +66,20 @@ export function CameraGroupSelector({ className }: CameraGroupSelectorProps) {
);
}, [config]);

// add group

const [addGroup, setAddGroup] = useState(false);

return (
<div
className={`flex items-center justify-start gap-2 ${className ?? ""} ${isDesktop ? "flex-col" : ""}`}
>
<NewGroupDialog
open={addGroup}
setOpen={setAddGroup}
currentGroups={groups}
/>

<Tooltip open={tooltip == "home"}>
<TooltipTrigger asChild>
<Button
Expand All @@ -62,7 +89,7 @@ export function CameraGroupSelector({ className }: CameraGroupSelectorProps) {
: "text-muted-foreground bg-secondary focus:text-muted-foreground focus:bg-secondary"
}
size="xs"
onClick={() => navigate(-1)}
onClick={() => (group ? navigate(-1) : null)}
onMouseEnter={() => (isDesktop ? showTooltip("home") : null)}
onMouseLeave={() => (isDesktop ? showTooltip(undefined) : null)}
>
Expand Down Expand Up @@ -97,6 +124,207 @@ export function CameraGroupSelector({ className }: CameraGroupSelectorProps) {
</Tooltip>
);
})}
{isDesktop && (
<Button
className="text-muted-foreground bg-secondary"
size="xs"
onClick={() => setAddGroup(true)}
>
<LuPlus className="size-4 text-primary-foreground" />
</Button>
)}
</div>
);
}

type NewGroupDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
currentGroups: [string, CameraGroupConfig][];
};
function NewGroupDialog({ open, setOpen, currentGroups }: NewGroupDialogProps) {
const { data: config, mutate: updateConfig } =
useSWR<FrigateConfig>("config");

// add fields

const [editState, setEditState] = useState<"none" | "add" | "edit">("none");
const [newTitle, setNewTitle] = useState("");
const [icon, setIcon] = useState("");
const [cameras, setCameras] = useState<string[]>([]);

// validation

const [error, setError] = useState("");

const onCreateGroup = useCallback(async () => {
if (!newTitle) {
setError("A title must be selected");
return;
}

if (!icon) {
setError("An icon must be selected");
return;
}

if (!cameras || cameras.length < 2) {
setError("At least 2 cameras must be selected");
return;
}

setError("");
const orderQuery = `camera_groups.${newTitle}.order=${currentGroups.length}`;
const iconQuery = `camera_groups.${newTitle}.icon=${icon}`;
const cameraQueries = cameras
.map((cam) => `&camera_groups.${newTitle}.cameras=${cam}`)
.join("");

const req = axios.put(
`config/set?${orderQuery}&${iconQuery}${cameraQueries}`,
{ requires_restart: 0 },
);

setOpen(false);

if ((await req).status == 200) {
setNewTitle("");
setIcon("");
setCameras([]);
updateConfig();
}
}, [currentGroups, cameras, newTitle, icon, setOpen, updateConfig]);

const onDeleteGroup = useCallback(
async (name: string) => {
const req = axios.put(`config/set?camera_groups.${name}`, {
requires_restart: 0,
});

if ((await req).status == 200) {
updateConfig();
}
},
[updateConfig],
);

return (
<Dialog
open={open}
onOpenChange={(open) => {
setEditState("none");
setNewTitle("");
setIcon("");
setCameras([]);
setOpen(open);
}}
>
<DialogContent className="min-w-0 w-96">
<DialogTitle>Camera Groups</DialogTitle>
{currentGroups.map((group) => (
<div className="flex justify-between items-center">
{group[0]}
<div className="flex justify-center gap-1">
<Button
className="bg-transparent"
size="icon"
onClick={() => {
setNewTitle(group[0]);
setIcon(group[1].icon);
setCameras(group[1].cameras);
setEditState("edit");
}}
>
<LuPencil />
</Button>
<Button
className="text-destructive bg-transparent"
size="icon"
onClick={() => onDeleteGroup(group[0])}
>
<LuTrash />
</Button>
</div>
</div>
))}
{currentGroups.length > 0 && <DropdownMenuSeparator />}
{editState == "none" && (
<Button
className="text-primary-foreground justify-start"
variant="ghost"
onClick={() => setEditState("add")}
>
<LuPlus className="size-4 mr-1" />
Create new group
</Button>
)}
{editState != "none" && (
<>
<Input
type="text"
placeholder="Name"
disabled={editState == "edit"}
value={newTitle}
onChange={(e) => setNewTitle(e.target.value)}
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="flex justify-start gap-2 items-center cursor-pointer">
{icon.length == 0 ? "Select Icon" : "Icon: "}
{icon ? getIconForGroup(icon) : <div className="size-4" />}
</div>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuRadioGroup value={icon} onValueChange={setIcon}>
{GROUP_ICONS.map((gIcon) => (
<DropdownMenuRadioItem
key={gIcon}
className="w-full flex justify-start items-center gap-2 cursor-pointer hover:bg-secondary"
value={gIcon}
>
{getIconForGroup(gIcon)}
{gIcon}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="flex justify-start gap-2 items-center cursor-pointer">
{cameras.length == 0
? "Select Cameras"
: `${cameras.length} Cameras`}
</div>
</DropdownMenuTrigger>
<DropdownMenuContent>
{Object.keys(config?.cameras ?? {}).map((camera) => (
<FilterCheckBox
key={camera}
isChecked={cameras.includes(camera)}
label={camera.replaceAll("_", " ")}
onCheckedChange={(checked) => {
if (checked) {
setCameras([...cameras, camera]);
} else {
const index = cameras.indexOf(camera);
setCameras([
...cameras.slice(0, index),
...cameras.slice(index + 1),
]);
}
}}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
{error && <div className="text-danger">{error}</div>}
<Button variant="select" onClick={onCreateGroup}>
Submit
</Button>
</>
)}
</DialogContent>
</Dialog>
);
}
32 changes: 32 additions & 0 deletions web/src/components/filter/FilterCheckBox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { LuCheck } from "react-icons/lu";
import { Button } from "../ui/button";
import { IconType } from "react-icons";

type FilterCheckBoxProps = {
label: string;
CheckIcon?: IconType;
isChecked: boolean;
onCheckedChange: (isChecked: boolean) => void;
};

export default function FilterCheckBox({
label,
CheckIcon = LuCheck,
isChecked,
onCheckedChange,
}: FilterCheckBoxProps) {
return (
<Button
className="capitalize flex justify-between items-center cursor-pointer w-full text-primary-foreground"
variant="ghost"
onClick={() => onCheckedChange(!isChecked)}
>
{isChecked ? (
<CheckIcon className="w-6 h-6" />
) : (
<div className="w-6 h-6" />
)}
<div className="ml-1 w-full flex justify-start">{label}</div>
</Button>
);
}
Loading

0 comments on commit 3d90f50

Please sign in to comment.