Merge branch 'main' into ui-enhance

This commit is contained in:
Sai charan Guntupalli authored and GitHub committed 2024-09-14 12:53:15 +05:30
commit 44d7bf0404
33 files changed
+441 -54

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
run: |
docker build --build-arg VERSION=${{ needs.release.outputs.new-release-version }} \
docker build --build-arg BUILD_VERSION=${{ needs.release.outputs.new-release-version }} VERSION=${{ needs.release.outputs.new-release-version }} \
-t ghcr.io/${{ github.repository }}:${{ needs.release.outputs.new-release-version }} \
-t ghcr.io/${{ github.repository }}:latest .
docker push ghcr.io/${{ github.repository }}:latest
BIN
View File
Binary file not shown.
+2
View File
@@ -10,3 +10,5 @@ services:
- "3000:3000"
env_file:
- .env
environment:
- BUILD_VERSION=${BUILD_VERSION}
+11 -1
View File
@@ -1,10 +1,20 @@
/** @type {import('next').NextConfig} */
import { readFileSync } from 'fs';
const { version } = JSON.parse(readFileSync('./package.json', 'utf-8'));
console.log(`Version: ${version}`);
const nextConfig = {
reactStrictMode: false,
output: 'standalone',
images: {
unoptimized: true,
}
},
env: {
VERSION: process.env.BUILD_VERSION || version,
},
};
export default nextConfig;
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "immich-power-tools",
"version": "0.5.0",
"version": "0.6.1",
"private": true,
"scripts": {
"dev": "next dev",
@@ -33,6 +33,7 @@
"@types/qs": "^6.9.15",
"@types/react-calendar-heatmap": "^1.6.7",
"axios": "^1.7.4",
"chrono-node": "^1.4.9",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "1.0.0",
@@ -49,6 +50,7 @@
"react-day-picker": "9.0.8",
"react-dom": "^18",
"react-grid-gallery": "^1.0.1",
"react-query": "^3.39.3",
"recharts": "^2.12.7",
"sass": "^1.77.8",
"tailwind-merge": "^2.5.2",
@@ -8,8 +8,11 @@ import Lightbox, { SlideImage, SlideTypes } from "yet-another-react-lightbox";
import Captions from "yet-another-react-lightbox/plugins/captions";
import { CalendarArrowDown, CalendarArrowUp, Hourglass } from "lucide-react";
import Video from "yet-another-react-lightbox/plugins/video";
import { useConfig } from "@/contexts/ConfigContext";
import LazyImage from "@/components/ui/lazy-image";
export default function PotentialAlbumsAssets() {
const { exImmichUrl } = useConfig();
const { startDate, selectedIds, assets, updateContext } =
usePotentialAlbumContext();
@@ -37,12 +40,22 @@ export default function PotentialAlbumsAssets() {
width: p.exifImageWidth as number,
height: p.exifImageHeight as number,
isSelected: selectedIds.includes(p.id),
tags: [
{
title: "Immich Link",
value: (
<a href={exImmichUrl + "/photos/" + p.id} target="_blank">
Open in Immich
</a>
),
},
],
}));
}, [assets, selectedIds]);
const slides = useMemo(
() =>
images.map(({ original, width, height, type, videoURL }) => ({
images.map(({ original, width, height, type, videoURL}) => ({
src: original,
width,
height,
@@ -111,6 +124,14 @@ export default function PotentialAlbumsAssets() {
onClick={handleClick}
enableImageSelection={true}
onSelect={handleSelect}
thumbnailImageComponent={LazyImage}
tagStyle={{
color: "white",
fontSize: "12px",
backgroundColor: "rgba(0, 0, 0)",
padding: "2px",
borderRadius: "5px",
}}
/>
</div>
</>
@@ -5,8 +5,10 @@ import {
import React, { use, useEffect, useState } from "react";
import PotentialDateItem from "./PotentialDateItem";
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { useRouter } from "next/router";
export default function PotentialAlbumsDates() {
const router = useRouter();
const { updateContext } = usePotentialAlbumContext();
const [dateRecords, setDateRecords] = React.useState<
IPotentialAlbumsDatesResponse[]
@@ -25,6 +27,11 @@ export default function PotentialAlbumsDates() {
const handleSelect = (date: string) => {
updateContext({ startDate: date });
router.push({
pathname: router.pathname,
query: { startDate: date },
})
};
useEffect(() => {
@@ -18,6 +18,7 @@ import { listMissingLocationAssets } from "@/handlers/api/asset.handler";
import { formatDate, parseDate } from "@/helpers/date.helper";
import { addDays } from "date-fns";
import { useConfig } from "@/contexts/ConfigContext";
import LazyImage from "@/components/ui/lazy-image";
export default function MissingLocationAssets() {
const { exImmichUrl } = useConfig();
@@ -125,6 +126,7 @@ export default function MissingLocationAssets() {
onClick={handleClick}
enableImageSelection={true}
onSelect={handleSelect}
thumbnailImageComponent={LazyImage}
tagStyle={{
color: "white",
fontSize: "12px",
@@ -3,13 +3,14 @@ import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { IMissingLocationDatesResponse, listMissingLocationDates } from "@/handlers/api/asset.handler";
import MissingLocationDateItem from "./MissingLocationDateItem";
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
import { useRouter } from "next/router";
export default function MissingLocationDates() {
const { updateContext } = useMissingLocationContext();
const router = useRouter();
const [dateRecords, setDateRecords] = React.useState<
IMissingLocationDatesResponse[]
>([]);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -23,6 +24,10 @@ export default function MissingLocationDates() {
const handleSelect = (date: string) => {
updateContext({ startDate: date });
router.push({
pathname: router.pathname,
query: { startDate: date },
});
};
useEffect(() => {
+16 -13
View File
@@ -10,11 +10,14 @@ import { ArrowRight, TriangleAlert } from "lucide-react";
import Link from "next/link";
import { LoginForm } from "../auth/LoginForm";
import { useConfig } from "@/contexts/ConfigContext";
import { queryClient } from "@/config/rQuery";
import { QueryClientProvider } from "react-query";
type RootLayoutProps = {
children: ReactNode;
};
export default function RootLayout({ children }: RootLayoutProps) {
const { immichURL, exImmichUrl } = useConfig();
const [user, setUser] = useState<IUser | null>(null);
@@ -34,9 +37,7 @@ export default function RootLayout({ children }: RootLayoutProps) {
.finally(() => setLoading(false));
};
const handleLoginCompletion = (user: IUser) => {
setUser(user);
}
const handleLoginCompletion = (user: IUser) => setUser(user);
useEffect(() => {
fetchData();
@@ -86,15 +87,17 @@ export default function RootLayout({ children }: RootLayoutProps) {
if (!user) return <LoginForm onLogin={handleLoginCompletion} />;
return (
<UserContext.Provider value={{
...user,
updateContext: setUser,
}}>
<div className="grid max-h-screen min-h-screen w-full md:grid-cols-[200px_1fr] lg:grid-cols-[240px_1fr]">
<Sidebar />
<div className="flex flex-col">{children}</div>
<Toaster />
</div>
</UserContext.Provider>
<QueryClientProvider client={queryClient}>
<UserContext.Provider value={{
...user,
updateContext: setUser,
}}>
<div className="grid max-h-screen min-h-screen w-full md:grid-cols-[200px_1fr] lg:grid-cols-[240px_1fr]">
<Sidebar />
<div className="flex flex-col">{children}</div>
<Toaster />
</div>
</UserContext.Provider>
</QueryClientProvider>
);
}
+23 -10
View File
@@ -13,11 +13,24 @@ import {
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { Input } from "../ui/input";
import { IPersonListFilters } from "@/handlers/api/people.handler";
import AssetFilter from "../shared/common/AssetFilter";
export function PeopleFilters() {
const router = useRouter();
const { updateContext, page, maximumAssetCount } = usePeopleFilterContext();
const handleChange = (data: Partial<IPersonListFilters>) => {
updateContext(data);
router.push({
pathname: router.pathname,
query: {
...router.query,
...data,
page: undefined,
},
});
}
const [nextPage, prevPage] = useMemo(() => {
const pageNum = parseInt(page.toString() || "1", 10);
return [pageNum + 1, pageNum - 1];
@@ -32,9 +45,9 @@ export function PeopleFilters() {
onChange={(e) => {
try {
const value = parseInt(e.target.value || "0", 10);
updateContext({ maximumAssetCount: value });
handleChange({ maximumAssetCount: value });
} catch (e) {
updateContext({ maximumAssetCount: 0 });
handleChange({ maximumAssetCount: 0 });
}
}}
/>
@@ -42,7 +55,7 @@ export function PeopleFilters() {
<Switch
id="nameLessOnly"
onCheckedChange={(checked) => {
updateContext({ nameLessOnly: checked, page: 1 });
handleChange({ nameLessOnly: checked, page: 1 });
}}
/>
<Label className="text-nowrap" htmlFor="nameLessOnly">
@@ -52,19 +65,19 @@ export function PeopleFilters() {
<Button
disabled={prevPage < 1}
onClick={() => updateContext({ page: prevPage })}
onClick={() => handleChange({ page: prevPage })}
>
<ArrowLeft size={16} />
</Button>
<Button onClick={() => updateContext({ page: nextPage })}>
<Button onClick={() => handleChange({ page: nextPage })}>
<ArrowRight size={16} />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant={"secondary"}
onClick={() => updateContext({ page: nextPage })}
onClick={() => handleChange({ page: nextPage })}
>
<SortDesc size={16} />
</Button>
@@ -72,7 +85,7 @@ export function PeopleFilters() {
<DropdownMenuContent>
<DropdownMenuItem
onClick={() =>
updateContext({ sort: "assetCount", sortOrder: "asc" })
handleChange({ sort: "assetCount", sortOrder: "asc" })
}
>
<SortAsc size={16} />
@@ -81,7 +94,7 @@ export function PeopleFilters() {
<DropdownMenuItem
onClick={() =>
updateContext({ sort: "assetCount", sortOrder: "desc" })
handleChange({ sort: "assetCount", sortOrder: "desc" })
}
>
<SortDesc size={16} />
@@ -91,7 +104,7 @@ export function PeopleFilters() {
<DropdownMenuItem
onClick={() =>
updateContext({ sort: "updatedAt", sortOrder: "asc" })
handleChange({ sort: "updatedAt", sortOrder: "asc" })
}
>
<SortAsc size={16} />
@@ -100,7 +113,7 @@ export function PeopleFilters() {
<DropdownMenuItem
onClick={() =>
updateContext({ sort: "updatedAt", sortOrder: "desc" })
handleChange({ sort: "updatedAt", sortOrder: "desc" })
}
>
<SortDesc size={16} />
+2 -1
View File
@@ -16,6 +16,7 @@ export default function PeopleList() {
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [filters, setFilters] = useState<IPersonListFilters>({
...router.query,
page: 1,
});
@@ -53,7 +54,7 @@ export default function PeopleList() {
if (errorMessage) return <div>{errorMessage}</div>;
return (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-1 p-2">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-1 p-2">
{people.map((person) => (
<PersonItem person={person} key={person.id} onRemove={handleRemove}/>
))}
+36 -5
View File
@@ -3,6 +3,12 @@ import React, { useState } from 'react'
import { DatePicker } from '../ui/datepicker'
import { updatePerson } from '@/handlers/api/people.handler';
import { formatDate } from '@/helpers/date.helper';
import { Input } from '../ui/input';
import { useToast } from '../ui/use-toast';
// @ts-ignore
import chrono from 'chrono-node'
interface IProps {
person: IPerson
@@ -11,19 +17,22 @@ interface IProps {
export default function PersonBirthdayCell(
{ person }: IProps
) {
const [formData, setFormData] = useState(person);
const [loading, setLoading] = useState(false);
const { toast } = useToast();
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [textDate, setTextDate] = useState<string | null>(person.birthDate ? formatDate(person.birthDate?.toString(), 'PPP'): "");
const handleEdit = (date?: Date | null) => {
if (!date) return;
const formatedDate = formatDate(date.toString(), 'yyyy-MM-dd');
const formatedDate = date ? formatDate(date.toString(), 'yyyy-MM-dd') : null;
setLoading(true);
return updatePerson(person.id, {
birthDate: formatedDate,
})
.then(() => {
toast({
title: "Success",
description: "Person updated successfully",
})
})
.catch(() => {})
.finally(() => {
@@ -33,5 +42,27 @@ export default function PersonBirthdayCell(
return <DatePicker date={person.birthDate} onSelect={handleEdit}/>
return (
<div className='flex gap-1'>
<Input
className=''
value={textDate || ""}
placeholder='Enter a date'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const parsedDate = chrono.parseDate(textDate || "");
if (parsedDate) {
handleEdit(parsedDate);
setTextDate(formatDate(parsedDate.toString(), 'PPP'));
} else {
handleEdit(null);
}
}
}}
disabled={loading}
onChange={(e) => setTextDate(e.target.value)}
/>
<DatePicker date={person.birthDate} onSelect={handleEdit} iconOnly/>
</div>
)
}
+1 -1
View File
@@ -86,7 +86,7 @@ export default function PersonItem({ person, onRemove }: IProps) {
}}
>
<Avatar
className="w-full h-auto rounded-lg"
className="w-full min-h-full h-auto rounded-lg"
src={person.thumbnailPath}
alt={person.name}
/>
+5 -2
View File
@@ -8,7 +8,7 @@ import { useToast } from "../ui/use-toast";
export default function ProfileInfo() {
const { updateContext, ...user } = useCurrentUser()
const { immichURL, exImmichUrl } = useConfig();
const { immichURL, exImmichUrl, version } = useConfig();
const toast = useToast();
const handleLogout = () => logoutUser()
@@ -44,7 +44,7 @@ export default function ProfileInfo() {
</>
)}
</div>
<div className="border text-muted-foreground text-xs text-center py-2">
<div className="border text-muted-foreground text-xs py-2 flex justify-between items-center px-2">
<p>
Made with <span className="text-red-500">&hearts;</span> by{" "}
<Link
@@ -55,6 +55,9 @@ export default function ProfileInfo() {
@zathvarun
</Link>
</p>
<Link target="_blank" href={`https://github.com/varun-raj/immich-power-tools/releases/tag/v${version}`}>
v{version}
</Link>
</div>
</>
);
@@ -0,0 +1,57 @@
import { Combobox } from '@/components/ui/combobox';
import { getFilters } from '@/handlers/api/common.handler';
import React, { useMemo, useState } from 'react'
import { useQuery } from 'react-query';
const fields = [
"make",
"model",
"lensModel",
"city",
"state",
"country",
"projectionType",
"colorspace",
"bitsPerSample",
"rating",
];
const formattedFields = fields.map(field => ({
label: field.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()),
value: field
}));
export default function AssetFilter() {
const [selectedField, setSelectedField] = useState<string | null>(null);
const { data } = useQuery('filters', getFilters)
const options = useMemo(() => {
if (!selectedField) return formattedFields;
const { filters } = data;
if (!filters) return formattedFields;
const field = filters[selectedField];
if (!field) return [];
return field.map((value: string) => ({
label: value,
value
}));
}, [selectedField, data]);
return (
<Combobox
options={options}
closeOnSelect={!!selectedField}
onSelect={(value) => {
if (!selectedField) setSelectedField(value);
}}
onOpenChange={(open) => {
if (!open) setSelectedField(null);
}}
/>
)
}
+78
View File
@@ -0,0 +1,78 @@
"use client"
import * as React from "react"
import { Check, Filter } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
export interface IComboBoxOption { label: string; value: string }
export interface IComboBoxProps {
options: IComboBoxOption[]
onSelect?: (value: string) => void
onOpenChange?: (open: boolean) => void
closeOnSelect?: boolean
}
export function Combobox(
{ options, onSelect, onOpenChange, closeOnSelect }: IComboBoxProps
) {
const [open, setOpen] = React.useState(false)
const [value, setValue] = React.useState("")
return (
<Popover open={open} onOpenChange={(openState) => {
setOpen(openState)
onOpenChange?.(openState)
}}>
<PopoverTrigger asChild>
<Filter />
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<Command>
<CommandInput placeholder="Search framework..." />
<CommandList>
<CommandEmpty>No framework found.</CommandEmpty>
<CommandGroup>
{options.map((option) => (
<CommandItem
key={option.value}
value={option.value}
onSelect={(currentValue) => {
setValue(currentValue === value ? "" : currentValue)
onSelect?.(currentValue)
if (closeOnSelect) {
setOpen(false)
}
}}
>
<Check
className={cn(
"mr-2 h-4 w-4 min-h-4 min-w-4",
value === option.value ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{option.label.trim()}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
+5 -4
View File
@@ -16,9 +16,10 @@ import {
interface IProps {
date?: Date | null
onSelect?: (date?: Date | null) => any
iconOnly?: boolean
}
export function DatePicker(
{ date: _date, onSelect }: IProps
{ date: _date, onSelect, iconOnly }: IProps
) {
const [date, setDate] = React.useState<Date | null>(_date || null)
@@ -32,12 +33,12 @@ export function DatePicker(
<Button
variant={"outline"}
className={cn(
"justify-start text-left font-normal",
"justify-start text-left font-normal flex gap-1",
!date && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, "PPP") : <span>Pick a date</span>}
<CalendarIcon className="h-3 w-3" />
{!iconOnly && <span>{date ? format(date, "PPP") : <span>Pick a date</span>}</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
+44
View File
@@ -0,0 +1,44 @@
/* eslint-disable @next/next/no-img-element */
import React, { useEffect } from 'react'
import { Image, ImageExtended, ThumbnailImageProps } from 'react-grid-gallery'
interface LazyImageProps extends ThumbnailImageProps<ImageExtended<Image>> {}
export default function LazyImage(
props: LazyImageProps
) {
const [isVisible, setIsVisible] = React.useState(false)
const imageRef = React.useRef<HTMLImageElement>(null)
const setupObserver = () => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true)
observer.disconnect()
}
})
})
if (imageRef.current) {
observer.observe(imageRef.current)
}
return observer
}
useEffect(() => {
const observer = setupObserver()
return () => {
observer?.disconnect()
}
}, [])
if (!isVisible) return (
<div style={{ height: props.height }} ref={imageRef} />
)
return (
<img {...props.imageProps} alt={props.imageProps.alt || ""} title="" />
)
}
+1
View File
@@ -5,6 +5,7 @@ export const ENV = {
DATABASE_URL: (process.env.DATABASE_URL || `postgresql://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${(process.env.DB_HOST || 'immich_postgres')}:${(process.env.DB_PORT || '5432')}/${process.env.DB_DATABASE_NAME}`),
JWT_SECRET: process.env.JWT_SECRET as string,
SECURE_COOKIE: process.env.SECURE_COOKIE === 'true',
VERSION: process.env.VERSION
};
+5
View File
@@ -0,0 +1,5 @@
import {
QueryClient,
} from 'react-query'
export const queryClient = new QueryClient()
+3 -1
View File
@@ -40,4 +40,6 @@ export const SEARCH_PLACES_PATH = BASE_PROXY_ENDPOINT + "/search/places";
export const ASSET_STATISTICS = BASE_PROXY_ENDPOINT + "/assets/statistics";
export const LIVE_PHOTO_STATISTICS = BASE_API_ENDPOINT + "/analytics/statistics/livephoto";
export const HEATMAP_DATA = BASE_API_ENDPOINT + "/analytics/statistics/heatmap";
export const HEATMAP_DATA = BASE_API_ENDPOINT + "/analytics/statistics/heatmap";
// Common
export const GET_FILTERS = BASE_API_ENDPOINT + "/filters/asset-filters";
+2
View File
@@ -3,11 +3,13 @@ import { createContext, useContext } from "react";
interface ConfigContextType {
immichURL: string;
exImmichUrl: string;
version?: string;
}
const ConfigContext = createContext<ConfigContextType>({
immichURL: "",
exImmichUrl: "",
version: "",
});
export default ConfigContext;
+19
View File
@@ -0,0 +1,19 @@
import { createContext, useContext } from "react";
type FilterValue = string | string[] | number | number[] | undefined;
interface ExifFiltersType {
updateContext: (key: string, value: FilterValue) => void;
[key: string]: FilterValue | ((key: string, value: FilterValue) => void);
}
const ExifFilters = createContext<ExifFiltersType>({
updateContext: () => {},
});
export default ExifFilters;
export const useExifFilters = () => {
const context = useContext(ExifFilters) as ExifFiltersType;
return context;
}
+5 -1
View File
@@ -1,4 +1,4 @@
import { SEARCH_PLACES_PATH } from "@/config/routes";
import { GET_FILTERS, SEARCH_PLACES_PATH } from "@/config/routes";
import API from "@/lib/api";
import { IPlace } from "@/types/common";
@@ -6,3 +6,7 @@ export const searchPlaces = async (name: string): Promise<IPlace[]> => {
return API.get(SEARCH_PLACES_PATH, { name });
}
export const getFilters = async () => {
return API.get(GET_FILTERS);
}
+1 -1
View File
@@ -26,7 +26,7 @@ export const listPeople = (filters: IPersonListFilters): Promise<IPeopleListResp
export const updatePerson = (id: string, data: Partial<{
name: string;
birthDate: string;
birthDate: string | null;
isHidden: boolean;
}>) => {
return API.put(UPDATE_PERSON_PATH(id), data)
+4 -4
View File
@@ -4,14 +4,12 @@ import type { AppProps } from "next/app";
import { ThemeProvider } from "next-themes";
import { ENV } from "@/config/environment";
import ConfigContext from "@/contexts/ConfigContext";
import { useEffect, useRef, useState } from "react";
import { getMe } from "@/handlers/api/user.handler";
import { db } from "@/config/db";
import { useRef } from "react";
interface AppPropsWithProps extends AppProps {
props: {
immichURL: string;
exImmichUrl: string;
version?: string;
};
}
const App = ({ Component, pageProps, ...props }: AppPropsWithProps) => {
@@ -29,10 +27,12 @@ const App = ({ Component, pageProps, ...props }: AppPropsWithProps) => {
};
App.getInitialProps = async () => {
return {
props: {
exImmichUrl: ENV.EXTERNAL_IMMICH_URL,
immichURL: ENV.IMMICH_URL,
version: ENV.VERSION
},
};
};
+6 -2
View File
@@ -13,14 +13,17 @@ import PotentialAlbumContext, {
} from "@/contexts/PotentialAlbumContext";
import { addAssetToAlbum, createAlbum } from "@/handlers/api/album.handler";
import { IAlbum, IAlbumCreate } from "@/types/album";
import { useRouter } from "next/router";
import React from "react";
export default function PotentialAlbums() {
const { toast } = useToast();
const { id } = useCurrentUser();
const { query } = useRouter();
const { startDate } = query as { startDate: string };
const [config, setConfig] = React.useState<IPotentialAlbumConfig>({
startDate: undefined,
startDate: startDate || undefined,
selectedIds: [],
assets: [],
});
@@ -62,6 +65,7 @@ export default function PotentialAlbums() {
}]
})
}
return (
<PageLayout className="!p-0 !mb-0">
<Header
@@ -71,7 +75,7 @@ export default function PotentialAlbums() {
<Badge variant={"outline"}>
{config.selectedIds.length} Selected
</Badge>
{config.selectedIds.length === config.assets.length ? (
{config.selectedIds.length && config.selectedIds.length === config.assets.length ? (
<Button
variant={"outline"}
onClick={() =>
@@ -4,7 +4,7 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { parseDate } from "@/helpers/date.helper";
import { assets, exif } from "@/schema";
import { addDays } from "date-fns";
import { and, count, desc, eq, gte, isNotNull, isNull, lte, ne, sql } from "drizzle-orm";
import { and, eq, gte, isNotNull, isNull, lte, ne, sql } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
@@ -51,7 +51,6 @@ export default async function handler(
isNotNull(assets.createdAt),
gte(exif.dateTimeOriginal, startDateDate),
lte(exif.dateTimeOriginal, endDateDate),
eq(assets.type, "VIDEO"),
eq(assets.ownerId, currentUser.id),
eq(assets.isVisible, true),
));
@@ -21,6 +21,7 @@ export default async function handler(
.leftJoin(exif, eq(exif.assetId, assets.id))
.where(and(
isNull(exif.latitude),
isNotNull(assets.createdAt),
eq(assets.type, "VIDEO"),
eq(assets.ownerId, currentUser.id),
eq(assets.isVisible, true),
+64
View File
@@ -0,0 +1,64 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { assets, exif } from "@/schema";
import { IExifColumns } from "@/schema/exif.schema";
import { IUser } from "@/types/user";
import { and, eq } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
const FIELDS: IExifColumns[] = [
"make",
"model",
"lensModel",
"city",
"state",
"country",
"projectionType",
"colorspace",
"bitsPerSample",
"rating",
];
const getFilters = async (currentUser: IUser) => {
const filters: {
[key in IExifColumns]?: (string | number | Date)[];
} = {};
for (const field of FIELDS) {
const values = (await db.selectDistinct({
[field]: exif[field],
})
.from(exif)
.leftJoin(assets, eq(exif.assetId, assets.id))
.where(
and(
eq(assets.ownerId, currentUser.id),
)
)
).map((value) => value[field]).filter((value) => value !== null);
filters[field] = values;
}
return filters;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({
error: "Unauthorized",
});
}
const filters = await getFilters(currentUser);
return res.status(200).json({ filters });
} catch (error: any) {
res.status(500).json({
error: error?.message,
});
}
}
+5 -1
View File
@@ -5,6 +5,7 @@ import MissingLocationAssets from "@/components/assets/missing-location/MissingL
import MissingLocationDates from "@/components/assets/missing-location/MissingLocationDates";
import TagMissingLocationDialog from "@/components/assets/missing-location/TagMissingLocationDialog/TagMissingLocationDialog";
import PageLayout from "@/components/layouts/PageLayout";
import AssetFilter from "@/components/shared/common/AssetFilter";
import Header from "@/components/shared/Header";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -15,13 +16,16 @@ import MissingLocationContext, {
import { updateAssets } from "@/handlers/api/asset.handler";
import { IPlace } from "@/types/common";
import { useRouter } from "next/router";
import React from "react";
export default function MissingLocations() {
const { toast } = useToast();
const { query } = useRouter();
const { startDate } = query as { startDate: string };
const [config, setConfig] = React.useState<IMissingLocationConfig>({
startDate: undefined,
startDate: startDate || undefined,
selectedIds: [],
assets: [],
});
+3 -1
View File
@@ -31,4 +31,6 @@ export const exif = pgTable('exif', {
bitsPerSample: integer('bitsPerSample'),
autoStackId: varchar('autoStackId'),
rating: integer('rating'),
});
});
export type IExifColumns = keyof typeof exif.$inferSelect