Merge branch 'main' into feat/arm-build

This commit is contained in:
Lukas Jost authored and GitHub committed 2024-11-25 12:35:12 +01:00
commit 3763c4f6d1
40 files changed
+1052 -84

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
name: Build and Tag Docker Image on PR
on:
pull_request:
types: [opened, synchronize]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract PR number
id: pr-number
run: echo "PR_NUMBER=${{ github.event.number }}" >> $GITHUB_ENV
- name: Build and push Docker image
run: |
docker build --build-arg VERSION=pr-${{ env.PR_NUMBER }} \
-t ghcr.io/${{ github.repository }}:pr-${{ env.PR_NUMBER }} .
+2
View File
@@ -3,6 +3,7 @@
# Install dependencies only when needed
FROM node:18-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json ./
@@ -10,6 +11,7 @@ RUN npm install --frozen-lockfile
# Rebuild the source code only when needed
FROM node:18-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
BIN
View File
Binary file not shown.
-2
View File
@@ -10,5 +10,3 @@ services:
- "3000:3000"
env_file:
- .env
environment:
- BUILD_VERSION=${BUILD_VERSION}
+1 -7
View File
@@ -1,11 +1,5 @@
/** @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',
@@ -13,7 +7,7 @@ const nextConfig = {
unoptimized: true,
},
env: {
VERSION: process.env.BUILD_VERSION || version,
VERSION: process.env.VERSION,
},
};
+4 -1
View File
@@ -1,6 +1,6 @@
{
"name": "immich-power-tools",
"version": "0.6.1",
"version": "0.8.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -17,6 +17,7 @@
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-hover-card": "^1.1.1",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-popover": "^1.1.1",
@@ -30,6 +31,7 @@
"@tanstack/react-table": "^8.20.1",
"@types/cookie": "^0.6.0",
"@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",
@@ -44,6 +46,7 @@
"pg": "^8.12.0",
"qs": "^6.13.0",
"react": "^18",
"react-calendar-heatmap": "^1.9.0",
"react-day-picker": "9.0.8",
"react-dom": "^18",
"react-grid-gallery": "^1.0.1",
@@ -6,6 +6,9 @@ import React, { use, useEffect, useState } from "react";
import PotentialDateItem from "./PotentialDateItem";
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { useRouter } from "next/router";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { ArrowDown, ArrowUp, ArrowUpDownIcon, SortAsc, SortDesc } from "lucide-react";
export default function PotentialAlbumsDates() {
const router = useRouter();
@@ -13,13 +16,17 @@ export default function PotentialAlbumsDates() {
const [dateRecords, setDateRecords] = React.useState<
IPotentialAlbumsDatesResponse[]
>([]);
const [filters, setFilters] = useState<{ sortBy: string, sortOrder: string }>({ sortBy: "date", sortOrder: "desc" });
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const fetchData = async () => {
return listPotentialAlbumsDates({})
return listPotentialAlbumsDates({
sortBy: filters.sortBy,
sortOrder: filters.sortOrder,
})
.then(setDateRecords)
.catch(setErrorMessage)
.finally(() => setLoading(false));
@@ -31,15 +38,38 @@ export default function PotentialAlbumsDates() {
pathname: router.pathname,
query: { startDate: date },
})
};
useEffect(() => {
fetchData();
}, []);
}, [filters]);
return (
<div className="overflow-y-auto min-w-[170px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="overflow-y-auto min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="flex justify-between items-center gap-2">
<Select
defaultValue={filters.sortBy}
onValueChange={(value) => setFilters({ ...filters, sortBy: value })}
>
<SelectTrigger className="!p-2">
<SelectValue placeholder="Sort by" />
</SelectTrigger>
<SelectContent defaultValue={filters.sortBy}>
<SelectGroup title="Sort by">
<SelectLabel>Sort by</SelectLabel>
<SelectItem value="date">Date</SelectItem>
<SelectItem value="asset_count">Asset Count</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<div>
<Button variant="default" size="sm" onClick={() => setFilters({ ...filters, sortOrder: filters.sortOrder === "asc" ? "desc" : "asc" })}>
{filters.sortOrder === "asc" ? <SortAsc size={16} /> : <SortDesc size={16} />}
</Button>
</div>
</div>
{dateRecords.map((record) => (
<PotentialDateItem
key={record.date}
@@ -1,7 +1,9 @@
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { IPotentialAlbumsDatesResponse } from "@/handlers/api/album.handler";
import { formatDate } from "@/helpers/date.helper";
import { parseDate } from "@/helpers/date.helper";
import { cn } from "@/lib/utils";
import React from "react";
import React, { useMemo } from "react";
interface IProps {
record: IPotentialAlbumsDatesResponse;
@@ -9,6 +11,9 @@ interface IProps {
}
export default function PotentialDateItem({ record, onSelect }: IProps) {
const { startDate } = usePotentialAlbumContext()
const dateLabel = useMemo(() => {
return formatDate(parseDate(record.date, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
}, [record.date])
return (
<div
role="button"
@@ -19,8 +24,8 @@ export default function PotentialDateItem({ record, onSelect }: IProps) {
startDate === record.date ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
}
>
<p className="font-mono text-sm">{record.date}</p>
<p className="text-xs">{record.asset_count} Orphan Assets</p>
<p className="font-mono text-sm">{dateLabel}</p>
<p className="text-xs text-foreground/50">{record.asset_count} Orphan Assets</p>
</div>
);
}
@@ -0,0 +1,145 @@
import React, { useEffect, useState } from "react";
import { getHeatMapData } from "@/handlers/api/analytics.handler";
import { useConfig } from "@/contexts/ConfigContext";
import { Tooltip } from "@/components/ui/tooltip";
type HeatMapEntry = {
date: string;
count: number;
};
export default function AssetHeatMap() {
const { exImmichUrl } = useConfig();
const [heatMapData, setHeatMapData] = useState<HeatMapEntry[][]>([]);
const [loading, setLoading] = useState(false);
const [weeksPerMonth, setWeeksPerMonth] = useState<number[]>([]); // Store weeks per month
const fetchHeatMapData = async () => {
setLoading(true);
try {
const data = await getHeatMapData();
setHeatMapData(formatHeatMapData(data));
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchHeatMapData();
}, []);
const currentDate = new Date();
const months: string[] = [];
// Build an array of the last 12 months
for (let i = 0; i < 12; i++) {
months.push(currentDate.toLocaleString("default", { month: "short" }));
currentDate.setMonth(currentDate.getMonth() - 1);
}
months.reverse();
// Flatten heatMapData to calculate min and max counts
const flattenedData = heatMapData.flat();
const minCount = Math.min(...flattenedData.map((entry) => entry.count));
const maxCount = Math.max(...flattenedData.map((entry) => entry.count));
// Check if a week contains a date with the first day of the month
const hasFirstDayOfMonth = (arr: HeatMapEntry[]) => {
return arr.some((entry) => new Date(entry.date).getDate() === 1);
};
const getColor = (count: number) => {
if (count === -1) return "";
// Calculate thresholds based on the data range
const range = maxCount - minCount;
const threshold1 = minCount + range * 0.2;
const threshold2 = minCount + range * 0.4;
const threshold3 = minCount + range * 0.6;
const threshold4 = minCount + range * 0.8;
if (count === 0) return "bg-zinc-800";
if (count <= threshold1) return "bg-green-200";
if (count <= threshold2) return "bg-green-400";
if (count <= threshold3) return "bg-green-500";
if (count <= threshold4) return "bg-green-600";
return "bg-green-800";
};
const formatHeatMapData = (data: HeatMapEntry[]) => {
const chunks = [];
const weeksPerMonthTemp: number[] = [];
let previousMonthIndex = 0;
for (let i = 0; i < data.length; i += 7) {
const thisWeek = data.slice(i, i + 7);
chunks.push(thisWeek);
if (hasFirstDayOfMonth(thisWeek)) {
const changeWeek = (i - previousMonthIndex) / 7;
previousMonthIndex = i;
weeksPerMonthTemp.push(changeWeek);
}
}
weeksPerMonthTemp.reverse();
setWeeksPerMonth(weeksPerMonthTemp);
return chunks;
};
return (
<div className="py-4 w-full">
<h2 className="text-xl font-bold mb-4">Past Year</h2>
{loading ? (
<p>Loading...</p>
) : (
<div className="overflow-x-auto">
<table className="table-auto border-separate border-spacing-1 w-full">
<thead>
<tr>
{weeksPerMonth.map((weeks, index) => (
<th
key={index}
className="text-center"
colSpan={weeks || 4}
>
{months[index]}
</th>
))}
</tr>
</thead>
<tbody>
{heatMapData[0]?.map((_, rowIndex) => (
<tr key={rowIndex}>
{heatMapData.map((column, colIndex) => (
<td
key={colIndex}
className={`h-[20px] w-[20px] ${getColor(column[rowIndex]?.count ?? -1)} rounded`}
// style={{ width: `calc(${100 / 60}%)` }}
>
{
column[rowIndex]?.date ? (
<Tooltip delayDuration={0} content={`Date: ${column[rowIndex]?.date ?? "N/A"} - Count: ${column[rowIndex]?.count ?? 0}`}>
<a
href={`${exImmichUrl}/search?query=%7B%22takenAfter%22%3A%22${column[rowIndex]?.date ?? "N/A"}T00%3A00%3A00.000Z%22%2C%22takenBefore%22%3A%22${column[rowIndex]?.date ?? "N/A"}T23%3A59%3A59.999Z%22%7D`}
className="block h-[20px] max-w-[20px]"
target="_blank"
>
<div
className="h-[20px] max-w-[20px]"
/>
</a></Tooltip>) : <div
className="h-[20px] max-w-[20px]"
/>
}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,128 @@
import React, { useEffect, useState } from 'react'
import { IAsset } from '@/types/asset';
import { Dialog, DialogTitle, DialogHeader, DialogContent } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { formatDate, offsetDate } from '@/helpers/date.helper';
import LazyImage from '@/components/ui/lazy-image';
import Image from 'next/image';
import { updateAssets } from '@/handlers/api/asset.handler';
import { useToast } from '@/components/ui/use-toast';
interface IProps {
assets: IAsset[];
open: boolean;
toggleOpen: (open: boolean) => void;
}
export default function AssetOffsetDialog({ assets: _assets, open, toggleOpen }: IProps) {
const { toast } = useToast();
const [assets, setAssets] = useState<IAsset[]>(_assets);
const [offsetData, setOffsetData] = useState<{ days: number, hours: number, minutes: number, seconds: number, years: number }>({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
years: 0
});
const [loading, setLoading] = useState(false);
const [assetStatus, setAssetStatus] = useState<Record<string, string>>({});
const handleChange = (key: keyof typeof offsetData, value: number) => {
setOffsetData({ ...offsetData, [key]: value });
}
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log(offsetData);
setLoading(true);
const promises = assets.map(async (asset) => {
setAssetStatus({ [asset.id]: 'pending' });
await updateAssets({
ids: [asset.id],
dateTimeOriginal: offsetDate(asset.dateTimeOriginal, offsetData)
})
.then(() => {
setLoading(false);
toggleOpen(false);
})
.catch((error) => {
setLoading(false);
setAssetStatus({ [asset.id]: 'error' });
})
});
await Promise.all(promises);
setLoading(false);
toggleOpen(false);
toast({
title: 'Asset dates offset',
description: 'Asset dates have been offset',
})
}
useEffect(() => {
setAssets(_assets);
}, [_assets]);
return (
<Dialog open={open} onOpenChange={toggleOpen}>
<DialogContent className='max-w-[800px]'>
<DialogHeader>
<DialogTitle>Offset Asset Dates</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className='flex items-center gap-2'>
<div>
<Label>Years</Label>
<Input type="number" value={offsetData.years} onChange={(e) => handleChange("years", parseInt(e.target.value))} />
</div>
<div>
<Label>Days</Label>
<Input type="number" value={offsetData.days} onChange={(e) => handleChange("days", parseInt(e.target.value))} />
</div>
<div>
<Label>Hours</Label>
<Input type="number" value={offsetData.hours} onChange={(e) => handleChange("hours", parseInt(e.target.value))} />
</div>
<div>
<Label>Minutes</Label>
<Input type="number" value={offsetData.minutes} onChange={(e) => handleChange("minutes", parseInt(e.target.value))} />
</div>
<div>
<Label>Seconds</Label>
<Input type="number" value={offsetData.seconds} onChange={(e) => handleChange("seconds", parseInt(e.target.value))} />
</div>
<Button disabled={loading} type="submit">Offset Dates</Button>
</form>
<div className='grid grid-cols-3 gap-4 py-2 overflow-y-auto max-h-[500px]'>
{assets.map((asset) => (
<div key={asset.id} >
<div className='relative w-full h-full rounded-md border overflow-hidden' >
{assetStatus[asset.id] === 'pending' ? <div className='absolute text-xs text-center bottom-0 left-0 right-0 bg-blue-500/50 text-white p-2'>
<p className='text-white'>Offsetting...</p>
</div> : (
<div className='absolute text-xs text-center bottom-0 left-0 right-0 bg-green-500/50 text-white p-2'>{formatDate(offsetDate(asset.dateTimeOriginal, offsetData), 'PPpp')} </div>
)}
<Image
src={asset.previewUrl}
alt={asset.originalFileName}
width={300}
height={300}
objectPosition='cover'
style={{
objectFit: 'cover',
overflow: 'hidden',
height: '100%',
width: '100%'
}}
/>
<div className='absolute text-xs text-center top-0 left-0 right-0 bg-red-500/50 text-white p-2'>{formatDate(asset.dateTimeOriginal, 'PPpp')}</div>
</div>
</div>
))}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,31 @@
import { Button } from '@/components/ui/button'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { IAsset } from '@/types/asset';
import { DotsVerticalIcon, HamburgerMenuIcon } from '@radix-ui/react-icons';
import { Clock, PlusIcon } from 'lucide-react'
import React, { useState } from 'react'
import AssetOffsetDialog from './AssetOffsetDialog';
interface IProps {
onAdd?: () => void;
assets: IAsset[];
}
export default function AssetsOptions({ onAdd, assets }: IProps) {
const [open, setOpen] = useState(false);
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild className='cursor-pointer'>
<HamburgerMenuIcon className="w-4 h-4" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem className='flex items-center gap-2' onSelect={() => setOpen(true)}>
<Clock className="w-4 h-4" /> Offset Asset Dates
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{open && <AssetOffsetDialog assets={assets} open={open} toggleOpen={setOpen} />}
</>
)
}
@@ -1,8 +1,9 @@
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
import { IMissingLocationDatesResponse } from "@/handlers/api/asset.handler";
import { parseDate, formatDate } from "@/helpers/date.helper";
import { cn } from "@/lib/utils";
import React from "react";
import React, { useMemo } from "react";
interface IProps {
record: IMissingLocationDatesResponse;
@@ -10,6 +11,10 @@ interface IProps {
}
export default function MissingLocationDateItem({ record, onSelect }: IProps) {
const { startDate } = useMissingLocationContext()
const dateLabel = useMemo(() => {
if (!record.date) return "Unknown"
return formatDate(parseDate(record.date, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
}, [record.date])
return (
<div
role="button"
@@ -20,8 +25,8 @@ export default function MissingLocationDateItem({ record, onSelect }: IProps) {
startDate === record.date ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
}
>
<p className="font-mono text-sm">{record.date}</p>
<p className="text-xs">{record.asset_count} W/O Location</p>
<p className="font-mono text-sm">{dateLabel}</p>
<p className="text-xs text-foreground/50">{record.asset_count} Orphan Assets</p>
</div>
);
}
@@ -4,6 +4,9 @@ import { IMissingLocationDatesResponse, listMissingLocationDates } from "@/handl
import MissingLocationDateItem from "./MissingLocationDateItem";
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
import { useRouter } from "next/router";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { SortAsc, SortDesc } from "lucide-react";
export default function MissingLocationDates() {
const { updateContext } = useMissingLocationContext();
@@ -11,12 +14,16 @@ export default function MissingLocationDates() {
const [dateRecords, setDateRecords] = React.useState<
IMissingLocationDatesResponse[]
>([]);
const [filters, setFilters] = useState<{ sortBy: string, sortOrder: string }>({ sortBy: "date", sortOrder: "desc" });
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const fetchData = async () => {
return listMissingLocationDates({})
return listMissingLocationDates({
sortBy: filters.sortBy,
sortOrder: filters.sortOrder,
})
.then(setDateRecords)
.catch(setErrorMessage)
.finally(() => setLoading(false));
@@ -30,12 +37,37 @@ export default function MissingLocationDates() {
});
};
useEffect(() => {
fetchData();
}, []);
}, [filters]);
return (
<div className="overflow-y-auto min-w-[170px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="overflow-y-auto min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="flex justify-between items-center gap-2">
<Select
defaultValue={filters.sortBy}
onValueChange={(value) => setFilters({ ...filters, sortBy: value })}
>
<SelectTrigger className="!p-2">
<SelectValue placeholder="Sort by" />
</SelectTrigger>
<SelectContent defaultValue={filters.sortBy}>
<SelectGroup title="Sort by">
<SelectLabel>Sort by</SelectLabel>
<SelectItem value="date">Date</SelectItem>
<SelectItem value="asset_count">Asset Count</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<div>
<Button variant="default" size="sm" onClick={() => setFilters({ ...filters, sortOrder: filters.sortOrder === "asc" ? "desc" : "asc" })}>
{filters.sortOrder === "asc" ? <SortAsc size={16} /> : <SortDesc size={16} />}
</Button>
</div>
</div>
{dateRecords.map((record) => (
<MissingLocationDateItem
key={record.date}
+1 -1
View File
@@ -27,7 +27,7 @@ export function PeopleFilters() {
query: {
...router.query,
...data,
page: undefined,
page: data.page || undefined,
},
});
}
+1 -1
View File
@@ -54,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-5 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}/>
))}
+20 -20
View File
@@ -103,47 +103,47 @@ export function PersonMergeDropdown({
setSelectedPeople(selectedPeople.filter((p) => p.id !== value.id));
return;
}
if (selectedPeople.length >= 5) {
toast({
title: "Error",
description: "You can only merge 5 people at a time",
});
return;
} else {
setSelectedPeople([...selectedPeople, value]);
}
setSelectedPeople([...selectedPeople, value]);
if (primaryPerson.name.length === 0 && value.name.length > 0) {
setPrimaryPerson(value);
}
};
const handleMerge = () => {
if (selectedPeople.length === 0) {
return;
}
const personIds = selectedPeople.map((p) => p.id);
setMerging(true);
return mergePerson(person.id, personIds)
.then(() => {
onRemove?.(person);
})
.then(() => {
const mergeInBatches = async (ids: string[], index: number = 0) => {
if (index >= ids.length) {
setOpen(false);
toast({
title: "Success",
description: "People merged successfully",
});
})
.catch(() => {
setMerging(false);
return;
}
const batch = ids.slice(index, index + 5);
try {
await mergePerson(person.id, batch);
mergeInBatches(ids, index + 5);
} catch {
toast({
title: "Error",
description: "Failed to merge people",
});
})
.finally(() => {
setMerging(false);
});
}
};
mergeInBatches(personIds);
};
const handleRemove = (value: IPerson) => {
+27
View File
@@ -0,0 +1,27 @@
import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
import { cn } from "@/lib/utils"
const HoverCard = HoverCardPrimitive.Root
const HoverCardTrigger = HoverCardPrimitive.Trigger
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName
export { HoverCard, HoverCardTrigger, HoverCardContent }
+100
View File
@@ -0,0 +1,100 @@
import { CartesianGrid, LabelList, Line, LineChart, XAxis, YAxis } from "recharts";
import {
ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/components/ui/chart";
import { useMemo } from "react";
import { CHART_COLORS } from "@/config/constants/chart.constant";
export interface ILineChartData {
label: string;
value: number;
}
interface ChartProps {
data: ILineChartData[];
topLabel?: string;
loading?: boolean;
errorMessage?: string | null;
}
export function LineChartDots({
data: _data,
topLabel,
loading,
errorMessage,
}: ChartProps) {
const data = useMemo(
() =>
_data.map((item, index) => ({
...item,
fill: CHART_COLORS[index] || "#000000",
})),
[_data]
);
const chartConfig = useMemo(() => {
let config: ChartConfig = {};
data.map((data) => {
config[data.label as string] = {
label: data.label,
color: "hsl(var(--chart-1))",
};
});
return config;
}, [data]);
if (loading) {
return <p>Loading...</p>;
}
if (errorMessage) {
return <p>{errorMessage}</p>;
}
return (
<ChartContainer config={chartConfig} className="min-h-[200px] w-full">
<LineChart
accessibilityLayer
data={data}
>
<CartesianGrid vertical={false} />
<YAxis /> {/* Added YAxis for the count */}
<XAxis padding={{ left: 20 }} />
<ChartTooltip
cursor={false}
content={
<ChartTooltipContent indicator="line" nameKey="label" hideLabel />
}
/>
<Line
dataKey="value"
type="natural"
stroke="#FF6B6B"
strokeWidth={2}
dot={{
fill: "var(--color-visitors)",
}}
activeDot={{
r: 6,
}}
>
<LabelList
position="top"
offset={12}
className="fill-foreground"
fontSize={12}
dataKey="label"
formatter={(value: keyof typeof chartConfig) =>
chartConfig[value]?.label
}
/>
</Line>
</LineChart>
</ChartContainer>
);
}
+78
View File
@@ -0,0 +1,78 @@
"use client"
import { TrendingUp } from "lucide-react"
import { PolarAngleAxis, PolarGrid, Radar, RadarChart } from "recharts"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/components/ui/chart"
import { useMemo } from "react"
import { CHART_COLORS } from "@/config/constants/chart.constant"
export const description = "A radar chart with dots"
export interface IRadarChartData {
label: string;
value: number;
color?: string; // Add color property here
}
interface ChartProps {
data: IRadarChartData[];
topLabel?: string;
loading?: boolean;
errorMessage?: string | null;
}
const chartConfig = {
label: {
label: "label",
color: "#FF0000",
},
} satisfies ChartConfig
export default function RadarChartDots({ data: _data, topLabel, loading, errorMessage }: ChartProps) {
const chartData = _data
return (
<Card>
<CardContent className="pb-0 border-none">
<ChartContainer
config={chartConfig}
className="mx-auto aspect-square max-h-[250px] border-none"
>
<RadarChart data={chartData}>
<ChartTooltip cursor={false} content={<ChartTooltipContent />} />
<PolarAngleAxis dataKey="label" />
<PolarGrid stroke="#FFFFFF" strokeDasharray="3 3" /> {/* Set grid color to white */}
<Radar
dataKey="value"
fill="#FF0000"
fillOpacity={0.8}
dot={({ cx, cy, payload }) => (
<circle
cx={cx}
cy={cy}
r={4}
fill={payload.color} // Set color dynamically
fillOpacity={1}
/>
)}
/>
</RadarChart>
</ChartContainer>
</CardContent>
</Card>
)
}
+11 -3
View File
@@ -26,14 +26,22 @@ const TooltipContent = React.forwardRef<
TooltipContent.displayName = TooltipPrimitive.Content.displayName
const Tooltip: React.FC<React.ComponentProps<typeof TooltipRoot>> = ({
export interface ITooltipProps extends React.ComponentProps<typeof TooltipRoot> {
content: string
}
const Tooltip: React.FC<ITooltipProps> = ({
children,
content,
...props
}) => (
<TooltipProvider>
<TooltipRoot {...props}>
{children}
<TooltipContent />
<TooltipTrigger asChild>
{children}
</TooltipTrigger>
<TooltipContent>
<p>{content}</p>
</TooltipContent>
</TooltipRoot>
</TooltipProvider>
)
+6 -1
View File
@@ -1,4 +1,4 @@
import { GalleryVerticalEnd, Home, Image, LocateOff, MapPinX, User } from "lucide-react";
import { Album, GalleryHorizontal, GalleryVerticalEnd, Home, Image, LocateOff, MapPinX, User } from "lucide-react";
export const sidebarNavs = [
{
@@ -21,4 +21,9 @@ export const sidebarNavs = [
link: "/assets/missing-locations",
icon: <MapPinX className="h-4 w-4" />,
},
{
title: "Albums",
link: "/albums",
icon: <GalleryHorizontal className="h-4 w-4" />,
},
];
+1 -1
View File
@@ -1,5 +1,5 @@
export const ENV = {
IMMICH_URL: (process.env.IMMICH_URL || 'http://immich_server:3001') as string,
IMMICH_URL: (process.env.IMMICH_URL || 'http://immich_server:2283') as string,
EXTERNAL_IMMICH_URL: (process.env.EXTERNAL_IMMICH_URL || process.env.IMMICH_URL) as string,
IMMICH_API_KEY: process.env.IMMICH_API_KEY as string,
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}`),
+6 -1
View File
@@ -36,5 +36,10 @@ export const ASSET_VIDEO_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/asset/vi
export const SEARCH_PLACES_PATH = BASE_PROXY_ENDPOINT + "/search/places";
//Analytics
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";
// Common
export const GET_FILTERS = BASE_API_ENDPOINT + "/filters/asset-filters";
export const GET_FILTERS = BASE_API_ENDPOINT + "/filters/asset-filters";
+2
View File
@@ -7,6 +7,8 @@ import { IAsset } from "@/types/asset";
interface IPotentialAlbumsDatesFilters {
startDate?: string;
endDate?: string;
sortBy?: string;
sortOrder?: string;
}
export interface IPotentialAlbumsDatesResponse {
date: string;
+13 -1
View File
@@ -1,4 +1,4 @@
import { EXIF_DISTRIBUTION_PATH } from "@/config/routes";
import { ASSET_STATISTICS, EXIF_DISTRIBUTION_PATH, HEATMAP_DATA, LIVE_PHOTO_STATISTICS } from "@/config/routes";
import API from "@/lib/api";
export type ISupportedEXIFColumns =
@@ -7,3 +7,15 @@ export type ISupportedEXIFColumns =
export const getExifDistribution = async (column: ISupportedEXIFColumns) => {
return API.get(EXIF_DISTRIBUTION_PATH(column));
};
export const getAssetStatistics = async () => {
return API.get(ASSET_STATISTICS);
}
export const getLivePhotoStatistics = async () => {
return API.get(LIVE_PHOTO_STATISTICS);
}
export const getHeatMapData = async () => {
return API.get(HEATMAP_DATA);
}
+3
View File
@@ -12,6 +12,8 @@ import { IAsset } from "@/types/asset";
interface IMissingAssetAlbumsFilters {
startDate?: string;
endDate?: string;
sortBy?: string;
sortOrder?: string;
}
export interface IMissingLocationDatesResponse {
date: string;
@@ -37,6 +39,7 @@ export interface IUpdateAssetsParams {
ids: string[];
latitude?: number;
longitude?: number;
dateTimeOriginal?: string;
}
export const updateAssets = async (params: IUpdateAssetsParams) => {
+19 -1
View File
@@ -1,4 +1,4 @@
import { format, parse } from "date-fns"
import { addSeconds, addHours, addMinutes, format, parse, addYears } from "date-fns"
export const formatDate = (date: string, outputFormat?: string): string => {
return format(date, outputFormat || "PPP")
@@ -13,3 +13,21 @@ export const addDays = (date: Date, days: number): Date => {
result.setDate(result.getDate() + days);
return result;
}
export const offsetDate = (date: string, offset: {
years: number,
days: number,
hours: number,
minutes: number,
seconds: number
}): string => {
console.log(offset)
const parsedDate = new Date(date);
const result = addYears(parsedDate, offset.years || 0)
const result2 = addDays(result, offset.days || 0)
const result3 = addHours(result2, offset.hours || 0)
const result4 = addMinutes(result3, offset.minutes || 0)
const result5 = addSeconds(result4, offset.seconds || 0)
return result5.toISOString()
}
+73
View File
@@ -0,0 +1,73 @@
import { ASSET_THUMBNAIL_PATH } from '@/config/routes'
import PageLayout from '@/components/layouts/PageLayout'
import Header from '@/components/shared/Header'
import Loader from '@/components/ui/loader'
import { useConfig } from '@/contexts/ConfigContext'
import { listAlbums } from '@/handlers/api/album.handler'
import { IAlbum } from '@/types/album'
import Image from 'next/image'
import Link from 'next/link'
import React, { useEffect, useState } from 'react'
export default function AlbumListPage() {
const { exImmichUrl } = useConfig()
const [albums, setAlbums] = useState<IAlbum[]>([])
const [loading, setLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const fetchAlbums = async () => {
setLoading(true)
listAlbums()
.then(setAlbums)
.catch((error) => {
setErrorMessage(error.message)
})
.finally(() => {
setLoading(false)
})
}
useEffect(() => {
fetchAlbums()
}, [])
const renderContent = () => {
if (loading) {
return <Loader />
}
else if (errorMessage) {
return <div>{errorMessage}</div>
}
return (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 p-4">
{albums.map((album) => (
<div key={album.id} className="border rounded-lg overflow-hidden shadow-lg">
<Image
src={ASSET_THUMBNAIL_PATH(album.albumThumbnailAssetId)} // Assuming this is a URL to the thumbnail
alt={album.albumName}
width={300}
height={300}
loading='lazy'
className="w-full h-48 object-cover"
/>
<div className="p-4">
<Link href={`${exImmichUrl}/albums/${album.id}`} target="_blank">
<h2 className="text-md font-semibold truncate">{album.albumName}</h2>
</Link>
<p className="text-sm text-gray-700 dark:text-gray-500">{album.assetCount} assets</p>
</div>
</div>
))}
</div>
)
}
return (
<PageLayout className="!p-0 !mb-0">
<Header
leftComponent="Albums"
/>
{renderContent()}
</PageLayout>
)
}
+6 -2
View File
@@ -2,6 +2,7 @@ import AlbumCreateDialog from "@/components/albums/AlbumCreateDialog";
import AlbumSelectorDialog from "@/components/albums/AlbumSelectorDialog";
import PotentialAlbumsAssets from "@/components/albums/potential-albums/PotentialAlbumsAssets";
import PotentialAlbumsDates from "@/components/albums/potential-albums/PotentialAlbumsDates";
import AssetsOptions from "@/components/assets/assets-options/AssetsOptions";
import PageLayout from "@/components/layouts/PageLayout";
import Header from "@/components/shared/Header";
import { Badge } from "@/components/ui/badge";
@@ -14,7 +15,7 @@ import PotentialAlbumContext, {
import { addAssetToAlbum, createAlbum } from "@/handlers/api/album.handler";
import { IAlbum, IAlbumCreate } from "@/types/album";
import { useRouter } from "next/router";
import React from "react";
import React, { useMemo } from "react";
export default function PotentialAlbums() {
const { toast } = useToast();
@@ -28,6 +29,8 @@ export default function PotentialAlbums() {
assets: [],
});
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]) ;
const handleSelect = (album: IAlbum) => {
return addAssetToAlbum(album.id, config.selectedIds)
.then(() => {
@@ -65,7 +68,7 @@ export default function PotentialAlbums() {
}]
})
}
return (
<PageLayout className="!p-0 !mb-0">
<Header
@@ -102,6 +105,7 @@ export default function PotentialAlbums() {
)}
<AlbumSelectorDialog onSelected={handleSelect} />
<AlbumCreateDialog onSubmit={handleCreate} assetIds={config.assets.map((a) => a.id)} />
<AssetsOptions assets={selectedAssets} onAdd={() => { }} />
</>
}
/>
+79 -16
View File
@@ -1,7 +1,20 @@
import { Inter } from "next/font/google";
import PageLayout from "@/components/layouts/PageLayout";
import Header from "@/components/shared/Header";
import EXIFDistribution, { IEXIFDistributionProps } from "@/components/analytics/exif/EXIFDistribution";
import EXIFDistribution, {
IEXIFDistributionProps,
} from "@/components/analytics/exif/EXIFDistribution";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import AssetHeatMap from "@/components/analytics/exif/AssetHeatMap";
import { useEffect, useState } from "react";
import { getAssetStatistics, getLivePhotoStatistics } from "@/handlers/api/analytics.handler";
const inter = Inter({ subsets: ["latin"] });
@@ -42,36 +55,86 @@ const exifCharts: IEXIFDistributionProps[] = [
description: "Distribution of ISO",
},
{
column: 'exposureTime',
title: 'Exposure Time',
description: 'Distribution of exposure time'
column: "exposureTime",
title: "Exposure Time",
description: "Distribution of exposure time",
},
{
column: 'lensModel',
title: 'Lens Model',
description: 'Distribution of lens model'
column: "lensModel",
title: "Lens Model",
description: "Distribution of lens model",
},
{
column: 'projectionType',
title: 'Projection Type',
description: 'Distribution of projection type'
}
]
column: "projectionType",
title: "Projection Type",
description: "Distribution of projection type",
},
];
export default function ExifDataAnalytics() {
const [statistics, setStatistics] = useState({ images: 0, videos: 0, total: 0 });
const [loading, setLoading] = useState(false);
const [livePhotoStatistics, setLivePhotoStatistics] = useState({ total: 0 });
const fetchLivePhotoStatistics = async () => {
setLoading(true);
try {
const data = await getLivePhotoStatistics();
const livePhotoData = Array.isArray(data) && data.length ? data[0].value : 0;
setLivePhotoStatistics({ total: livePhotoData });
} finally {
setLoading(false);
}
};
const fetchStatisticsData = async () => {
setLoading(true);
try {
const data = await getAssetStatistics();
setStatistics(data);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchStatisticsData();
fetchLivePhotoStatistics();
}, []);
return (
<PageLayout>
<Header
leftComponent="Exif Data"
/>
<Header leftComponent="Exif Data" />
<div className="grid grid-cols-4 gap-4">
{["Total", "Images", "Videos"].map((type, i) => (
<Card key={i}>
<CardHeader>
<CardTitle className="text-center text-lg font-mono">{type}</CardTitle>
</CardHeader>
<CardContent className="text-center text-3xl font-mono">
{loading ? "Loading..." : statistics[type.toLowerCase() as keyof typeof statistics].toLocaleString()}
</CardContent>
</Card>
))}
<Card>
<CardHeader>
<CardTitle className="text-center text-lg font-mono">Live Photos</CardTitle>
</CardHeader>
<CardContent className="text-center text-3xl font-mono">
{loading ? "Loading..." : livePhotoStatistics.total.toLocaleString()}
</CardContent>
</Card>
</div>
<AssetHeatMap />
<div className="grid grid-cols-3 gap-4">
{exifCharts.map((chart) => (
<EXIFDistribution
<EXIFDistribution
key={chart.column}
column={chart.column}
title={chart.title}
description={chart.description}
/>
))}
</div>
</PageLayout>
);
@@ -21,9 +21,9 @@ const SELECT_ORPHAN_PHOTOS = (date: string, ownerId: string) =>
a."sidecarPath",
a."thumbhash",
a."deletedAt",
a."localDateTime",
e."exifImageWidth",
e."exifImageHeight"
e."exifImageHeight",
e."dateTimeOriginal"
FROM
assets a
LEFT JOIN
@@ -35,7 +35,7 @@ const SELECT_ORPHAN_PHOTOS = (date: string, ownerId: string) =>
WHERE
aaa."albumsId" IS NULL
AND a."ownerId" = '${ownerId}'
AND a."localDateTime"::date = '${date}'
AND e."dateTimeOriginal"::date = '${date}'
AND a."isVisible" = true
`);
+22 -3
View File
@@ -1,25 +1,30 @@
// 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 { IPotentialAlbumsDatesResponse } from "@/handlers/api/album.handler";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { parseDate } from "@/helpers/date.helper";
import { exif } from "@/schema";
import { count, desc, isNotNull, ne, sql } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
const SELECT_ORPHAN_PHOTOS = (ownerId: string) => sql`
SELECT
DATE(a."localDateTime") AS "date",
DATE(e."dateTimeOriginal") AS "date",
COUNT(a."id") AS "asset_count"
FROM
"assets" a
LEFT JOIN
"albums_assets_assets" aaa ON a."id" = aaa."assetsId"
LEFT JOIN
"exif" e ON a."id" = e."assetId"
WHERE
aaa."albumsId" IS NULL
AND a."ownerId" = ${ownerId}
AND a."isVisible" = true
AND e."dateTimeOriginal" IS NOT NULL
GROUP BY
DATE(a."localDateTime")
DATE(e."dateTimeOriginal")
ORDER BY
"asset_count" DESC;
`;
@@ -29,8 +34,22 @@ export default async function handler(
res: NextApiResponse
) {
try {
const { sortBy = "date", sortOrder = "desc" } = req.query;
const currentUser = await getCurrentUser(req)
const { rows } = await db.execute(SELECT_ORPHAN_PHOTOS(currentUser.id));
const data = await db.execute(SELECT_ORPHAN_PHOTOS(currentUser.id)) as any;
const rows = data.rows as IPotentialAlbumsDatesResponse[];
if (sortBy === "date") {
rows.sort((a, b) => {
const aDate = parseDate(a.date, "yyyy-MM-dd");
const bDate = parseDate(b.date, "yyyy-MM-dd");
return sortOrder === "asc" ? aDate.getTime() - bDate.getTime() : bDate.getTime() - aDate.getTime();
});
} else if (sortBy === "asset_count") {
rows.sort((a, b) => {
return sortOrder === "asc" ? a.asset_count - b.asset_count : b.asset_count - a.asset_count;
});
}
return res.status(200).json(rows);
} catch (error: any) {
res.status(500).json({
@@ -0,0 +1,69 @@
// 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 { and, count, desc, eq, gte, isNotNull, ne, sql, } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
// Helper function to format date as YYYY-MM-DD
function formatDate(date: Date) {
return date.toISOString().split('T')[0];
}
function fillMissingDates(data: any[]) {
const today = new Date();
// Set the start date as one year ago, excluding the current month in the previous year
const oneYearAgo = new Date(today.getFullYear() - 1, today.getMonth() + 1, 1); // First day of the next month last year
const existingDates = new Set(data.map(item => item.date));
const filledData = [];
// Iterate from today to one year ago, but skip the current month from last year
for (let d = new Date(today); d >= oneYearAgo; d.setDate(d.getDate() - 1)) {
const dateStr = formatDate(d);
// Skip dates in the current month of the previous year
if (d.getFullYear() === today.getFullYear() - 1 && d.getMonth() === today.getMonth()) {
continue;
}
if (existingDates.has(dateStr)) {
filledData.push(data.find(item => item.date === dateStr));
} else {
filledData.push({ date: dateStr, count: 0 });
}
}
// Sort the filled data in descending order
filledData.sort((a, b) => a.date.localeCompare(b.date));
return filledData;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const currentUser = await getCurrentUser(req);
const dataFromDB = await db.select({
date: sql`DATE(${assets.fileCreatedAt})`.as('date'),
count: count(),
})
.from(assets)
.where(
and(
eq(assets.ownerId, currentUser.id),
gte(assets.fileCreatedAt, sql`CURRENT_DATE - INTERVAL '1 YEAR'`))
)
.groupBy(sql`DATE(${assets.fileCreatedAt})`)
.orderBy(sql`DATE(${assets.fileCreatedAt}) DESC`)
const updatedData = fillMissingDates(dataFromDB);
return res.status(200).json(updatedData);
} catch (error: any) {
res.status(500).json({
error: error?.message,
});
}
}
@@ -0,0 +1,31 @@
// 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 { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { assets, exif } from "@/schema";
import { and, count, desc, eq, isNotNull, ne } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const currentUser = await getCurrentUser(req);
const dataFromDB = await db.select({
value: count(),
})
.from(assets)
.where(and(
eq(assets.ownerId, currentUser.id),
isNotNull(assets.livePhotoVideoId))
);
return res.status(200).json(dataFromDB);
} catch (error: any) {
res.status(500).json({
error: error?.message,
});
}
}
@@ -43,6 +43,7 @@ export default async function handler(
exifImageWidth: exif.exifImageWidth,
exifImageHeight: exif.exifImageHeight,
ownerId: assets.ownerId,
dateTimeOriginal: exif.dateTimeOriginal,
})
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
+23 -2
View File
@@ -1,7 +1,9 @@
// 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 { IMissingLocationDatesResponse } from "@/handlers/api/asset.handler";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { parseDate } from "@/helpers/date.helper";
import { assets, exif } from "@/schema";
import { and, count, desc, eq, isNotNull, isNull, ne, sql } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -11,7 +13,13 @@ export default async function handler(
res: NextApiResponse
) {
try {
const { sortBy = "date", sortOrder = "desc" } = req.query;
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({
error: "Unauthorized",
});
}
const rows = await db
.select({
asset_count: desc(count(assets.id)),
@@ -22,12 +30,25 @@ export default async function handler(
.where(and(
isNull(exif.latitude),
isNotNull(assets.createdAt),
isNotNull(exif.dateTimeOriginal),
eq(assets.type, "VIDEO"),
eq(assets.ownerId, currentUser.id),
eq(assets.ownerId, currentUser.id),
eq(assets.isVisible, true),
))
.groupBy(sql`DATE(${exif.dateTimeOriginal})`)
.orderBy(desc(count(assets.id)));
.orderBy(desc(count(assets.id))) as IMissingLocationDatesResponse[];
if (sortBy === "date") {
rows.sort((a, b) => {
const aDate = parseDate(a.date, "yyyy-MM-dd");
const bDate = parseDate(b.date, "yyyy-MM-dd");
return sortOrder === "asc" ? aDate.getTime() - bDate.getTime() : bDate.getTime() - aDate.getTime();
});
} else if (sortBy === "asset_count") {
rows.sort((a, b) => {
return sortOrder === "asc" ? a.asset_count - b.asset_count : b.asset_count - a.asset_count;
});
}
return res.status(200).json(rows);
} catch (error: any) {
res.status(500).json({
+9 -4
View File
@@ -14,10 +14,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
try {
const response = await fetch(targetUrl, {
method: req.method,
headers: getUserHeaders(currentUser),
headers: {
...getUserHeaders(currentUser),
'Accept-Encoding': 'gzip, deflate, br',
},
body: req.method !== 'GET' && req.method !== 'HEAD' ? JSON.stringify(req.body) : null,
})
// Log response headers for debugging
console.log('Response Headers:', response.headers);
// Forward the status code
res.status(response.status)
@@ -28,7 +33,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res.setHeader(key, value)
})
// Stream the response body
// Stream the response body
const reader = response.body?.getReader()
if (reader) {
while (true) {
@@ -38,8 +43,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
}
res.end()
} catch (error) {
} catch (error: any) {
console.error('Proxy error:', error)
res.status(500).json({ error })
res.status(500).json({ error: error?.message })
}
}
+5 -1
View File
@@ -1,6 +1,7 @@
import AlbumSelectorDialog from "@/components/albums/AlbumSelectorDialog";
import PotentialAlbumsAssets from "@/components/albums/potential-albums/PotentialAlbumsAssets";
import PotentialAlbumsDates from "@/components/albums/potential-albums/PotentialAlbumsDates";
import AssetsOptions from "@/components/assets/assets-options/AssetsOptions";
import MissingLocationAssets from "@/components/assets/missing-location/MissingLocationAssets";
import MissingLocationDates from "@/components/assets/missing-location/MissingLocationDates";
import TagMissingLocationDialog from "@/components/assets/missing-location/TagMissingLocationDialog/TagMissingLocationDialog";
@@ -17,7 +18,7 @@ import { updateAssets } from "@/handlers/api/asset.handler";
import { IPlace } from "@/types/common";
import { useRouter } from "next/router";
import React from "react";
import React, { useMemo } from "react";
export default function MissingLocations() {
const { toast } = useToast();
@@ -30,6 +31,8 @@ export default function MissingLocations() {
assets: [],
});
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]) ;
const handleSubmit = (place: IPlace) => {
return updateAssets({
ids: config.selectedIds,
@@ -78,6 +81,7 @@ export default function MissingLocations() {
</Button>
)}
<TagMissingLocationDialog onSubmit={handleSubmit} />
<AssetsOptions assets={selectedAssets} onAdd={() => { }} />
</>
}
/>
+14
View File
@@ -0,0 +1,14 @@
import { pgTable, uuid, varchar, timestamp, boolean, text } from 'drizzle-orm/pg-core';
export const albums = pgTable('albums', {
id: uuid('id').defaultRandom().primaryKey().notNull(),
ownerId: uuid('ownerId').notNull(),
albumName: varchar('albumName').notNull().default('Untitled Album'),
createdAt: timestamp('createdAt', { withTimezone: true }).defaultNow().notNull(),
albumThumbnailAssetId: uuid('albumThumbnailAssetId'),
updatedAt: timestamp('updatedAt', { withTimezone: true }).defaultNow().notNull(),
description: text('description').notNull().default(''),
deletedAt: timestamp('deletedAt', { withTimezone: true }),
isActivityEnabled: boolean('isActivityEnabled').notNull().default(true),
order: varchar('order').notNull().default('desc'),
});
+1
View File
@@ -17,6 +17,7 @@ export interface IAsset {
url: string;
previewUrl: string;
videoURL?: string;
dateTimeOriginal: string;
}
export interface IAssetThumbhash {