feat: filter people with different attributes to find faces to hide
Signed-off-by: Varun Raj <mailme@varunraj.in>
This commit is contained in:
1 parent
d0dcb00fd8
commit
b752bd2322
23 files changed
+558
-141
No files matched your search
@@ -0,0 +1,113 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useMemo } from "react";
|
||||
import { Button } from "../ui/button";
|
||||
import { ArrowLeft, ArrowRight, SortAsc, SortDesc } from "lucide-react";
|
||||
import { usePeopleFilterContext } from "@/contexts/PeopleFilterContext";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Label } from "../ui/label";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "../ui/dropdown-menu";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
export function PeopleFilters() {
|
||||
const router = useRouter();
|
||||
const { updateContext, page, maximumAssetCount } = usePeopleFilterContext();
|
||||
|
||||
const [nextPage, prevPage] = useMemo(() => {
|
||||
const pageNum = parseInt(page.toString() || "1", 10);
|
||||
return [pageNum + 1, pageNum - 1];
|
||||
}, [page]);
|
||||
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="Max Asset Count"
|
||||
defaultValue={maximumAssetCount}
|
||||
onChange={(e) => {
|
||||
try {
|
||||
const value = parseInt(e.target.value || "0", 10);
|
||||
updateContext({ maximumAssetCount: value });
|
||||
} catch (e) {
|
||||
updateContext({ maximumAssetCount: 0 });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-1">
|
||||
<Switch
|
||||
id="nameLessOnly"
|
||||
onCheckedChange={(checked) => {
|
||||
updateContext({ nameLessOnly: checked, page: 1 });
|
||||
}}
|
||||
/>
|
||||
<Label className="text-nowrap" htmlFor="nameLessOnly">
|
||||
Show only Nameless
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
disabled={prevPage < 1}
|
||||
onClick={() => updateContext({ page: prevPage })}
|
||||
>
|
||||
<ArrowLeft size={16} />
|
||||
</Button>
|
||||
|
||||
<Button onClick={() => updateContext({ page: nextPage })}>
|
||||
<ArrowRight size={16} />
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant={"secondary"}
|
||||
onClick={() => updateContext({ page: nextPage })}
|
||||
>
|
||||
<SortDesc size={16} />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateContext({ sort: "assetCount", sortOrder: "asc" })
|
||||
}
|
||||
>
|
||||
<SortAsc size={16} />
|
||||
<span>Asset Count - ASC</span>
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateContext({ sort: "assetCount", sortOrder: "desc" })
|
||||
}
|
||||
>
|
||||
<SortDesc size={16} />
|
||||
<span>Asset Count - DESC</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateContext({ sort: "updatedAt", sortOrder: "asc" })
|
||||
}
|
||||
>
|
||||
<SortAsc size={16} />
|
||||
<span>Updated At - ASC</span>
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateContext({ sort: "updatedAt", sortOrder: "desc" })
|
||||
}
|
||||
>
|
||||
<SortDesc size={16} />
|
||||
<span>Updated At - DESC</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +1,29 @@
|
||||
import { listPeople } from "@/handlers/api/people.handler";
|
||||
import { IPersonListFilters, listPeople } from "@/handlers/api/people.handler";
|
||||
import { IPerson } from "@/types/person";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Loader from "../ui/loader";
|
||||
import PersonItem from "./PersonItem";
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { Table } from "../ui/table";
|
||||
import PersonBirthdayCell from "./PersonBirthdayCell";
|
||||
import Link from "next/link";
|
||||
import { ENV } from "@/config/environment";
|
||||
import PersonHideCell from "./PersonHideCell";
|
||||
import { PeoplePagination } from "./PeoplePagination";
|
||||
import { PeopleFilters } from "./PeopleFilters";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import PeopleFilterContext from "@/contexts/PeopleFilterContext";
|
||||
import PageLayout from "../layouts/PageLayout";
|
||||
import Header from "../shared/Header";
|
||||
|
||||
export default function PeopleList() {
|
||||
const router = useRouter()
|
||||
const { page = 1 } = router.query as { page: string }
|
||||
const router = useRouter();
|
||||
const [people, setPeople] = useState<IPerson[]>([]);
|
||||
const [count, setCount] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [filters, setFilters] = useState<IPersonListFilters>({
|
||||
page: 1,
|
||||
});
|
||||
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
return listPeople({
|
||||
page
|
||||
})
|
||||
setErrorMessage(null);
|
||||
return listPeople(filters)
|
||||
.then((response) => {
|
||||
setPeople(response.people);
|
||||
setCount(response.total);
|
||||
@@ -38,20 +36,47 @@ export default function PeopleList() {
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemove = (person: IPerson) => {
|
||||
setPeople((prev) => prev.filter((p) => {
|
||||
console.log(p.id, person.id, p.id !== person.id);
|
||||
return p.id !== person.id
|
||||
}));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!router.isReady) return;
|
||||
fetchData();
|
||||
}, [page]);
|
||||
}, [filters]);
|
||||
|
||||
console.log(people.length);
|
||||
|
||||
const renderContent = () => {
|
||||
if (loading) return <Loader />;
|
||||
if (errorMessage) return <div>{errorMessage}</div>;
|
||||
|
||||
if (loading) return <Loader />;
|
||||
if (errorMessage) return <div>{errorMessage}</div>;
|
||||
return (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-4 p-2">
|
||||
{people.map((person) => (
|
||||
<PersonItem person={person} key={person.id} onRemove={handleRemove}/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-4 p-2">
|
||||
{people.map((person) => (
|
||||
<PersonItem person={person} key={person.id}/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
<PeopleFilterContext.Provider
|
||||
value={{
|
||||
...filters,
|
||||
updateContext: (newConfig) =>
|
||||
setFilters((prev) => ({ ...prev, ...newConfig })),
|
||||
}}
|
||||
>
|
||||
<PageLayout>
|
||||
<Header
|
||||
leftComponent="Manage People"
|
||||
rightComponent={<PeopleFilters />}
|
||||
/>
|
||||
{renderContent()}
|
||||
</PageLayout>
|
||||
</PeopleFilterContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
|
||||
import { useRouter } from "next/router"
|
||||
import { useMemo } from "react"
|
||||
import { Button } from "../ui/button"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
|
||||
export function PeoplePagination() {
|
||||
const router = useRouter()
|
||||
const { pathname } = router;
|
||||
const { page = 1 } = router.query as { page: string }
|
||||
|
||||
const [nextPage, prevPage] = useMemo(() => {
|
||||
const pageNum = parseInt(page.toString() || "1", 10)
|
||||
return [pageNum + 1, pageNum - 1]
|
||||
|
||||
}, [page])
|
||||
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Link href={{
|
||||
pathname,
|
||||
query: { page: prevPage }
|
||||
}}>
|
||||
<Button
|
||||
className="w-[150px]"
|
||||
disabled={prevPage < 1}
|
||||
>
|
||||
<ArrowLeft className="mr-2" size={16} />
|
||||
Previous Page
|
||||
</Button>
|
||||
</Link>
|
||||
|
||||
<Link href={{
|
||||
pathname,
|
||||
query: { page: nextPage }
|
||||
}}>
|
||||
<Button
|
||||
className="w-[150px]"
|
||||
>
|
||||
Next Page
|
||||
<ArrowRight className="ml-2" size={16} />
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -11,11 +11,13 @@ import { ENV } from "@/config/environment";
|
||||
import { ArrowUpRight } from "lucide-react";
|
||||
import { useConfig } from "@/contexts/ConfigContext";
|
||||
import { useToast } from "../ui/use-toast";
|
||||
import { Badge } from "../ui/badge";
|
||||
|
||||
interface IProps {
|
||||
person: IPerson;
|
||||
onRemove: (person: IPerson) => void;
|
||||
}
|
||||
export default function PersonItem({ person }: IProps) {
|
||||
export default function PersonItem({ person, onRemove }: IProps) {
|
||||
const { immichURL } = useConfig();
|
||||
const { toast } = useToast();
|
||||
const [editMode, setEditMode] = useState(false);
|
||||
@@ -90,6 +92,9 @@ export default function PersonItem({ person }: IProps) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="absolute bottom-2 w-full flex justify-center items-center">
|
||||
<Badge variant={"secondary"} className="text-xs !font-medium font-mono">{person.assetCount} Assets</Badge>
|
||||
</div>
|
||||
<div className="absolute top-2 left-2 group-hover:block hidden">
|
||||
<Link
|
||||
className="bg-green-300 block rounded-lg px-2 py-1 text-sm dark:text-gray-900"
|
||||
@@ -100,7 +105,7 @@ export default function PersonItem({ person }: IProps) {
|
||||
</Link>
|
||||
</div>
|
||||
<div className="absolute top-2 right-2 ">
|
||||
<PersonMergeDropdown person={person} />
|
||||
<PersonMergeDropdown person={person} onRemove={onRemove}/>
|
||||
</div>
|
||||
</div>
|
||||
{!editMode ? (
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
@@ -11,56 +9,29 @@ import {
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { Merge } from "lucide-react";
|
||||
import { mergePerson, searchPeople } from "@/handlers/api/people.handler";
|
||||
import { IPerson } from "@/types/person";
|
||||
import { set } from "date-fns";
|
||||
import { CommandLoading } from "cmdk";
|
||||
import { Avatar } from "../ui/avatar";
|
||||
|
||||
type Status = {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
const statuses: Status[] = [
|
||||
{
|
||||
value: "backlog",
|
||||
label: "Backlog",
|
||||
},
|
||||
{
|
||||
value: "todo",
|
||||
label: "Todo",
|
||||
},
|
||||
{
|
||||
value: "in progress",
|
||||
label: "In Progress",
|
||||
},
|
||||
{
|
||||
value: "done",
|
||||
label: "Done",
|
||||
},
|
||||
{
|
||||
value: "canceled",
|
||||
label: "Canceled",
|
||||
},
|
||||
];
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useToast } from "../ui/use-toast";
|
||||
|
||||
interface PersonMergeDropdownProps {
|
||||
person: IPerson;
|
||||
onRemove?: (person: IPerson) => void;
|
||||
}
|
||||
export function PersonMergeDropdown(
|
||||
{ person }: PersonMergeDropdownProps
|
||||
) {
|
||||
const [searchedPeople, setSearchedPeople] = React.useState<IPerson[]>([]);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const searchTimer = React.useRef<NodeJS.Timeout>();
|
||||
export function PersonMergeDropdown({
|
||||
person,
|
||||
onRemove,
|
||||
}: PersonMergeDropdownProps) {
|
||||
const [searchedPeople, setSearchedPeople] = useState<IPerson[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const searchTimer = useRef<NodeJS.Timeout>();
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleSearch = (value: string) => {
|
||||
if (searchTimer.current) {
|
||||
@@ -86,20 +57,30 @@ export function PersonMergeDropdown(
|
||||
const handleSelect = (value: IPerson) => {
|
||||
setOpen(false);
|
||||
return mergePerson(person.id, value.id)
|
||||
.then(() => {
|
||||
|
||||
})
|
||||
.then(() => {
|
||||
onRemove?.(person);
|
||||
})
|
||||
.then(() => {
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Person merged successfully",
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) handleSearch("");
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-4">
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7">
|
||||
Merge
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0" side="bottom" align="center">
|
||||
</DialogTrigger>
|
||||
<DialogContent className="p-0">
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder="Change status..."
|
||||
@@ -128,8 +109,8 @@ export function PersonMergeDropdown(
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export default function Header({ leftComponent, rightComponent }: IProps) {
|
||||
<title>{leftComponent} - Immich Power Tools</title>
|
||||
</Head>
|
||||
)}
|
||||
<header key="header" className="sticky z-10 top-0 w-full flex h-14 items-center gap-4 border-b bg-muted px-4 lg:h-[60px] lg:px-6">
|
||||
<header key="header" className="sticky z-10 top-0 w-full flex h-14 items-center gap-4 border-b px-4 lg:h-[60px] lg:px-6">
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="outline" size="icon" className="shrink-0 md:hidden">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export const BASE_API_ENDPOINT = '/api';
|
||||
export const BASE_PROXY_ENDPOINT = BASE_API_ENDPOINT + '/immich-proxy';
|
||||
|
||||
export const LIST_PEOPLE_PATH = BASE_PROXY_ENDPOINT + "/people";
|
||||
export const LIST_PEOPLE_PATH = BASE_API_ENDPOINT + "/people/list";
|
||||
export const SEARCH_PEOPLE_PATH = BASE_PROXY_ENDPOINT + "/search/person";
|
||||
export const PERSON_THUBNAIL_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/thumbnail/" + id;
|
||||
export const UPDATE_PERSON_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/people/" + id;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { IPersonListFilters } from "@/handlers/api/people.handler";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
interface IPeopleFilterContext extends IPersonListFilters {
|
||||
updateContext: (newConfig: Partial<IPersonListFilters>) => void;
|
||||
}
|
||||
const PeopleFilterContext = createContext<IPeopleFilterContext>({
|
||||
page: 1,
|
||||
updateContext: () => { },
|
||||
})
|
||||
|
||||
export default PeopleFilterContext;
|
||||
|
||||
export const usePeopleFilterContext = () => {
|
||||
return useContext(PeopleFilterContext) as IPeopleFilterContext;
|
||||
}
|
||||
@@ -3,8 +3,17 @@ import { cleanUpPerson } from "@/helpers/person.helper";
|
||||
import API from "@/lib/api"
|
||||
import { IPeopleListResponse, IPerson } from "@/types/person"
|
||||
|
||||
interface IPersonListFilters {
|
||||
page: string | number;
|
||||
type ISortField = "assetCount" | "updatedAt" | "createdAt";
|
||||
|
||||
export interface IPersonListFilters {
|
||||
page: number | string;
|
||||
perPage?: number;
|
||||
nameLessOnly?: boolean | string;
|
||||
minimumAssetCount?: number;
|
||||
maximumAssetCount?: number;
|
||||
sort?: ISortField;
|
||||
sortOrder?: "asc" | "desc";
|
||||
|
||||
}
|
||||
export const listPeople = (filters: IPersonListFilters): Promise<IPeopleListResponse> => {
|
||||
return API.get(LIST_PEOPLE_PATH, filters).then((response) => {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export const stringToBoolean = (value: string | boolean): boolean => {
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
return value === 'true';
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export const cleanUpPerson = (person: IAPIPerson): IPerson => {
|
||||
return {
|
||||
...person,
|
||||
thumbnailPath: PERSON_THUBNAIL_PATH(person.id),
|
||||
birthDate: person.birthDate ? new Date(parseDate(person.birthDate, 'yyyy-MM-dd')) : null,
|
||||
birthDate: person.birthDate ? new Date(person.birthDate) : null,
|
||||
updatedAt: new Date(person.updatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import { CHART_COLORS } from "@/config/constants/chart.constant";
|
||||
import { db } from "@/config/db";
|
||||
import { stringToBoolean } from "@/helpers/data.helper";
|
||||
import { assetFaces, assets, exif, person } from "@/schema";
|
||||
import { faceSearch } from "@/schema/faceSearch.schema";
|
||||
import { cosineDistance, desc, eq, gt, ne, sql } from "drizzle-orm";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
type ISortField = "assetCount" | "updatedAt" | "createdAt";
|
||||
|
||||
interface IQuery {
|
||||
id: string;
|
||||
page: number;
|
||||
perPage: number;
|
||||
nameLessOnly: boolean | string;
|
||||
minimumAssetCount: number;
|
||||
sort: ISortField;
|
||||
sortOrder: "asc" | "desc";
|
||||
}
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
try {
|
||||
const {
|
||||
id,
|
||||
page = 1,
|
||||
perPage = 60,
|
||||
nameLessOnly = false,
|
||||
minimumAssetCount = 0,
|
||||
sort = "assetCount",
|
||||
sortOrder = "desc",
|
||||
} = req.query as any as IQuery;
|
||||
|
||||
const personRecords = await db
|
||||
.select()
|
||||
.from(person)
|
||||
.where(eq(person.id, id))
|
||||
.limit(1);
|
||||
const personRecord = personRecords?.[0];
|
||||
if (!personRecord) {
|
||||
return res.status(404).json({
|
||||
error: "Person not found",
|
||||
});
|
||||
}
|
||||
|
||||
const assetFaceRecords = await db
|
||||
.select()
|
||||
.from(assetFaces)
|
||||
.where(eq(assetFaces.personId, personRecord.id))
|
||||
.limit(1);
|
||||
const assetFaceRecord = assetFaceRecords?.[0];
|
||||
|
||||
if (!assetFaceRecord) {
|
||||
return res.status(404).json({
|
||||
error: "Person has no face",
|
||||
});
|
||||
}
|
||||
|
||||
const faceSearchRecords = await db
|
||||
.select()
|
||||
.from(faceSearch)
|
||||
.where(ne(faceSearch.faceId, assetFaceRecord.id))
|
||||
.limit(1);
|
||||
|
||||
const faceSearchRecord = faceSearchRecords?.[0];
|
||||
if (!faceSearchRecord) {
|
||||
return res.status(404).json({
|
||||
error: "No similar faces found",
|
||||
});
|
||||
}
|
||||
|
||||
const similarity = sql<number>`1 - (${cosineDistance(
|
||||
faceSearch.embedding,
|
||||
faceSearchRecord.embedding
|
||||
)})`;
|
||||
|
||||
const people = await db
|
||||
.select({
|
||||
id: person.id,
|
||||
name: person.name,
|
||||
thumbnailPath: person.thumbnailPath,
|
||||
birthDate: person.birthDate,
|
||||
isHidden: person.isHidden,
|
||||
updatedAt: person.updatedAt,
|
||||
assetId: assetFaces.assetId,
|
||||
similarity,
|
||||
})
|
||||
.from(faceSearch)
|
||||
.leftJoin(assetFaces, eq(assetFaces.id, faceSearch.faceId))
|
||||
.leftJoin(person, eq(person.id, assetFaces.personId))
|
||||
.where(gt(similarity, 0.5))
|
||||
.limit(4);
|
||||
|
||||
console.log(people);
|
||||
|
||||
return res.status(200).json({
|
||||
people,
|
||||
total: 10,
|
||||
});
|
||||
} catch (error: any) {
|
||||
res.status(500).json({
|
||||
error: error?.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import { CHART_COLORS } from "@/config/constants/chart.constant";
|
||||
import { db } from "@/config/db";
|
||||
import { stringToBoolean } from "@/helpers/data.helper";
|
||||
import { assetFaces, assets, exif, person } from "@/schema";
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
gte,
|
||||
isNotNull,
|
||||
isNull,
|
||||
lte,
|
||||
ne,
|
||||
sql,
|
||||
sum,
|
||||
} from "drizzle-orm";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
type ISortField = "assetCount" | "updatedAt" | "createdAt";
|
||||
|
||||
interface IQuery {
|
||||
page: number;
|
||||
perPage: number;
|
||||
nameLessOnly: boolean | string;
|
||||
maximumAssetCount: number;
|
||||
sort: ISortField;
|
||||
sortOrder: "asc" | "desc";
|
||||
}
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
try {
|
||||
const {
|
||||
page = 1,
|
||||
perPage = 60,
|
||||
nameLessOnly = false,
|
||||
maximumAssetCount: maxValue = 1000000,
|
||||
sort = "assetCount",
|
||||
sortOrder = "desc",
|
||||
} = req.query as any as IQuery;
|
||||
|
||||
const maximumAssetCount = !maxValue || maxValue <= 0 ? 1000000 : maxValue;
|
||||
const whereClause = and(
|
||||
eq(person.isHidden, false),
|
||||
isNull(assets.duplicateId),
|
||||
eq(assets.isVisible, true),
|
||||
eq(assets.isArchived, false),
|
||||
stringToBoolean(nameLessOnly) ? eq(person.name, "") : undefined
|
||||
);
|
||||
|
||||
let query = db
|
||||
.select({
|
||||
id: person.id,
|
||||
name: person.name,
|
||||
thumbnailPath: person.thumbnailPath,
|
||||
birthDate: person.birthDate,
|
||||
isHidden: person.isHidden,
|
||||
updatedAt: person.updatedAt,
|
||||
assetCount: count(assetFaces.id),
|
||||
})
|
||||
.from(person)
|
||||
.leftJoin(assetFaces, eq(assetFaces.personId, person.id))
|
||||
.leftJoin(assets, eq(assets.id, assetFaces.assetId))
|
||||
.where(whereClause)
|
||||
.having(lte(count(assetFaces.id), maximumAssetCount))
|
||||
.groupBy(person.id);
|
||||
|
||||
let sortedQuery;
|
||||
if (sort === "assetCount") {
|
||||
sortedQuery = query.orderBy(
|
||||
sortOrder === "asc"
|
||||
? asc(count(assetFaces.id))
|
||||
: desc(count(assetFaces.id))
|
||||
);
|
||||
} else if (sort === "updatedAt") {
|
||||
sortedQuery = query.orderBy(
|
||||
sortOrder === "asc" ? asc(person.updatedAt) : desc(person.updatedAt)
|
||||
);
|
||||
}
|
||||
const people = await query.limit(perPage).offset((page - 1) * perPage);
|
||||
|
||||
|
||||
|
||||
return res.status(200).json({
|
||||
people,
|
||||
total: 10,
|
||||
});
|
||||
} catch (error: any) {
|
||||
res.status(500).json({
|
||||
error: error?.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-11
@@ -7,15 +7,5 @@ import { PeoplePagination } from "@/components/people/PeoplePagination";
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<PageLayout>
|
||||
<Header
|
||||
leftComponent="Manage People"
|
||||
rightComponent={
|
||||
<PeoplePagination />
|
||||
}
|
||||
/>
|
||||
<PeopleList />
|
||||
</PageLayout>
|
||||
);
|
||||
return <PeopleList />
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { pgTable, uuid, integer } from "drizzle-orm/pg-core";
|
||||
|
||||
export const assetFaces = pgTable("asset_faces", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
assetId: uuid("assetId").notNull(),
|
||||
personId: uuid("personId"),
|
||||
imageWidth: integer("imageWidth").notNull().default(0),
|
||||
imageHeight: integer("imageHeight").notNull().default(0),
|
||||
boundingBoxX1: integer("boundingBoxX1").notNull().default(0),
|
||||
boundingBoxY1: integer("boundingBoxY1").notNull().default(0),
|
||||
boundingBoxX2: integer("boundingBoxX2").notNull().default(0),
|
||||
boundingBoxY2: integer("boundingBoxY2").notNull().default(0),
|
||||
});
|
||||
@@ -28,7 +28,7 @@ export const assets = pgTable('assets', {
|
||||
isExternal: boolean('isExternal').default(false).notNull(),
|
||||
deletedAt: timestamp('deletedAt', { withTimezone: true }),
|
||||
localDateTime: timestamp('localDateTime', { withTimezone: true }).notNull(),
|
||||
// stackId: uuid('stackId').references(() => assetStack.id, { onDelete: 'set null', onUpdate: 'cascade' }),
|
||||
stackId: uuid('stackId'),
|
||||
duplicateId: uuid('duplicateId'),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { pgTable, uuid, vector } from "drizzle-orm/pg-core";
|
||||
|
||||
export const faceSearch = pgTable("face_search", {
|
||||
faceId: uuid("faceId").notNull(),
|
||||
embedding: vector("embedding", {
|
||||
dimensions: 512,
|
||||
}).notNull(),
|
||||
});
|
||||
|
||||
+5
-1
@@ -1,2 +1,6 @@
|
||||
export { assets } from './assets.schema';
|
||||
export { exif } from './exif.schema';
|
||||
export { exif } from './exif.schema';
|
||||
export { person } from './person.schema';
|
||||
export { assetFaces } from './assetFaces.schema';
|
||||
export { users } from './users.schema';
|
||||
export * from './relationships';
|
||||
@@ -0,0 +1,14 @@
|
||||
import { pgTable, uuid, varchar, timestamp, boolean, date, pgEnum } from "drizzle-orm/pg-core";
|
||||
|
||||
|
||||
export const person = pgTable("person", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
createdAt: timestamp("createdAt", { withTimezone: true }).defaultNow(),
|
||||
updatedAt: timestamp("updatedAt", { withTimezone: true }).defaultNow(),
|
||||
ownerId: uuid("ownerId").notNull(),
|
||||
name: varchar("name").notNull().default(''),
|
||||
thumbnailPath: varchar("thumbnailPath").notNull().default(''),
|
||||
isHidden: boolean("isHidden").notNull().default(false),
|
||||
birthDate: date("birthDate", { mode: "date" }),
|
||||
faceAssetId: uuid("faceAssetId"),
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { assetFaces } from "./assetFaces.schema";
|
||||
import { assets } from "./assets.schema";
|
||||
import { person } from "./person.schema";
|
||||
import { users } from "./users.schema";
|
||||
import { faceSearch } from "./faceSearch.schema";
|
||||
|
||||
// Assuming there are relations to be defined with `assets` and `person`
|
||||
export const assetFacesRelations = relations(assetFaces, ({ one }) => ({
|
||||
asset: one(assets, {
|
||||
fields: [assetFaces.assetId],
|
||||
references: [assets.id],
|
||||
}),
|
||||
person: one(person, {
|
||||
fields: [assetFaces.personId],
|
||||
references: [person.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
// Assuming there are relations to be defined with `users` and `asset_faces`
|
||||
export const personRelations = relations(person, ({ one }) => ({
|
||||
owner: one(users, {
|
||||
fields: [person.ownerId],
|
||||
references: [users.id],
|
||||
}),
|
||||
faceAsset: one(assetFaces, {
|
||||
fields: [person.faceAssetId],
|
||||
references: [assetFaces.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
// Assuming there are relations to be defined with `asset_faces`
|
||||
export const faceSearchRelations = relations(faceSearch, ({ one }) => ({
|
||||
face: one(assetFaces, {
|
||||
fields: [faceSearch.faceId],
|
||||
references: [assetFaces.id],
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,23 @@
|
||||
import { pgTable, uuid, varchar, timestamp, boolean, bigint } from "drizzle-orm/pg-core";
|
||||
|
||||
export const users = pgTable("users", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
email: varchar("email").notNull(),
|
||||
password: varchar("password").notNull().default(''),
|
||||
createdAt: timestamp("createdAt", { withTimezone: true }).defaultNow(),
|
||||
profileImagePath: varchar("profileImagePath").notNull().default(''),
|
||||
isAdmin: boolean("isAdmin").notNull().default(false),
|
||||
shouldChangePassword: boolean("shouldChangePassword").notNull().default(true),
|
||||
deletedAt: timestamp("deletedAt", { withTimezone: true }),
|
||||
oauthId: varchar("oauthId").notNull().default(''),
|
||||
updatedAt: timestamp("updatedAt", { withTimezone: true }).defaultNow(),
|
||||
storageLabel: varchar("storageLabel"),
|
||||
name: varchar("name").notNull().default(''),
|
||||
quotaSizeInBytes: bigint("quotaSizeInBytes", {
|
||||
mode: 'bigint'
|
||||
}),
|
||||
quotaUsageInBytes: bigint("quotaUsageInBytes", {
|
||||
mode: 'bigint'
|
||||
}).notNull(),
|
||||
status: varchar("status").notNull().default('active'),
|
||||
});
|
||||
Vendored
+1
@@ -5,6 +5,7 @@ export interface IPerson {
|
||||
thumbnailPath: string;
|
||||
isHidden: boolean;
|
||||
updatedAt: Date;
|
||||
assetCount: number;
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user