From 4861bbf0cea16e629e37679fa1b9d2dd022d04c6 Mon Sep 17 00:00:00 2001 From: sai80082 Date: Thu, 9 Apr 2026 10:57:56 +0530 Subject: [PATCH 01/25] feat: enhance API key validation with detailed permission checks and user feedback --- src/pages/api/settings/validate-api-key.ts | 63 +++-------------- src/pages/settings/index.tsx | 80 +++++++++++++++++++--- 2 files changed, 79 insertions(+), 64 deletions(-) diff --git a/src/pages/api/settings/validate-api-key.ts b/src/pages/api/settings/validate-api-key.ts index 8f7c2aa..ff49774 100644 --- a/src/pages/api/settings/validate-api-key.ts +++ b/src/pages/api/settings/validate-api-key.ts @@ -2,7 +2,7 @@ import { ENV } from "@/config/environment"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { NextApiRequest, NextApiResponse } from "next"; -const REQUIRED_PERMISSIONS = [ +const WORKFLOW_PERMISSIONS = [ "asset.read", "asset.update", "album.create", @@ -16,16 +16,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const currentUser = await getCurrentUser(req); if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - const { apiKey } = req.body; + const { apiKey, requiredPermissions } = req.body; if (!apiKey) return res.status(400).json({ message: "apiKey is required" }); + const REQUIRED_PERMISSIONS: string[] = Array.isArray(requiredPermissions) ? requiredPermissions : WORKFLOW_PERMISSIONS; + try { - // Validate by calling Immich's auth endpoint with the key - const authRes = await fetch(`${ENV.IMMICH_URL}/api/users/me`, { + const keyRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys/me`, { headers: { "x-api-key": apiKey }, }); - if (!authRes.ok) { + if (!keyRes.ok) { return res.status(200).json({ valid: false, error: "Invalid API key — could not authenticate with Immich", @@ -34,56 +35,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) }); } - // Get the API key details to check permissions - const keysRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, { - headers: { "x-api-key": apiKey }, - }); - - if (!keysRes.ok) { - // Can authenticate but can't list keys — might be a full-access key - return res.status(200).json({ - valid: true, - error: null, - permissions: ["all (could not verify individual permissions)"], - missing: [], - }); - } - - const keys = await keysRes.json(); - - // Find the key being used — it's the one that matches our request - // Immich doesn't directly tell us which key is in use, so check all permissions across all keys - // The safest check: try to access endpoints that require each permission - const permissionChecks = await Promise.all([ - // asset.read — try searching assets - fetch(`${ENV.IMMICH_URL}/api/assets?take=1`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "asset.read", granted: r.ok })), - - // asset.update — try a dry validation (we just check if the endpoint doesn't 403) - fetch(`${ENV.IMMICH_URL}/api/assets`, { - method: "PUT", - headers: { "x-api-key": apiKey, "Content-Type": "application/json" }, - body: JSON.stringify({ ids: [], isFavorite: true }), - }).then((r) => ({ permission: "asset.update", granted: r.status !== 403 })), - - // album.create — check via OPTIONS or a minimal request - fetch(`${ENV.IMMICH_URL}/api/albums`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "album.create", granted: r.ok })), - - // album.update — same endpoint access implies read+write - fetch(`${ENV.IMMICH_URL}/api/albums`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "album.update", granted: r.ok })), - - // tag.create - fetch(`${ENV.IMMICH_URL}/api/tags`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "tag.create", granted: r.ok || r.status !== 403 })), - ]); - - const granted = permissionChecks.filter((p) => p.granted).map((p) => p.permission); + const keyData = await keyRes.json(); + const granted: string[] = keyData.permissions ?? []; const missing = REQUIRED_PERMISSIONS.filter((p) => !granted.includes(p)); return res.status(200).json({ diff --git a/src/pages/settings/index.tsx b/src/pages/settings/index.tsx index 164f1bd..0616f2e 100644 --- a/src/pages/settings/index.tsx +++ b/src/pages/settings/index.tsx @@ -50,6 +50,9 @@ export default function SettingsPage() { const [showImportApiKey, setShowImportApiKey] = useState(false); const [importApiKeySaved, setImportApiKeySaved] = useState(false); const [generatingImportKey, setGeneratingImportKey] = useState(false); + const [importValidationResult, setImportValidationResult] = useState<{ + valid: boolean; error: string | null; permissions: string[]; missing: string[]; + } | null>(null); const fetchWorkflowApiKey = async () => { try { @@ -71,14 +74,45 @@ export default function SettingsPage() { } }; + const IMPORT_REQUIRED_PERMISSIONS = ["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create"]; + const saveImportApiKey = async () => { + if (!importApiKey.trim()) { + setImportApiKeyLoading(true); + try { + await API.put("/api/settings/kv/import_api_key", { value: "" }); + setImportApiKeySaved(false); + setImportValidationResult(null); + toast.success("Import API key cleared"); + } catch { + toast.error("Failed to clear import API key"); + } + setImportApiKeyLoading(false); + return; + } + setImportApiKeyLoading(true); + setImportValidationResult(null); + toast("Validating API key..."); + try { + const result = await API.post("/api/settings/validate-api-key", { + apiKey: importApiKey, + requiredPermissions: IMPORT_REQUIRED_PERMISSIONS, + }); + setImportValidationResult(result); + + if (!result.valid) { + toast.error(result.error || "API key validation failed"); + setImportApiKeyLoading(false); + return; + } + await API.put("/api/settings/kv/import_api_key", { value: importApiKey.trim() }); - setImportApiKeySaved(!!importApiKey.trim()); - toast.success(importApiKey.trim() ? "Import API key saved" : "Import API key cleared"); + setImportApiKeySaved(true); + toast.success("API key validated and saved"); } catch { - toast.error("Failed to save import API key"); + toast.error("Failed to validate API key"); } setImportApiKeyLoading(false); }; @@ -294,18 +328,46 @@ export default function SettingsPage() { {importApiKeyLoading ? "Saving..." : "Save"} -
- {["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create"].map((p) => ( - {p} - ))} -
+ {importValidationResult && ( +
+
+ {importValidationResult.valid ? ( + <>All permissions verified + ) : ( + <>{importValidationResult.error} + )} +
+
+ {IMPORT_REQUIRED_PERMISSIONS.map((p) => { + const granted = importValidationResult.permissions.includes(p); + const missing = importValidationResult.missing.includes(p); + return ( + + {granted ? "✓" : "✗"} {p} + + ); + })} +
+
+ )} + {!importValidationResult && ( +
+ {IMPORT_REQUIRED_PERMISSIONS.map((p) => ( + {p} + ))} +
+ )}
- From 3806ac389206ac06da3cbdba3f18d7e6fee30f83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Gil=20P=C3=A9rez?= Date: Tue, 21 Apr 2026 00:26:40 +0200 Subject: [PATCH 05/25] feat(analytics): year selector on asset heatmap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Today the Analytics heatmap hard-codes "last 12 months" both in the SQL (`WHERE fileCreatedAt >= CURRENT_DATE - INTERVAL '1 YEAR'`) and in the frontend's month labels loop. Users with multi-year libraries can't look back at 2018 or 2020 from this view. Changes: - API `/api/analytics/statistics/heatmap` now accepts an optional `year` query param. With it, the query spans the full calendar year (Jan 1 to Dec 31) and `fillMissingDates` walks that range. Without it, the legacy rolling 12-month behaviour is preserved (including the "skip the repeating current month from last year" seam guard). - Response shape changed from `[]` to `{ data, year, availableYears }`. `availableYears` comes from a DISTINCT EXTRACT(YEAR ...) over the user's assets so the UI can render a correct dropdown without guessing. - Component shows a Select next to the heatmap: "Last 12 months" (default) plus one entry per year that actually has assets. Month labels and the `weeksPerMonth` computation switch accordingly. - No migrations needed; drizzle query only. Callers of `getHeatMapData()` now receive an object — there was only one caller (the heatmap component) so the change is localised. --- .../analytics/exif/AssetHeatMap.tsx | 59 ++++++-- src/handlers/api/analytics.handler.ts | 11 +- .../api/analytics/statistics/heatmap.tsx | 140 +++++++++++------- 3 files changed, 140 insertions(+), 70 deletions(-) diff --git a/src/components/analytics/exif/AssetHeatMap.tsx b/src/components/analytics/exif/AssetHeatMap.tsx index 1418185..3b06679 100644 --- a/src/components/analytics/exif/AssetHeatMap.tsx +++ b/src/components/analytics/exif/AssetHeatMap.tsx @@ -1,13 +1,16 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useMemo, useState } from "react"; import { getHeatMapData } from "@/handlers/api/analytics.handler"; import { useConfig } from "@/contexts/ConfigContext"; import { Tooltip } from "@/components/ui/tooltip"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; type HeatMapEntry = { date: string; count: number; }; +const ROLLING = "rolling" as const; + const COLOR_SCALE = [ "bg-zinc-100 dark:bg-zinc-800/60", "bg-emerald-200 dark:bg-emerald-900/70", @@ -25,29 +28,39 @@ export default function AssetHeatMap() { const [heatMapData, setHeatMapData] = useState([]); const [loading, setLoading] = useState(false); const [weeksPerMonth, setWeeksPerMonth] = useState([]); + const [availableYears, setAvailableYears] = useState([]); + const [selection, setSelection] = useState(ROLLING); - const fetchHeatMapData = async () => { + const fetchHeatMapData = async (sel: typeof ROLLING | number) => { setLoading(true); try { - const data = await getHeatMapData(); - setHeatMapData(formatHeatMapData(data)); + const resp = await getHeatMapData(sel === ROLLING ? undefined : sel); + setAvailableYears(resp.availableYears ?? []); + setHeatMapData(formatHeatMapData(resp.data)); } finally { setLoading(false); } }; useEffect(() => { - fetchHeatMapData(); - }, []); + fetchHeatMapData(selection); + }, [selection]); - const currentDate = new Date(); - const months: string[] = []; - - for (let i = 0; i < 12; i++) { - months.push(currentDate.toLocaleString("default", { month: "short" })); - currentDate.setMonth(currentDate.getMonth() - 1); - } - months.reverse(); + const months = useMemo(() => { + if (selection === ROLLING) { + const cursor = new Date(); + const out: string[] = []; + for (let i = 0; i < 12; i++) { + out.push(cursor.toLocaleString("default", { month: "short" })); + cursor.setMonth(cursor.getMonth() - 1); + } + return out.reverse(); + } + // Calendar year: Jan-Dec in order. + return Array.from({ length: 12 }, (_, i) => + new Date(selection, i, 1).toLocaleString("default", { month: "short" }) + ); + }, [selection]); const flattenedData = heatMapData.flat(); const minCount = Math.min(...flattenedData.map((entry) => entry.count)); @@ -106,6 +119,24 @@ export default function AssetHeatMap() { return (
+
+ +
diff --git a/src/handlers/api/analytics.handler.ts b/src/handlers/api/analytics.handler.ts index 605792e..523c7bb 100644 --- a/src/handlers/api/analytics.handler.ts +++ b/src/handlers/api/analytics.handler.ts @@ -16,8 +16,15 @@ export const getLivePhotoStatistics = async () => { return API.get(LIVE_PHOTO_STATISTICS); } -export const getHeatMapData = async () => { - return API.get(HEATMAP_DATA); +export interface IHeatMapResponse { + data: Array<{ date: string; count: number }>; + year: number | null; + availableYears: number[]; +} + +export const getHeatMapData = async (year?: number): Promise => { + const params = year ? { year: String(year) } : {}; + return API.get(HEATMAP_DATA, params); } export const getPeopleNamesStatistics = async () => { diff --git a/src/pages/api/analytics/statistics/heatmap.tsx b/src/pages/api/analytics/statistics/heatmap.tsx index d330b1a..c502720 100644 --- a/src/pages/api/analytics/statistics/heatmap.tsx +++ b/src/pages/api/analytics/statistics/heatmap.tsx @@ -1,69 +1,101 @@ // 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 { assets } from "@/schema"; +import { and, between, eq, gte, sql } from "drizzle-orm"; +import { count } 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]; + return date.toISOString().split("T")[0]; } -function fillMissingDates(data: any[]) { - const today = new Date(); +/** + * Fill gaps in a date-indexed series so the heatmap always has 365ish cells + * drawn, even for dates with zero photos. + * + * - No `year` → 12-month rolling window ending today (legacy behaviour). + * - `year` given → fill every day of that calendar year. + */ +function fillMissingDates(data: Array<{ date: string; count: number }>, year?: number) { + const existing = new Map(data.map((d) => [d.date, d])); - // 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 + let start: Date; + let end: Date; + if (year) { + start = new Date(Date.UTC(year, 0, 1)); + end = new Date(Date.UTC(year, 11, 31)); + } else { + end = new Date(); + start = new Date(end.getFullYear() - 1, end.getMonth() + 1, 1); + } - 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 }); - } + const filled: Array<{ date: string; count: number }> = []; + for (let d = new Date(start); d <= end; d.setUTCDate(d.getUTCDate() + 1)) { + // Legacy quirk preserved: skip days that land in the repeating "current + // month" of the previous year in the rolling 12-month window, so the + // heatmap isn't double-counted on the seam. + if (!year && d.getFullYear() === end.getFullYear() - 1 && d.getMonth() === end.getMonth()) { + continue; } - - // Sort the filled data in descending order - filledData.sort((a, b) => a.date.localeCompare(b.date)); - return filledData; + const key = formatDate(d); + filled.push(existing.get(key) ?? { date: key, count: 0 }); + } + filled.sort((a, b) => a.date.localeCompare(b.date)); + return filled; } -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(), +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + try { + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + const rawYear = (req.query.year as string | undefined)?.trim(); + const year = + rawYear && /^\d{4}$/.test(rawYear) ? Number.parseInt(rawYear, 10) : undefined; + + // Range clause: either a whole calendar year, or the legacy 12-month rolling window. + const rangeClause = year + ? between( + assets.fileCreatedAt, + sql`${`${year}-01-01`}::timestamptz`, + sql`${`${year}-12-31 23:59:59`}::timestamptz` + ) + : gte(assets.fileCreatedAt, sql`CURRENT_DATE - INTERVAL '1 YEAR'`); + + const [dataFromDB, yearsRaw] = await Promise.all([ + db + .select({ + date: sql`TO_CHAR(DATE(${assets.fileCreatedAt}), 'YYYY-MM-DD')`.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, - }); - } + .from(assets) + .where(and(eq(assets.ownerId, currentUser.id), rangeClause)) + .groupBy(sql`DATE(${assets.fileCreatedAt})`) + .orderBy(sql`DATE(${assets.fileCreatedAt}) DESC`), + // Distinct years the user has assets for, for the UI year selector. + db + .select({ + year: sql`EXTRACT(YEAR FROM ${assets.fileCreatedAt})::int`.as("year"), + }) + .from(assets) + .where(eq(assets.ownerId, currentUser.id)) + .groupBy(sql`EXTRACT(YEAR FROM ${assets.fileCreatedAt})`) + .orderBy(sql`EXTRACT(YEAR FROM ${assets.fileCreatedAt}) DESC`), + ]); + + const filled = fillMissingDates( + (dataFromDB as Array<{ date: string; count: number }>), + year + ); + + return res.status(200).json({ + data: filled, + year: year ?? null, + availableYears: (yearsRaw as Array<{ year: number }>).map((r) => r.year).filter(Boolean), + }); + } catch (error: any) { + console.error(error); + return res.status(500).json({ error: error?.message }); + } } From 23333c51d5bb4184ed7206614d4f664a178ee1fa Mon Sep 17 00:00:00 2001 From: Varun Date: Thu, 23 Apr 2026 14:48:06 +0530 Subject: [PATCH 06/25] fix: restore gallery grid selection UI and enable starting selection --- src/components/shared/AssetGrid.tsx | 4 ++- .../shared/ResponsiveVirtualizedAssetGrid.tsx | 10 ++++--- .../shared/VirtualizedAssetGrid.tsx | 10 ++++--- src/components/ui/lazy-grid-image.tsx | 27 +++++++++++++++++-- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/components/shared/AssetGrid.tsx b/src/components/shared/AssetGrid.tsx index c21a349..4dbd27b 100644 --- a/src/components/shared/AssetGrid.tsx +++ b/src/components/shared/AssetGrid.tsx @@ -121,7 +121,7 @@ const AssetGrid = forwardRef(({ assets, isInternal const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => { - if (selectedIds.length > 0) { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { handleSelect(index, asset, event); } else { setIndex(index); @@ -214,6 +214,8 @@ const AssetGrid = forwardRef(({ assets, isInternal photo={context.photo} width={context.width} height={context.height} + selectable={selectable} + onSelect={(event) => handleSelect(context.index, context.photo, event)} /> ); }; diff --git a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx index 4c971f2..81d3699 100644 --- a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx +++ b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx @@ -113,12 +113,12 @@ const ResponsiveVirtualizedAssetGrid = forwardRef) => { - if (selectedIds.length > 0) { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { handleSelect(index, asset, event); } else { setIndex(index); } - }, [selectedIds]); + }, [selectedIds, selectable, handleSelect]); const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { event.stopPropagation(); @@ -200,11 +200,15 @@ const ResponsiveVirtualizedAssetGrid = forwardRef { + e.stopPropagation(); + handleSelect(assetIndex, asset, e); + }} /> )} diff --git a/src/components/shared/VirtualizedAssetGrid.tsx b/src/components/shared/VirtualizedAssetGrid.tsx index add29f4..a5367e1 100644 --- a/src/components/shared/VirtualizedAssetGrid.tsx +++ b/src/components/shared/VirtualizedAssetGrid.tsx @@ -77,12 +77,12 @@ const VirtualizedAssetGrid = forwardRef) => { - if (selectedIds.length > 0) { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { handleSelect(index, asset, event); } else { setIndex(index); } - }, [selectedIds]); + }, [selectedIds, selectable, handleSelect]); const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { event.stopPropagation(); @@ -166,11 +166,15 @@ const VirtualizedAssetGrid = forwardRef { + e.stopPropagation(); + handleSelect(assetIndex, asset, e); + }} /> )} diff --git a/src/components/ui/lazy-grid-image.tsx b/src/components/ui/lazy-grid-image.tsx index 015fc33..703bf10 100644 --- a/src/components/ui/lazy-grid-image.tsx +++ b/src/components/ui/lazy-grid-image.tsx @@ -1,6 +1,7 @@ /* eslint-disable @next/next/no-img-element */ import { humanizeDuration } from '@/helpers/string.helper' import { PlayIcon } from '@radix-ui/react-icons' +import { CircleCheck } from 'lucide-react' import React, { useEffect } from 'react' import type { RenderImageProps } from 'react-photo-album' import type { AssetPhoto } from '../shared/AssetGrid' @@ -10,9 +11,11 @@ interface LazyGridImageProps { photo: AssetPhoto; width: number; height: number; + selectable?: boolean; + onSelect?: (event: React.MouseEvent) => void; } -export default function LazyGridImage({ imageProps, photo, width, height }: LazyGridImageProps) { +export default function LazyGridImage({ imageProps, photo, width, height, selectable, onSelect }: LazyGridImageProps) { const [isVisible, setIsVisible] = React.useState(false) const imageRef = React.useRef(null) @@ -45,12 +48,32 @@ export default function LazyGridImage({ imageProps, photo, width, height }: Lazy ) return ( -
+
{imageProps.alt {photo.isVideo &&
{!!photo.duration && {humanizeDuration(photo.duration)}}
} + {selectable && ( +
{ + e.stopPropagation(); + onSelect?.(e); + }} + > +
+ +
+
+ )}
) } From c99a2c6854ce20823f38575595a3701bfa80348c Mon Sep 17 00:00:00 2001 From: Varun Date: Thu, 23 Apr 2026 14:53:33 +0530 Subject: [PATCH 07/25] fix: resolve block-scoped variable usage before declaration --- src/components/shared/AssetGrid.tsx | 16 ++++++++-------- .../shared/ResponsiveVirtualizedAssetGrid.tsx | 16 ++++++++-------- src/components/shared/VirtualizedAssetGrid.tsx | 16 ++++++++-------- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/components/shared/AssetGrid.tsx b/src/components/shared/AssetGrid.tsx index 4dbd27b..74b33a6 100644 --- a/src/components/shared/AssetGrid.tsx +++ b/src/components/shared/AssetGrid.tsx @@ -120,14 +120,6 @@ const AssetGrid = forwardRef(({ assets, isInternal }), [assets, selectedIds, updateContext]); - const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => { - if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { - handleSelect(index, asset, event); - } else { - setIndex(index); - } - } - const handleSelect = (_idx: number, asset: AssetPhoto, event: React.MouseEvent) => { event.stopPropagation(); @@ -157,6 +149,14 @@ const AssetGrid = forwardRef(({ assets, isInternal } }; + const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + } + const slides = useMemo(() => { return assets.filter((asset) => !deletedIds.has(asset.id)).map((asset) => ({ ...asset, diff --git a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx index 81d3699..ed21a71 100644 --- a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx +++ b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx @@ -112,14 +112,6 @@ const ResponsiveVirtualizedAssetGrid = forwardRef) => { - if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { - handleSelect(index, asset, event); - } else { - setIndex(index); - } - }, [selectedIds, selectable, handleSelect]); - const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { event.stopPropagation(); const isPresent = selectedIds.includes(asset.id); @@ -146,6 +138,14 @@ const ResponsiveVirtualizedAssetGrid = forwardRef) => { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + }, [selectedIds, selectable, handleSelect]); + const handleEsc = useCallback((event: KeyboardEvent) => { if (event.key === "Escape") { updateContext({ selectedIds: [] }); diff --git a/src/components/shared/VirtualizedAssetGrid.tsx b/src/components/shared/VirtualizedAssetGrid.tsx index a5367e1..57837b4 100644 --- a/src/components/shared/VirtualizedAssetGrid.tsx +++ b/src/components/shared/VirtualizedAssetGrid.tsx @@ -76,14 +76,6 @@ const VirtualizedAssetGrid = forwardRef) => { - if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { - handleSelect(index, asset, event); - } else { - setIndex(index); - } - }, [selectedIds, selectable, handleSelect]); - const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { event.stopPropagation(); const isPresent = selectedIds.includes(asset.id); @@ -110,6 +102,14 @@ const VirtualizedAssetGrid = forwardRef) => { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + }, [selectedIds, selectable, handleSelect]); + const handleEsc = useCallback((event: KeyboardEvent) => { if (event.key === "Escape") { updateContext({ selectedIds: [] }); From 28cd757366845d9d764229b522862ad880aa8d40 Mon Sep 17 00:00:00 2001 From: sai80082 Date: Fri, 24 Apr 2026 15:13:19 +0530 Subject: [PATCH 08/25] feat: replace react-mentions with rc-mentions in FindInput component - Updated FindInput component to use rc-mentions for better performance and flexibility. - Removed unused styles related to react-mentions and added new styles for rc-mentions in globals.scss. - Enhanced search functionality to handle mentions and clear input more effectively. - Updated FindPage to manage searched queries and loading state. --- bun.lock | 51 +++++----- package.json | 3 +- src/components/find/FindInput.tsx | 128 +++++++++++++++++------- src/components/find/findInputStyle.ts | 45 --------- src/components/find/findMentionStyle.ts | 6 -- src/pages/find/index.tsx | 11 +- src/styles/globals.scss | 88 ++++++++++++++++ 7 files changed, 216 insertions(+), 116 deletions(-) delete mode 100644 src/components/find/findInputStyle.ts delete mode 100644 src/components/find/findMentionStyle.ts diff --git a/bun.lock b/bun.lock index 9e17343..d7091b5 100644 --- a/bun.lock +++ b/bun.lock @@ -58,13 +58,13 @@ "node-cron": "3.0.3", "pg": "^8.20.0", "qs": "^6.15.0", + "rc-mentions": "^2.20.0", "react": "19.2.4", "react-autosuggest": "^10.1.0", "react-day-picker": "9.0.8", "react-dom": "19.2.4", "react-hot-toast": "^2.6.0", "react-leaflet": "^4.2.1", - "react-mentions": "^4.4.10", "react-photo-album": "^3.5.1", "react-window": "^1.8.11", "recharts": "^2.15.4", @@ -85,7 +85,6 @@ "@types/pg": "^8.20.0", "@types/react": "19.2.14", "@types/react-dom": "19.2.3", - "@types/react-mentions": "^4.4.1", "autoprefixer": "^10.4.27", "drizzle-kit": "^0.31.10", "eslint": "^9.39.4", @@ -117,7 +116,7 @@ "@babel/parser": ["@babel/parser@7.24.1", "", { "bin": "./bin/babel-parser.js" }, "sha512-Zo9c7N3xdOIQrNip7Lc9wvRPzlRtovHVE4lkz8WEDr7uYh/GMQhSiIgFxGIArRHYdJE5kxtZjAf8rT0xhdLCzg=="], - "@babel/runtime": ["@babel/runtime@7.4.5", "", { "dependencies": { "regenerator-runtime": "^0.13.2" } }, "sha512-TuI4qpWZP6lGOGIuGWtp9sPluqYICmbk8T/1vpSysqJxRPkudh/ofFWyqdcMsDf2s7KvDL4/YHgKyvcS3g9CJQ=="], + "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], @@ -459,6 +458,10 @@ "@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + "@rc-component/portal": ["@rc-component/portal@1.1.2", "", { "dependencies": { "@babel/runtime": "^7.18.0", "classnames": "^2.3.2", "rc-util": "^5.24.4" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-6f813C0IsasTZms08kfA8kPAGxbbkYToa8ALaiDIGGECU4i9hj8Plgbx0sNJDrey3EtHO30hmdaxtT0138xZcg=="], + + "@rc-component/trigger": ["@rc-component/trigger@2.3.1", "", { "dependencies": { "@babel/runtime": "^7.23.2", "@rc-component/portal": "^1.1.0", "classnames": "^2.3.2", "rc-motion": "^2.0.0", "rc-resize-observer": "^1.3.1", "rc-util": "^5.44.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-ORENF39PeXTzM+gQEshuk460Z8N4+6DkjpxlpE7Q3gYy1iBpLrx0FOJz3h62ryrJZ/3zCAUIkT1Pb/8hHWpb3A=="], + "@react-leaflet/core": ["@react-leaflet/core@2.1.0", "", { "peerDependencies": { "leaflet": "^1.9.0", "react": "^18.0.0", "react-dom": "^18.0.0" } }, "sha512-Qk7Pfu8BSarKGqILj4x7bCSZ1pjuAPZ+qmRwH5S7mDS91VSbVVsJSrW4qA+GPrro8t69gFYVMWb1Zc4yFmPiVg=="], "@remotion/bundler": ["@remotion/bundler@4.0.232", "", { "dependencies": { "@remotion/studio": "4.0.232", "@remotion/studio-shared": "4.0.232", "css-loader": "5.2.7", "esbuild": "0.18.6", "react-refresh": "0.9.0", "remotion": "4.0.232", "source-map": "0.7.3", "style-loader": "2.0.0", "webpack": "5.96.1" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-9Z4O+D2g6cJWFsLsvOy9VOfhgrEZ8YppkuMmE4WJKgh+8r1VpwWcmWp8U/3izCNdB6njI2RVlOUBUxZX0yG94w=="], @@ -579,8 +582,6 @@ "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], - "@types/react-mentions": ["@types/react-mentions@4.4.1", "", { "dependencies": { "@types/react": "*" } }, "sha512-65QdcZYkGe2I4GnOLY2OhlXCGz/Csd8NhytwE5r59CoFeYafMltAE/WqFB/Y6SoPU8LvF7EyUrq6Rxrf0Kzxkg=="], - "@types/react-window": ["@types/react-window@1.8.8", "", { "dependencies": { "@types/react": "*" } }, "sha512-8Ls660bHR1AUA2kuRvVG9D/4XpRC6wjAaPT9dil7Ckc76eP9TKWZwwmgfq8Q1LANX3QNDnoU4Zp48A3w+zK69Q=="], "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], @@ -791,6 +792,8 @@ "classcat": ["classcat@5.0.5", "", {}, "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="], + "classnames": ["classnames@2.5.1", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="], + "client-only": ["client-only@0.0.1", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="], "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], @@ -1105,8 +1108,6 @@ "internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="], - "invariant": ["invariant@2.2.4", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="], - "is-array-buffer": ["is-array-buffer@3.0.5", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "get-intrinsic": "^1.2.6" } }, "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A=="], "is-async-function": ["is-async-function@2.1.1", "", { "dependencies": { "async-function": "^1.0.0", "call-bound": "^1.0.3", "get-proto": "^1.0.1", "has-tostringtag": "^1.0.2", "safe-regex-test": "^1.1.0" } }, "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ=="], @@ -1431,6 +1432,22 @@ "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], + "rc-input": ["rc-input@1.8.0", "", { "dependencies": { "@babel/runtime": "^7.11.1", "classnames": "^2.2.1", "rc-util": "^5.18.1" }, "peerDependencies": { "react": ">=16.0.0", "react-dom": ">=16.0.0" } }, "sha512-KXvaTbX+7ha8a/k+eg6SYRVERK0NddX8QX7a7AnRvUa/rEH0CNMlpcBzBkhI0wp2C8C4HlMoYl8TImSN+fuHKA=="], + + "rc-mentions": ["rc-mentions@2.20.0", "", { "dependencies": { "@babel/runtime": "^7.22.5", "@rc-component/trigger": "^2.0.0", "classnames": "^2.2.6", "rc-input": "~1.8.0", "rc-menu": "~9.16.0", "rc-textarea": "~1.10.0", "rc-util": "^5.34.1" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-w8HCMZEh3f0nR8ZEd466ATqmXFCMGMN5UFCzEUL0bM/nGw/wOS2GgRzKBcm19K++jDyuWCOJOdgcKGXU3fXfbQ=="], + + "rc-menu": ["rc-menu@9.16.1", "", { "dependencies": { "@babel/runtime": "^7.10.1", "@rc-component/trigger": "^2.0.0", "classnames": "2.x", "rc-motion": "^2.4.3", "rc-overflow": "^1.3.1", "rc-util": "^5.27.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-ghHx6/6Dvp+fw8CJhDUHFHDJ84hJE3BXNCzSgLdmNiFErWSOaZNsihDAsKq9ByTALo/xkNIwtDFGIl6r+RPXBg=="], + + "rc-motion": ["rc-motion@2.9.5", "", { "dependencies": { "@babel/runtime": "^7.11.1", "classnames": "^2.2.1", "rc-util": "^5.44.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-w+XTUrfh7ArbYEd2582uDrEhmBHwK1ZENJiSJVb7uRxdE7qJSYjbO2eksRXmndqyKqKoYPc9ClpPh5242mV1vA=="], + + "rc-overflow": ["rc-overflow@1.5.0", "", { "dependencies": { "@babel/runtime": "^7.11.1", "classnames": "^2.2.1", "rc-resize-observer": "^1.0.0", "rc-util": "^5.37.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-Lm/v9h0LymeUYJf0x39OveU52InkdRXqnn2aYXfWmo8WdOonIKB2kfau+GF0fWq6jPgtdO9yMqveGcK6aIhJmg=="], + + "rc-resize-observer": ["rc-resize-observer@1.4.3", "", { "dependencies": { "@babel/runtime": "^7.20.7", "classnames": "^2.2.1", "rc-util": "^5.44.1", "resize-observer-polyfill": "^1.5.1" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-YZLjUbyIWox8E9i9C3Tm7ia+W7euPItNWSPX5sCcQTYbnwDb5uNpnLHQCG1f22oZWUhLw4Mv2tFmeWe68CDQRQ=="], + + "rc-textarea": ["rc-textarea@1.10.2", "", { "dependencies": { "@babel/runtime": "^7.10.1", "classnames": "^2.2.1", "rc-input": "~1.8.0", "rc-resize-observer": "^1.0.0", "rc-util": "^5.27.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-HfaeXiaSlpiSp0I/pvWpecFEHpVysZ9tpDLNkxQbMvMz6gsr7aVZ7FpWP9kt4t7DB+jJXesYS0us1uPZnlRnwQ=="], + + "rc-util": ["rc-util@5.44.4", "", { "dependencies": { "@babel/runtime": "^7.18.3", "react-is": "^18.2.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-resueRJzmHG9Q6rI/DfK6Kdv9/Lfls05vzMs1Sk3M2P+3cJa+MakaZyWY8IPfehVuhPJFKrIY1IK4GqbiaiY5w=="], + "react": ["react@19.2.4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="], "react-autosuggest": ["react-autosuggest@10.1.0", "", { "dependencies": { "es6-promise": "^4.2.8", "prop-types": "^15.7.2", "react-themeable": "^1.1.0", "section-iterator": "^2.0.0", "shallow-equal": "^1.2.1" }, "peerDependencies": { "react": ">=16.3.0" } }, "sha512-/azBHmc6z/31s/lBf6irxPf/7eejQdR0IqnZUzjdSibtlS8+Rw/R79pgDAo6Ft5QqCUTyEQ+f0FhL+1olDQ8OA=="], @@ -1445,8 +1462,6 @@ "react-leaflet": ["react-leaflet@4.2.1", "", { "dependencies": { "@react-leaflet/core": "^2.1.0" }, "peerDependencies": { "leaflet": "^1.9.0", "react": "^18.0.0", "react-dom": "^18.0.0" } }, "sha512-p9chkvhcKrWn/H/1FFeVSqLdReGwn2qmiobOQGO3BifX+/vV/39qhY8dGqbdcPh1e6jxh/QHriLXr7a4eLFK4Q=="], - "react-mentions": ["react-mentions@4.4.10", "", { "dependencies": { "@babel/runtime": "7.4.5", "invariant": "^2.2.4", "prop-types": "^15.5.8", "substyle": "^9.1.0" }, "peerDependencies": { "react": ">=16.8.3", "react-dom": ">=16.8.3" } }, "sha512-JHiQlgF1oSZR7VYPjq32wy97z1w1oE4x10EuhKjPr4WUKhVzG1uFQhQjKqjQkbVqJrmahf+ldgBTv36NrkpKpA=="], - "react-photo-album": ["react-photo-album@3.5.1", "", { "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-g1uFG+loxdIb8eIOGnrh/71Ao80+XWV+NLfluY9qDDTbS76m+X1K6dpfNtsx1xKr9aw5N1ornkFTWpfyqOoD5Q=="], "react-refresh": ["react-refresh@0.9.0", "", {}, "sha512-Gvzk7OZpiqKSkxsQvO/mbTN1poglhmAV7gR/DdIrRrSMXraRQQlfikRJOr3Nb9GTMPC5kof948Zy6jJZIFtDvQ=="], @@ -1477,14 +1492,14 @@ "reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="], - "regenerator-runtime": ["regenerator-runtime@0.13.11", "", {}, "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="], - "regexp.prototype.flags": ["regexp.prototype.flags@1.5.4", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-errors": "^1.3.0", "get-proto": "^1.0.1", "gopd": "^1.2.0", "set-function-name": "^2.0.2" } }, "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA=="], "remotion": ["remotion@4.0.232", "", { "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-tuWZ5kQckqDL8/Zq1xLeUF+Bed1dN1sZeJ5nNbO0aBw1ETXNVrlJeobzt72lZDKZ+coU8k7sPWrIq65td1y9Gg=="], "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + "resize-observer-polyfill": ["resize-observer-polyfill@1.5.1", "", {}, "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg=="], + "resolve": ["resolve@1.22.11", "", { "dependencies": { "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ=="], "resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], @@ -1577,8 +1592,6 @@ "styled-jsx": ["styled-jsx@5.1.6", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="], - "substyle": ["substyle@9.4.1", "", { "dependencies": { "@babel/runtime": "^7.3.4", "invariant": "^2.2.4" }, "peerDependencies": { "react": ">=16.8.3" } }, "sha512-VOngeq/W1/UkxiGzeqVvDbGDPM8XgUyJVWjrqeh+GgKqspEPiLYndK+XRcsKUHM5Muz/++1ctJ1QCF/OqRiKWA=="], - "sucrase": ["sucrase@3.35.1", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "tinyglobby": "^0.2.11", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw=="], "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], @@ -1763,8 +1776,6 @@ "css-loader/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="], - "dom-helpers/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "eslint-import-resolver-node/debug": ["debug@3.2.7", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="], "eslint-import-resolver-node/resolve": ["resolve@2.0.0-next.6", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.16.1", "node-exports-info": "^1.6.0", "object-keys": "^1.1.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA=="], @@ -1799,10 +1810,6 @@ "react-themeable/object-assign": ["object-assign@3.0.0", "", {}, "sha512-jHP15vXVGeVh1HuaA2wY6lxk+whK/x4KBG88VXeRma7CCun7iGD5qPc4eYykQ9sdQvg8jkwFKsSxHln2ybW3xQ=="], - "react-transition-group/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - - "react-window/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "recast/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "sass/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], @@ -1813,8 +1820,6 @@ "source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], - "substyle/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], "terser-webpack-plugin/schema-utils": ["schema-utils@4.3.3", "", { "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", "ajv-formats": "^2.1.1", "ajv-keywords": "^5.1.0" } }, "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA=="], @@ -1929,8 +1934,6 @@ "ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], - "cmdk/@radix-ui/react-dialog/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "cmdk/@radix-ui/react-dialog/@radix-ui/primitive": ["@radix-ui/primitive@1.0.1", "", { "dependencies": { "@babel/runtime": "^7.13.10" } }, "sha512-yQ8oGX2GVsEYMWGxcovu1uGWPCxV5BFfeeYxqPmuAzUyLT9qmaMXSAhXpb0WrspIeqYzdJpkh2vHModJPgRIaw=="], "cmdk/@radix-ui/react-dialog/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.0.1", "", { "dependencies": { "@babel/runtime": "^7.13.10" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0" }, "optionalPeers": ["@types/react"] }, "sha512-fDSBgd44FKHa1FRMU59qBMPFcl2PZE+2nmqunj+BWFyYYjnhIDWL2ItDs3rrbJDQOtzt5nIebLCQc4QRfz6LJw=="], @@ -1955,8 +1958,6 @@ "cmdk/@radix-ui/react-dialog/react-remove-scroll": ["react-remove-scroll@2.5.5", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.3", "react-style-singleton": "^2.2.1", "tslib": "^2.1.0", "use-callback-ref": "^1.3.0", "use-sidecar": "^1.1.2" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-ImKhrzJJsyXJfBZ4bzu8Bwpka14c/fQt0k+cyFp/PBhTfyDnU5hjOtM4AG/0AMyy8oKzOTR0lDgJIM7pYXI0kw=="], - "cmdk/@radix-ui/react-primitive/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "cmdk/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.0.2", "", { "dependencies": { "@babel/runtime": "^7.13.10", "@radix-ui/react-compose-refs": "1.0.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0" }, "optionalPeers": ["@types/react"] }, "sha512-YeTpuq4deV+6DusvVUW4ivBgnkHwECUu0BiN43L5UCDFgdhsRUWAghhTF5MbvNTPzmiFOx90asDSUjWuCNapwg=="], "cross-fetch/node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], diff --git a/package.json b/package.json index 757748a..8c39c04 100644 --- a/package.json +++ b/package.json @@ -70,13 +70,13 @@ "node-cron": "3.0.3", "pg": "^8.20.0", "qs": "^6.15.0", + "rc-mentions": "^2.20.0", "react": "19.2.4", "react-autosuggest": "^10.1.0", "react-day-picker": "9.0.8", "react-dom": "19.2.4", "react-hot-toast": "^2.6.0", "react-leaflet": "^4.2.1", - "react-mentions": "^4.4.10", "react-photo-album": "^3.5.1", "react-window": "^1.8.11", "recharts": "^2.15.4", @@ -97,7 +97,6 @@ "@types/pg": "^8.20.0", "@types/react": "19.2.14", "@types/react-dom": "19.2.3", - "@types/react-mentions": "^4.4.1", "autoprefixer": "^10.4.27", "drizzle-kit": "^0.31.10", "eslint": "^9.39.4", diff --git a/src/components/find/FindInput.tsx b/src/components/find/FindInput.tsx index fa75919..b5a8ed2 100644 --- a/src/components/find/FindInput.tsx +++ b/src/components/find/FindInput.tsx @@ -1,50 +1,106 @@ -import React, { useState } from 'react' -import inputStyle from './findInputStyle' -import { MentionsInput, Mention } from 'react-mentions' -import { searchPeople } from '@/handlers/api/people.handler'; -import mentionStyle from './findMentionStyle'; +import React from 'react' +import Mentions from 'rc-mentions' +import { listPeople, searchPeople } from '@/handlers/api/people.handler' +import { ArrowRight, Loader2, Search, X } from 'lucide-react' +import { cn } from '@/lib/utils' interface FindInputProps { onSearch: (query: string) => void; value: string; onChange: (value: string) => void; + loading?: boolean; } -export default function FindInput({ onSearch, value, onChange }: FindInputProps) { +export default function FindInput({ onSearch, value, onChange, loading }: FindInputProps) { + const [options, setOptions] = React.useState<{ value: string; label: string }[]>([]) + const [focused, setFocused] = React.useState(false) + const nameToIdRef = React.useRef>({}) - const handleSearchPeople = async (e: any, callback: any) => { - if (!e.length) return []; - return searchPeople(e).then((people) => people.map((person: any) => ({ - id: person.id, - display: person.name, - }))).then((people) => callback(people)); + const handleMentionSearch = async (text: string, prefix: string) => { + if (prefix !== '@') { + setOptions([]) + return + } + const people = text.length + ? await searchPeople(text) + : await listPeople({ page: 1, perPage: 50, sort: 'assetCount', sortOrder: 'desc' }).then((r) => r.people) + people.forEach((person: any) => { + if (person.name) nameToIdRef.current[person.name] = person.id + }) + setOptions( + people + .filter((person: any) => person.name) + .map((person: any) => ({ + value: person.name, + label: person.name, + })) + ) + } + + const handleClear = () => { + onChange('') + } + + const buildQueryWithIds = (displayValue: string) => { + let query = displayValue + for (const [name, id] of Object.entries(nameToIdRef.current)) { + query = query.replaceAll(`@${name}`, `@${id}`) + } + return query + } + + const handleSubmit = () => { + if (value.trim()) { + onSearch(buildQueryWithIds(value)) + } + } + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Enter') { + e.preventDefault() + handleSubmit() + } } return ( - { - if (e.key === 'Enter') { - onSearch(value); - } - }} - onChange={(e) => onChange(e.target.value)}> - ( -
- {highlightedDisplay.display} -
- )} +
+ + setFocused(true)} + onBlur={() => setFocused(false)} + options={options} + rows={1} /> - + {value && !loading && ( + + )} + +
) } diff --git a/src/components/find/findInputStyle.ts b/src/components/find/findInputStyle.ts deleted file mode 100644 index 4d44afe..0000000 --- a/src/components/find/findInputStyle.ts +++ /dev/null @@ -1,45 +0,0 @@ -const findInputStyle = { - control: { - backgroundColor: 'hsl(var(--input))', - fontSize: 20, - fontWeight: 'normal', - outline: 'none', - borderRadius: '15px', - - }, - - '&singleLine': { - // display: 'inline-block', - width: '100%', - - highlighter: { - padding: '10px 15px', - border: 'none', - outline: 'none', - }, - input: { - padding: '10px 15px', - border: 'none', - outline: 'none', - }, - }, - - suggestions: { - - list: { - backgroundColor: 'hsl(var(--background))', - fontSize: 14, - border: '1px solid hsl(var(--border))', - overflow: 'hidden', - }, - item: { - padding: '5px 15px', - border: 'none', - '&focused': { - backgroundColor: 'hsl(var(--chart-2))', - }, - }, - }, -} - -export default findInputStyle; \ No newline at end of file diff --git a/src/components/find/findMentionStyle.ts b/src/components/find/findMentionStyle.ts deleted file mode 100644 index 7dc4486..0000000 --- a/src/components/find/findMentionStyle.ts +++ /dev/null @@ -1,6 +0,0 @@ -const mentionStyle: React.CSSProperties = { - backgroundColor: 'hsla(var(--chart-2) / 0.3)', - position: 'relative', -} - -export default mentionStyle; \ No newline at end of file diff --git a/src/pages/find/index.tsx b/src/pages/find/index.tsx index 0518064..053db33 100644 --- a/src/pages/find/index.tsx +++ b/src/pages/find/index.tsx @@ -51,6 +51,7 @@ export default function FindPage() { const { toast } = useToast(); // Initialize toast const { aiEnabled } = useConfig(); const [query, setQuery] = useState(''); + const [searchedQuery, setSearchedQuery] = useState(''); const [loading, setLoading] = useState(false); const [filters, setFilters] = useState({}); const [error, setError] = useState(null); @@ -92,7 +93,9 @@ export default function FindPage() { }, [filters]); const handleSearch = (query: string) => { + if (!query.trim()) return; setQuery(query); + setSearchedQuery(query); setLoading(true); setError(null); // Clear previous errors findAssets(query) @@ -193,7 +196,7 @@ export default function FindPage() {
) } - else if (query.length === 0) { + else if (searchedQuery.length === 0) { return (
@@ -209,7 +212,10 @@ export default function FindPage() { variant="outline" size="sm" className="text-xs" - onClick={() => handleSearch(suggestion.query)} + onClick={() => { + setQuery(suggestion.query); + handleSearch(suggestion.query); + }} > {suggestion.label} @@ -279,6 +285,7 @@ export default function FindPage() { value={query} onChange={setQuery} onSearch={handleSearch} + loading={loading} />
{/* renderContent now includes the Provider */} diff --git a/src/styles/globals.scss b/src/styles/globals.scss index 6c4161f..b174075 100644 --- a/src/styles/globals.scss +++ b/src/styles/globals.scss @@ -117,4 +117,92 @@ } .leaflet-control-container { z-index: 3 !important; +} + +/* rc-mentions styles for FindInput */ +.rc-mentions { + flex: 1; + min-width: 0; + width: 100%; + font-size: 16px; + font-weight: normal; + background: transparent; + border: none; + outline: none; + position: relative; + display: block; +} + +.rc-mentions > textarea { + width: 100% !important; + height: 40px !important; + padding: 10px 0; + border: none; + outline: none; + font-size: 16px; + font-weight: normal; + font-family: inherit; + background: transparent; + color: hsl(var(--foreground)); + resize: none; + white-space: nowrap; + overflow: hidden; +} + +.rc-mentions-measure { + position: absolute !important; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: -1; + color: transparent !important; + pointer-events: none; + white-space: nowrap; + overflow: hidden; +} + +.rc-mentions > textarea::placeholder { + color: hsl(var(--muted-foreground)); +} + +.rc-mentions-dropdown { + position: absolute; + z-index: 50; + background-color: hsl(var(--popover)); + border: 1px solid hsl(var(--border)); + border-radius: 8px; + overflow: hidden; + font-size: 14px; + box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); + animation: mentions-dropdown-in 0.15s ease-out; +} + +@keyframes mentions-dropdown-in { + from { + opacity: 0; + transform: translateY(-4px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.rc-mentions-dropdown-menu { + list-style: none; + margin: 0; + padding: 4px; +} + +.rc-mentions-dropdown-menu-item { + padding: 6px 12px; + cursor: pointer; + border-radius: 4px; + transition: background-color 0.1s ease; +} + +.rc-mentions-dropdown-menu-item-active { + background-color: hsl(var(--accent)); + color: hsl(var(--accent-foreground)); } \ No newline at end of file From c32e38bac74bdc1fa8adbfc9a6c33cd583a4a452 Mon Sep 17 00:00:00 2001 From: sai80082 Date: Fri, 24 Apr 2026 15:48:34 +0530 Subject: [PATCH 09/25] feat: implement permissions management with new Permission interface and refactor API key handlers --- src/config/permissions.ts | 26 +++++++++++++++++++ .../api/settings/generate-import-api-key.ts | 11 ++------ .../api/settings/generate-workflow-api-key.ts | 11 ++------ src/pages/api/settings/validate-api-key.ts | 11 ++------ src/pages/assets/import-shared.tsx | 9 +------ src/pages/settings/index.tsx | 7 ++--- src/pages/workflows/[id].tsx | 9 +------ 7 files changed, 38 insertions(+), 46 deletions(-) create mode 100644 src/config/permissions.ts diff --git a/src/config/permissions.ts b/src/config/permissions.ts new file mode 100644 index 0000000..482f5f1 --- /dev/null +++ b/src/config/permissions.ts @@ -0,0 +1,26 @@ +export interface Permission { + name: string; + description: string; +} + +export const IMPORT_PERMISSIONS: Permission[] = [ + { name: "asset.read", description: "Check for existing assets" }, + { name: "asset.upload", description: "Upload new assets" }, + { name: "album.read", description: "Read album data" }, + { name: "album.create", description: "Create new albums" }, + { name: "album.update", description: "Add assets to albums" }, + { name: "tag.create", description: "Tag imported assets" }, + { name: "tag.asset", description: "Assign tags to assets" }, +]; + +export const WORKFLOW_PERMISSIONS: Permission[] = [ + { name: "asset.read", description: "Query and filter assets" }, + { name: "asset.update", description: "Favorite, archive, update metadata" }, + { name: "album.read", description: "Read album data" }, + { name: "album.create", description: "Create new albums" }, + { name: "album.update", description: "Add/remove assets from albums" }, + { name: "tag.create", description: "Create and assign tags" }, +]; + +export const getPermissionNames = (permissions: Permission[]): string[] => + permissions.map((p) => p.name); diff --git a/src/pages/api/settings/generate-import-api-key.ts b/src/pages/api/settings/generate-import-api-key.ts index df97ea5..24f46cc 100644 --- a/src/pages/api/settings/generate-import-api-key.ts +++ b/src/pages/api/settings/generate-import-api-key.ts @@ -5,17 +5,10 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { getUserHeaders } from "@/helpers/user.helper"; import { and, eq } from "drizzle-orm"; import { NextApiRequest, NextApiResponse } from "next"; +import { IMPORT_PERMISSIONS, getPermissionNames } from "@/config/permissions"; export const IMPORT_API_KEY_SETTING = "import_api_key"; const IMPORT_KEY_NAME = "Power Tools Import Key"; -const IMPORT_PERMISSIONS = [ - "asset.read", - "asset.upload", - "album.read", - "album.create", - "album.update", - "tag.create", -]; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -26,7 +19,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const immichRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, { method: "POST", headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }), - body: JSON.stringify({ name: IMPORT_KEY_NAME, permissions: IMPORT_PERMISSIONS }), + body: JSON.stringify({ name: IMPORT_KEY_NAME, permissions: getPermissionNames(IMPORT_PERMISSIONS) }), }); if (!immichRes.ok) { diff --git a/src/pages/api/settings/generate-workflow-api-key.ts b/src/pages/api/settings/generate-workflow-api-key.ts index e5cdd8f..7053631 100644 --- a/src/pages/api/settings/generate-workflow-api-key.ts +++ b/src/pages/api/settings/generate-workflow-api-key.ts @@ -5,17 +5,10 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { getUserHeaders } from "@/helpers/user.helper"; import { and, eq } from "drizzle-orm"; import { NextApiRequest, NextApiResponse } from "next"; +import { WORKFLOW_PERMISSIONS, getPermissionNames } from "@/config/permissions"; const WORKFLOW_API_KEY_SETTING = "workflow_api_key"; const WORKFLOW_KEY_NAME = "Power Tools Workflow Key"; -const WORKFLOW_PERMISSIONS = [ - "asset.read", - "asset.update", - "album.read", - "album.create", - "album.update", - "tag.create", -]; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -27,7 +20,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const immichRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, { method: "POST", headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }), - body: JSON.stringify({ name: WORKFLOW_KEY_NAME, permissions: WORKFLOW_PERMISSIONS }), + body: JSON.stringify({ name: WORKFLOW_KEY_NAME, permissions: getPermissionNames(WORKFLOW_PERMISSIONS) }), }); if (!immichRes.ok) { diff --git a/src/pages/api/settings/validate-api-key.ts b/src/pages/api/settings/validate-api-key.ts index ff49774..61b9491 100644 --- a/src/pages/api/settings/validate-api-key.ts +++ b/src/pages/api/settings/validate-api-key.ts @@ -1,14 +1,7 @@ import { ENV } from "@/config/environment"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { NextApiRequest, NextApiResponse } from "next"; - -const WORKFLOW_PERMISSIONS = [ - "asset.read", - "asset.update", - "album.create", - "album.update", - "tag.create", -]; +import { WORKFLOW_PERMISSIONS, getPermissionNames } from "@/config/permissions"; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -19,7 +12,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const { apiKey, requiredPermissions } = req.body; if (!apiKey) return res.status(400).json({ message: "apiKey is required" }); - const REQUIRED_PERMISSIONS: string[] = Array.isArray(requiredPermissions) ? requiredPermissions : WORKFLOW_PERMISSIONS; + const REQUIRED_PERMISSIONS: string[] = Array.isArray(requiredPermissions) ? requiredPermissions : getPermissionNames(WORKFLOW_PERMISSIONS); try { const keyRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys/me`, { diff --git a/src/pages/assets/import-shared.tsx b/src/pages/assets/import-shared.tsx index 14c4301..97e7ec0 100644 --- a/src/pages/assets/import-shared.tsx +++ b/src/pages/assets/import-shared.tsx @@ -22,14 +22,7 @@ import PageLayout from "@/components/layouts/PageLayout"; import Header from "@/components/shared/Header"; import ApiKeyGate from "@/components/shared/ApiKeyGate"; -const IMPORT_PERMISSIONS = [ - { name: "asset.read", description: "Check for existing assets" }, - { name: "asset.upload", description: "Upload new assets" }, - { name: "album.read", description: "Read album data" }, - { name: "album.create", description: "Create new albums" }, - { name: "album.update", description: "Add assets to albums" }, - { name: "tag.create", description: "Tag imported assets" }, -]; +import { IMPORT_PERMISSIONS } from "@/config/permissions"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; diff --git a/src/pages/settings/index.tsx b/src/pages/settings/index.tsx index 0616f2e..a19eccf 100644 --- a/src/pages/settings/index.tsx +++ b/src/pages/settings/index.tsx @@ -12,6 +12,7 @@ import toast from "react-hot-toast"; import API from "@/lib/api"; import { useConfig } from "@/contexts/ConfigContext"; import Link from "next/link"; +import { WORKFLOW_PERMISSIONS } from "@/config/permissions"; function ConnectionStatus({ label, url, icon: Icon }: { label: string; url: string; icon: any }) { return ( @@ -74,7 +75,7 @@ export default function SettingsPage() { } }; - const IMPORT_REQUIRED_PERMISSIONS = ["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create"]; + const IMPORT_REQUIRED_PERMISSIONS = ["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create", "tag.asset"]; const saveImportApiKey = async () => { if (!importApiKey.trim()) { @@ -269,8 +270,8 @@ export default function SettingsPage() { )} {!validationResult && (
- {["asset.read", "asset.update", "album.create", "album.update", "tag.create"].map((p) => ( - {p} + {WORKFLOW_PERMISSIONS.map((p) => ( + {p.name} ))}
)} diff --git a/src/pages/workflows/[id].tsx b/src/pages/workflows/[id].tsx index 24ce4e7..3cd991c 100644 --- a/src/pages/workflows/[id].tsx +++ b/src/pages/workflows/[id].tsx @@ -39,14 +39,7 @@ import Loader from "@/components/ui/loader"; import API from "@/lib/api"; import ApiKeyGate from "@/components/shared/ApiKeyGate"; -const WORKFLOW_PERMISSIONS = [ - { name: "asset.read", description: "Query and filter assets" }, - { name: "asset.update", description: "Favorite, archive, update metadata" }, - { name: "album.read", description: "Read album data" }, - { name: "album.create", description: "Create new albums" }, - { name: "album.update", description: "Add/remove assets from albums" }, - { name: "tag.create", description: "Create and assign tags" }, -]; +import { WORKFLOW_PERMISSIONS } from "@/config/permissions"; function generateId() { return Math.random().toString(36).substring(2, 15); From 9195ceb70dae504a5e04c2deee2b4dc9f1c2a2cb Mon Sep 17 00:00:00 2001 From: sai80082 Date: Fri, 24 Apr 2026 15:54:40 +0530 Subject: [PATCH 10/25] feat: add support for Ente platform integration - Updated importJobs schema to include 'ente' as a valid platform. - Enhanced import-shared API to handle Ente shared links, including detection and fetching of albums. - Introduced new ente.ts module for Ente-specific decryption and API interactions. - Implemented thumbnail and video handling for Ente assets in import-shared API. - Created EnteSharedLinkProcessor for processing Ente shared links during import jobs. - Updated asset interfaces to accommodate Ente-specific encryption artifacts. - Registered EnteSharedLinkProcessor in the import processors registry. - Added necessary dependencies (bs58, libsodium-wrappers-sumo) to package.json and bun.lock. --- bun.lock | 13 + package.json | 3 + src/db/schema/importJobs.schema.ts | 2 +- src/pages/api/import-shared.ts | 92 ++++- src/pages/api/import-shared/ente.ts | 328 ++++++++++++++++++ src/pages/api/import-shared/thumbnail.ts | 28 ++ src/pages/api/import-shared/video.ts | 5 + src/pages/assets/import-shared.tsx | 39 ++- .../import/processors/ente-shared-link.ts | 240 +++++++++++++ src/workers/import/processors/index.ts | 2 + 10 files changed, 743 insertions(+), 9 deletions(-) create mode 100644 src/pages/api/import-shared/ente.ts create mode 100644 src/workers/import/processors/ente-shared-link.ts diff --git a/bun.lock b/bun.lock index d7091b5..975810e 100644 --- a/bun.lock +++ b/bun.lock @@ -39,6 +39,7 @@ "@xyflow/react": "^12.10.2", "ai": "^6.0.146", "axios": "^1.14.0", + "bs58": "^6.0.0", "chrono-node": "^1.4.9", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -52,6 +53,7 @@ "jsonwebtoken": "^9.0.3", "leaflet": "^1.9.4", "leaflet.heat": "^0.2.0", + "libsodium-wrappers-sumo": "^0.8.2", "lucide-react": "^0.428.0", "next": "15.5.14", "next-themes": "^0.3.0", @@ -80,6 +82,7 @@ "@types/jsonwebtoken": "^9.0.10", "@types/leaflet": "^1.9.21", "@types/leaflet.heat": "^0.2.5", + "@types/libsodium-wrappers-sumo": "^0.8.2", "@types/node": "^20.19.39", "@types/node-cron": "3.0.11", "@types/pg": "^8.20.0", @@ -564,6 +567,8 @@ "@types/leaflet.heat": ["@types/leaflet.heat@0.2.5", "", { "dependencies": { "@types/leaflet": "^1.9" } }, "sha512-wmDePJPn2vhW9BScsWTV4pSfWayhdDwXuWIQzUuaJkvk5DCHsYsIegTD7tybo38E/0mxpuWODKV/LhsxPESWJg=="], + "@types/libsodium-wrappers-sumo": ["@types/libsodium-wrappers-sumo@0.8.2", "", { "dependencies": { "libsodium-wrappers-sumo": "*" } }, "sha512-uFOBpg/r21hExVlh2ty8YpDfSR+Yy3Jn8XS4+SSjitbhTxdYq+pBz/49XRxyUFe8SzqujHf/Wu0/O4d+FUtNfQ=="], + "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], "@types/node": ["@types/node@20.19.39", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw=="], @@ -750,6 +755,8 @@ "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + "base-x": ["base-x@5.0.1", "", {}, "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.10.15", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-1nfKCq9wuAZFTkA2ey/3OXXx7GzFjLdkTiFVNwlJ9WqdI706CZRIhEqjuwanjMIja+84jDLa9rcyZDPDiVkASQ=="], "big.js": ["big.js@5.2.2", "", {}, "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ=="], @@ -762,6 +769,8 @@ "browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="], + "bs58": ["bs58@6.0.0", "", { "dependencies": { "base-x": "^5.0.0" } }, "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw=="], + "buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="], "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], @@ -1218,6 +1227,10 @@ "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], + "libsodium-sumo": ["libsodium-sumo@0.8.2", "", {}, "sha512-uMgnjphJ717jLN+jFG1HUgNrK/gOVVfaO1DGZ1Ig/fKLKLVhvaH/sM1I1v784JFvmkJDaczDpi7xSYC4Jvdo1Q=="], + + "libsodium-wrappers-sumo": ["libsodium-wrappers-sumo@0.8.2", "", { "dependencies": { "libsodium-sumo": "^0.8.0" } }, "sha512-wd1xAY++Kr6VMikSaa4EPRAHJmFvNlGWiiwU3Jh3GR1zRYF3/I3vy/wYsr4k3LVsNzwb9sqfEQ4LdVQ6zEebyQ=="], + "libsql": ["libsql@0.5.29", "", { "dependencies": { "@neon-rs/load": "^0.0.4", "detect-libc": "2.0.2" }, "optionalDependencies": { "@libsql/darwin-arm64": "0.5.29", "@libsql/darwin-x64": "0.5.29", "@libsql/linux-arm-gnueabihf": "0.5.29", "@libsql/linux-arm-musleabihf": "0.5.29", "@libsql/linux-arm64-gnu": "0.5.29", "@libsql/linux-arm64-musl": "0.5.29", "@libsql/linux-x64-gnu": "0.5.29", "@libsql/linux-x64-musl": "0.5.29", "@libsql/win32-x64-msvc": "0.5.29" }, "os": [ "linux", "win32", "darwin", ], "cpu": [ "arm", "x64", "arm64", ] }, "sha512-8lMP8iMgiBzzoNbAPQ59qdVcj6UaE/Vnm+fiwX4doX4Narook0a4GPKWBEv+CR8a1OwbfkgL18uBfBjWdF0Fzg=="], "lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="], diff --git a/package.json b/package.json index 8c39c04..7fbb851 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "@xyflow/react": "^12.10.2", "ai": "^6.0.146", "axios": "^1.14.0", + "bs58": "^6.0.0", "chrono-node": "^1.4.9", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -64,6 +65,7 @@ "jsonwebtoken": "^9.0.3", "leaflet": "^1.9.4", "leaflet.heat": "^0.2.0", + "libsodium-wrappers-sumo": "^0.8.2", "lucide-react": "^0.428.0", "next": "15.5.14", "next-themes": "^0.3.0", @@ -92,6 +94,7 @@ "@types/jsonwebtoken": "^9.0.10", "@types/leaflet": "^1.9.21", "@types/leaflet.heat": "^0.2.5", + "@types/libsodium-wrappers-sumo": "^0.8.2", "@types/node": "^20.19.39", "@types/node-cron": "3.0.11", "@types/pg": "^8.20.0", diff --git a/src/db/schema/importJobs.schema.ts b/src/db/schema/importJobs.schema.ts index 259f16d..9630ec1 100644 --- a/src/db/schema/importJobs.schema.ts +++ b/src/db/schema/importJobs.schema.ts @@ -4,7 +4,7 @@ import { randomUUID } from "crypto"; export const importJobs = sqliteTable("import_jobs", { id: text("id").primaryKey().$defaultFn(() => randomUUID()), userId: text("user_id").notNull(), - platform: text("platform").notNull(), // 'immich' | 'nextcloud' | 'photoprism' + platform: text("platform").notNull(), // 'immich' | 'nextcloud' | 'ente' | 'photoprism' status: text("status").notNull().default("pending"), // pending | processing | completed | failed url: text("url").notNull(), // base URL of source urlConfig: text("url_config").notNull().default("{}"), // JSON: auth/connection (key, token, etc.) diff --git a/src/pages/api/import-shared.ts b/src/pages/api/import-shared.ts index c2238a3..497f966 100644 --- a/src/pages/api/import-shared.ts +++ b/src/pages/api/import-shared.ts @@ -1,5 +1,6 @@ import type { NextApiRequest, NextApiResponse } from "next"; import { detectNextcloud, checkPasswordProtection, listNextcloudFiles } from "./import-shared/nextcloud"; +import { detectEnte, fetchEnteAlbum } from "./import-shared/ente"; interface IAlbumContributorCount { userId: string; @@ -66,6 +67,10 @@ interface IImportSharedAsset { location?: string | null; thumbhash?: string | null; fileSizeInByte?: number | null; + // Ente-specific encryption artifacts (optional) + enteFileKey?: string; + enteFileDecryptionHeader?: string; + enteThumbnailDecryptionHeader?: string; } interface IImportSharedAlbum { @@ -84,7 +89,7 @@ interface IImportSharedAlbum { } interface IImportSharedResponse { - platform: "immich" | "nextcloud"; + platform: "immich" | "nextcloud" | "ente"; link: string; origin: string; key: string; @@ -98,6 +103,9 @@ interface IImportSharedResponse { showMetadata?: boolean; }; album: IImportSharedAlbum | null; + // Ente-specific (optional) + enteApiBase?: string; + enteAlbumKey?: string; } const respondWithError = (res: NextApiResponse, status: number, message: string) => { @@ -246,10 +254,90 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } } + // ── Ente flow ── + const ente = detectEnte(link); + if (ente) { + try { + const result = await fetchEnteAlbum(link); + + const assets: IImportSharedAsset[] = result.files.map((f) => ({ + id: f.id, + originalFileName: f.title, + type: f.type, + fileCreatedAt: f.creationTime + ? new Date(f.creationTime / 1000).toISOString() + : null, + localDateTime: f.modificationTime + ? new Date(f.modificationTime / 1000).toISOString() + : null, + description: null, + location: null, + thumbhash: null, + fileSizeInByte: f.fileSize ?? null, + enteFileKey: f.fileKey, + enteFileDecryptionHeader: f.fileDecryptionHeader, + enteThumbnailDecryptionHeader: f.thumbnailDecryptionHeader, + })); + + const dates = result.files + .map((f) => f.creationTime) + .filter((t) => t > 0); + const startDate = + dates.length > 0 + ? new Date(Math.min(...dates) / 1000).toISOString() + : null; + const endDate = + dates.length > 0 + ? new Date(Math.max(...dates) / 1000).toISOString() + : null; + + const responseBody: IImportSharedResponse = { + platform: "ente", + link: link.trim(), + origin: result.apiBase, + key: result.token, + sharedLink: { + id: result.token, + type: "ALBUM", + createdAt: new Date().toISOString(), + expiresAt: null, + allowUpload: false, + allowDownload: true, + showMetadata: true, + }, + album: { + albumName: result.albumName, + assetCount: assets.length, + owner: null, + description: null, + startDate, + endDate, + shared: true, + hasSharedLink: true, + lastModifiedAssetTimestamp: endDate, + order: null, + contributorCounts: [], + assets, + }, + enteApiBase: result.apiBase, + enteAlbumKey: result.albumKeyB58, + }; + + return res.status(200).json(responseBody); + } catch (error: any) { + console.error("Ente import shared error", error); + return respondWithError( + res, + 500, + error?.message ?? "Failed to fetch Ente album" + ); + } + } + // ── Immich flow ── const parsed = parseSharedLink(link); if (!parsed) { - return respondWithError(res, 400, "Invalid share link. Supported: Immich or Nextcloud share URLs."); + return respondWithError(res, 400, "Invalid share link. Supported: Immich, Nextcloud, or Ente share URLs."); } const authQuery = password diff --git a/src/pages/api/import-shared/ente.ts b/src/pages/api/import-shared/ente.ts new file mode 100644 index 0000000..37ccf24 --- /dev/null +++ b/src/pages/api/import-shared/ente.ts @@ -0,0 +1,328 @@ +import _sodium from "libsodium-wrappers-sumo"; +import bs58 from "bs58"; +import { inferAssetTypeFromName } from "./helpers"; + +// ── Types ──────────────────────────────────────────────────────────────────── + +export interface EnteDetection { + apiBase: string; + token: string; + albumKeyB58: string; + albumKey: Uint8Array; +} + +export interface EnteDecryptedFile { + id: string; + title: string; + type: "IMAGE" | "VIDEO"; + creationTime: number; + modificationTime: number; + fileSize?: number; + fileKey: string; // base64 + fileDecryptionHeader: string; // base64 + thumbnailDecryptionHeader: string; // base64 +} + +export interface EnteAlbumResult { + albumName: string; + apiBase: string; + token: string; + albumKeyB58: string; + files: EnteDecryptedFile[]; +} + +interface EnteCollectionResponse { + collection: { + id: number; + encryptedKey: string; + keyDecryptionNonce: string; + encryptedName: string; + nameDecryptionNonce: string; + publicURLs?: Array<{ + enableDownload?: boolean; + enableCollect?: boolean; + }>; + }; +} + +interface EnteDiffFile { + id: number; + encryptedKey: string; + keyDecryptionNonce: string; + file: { decryptionHeader: string; size: number }; + thumbnail: { decryptionHeader: string; size: number }; + metadata: { + encryptedData: string; + decryptionHeader: string; + size: number; + }; + isDeleted: boolean; + updationTime: number; + info?: { fileSize?: number; thumbSize?: number }; +} + +interface EnteDiffResponse { + diff: EnteDiffFile[]; + hasMore: boolean; +} + +// ── Crypto ─────────────────────────────────────────────────────────────────── + +let sodiumReady: typeof _sodium | null = null; + +const initSodium = async (): Promise => { + if (sodiumReady) return sodiumReady; + await _sodium.ready; + sodiumReady = _sodium; + return _sodium; +}; + +export const decryptSecretBox = async ( + ciphertext_b64: string, + nonce_b64: string, + key: Uint8Array +): Promise => { + const sodium = await initSodium(); + const ciphertext = sodium.from_base64(ciphertext_b64, sodium.base64_variants.ORIGINAL); + const nonce = sodium.from_base64(nonce_b64, sodium.base64_variants.ORIGINAL); + return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key); +}; + +const PLAIN_CHUNK = 4 * 1024 * 1024; // 4 MiB + +export const decryptSecretStream = async ( + encryptedData: Buffer | Uint8Array, + header_b64: string, + key: Uint8Array +): Promise => { + const sodium = await initSodium(); + const header = sodium.from_base64(header_b64, sodium.base64_variants.ORIGINAL); + const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES; + const ENC_CHUNK = PLAIN_CHUNK + ABYTES; + + const state = sodium.crypto_secretstream_xchacha20poly1305_init_pull(header, key); + const out: Uint8Array[] = []; + let offset = 0; + const total = encryptedData.length; + + while (offset < total) { + const end = Math.min(offset + ENC_CHUNK, total); + const chunk = encryptedData.subarray(offset, end); + const result = sodium.crypto_secretstream_xchacha20poly1305_pull(state, chunk, null); + if (!result) throw new Error("Decryption failed: invalid secretstream chunk"); + out.push(result.message); + offset = end; + } + + return Buffer.concat(out); +}; + +// ── URL Detection ──────────────────────────────────────────────────────────── + +/** + * Detect if a URL is an Ente public album link. + * Format: https://albums.ente.io/?t=TOKEN#BASE58KEY + * Or self-hosted: https://albums.example.com/?t=TOKEN#BASE58KEY + */ +export const detectEnte = (url: string): EnteDetection | null => { + const trimmed = url.trim(); + + // Extract fragment from raw string (new URL strips it) + const hashIdx = trimmed.indexOf("#"); + if (hashIdx < 0) return null; + const fragment = trimmed.substring(hashIdx + 1); + if (!fragment) return null; + + // Parse the part before the fragment + let parsed: URL; + try { + parsed = new URL(trimmed.substring(0, hashIdx)); + } catch { + return null; + } + + const token = parsed.searchParams.get("t"); + if (!token) return null; + + // Validate base58 key + let albumKey: Uint8Array; + try { + albumKey = bs58.decode(fragment); + if (albumKey.length !== 32) return null; // XSalsa20-Poly1305 key must be 32 bytes + } catch { + return null; + } + + const apiBase = resolveApiBase(parsed); + + return { apiBase, token, albumKeyB58: fragment, albumKey }; +}; + +const resolveApiBase = (parsed: URL): string => { + if (parsed.hostname === "albums.ente.io") { + return "https://api.ente.io"; + } + // Self-hosted: replace "albums." prefix with "api." if present + if (parsed.hostname.startsWith("albums.")) { + const rest = parsed.hostname.substring("albums.".length); + return `${parsed.protocol}//api.${rest}`; + } + // Fallback: same origin + return parsed.origin; +}; + +// ── Ente API Client ────────────────────────────────────────────────────────── + +const enteHeaders = (token: string): Record => ({ + "X-Auth-Access-Token": token, + Accept: "application/json", +}); + +const getCollectionInfo = async ( + apiBase: string, + token: string +): Promise => { + const resp = await fetch(`${apiBase}/public-collection/info`, { + headers: enteHeaders(token), + timeout: 10_000, + } as RequestInit); + if (!resp.ok) { + throw new Error(`Ente API /public-collection/info failed (status ${resp.status})`); + } + return resp.json(); +}; + +const getCollectionFiles = async ( + apiBase: string, + token: string +): Promise => { + const files: EnteDiffFile[] = []; + let sinceTime = 0; + + while (true) { + const resp = await fetch( + `${apiBase}/public-collection/diff?sinceTime=${sinceTime}`, + { headers: enteHeaders(token), timeout: 15_000 } as RequestInit + ); + if (!resp.ok) { + throw new Error(`Ente API /public-collection/diff failed (status ${resp.status})`); + } + const data: EnteDiffResponse = await resp.json(); + const batch = data.diff.filter((f) => !f.isDeleted); + files.push(...batch); + + if (!data.hasMore) break; + sinceTime = Math.max(...data.diff.map((f) => f.updationTime)); + } + + return files; +}; + +/** + * Get the presigned download URL for an Ente file or thumbnail. + * The API returns a 307 redirect — we capture the Location header. + * Note: Ente uses "preview" (not "thumbnail") for the thumbnail endpoint. + */ +export const getFileRedirectUrl = async ( + apiBase: string, + token: string, + fileId: string | number, + kind: "download" | "preview" +): Promise => { + const resp = await fetch( + `${apiBase}/public-collection/files/${kind}/${fileId}`, + { + headers: enteHeaders(token), + redirect: "manual", + timeout: 15_000, + } as RequestInit + ); + + if (resp.status >= 301 && resp.status <= 308) { + const location = resp.headers.get("Location"); + if (location) return location; + } + + if (resp.ok) return resp.url; + + throw new Error( + `Ente API files/${kind}/${fileId} failed (status ${resp.status})` + ); +}; + +// ── High-level Orchestrator ────────────────────────────────────────────────── + +/** + * Fetch and decrypt an Ente shared album. + * Returns decrypted album name, file metadata, and encryption artifacts for later download. + */ +export const fetchEnteAlbum = async (url: string): Promise => { + const detection = detectEnte(url); + if (!detection) throw new Error("Invalid Ente album URL"); + + const { apiBase, token, albumKey, albumKeyB58 } = detection; + const sodium = await initSodium(); + + // Fetch collection info & decrypt album name + const info = await getCollectionInfo(apiBase, token); + const collection = info.collection; + + let albumName = "Ente Album"; + try { + const nameBytes = await decryptSecretBox( + collection.encryptedName, + collection.nameDecryptionNonce, + albumKey + ); + albumName = sodium.to_string(nameBytes); + } catch { + // Album name decryption failed — use default + } + + // Fetch all files + const rawFiles = await getCollectionFiles(apiBase, token); + + // Decrypt metadata for each file + const files: EnteDecryptedFile[] = []; + + for (const file of rawFiles) { + try { + // Decrypt per-file key using album key + const fileKey = await decryptSecretBox( + file.encryptedKey, + file.keyDecryptionNonce, + albumKey + ); + + // Decrypt metadata using file key + secretstream + const metadataBuffer = await decryptSecretStream( + Buffer.from(file.metadata.encryptedData, "base64"), + file.metadata.decryptionHeader, + fileKey + ); + const metadata = JSON.parse(metadataBuffer.toString("utf-8")); + + const title: string = metadata.title || `file_${file.id}`; + const fileType: number = metadata.fileType ?? 0; // 0=image, 1=video + const type: "IMAGE" | "VIDEO" = + fileType === 1 ? "VIDEO" : inferAssetTypeFromName(title) === "VIDEO" ? "VIDEO" : "IMAGE"; + + files.push({ + id: String(file.id), + title, + type, + creationTime: metadata.creationTime ?? 0, + modificationTime: metadata.modificationTime ?? metadata.creationTime ?? 0, + fileSize: file.info?.fileSize, + fileKey: sodium.to_base64(fileKey, sodium.base64_variants.ORIGINAL), + fileDecryptionHeader: file.file.decryptionHeader, + thumbnailDecryptionHeader: file.thumbnail.decryptionHeader, + }); + } catch (err) { + console.warn(`[Ente] Failed to decrypt metadata for file ${file.id}:`, err); + // Skip files we can't decrypt + } + } + + return { albumName, apiBase, token, albumKeyB58, files }; +}; diff --git a/src/pages/api/import-shared/thumbnail.ts b/src/pages/api/import-shared/thumbnail.ts index ae120c6..349fc7d 100644 --- a/src/pages/api/import-shared/thumbnail.ts +++ b/src/pages/api/import-shared/thumbnail.ts @@ -1,4 +1,6 @@ import type { NextApiRequest, NextApiResponse } from "next"; +import { getFileRedirectUrl, decryptSecretStream, decryptSecretBox } from "./ente"; +import _sodium from "libsodium-wrappers-sumo"; const respondWithError = (res: NextApiResponse, status: number, message: string) => { return res.status(status).json({ error: message }); @@ -59,6 +61,32 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } try { + // ── Ente: encrypted thumbnails ── + if (params.platform === "ente") { + const enteFileKey = typeof req.query.enteFileKey === "string" ? req.query.enteFileKey : ""; + const enteThumbnailHeader = typeof req.query.enteThumbnailHeader === "string" ? req.query.enteThumbnailHeader : ""; + const apiBase = typeof req.query.apiBase === "string" ? req.query.apiBase : params.origin; + + if (!enteFileKey || !enteThumbnailHeader) { + return respondWithError(res, 400, "Missing Ente encryption params (enteFileKey, enteThumbnailHeader)"); + } + + await _sodium.ready; + const fileKeyBytes = _sodium.from_base64(enteFileKey, _sodium.base64_variants.ORIGINAL); + + const redirectUrl = await getFileRedirectUrl(apiBase, params.key, params.assetId, "preview"); + const encryptedResp = await fetch(redirectUrl); + if (!encryptedResp.ok) { + return respondWithError(res, encryptedResp.status, "Failed to fetch Ente thumbnail"); + } + const encrypted = Buffer.from(await encryptedResp.arrayBuffer()); + const decrypted = await decryptSecretStream(encrypted, enteThumbnailHeader, fileKeyBytes); + + res.setHeader("Content-Type", "image/jpeg"); + res.setHeader("Cache-Control", "public, max-age=300"); + return res.status(200).send(decrypted); + } + let targetUrl: string; if (params.platform === "nextcloud") { diff --git a/src/pages/api/import-shared/video.ts b/src/pages/api/import-shared/video.ts index 876db05..c1a64be 100644 --- a/src/pages/api/import-shared/video.ts +++ b/src/pages/api/import-shared/video.ts @@ -56,6 +56,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } try { + // Ente videos are encrypted — full decryption for preview is too expensive + if (params.platform === "ente") { + return respondWithError(res, 501, "Video preview is not available for Ente imports"); + } + let targetUrl: string; let fetchHeaders: Record; diff --git a/src/pages/assets/import-shared.tsx b/src/pages/assets/import-shared.tsx index 97e7ec0..1292a6f 100644 --- a/src/pages/assets/import-shared.tsx +++ b/src/pages/assets/import-shared.tsx @@ -66,6 +66,10 @@ interface IImportSharedAsset { duration?: string | null; isFavorite?: boolean; isArchived?: boolean; + // Ente-specific encryption artifacts (optional) + enteFileKey?: string; + enteFileDecryptionHeader?: string; + enteThumbnailDecryptionHeader?: string; } interface IImportSharedAlbum { @@ -87,7 +91,7 @@ interface IImportSharedAlbum { } interface IImportSharedResponse { - platform: "immich" | "nextcloud"; + platform: "immich" | "nextcloud" | "ente"; link: string; origin: string; key: string; @@ -101,6 +105,9 @@ interface IImportSharedResponse { showMetadata?: boolean; }; album: IImportSharedAlbum | null; + // Ente-specific (optional) + enteApiBase?: string; + enteAlbumKey?: string; } const formatDate = (value?: string | null) => { @@ -340,6 +347,11 @@ export default function ImportSharedPage() { platform: sharedData.platform, }); if (asset.thumbhash) params.set("thumbhash", asset.thumbhash); + if (sharedData.platform === "ente") { + if (asset.enteFileKey) params.set("enteFileKey", asset.enteFileKey); + if (asset.enteThumbnailDecryptionHeader) params.set("enteThumbnailHeader", asset.enteThumbnailDecryptionHeader); + if (sharedData.enteApiBase) params.set("apiBase", sharedData.enteApiBase); + } return `/api/import-shared/thumbnail?${params.toString()}`; }; @@ -368,6 +380,11 @@ export default function ImportSharedPage() { platform: sharedData.platform, }); if (asset.thumbhash) params.set("thumbhash", asset.thumbhash); + if (sharedData.platform === "ente") { + if (asset.enteFileKey) params.set("enteFileKey", asset.enteFileKey); + if (asset.enteThumbnailDecryptionHeader) params.set("enteThumbnailHeader", asset.enteThumbnailDecryptionHeader); + if (sharedData.enteApiBase) params.set("apiBase", sharedData.enteApiBase); + } return `/api/import-shared/thumbnail?${params.toString()}`; }; @@ -400,10 +417,15 @@ export default function ImportSharedPage() { setImportAllLoading(true); try { const isNextcloud = sharedData.platform === "nextcloud"; + const isEnte = sharedData.platform === "ente"; const urlConfig: Record = { key: sharedData.key }; if (isNextcloud && shareLinkPassword) { urlConfig.password = shareLinkPassword; } + if (isEnte) { + if (sharedData.enteApiBase) urlConfig.apiBase = sharedData.enteApiBase; + if (sharedData.enteAlbumKey) urlConfig.albumKey = sharedData.enteAlbumKey; + } const job = await createImportJob({ platform: sharedData.platform, @@ -420,6 +442,11 @@ export default function ImportSharedPage() { isFavorite: asset.isFavorite ?? false, isArchived: asset.isArchived ?? false, ...(isNextcloud ? { relativePath: asset.id } : {}), + ...(isEnte ? { + enteFileKey: asset.enteFileKey ?? null, + enteFileDecryptionHeader: asset.enteFileDecryptionHeader ?? null, + enteThumbnailDecryptionHeader: asset.enteThumbnailDecryptionHeader ?? null, + } : {}), })), }); setActiveJobId(job.jobId); @@ -494,7 +521,7 @@ export default function ImportSharedPage() {

Import a shared album

- Paste a public shared link from Immich or Nextcloud to import its assets into your Immich instance. + Paste a public shared link from Immich, Nextcloud, or Ente to import its assets into your Immich instance.

@@ -511,7 +538,7 @@ export default function ImportSharedPage() { setShareLinkPassword(""); } }} - placeholder="Immich or Nextcloud share URL" + placeholder="Immich, Nextcloud, or Ente share URL" type="url" required className="pl-9" @@ -710,7 +737,7 @@ export default function ImportSharedPage() { : "hover:opacity-90" }`} onClick={() => { - if (isVideoAsset) { + if (isVideoAsset && sharedData?.platform !== "ente") { setActiveImageAsset(null); setActiveVideoAsset(asset); setPreviewLoading(false); @@ -751,8 +778,8 @@ export default function ImportSharedPage() { /> - {/* Video play indicator */} - {isVideoAsset && ( + {/* Video play indicator (hidden for Ente — no video preview) */} + {isVideoAsset && sharedData?.platform !== "ente" && (
diff --git a/src/workers/import/processors/ente-shared-link.ts b/src/workers/import/processors/ente-shared-link.ts new file mode 100644 index 0000000..5f1878d --- /dev/null +++ b/src/workers/import/processors/ente-shared-link.ts @@ -0,0 +1,240 @@ +import { eq } from "drizzle-orm"; +import { appDb } from "@/db"; +import { importJobItems } from "@/db/schema"; +import { ENV } from "@/config/environment"; +import { + ensurePowerToolsTag, + HeadersRecord, + createImmichAlbum, + addAssetToAlbum, + uploadAssetBuffer, + SharedAssetPayload, + DownloadedAssetPayload, + DEVICE_ID, + guessContentType, +} from "@/pages/api/import-shared/helpers"; +import { + getFileRedirectUrl, + decryptSecretStream, +} from "@/pages/api/import-shared/ente"; +import _sodium from "libsodium-wrappers-sumo"; +import type { + ImportJob, + ImportJobItem, + ImportProcessor, + ProcessorContext, + SetupResult, +} from "../types"; + +const makeDeviceAssetId = (fileId: string) => `shared-ente-${fileId}`; + +const downloadEnteAsset = async ( + apiBase: string, + token: string, + fileId: string, + fileDecryptionHeader: string, + fileKey: Uint8Array, + title: string +): Promise => { + const redirectUrl = await getFileRedirectUrl(apiBase, token, fileId, "download"); + + const response = await fetch(redirectUrl, { + method: "GET", + headers: { accept: "*/*" }, + }); + + if (!response.ok) { + throw new Error(`Failed to download Ente file ${fileId} (status ${response.status})`); + } + + const encrypted = Buffer.from(await response.arrayBuffer()); + const decrypted = await decryptSecretStream(encrypted, fileDecryptionHeader, fileKey); + + return { + buffer: decrypted, + fileName: title, + contentType: guessContentType(title), + }; +}; + +export class EnteSharedLinkProcessor implements ImportProcessor { + async setup(job: ImportJob, context: ProcessorContext): Promise { + const headers = context.headers as HeadersRecord; + + const items = await appDb + .select() + .from(importJobItems) + .where(eq(importJobItems.jobId, job.id)); + + // Build deviceAssetIds for dedup check + const deviceAssetIds: string[] = []; + const deviceAssetIdLookup = new Map(); + for (const item of items) { + const deviceAssetId = makeDeviceAssetId(item.assetId); + deviceAssetIds.push(deviceAssetId); + deviceAssetIdLookup.set(deviceAssetId.toLowerCase(), item.assetId); + } + + // Check which assets already exist in Immich + const skipAssetIds: string[] = []; + if (deviceAssetIds.length > 0) { + try { + const jsonHeaders: HeadersRecord = { ...headers, "Content-Type": "application/json" }; + const checkResponse = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { + method: "POST", + headers: jsonHeaders, + body: JSON.stringify({ deviceAssetIds, deviceId: DEVICE_ID }), + }); + + if (checkResponse.ok) { + const existPayload = await checkResponse.json().catch(() => ({})); + const existingIds: string[] = existPayload?.existingIds ?? []; + for (const deviceAssetId of existingIds) { + if (typeof deviceAssetId !== "string") continue; + const matchedAssetId = deviceAssetIdLookup.get(deviceAssetId.toLowerCase()); + if (matchedAssetId) { + skipAssetIds.push(matchedAssetId); + } + } + } else { + console.warn(`[EnteProcessor] Failed to check existing assets (status ${checkResponse.status})`); + } + } catch (error) { + console.warn("[EnteProcessor] Unable to check existing assets", error); + } + } + + // Parse importData for album options + let importData: Record = {}; + try { + importData = JSON.parse(job.importData); + } catch { + // ignore + } + + const albumOptions = importData.albumOptions as { + createAlbum?: boolean; + albumName?: string; + addToAlbumId?: string; + } | undefined; + + let albumId: string | undefined; + const jsonHeaders: HeadersRecord = { ...headers, "Content-Type": "application/json" }; + + if (albumOptions?.createAlbum) { + const desiredAlbumName = + albumOptions.albumName?.trim() || `Ente import ${new Date().toISOString()}`; + albumId = await createImmichAlbum(desiredAlbumName, jsonHeaders); + console.log(`[EnteProcessor] Created album ${albumId} (${desiredAlbumName})`); + } else if (typeof albumOptions?.addToAlbumId === "string" && albumOptions.addToAlbumId.trim()) { + albumId = albumOptions.addToAlbumId.trim(); + } + + const importDataPatch: Record = {}; + if (albumId) importDataPatch.albumId = albumId; + + const tagAssets = importData.tagAssets !== false; + if (tagAssets) { + try { + const tag = await ensurePowerToolsTag(jsonHeaders); + importDataPatch.tagId = tag.id; + } catch (err) { + console.warn("[EnteProcessor] Failed to create power-tools tag, skipping tagging", err); + } + } + + return { skipAssetIds, albumId, importDataPatch }; + } + + async processItem( + job: ImportJob, + item: ImportJobItem, + context: ProcessorContext + ): Promise<{ immichId: string }> { + const headers = context.headers as HeadersRecord; + + // Parse item metadata + encryption artifacts + let title = `file_${item.assetId}`; + let type = "IMAGE"; + let fileCreatedAt: string | null = null; + let localDateTime: string | null = null; + let enteFileKey = ""; + let enteFileDecryptionHeader = ""; + + try { + const parsed = JSON.parse(item.itemData); + title = parsed.originalFileName ?? parsed.title ?? title; + type = parsed.type ?? "IMAGE"; + fileCreatedAt = parsed.fileCreatedAt ?? null; + localDateTime = parsed.localDateTime ?? null; + enteFileKey = parsed.enteFileKey ?? ""; + enteFileDecryptionHeader = parsed.enteFileDecryptionHeader ?? ""; + } catch { + // ignore parse errors + } + + // Parse urlConfig for token and apiBase + let urlConfig: Record = {}; + try { + urlConfig = JSON.parse(job.urlConfig); + } catch { + // ignore + } + const token = typeof urlConfig.key === "string" ? urlConfig.key : ""; + const apiBase = typeof urlConfig.apiBase === "string" ? urlConfig.apiBase : job.url; + + if (!enteFileKey || !enteFileDecryptionHeader) { + throw new Error(`Missing encryption artifacts for Ente file ${item.assetId}`); + } + + // Decode file key from base64 + await _sodium.ready; + const fileKeyBytes = _sodium.from_base64(enteFileKey, _sodium.base64_variants.ORIGINAL); + + // Download and decrypt + const downloaded = await downloadEnteAsset( + apiBase, + token, + item.assetId, + enteFileDecryptionHeader, + fileKeyBytes, + title + ); + + // Build asset payload for upload + const asset: SharedAssetPayload = { + id: item.assetId, + originalFileName: title, + type, + fileCreatedAt, + localDateTime, + duration: null, + isFavorite: false, + isArchived: false, + }; + + // Strip Content-Type for multipart upload + const { ["Content-Type"]: _omit, ...uploadHeaders } = headers; + + // Read tagId from importData set during setup() + const importData = JSON.parse(job.importData) as { albumId?: string; tagId?: string }; + const tagId = importData.tagId; + + const immichId = await uploadAssetBuffer( + asset, + downloaded, + uploadHeaders as HeadersRecord, + headers as HeadersRecord, + makeDeviceAssetId(item.assetId), + tagId + ); + + // Add to album if one was resolved during setup + if (context.albumId) { + const jsonHeaders: HeadersRecord = { ...headers, "Content-Type": "application/json" }; + await addAssetToAlbum(context.albumId, immichId, jsonHeaders); + } + + return { immichId }; + } +} diff --git a/src/workers/import/processors/index.ts b/src/workers/import/processors/index.ts index 19c1d3d..b614482 100644 --- a/src/workers/import/processors/index.ts +++ b/src/workers/import/processors/index.ts @@ -1,6 +1,8 @@ import { registerProcessor } from "../registry"; import { ImmichSharedLinkProcessor } from "./immich-shared-link"; import { NextcloudSharedLinkProcessor } from "./nextcloud-shared-link"; +import { EnteSharedLinkProcessor } from "./ente-shared-link"; registerProcessor("immich", new ImmichSharedLinkProcessor()); registerProcessor("nextcloud", new NextcloudSharedLinkProcessor()); +registerProcessor("ente", new EnteSharedLinkProcessor()); From 9df6d7850148a49347bb64aa5279966fe06b1e1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Gil=20P=C3=A9rez?= Date: Mon, 20 Apr 2026 23:03:40 +0200 Subject: [PATCH 11/25] fix(AssetGrid): dim non-selected siblings during selection mode Upstream already shows the selected ring + clickable check badge on each thumbnail. This adds the missing piece for dense grids: a slight opacity reduction on non-selected items while a selection is in progress, so the selected set stays visible at a glance. Implemented by passing selectionMode={selectable && selectedIds.length > 0} from AssetGrid to LazyGridImage; LazyGridImage applies opacity-60 to its container when selectionMode && !photo.isSelected. --- src/components/shared/AssetGrid.tsx | 1 + src/components/ui/lazy-grid-image.tsx | 20 ++++++++++++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/components/shared/AssetGrid.tsx b/src/components/shared/AssetGrid.tsx index 74b33a6..160d52d 100644 --- a/src/components/shared/AssetGrid.tsx +++ b/src/components/shared/AssetGrid.tsx @@ -216,6 +216,7 @@ const AssetGrid = forwardRef(({ assets, isInternal height={context.height} selectable={selectable} onSelect={(event) => handleSelect(context.index, context.photo, event)} + selectionMode={selectable && selectedIds.length > 0} /> ); }; diff --git a/src/components/ui/lazy-grid-image.tsx b/src/components/ui/lazy-grid-image.tsx index 703bf10..4751fa5 100644 --- a/src/components/ui/lazy-grid-image.tsx +++ b/src/components/ui/lazy-grid-image.tsx @@ -13,15 +13,17 @@ interface LazyGridImageProps { height: number; selectable?: boolean; onSelect?: (event: React.MouseEvent) => void; + /** When true, dim non-selected siblings so the selected set is visible in dense grids. */ + selectionMode?: boolean; } -export default function LazyGridImage({ imageProps, photo, width, height, selectable, onSelect }: LazyGridImageProps) { +export default function LazyGridImage({ imageProps, photo, width, height, selectable, onSelect, selectionMode = false }: LazyGridImageProps) { const [isVisible, setIsVisible] = React.useState(false) const imageRef = React.useRef(null) const setupObserver = () => { const observer = new IntersectionObserver((entries) => { - + entries.forEach((entry) => { if (entry.isIntersecting) { setIsVisible(true) @@ -47,14 +49,16 @@ export default function LazyGridImage({ imageProps, photo, width, height, select
) + const dim = selectionMode && !photo.isSelected ? 'opacity-60' : ''; + return ( -
{imageProps.alt {photo.isVideo &&
@@ -62,7 +66,7 @@ export default function LazyGridImage({ imageProps, photo, width, height, select {!!photo.duration && {humanizeDuration(photo.duration)}}
} {selectable && ( -
{ e.stopPropagation(); From 54038c2512469f807e0e2295b374cdc8f9945ad0 Mon Sep 17 00:00:00 2001 From: sai80082 Date: Fri, 1 May 2026 16:17:03 +0530 Subject: [PATCH 12/25] feat: enhance release workflow with multi-platform support --- .github/workflows/release.yml | 95 ++++++++++++++++++++++++++++------- 1 file changed, 78 insertions(+), 17 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e1ea781..d57528b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,28 +7,35 @@ on: jobs: build: - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-24.04 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} permissions: - contents: write + contents: read packages: write steps: - - uses: actions/checkout@v3 + - name: Prepare platform pair + run: | + platform=${{ matrix.platform }} + echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV + + - uses: actions/checkout@v6 - name: Extract version from tag id: version run: echo "VERSION=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT - uses: docker/metadata-action@v5 - name: Docker meta id: meta with: - images: | - ghcr.io/${{ github.repository }} - tags: | - type=raw,value=latest - type=semver,pattern={{major}}.{{minor}}.{{patch}} - type=raw,value=${{ github.ref_name }} + images: ghcr.io/${{ github.repository }} - uses: docker/setup-buildx-action@v3 @@ -38,19 +45,73 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Build and push - uses: docker/build-push-action@v6 + - name: Build and push by digest + id: build + uses: docker/build-push-action@v7 with: context: . - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ steps.meta.outputs.tags }} + platforms: ${{ matrix.platform }} labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max + outputs: type=image,name=ghcr.io/${{ github.repository }},push-by-digest=true,name-canonical=true,push=true + cache-from: type=gha,scope=${{ env.PLATFORM_PAIR }} + cache-to: type=gha,mode=max,scope=${{ env.PLATFORM_PAIR }} build-args: | VERSION=${{ steps.version.outputs.VERSION }} + - name: Export digest + run: | + mkdir -p ${{ runner.temp }}/digests + digest="${{ steps.build.outputs.digest }}" + touch "${{ runner.temp }}/digests/${digest#sha256:}" + + - uses: actions/upload-artifact@v4 + with: + name: digests-${{ env.PLATFORM_PAIR }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + merge: + runs-on: ubuntu-24.04 + needs: build + permissions: + contents: write + packages: write + + steps: + - uses: actions/download-artifact@v4 + with: + path: ${{ runner.temp }}/digests + pattern: digests-* + merge-multiple: true + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - uses: docker/metadata-action@v5 + id: meta + with: + images: ghcr.io/${{ github.repository }} + tags: | + type=raw,value=latest + type=semver,pattern={{major}}.{{minor}}.{{patch}} + type=raw,value=${{ github.ref_name }} + + - name: Create manifest list and push + working-directory: ${{ runner.temp }}/digests + run: | + docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + $(printf 'ghcr.io/${{ github.repository }}@sha256:%s ' *) + + - name: Inspect image + run: | + docker buildx imagetools inspect ghcr.io/${{ github.repository }}:${{ steps.meta.outputs.version }} + - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: From b2aa043ab65b21b1a85a41ea94a1feb576cff679 Mon Sep 17 00:00:00 2001 From: sai80082 Date: Tue, 5 May 2026 14:41:36 +0530 Subject: [PATCH 13/25] feat: enhance error handling for database and API connections with detailed descriptions --- src/config/db.ts | 46 +++++++++++++++++++++++++- src/handlers/serverUtils/user.utils.ts | 24 ++++++++++++-- 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/config/db.ts b/src/config/db.ts index f39e4e1..c3b1e0d 100644 --- a/src/config/db.ts +++ b/src/config/db.ts @@ -26,6 +26,40 @@ class DatabaseConnectionError extends Error { this.error = error; } } + +const getRootCause = (error: any): any => { + let current = error; + while (current?.cause) current = current.cause; + return current; +}; + +const describePgError = (error: any): string => { + const root = getRootCause(error); + const target = `${ENV.DB_HOST || '?'}:${ENV.DB_PORT || '?'}`; + const code = root?.code as string | undefined; + + switch (code) { + case 'ENOTFOUND': + return `Cannot resolve database host "${ENV.DB_HOST}". Check DB_HOST and that the power-tools container is on the same Docker network as the Immich Postgres container (use the container name, e.g. "immich_postgres").`; + case 'ECONNREFUSED': + return `Connection refused at ${target}. The host is reachable but nothing is listening on that port — check DB_PORT and that Postgres is running.`; + case 'ETIMEDOUT': + case 'EHOSTUNREACH': + case 'ENETUNREACH': + return `Cannot reach ${target} (${code}). Likely a network/firewall issue or the wrong DB_HOST for this container.`; + case '28P01': + return `Password authentication failed for user "${ENV.DB_USERNAME}". Check DB_PASSWORD (and ensure no extra quotes/spaces in .env).`; + case '28000': + return `Authentication failed for user "${ENV.DB_USERNAME}" at ${target}. Check DB_USERNAME and pg_hba rules.`; + case '3D000': + return `Database "${ENV.DB_DATABASE_NAME}" does not exist on ${target}. Check DB_DATABASE_NAME.`; + case '57P03': + return `Postgres at ${target} is starting up and not yet ready to accept connections.`; + default: + return `${root?.message || error?.message || 'Unknown error'}${code ? ` (code: ${code})` : ''} — target ${target}, user "${ENV.DB_USERNAME}", db "${ENV.DB_DATABASE_NAME}".`; + } +}; + export const connectDB = async (db: NodePgDatabase) => { try { const missingKeys = findMissingKeys(ENV, ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DATABASE_NAME']); @@ -38,7 +72,17 @@ export const connectDB = async (db: NodePgDatabase) => { return await db.execute(sql`SELECT 1`); // Execute a simple query } } catch (error: any) { - throw new DatabaseConnectionError(error.message, "Database connection failed"); + if (error instanceof APIError) throw error; + const root = getRootCause(error); + console.error('[db] connection failed:', { + code: root?.code, + message: root?.message, + host: ENV.DB_HOST, + port: ENV.DB_PORT, + user: ENV.DB_USERNAME, + database: ENV.DB_DATABASE_NAME, + }); + throw new DatabaseConnectionError(describePgError(error), "Database connection failed"); } } diff --git a/src/handlers/serverUtils/user.utils.ts b/src/handlers/serverUtils/user.utils.ts index 6756e1a..93282e0 100644 --- a/src/handlers/serverUtils/user.utils.ts +++ b/src/handlers/serverUtils/user.utils.ts @@ -6,6 +6,24 @@ import { getCookie } from "@/lib/cookie" import { NextApiRequest } from "next" +const describeFetchError = (error: any, url: string): string => { + let current = error; + while (current?.cause) current = current.cause; + const code = current?.code as string | undefined; + switch (code) { + case 'ENOTFOUND': + return `Cannot resolve host for ${url}. Check IMMICH_URL — from inside this container, an IP on the host network may not be reachable; prefer the Immich container name (e.g. http://immich_server:2283).`; + case 'ECONNREFUSED': + return `Connection refused at ${url}. Check that the Immich server is running and that IMMICH_URL points to its internal port (default 2283).`; + case 'ETIMEDOUT': + case 'EHOSTUNREACH': + case 'ENETUNREACH': + return `Cannot reach Immich API at ${url} (${code}). Likely the power-tools container is not on the same network as the Immich server.`; + default: + return `Failed to connect to Immich API at ${url}: ${current?.message || error?.message || 'Unknown error'}${code ? ` (${code})` : ''}`; + } +}; + export const getCurrentUserFromAPIKey = () => { if (!ENV.IMMICH_URL || !ENV.IMMICH_API_KEY) return null; @@ -32,8 +50,9 @@ export const getCurrentUserFromAPIKey = () => { if (error instanceof APIError) { throw error; } + console.error('[immich-api] connect failed:', { url: ENV.IMMICH_URL, message: error?.message, cause: error?.cause }); throw new APIError({ - message: "Failed to connect to Immich API: " + ENV.IMMICH_URL, + message: describeFetchError(error, ENV.IMMICH_URL), status: 500, }); }) @@ -51,8 +70,9 @@ export const getCurrentUserFromAccessToken = (token: string) => { } return null }).catch((error) => { + console.error('[immich-api] connect failed:', { url: ENV.IMMICH_URL, message: error?.message, cause: error?.cause }); throw new APIError({ - message: "Failed to connect to Immich API: " + ENV.IMMICH_URL, + message: describeFetchError(error, ENV.IMMICH_URL), status: 500, }); }) From e3c71704481b8eecedaaf1697671632079cd2273 Mon Sep 17 00:00:00 2001 From: tikibozo <4793440+tikibozo@users.noreply.github.com> Date: Thu, 21 May 2026 00:37:39 -0700 Subject: [PATCH 14/25] fix(api): raise bodyParser limit on albums-by-assets The /api/assets/albums-by-assets route accepts a POST body shaped { assetIds: string[] } and is invoked from the bulk-duplicate-finder page with every asset across every duplicate group. With a large duplicate set the body easily exceeds Next.js's default 1 MB bodyParser limit and the route returns 413 before the handler runs. Concrete case: a library with ~14,500 duplicate groups produces a request body around 1.4-1.8 MB, which is rejected. The page renders but never finishes loading (413 in browser console). Fix: add the per-route Next.js bodyParser config to bump the limit to 10 MB, leaving plenty of headroom for very large libraries while still bounding worst-case request size. --- src/pages/api/assets/albums-by-assets.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/pages/api/assets/albums-by-assets.ts b/src/pages/api/assets/albums-by-assets.ts index 3573a9a..cf29784 100644 --- a/src/pages/api/assets/albums-by-assets.ts +++ b/src/pages/api/assets/albums-by-assets.ts @@ -5,6 +5,14 @@ import { albums } from "@/schema/albums.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; import { eq, inArray, and } from "drizzle-orm"; +export const config = { + api: { + bodyParser: { + sizeLimit: "10mb", + }, + }, +}; + export default async function handler( req: NextApiRequest, res: NextApiResponse From af4cfceb475f6672874bfeef0460e9c6d13754fd Mon Sep 17 00:00:00 2001 From: sai80082 Date: Thu, 2 Jul 2026 20:13:29 +0530 Subject: [PATCH 15/25] fix: migrate to Immich v3.0 API and DB schema - Updated albumColumns and AlbumThumbnail components to display placeholder when no thumbnail is available. - added album_user table (album ownership moved here, role='owner') - drop asset.deviceId/deviceAssetId and albums.ownerId - asset.duration varchar -> integer (milliseconds) - removed isArchived instead use visibility --- src/components/albums/AlbumTableColumns.tsx | 40 ++++++++++------- src/components/albums/list/AlbumThumbnail.tsx | 44 +++++++++++++------ src/helpers/string.helper.ts | 24 +++++----- src/lib/workflow/actionExecutor.ts | 5 +-- src/pages/api/albums/[id]/assets.ts | 1 - src/pages/api/albums/[id]/info.ts | 4 +- src/pages/api/albums/[id]/people.ts | 4 +- src/pages/api/albums/list.ts | 8 ++-- src/pages/api/albums/merge.ts | 10 ++++- .../api/albums/potential-albums-assets.ts | 1 - src/pages/api/assets/albums-by-assets.ts | 4 +- src/pages/api/assets/empty-videos.ts | 10 +---- .../api/assets/missing-location-assets.ts | 2 - src/pages/api/assets/orphan-finder.ts | 1 - src/pages/api/share-link/[token]/assets.ts | 3 +- src/pages/api/validate-permissions.ts | 6 ++- src/schema/albumUsers.schema.ts | 8 ++++ src/schema/albums.schema.ts | 1 - src/schema/assets.schema.ts | 6 +-- src/types/asset.d.ts | 7 +-- 20 files changed, 110 insertions(+), 79 deletions(-) create mode 100644 src/schema/albumUsers.schema.ts diff --git a/src/components/albums/AlbumTableColumns.tsx b/src/components/albums/AlbumTableColumns.tsx index 2109247..7ed9bb6 100644 --- a/src/components/albums/AlbumTableColumns.tsx +++ b/src/components/albums/AlbumTableColumns.tsx @@ -2,7 +2,7 @@ import { ColumnDef } from "@tanstack/react-table" import { IAlbum } from "@/types/album" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" -import { ArrowUpDown, MoreHorizontal, Calendar, Camera, Users, HardDrive } from "lucide-react" +import { ArrowUpDown, MoreHorizontal, Calendar, Camera, Users, HardDrive, ImageOff } from "lucide-react" import { DropdownMenu, DropdownMenuContent, @@ -48,15 +48,21 @@ export const albumColumns: ColumnDef[] = [ const album = row.original return (
- + {album.albumThumbnailAssetId ? ( + + ) : ( +
+ +
+ )}
) }, @@ -164,16 +170,20 @@ export const albumColumns: ColumnDef[] = [ }, cell: ({ row }) => { const album = row.original - const numberOfDays = differenceInDays(album.lastPhotoDate, album.firstPhotoDate) - + const numberOfDays = (album.firstPhotoDate && album.lastPhotoDate) + ? differenceInDays(album.lastPhotoDate, album.firstPhotoDate) + : null + return (
{album.firstPhotoDate ? formatDate(album.firstPhotoDate.toString(), 'MMM d, yyyy') : ''} - {album.lastPhotoDate ? formatDate(album.lastPhotoDate.toString(), 'MMM d, yyyy') : ''}
-
- {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`} -
+ {numberOfDays !== null && ( +
+ {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`} +
+ )}
) }, diff --git a/src/components/albums/list/AlbumThumbnail.tsx b/src/components/albums/list/AlbumThumbnail.tsx index af70d22..45dbb0e 100644 --- a/src/components/albums/list/AlbumThumbnail.tsx +++ b/src/components/albums/list/AlbumThumbnail.tsx @@ -8,7 +8,7 @@ import { IAlbum } from '@/types/album'; import { formatDate } from '@/helpers/date.helper'; import { Checkbox } from '@/components/ui/checkbox'; import { differenceInDays } from 'date-fns'; -import { Calendar, Camera } from 'lucide-react'; +import { Calendar, Camera, ImageOff } from 'lucide-react'; interface IAlbumThumbnailProps { album: IAlbum; @@ -18,6 +18,9 @@ interface IAlbumThumbnailProps { export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThumbnailProps) { const numberOfDays = useMemo(() => { + if (!album.firstPhotoDate || !album.lastPhotoDate) { + return null; + } return differenceInDays(album.lastPhotoDate, album.firstPhotoDate); }, [album.firstPhotoDate, album.lastPhotoDate]); @@ -29,16 +32,27 @@ export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThum return (
-

- {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString() } days`} -

+ {numberOfDays !== null && ( +

+ {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString() } days`} +

+ )}
diff --git a/src/helpers/string.helper.ts b/src/helpers/string.helper.ts index 28e77e4..db06d16 100644 --- a/src/helpers/string.helper.ts +++ b/src/helpers/string.helper.ts @@ -7,6 +7,9 @@ export const pluralize = (number: number, word: string, pluralWord: string) => { } export const humanizeBytes = (bytes: number) => { + if (!bytes || isNaN(bytes)) { + return `0 bytes` + } if (bytes < 1024) { return `${bytes} bytes` } @@ -19,22 +22,23 @@ export const humanizeBytes = (bytes: number) => { return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB` } -export const humanizeDuration = (duration: string) => { - if (!duration) { +export const humanizeDuration = (duration: string | number | null | undefined) => { + if (duration === null || duration === undefined || duration === '') { return null; } - // Example input : 00:00:04.350 - const [hours, minutes, seconds] = duration.split(':').map(Number); - const totalSeconds = Math.round(hours * 3600 + minutes * 60 + seconds); + const ms = Number(duration); + if (isNaN(ms)) { + return null; + } + const totalSeconds = Math.round(ms / 1000); if (totalSeconds < 60) { return `${totalSeconds}s`; } + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); if (totalSeconds < 3600) { - // Show only minutes - return `${Math.round(minutes)}m`; + return `${minutes}m`; } - - - return `${Math.round(hours)}h ${Math.round(minutes)}m`; + return `${hours}h ${minutes}m`; } diff --git a/src/lib/workflow/actionExecutor.ts b/src/lib/workflow/actionExecutor.ts index 3625a93..1fd09b1 100644 --- a/src/lib/workflow/actionExecutor.ts +++ b/src/lib/workflow/actionExecutor.ts @@ -163,16 +163,15 @@ export async function executeAction( } case "archive": { - await immichFetch("/assets", "PUT", { ids: assetIds, isArchived: true }, user); + await immichFetch("/assets", "PUT", { ids: assetIds, visibility: "archive" }, user); return { action: "archive", assetsProcessed: assetIds.length }; } case "tag": { if (!config.tagName) throw new Error("Tag name is required"); - // Tags API may vary by Immich version — try the standard approach try { // Create or get tag - const tag = await immichFetch("/tags", "POST", { name: config.tagName, type: "OBJECT" }, user); + const tag = await immichFetch("/tags", "POST", { name: config.tagName }, user); // Tag assets await immichFetch(`/tags/${tag.id}/assets`, "PUT", { ids: assetIds }, user); return { action: "tag", assetsProcessed: assetIds.length }; diff --git a/src/pages/api/albums/[id]/assets.ts b/src/pages/api/albums/[id]/assets.ts index 2c0e683..17327af 100644 --- a/src/pages/api/albums/[id]/assets.ts +++ b/src/pages/api/albums/[id]/assets.ts @@ -29,7 +29,6 @@ export default async function handler( } const dbAssets = await db.selectDistinctOn([assets.id], { id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/albums/[id]/info.ts b/src/pages/api/albums/[id]/info.ts index e0fb466..c9dc209 100644 --- a/src/pages/api/albums/[id]/info.ts +++ b/src/pages/api/albums/[id]/info.ts @@ -7,6 +7,7 @@ import { albums } from "@/schema/albums.schema"; import { count, eq, min, max, sql, and } from "drizzle-orm"; import { assets } from "@/schema/assets.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { assetFaces, exif, person } from "@/schema"; export default async function handler( @@ -31,12 +32,13 @@ export default async function handler( faceCount: count(sql`DISTINCT ${person.id}`), // Ensure unique personId }) .from(albums) + .innerJoin(albumUsers, and(eq(albums.id, albumUsers.albumId), eq(albumUsers.role, "owner"))) .leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumId)) .leftJoin(assets, eq(albumsAssetsAssets.assetId, assets.id)) .leftJoin(exif, and(eq(assets.id, exif.assetId), eq(assets.visibility, "timeline"))) .leftJoin(assetFaces, eq(assets.id, assetFaces.assetId)) .leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false))) - .where(and(eq(albums.ownerId, currentUser.id), eq(albums.id, id))) + .where(and(eq(albumUsers.userId, currentUser.id), eq(albums.id, id))) .groupBy(albums.id) .limit(1); diff --git a/src/pages/api/albums/[id]/people.ts b/src/pages/api/albums/[id]/people.ts index b39c3db..364af31 100644 --- a/src/pages/api/albums/[id]/people.ts +++ b/src/pages/api/albums/[id]/people.ts @@ -7,6 +7,7 @@ import { albums } from "@/schema/albums.schema"; import { count, desc, eq, and, isNotNull } from "drizzle-orm"; import { assets } from "@/schema/assets.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { assetFaces, person } from "@/schema"; export default async function handler( @@ -26,11 +27,12 @@ export default async function handler( numberOfPhotos: count(assets.id), }) .from(albums) + .innerJoin(albumUsers, and(eq(albums.id, albumUsers.albumId), eq(albumUsers.role, "owner"))) .leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumId)) .leftJoin(assets, eq(albumsAssetsAssets.assetId, assets.id)) .leftJoin(assetFaces, eq(assets.id, assetFaces.assetId)) .leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false))) - .where(and(eq(albums.ownerId, currentUser.id), eq(albums.id, id), isNotNull(person.id))) + .where(and(eq(albumUsers.userId, currentUser.id), eq(albums.id, id), isNotNull(person.id))) .orderBy(desc(person.name)) .groupBy(person.id); diff --git a/src/pages/api/albums/list.ts b/src/pages/api/albums/list.ts index 4eb2f17..275b375 100644 --- a/src/pages/api/albums/list.ts +++ b/src/pages/api/albums/list.ts @@ -7,6 +7,7 @@ import { albums } from "@/schema/albums.schema"; import { count, desc, eq, min, max, sql, and, sum, isNotNull } from "drizzle-orm"; import { assets } from "@/schema/assets.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { assetFaces, exif, person } from "@/schema"; import { IAlbum } from "@/types/album"; @@ -63,12 +64,13 @@ export default async function handler( size: sum(exif.fileSizeInByte), order: albums.order, isActivityEnabled: albums.isActivityEnabled, - ownerId: albums.ownerId, + ownerId: albumUsers.userId, description: albums.description, lastModifiedAssetTimestamp: max(exif.dateTimeOriginal), faceCount: count(sql`DISTINCT ${assetFaces.personId}`), // Ensure unique personId }) .from(albums) + .innerJoin(albumUsers, and(eq(albums.id, albumUsers.albumId), eq(albumUsers.role, "owner"))) .leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumId)) .leftJoin(assets, and( eq(albumsAssetsAssets.assetId, assets.id), @@ -78,8 +80,8 @@ export default async function handler( .leftJoin(exif, eq(assets.id, exif.assetId)) .leftJoin(assetFaces, eq(assets.id, assetFaces.assetId)) .leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false))) - .where(eq(albums.ownerId, currentUser.id)) - .groupBy(albums.id) + .where(eq(albumUsers.userId, currentUser.id)) + .groupBy(albums.id, albumUsers.userId) .orderBy(desc(albums.createdAt)); const sortedAlbums = sortAlbums(dbAlbums as IAlbum[], sortBy, sortOrder); diff --git a/src/pages/api/albums/merge.ts b/src/pages/api/albums/merge.ts index 45e56ab..979c2fe 100644 --- a/src/pages/api/albums/merge.ts +++ b/src/pages/api/albums/merge.ts @@ -5,6 +5,7 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import API from "@/lib/api"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; import { albums } from "@/schema/albums.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { and, eq, inArray } from "drizzle-orm"; import { NextApiRequest, NextApiResponse } from "next"; @@ -35,11 +36,16 @@ export default async function handler( }); } + const ownedAlbumIds = db + .select({ albumId: albumUsers.albumId }) + .from(albumUsers) + .where(and(eq(albumUsers.userId, currentUser.id), eq(albumUsers.role, "owner"))); + const primaryAlbum = await db .select() .from(albums) .where( - and(eq(albums.id, primaryAlbumId), eq(albums.ownerId, currentUser.id)) + and(eq(albums.id, primaryAlbumId), inArray(albums.id, ownedAlbumIds)) ) .limit(1); @@ -51,7 +57,7 @@ export default async function handler( const secondaryAlbums = await db .select() .from(albums) - .where(and(inArray(albums.id, secondaryAlbumIds), eq(albums.ownerId, currentUser.id))); + .where(and(inArray(albums.id, secondaryAlbumIds), inArray(albums.id, ownedAlbumIds))); if (secondaryAlbums.length === 0) { diff --git a/src/pages/api/albums/potential-albums-assets.ts b/src/pages/api/albums/potential-albums-assets.ts index 10832cc..89d078f 100644 --- a/src/pages/api/albums/potential-albums-assets.ts +++ b/src/pages/api/albums/potential-albums-assets.ts @@ -9,7 +9,6 @@ const SELECT_ORPHAN_PHOTOS = (date: string, ownerId: string) => SELECT a."id", a."ownerId", - a."deviceId", a."type", a."originalPath", a."isFavorite", diff --git a/src/pages/api/assets/albums-by-assets.ts b/src/pages/api/assets/albums-by-assets.ts index cf29784..511c76f 100644 --- a/src/pages/api/assets/albums-by-assets.ts +++ b/src/pages/api/assets/albums-by-assets.ts @@ -3,6 +3,7 @@ import { db } from "@/config/db"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { albums } from "@/schema/albums.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { eq, inArray, and } from "drizzle-orm"; export const config = { @@ -39,10 +40,11 @@ export default async function handler( }) .from(albumsAssetsAssets) .innerJoin(albums, eq(albumsAssetsAssets.albumId, albums.id)) + .innerJoin(albumUsers, and(eq(albumUsers.albumId, albums.id), eq(albumUsers.role, "owner"))) .where( and( inArray(albumsAssetsAssets.assetId, assetIds), - eq(albums.ownerId, currentUser.id) + eq(albumUsers.userId, currentUser.id) ) ); diff --git a/src/pages/api/assets/empty-videos.ts b/src/pages/api/assets/empty-videos.ts index 4a7b62d..46d4fbd 100644 --- a/src/pages/api/assets/empty-videos.ts +++ b/src/pages/api/assets/empty-videos.ts @@ -39,19 +39,11 @@ export default async function handler( } - const durationExpr = sql` - ( - CAST(SUBSTRING(${assets.duration}, 1, 2) AS DECIMAL) * 3600 + - CAST(SUBSTRING(${assets.duration}, 4, 2) AS DECIMAL) * 60 + - CAST(SUBSTRING(${assets.duration}, 7, 2) AS DECIMAL) + - CAST(SUBSTRING(${assets.duration}, 10, 3) AS DECIMAL) / 1000 - ) -`; + const durationExpr = sql`(${assets.duration}::decimal / 1000)`; const dbAssets = await db .selectDistinctOn([assets.id], { id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/assets/missing-location-assets.ts b/src/pages/api/assets/missing-location-assets.ts index e7bd342..09105a4 100644 --- a/src/pages/api/assets/missing-location-assets.ts +++ b/src/pages/api/assets/missing-location-assets.ts @@ -15,7 +15,6 @@ const getRowsByDates = async (startDateDate: Date, endDateDate: Date, currentUse return db .select({ id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, @@ -46,7 +45,6 @@ const getRowsByDates = async (startDateDate: Date, endDateDate: Date, currentUse const getRowsByAlbums = async (currentUser: IUser, albumId: string) => { return db.select({ id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/assets/orphan-finder.ts b/src/pages/api/assets/orphan-finder.ts index 55c3e82..ffd682b 100644 --- a/src/pages/api/assets/orphan-finder.ts +++ b/src/pages/api/assets/orphan-finder.ts @@ -67,7 +67,6 @@ export default async function handler( const dbAssets = await db .selectDistinctOn([assets.id], { id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/share-link/[token]/assets.ts b/src/pages/api/share-link/[token]/assets.ts index a458a71..bfbc939 100644 --- a/src/pages/api/share-link/[token]/assets.ts +++ b/src/pages/api/share-link/[token]/assets.ts @@ -56,7 +56,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const dbAssets = await db.select({ id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, @@ -92,7 +91,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) return { ...asset, localDateTime: new Date(asset.localDateTime), - duration: asset.duration ? parseInt(asset.duration) : 0, + duration: asset.duration ?? 0, exifImageWidth: (isFlipped(asset.orientation) ? asset.exifImageHeight : asset.exifImageWidth) ?? 0, exifImageHeight: (isFlipped(asset.orientation) ? asset.exifImageWidth : asset.exifImageHeight) ?? 0, dateTimeOriginal: new Date(asset.dateTimeOriginal || new Date()).toISOString(), diff --git a/src/pages/api/validate-permissions.ts b/src/pages/api/validate-permissions.ts index 37959f9..7e65f89 100644 --- a/src/pages/api/validate-permissions.ts +++ b/src/pages/api/validate-permissions.ts @@ -19,10 +19,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) // Test asset upload permission by calling a no-op endpoint try { - const response = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { + const response = await fetch(`${ENV.IMMICH_URL}/api/assets/bulk-upload-check`, { method: "POST", headers, - body: JSON.stringify({ deviceAssetIds: ["permission-check"], deviceId: "immich-power-tools-check" }), + body: JSON.stringify({ + assets: [{ id: "permission-check", checksum: "0000000000000000000000000000000000000000" }], + }), }); result.canUpload = response.ok; } catch { diff --git a/src/schema/albumUsers.schema.ts b/src/schema/albumUsers.schema.ts new file mode 100644 index 0000000..13fee97 --- /dev/null +++ b/src/schema/albumUsers.schema.ts @@ -0,0 +1,8 @@ +import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core'; + +export const albumUsers = pgTable('album_user', { + albumId: uuid('albumId').notNull(), + userId: uuid('userId').notNull(), + role: varchar('role').notNull().default('editor'), + createdAt: timestamp('createdAt', { withTimezone: true }).defaultNow().notNull(), +}); diff --git a/src/schema/albums.schema.ts b/src/schema/albums.schema.ts index aed3f0c..11f8d34 100644 --- a/src/schema/albums.schema.ts +++ b/src/schema/albums.schema.ts @@ -2,7 +2,6 @@ import { pgTable, uuid, varchar, timestamp, boolean, text } from 'drizzle-orm/pg export const albums = pgTable('album', { 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'), diff --git a/src/schema/assets.schema.ts b/src/schema/assets.schema.ts index 0a12372..67b99b2 100644 --- a/src/schema/assets.schema.ts +++ b/src/schema/assets.schema.ts @@ -1,16 +1,14 @@ -import { pgTable, uuid, varchar, timestamp, boolean } from 'drizzle-orm/pg-core'; +import { pgTable, uuid, varchar, timestamp, boolean, integer } from 'drizzle-orm/pg-core'; export const assets = pgTable('asset', { id: uuid('id').defaultRandom().primaryKey().notNull(), - deviceAssetId: varchar('deviceAssetId').notNull(), ownerId: uuid('ownerId').notNull(), - deviceId: varchar('deviceId').notNull(), type: varchar('type').notNull(), originalPath: varchar('originalPath').notNull(), fileCreatedAt: timestamp('fileCreatedAt', { withTimezone: true }).notNull(), fileModifiedAt: timestamp('fileModifiedAt', { withTimezone: true }).notNull(), isFavorite: boolean('isFavorite').default(false).notNull(), - duration: varchar('duration'), + duration: integer('duration'), // checksum: bytea('checksum').notNull(), visibility: varchar('visibility').default('timeline').notNull(), livePhotoVideoId: uuid('livePhotoVideoId').references((): any => assets.id, { onDelete: 'set null', onUpdate: 'cascade' }), diff --git a/src/types/asset.d.ts b/src/types/asset.d.ts index baedc41..38f3f67 100644 --- a/src/types/asset.d.ts +++ b/src/types/asset.d.ts @@ -1,7 +1,6 @@ export interface IAsset { id: string; ownerId: string; - deviceId: string; type: string; originalPath: string; isFavorite: boolean; @@ -32,9 +31,7 @@ export interface IDuplicateAssetRecord { export interface IDuplicateAsset { id: string; - deviceAssetId: string; ownerId: string; - deviceId: string; libraryId: null; type: string; originalPath: string; @@ -46,10 +43,8 @@ export interface IDuplicateAsset { localDateTime: Date; updatedAt: Date; isFavorite: boolean; - isArchived: boolean; - isTrashed: boolean; visibility: string; - duration: string; + duration: number | null; exifInfo: IDuplicateAssetExifInfo; livePhotoVideoId: null; people: any[]; From 46768eea7a9b672ae6236c5e8f8ec9e43833d46f Mon Sep 17 00:00:00 2001 From: sai80082 Date: Thu, 2 Jul 2026 20:26:53 +0530 Subject: [PATCH 16/25] fix: update README and asset upload for Immich v3.0 compatibility --- README.md | 3 + src/pages/api/import-shared.ts | 86 ++++++++++--------- src/pages/api/import-shared/helpers.ts | 52 +++++++++-- src/pages/api/import-shared/upload-all.ts | 51 ++--------- src/pages/api/import-shared/upload.ts | 5 +- .../import/processors/immich-shared-link.ts | 60 ++++--------- .../processors/nextcloud-shared-link.ts | 41 --------- 7 files changed, 119 insertions(+), 179 deletions(-) diff --git a/README.md b/README.md index 52d4cc5..33e7196 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ A unofficial immich client to provide better tools to organize and manage your immich account. Building it to speed up your workflows in Immich to organize your people and albums. +> [!IMPORTANT] +> **Immich v3.0 compatibility:** Power Tools **v0.22.0 and above require Immich 3.0 or newer**. + [Watch Demo Video here](https://www.loom.com/embed/13aa90d8ab2e4acab0993bdc8703a750?sid=71498690-b745-473f-b239-a7bdbe6efc21) [![Immich Power Tools](./screenshots/screenshot-1.png)](https://www.loom.com/embed/13aa90d8ab2e4acab0993bdc8703a750?sid=71498690-b745-473f-b239-a7bdbe6efc21) diff --git a/src/pages/api/import-shared.ts b/src/pages/api/import-shared.ts index c2238a3..1a4d983 100644 --- a/src/pages/api/import-shared.ts +++ b/src/pages/api/import-shared.ts @@ -11,28 +11,10 @@ interface ImmichOwner { email?: string | null; } -interface ImmichExifInfo { - city?: string | null; - state?: string | null; - country?: string | null; - description?: string | null; - fileSizeInByte?: number | null; -} - -interface ImmichAsset { - id: string; - originalFileName: string; - type: string; - fileCreatedAt?: string | null; - localDateTime?: string | null; - thumbhash?: string | null; - exifInfo?: ImmichExifInfo | null; -} - interface ImmichAlbumResponse { albumName: string; assetCount?: number; - owner?: ImmichOwner | null; + albumUsers?: { user: ImmichOwner; role: string }[]; description?: string | null; startDate?: string | null; endDate?: string | null; @@ -41,7 +23,6 @@ interface ImmichAlbumResponse { lastModifiedAssetTimestamp?: string | null; order?: string | null; contributorCounts?: IAlbumContributorCount[]; - assets: ImmichAsset[]; } interface ImmichSharedLinkResponse { @@ -58,7 +39,7 @@ interface ImmichSharedLinkResponse { interface IImportSharedAsset { id: string; - originalFileName: string; + originalFileName?: string; type: string; fileCreatedAt?: string | null; localDateTime?: string | null; @@ -68,6 +49,15 @@ interface IImportSharedAsset { fileSizeInByte?: number | null; } +interface ITimeBucketAssets { + id: string[]; + fileCreatedAt: string[]; + isImage: boolean[]; + thumbhash: (string | null)[]; + city?: (string | null)[]; + country?: (string | null)[]; +} + interface IImportSharedAlbum { albumName: string; assetCount: number; @@ -122,13 +112,39 @@ const parseSharedLink = (link: string) => { } }; -const buildLocationString = (exif?: ImmichExifInfo | null) => { - if (!exif) { - return null; +const enumerateAlbumAssets = async ( + origin: string, + albumId: string, + authQuery: string +): Promise => { + const buckets = await fetchJson<{ timeBucket: string }[]>( + `${origin}/api/timeline/buckets?albumId=${albumId}&${authQuery}` + ); + + const assets: IImportSharedAsset[] = []; + for (const bucket of buckets) { + const columns = await fetchJson( + `${origin}/api/timeline/bucket?albumId=${albumId}&timeBucket=${encodeURIComponent(bucket.timeBucket)}&${authQuery}` + ); + const count = columns.id?.length ?? 0; + for (let i = 0; i < count; i++) { + const city = columns.city?.[i] ?? null; + const country = columns.country?.[i] ?? null; + const location = [city, country].filter(Boolean).join(", ") || null; + const fileCreatedAt = columns.fileCreatedAt?.[i] ?? null; + assets.push({ + id: columns.id[i], + type: columns.isImage?.[i] === false ? "VIDEO" : "IMAGE", + fileCreatedAt, + localDateTime: fileCreatedAt, + description: null, + location, + thumbhash: columns.thumbhash?.[i] ?? null, + fileSizeInByte: null, + }); + } } - const parts = [exif.city, exif.state, exif.country] - .filter((value): value is string => !!value && value.trim().length > 0); - return parts.length > 0 ? parts.join(", ") : null; + return assets; }; const fetchJson = async (url: string) => { @@ -266,25 +282,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) if (albumId) { const album = await fetchJson( - `${parsed.origin}/api/albums/${albumId}?${authQuery}&withoutAssets=false` + `${parsed.origin}/api/albums/${albumId}?${authQuery}` ); - const assets = (album.assets || []).map((asset) => ({ - id: asset.id, - originalFileName: asset.originalFileName, - type: asset.type, - fileCreatedAt: asset.fileCreatedAt ?? null, - localDateTime: asset.localDateTime ?? null, - description: asset.exifInfo?.description ?? null, - location: buildLocationString(asset.exifInfo), - thumbhash: asset.thumbhash ?? null, - fileSizeInByte: asset.exifInfo?.fileSizeInByte ?? null, - } satisfies IImportSharedAsset)); + const assets = await enumerateAlbumAssets(parsed.origin, albumId, authQuery); albumResult = { albumName: album.albumName, assetCount: album.assetCount ?? assets.length, - owner: album.owner ?? null, + owner: album.albumUsers?.[0]?.user ?? null, description: album.description ?? null, startDate: album.startDate ?? null, endDate: album.endDate ?? null, diff --git a/src/pages/api/import-shared/helpers.ts b/src/pages/api/import-shared/helpers.ts index 8f4968f..36f6919 100644 --- a/src/pages/api/import-shared/helpers.ts +++ b/src/pages/api/import-shared/helpers.ts @@ -174,7 +174,6 @@ export const uploadAssetBuffer = async ( payload: DownloadedAssetPayload, uploadHeaders: HeadersRecord, jsonHeaders: HeadersRecord, - deviceAssetId: string, tagId?: string ): Promise => { const fileType = asset.type ?? inferAssetTypeFromName(payload.fileName); @@ -187,14 +186,11 @@ export const uploadAssetBuffer = async ( const modifiedAt = asset.localDateTime ?? asset.fileCreatedAt ?? createdAt; const formData = new FormData(); - formData.set("deviceAssetId", deviceAssetId); - formData.set("deviceId", DEVICE_ID); formData.set("fileCreatedAt", createdAt); formData.set("fileModifiedAt", modifiedAt); formData.set("fileType", fileType); - formData.set("duration", asset.duration ?? "0:00:00.000000"); formData.set("assetData", blob, resolvedFileName); - if (asset.isArchived) formData.set("isArchived", String(asset.isArchived)); + if (asset.isArchived) formData.set("visibility", "archive"); if (asset.isFavorite) formData.set("isFavorite", String(asset.isFavorite)); const uploadResponse = await fetch(`${ENV.IMMICH_URL}/api/assets`, { @@ -222,6 +218,52 @@ export const uploadAssetBuffer = async ( return uploadedId; }; +export const fetchSourceAssetChecksum = async ( + origin: string, + assetId: string, + key: string +): Promise => { + try { + const res = await fetch( + `${origin}/api/assets/${assetId}?key=${encodeURIComponent(key)}`, + { headers: { accept: "application/json" } } + ); + if (!res.ok) return null; + const data = await res.json().catch(() => null); + return typeof data?.checksum === "string" ? data.checksum : null; + } catch { + return null; + } +}; + +export const findExistingAssetIds = async ( + targetJsonHeaders: HeadersRecord, + items: { id: string; checksum: string }[] +): Promise> => { + const existing = new Set(); + if (items.length === 0) return existing; + try { + const res = await fetch(`${ENV.IMMICH_URL}/api/assets/bulk-upload-check`, { + method: "POST", + headers: targetJsonHeaders, + body: JSON.stringify({ assets: items }), + }); + if (!res.ok) { + console.warn(`[import] bulk-upload-check failed (status ${res.status})`); + return existing; + } + const data = await res.json().catch(() => ({})); + for (const result of data?.results ?? []) { + if (result?.action === "reject" && result?.reason === "duplicate" && typeof result?.id === "string") { + existing.add(result.id); + } + } + } catch (error) { + console.warn("[import] bulk-upload-check error", error); + } + return existing; +}; + export const tagAssetWithPowerTools = async ( tagId: string, assetId: string, diff --git a/src/pages/api/import-shared/upload-all.ts b/src/pages/api/import-shared/upload-all.ts index 0790d71..4b3f293 100644 --- a/src/pages/api/import-shared/upload-all.ts +++ b/src/pages/api/import-shared/upload-all.ts @@ -6,6 +6,8 @@ import { HeadersRecord, ensurePowerToolsTag, tagAssetWithPowerTools, + fetchSourceAssetChecksum, + findExistingAssetIds, } from "./helpers"; interface ISharedAssetPayload { @@ -43,10 +45,8 @@ interface DownloadedAssetPayload { contentType: string | null; } -const DEVICE_ID = "immich-power-tools"; const ALLOWED_ASSET_TYPES = new Set(["IMAGE", "VIDEO"]); const CONCURRENT_TRANSFERS = 4; -const makeDeviceAssetId = (assetId: string) => `shared-${assetId}`; const respondWithError = (res: NextApiResponse, status: number, message: string) => { return res.status(status).json({ error: message }); @@ -316,16 +316,13 @@ const uploadAssetBuffer = async ( const modifiedAt = asset.localDateTime ?? asset.fileCreatedAt ?? createdAt; const formData = new FormData(); - formData.set("deviceAssetId", makeDeviceAssetId(asset.id)); - formData.set("deviceId", DEVICE_ID); formData.set("fileCreatedAt", createdAt); formData.set("fileModifiedAt", modifiedAt); formData.set("fileType", fileType); - formData.set("duration", asset.duration ?? "0:00:00.000000"); formData.set("assetData", blob, resolvedFileName); if (asset.isArchived) { - formData.set("isArchived", String(asset.isArchived)); + formData.set("visibility", "archive"); } if (asset.isFavorite) { formData.set("isFavorite", String(asset.isFavorite)); @@ -390,46 +387,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) "Content-Type": "application/json", }; - const deviceAssetIds: string[] = []; - const deviceAssetIdLookup = new Map(); + const checkItems: { id: string; checksum: string }[] = []; for (const asset of uploadableAssets) { - const deviceAssetId = makeDeviceAssetId(asset.id); - deviceAssetIds.push(deviceAssetId); - deviceAssetIdLookup.set(deviceAssetId.toLowerCase(), asset.id); - } - - const existingAssetIds = new Set(); - if (deviceAssetIds.length > 0) { - try { - const checkResponse = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { - method: "POST", - headers: jsonHeadersWithContentType, - body: JSON.stringify({ - deviceAssetIds, - deviceId: DEVICE_ID, - }), - }); - - if (checkResponse.ok) { - const existPayload = await checkResponse.json().catch(() => ({})); - const existingIds: string[] = existPayload?.existingIds ?? []; - for (const deviceAssetId of existingIds) { - if (typeof deviceAssetId !== "string") { - continue; - } - const normalizedId = deviceAssetId.toLowerCase(); - const matchedAssetId = deviceAssetIdLookup.get(normalizedId); - if (matchedAssetId) { - existingAssetIds.add(matchedAssetId); - } - } - } else { - console.warn(`Failed to check existing assets before import (status ${checkResponse.status})`); - } - } catch (error) { - console.warn("Unable to check existing assets before import", error); - } + const checksum = await fetchSourceAssetChecksum(origin, asset.id, key); + if (checksum) checkItems.push({ id: asset.id, checksum }); } + const existingAssetIds = await findExistingAssetIds(jsonHeadersWithContentType, checkItems); const assetsToImport = uploadableAssets.filter((asset) => !existingAssetIds.has(asset.id)); const skippedAssetIds = uploadableAssets diff --git a/src/pages/api/import-shared/upload.ts b/src/pages/api/import-shared/upload.ts index 0732731..7fb36f5 100644 --- a/src/pages/api/import-shared/upload.ts +++ b/src/pages/api/import-shared/upload.ts @@ -117,16 +117,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const modifiedAt = asset.localDateTime ?? asset.fileCreatedAt ?? createdAt; const formData = new FormData(); - formData.set("deviceAssetId", `shared-${params.assetId}`); - formData.set("deviceId", "immich-power-tools"); formData.set("fileCreatedAt", createdAt); formData.set("fileModifiedAt", modifiedAt); formData.set("fileType", asset.type ?? "IMAGE"); - formData.set("duration", asset.duration ?? "0:00:00.000000"); formData.set("assetData", assetBlob, fileName); if (asset.isArchived) { - formData.set("isArchived", asset.isArchived.toString()); + formData.set("visibility", "archive"); } if (asset.isFavorite) { formData.set("isFavorite", asset.isFavorite.toString()); diff --git a/src/workers/import/processors/immich-shared-link.ts b/src/workers/import/processors/immich-shared-link.ts index ed6b1aa..4a11a9d 100644 --- a/src/workers/import/processors/immich-shared-link.ts +++ b/src/workers/import/processors/immich-shared-link.ts @@ -1,24 +1,20 @@ import { eq } from "drizzle-orm"; import { appDb } from "@/db"; import { importJobItems } from "@/db/schema"; -import { ENV } from "@/config/environment"; import { ensurePowerToolsTag, HeadersRecord, - inferAssetTypeFromName, parseFileNameFromDisposition, - guessContentType, createImmichAlbum, addAssetToAlbum, uploadAssetBuffer, SharedAssetPayload, DownloadedAssetPayload, - DEVICE_ID, + fetchSourceAssetChecksum, + findExistingAssetIds, } from "@/pages/api/import-shared/helpers"; import type { ImportJob, ImportJobItem, ImportProcessor, ProcessorContext, SetupResult } from "../types"; -const makeDeviceAssetId = (assetId: string) => `shared-${assetId}`; - const downloadSharedAsset = async ( asset: SharedAssetPayload, origin: string, @@ -47,46 +43,21 @@ export class ImmichSharedLinkProcessor implements ImportProcessor { .from(importJobItems) .where(eq(importJobItems.jobId, job.id)); - // Build deviceAssetIds for dedup check - const deviceAssetIds: string[] = []; - const deviceAssetIdLookup = new Map(); + let shareKey = ""; + try { + const urlConfig = JSON.parse(job.urlConfig) as { key?: string }; + if (typeof urlConfig.key === "string") shareKey = urlConfig.key; + } catch { + } + + const dedupHeaders: HeadersRecord = { ...headers, "Content-Type": "application/json" }; + const checkItems: { id: string; checksum: string }[] = []; for (const item of items) { - const deviceAssetId = makeDeviceAssetId(item.assetId); - deviceAssetIds.push(deviceAssetId); - deviceAssetIdLookup.set(deviceAssetId.toLowerCase(), item.assetId); - } - - // Check which assets already exist in Immich - const skipAssetIds: string[] = []; - if (deviceAssetIds.length > 0) { - try { - const jsonHeadersWithContentType: HeadersRecord = { - ...headers, - "Content-Type": "application/json", - }; - const checkResponse = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { - method: "POST", - headers: jsonHeadersWithContentType, - body: JSON.stringify({ deviceAssetIds, deviceId: DEVICE_ID }), - }); - - if (checkResponse.ok) { - const existPayload = await checkResponse.json().catch(() => ({})); - const existingIds: string[] = existPayload?.existingIds ?? []; - for (const deviceAssetId of existingIds) { - if (typeof deviceAssetId !== "string") continue; - const matchedAssetId = deviceAssetIdLookup.get(deviceAssetId.toLowerCase()); - if (matchedAssetId) { - skipAssetIds.push(matchedAssetId); - } - } - } else { - console.warn(`[ImmichSharedLinkProcessor] Failed to check existing assets (status ${checkResponse.status})`); - } - } catch (error) { - console.warn("[ImmichSharedLinkProcessor] Unable to check existing assets", error); - } + const checksum = await fetchSourceAssetChecksum(job.url, item.assetId, shareKey); + if (checksum) checkItems.push({ id: item.assetId, checksum }); } + const existingAssetIds = await findExistingAssetIds(dedupHeaders, checkItems); + const skipAssetIds: string[] = Array.from(existingAssetIds); // Parse importData for album options let importData: Record = {}; @@ -183,7 +154,6 @@ export class ImmichSharedLinkProcessor implements ImportProcessor { downloaded, uploadHeaders as HeadersRecord, headers as HeadersRecord, - makeDeviceAssetId(asset.id), tagId ); diff --git a/src/workers/import/processors/nextcloud-shared-link.ts b/src/workers/import/processors/nextcloud-shared-link.ts index 6cdd62f..9bc589b 100644 --- a/src/workers/import/processors/nextcloud-shared-link.ts +++ b/src/workers/import/processors/nextcloud-shared-link.ts @@ -1,7 +1,6 @@ import { eq } from "drizzle-orm"; import { appDb } from "@/db"; import { importJobItems } from "@/db/schema"; -import { ENV } from "@/config/environment"; import { ensurePowerToolsTag, HeadersRecord, @@ -10,13 +9,10 @@ import { uploadAssetBuffer, SharedAssetPayload, DownloadedAssetPayload, - DEVICE_ID, parseFileNameFromDisposition, } from "@/pages/api/import-shared/helpers"; import type { ImportJob, ImportJobItem, ImportProcessor, ProcessorContext, SetupResult } from "../types"; -const makeDeviceAssetId = (relativePath: string) => `shared-nc-${relativePath}`; - const buildBasicAuth = (username: string, password: string): string => { const encoded = Buffer.from(`${username}:${password}`).toString("base64"); return `Basic ${encoded}`; @@ -66,43 +62,7 @@ export class NextcloudSharedLinkProcessor implements ImportProcessor { .from(importJobItems) .where(eq(importJobItems.jobId, job.id)); - // Build deviceAssetIds for dedup check - const deviceAssetIds: string[] = []; - const deviceAssetIdLookup = new Map(); - for (const item of items) { - const deviceAssetId = makeDeviceAssetId(item.assetId); - deviceAssetIds.push(deviceAssetId); - deviceAssetIdLookup.set(deviceAssetId.toLowerCase(), item.assetId); - } - - // Check which assets already exist in Immich const skipAssetIds: string[] = []; - if (deviceAssetIds.length > 0) { - try { - const jsonHeaders: HeadersRecord = { ...headers, "Content-Type": "application/json" }; - const checkResponse = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { - method: "POST", - headers: jsonHeaders, - body: JSON.stringify({ deviceAssetIds, deviceId: DEVICE_ID }), - }); - - if (checkResponse.ok) { - const existPayload = await checkResponse.json().catch(() => ({})); - const existingIds: string[] = existPayload?.existingIds ?? []; - for (const deviceAssetId of existingIds) { - if (typeof deviceAssetId !== "string") continue; - const matchedAssetId = deviceAssetIdLookup.get(deviceAssetId.toLowerCase()); - if (matchedAssetId) { - skipAssetIds.push(matchedAssetId); - } - } - } else { - console.warn(`[NextcloudProcessor] Failed to check existing assets (status ${checkResponse.status})`); - } - } catch (error) { - console.warn("[NextcloudProcessor] Unable to check existing assets", error); - } - } // Parse importData for album options let importData: Record = {}; @@ -199,7 +159,6 @@ export class NextcloudSharedLinkProcessor implements ImportProcessor { downloaded, uploadHeaders as HeadersRecord, headers as HeadersRecord, - makeDeviceAssetId(relativePath), tagId ); From 1cc5d44e7645d82d5ed79962a9bf8b2ff18fc038 Mon Sep 17 00:00:00 2001 From: jonvdveen <196496658+jonvdveen@users.noreply.github.com> Date: Thu, 2 Jul 2026 18:26:43 -0600 Subject: [PATCH 17/25] fix: update API key permissions for Immich v3 granular permissions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Immich v3 split album-membership rights out of album.update into albumAsset.create / albumAsset.delete, and assigning tags to assets requires tag.asset. The hardcoded WORKFLOW_PERMISSIONS list predates this, so auto-generated workflow keys 403 at runtime on Add to Album (and Add Tag) actions: Immich API error 403: {"message":"Missing required permission: albumAsset.create"} Also, validate-api-key.ts literal-matched required permissions against the key's permission list, so a key created with the "All" checkbox (stored as ["all"]) failed validation for every permission — and the settings page refuses to save a key that fails validation, making it impossible to work around with a full-permission key. - Add albumAsset.create, albumAsset.delete, tag.asset to WORKFLOW_PERMISSIONS (matching the endpoints actionExecutor.ts actually calls: PUT/DELETE /albums/:id/assets, PUT /tags/:id/assets) - Add albumAsset.create to IMPORT_PERMISSIONS for the same reason - Treat a granted "all" permission as satisfying all requirements in validate-api-key.ts Follow-up to #294. Co-Authored-By: Claude Fable 5 --- src/config/permissions.ts | 10 +++++++--- src/pages/api/settings/validate-api-key.ts | 6 +++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/config/permissions.ts b/src/config/permissions.ts index 482f5f1..cdbdd66 100644 --- a/src/config/permissions.ts +++ b/src/config/permissions.ts @@ -8,7 +8,8 @@ export const IMPORT_PERMISSIONS: Permission[] = [ { name: "asset.upload", description: "Upload new assets" }, { name: "album.read", description: "Read album data" }, { name: "album.create", description: "Create new albums" }, - { name: "album.update", description: "Add assets to albums" }, + { name: "album.update", description: "Update album metadata" }, + { name: "albumAsset.create", description: "Add assets to albums" }, { name: "tag.create", description: "Tag imported assets" }, { name: "tag.asset", description: "Assign tags to assets" }, ]; @@ -18,8 +19,11 @@ export const WORKFLOW_PERMISSIONS: Permission[] = [ { name: "asset.update", description: "Favorite, archive, update metadata" }, { name: "album.read", description: "Read album data" }, { name: "album.create", description: "Create new albums" }, - { name: "album.update", description: "Add/remove assets from albums" }, - { name: "tag.create", description: "Create and assign tags" }, + { name: "album.update", description: "Update album metadata" }, + { name: "albumAsset.create", description: "Add assets to albums" }, + { name: "albumAsset.delete", description: "Remove assets from albums" }, + { name: "tag.create", description: "Create tags" }, + { name: "tag.asset", description: "Assign tags to assets" }, ]; export const getPermissionNames = (permissions: Permission[]): string[] => diff --git a/src/pages/api/settings/validate-api-key.ts b/src/pages/api/settings/validate-api-key.ts index 61b9491..98eea94 100644 --- a/src/pages/api/settings/validate-api-key.ts +++ b/src/pages/api/settings/validate-api-key.ts @@ -30,7 +30,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const keyData = await keyRes.json(); const granted: string[] = keyData.permissions ?? []; - const missing = REQUIRED_PERMISSIONS.filter((p) => !granted.includes(p)); + // A key created with the "All" checkbox reports its permissions as ["all"], + // which grants every permission without listing them individually. + const missing = granted.includes("all") + ? [] + : REQUIRED_PERMISSIONS.filter((p) => !granted.includes(p)); return res.status(200).json({ valid: missing.length === 0, From 00aa50ba66b1a15ce71f36b4d5afde840fe2fa84 Mon Sep 17 00:00:00 2001 From: jonvdveen <196496658+jonvdveen@users.noreply.github.com> Date: Thu, 2 Jul 2026 18:56:25 -0600 Subject: [PATCH 18/25] feat: paginate workflow queries so large libraries are fully scanned All workflow trigger queries were capped at .limit(10000) with no ORDER BY and no pagination, so on libraries larger than 10k assets an all_assets ("full library scan") trigger silently evaluated an arbitrary 10k subset. The IF/SWITCH condition queries had the same cap, and bulk actions sent every asset id in a single Immich API request. - resolveAssetTrigger: keyset pagination (ORDER BY id, batches of 5000) for all three trigger types - IF/SWITCH: evaluate conditions against the incoming asset set in chunks instead of one capped inArray query - actionExecutor: call Immich bulk endpoints in batches of 1000 ids Verified on a 26,063-asset library (Immich v3.0.1): all_assets now resolves 26,063 (previously 10,000), a person-filter IF matched 813 assets vs 142 under the cap, and a 25,250-asset remove_from_album branch completed via batched requests. Fixes #296. Co-Authored-By: Claude Fable 5 --- src/lib/workflow/actionExecutor.ts | 27 +++++-- src/lib/workflow/engine.ts | 118 +++++++++++++++++++---------- 2 files changed, 96 insertions(+), 49 deletions(-) diff --git a/src/lib/workflow/actionExecutor.ts b/src/lib/workflow/actionExecutor.ts index 1fd09b1..6597a64 100644 --- a/src/lib/workflow/actionExecutor.ts +++ b/src/lib/workflow/actionExecutor.ts @@ -28,6 +28,16 @@ async function getWorkflowApiKey(ownerId: string): Promise { return row?.value || null; } +// Immich bulk endpoints are called in batches so large asset sets don't +// produce oversized request bodies. +const API_BATCH_SIZE = 1000; + +async function immichFetchBatched(path: string, method: string, ids: string[], extraBody: Record, user: IUser): Promise { + for (let i = 0; i < ids.length; i += API_BATCH_SIZE) { + await immichFetch(path, method, { ...extraBody, ids: ids.slice(i, i + API_BATCH_SIZE) }, user); + } +} + async function immichFetch(path: string, method: string, body: any, user: IUser): Promise { const workflowApiKey = await getWorkflowApiKey(user.id); @@ -136,34 +146,37 @@ export async function executeAction( switch (subType) { case "create_album": { const albumName = await resolveTemplate(config.nameTemplate || "Auto Album", assetIds); - const album = await immichFetch("/albums", "POST", { albumName, assetIds }, user); + const album = await immichFetch("/albums", "POST", { albumName, assetIds: assetIds.slice(0, API_BATCH_SIZE) }, user); + if (assetIds.length > API_BATCH_SIZE) { + await immichFetchBatched(`/albums/${album.id}/assets`, "PUT", assetIds.slice(API_BATCH_SIZE), {}, user); + } return { action: "create_album", assetsProcessed: assetIds.length, albumId: album.id, albumName }; } case "add_to_album": { if (!config.albumId) throw new Error("Album ID is required for add_to_album"); - await immichFetch(`/albums/${config.albumId}/assets`, "PUT", { ids: assetIds }, user); + await immichFetchBatched(`/albums/${config.albumId}/assets`, "PUT", assetIds, {}, user); return { action: "add_to_album", assetsProcessed: assetIds.length, albumId: config.albumId }; } case "remove_from_album": { if (!config.albumId) throw new Error("Album ID is required for remove_from_album"); - await immichFetch(`/albums/${config.albumId}/assets`, "DELETE", { ids: assetIds }, user); + await immichFetchBatched(`/albums/${config.albumId}/assets`, "DELETE", assetIds, {}, user); return { action: "remove_from_album", assetsProcessed: assetIds.length, albumId: config.albumId }; } case "favorite": { - await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: true }, user); + await immichFetchBatched("/assets", "PUT", assetIds, { isFavorite: true }, user); return { action: "favorite", assetsProcessed: assetIds.length }; } case "unfavorite": { - await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: false }, user); + await immichFetchBatched("/assets", "PUT", assetIds, { isFavorite: false }, user); return { action: "unfavorite", assetsProcessed: assetIds.length }; } case "archive": { - await immichFetch("/assets", "PUT", { ids: assetIds, visibility: "archive" }, user); + await immichFetchBatched("/assets", "PUT", assetIds, { visibility: "archive" }, user); return { action: "archive", assetsProcessed: assetIds.length }; } @@ -173,7 +186,7 @@ export async function executeAction( // Create or get tag const tag = await immichFetch("/tags", "POST", { name: config.tagName }, user); // Tag assets - await immichFetch(`/tags/${tag.id}/assets`, "PUT", { ids: assetIds }, user); + await immichFetchBatched(`/tags/${tag.id}/assets`, "PUT", assetIds, {}, user); return { action: "tag", assetsProcessed: assetIds.length }; } catch (e: any) { return { action: "tag", assetsProcessed: 0, error: e.message }; diff --git a/src/lib/workflow/engine.ts b/src/lib/workflow/engine.ts index e49683f..4289c08 100644 --- a/src/lib/workflow/engine.ts +++ b/src/lib/workflow/engine.ts @@ -3,7 +3,7 @@ import { db } from "@/config/db"; import { workflows, workflowNodes, workflowEdges, workflowRuns, workflowProcessedAssets } from "@/db/schema/workflows.schema"; import { assets } from "@/schema/assets.schema"; import { exif } from "@/schema"; -import { eq, and, desc, gte, isNull, inArray, sql, ne } from "drizzle-orm"; +import { eq, and, desc, gt, gte, isNull, inArray, sql, ne, SQL } from "drizzle-orm"; import { buildConditions } from "./conditionBuilder"; import { executeAction } from "./actionExecutor"; import { IUser } from "@/types/user"; @@ -19,6 +19,53 @@ function logError(runId: string, ...args: any[]) { console.error(`${PREFIX} [run:${runId.slice(0, 8)}]`, ...args); } +const QUERY_BATCH_SIZE = 5000; + +// Keyset-paginate an asset query so large libraries aren't silently truncated. +// fetchBatch must ORDER BY assets.id and apply gt(assets.id, afterId) when given. +async function fetchAllBatches( + fetchBatch: (afterId: string | null, limit: number) => Promise, +): Promise { + const all: T[] = []; + let cursor: string | null = null; + for (;;) { + const batch = await fetchBatch(cursor, QUERY_BATCH_SIZE); + all.push(...batch); + if (batch.length < QUERY_BATCH_SIZE) break; + cursor = batch[batch.length - 1].id; + } + return all; +} + +// Evaluate condition clauses against an incoming asset set (chunked to keep +// IN-lists bounded), or against the whole library when scopeIds is null. +async function queryConditionMatches(whereClauses: SQL[], scopeIds: string[] | null): Promise { + if (scopeIds !== null) { + const matched: string[] = []; + for (let i = 0; i < scopeIds.length; i += QUERY_BATCH_SIZE) { + const chunk = scopeIds.slice(i, i + QUERY_BATCH_SIZE); + const rows = await db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where(and(...whereClauses, inArray(assets.id, chunk))); + matched.push(...rows.map((r) => r.id)); + } + return matched; + } + + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where(and(...whereClauses, ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); + return rows.map((r) => r.id); +} + async function resolveAssetTrigger( subType: string, workflowId: string, @@ -80,21 +127,27 @@ async function resolveAssetTrigger( let candidateIds: string[]; if (subType === "new_asset") { - const rows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .where(and(...baseConditions, gte(assets.createdAt, sinceDate))) - .limit(10000); + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .where(and(...baseConditions, gte(assets.createdAt, sinceDate), ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); const totalCandidates = rows.length; // For new_asset: skip any asset we've ever processed candidateIds = rows.map((r) => r.id).filter((id) => !processedMap?.has(id)); log(runId, `Trigger [new_asset]: ${totalCandidates} candidates, ${totalCandidates - candidateIds.length} already processed, ${candidateIds.length} remaining`); } else if (subType === "asset_updated") { - const rows = await db - .selectDistinctOn([assets.id], { id: assets.id, updatedAt: assets.updatedAt }) - .from(assets) - .where(and(...baseConditions, gte(assets.updatedAt, sinceDate))) - .limit(10000); + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id, updatedAt: assets.updatedAt }) + .from(assets) + .where(and(...baseConditions, gte(assets.updatedAt, sinceDate), ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); const totalCandidates = rows.length; // For asset_updated: only skip if we processed it AFTER its current updatedAt candidateIds = rows @@ -107,11 +160,14 @@ async function resolveAssetTrigger( log(runId, `Trigger [asset_updated]: ${totalCandidates} candidates, ${totalCandidates - candidateIds.length} skipped (not updated since processing), ${candidateIds.length} remaining`); } else { // all_assets — no dedup - const rows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .where(and(...baseConditions)) - .limit(10000); + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .where(and(...baseConditions, ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); log(runId, `Trigger [all_assets]: ${rows.length} assets found`); return rows.map((r) => r.id); } @@ -244,19 +300,8 @@ export async function executeWorkflow( const whereClauses = buildConditions(conditions, user.id); - // Scope to incoming assets if available - if (assetIds !== null && assetIds.length > 0) { - whereClauses.push(inArray(assets.id, assetIds)); - } - - const matchedRows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .leftJoin(exif, eq(assets.id, exif.assetId)) - .where(and(...whereClauses)) - .limit(10000); - - const matchedIds = matchedRows.map((r) => r.id); + // Scoped to incoming assets (chunked) when available + const matchedIds = await queryConditionMatches(whereClauses, assetIds); const matchedSet = new Set(matchedIds); let trueIds = matchedIds; @@ -298,19 +343,8 @@ export async function executeWorkflow( const whereClauses = buildConditions(c.conditions || [], user.id); - // Scope to remaining assets if available - if (remaining !== null && remaining.length > 0) { - whereClauses.push(inArray(assets.id, remaining)); - } - - const matchedRows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .leftJoin(exif, eq(assets.id, exif.assetId)) - .where(and(...whereClauses)) - .limit(10000); - - const matchedIds = matchedRows.map((r) => r.id); + // Scoped to remaining assets (chunked) when available + const matchedIds = await queryConditionMatches(whereClauses, remaining); const matchedSet = new Set(matchedIds); let caseIds: string[]; From 37e0606122835f68e5eddf67b53384a46cd93403 Mon Sep 17 00:00:00 2001 From: jonvdveen <196496658+jonvdveen@users.noreply.github.com> Date: Thu, 2 Jul 2026 19:43:02 -0600 Subject: [PATCH 19/25] feat: tag condition for workflow IF/SWITCH nodes Adds a "Tag" condition type that filters assets by Immich tags, with the same match modes as the person condition (has any of / has all of / has none of). Selected tags also match their child tags via Immich's tag_closure hierarchy table, mirroring how tag browsing behaves in Immich itself. - conditionBuilder: tag case with EXISTS subqueries on tag_asset, descendant-inclusive via tag_closure (plus a direct id check so a missing self-closure row can't drop matches) - ConditionEditor: Tag entry + TagPicker multi-select (PersonPicker pattern) with tag color chips - conditionSummary: node label ("Tag any of: ...") - new GET /api/tags route + client handler + drizzle schema for Immich's tag table Co-Authored-By: Claude Fable 5 --- .../workflows/config/ConditionEditor.tsx | 111 +++++++++++++++++- .../workflows/nodes/conditionSummary.ts | 8 ++ src/config/routes.ts | 1 + src/handlers/api/tag.handler.ts | 13 ++ src/lib/workflow/conditionBuilder.ts | 30 +++++ src/pages/api/tags/index.ts | 30 +++++ src/schema/index.ts | 3 +- src/schema/tags.schema.ts | 11 ++ src/types/workflow.d.ts | 2 +- 9 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 src/handlers/api/tag.handler.ts create mode 100644 src/pages/api/tags/index.ts create mode 100644 src/schema/tags.schema.ts diff --git a/src/components/workflows/config/ConditionEditor.tsx b/src/components/workflows/config/ConditionEditor.tsx index 084e63b..7b60ba0 100644 --- a/src/components/workflows/config/ConditionEditor.tsx +++ b/src/components/workflows/config/ConditionEditor.tsx @@ -4,8 +4,9 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"; import { ICondition, ConditionType } from "@/types/workflow"; -import { Plus, X, Check } from "lucide-react"; +import { Plus, X, Check, Tag } from "lucide-react"; import { listPeople } from "@/handlers/api/people.handler"; +import { listTags, ITag } from "@/handlers/api/tag.handler"; import { IPerson } from "@/types/person"; import { PERSON_THUBNAIL_PATH } from "@/config/routes"; import { useEffect, useState } from "react"; @@ -14,6 +15,7 @@ import { cn } from "@/lib/utils"; const conditionTypeLabels: Record = { person: "Person", person_unnamed: "Unnamed People", + tag: "Tag", city: "City", state: "State", country: "Country", @@ -124,6 +126,95 @@ function PersonPicker({ selectedIds, onChange }: PersonPickerProps) { ); } +interface TagPickerProps { + selectedIds: string[]; + onChange: (tagIds: string[], tagValues: string[]) => void; +} + +function TagPicker({ selectedIds, onChange }: TagPickerProps) { + const [open, setOpen] = useState(false); + const [tags, setTags] = useState([]); + const [loading, setLoading] = useState(false); + + useEffect(() => { + setLoading(true); + listTags() + .then((res) => setTags(res.tags)) + .finally(() => setLoading(false)); + }, []); + + const selectedSet = new Set(selectedIds || []); + const selectedTags = tags.filter((t) => selectedSet.has(t.id)); + + const toggleTag = (tag: ITag) => { + let nextIds: string[]; + let nextValues: string[]; + if (selectedSet.has(tag.id)) { + nextIds = selectedIds.filter((id) => id !== tag.id); + nextValues = selectedTags.filter((t) => t.id !== tag.id).map((t) => t.value); + } else { + nextIds = [...selectedIds, tag.id]; + nextValues = [...selectedTags.map((t) => t.value), tag.value]; + } + onChange(nextIds, nextValues); + }; + + return ( +
+ {/* Selected tag chips */} + {selectedTags.length > 0 && ( +
+ {selectedTags.map((t) => ( + + ))} +
+ )} + + {/* Picker */} + + + + + + + + + {loading ? "Loading..." : "No tags found."} + + {tags.map((tag) => ( + toggleTag(tag)} + className="flex items-center gap-2" + > + + {tag.value} + + + ))} + + + + + +
+ ); +} + interface ConditionEditorProps { conditions: ICondition[]; onChange: (conditions: ICondition[]) => void; @@ -219,6 +310,24 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha />
); + case "tag": + return ( +
+ + onChange({ ...condition, tagIds, tagValues })} + /> +

Selected tags also match their child tags.

+
+ ); case "geo_radius": return (
diff --git a/src/components/workflows/nodes/conditionSummary.ts b/src/components/workflows/nodes/conditionSummary.ts index 5cc441c..ce8c3f9 100644 --- a/src/components/workflows/nodes/conditionSummary.ts +++ b/src/components/workflows/nodes/conditionSummary.ts @@ -3,6 +3,7 @@ import { ICondition, ConditionType } from "@/types/workflow"; const conditionTypeLabels: Record = { person: "Person", person_unnamed: "Unnamed People", + tag: "Tag", city: "City", state: "State", country: "Country", @@ -45,6 +46,13 @@ export function formatConditionSummary(c: ICondition): string { } case "person_unnamed": return label; + case "tag": { + const values: string[] = c.tagValues || []; + const match = matchLabels[c.match] || c.match || "any of"; + if (values.length === 0) return `${label}: (none selected)`; + const valueStr = values.length <= 2 ? values.join(", ") : `${values[0]}, ${values[1]} +${values.length - 2}`; + return `${label} ${match}: ${valueStr}`; + } case "city": case "state": case "country": { diff --git a/src/config/routes.ts b/src/config/routes.ts index 5ecd930..2a6478e 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -7,6 +7,7 @@ export const LOGOUT_PATH = BASE_API_ENDPOINT + "/users/logout"; export const LIST_PEOPLE_PATH = BASE_API_ENDPOINT + "/people/list"; +export const LIST_TAGS_PATH = BASE_API_ENDPOINT + "/tags"; export const SEARCH_PEOPLE_PATH = BASE_PROXY_ENDPOINT + "/search/person"; export const SIMILAR_FACES_PATH = (id: string) => BASE_API_ENDPOINT + "/people/" + id + "/similar-faces"; export const PERSON_THUBNAIL_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/thumbnail/" + id; diff --git a/src/handlers/api/tag.handler.ts b/src/handlers/api/tag.handler.ts new file mode 100644 index 0000000..0f62fce --- /dev/null +++ b/src/handlers/api/tag.handler.ts @@ -0,0 +1,13 @@ +import { LIST_TAGS_PATH } from "@/config/routes"; +import API from "@/lib/api"; + +export interface ITag { + id: string; + value: string; + color: string | null; + parentId: string | null; +} + +export const listTags = (): Promise<{ tags: ITag[] }> => { + return API.get(LIST_TAGS_PATH); +}; diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts index e695515..3e01a00 100644 --- a/src/lib/workflow/conditionBuilder.ts +++ b/src/lib/workflow/conditionBuilder.ts @@ -117,6 +117,36 @@ function buildSingleCondition(c: ICondition): SQL | undefined { return sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IN (${sql.raw(idList)}))`; } + case "tag": { + const ids: string[] = c.tagIds || []; + if (ids.length === 0) return undefined; + + // A selected tag also matches assets tagged with any of its child tags + // (tag_closure holds the hierarchy, including self-references). + const descendants = (tagId: string) => + sql`(SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" = ${tagId})`; + + if (c.match === "not_contains") { + // Asset must not carry ANY of these tags (or their children) + const checks = ids.map((tid: string) => + sql`NOT EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" = ${tid} OR ta."tagId" IN ${descendants(tid)}))` + ); + return and(...checks)!; + } + + if (c.match === "contains_all") { + // Asset must carry ALL of these tags (or their children) + const checks = ids.map((tid: string) => + sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" = ${tid} OR ta."tagId" IN ${descendants(tid)}))` + ); + return and(...checks)!; + } + + // contains_any (default) — asset carries at least one of these tags (or their children) + const idList = ids.map((id: string) => `'${id}'`).join(","); + return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${sql.raw(idList)}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${sql.raw(idList)}))))`; + } + case "person_unnamed": if (c.match === "no_unnamed") { return sql`NOT EXISTS (SELECT 1 FROM "asset_face" af JOIN "person" p ON af."personId" = p.id WHERE af."assetId" = ${assets.id} AND (p.name = '' OR p.name IS NULL))`; diff --git a/src/pages/api/tags/index.ts b/src/pages/api/tags/index.ts new file mode 100644 index 0000000..42e37c3 --- /dev/null +++ b/src/pages/api/tags/index.ts @@ -0,0 +1,30 @@ +import { db } from "@/config/db"; +import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; +import { tags } from "@/schema"; +import { asc, eq } from "drizzle-orm"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function handler( + req: NextApiRequest, + res: NextApiResponse +) { + try { + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + const rows = await db + .select({ + id: tags.id, + value: tags.value, + color: tags.color, + parentId: tags.parentId, + }) + .from(tags) + .where(eq(tags.userId, currentUser.id)) + .orderBy(asc(tags.value)); + + return res.status(200).json({ tags: rows }); + } catch (error: any) { + res.status(500).json({ error: error?.message }); + } +} diff --git a/src/schema/index.ts b/src/schema/index.ts index a3d340a..8ea2ff7 100644 --- a/src/schema/index.ts +++ b/src/schema/index.ts @@ -4,4 +4,5 @@ export { person } from './person.schema'; export { assetFaces } from './assetFaces.schema'; export { users } from './users.schema'; export { albumsAssetsAssets } from './albumAssetsAssets.schema'; -export * from './relationships'; \ No newline at end of file +export { tags } from './tags.schema'; +export * from './relationships'; diff --git a/src/schema/tags.schema.ts b/src/schema/tags.schema.ts new file mode 100644 index 0000000..00140bf --- /dev/null +++ b/src/schema/tags.schema.ts @@ -0,0 +1,11 @@ +import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; + +export const tags = pgTable("tag", { + id: uuid("id").notNull().primaryKey(), + userId: uuid("userId").notNull(), + value: varchar("value").notNull(), + color: varchar("color"), + parentId: uuid("parentId"), + createdAt: timestamp("createdAt").notNull(), + updatedAt: timestamp("updatedAt").notNull(), +}); diff --git a/src/types/workflow.d.ts b/src/types/workflow.d.ts index fd1367b..678f9ea 100644 --- a/src/types/workflow.d.ts +++ b/src/types/workflow.d.ts @@ -49,7 +49,7 @@ export interface IWorkflowWithDetails extends IWorkflow { } export type ConditionType = - | "person" | "person_unnamed" + | "person" | "person_unnamed" | "tag" | "city" | "state" | "country" | "geo_radius" | "date_range" | "date_relative" | "day_of_week" | "camera_make" | "camera_model" | "lens" From b473bfdc5dd61963ccaf81f19ac27e482c9ecac2 Mon Sep 17 00:00:00 2001 From: jonvdveen <196496658+jonvdveen@users.noreply.github.com> Date: Thu, 2 Jul 2026 21:23:57 -0600 Subject: [PATCH 20/25] feat: resolution condition for workflow IF/SWITCH nodes (megapixels, short/long edge) Adds a "Resolution" condition type filtering assets by image dimensions, useful for isolating low-resolution images for cleanup or selecting high-resolution ones. Three metrics with optional min/max bounds: - Megapixels (width x height / 1e6, fractional values allowed) - Short edge in pixels (LEAST of width/height) - Long edge in pixels (GREATEST of width/height) Short/long edge are orientation-agnostic, so a 4000x3000 landscape and a 3000x4000 portrait are treated identically. Uses the exifImageWidth/ exifImageHeight columns on asset_exif, which the condition queries already join; assets without recorded dimensions never match. Co-Authored-By: Claude Fable 5 --- .../workflows/config/ConditionEditor.tsx | 20 +++++++++++++++++++ .../workflows/nodes/conditionSummary.ts | 11 ++++++++++ src/lib/workflow/conditionBuilder.ts | 15 ++++++++++++++ src/types/workflow.d.ts | 2 +- 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/components/workflows/config/ConditionEditor.tsx b/src/components/workflows/config/ConditionEditor.tsx index 084e63b..edd15da 100644 --- a/src/components/workflows/config/ConditionEditor.tsx +++ b/src/components/workflows/config/ConditionEditor.tsx @@ -27,6 +27,7 @@ const conditionTypeLabels: Record = { asset_type: "Asset Type", iso_range: "ISO Range", focal_length: "Focal Length", + resolution: "Resolution", rating: "Rating", is_favorited: "Favorited", not_in_album: "Not in Any Album", @@ -192,6 +193,25 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha onChange({ ...condition, max: parseInt(e.target.value) || undefined })} />
); + case "resolution": { + const unit = (condition.metric || "megapixels") === "megapixels" ? "MP" : "px"; + return ( +
+ +
+ onChange({ ...condition, min: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> + onChange({ ...condition, max: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> +
+
+ ); + } case "is_favorited": return ( ); + case "file_size": + return ( +
+ onChange({ ...condition, min: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> + onChange({ ...condition, max: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> +
+ ); + case "filename": + return ( +
+
+ + +
+ onChange({ ...condition, text: e.target.value })} /> +
+ ); + case "file_extension": + return ( +
+ + onChange({ ...condition, extensions: e.target.value })} /> +
+ ); + case "face_count": + return ( +
+ onChange({ ...condition, min: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + onChange({ ...condition, max: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + faces +
+ ); + case "time_of_day": + return ( +
+
+ From + onChange({ ...condition, fromHour: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + to + onChange({ ...condition, toHour: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + h +
+

Hours 0–23; From > To wraps past midnight (e.g. 22 to 5).

+
+ ); case "person": return (
diff --git a/src/components/workflows/nodes/conditionSummary.ts b/src/components/workflows/nodes/conditionSummary.ts index 5cc441c..819bc40 100644 --- a/src/components/workflows/nodes/conditionSummary.ts +++ b/src/components/workflows/nodes/conditionSummary.ts @@ -18,6 +18,11 @@ const conditionTypeLabels: Record = { focal_length: "Focal Length", rating: "Rating", is_favorited: "Favorited", + file_size: "File Size", + filename: "File Name / Path", + file_extension: "Extension", + face_count: "Faces", + time_of_day: "Time of Day", not_in_album: "Not in Any Album", not_in_specific_album: "Not in Specific Album", }; @@ -97,6 +102,32 @@ export function formatConditionSummary(c: ICondition): string { } case "is_favorited": return c.value === false ? "Not Favorited" : "Favorited"; + case "file_size": { + if (c.min != null && c.max != null) return `${label}: ${c.min}–${c.max}MB`; + if (c.min != null) return `${label}: ≥${c.min}MB`; + if (c.max != null) return `${label}: ≤${c.max}MB`; + return label; + } + case "filename": { + if (!c.text) return label; + const field = c.field === "path" ? "Path" : "Name"; + const matchNames: Record = { contains: "contains", not_contains: "doesn't contain", starts_with: "starts with", ends_with: "ends with" }; + return `${field} ${matchNames[c.match] || "contains"}: ${c.text}`; + } + case "file_extension": { + if (!c.extensions) return label; + return `${label} ${c.match === "not_in" ? "none of" : "any of"}: ${c.extensions}`; + } + case "face_count": { + if (c.min != null && c.max != null) return c.min === c.max ? `${label}: ${c.min}` : `${label}: ${c.min}–${c.max}`; + if (c.min != null) return `${label}: ≥${c.min}`; + if (c.max != null) return `${label}: ≤${c.max}`; + return label; + } + case "time_of_day": { + if (c.fromHour == null || c.toHour == null) return label; + return `${label}: ${c.fromHour}:00–${c.toHour}:59`; + } case "not_in_album": return label; case "not_in_specific_album": diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts index e695515..e00ad4d 100644 --- a/src/lib/workflow/conditionBuilder.ts +++ b/src/lib/workflow/conditionBuilder.ts @@ -92,6 +92,63 @@ function buildSingleCondition(c: ICondition): SQL | undefined { return parts.length > 0 ? and(...parts)! : undefined; } + case "file_size": { + // min/max in megabytes (fractional allowed) + const parts: SQL[] = []; + if (c.min !== undefined && c.min !== null) parts.push(sql`${exif.fileSizeInByte} >= ${Math.round(c.min * 1048576)}`); + if (c.max !== undefined && c.max !== null) parts.push(sql`${exif.fileSizeInByte} <= ${Math.round(c.max * 1048576)}`); + return parts.length > 0 ? and(...parts)! : undefined; + } + + case "filename": { + if (!c.text) return undefined; + const column = c.field === "path" ? assets.originalPath : assets.originalFileName; + // Escape LIKE wildcards so user text is matched literally + const escaped = c.text.replace(/([\\%_])/g, "\\$1"); + const match = c.match || "contains"; + const pattern = + match === "starts_with" ? `${escaped}%` + : match === "ends_with" ? `%${escaped}` + : `%${escaped}%`; + return match === "not_contains" + ? sql`${column} NOT ILIKE ${pattern}` + : sql`${column} ILIKE ${pattern}`; + } + + case "file_extension": { + const raw: string = c.extensions || ""; + const exts = raw + .split(",") + .map((e: string) => e.trim().replace(/^\./, "").toLowerCase()) + .filter(Boolean); + if (exts.length === 0) return undefined; + // Extension = text after the last dot; files without one never match either mode + const extExpr = sql`lower(substring(${assets.originalFileName} from '\\.([^.]+)$'))`; + const list = exts.map((e: string) => `'${e.replace(/'/g, "''")}'`).join(","); + return c.match === "not_in" + ? sql`${extExpr} NOT IN (${sql.raw(list)})` + : sql`${extExpr} IN (${sql.raw(list)})`; + } + + case "face_count": { + const faceCount = sql`(SELECT count(*) FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."deletedAt" IS NULL AND af."isVisible" = true)`; + const parts: SQL[] = []; + if (c.min !== undefined && c.min !== null) parts.push(sql`${faceCount} >= ${c.min}`); + if (c.max !== undefined && c.max !== null) parts.push(sql`${faceCount} <= ${c.max}`); + return parts.length > 0 ? and(...parts)! : undefined; + } + + case "time_of_day": { + if (c.fromHour == null || c.toHour == null) return undefined; + // localDateTime holds the capture wall-clock time, so no timezone math needed + const hour = sql`EXTRACT(HOUR FROM ${assets.localDateTime})`; + if (c.fromHour <= c.toHour) { + return sql`${hour} BETWEEN ${c.fromHour} AND ${c.toHour}`; + } + // From > To wraps past midnight, e.g. 22–5 = evening through early morning + return sql`(${hour} >= ${c.fromHour} OR ${hour} <= ${c.toHour})`; + } + case "person": { const ids: string[] = c.personIds || (c.personId ? [c.personId] : []); if (ids.length === 0) return undefined; diff --git a/src/types/workflow.d.ts b/src/types/workflow.d.ts index fd1367b..ccd7ca3 100644 --- a/src/types/workflow.d.ts +++ b/src/types/workflow.d.ts @@ -55,6 +55,8 @@ export type ConditionType = | "camera_make" | "camera_model" | "lens" | "asset_type" | "iso_range" | "focal_length" | "rating" | "is_favorited" + | "file_size" | "filename" | "file_extension" + | "face_count" | "time_of_day" | "not_in_album" | "not_in_specific_album"; export interface ICondition { From 95ede2efd72351eb5cf228680dcabf230a83810d Mon Sep 17 00:00:00 2001 From: jonvdveen <196496658+jonvdveen@users.noreply.github.com> Date: Thu, 2 Jul 2026 22:54:43 -0600 Subject: [PATCH 22/25] feat: Remove Tag workflow action to complement Add Tag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removes a tag (by name, matching the tag's full path value) from the matched assets via DELETE /tags/:id/assets. The tag is looked up without creating it — removing a tag that doesn't exist is a no-op rather than an error, so add/remove pairs are safe in the same workflow. Registered in the node palette, action node, run-detail view, and action config (same tag-name field as Add Tag). Co-Authored-By: Claude Fable 5 --- src/components/workflows/NodePalette.tsx | 1 + .../workflows/config/ActionConfig.tsx | 5 ++++- src/components/workflows/nodes/ActionNode.tsx | 4 +++- src/lib/workflow/actionExecutor.ts | 19 +++++++++++++++++++ src/pages/workflows/[id]/runs/[runId].tsx | 4 ++-- 5 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/components/workflows/NodePalette.tsx b/src/components/workflows/NodePalette.tsx index 4ffc7c4..632db56 100644 --- a/src/components/workflows/NodePalette.tsx +++ b/src/components/workflows/NodePalette.tsx @@ -27,6 +27,7 @@ const actionItems: PaletteItem[] = [ { type: "action", subType: "unfavorite", label: "Unfavorite", icon: HeartOff, color: "text-purple-500" }, { type: "action", subType: "archive", label: "Archive", icon: Archive, color: "text-purple-500" }, { type: "action", subType: "tag", label: "Add Tag", icon: Tag, color: "text-purple-500" }, + { type: "action", subType: "remove_tag", label: "Remove Tag", icon: Tag, color: "text-purple-500" }, ]; function PaletteGroup({ title, items }: { title: string; items: PaletteItem[] }) { diff --git a/src/components/workflows/config/ActionConfig.tsx b/src/components/workflows/config/ActionConfig.tsx index 09a62cc..cc15cb0 100644 --- a/src/components/workflows/config/ActionConfig.tsx +++ b/src/components/workflows/config/ActionConfig.tsx @@ -115,7 +115,7 @@ export default function ActionConfig({ subType, config, onChange }: ActionConfig ); } - if (subType === "tag") { + if (subType === "tag" || subType === "remove_tag") { return (
@@ -125,6 +125,9 @@ export default function ActionConfig({ subType, config, onChange }: ActionConfig value={config.tagName || ""} onChange={(e) => onChange({ ...config, tagName: e.target.value })} /> + {subType === "remove_tag" && ( +

Removes this tag from matched assets. If the tag doesn't exist, nothing happens.

+ )}
); } diff --git a/src/components/workflows/nodes/ActionNode.tsx b/src/components/workflows/nodes/ActionNode.tsx index fea2f50..08f937e 100644 --- a/src/components/workflows/nodes/ActionNode.tsx +++ b/src/components/workflows/nodes/ActionNode.tsx @@ -9,6 +9,7 @@ const actionIcons: Record = { unfavorite: HeartOff, archive: Archive, tag: Tag, + remove_tag: Tag, }; const actionLabels: Record = { @@ -19,6 +20,7 @@ const actionLabels: Record = { unfavorite: "Unfavorite", archive: "Archive", tag: "Add Tag", + remove_tag: "Remove Tag", }; export default function ActionNode({ data, selected }: NodeProps) { @@ -42,7 +44,7 @@ export default function ActionNode({ data, selected }: NodeProps) { {(subType === "add_to_album" || subType === "remove_from_album") && config.albumName && (

{config.albumName}

)} - {subType === "tag" && config.tagName && ( + {(subType === "tag" || subType === "remove_tag") && config.tagName && (

{config.tagName}

)}
diff --git a/src/lib/workflow/actionExecutor.ts b/src/lib/workflow/actionExecutor.ts index 1fd09b1..244ecb6 100644 --- a/src/lib/workflow/actionExecutor.ts +++ b/src/lib/workflow/actionExecutor.ts @@ -180,6 +180,25 @@ export async function executeAction( } } + case "remove_tag": { + if (!config.tagName) throw new Error("Tag name is required"); + try { + // Look up the tag by value (full path for nested tags) without creating it — + // removing a tag that doesn't exist is a no-op, not an error. + const result = await db.execute( + sql`SELECT id FROM "tag" WHERE "userId" = ${user.id} AND "value" = ${config.tagName} LIMIT 1` + ); + const tagId = result.rows?.[0]?.id as string | undefined; + if (!tagId) { + return { action: "remove_tag", assetsProcessed: 0 }; + } + await immichFetch(`/tags/${tagId}/assets`, "DELETE", { ids: assetIds }, user); + return { action: "remove_tag", assetsProcessed: assetIds.length }; + } catch (e: any) { + return { action: "remove_tag", assetsProcessed: 0, error: e.message }; + } + } + default: return { action: subType, assetsProcessed: 0, error: `Unknown action: ${subType}` }; } diff --git a/src/pages/workflows/[id]/runs/[runId].tsx b/src/pages/workflows/[id]/runs/[runId].tsx index 14f6e6c..eb261c8 100644 --- a/src/pages/workflows/[id]/runs/[runId].tsx +++ b/src/pages/workflows/[id]/runs/[runId].tsx @@ -135,11 +135,11 @@ function AnnotatedActionNode({ data }: NodeProps) { const step = data.runStep as any; const icons: Record = { create_album: FolderPlus, add_to_album: FolderInput, remove_from_album: FolderMinus, - favorite: Heart, unfavorite: HeartOff, archive: Archive, tag: Tag, + favorite: Heart, unfavorite: HeartOff, archive: Archive, tag: Tag, remove_tag: Tag, }; const labels: Record = { create_album: "Create Album", add_to_album: "Add to Album", remove_from_album: "Remove from Album", - favorite: "Favorite", unfavorite: "Unfavorite", archive: "Archive", tag: "Add Tag", + favorite: "Favorite", unfavorite: "Unfavorite", archive: "Archive", tag: "Add Tag", remove_tag: "Remove Tag", }; const Icon = icons[subType] || FolderPlus; const isDryRun = step?.detail?.includes("DRY RUN"); From b66c8218bcfd218c0a6ade1d9238fed50ae6d750 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 13:59:52 +0000 Subject: [PATCH 23/25] fix: parameterize tag contains_any IN-list to close SQL injection vector The id list was built via raw string interpolation into sql.raw(). Switch to sql.join with proper parameter binding, matching the pattern used by the other match branches in this function. --- src/lib/workflow/conditionBuilder.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts index 3e01a00..587ab93 100644 --- a/src/lib/workflow/conditionBuilder.ts +++ b/src/lib/workflow/conditionBuilder.ts @@ -143,8 +143,8 @@ function buildSingleCondition(c: ICondition): SQL | undefined { } // contains_any (default) — asset carries at least one of these tags (or their children) - const idList = ids.map((id: string) => `'${id}'`).join(","); - return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${sql.raw(idList)}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${sql.raw(idList)}))))`; + const idParams = sql.join(ids.map((id: string) => sql`${id}`), sql`, `); + return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${idParams}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${idParams}))))`; } case "person_unnamed": From 9659c8b36bfd8cade7cb371a3bf3b75a1fb31e49 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 14:00:21 +0000 Subject: [PATCH 24/25] fix: remove stray argument breaking uploadAssetBuffer call makeDeviceAssetId(item.assetId) was passed as an extra 5th argument before tagId, which doesn't match uploadAssetBuffer's signature (asset, payload, uploadHeaders, jsonHeaders, tagId?) and broke the TS build. Match the call pattern used by the sibling nextcloud/immich processors. --- src/workers/import/processors/ente-shared-link.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/workers/import/processors/ente-shared-link.ts b/src/workers/import/processors/ente-shared-link.ts index 5f1878d..f630e8c 100644 --- a/src/workers/import/processors/ente-shared-link.ts +++ b/src/workers/import/processors/ente-shared-link.ts @@ -225,7 +225,6 @@ export class EnteSharedLinkProcessor implements ImportProcessor { downloaded, uploadHeaders as HeadersRecord, headers as HeadersRecord, - makeDeviceAssetId(item.assetId), tagId ); From 40e9e0dde2854784fe4398d18f9f47ecddf48df2 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 15:48:29 +0000 Subject: [PATCH 25/25] fix: resolve tag via Immich API instead of local DB table in remove_tag The local tag table can lag behind Immich's own tag state (e.g. tags created directly in Immich, or before this app's sync ran), causing remove_tag to silently no-op on a tag that actually exists. Mirror the sibling "tag" action's approach and resolve against the Immich API, matching on the tag's full-path "value" field. Drops the now-unused db/sql local lookup. --- src/lib/workflow/actionExecutor.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/lib/workflow/actionExecutor.ts b/src/lib/workflow/actionExecutor.ts index 244ecb6..f325cba 100644 --- a/src/lib/workflow/actionExecutor.ts +++ b/src/lib/workflow/actionExecutor.ts @@ -6,7 +6,7 @@ import { exif } from "@/schema"; import { assets } from "@/schema/assets.schema"; import { person } from "@/schema/person.schema"; import { assetFaces } from "@/schema/assetFaces.schema"; -import { eq, and, inArray, sql, desc } from "drizzle-orm"; +import { eq, and, inArray, desc } from "drizzle-orm"; import { IUser } from "@/types/user"; import { getUserHeaders } from "@/helpers/user.helper"; @@ -183,16 +183,15 @@ export async function executeAction( case "remove_tag": { if (!config.tagName) throw new Error("Tag name is required"); try { - // Look up the tag by value (full path for nested tags) without creating it — - // removing a tag that doesn't exist is a no-op, not an error. - const result = await db.execute( - sql`SELECT id FROM "tag" WHERE "userId" = ${user.id} AND "value" = ${config.tagName} LIMIT 1` - ); - const tagId = result.rows?.[0]?.id as string | undefined; - if (!tagId) { + // Look up the tag via Immich's API (same source of truth the "tag" + // action creates/gets from) without creating it — removing a tag + // that doesn't exist is a no-op, not an error. + const tags = await immichFetch("/tags", "GET", undefined, user); + const tag = Array.isArray(tags) ? tags.find((t: any) => t.value === config.tagName) : undefined; + if (!tag) { return { action: "remove_tag", assetsProcessed: 0 }; } - await immichFetch(`/tags/${tagId}/assets`, "DELETE", { ids: assetIds }, user); + await immichFetch(`/tags/${tag.id}/assets`, "DELETE", { ids: assetIds }, user); return { action: "remove_tag", assetsProcessed: assetIds.length }; } catch (e: any) { return { action: "remove_tag", assetsProcessed: 0, error: e.message };