Merge remote-tracking branch 'origin/prerelease' into feat/potential-trips

This commit is contained in:
Varun Raj committed 2026-07-10 16:13:24 +00:00
commit 5068419e3b
73 files changed
+2247 -690

No files matched your search

+25 -15
View File
@@ -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<IAlbum>[] = [
const album = row.original
return (
<div className="w-16 h-16 rounded-md overflow-hidden">
<LazyImage
src={ASSET_THUMBNAIL_PATH(album.albumThumbnailAssetId)}
alt={album.albumName}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
{album.albumThumbnailAssetId ? (
<LazyImage
src={ASSET_THUMBNAIL_PATH(album.albumThumbnailAssetId)}
alt={album.albumName}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800 text-gray-400">
<ImageOff size={20} />
</div>
)}
</div>
)
},
@@ -164,16 +170,20 @@ export const albumColumns: ColumnDef<IAlbum>[] = [
},
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 (
<div className="space-y-1">
<div className="text-sm">
{album.firstPhotoDate ? formatDate(album.firstPhotoDate.toString(), 'MMM d, yyyy') : ''} - {album.lastPhotoDate ? formatDate(album.lastPhotoDate.toString(), 'MMM d, yyyy') : ''}
</div>
<div className="text-xs text-muted-foreground">
{numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`}
</div>
{numberOfDays !== null && (
<div className="text-xs text-muted-foreground">
{numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`}
</div>
)}
</div>
)
},
+30 -14
View File
@@ -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 (
<div className="border rounded-lg overflow-hidden shadow-lg relative group">
<label className="block relative ">
<LazyImage
src={ASSET_THUMBNAIL_PATH(album.albumThumbnailAssetId)}
alt={album.albumName}
title={album.albumName}
style={{
width: '100%',
height: '200px',
objectFit: 'cover',
}}
/>
{album.albumThumbnailAssetId ? (
<LazyImage
src={ASSET_THUMBNAIL_PATH(album.albumThumbnailAssetId)}
alt={album.albumName}
title={album.albumName}
style={{
width: '100%',
height: '200px',
objectFit: 'cover',
}}
/>
) : (
<div
className="flex flex-col items-center justify-center gap-2 bg-gray-100 dark:bg-gray-800 text-gray-400"
style={{ width: '100%', height: '200px' }}
title={album.albumName}
>
<ImageOff size={32} />
<span className="text-xs">No photos</span>
</div>
)}
<div className="absolute bottom-0 w-full bg-gray-800/70 text-white text-center text-xs font-bold py-1 group-hover:hidden">
{album.firstPhotoDate ? formatDate(album.firstPhotoDate?.toString(), 'MMM d, yyyy') : ''} - {album.lastPhotoDate ? formatDate(album.lastPhotoDate?.toString(), 'MMM d, yyyy') : ''}
</div>
@@ -54,9 +68,11 @@ export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThum
<Camera size={12} />
{humanizeNumber(album.assetCount)}
</div>
<p className="bg-gray-800 flex items-center gap-1 text-white text-xs py-1 px-2 rounded">
{numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString() } days`} <Calendar size={12} />
</p>
{numberOfDays !== null && (
<p className="bg-gray-800 flex items-center gap-1 text-white text-xs py-1 px-2 rounded">
{numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString() } days`} <Calendar size={12} />
</p>
)}
</div>
<div className={`p-4 ${selected ? 'bg-blue-500' : ''}`}>
<Link href={`/albums/${album.id}`}>
+45 -14
View File
@@ -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<HeatMapEntry[][]>([]);
const [loading, setLoading] = useState(false);
const [weeksPerMonth, setWeeksPerMonth] = useState<number[]>([]);
const [availableYears, setAvailableYears] = useState<number[]>([]);
const [selection, setSelection] = useState<typeof ROLLING | number>(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 (
<div className="w-full">
<div className="flex items-center justify-end mb-2">
<Select
value={selection === ROLLING ? ROLLING : String(selection)}
onValueChange={(v) => setSelection(v === ROLLING ? ROLLING : Number(v))}
>
<SelectTrigger className="w-[180px] h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={ROLLING}>Last 12 months</SelectItem>
{availableYears.map((y) => (
<SelectItem key={y} value={String(y)}>
{y}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="overflow-x-auto">
<table className="table-auto border-separate border-spacing-[3px]">
<thead>
+92 -36
View File
@@ -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<Record<string, string>>({})
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 (
<MentionsInput
value={value}
singleLine={true}
placeholder='Search for photos, use @ to search for people'
style={inputStyle}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onSearch(value);
}
}}
onChange={(e) => onChange(e.target.value)}>
<Mention
trigger="@"
style={mentionStyle}
data={handleSearchPeople}
renderSuggestion={(
highlightedDisplay,
focused
) => (
<div className={`user ${focused ? 'focused' : ''} `}>
{highlightedDisplay.display}
</div>
)}
<div className={cn(
"flex items-center gap-2 rounded-xl border bg-background px-3 transition-shadow w-full",
focused ? "ring-2 ring-ring shadow-sm" : "border-input"
)}>
<Search className="h-5 w-5 shrink-0 text-muted-foreground" />
<Mentions
value={value}
prefix="@"
placeholder="Search for photos, use @ to mention people"
onSearch={handleMentionSearch}
onChange={onChange}
onKeyDown={handleKeyDown}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
options={options}
rows={1}
/>
</MentionsInput>
{value && !loading && (
<button
onClick={handleClear}
className="shrink-0 rounded-full p-1 hover:bg-muted transition-colors"
aria-label="Clear search"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
)}
<button
onClick={handleSubmit}
disabled={!value.trim() || loading}
className="shrink-0 rounded-lg p-1.5 bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:pointer-events-none"
aria-label="Search"
>
{loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<ArrowRight className="h-4 w-4" />
)}
</button>
</div>
)
}
-45
View File
@@ -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;
-6
View File
@@ -1,6 +0,0 @@
const mentionStyle: React.CSSProperties = {
backgroundColor: 'hsla(var(--chart-2) / 0.3)',
position: 'relative',
}
export default mentionStyle;
+19 -13
View File
@@ -23,19 +23,24 @@ export function PeopleFilters() {
const { updateContext, page, maximumAssetCount, type = "all", query = "", visibility = "all" } = filters;
const handleChange = (data: Partial<IPersonListFilters>) => {
updateContext(data);
// Any filter change other than an explicit page navigation must reset
// pagination: without this, typing a name while on page 2 keeps page=2
// and the now-smaller result set returns nothing until the user clicks
// back to page 1 manually.
const nextData = "page" in data ? data : { ...data, page: 1 };
updateContext(nextData);
router.push({
pathname: router.pathname,
query: {
...router.query,
...data,
page: data.page || undefined,
type: data.type || undefined,
visibility: data.visibility || undefined,
query: data.query || undefined,
maximumAssetCount: data.maximumAssetCount || undefined,
sort: data.sort || undefined,
sortOrder: data.sortOrder || undefined,
...nextData,
page: nextData.page || undefined,
type: nextData.type || undefined,
visibility: nextData.visibility || undefined,
query: nextData.query || undefined,
maximumAssetCount: nextData.maximumAssetCount || undefined,
sort: nextData.sort || undefined,
sortOrder: nextData.sortOrder || undefined,
},
});
}
@@ -109,10 +114,11 @@ export function PeopleFilters() {
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant={"secondary"}
onClick={() => handleChange({ page: nextPage })}
>
{/* No onClick here: DropdownMenuTrigger handles the popover open/close
itself. The previous handler was a copy-paste of the page-next
button and advanced the page every time the user opened the
sort menu. */}
<Button variant={"secondary"}>
<SortDesc size={16} />
</Button>
</DropdownMenuTrigger>
+11 -8
View File
@@ -120,14 +120,6 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
}), [assets, selectedIds, updateContext]);
const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => {
if (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<AssetGridRef, AssetGridProps>(({ 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,
@@ -214,6 +214,9 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
photo={context.photo}
width={context.width}
height={context.height}
selectable={selectable}
onSelect={(event) => handleSelect(context.index, context.photo, event)}
selectionMode={selectable && selectedIds.length > 0}
/>
);
};
@@ -112,14 +112,6 @@ const ResponsiveVirtualizedAssetGrid = forwardRef<ResponsiveVirtualizedAssetGrid
}));
}, [assets]);
const handleClick = useCallback((index: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
if (selectedIds.length > 0) {
handleSelect(index, asset, event);
} else {
setIndex(index);
}
}, [selectedIds]);
const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
event.stopPropagation();
const isPresent = selectedIds.includes(asset.id);
@@ -146,6 +138,14 @@ const ResponsiveVirtualizedAssetGrid = forwardRef<ResponsiveVirtualizedAssetGrid
}
}, [selectedIds, assets, lastSelectedIndex, updateContext, onSelectionChange]);
const handleClick = useCallback((index: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
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: [] });
@@ -200,11 +200,15 @@ const ResponsiveVirtualizedAssetGrid = forwardRef<ResponsiveVirtualizedAssetGrid
)}
{selectable && (
<div
className={`absolute top-2 left-2 w-4 h-4 rounded-full border-2 ${
className={`absolute top-2 left-2 w-4 h-4 rounded-full border-2 cursor-pointer z-10 ${
isSelected
? 'bg-blue-500 border-blue-500'
: 'bg-white/80 border-gray-300'
}`}
onClick={(e) => {
e.stopPropagation();
handleSelect(assetIndex, asset, e);
}}
/>
)}
</div>
+13 -9
View File
@@ -76,14 +76,6 @@ const VirtualizedAssetGrid = forwardRef<VirtualizedAssetGridRef, VirtualizedAsse
}));
}, [assets]);
const handleClick = useCallback((index: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
if (selectedIds.length > 0) {
handleSelect(index, asset, event);
} else {
setIndex(index);
}
}, [selectedIds]);
const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
event.stopPropagation();
const isPresent = selectedIds.includes(asset.id);
@@ -110,6 +102,14 @@ const VirtualizedAssetGrid = forwardRef<VirtualizedAssetGridRef, VirtualizedAsse
}
}, [selectedIds, assets, lastSelectedIndex, updateContext, onSelectionChange]);
const handleClick = useCallback((index: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
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: [] });
@@ -166,11 +166,15 @@ const VirtualizedAssetGrid = forwardRef<VirtualizedAssetGridRef, VirtualizedAsse
)}
{selectable && (
<div
className={`absolute top-2 left-2 w-4 h-4 rounded-full border-2 ${
className={`absolute top-2 left-2 w-4 h-4 rounded-full border-2 cursor-pointer z-10 ${
isSelected
? 'bg-blue-500 border-blue-500'
: 'bg-white/80 border-gray-300'
}`}
onClick={(e) => {
e.stopPropagation();
handleSelect(assetIndex, asset, e);
}}
/>
)}
</div>
+30 -3
View File
@@ -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,15 +11,19 @@ interface LazyGridImageProps {
photo: AssetPhoto;
width: number;
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 }: LazyGridImageProps) {
export default function LazyGridImage({ imageProps, photo, width, height, selectable, onSelect, selectionMode = false }: LazyGridImageProps) {
const [isVisible, setIsVisible] = React.useState(false)
const imageRef = React.useRef<HTMLDivElement>(null)
const setupObserver = () => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true)
@@ -44,13 +49,35 @@ export default function LazyGridImage({ imageProps, photo, width, height }: Lazy
<div style={{ height, width }} ref={imageRef} />
)
const dim = selectionMode && !photo.isSelected ? 'opacity-60' : '';
return (
<div style={{ position: 'relative', width, height }}>
<div
style={{
position: 'relative',
width,
height,
}}
className={`group ${photo.isSelected ? 'ring-4 ring-blue-500 ring-inset' : ''} ${dim}`.trim()}
>
<img {...imageProps} alt={imageProps.alt || ""} title="" style={{ ...imageProps.style, width, height, objectFit: 'cover' }} />
{photo.isVideo && <div className="absolute bottom-2 right-2 bg-black/50 p-1 rounded-full flex items-center gap-1">
<PlayIcon className="w-3 h-3 text-white" />
{!!photo.duration && <span className="text-xs text-white">{humanizeDuration(photo.duration)}</span>}
</div>}
{selectable && (
<div
className={`absolute top-2 left-2 z-10 cursor-pointer transition-opacity ${photo.isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}
onClick={(e) => {
e.stopPropagation();
onSelect?.(e);
}}
>
<div className={`rounded-full p-0.5 ${photo.isSelected ? 'bg-blue-500 text-white' : 'bg-black/20 text-white/50'}`}>
<CircleCheck className="w-5 h-5" />
</div>
</div>
)}
</div>
)
}
+1
View File
@@ -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[] }) {
@@ -115,7 +115,7 @@ export default function ActionConfig({ subType, config, onChange }: ActionConfig
);
}
if (subType === "tag") {
if (subType === "tag" || subType === "remove_tag") {
return (
<div className="space-y-2">
<Label className="text-xs">Tag Name</Label>
@@ -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" && (
<p className="text-[10px] text-muted-foreground">Removes this tag from matched assets. If the tag doesn&apos;t exist, nothing happens.</p>
)}
</div>
);
}
@@ -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<ConditionType, string> = {
person: "Person",
person_unnamed: "Unnamed People",
tag: "Tag",
city: "City",
state: "State",
country: "Country",
@@ -27,8 +29,14 @@ const conditionTypeLabels: Record<ConditionType, string> = {
asset_type: "Asset Type",
iso_range: "ISO Range",
focal_length: "Focal Length",
resolution: "Resolution",
rating: "Rating",
is_favorited: "Favorited",
file_size: "File Size",
filename: "File Name / Path",
file_extension: "File Extension",
face_count: "Face Count",
time_of_day: "Time of Day",
not_in_album: "Not in Any Album",
not_in_specific_album: "Not in Specific Album",
};
@@ -124,6 +132,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<ITag[]>([]);
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 (
<div className="space-y-2">
{/* Selected tag chips */}
{selectedTags.length > 0 && (
<div className="flex flex-wrap gap-1">
{selectedTags.map((t) => (
<button
key={t.id}
type="button"
onClick={() => toggleTag(t)}
className="flex items-center gap-1 px-1.5 py-0.5 rounded-full bg-muted hover:bg-destructive/10 transition-colors group"
>
<Tag className="h-2.5 w-2.5" style={t.color ? { color: t.color } : undefined} />
<span className="text-[10px] font-medium">{t.value}</span>
<X className="h-2.5 w-2.5 text-muted-foreground group-hover:text-destructive" />
</button>
))}
</div>
)}
{/* Picker */}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button type="button" className="flex items-center gap-2 h-7 px-2 w-full border rounded text-xs bg-background hover:bg-muted transition-colors">
<span className="text-muted-foreground">
{selectedIds.length === 0 ? "Select tags..." : "Add more..."}
</span>
</button>
</PopoverTrigger>
<PopoverContent className="w-56 p-0 z-[10000]" align="start">
<Command>
<CommandInput placeholder="Search tags..." className="text-xs" />
<CommandList>
<CommandEmpty>{loading ? "Loading..." : "No tags found."}</CommandEmpty>
<CommandGroup>
{tags.map((tag) => (
<CommandItem
key={tag.id}
value={tag.value}
onSelect={() => toggleTag(tag)}
className="flex items-center gap-2"
>
<Tag className="h-3 w-3" style={tag.color ? { color: tag.color } : undefined} />
<span className="text-xs truncate flex-1">{tag.value}</span>
<Check className={cn("h-3 w-3", selectedSet.has(tag.id) ? "opacity-100" : "opacity-0")} />
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
);
}
interface ConditionEditorProps {
conditions: ICondition[];
onChange: (conditions: ICondition[]) => void;
@@ -192,6 +289,25 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha
<Input className="h-7 text-xs w-16" type="number" min={1} max={5} placeholder="Max" value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: parseInt(e.target.value) || undefined })} />
</div>
);
case "resolution": {
const unit = (condition.metric || "megapixels") === "megapixels" ? "MP" : "px";
return (
<div className="space-y-2">
<Select value={condition.metric || "megapixels"} onValueChange={(v) => onChange({ ...condition, metric: v })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="megapixels">Megapixels</SelectItem>
<SelectItem value="short_edge">Short Edge (px)</SelectItem>
<SelectItem value="long_edge">Long Edge (px)</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center gap-2">
<Input className="h-7 text-xs" type="number" min={0} step="any" placeholder={`Min ${unit}`} value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: e.target.value === "" ? undefined : parseFloat(e.target.value) })} />
<Input className="h-7 text-xs" type="number" min={0} step="any" placeholder={`Max ${unit}`} value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: e.target.value === "" ? undefined : parseFloat(e.target.value) })} />
</div>
</div>
);
}
case "is_favorited":
return (
<Select value={condition.value === false ? "false" : "true"} onValueChange={(v) => onChange({ ...condition, value: v === "true" })}>
@@ -202,6 +318,71 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha
</SelectContent>
</Select>
);
case "file_size":
return (
<div className="flex items-center gap-2">
<Input className="h-7 text-xs" type="number" min={0} step="any" placeholder="Min MB" value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: e.target.value === "" ? undefined : parseFloat(e.target.value) })} />
<Input className="h-7 text-xs" type="number" min={0} step="any" placeholder="Max MB" value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: e.target.value === "" ? undefined : parseFloat(e.target.value) })} />
</div>
);
case "filename":
return (
<div className="space-y-2">
<div className="flex gap-2">
<Select value={condition.field || "name"} onValueChange={(v) => onChange({ ...condition, field: v })}>
<SelectTrigger className="h-7 text-xs w-28"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="name">File Name</SelectItem>
<SelectItem value="path">File Path</SelectItem>
</SelectContent>
</Select>
<Select value={condition.match || "contains"} onValueChange={(v) => onChange({ ...condition, match: v })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="contains">Contains</SelectItem>
<SelectItem value="not_contains">Does not contain</SelectItem>
<SelectItem value="starts_with">Starts with</SelectItem>
<SelectItem value="ends_with">Ends with</SelectItem>
</SelectContent>
</Select>
</div>
<Input className="h-7 text-xs" placeholder="e.g. Screenshot" value={condition.text || ""} onChange={(e) => onChange({ ...condition, text: e.target.value })} />
</div>
);
case "file_extension":
return (
<div className="space-y-2">
<Select value={condition.match || "in"} onValueChange={(v) => onChange({ ...condition, match: v })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="in">Is any of</SelectItem>
<SelectItem value="not_in">Is none of</SelectItem>
</SelectContent>
</Select>
<Input className="h-7 text-xs" placeholder="e.g. png, gif, heic" value={condition.extensions || ""} onChange={(e) => onChange({ ...condition, extensions: e.target.value })} />
</div>
);
case "face_count":
return (
<div className="flex items-center gap-2">
<Input className="h-7 text-xs w-20" type="number" min={0} placeholder="Min" value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: e.target.value === "" ? undefined : parseInt(e.target.value) })} />
<Input className="h-7 text-xs w-20" type="number" min={0} placeholder="Max" value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: e.target.value === "" ? undefined : parseInt(e.target.value) })} />
<span className="text-xs text-muted-foreground">faces</span>
</div>
);
case "time_of_day":
return (
<div className="space-y-1">
<div className="flex items-center gap-1">
<span className="text-xs text-muted-foreground">From</span>
<Input className="h-7 text-xs w-16" type="number" min={0} max={23} placeholder="0" value={condition.fromHour ?? ""} onChange={(e) => onChange({ ...condition, fromHour: e.target.value === "" ? undefined : parseInt(e.target.value) })} />
<span className="text-xs text-muted-foreground">to</span>
<Input className="h-7 text-xs w-16" type="number" min={0} max={23} placeholder="23" value={condition.toHour ?? ""} onChange={(e) => onChange({ ...condition, toHour: e.target.value === "" ? undefined : parseInt(e.target.value) })} />
<span className="text-xs text-muted-foreground">h</span>
</div>
<p className="text-[10px] text-muted-foreground">Hours 0–23; From &gt; To wraps past midnight (e.g. 22 to 5).</p>
</div>
);
case "person":
return (
<div className="space-y-2">
@@ -219,6 +400,24 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha
/>
</div>
);
case "tag":
return (
<div className="space-y-2">
<Select value={condition.match || "contains_any"} onValueChange={(v) => onChange({ ...condition, match: v })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="contains_any">Has any of</SelectItem>
<SelectItem value="contains_all">Has all of</SelectItem>
<SelectItem value="not_contains">Has none of</SelectItem>
</SelectContent>
</Select>
<TagPicker
selectedIds={condition.tagIds || []}
onChange={(tagIds, tagValues) => onChange({ ...condition, tagIds, tagValues })}
/>
<p className="text-[10px] text-muted-foreground">Selected tags also match their child tags.</p>
</div>
);
case "geo_radius":
return (
<div className="space-y-1">
@@ -9,6 +9,7 @@ const actionIcons: Record<string, any> = {
unfavorite: HeartOff,
archive: Archive,
tag: Tag,
remove_tag: Tag,
};
const actionLabels: Record<string, string> = {
@@ -19,6 +20,7 @@ const actionLabels: Record<string, string> = {
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 && (
<p className="text-[10px] text-muted-foreground truncate max-w-[160px]">{config.albumName}</p>
)}
{subType === "tag" && config.tagName && (
{(subType === "tag" || subType === "remove_tag") && config.tagName && (
<p className="text-[10px] text-muted-foreground truncate max-w-[160px]">{config.tagName}</p>
)}
</div>
@@ -3,6 +3,7 @@ import { ICondition, ConditionType } from "@/types/workflow";
const conditionTypeLabels: Record<ConditionType, string> = {
person: "Person",
person_unnamed: "Unnamed People",
tag: "Tag",
city: "City",
state: "State",
country: "Country",
@@ -16,8 +17,14 @@ const conditionTypeLabels: Record<ConditionType, string> = {
asset_type: "Asset Type",
iso_range: "ISO Range",
focal_length: "Focal Length",
resolution: "Resolution",
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",
};
@@ -45,6 +52,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": {
@@ -95,8 +109,44 @@ export function formatConditionSummary(c: ICondition): string {
if (c.max != null) return `${label}: ≤${c.max}`;
return label;
}
case "resolution": {
const metricNames: Record<string, string> = { megapixels: "MP", short_edge: "short edge", long_edge: "long edge" };
const metric = c.metric || "megapixels";
const unit = metric === "megapixels" ? "MP" : "px";
const name = metric === "megapixels" ? "" : `${metricNames[metric]} `;
if (c.min != null && c.max != null) return `${label}: ${name}${c.min}–${c.max}${unit}`;
if (c.min != null) return `${label}: ${name}≥${c.min}${unit}`;
if (c.max != null) return `${label}: ${name}≤${c.max}${unit}`;
return label;
}
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<string, string> = { 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":
+45 -1
View File
@@ -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<typeof schema>) => {
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<typeof schema>) => {
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");
}
}
+30
View File
@@ -0,0 +1,30 @@
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: "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" },
];
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: "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[] =>
permissions.map((p) => p.name);
+1
View File
@@ -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;
+1 -1
View File
@@ -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.)
+9 -2
View File
@@ -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<IHeatMapResponse> => {
const params = year ? { year: String(year) } : {};
return API.get(HEATMAP_DATA, params);
}
export const getPeopleNamesStatistics = async () => {
+13
View File
@@ -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);
};
+22 -2
View File
@@ -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,
});
})
+16 -7
View File
@@ -67,10 +67,11 @@ const getOpenAICompatibleModel = () => {
};
export const parseFindQuery = async (query: string): Promise<FindQuery> => {
const today = new Date().toISOString().split("T")[0];
const prompt = [
`Parse the following query and return extracted filters as JSON: ${query}.`,
"Do not include any information that is not intentionally provided in the query.",
`Today's date is ${new Date().toISOString().split("T")[0]}.`,
`Today's date is ${today}. Use it ONLY to resolve relative expressions like "last week" or "yesterday" that APPEAR IN THE QUERY. If no date-related word is in the query, DO NOT return takenAfter or takenBefore.`,
"Dates must be in YYYY-MM-DD format.",
"Return ONLY valid JSON object with keys: query, personIds, city, country, state, size, model, takenAfter, takenBefore, type.",
"Do not use null values. Omit a key when it is not present in the query.",
@@ -81,10 +82,9 @@ export const parseFindQuery = async (query: string): Promise<FindQuery> => {
model: getOpenAICompatibleModel(),
prompt,
output: Output.object({
name:"json",
name: "json",
schema: responseSchema,
}),
});
const parsedResponse = JSON.parse(text) as FindQuery;
@@ -94,9 +94,18 @@ export const parseFindQuery = async (query: string): Promise<FindQuery> => {
delete parsedResponse.type;
}
}
const cleanedResponse = {
...parsedResponse
};
return removeNullOrUndefinedProperties(cleanedResponse) as any as FindQuery;
// Guardrail against a common LLM failure mode: small-to-medium models
// (qwen2.5:7b, Gemini flash, etc.) often echo the prompt's "today" date as
// `takenAfter` even when the query has no date. A date in the future can
// never match a photo, so drop any takenAfter/takenBefore that is today or
// later — this keeps the filter purely corrective without guessing intent.
if (parsedResponse.takenAfter && parsedResponse.takenAfter >= today) {
delete parsedResponse.takenAfter;
}
if (parsedResponse.takenBefore && parsedResponse.takenBefore > today) {
delete parsedResponse.takenBefore;
}
return removeNullOrUndefinedProperties(parsedResponse) as any as FindQuery;
};
+14 -10
View File
@@ -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`;
}
+40 -10
View File
@@ -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";
@@ -28,6 +28,16 @@ async function getWorkflowApiKey(ownerId: string): Promise<string | null> {
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<string, any>, user: IUser): Promise<void> {
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<any> {
const workflowApiKey = await getWorkflowApiKey(user.id);
@@ -136,51 +146,71 @@ 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, isArchived: true }, user);
await immichFetchBatched("/assets", "PUT", 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);
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 };
}
}
case "remove_tag": {
if (!config.tagName) throw new Error("Tag name is required");
try {
// 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/${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 };
}
}
default:
return { action: subType, assetsProcessed: 0, error: `Unknown action: ${subType}` };
}
+102
View File
@@ -92,6 +92,78 @@ function buildSingleCondition(c: ICondition): SQL | undefined {
return parts.length > 0 ? and(...parts)! : undefined;
}
case "resolution": {
// Short/long edge are orientation-agnostic; megapixels = width × height / 1e6.
const metric = c.metric || "megapixels";
const value =
metric === "short_edge"
? sql`LEAST(${exif.exifImageWidth}, ${exif.exifImageHeight})`
: metric === "long_edge"
? sql`GREATEST(${exif.exifImageWidth}, ${exif.exifImageHeight})`
: sql`(${exif.exifImageWidth}::bigint * ${exif.exifImageHeight}) / 1000000.0`;
const parts: SQL[] = [];
if (c.min !== undefined && c.min !== null) parts.push(sql`${value} >= ${c.min}`);
if (c.max !== undefined && c.max !== null) parts.push(sql`${value} <= ${c.max}`);
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;
@@ -117,6 +189,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 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":
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))`;
+76 -42
View File
@@ -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<T extends { id: string }>(
fetchBatch: (afterId: string | null, limit: number) => Promise<T[]>,
): Promise<T[]> {
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<string[]> {
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[];
-1
View File
@@ -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,
+3 -1
View File
@@ -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<string>`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);
+3 -1
View File
@@ -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);
+5 -3
View File
@@ -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<string>`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);
+8 -2
View File
@@ -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) {
+86 -54
View File
@@ -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<string>`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<number>`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 });
}
}
+11 -1
View File
@@ -3,8 +3,17 @@ 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 = {
api: {
bodyParser: {
sizeLimit: "10mb",
},
},
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
@@ -31,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)
)
);
+1 -9
View File
@@ -39,19 +39,11 @@ export default async function handler(
}
const durationExpr = sql<number>`
(
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<number>`(${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,
@@ -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,
-1
View File
@@ -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,
+5 -4
View File
@@ -4,6 +4,7 @@ import { ASSET_VIDEO_PATH } from "@/config/routes";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { cleanUpAsset, isFlipped } from "@/helpers/asset.helper";
import { parseFindQuery } from "@/helpers/ai.helper";
import { getUserHeaders } from "@/helpers/user.helper";
import { person } from "@/schema";
import { Person } from "@/schema/person.schema";
import { inArray } from "drizzle-orm";
@@ -16,6 +17,9 @@ export default async function search(
try {
const { query } = req.body;
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(403).json({ message: "Not authenticated" });
}
const parsedQuery = await parseFindQuery(query as string);
const { personIds } = parsedQuery;
@@ -32,10 +36,7 @@ export default async function search(
return fetch(url, {
method: "POST",
body: JSON.stringify({ ...parsedQuery, withExif: true }),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${currentUser?.accessToken}`,
},
headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }),
})
.then((response) => {
if (response.status !== 200) {
+136 -42
View File
@@ -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;
@@ -11,28 +12,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 +24,6 @@ interface ImmichAlbumResponse {
lastModifiedAssetTimestamp?: string | null;
order?: string | null;
contributorCounts?: IAlbumContributorCount[];
assets: ImmichAsset[];
}
interface ImmichSharedLinkResponse {
@@ -58,7 +40,7 @@ interface ImmichSharedLinkResponse {
interface IImportSharedAsset {
id: string;
originalFileName: string;
originalFileName?: string;
type: string;
fileCreatedAt?: string | null;
localDateTime?: string | null;
@@ -66,6 +48,19 @@ interface IImportSharedAsset {
location?: string | null;
thumbhash?: string | null;
fileSizeInByte?: number | null;
// Ente-specific encryption artifacts (optional)
enteFileKey?: string;
enteFileDecryptionHeader?: string;
enteThumbnailDecryptionHeader?: string;
}
interface ITimeBucketAssets {
id: string[];
fileCreatedAt: string[];
isImage: boolean[];
thumbhash: (string | null)[];
city?: (string | null)[];
country?: (string | null)[];
}
interface IImportSharedAlbum {
@@ -84,7 +79,7 @@ interface IImportSharedAlbum {
}
interface IImportSharedResponse {
platform: "immich" | "nextcloud";
platform: "immich" | "nextcloud" | "ente";
link: string;
origin: string;
key: string;
@@ -98,6 +93,9 @@ interface IImportSharedResponse {
showMetadata?: boolean;
};
album: IImportSharedAlbum | null;
// Ente-specific (optional)
enteApiBase?: string;
enteAlbumKey?: string;
}
const respondWithError = (res: NextApiResponse, status: number, message: string) => {
@@ -122,13 +120,39 @@ const parseSharedLink = (link: string) => {
}
};
const buildLocationString = (exif?: ImmichExifInfo | null) => {
if (!exif) {
return null;
const enumerateAlbumAssets = async (
origin: string,
albumId: string,
authQuery: string
): Promise<IImportSharedAsset[]> => {
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<ITimeBucketAssets>(
`${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 <T>(url: string) => {
@@ -246,10 +270,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
@@ -266,25 +370,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (albumId) {
const album = await fetchJson<ImmichAlbumResponse>(
`${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,
+328
View File
@@ -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<typeof _sodium> => {
if (sodiumReady) return sodiumReady;
await _sodium.ready;
sodiumReady = _sodium;
return _sodium;
};
export const decryptSecretBox = async (
ciphertext_b64: string,
nonce_b64: string,
key: Uint8Array
): Promise<Uint8Array> => {
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<Buffer> => {
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<string, string> => ({
"X-Auth-Access-Token": token,
Accept: "application/json",
});
const getCollectionInfo = async (
apiBase: string,
token: string
): Promise<EnteCollectionResponse> => {
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<EnteDiffFile[]> => {
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<string> => {
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<EnteAlbumResult> => {
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 };
};
+47 -5
View File
@@ -174,7 +174,6 @@ export const uploadAssetBuffer = async (
payload: DownloadedAssetPayload,
uploadHeaders: HeadersRecord,
jsonHeaders: HeadersRecord,
deviceAssetId: string,
tagId?: string
): Promise<string> => {
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<string | null> => {
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<Set<string>> => {
const existing = new Set<string>();
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,
+28
View File
@@ -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") {
+7 -44
View File
@@ -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<string, string>();
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<string>();
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
+1 -4
View File
@@ -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());
+5
View File
@@ -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<string, string>;
@@ -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) {
@@ -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) {
+13 -63
View File
@@ -1,14 +1,7 @@
import { ENV } from "@/config/environment";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiRequest, NextApiResponse } from "next";
const REQUIRED_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" });
@@ -16,16 +9,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 : getPermissionNames(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,57 +28,13 @@ 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 missing = REQUIRED_PERMISSIONS.filter((p) => !granted.includes(p));
const keyData = await keyRes.json();
const granted: string[] = keyData.permissions ?? [];
// 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,
+1 -2
View File
@@ -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(),
+30
View File
@@ -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 });
}
}
+4 -2
View File
@@ -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 {
+34 -14
View File
@@ -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";
@@ -73,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 {
@@ -94,7 +91,7 @@ interface IImportSharedAlbum {
}
interface IImportSharedResponse {
platform: "immich" | "nextcloud";
platform: "immich" | "nextcloud" | "ente";
link: string;
origin: string;
key: string;
@@ -108,6 +105,9 @@ interface IImportSharedResponse {
showMetadata?: boolean;
};
album: IImportSharedAlbum | null;
// Ente-specific (optional)
enteApiBase?: string;
enteAlbumKey?: string;
}
const formatDate = (value?: string | null) => {
@@ -347,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()}`;
};
@@ -375,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()}`;
};
@@ -407,10 +417,15 @@ export default function ImportSharedPage() {
setImportAllLoading(true);
try {
const isNextcloud = sharedData.platform === "nextcloud";
const isEnte = sharedData.platform === "ente";
const urlConfig: Record<string, string> = { 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,
@@ -427,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);
@@ -501,7 +521,7 @@ export default function ImportSharedPage() {
<div className="space-y-2">
<h1 className="text-2xl font-bold tracking-tight">Import a shared album</h1>
<p className="text-sm text-muted-foreground">
Paste a public shared link from <strong className="font-medium">Immich</strong> or <strong className="font-medium">Nextcloud</strong> to import its assets into your Immich instance.
Paste a public shared link from <strong className="font-medium">Immich</strong>, <strong className="font-medium">Nextcloud</strong>, or <strong className="font-medium">Ente</strong> to import its assets into your Immich instance.
</p>
</div>
@@ -518,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"
@@ -717,7 +737,7 @@ export default function ImportSharedPage() {
: "hover:opacity-90"
}`}
onClick={() => {
if (isVideoAsset) {
if (isVideoAsset && sharedData?.platform !== "ente") {
setActiveImageAsset(null);
setActiveVideoAsset(asset);
setPreviewLoading(false);
@@ -758,8 +778,8 @@ export default function ImportSharedPage() {
/>
</div>
{/* Video play indicator */}
{isVideoAsset && (
{/* Video play indicator (hidden for Ente — no video preview) */}
{isVideoAsset && sharedData?.platform !== "ente" && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="rounded-full bg-black/50 p-2">
<svg className="h-4 w-4 text-white ml-0.5" viewBox="0 0 24 24" fill="currentColor">
+9 -2
View File
@@ -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<IFindFilters>({});
const [error, setError] = useState<string | null>(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() {
</div>
)
}
else if (query.length === 0) {
else if (searchedQuery.length === 0) {
return (
<div className="flex justify-center flex-col gap-2 items-center h-full">
<Search className='w-10 h-10 text-muted-foreground' />
@@ -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}
</Button>
@@ -279,6 +285,7 @@ export default function FindPage() {
value={query}
onChange={setQuery}
onSearch={handleSearch}
loading={loading}
/>
</div>
{/* renderContent now includes the Provider */}
+74 -11
View File
@@ -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 (
@@ -50,6 +51,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 +75,45 @@ export default function SettingsPage() {
}
};
const IMPORT_REQUIRED_PERMISSIONS = ["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create", "tag.asset"];
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);
};
@@ -235,8 +270,8 @@ export default function SettingsPage() {
)}
{!validationResult && (
<div className="flex flex-wrap gap-1">
{["asset.read", "asset.update", "album.create", "album.update", "tag.create"].map((p) => (
<Badge key={p} variant="outline" className="text-[10px] h-5 font-mono font-normal">{p}</Badge>
{WORKFLOW_PERMISSIONS.map((p) => (
<Badge key={p.name} variant="outline" className="text-[10px] h-5 font-mono font-normal">{p.name}</Badge>
))}
</div>
)}
@@ -294,18 +329,46 @@ export default function SettingsPage() {
{importApiKeyLoading ? "Saving..." : "Save"}
</Button>
</div>
<div className="flex flex-wrap gap-1">
{["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create"].map((p) => (
<Badge key={p} variant="outline" className="text-[10px] h-5 font-mono font-normal">{p}</Badge>
))}
</div>
{importValidationResult && (
<div className={`rounded-md p-2.5 text-xs ${importValidationResult.valid ? "bg-green-500/10 border border-green-500/20" : "bg-destructive/10 border border-destructive/20"}`}>
<div className="flex items-center gap-1.5 mb-1.5">
{importValidationResult.valid ? (
<><CheckCircle className="h-3.5 w-3.5 text-green-500" /><span className="font-medium text-green-600 dark:text-green-400">All permissions verified</span></>
) : (
<><XCircle className="h-3.5 w-3.5 text-destructive" /><span className="font-medium text-destructive">{importValidationResult.error}</span></>
)}
</div>
<div className="flex flex-wrap gap-1">
{IMPORT_REQUIRED_PERMISSIONS.map((p) => {
const granted = importValidationResult.permissions.includes(p);
const missing = importValidationResult.missing.includes(p);
return (
<Badge
key={p}
variant="outline"
className={`text-[10px] h-5 font-mono font-normal ${granted ? "border-green-500/40 text-green-600 dark:text-green-400" : missing ? "border-destructive/40 text-destructive" : ""}`}
>
{granted ? "✓" : "✗"} {p}
</Badge>
);
})}
</div>
</div>
)}
{!importValidationResult && (
<div className="flex flex-wrap gap-1">
{IMPORT_REQUIRED_PERMISSIONS.map((p) => (
<Badge key={p} variant="outline" className="text-[10px] h-5 font-mono font-normal">{p}</Badge>
))}
</div>
)}
<div className="flex items-center justify-between">
<Button
size="sm"
variant="outline"
className="h-7 text-xs"
onClick={handleGenerateImportKey}
disabled={generatingImportKey}
disabled={generatingImportKey || importApiKeySaved}
>
<Wand2 className="h-3 w-3 mr-1" />
{generatingImportKey ? "Generating..." : "Generate automatically"}
+1 -8
View File
@@ -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);
+2 -2
View File
@@ -135,11 +135,11 @@ function AnnotatedActionNode({ data }: NodeProps) {
const step = data.runStep as any;
const icons: Record<string, any> = {
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<string, string> = {
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");
+8
View File
@@ -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(),
});
-1
View File
@@ -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'),
+2 -4
View File
@@ -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' }),
+2 -1
View File
@@ -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';
export { tags } from './tags.schema';
export * from './relationships';
+11
View File
@@ -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(),
});
+88
View File
@@ -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));
}
+1 -6
View File
@@ -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[];
+4 -2
View File
@@ -49,12 +49,14 @@ 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"
| "asset_type" | "iso_range" | "focal_length"
| "rating" | "is_favorited"
| "rating" | "is_favorited" | "resolution"
| "file_size" | "filename" | "file_extension"
| "face_count" | "time_of_day"
| "not_in_album" | "not_in_specific_album";
export interface ICondition {
@@ -0,0 +1,239 @@
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<DownloadedAssetPayload> => {
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<SetupResult> {
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<string, 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 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<string, unknown> = {};
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<string, unknown> = {};
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<string, unknown> = {};
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,
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 };
}
}
@@ -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<string, string>();
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<string, unknown> = {};
@@ -183,7 +154,6 @@ export class ImmichSharedLinkProcessor implements ImportProcessor {
downloaded,
uploadHeaders as HeadersRecord,
headers as HeadersRecord,
makeDeviceAssetId(asset.id),
tagId
);
+2
View File
@@ -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());
@@ -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<string, 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 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<string, unknown> = {};
@@ -199,7 +159,6 @@ export class NextcloudSharedLinkProcessor implements ImportProcessor {
downloaded,
uploadHeaders as HeadersRecord,
headers as HeadersRecord,
makeDeviceAssetId(relativePath),
tagId
);