Merge pull request #249 from immich-power-tools/feat/smart-auto-albums
Smart auto albums and workflows 🚀
This commit is contained in:
113 files changed
+13481
-939
No files matched your search
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "",
|
||||
"pr": ""
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -15,6 +15,8 @@ AI_BASE_URL="https://api.openai.com/v1" # Base URL for OpenAI-compatible API
|
||||
AI_MODEL="gpt-4o-mini" # Model used for parsing search queries in "Find"
|
||||
|
||||
# Immich Share Link
|
||||
IMMICH_SHARE_LINK_KEY="" # Share link key for Immich
|
||||
POWER_TOOLS_ENDPOINT_URL="" # URL of the Power Tools endpoint (Used for share links)
|
||||
JWT_SECRET="" # JWT Secret for authentication
|
||||
|
||||
# App Database (SQLite)
|
||||
APP_DB_PATH="" # Path to the SQLite database file (default: ./data/app.db)
|
||||
@@ -28,6 +28,11 @@ yarn-error.log*
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# SQLite database files
|
||||
/data/*.db
|
||||
/data/*.db-shm
|
||||
/data/*.db-wal
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
@@ -35,4 +40,7 @@ yarn-error.log*
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# plans
|
||||
/docs/plans
|
||||
|
||||
.env
|
||||
+10
-8
@@ -1,13 +1,10 @@
|
||||
# Source: https://github.com/vercel/next.js/blob/canary/examples/with-docker/README.md
|
||||
|
||||
# Install dependencies only when needed
|
||||
FROM node:22-alpine AS deps
|
||||
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
|
||||
|
||||
RUN apk add --no-cache libc6-compat
|
||||
FROM oven/bun:1-alpine AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json ./
|
||||
RUN npm install --frozen-lockfile
|
||||
COPY package.json bun.lock ./
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
# Rebuild the source code only when needed
|
||||
FROM node:22-alpine AS builder
|
||||
@@ -38,10 +35,15 @@ RUN adduser -S nextjs -u 1001
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/package.json ./package.json
|
||||
|
||||
# Automatically leverage output traces to reduce image size
|
||||
# Automatically leverage output traces to reduce image size
|
||||
# https://nextjs.org/docs/advanced-features/output-file-tracing
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/src/db/migrations ./src/db/migrations
|
||||
|
||||
# Copy native libsql binaries — Next.js standalone tracing misses dynamically required native modules
|
||||
COPY --from=deps --chown=nextjs:nodejs /app/node_modules/@libsql ./node_modules/@libsql
|
||||
COPY --from=deps --chown=nextjs:nodejs /app/node_modules/libsql ./node_modules/libsql
|
||||
|
||||
USER nextjs
|
||||
|
||||
@@ -58,4 +60,4 @@ ENV HOSTNAME=0.0.0.0
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
|
||||
HEALTHCHECK CMD curl --fail http://localhost:3000/api/health || exit 1
|
||||
HEALTHCHECK CMD curl --fail http://localhost:3000/api/health || exit 1
|
||||
@@ -0,0 +1,549 @@
|
||||
# Orphan Asset Finder Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Build a page that finds "orphaned" assets — those not in albums, without detected people, missing location, or never favorited — with combinable checkbox filters, asset grid, and bulk actions (add to album, trash, delete).
|
||||
|
||||
**Architecture:** New API route queries Immich's DB via Drizzle with LEFT JOINs to detect orphan conditions. Frontend page follows the empty-videos pattern: filters in Header, AssetGrid with PhotoSelectionContext, FloatingBar with bulk actions. Sidebar entry added.
|
||||
|
||||
**Tech Stack:** Next.js API route, Drizzle ORM (PostgreSQL), React, Tailwind, existing shared components (PageLayout, Header, FloatingBar, AssetGrid, AlbumSelectorDialog, AlertDialog).
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add API route for orphan assets
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pages/api/assets/orphan-finder.ts`
|
||||
|
||||
**Step 1: Create the API route**
|
||||
|
||||
```typescript
|
||||
import { db } from "@/config/db";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { and, eq, isNull, isNotNull, sql, desc, asc, not } from "drizzle-orm";
|
||||
import { assets } from "@/schema/assets.schema";
|
||||
import { exif } from "@/schema";
|
||||
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
|
||||
import { assetFaces } from "@/schema/assetFaces.schema";
|
||||
import { isFlipped } from "@/helpers/asset.helper";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const {
|
||||
notInAlbum,
|
||||
noPeople,
|
||||
noLocation,
|
||||
notFavorited,
|
||||
type,
|
||||
limit = "100",
|
||||
page = "1",
|
||||
} = req.query as Record<string, string>;
|
||||
|
||||
const limitNum = parseInt(limit, 10);
|
||||
const pageNum = parseInt(page, 10);
|
||||
|
||||
// Build conditions
|
||||
const conditions = [
|
||||
eq(assets.ownerId, currentUser.id),
|
||||
eq(assets.visibility, "timeline"),
|
||||
eq(assets.status, "active"),
|
||||
isNull(assets.deletedAt),
|
||||
];
|
||||
|
||||
if (type && type !== "ALL") {
|
||||
conditions.push(eq(assets.type, type));
|
||||
}
|
||||
|
||||
if (notFavorited === "true") {
|
||||
conditions.push(eq(assets.isFavorite, false));
|
||||
}
|
||||
|
||||
if (noLocation === "true") {
|
||||
conditions.push(isNull(exif.latitude));
|
||||
}
|
||||
|
||||
// Subquery approach for notInAlbum and noPeople
|
||||
const notInAlbumCondition = notInAlbum === "true"
|
||||
? sql`NOT EXISTS (SELECT 1 FROM "album_asset" aa WHERE aa."assetId" = ${assets.id})`
|
||||
: undefined;
|
||||
|
||||
const noPeopleCondition = noPeople === "true"
|
||||
? sql`NOT EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IS NOT NULL)`
|
||||
: undefined;
|
||||
|
||||
if (notInAlbumCondition) conditions.push(notInAlbumCondition);
|
||||
if (noPeopleCondition) conditions.push(noPeopleCondition);
|
||||
|
||||
// At least one orphan filter must be active
|
||||
const hasOrphanFilter = notInAlbum === "true" || noPeople === "true" || noLocation === "true" || notFavorited === "true";
|
||||
if (!hasOrphanFilter) {
|
||||
return res.status(400).json({ message: "At least one orphan filter is required" });
|
||||
}
|
||||
|
||||
const dbAssets = await db
|
||||
.selectDistinctOn([assets.id], {
|
||||
id: assets.id,
|
||||
deviceId: assets.deviceId,
|
||||
type: assets.type,
|
||||
originalPath: assets.originalPath,
|
||||
isFavorite: assets.isFavorite,
|
||||
duration: assets.duration,
|
||||
originalFileName: assets.originalFileName,
|
||||
deletedAt: assets.deletedAt,
|
||||
localDateTime: assets.localDateTime,
|
||||
exifImageWidth: exif.exifImageWidth,
|
||||
exifImageHeight: exif.exifImageHeight,
|
||||
ownerId: assets.ownerId,
|
||||
dateTimeOriginal: exif.dateTimeOriginal,
|
||||
orientation: exif.orientation,
|
||||
})
|
||||
.from(assets)
|
||||
.leftJoin(exif, eq(assets.id, exif.assetId))
|
||||
.where(and(...conditions))
|
||||
.orderBy(assets.id, desc(assets.localDateTime))
|
||||
.limit(limitNum)
|
||||
.offset((pageNum - 1) * limitNum);
|
||||
|
||||
const cleanedAssets = dbAssets.map((asset) => ({
|
||||
...asset,
|
||||
exifImageHeight: isFlipped(asset?.orientation) ? asset?.exifImageWidth : asset?.exifImageHeight,
|
||||
exifImageWidth: isFlipped(asset?.orientation) ? asset?.exifImageHeight : asset?.exifImageWidth,
|
||||
orientation: asset?.orientation,
|
||||
}));
|
||||
|
||||
return res.status(200).json(cleanedAssets);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/pages/api/assets/orphan-finder.ts
|
||||
git commit -m "feat: add orphan finder API route"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Add route constant and handler function
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/config/routes.ts`
|
||||
- Modify: `src/handlers/api/asset.handler.ts`
|
||||
|
||||
**Step 1: Add route constant**
|
||||
|
||||
In `src/config/routes.ts`, add after `LIST_EMPTY_VIDEOS_PATH`:
|
||||
|
||||
```typescript
|
||||
export const LIST_ORPHAN_ASSETS_PATH = BASE_API_ENDPOINT + "/assets/orphan-finder";
|
||||
```
|
||||
|
||||
**Step 2: Add handler function**
|
||||
|
||||
In `src/handlers/api/asset.handler.ts`, add import and function:
|
||||
|
||||
Add `LIST_ORPHAN_ASSETS_PATH` to the imports from `@/config/routes`.
|
||||
|
||||
Add this function:
|
||||
|
||||
```typescript
|
||||
export interface IOrphanFilters {
|
||||
notInAlbum?: boolean;
|
||||
noPeople?: boolean;
|
||||
noLocation?: boolean;
|
||||
notFavorited?: boolean;
|
||||
type?: string;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export const listOrphanAssets = async (filters: IOrphanFilters): Promise<IAsset[]> => {
|
||||
const params: Record<string, string> = {};
|
||||
if (filters.notInAlbum) params.notInAlbum = "true";
|
||||
if (filters.noPeople) params.noPeople = "true";
|
||||
if (filters.noLocation) params.noLocation = "true";
|
||||
if (filters.notFavorited) params.notFavorited = "true";
|
||||
if (filters.type) params.type = filters.type;
|
||||
if (filters.limit) params.limit = String(filters.limit);
|
||||
if (filters.page) params.page = String(filters.page);
|
||||
return API.get(LIST_ORPHAN_ASSETS_PATH, params).then((assets) => assets.map(cleanUpAsset));
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/config/routes.ts src/handlers/api/asset.handler.ts
|
||||
git commit -m "feat: add orphan finder route constant and handler"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Create the Orphan Finder page
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pages/assets/orphan-finder.tsx`
|
||||
|
||||
**Step 1: Create the page**
|
||||
|
||||
Follow the empty-videos pattern: PageLayout, Header with filters, PhotoSelectionContext, AssetGrid, FloatingBar with bulk actions.
|
||||
|
||||
```tsx
|
||||
import PageLayout from '@/components/layouts/PageLayout'
|
||||
import Header from '@/components/shared/Header'
|
||||
import Loader from '@/components/ui/loader'
|
||||
import { listOrphanAssets, deleteAssets, IOrphanFilters } from '@/handlers/api/asset.handler'
|
||||
import { addAssetToAlbum, createAlbumWithAssets } from '@/handlers/api/album.handler'
|
||||
import { IAsset } from '@/types/asset'
|
||||
import React, { useEffect, useState, useMemo } from 'react'
|
||||
import { Camera, Trash2, Trash, Search } from 'lucide-react'
|
||||
import { humanizeNumber } from '@/helpers/string.helper'
|
||||
import PhotoSelectionContext, { IPhotoSelectionContext } from '@/contexts/PhotoSelectionContext'
|
||||
import FloatingBar from '@/components/shared/FloatingBar'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { AlertDialog } from '@/components/ui/alert-dialog'
|
||||
import AssetGrid from '@/components/shared/AssetGrid'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import AlbumSelectorDialog from '@/components/albums/AlbumSelectorDialog'
|
||||
import { IAlbum } from '@/types/album'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
|
||||
export default function OrphanFinderPage() {
|
||||
const [assets, setAssets] = useState<IAsset[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState('')
|
||||
|
||||
const [filters, setFilters] = useState<IOrphanFilters>({
|
||||
notInAlbum: true,
|
||||
noPeople: false,
|
||||
noLocation: false,
|
||||
notFavorited: false,
|
||||
type: 'ALL',
|
||||
limit: 200,
|
||||
page: 1,
|
||||
})
|
||||
|
||||
const [contextState, setContextState] = useState<IPhotoSelectionContext>({
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
config: {
|
||||
albumId: '',
|
||||
sort: "fileOriginalDate",
|
||||
sortOrder: "asc"
|
||||
},
|
||||
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => {
|
||||
setContextState(prevState => ({
|
||||
...prevState,
|
||||
...newConfig,
|
||||
config: newConfig.config ? { ...prevState.config, ...newConfig.config } : prevState.config
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
const selectedAssets = useMemo(() =>
|
||||
contextState.assets.filter((a) => contextState.selectedIds.includes(a.id)),
|
||||
[contextState.assets, contextState.selectedIds]
|
||||
);
|
||||
|
||||
const hasActiveFilter = filters.notInAlbum || filters.noPeople || filters.noLocation || filters.notFavorited;
|
||||
|
||||
const fetchOrphans = async () => {
|
||||
if (!hasActiveFilter) return;
|
||||
setLoading(true)
|
||||
setErrorMessage('')
|
||||
listOrphanAssets(filters)
|
||||
.then((fetchedAssets) => {
|
||||
setAssets(fetchedAssets)
|
||||
contextState.updateContext({ assets: fetchedAssets, selectedIds: [] })
|
||||
})
|
||||
.catch((error) => {
|
||||
setErrorMessage(error.message || 'Failed to load orphan assets')
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchOrphans()
|
||||
}, [filters])
|
||||
|
||||
const handleDelete = () => {
|
||||
return deleteAssets(contextState.selectedIds, { force: true }).then(() => {
|
||||
const newAssets = contextState.assets.filter((a) => !contextState.selectedIds.includes(a.id));
|
||||
setAssets(newAssets)
|
||||
contextState.updateContext({ selectedIds: [], assets: newAssets });
|
||||
})
|
||||
}
|
||||
|
||||
const handleTrash = () => {
|
||||
return deleteAssets(contextState.selectedIds, { force: false }).then(() => {
|
||||
const newAssets = contextState.assets.filter((a) => !contextState.selectedIds.includes(a.id));
|
||||
setAssets(newAssets)
|
||||
contextState.updateContext({ selectedIds: [], assets: newAssets });
|
||||
})
|
||||
}
|
||||
|
||||
const handleAddToAlbum = async (album: IAlbum) => {
|
||||
await addAssetToAlbum(album.id, contextState.selectedIds);
|
||||
toast({ title: "Success", description: `Added ${contextState.selectedIds.length} asset(s) to "${album.albumName}"` });
|
||||
// Re-fetch if "not in album" filter is active (assets may no longer be orphans)
|
||||
if (filters.notInAlbum) {
|
||||
fetchOrphans();
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateAlbumWithAssets = async (data: { albumName: string }) => {
|
||||
return createAlbumWithAssets(data.albumName, contextState.selectedIds).then(() => {
|
||||
if (filters.notInAlbum) {
|
||||
fetchOrphans();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const handleFilterToggle = (key: keyof IOrphanFilters) => {
|
||||
setFilters(prev => ({ ...prev, [key]: !prev[key], page: 1 }));
|
||||
}
|
||||
|
||||
const renderContent = () => {
|
||||
if (!hasActiveFilter) {
|
||||
return (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
Select at least one filter to find orphan assets.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (loading) return <Loader />
|
||||
if (errorMessage) return <div className="text-red-500 p-4">{errorMessage}</div>
|
||||
return (
|
||||
<div className="p-4">
|
||||
{assets.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
<Search size={48} className="mx-auto text-gray-400 mb-4" />
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">No orphan assets found</h3>
|
||||
<p>All your assets are well-organized with the current filters.</p>
|
||||
</div>
|
||||
) : (
|
||||
<AssetGrid
|
||||
assets={assets}
|
||||
selectable={true}
|
||||
onSelectionChange={(ids) => contextState.updateContext({ selectedIds: ids })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PageLayout className="!p-0 !mb-0 relative pb-20">
|
||||
<Header
|
||||
leftComponent="Orphan Finder"
|
||||
rightComponent={
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="notInAlbum"
|
||||
checked={filters.notInAlbum}
|
||||
onCheckedChange={() => handleFilterToggle('notInAlbum')}
|
||||
/>
|
||||
<Label htmlFor="notInAlbum" className="text-sm cursor-pointer">No Album</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="noPeople"
|
||||
checked={filters.noPeople}
|
||||
onCheckedChange={() => handleFilterToggle('noPeople')}
|
||||
/>
|
||||
<Label htmlFor="noPeople" className="text-sm cursor-pointer">No People</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="noLocation"
|
||||
checked={filters.noLocation}
|
||||
onCheckedChange={() => handleFilterToggle('noLocation')}
|
||||
/>
|
||||
<Label htmlFor="noLocation" className="text-sm cursor-pointer">No Location</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="notFavorited"
|
||||
checked={filters.notFavorited}
|
||||
onCheckedChange={() => handleFilterToggle('notFavorited')}
|
||||
/>
|
||||
<Label htmlFor="notFavorited" className="text-sm cursor-pointer">Not Favorited</Label>
|
||||
</div>
|
||||
</div>
|
||||
<Select
|
||||
value={filters.type}
|
||||
onValueChange={(value) => setFilters(prev => ({ ...prev, type: value, page: 1 }))}
|
||||
>
|
||||
<SelectTrigger className="w-28 h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ALL">All Types</SelectItem>
|
||||
<SelectItem value="IMAGE">Images</SelectItem>
|
||||
<SelectItem value="VIDEO">Videos</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{!loading && assets.length > 0 && (
|
||||
<div className="flex items-center gap-1 text-sm text-gray-700 dark:text-gray-500">
|
||||
{humanizeNumber(assets.length)}
|
||||
<Camera className="w-4 h-4" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<PhotoSelectionContext.Provider value={{ ...contextState, updateContext: contextState.updateContext }}>
|
||||
{renderContent()}
|
||||
{selectedAssets.length > 0 && (
|
||||
<FloatingBar>
|
||||
<div className="flex items-center gap-2 justify-between w-full">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{contextState.selectedIds.length} Selected
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
{contextState.selectedIds.length === contextState.assets.length ? (
|
||||
<Button variant="outline" size="sm" onClick={() => contextState.updateContext({ selectedIds: [] })}>
|
||||
Unselect all
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outline" size="sm" onClick={() => contextState.updateContext({ selectedIds: contextState.assets.map((a) => a.id) })}>
|
||||
Select all
|
||||
</Button>
|
||||
)}
|
||||
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600" />
|
||||
<AlbumSelectorDialog
|
||||
onSelected={handleAddToAlbum}
|
||||
onSubmit={handleCreateAlbumWithAssets}
|
||||
/>
|
||||
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600" />
|
||||
<AlertDialog
|
||||
title="Move selected assets to Trash?"
|
||||
description="This action will move the selected assets to trash. You can restore them later."
|
||||
onConfirm={handleTrash}
|
||||
disabled={contextState.selectedIds.length === 0}
|
||||
>
|
||||
<Button variant="outline" size="sm" disabled={contextState.selectedIds.length === 0}>
|
||||
<Trash className="w-4 h-4 mr-2" />
|
||||
Trash
|
||||
</Button>
|
||||
</AlertDialog>
|
||||
<AlertDialog
|
||||
title="Delete the selected assets?"
|
||||
description="This action will delete the selected assets and cannot be undone."
|
||||
onConfirm={handleDelete}
|
||||
disabled={contextState.selectedIds.length === 0}
|
||||
>
|
||||
<Button variant="destructive" size="sm" disabled={contextState.selectedIds.length === 0}>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Delete
|
||||
</Button>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
</FloatingBar>
|
||||
)}
|
||||
</PhotoSelectionContext.Provider>
|
||||
</PageLayout>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/pages/assets/orphan-finder.tsx
|
||||
git commit -m "feat: add orphan finder page with filters and bulk actions"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Add sidebar entry
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/config/constants/sidebarNavs.tsx`
|
||||
|
||||
**Step 1: Add the sidebar nav entry**
|
||||
|
||||
Add `PackageSearch` to the lucide-react import, then add the entry after "Bulk Duplicate Finder":
|
||||
|
||||
```tsx
|
||||
{
|
||||
title: "Orphan Finder",
|
||||
link: "/assets/orphan-finder",
|
||||
icon: <PackageSearch className="h-4 w-4" />,
|
||||
},
|
||||
```
|
||||
|
||||
**Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/config/constants/sidebarNavs.tsx
|
||||
git commit -m "feat: add orphan finder to sidebar navigation"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Verify createAlbumWithAssets handler exists
|
||||
|
||||
**Files:**
|
||||
- Possibly modify: `src/handlers/api/album.handler.ts`
|
||||
|
||||
**Step 1: Check if `createAlbumWithAssets` exists in album handler**
|
||||
|
||||
If it doesn't exist, add it. This function should create an album via Immich API and then add selected assets to it.
|
||||
|
||||
```typescript
|
||||
export const createAlbumWithAssets = async (albumName: string, assetIds: string[]) => {
|
||||
const album = await API.post(CREATE_ALBUM_PATH, { albumName, assetIds });
|
||||
return album;
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Commit if changes were needed**
|
||||
|
||||
```bash
|
||||
git add src/handlers/api/album.handler.ts
|
||||
git commit -m "feat: add createAlbumWithAssets handler"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Manual testing and fixes
|
||||
|
||||
**Step 1: Run the dev server**
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
|
||||
**Step 2: Test each filter combination**
|
||||
|
||||
- Visit `/assets/orphan-finder`
|
||||
- Toggle each checkbox individually, verify results
|
||||
- Combine filters, verify AND behavior
|
||||
- Test asset type dropdown
|
||||
- Select assets, verify floating bar appears
|
||||
- Test "Add to Album" flow
|
||||
- Test Trash and Delete flows
|
||||
- Verify sidebar link works
|
||||
|
||||
**Step 3: Fix any issues found and commit**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: orphan finder polish and bug fixes"
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "sqlite",
|
||||
schema: "./src/db/schema/index.ts",
|
||||
out: "./src/db/migrations",
|
||||
dbCredentials: {
|
||||
url: process.env.APP_DB_PATH
|
||||
? `file:${process.env.APP_DB_PATH}`
|
||||
: "file:./data/app.db",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { defineConfig } from "eslint/config";
|
||||
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
|
||||
import remotion from "@remotion/eslint-plugin";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import js from "@eslint/js";
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
recommendedConfig: js.configs.recommended,
|
||||
allConfig: js.configs.all
|
||||
});
|
||||
|
||||
export default defineConfig([{
|
||||
extends: [...nextCoreWebVitals],
|
||||
|
||||
plugins: {
|
||||
"@remotion": remotion,
|
||||
},
|
||||
|
||||
rules: {
|
||||
"react-hooks/exhaustive-deps": "off",
|
||||
"@next/next/no-img-element": "off",
|
||||
},
|
||||
}, {
|
||||
files: ["remotion/*.{ts,tsx}"],
|
||||
extends: [...compat.extends("plugin:@remotion/recommended")],
|
||||
}]);
|
||||
+67
-57
@@ -3,10 +3,13 @@
|
||||
"version": "0.19.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build",
|
||||
"start": "next start -p ${PORT:=3000} -H ${HOST:=0.0.0.0}",
|
||||
"lint": "next lint"
|
||||
"lint": "eslint .",
|
||||
"db:generate": "drizzle-kit generate --config=drizzle.app.config.ts",
|
||||
"db:migrate": "drizzle-kit migrate --config=drizzle.app.config.ts",
|
||||
"db:studio": "drizzle-kit studio --config=drizzle.app.config.ts"
|
||||
},
|
||||
"author": {
|
||||
"name": "Varun Raj Manoharan",
|
||||
@@ -14,89 +17,96 @@
|
||||
"url": "https://varunraj.in"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/openai": "^3.0.29",
|
||||
"@ai-sdk/openai-compatible": "^2.0.30",
|
||||
"@ai-sdk/react": "^3.0.88",
|
||||
"@radix-ui/react-accordion": "^1.2.1",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.4",
|
||||
"@radix-ui/react-avatar": "^1.1.0",
|
||||
"@radix-ui/react-checkbox": "^1.1.2",
|
||||
"@ai-sdk/openai": "^3.0.50",
|
||||
"@ai-sdk/openai-compatible": "^2.0.38",
|
||||
"@ai-sdk/react": "^3.0.148",
|
||||
"@libsql/client": "^0.17.2",
|
||||
"@radix-ui/react-accordion": "^1.2.12",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-context-menu": "^2.2.16",
|
||||
"@radix-ui/react-dialog": "^1.1.1",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.1",
|
||||
"@radix-ui/react-hover-card": "^1.1.1",
|
||||
"@radix-ui/react-icons": "^1.3.0",
|
||||
"@radix-ui/react-label": "^2.1.0",
|
||||
"@radix-ui/react-popover": "^1.1.1",
|
||||
"@radix-ui/react-scroll-area": "^1.1.0",
|
||||
"@radix-ui/react-select": "^2.1.1",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-hover-card": "^1.1.15",
|
||||
"@radix-ui/react-icons": "^1.3.2",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.1.0",
|
||||
"@radix-ui/react-tabs": "^1.1.0",
|
||||
"@radix-ui/react-toast": "^1.2.1",
|
||||
"@radix-ui/react-tooltip": "^1.1.2",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@remotion/cli": "4.0.232",
|
||||
"@remotion/eslint-plugin": "^4.0.232",
|
||||
"@tanstack/react-query": "^5.69.0",
|
||||
"@remotion/eslint-plugin": "^4.0.446",
|
||||
"@tanstack/react-query": "^5.96.2",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/cookie": "^0.6.0",
|
||||
"@types/qs": "^6.9.15",
|
||||
"@types/qs": "^6.15.0",
|
||||
"@types/react-autosuggest": "^10.1.11",
|
||||
"@types/react-calendar-heatmap": "^1.6.7",
|
||||
"@types/react-calendar-heatmap": "^1.9.0",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"ai": "^6.0.86",
|
||||
"axios": "^1.7.4",
|
||||
"@xyflow/react": "^12.10.2",
|
||||
"ai": "^6.0.146",
|
||||
"axios": "^1.14.0",
|
||||
"chrono-node": "^1.4.9",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "1.0.0",
|
||||
"compatibility": "^1.0.1",
|
||||
"cookie": "^0.6.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"date-fns-tz": "^3.2.0",
|
||||
"drizzle-orm": "^0.33.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"leaflet": "^1.9.4",
|
||||
"leaflet-defaulticon-compatibility": "0.1.2",
|
||||
"leaflet.heat": "^0.2.0",
|
||||
"lucide-react": "^0.428.0",
|
||||
"next": "14.2.5",
|
||||
"next": "15.5.14",
|
||||
"next-themes": "^0.3.0",
|
||||
"pg": "^8.12.0",
|
||||
"qs": "^6.13.0",
|
||||
"react": "^18",
|
||||
"node-cron": "3.0.3",
|
||||
"pg": "^8.20.0",
|
||||
"qs": "^6.15.0",
|
||||
"react": "19.2.4",
|
||||
"react-autosuggest": "^10.1.0",
|
||||
"react-day-picker": "9.0.8",
|
||||
"react-dom": "^18",
|
||||
"react-grid-gallery": "^1.0.1",
|
||||
"react-hot-toast": "^2.5.1",
|
||||
"react-dom": "19.2.4",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-leaflet": "^4.2.1",
|
||||
"react-mentions": "^4.4.10",
|
||||
"react-photo-album": "^3.5.1",
|
||||
"react-window": "^1.8.11",
|
||||
"recharts": "^2.12.7",
|
||||
"recharts": "^2.15.4",
|
||||
"remotion": "4.0.232",
|
||||
"sass": "^1.77.8",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"sass": "^1.99.0",
|
||||
"tailwind-merge": "^2.6.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"yet-another-react-lightbox": "^3.21.4",
|
||||
"yet-another-react-lightbox": "^3.30.1",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tanstack/eslint-plugin-query": "^5.68.0",
|
||||
"@types/jsonwebtoken": "^9.0.6",
|
||||
"@types/leaflet": "^1.9.15",
|
||||
"@types/leaflet.heat": "^0.2.4",
|
||||
"@types/node": "^20",
|
||||
"@types/pg": "^8.11.6",
|
||||
"@types/react": "^18",
|
||||
"@types/react-dom": "^18",
|
||||
"@tanstack/eslint-plugin-query": "^5.96.2",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"@types/leaflet.heat": "^0.2.5",
|
||||
"@types/node": "^20.19.39",
|
||||
"@types/node-cron": "3.0.11",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@types/react-mentions": "^4.4.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"drizzle-kit": "^0.24.0",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "14.2.5",
|
||||
"postcss": "^8.4.41",
|
||||
"tailwindcss": "^3.4.10",
|
||||
"typescript": "^5"
|
||||
"autoprefixer": "^10.4.27",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-config-next": "15.5.14",
|
||||
"postcss": "^8.5.8",
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"overrides": {
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3"
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,16 @@ import 'leaflet.heat';
|
||||
import { getAssetGeoHeatmap, IHeatMapParams } from '@/handlers/api/asset.handler';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
// Fix for default markers in Leaflet
|
||||
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css';
|
||||
import 'leaflet-defaulticon-compatibility';
|
||||
// Fix default marker icons for bundlers that don't support ~ aliases
|
||||
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
|
||||
import markerIcon from 'leaflet/dist/images/marker-icon.png';
|
||||
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
|
||||
|
||||
L.Icon.Default.mergeOptions({
|
||||
iconUrl: markerIcon.src,
|
||||
iconRetinaUrl: markerIcon2x.src,
|
||||
shadowUrl: markerShadow.src,
|
||||
});
|
||||
|
||||
interface LeafletHeatMapProps {
|
||||
filters: IHeatMapParams;
|
||||
|
||||
@@ -26,14 +26,14 @@ export default function AlbumPhotosChart() {
|
||||
|
||||
return (
|
||||
<Card
|
||||
title="Album Distribution"
|
||||
description="Distribution of photos in and out of albums"
|
||||
title="Album Coverage"
|
||||
description="In albums vs unorganized"
|
||||
>
|
||||
<PieChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
<PieChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
errorMessage={errorMessage}
|
||||
/>
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -8,12 +8,23 @@ type HeatMapEntry = {
|
||||
count: number;
|
||||
};
|
||||
|
||||
const COLOR_SCALE = [
|
||||
"bg-zinc-100 dark:bg-zinc-800/60",
|
||||
"bg-emerald-200 dark:bg-emerald-900/70",
|
||||
"bg-emerald-300 dark:bg-emerald-800/80",
|
||||
"bg-emerald-400 dark:bg-emerald-700",
|
||||
"bg-emerald-500 dark:bg-emerald-600",
|
||||
"bg-emerald-600 dark:bg-emerald-500",
|
||||
];
|
||||
|
||||
const LEGEND_LABELS = ["None", "", "", "", "", "Max"];
|
||||
|
||||
export default function AssetHeatMap() {
|
||||
const { exImmichUrl } = useConfig();
|
||||
|
||||
const [heatMapData, setHeatMapData] = useState<HeatMapEntry[][]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [weeksPerMonth, setWeeksPerMonth] = useState<number[]>([]); // Store weeks per month
|
||||
const [weeksPerMonth, setWeeksPerMonth] = useState<number[]>([]);
|
||||
|
||||
const fetchHeatMapData = async () => {
|
||||
setLoading(true);
|
||||
@@ -32,38 +43,35 @@ export default function AssetHeatMap() {
|
||||
const currentDate = new Date();
|
||||
const months: string[] = [];
|
||||
|
||||
// Build an array of the last 12 months
|
||||
for (let i = 0; i < 12; i++) {
|
||||
months.push(currentDate.toLocaleString("default", { month: "short" }));
|
||||
currentDate.setMonth(currentDate.getMonth() - 1);
|
||||
}
|
||||
months.reverse();
|
||||
|
||||
// Flatten heatMapData to calculate min and max counts
|
||||
const flattenedData = heatMapData.flat();
|
||||
const minCount = Math.min(...flattenedData.map((entry) => entry.count));
|
||||
const maxCount = Math.max(...flattenedData.map((entry) => entry.count));
|
||||
|
||||
// Check if a week contains a date with the first day of the month
|
||||
const hasFirstDayOfMonth = (arr: HeatMapEntry[]) => {
|
||||
return arr.some((entry) => new Date(entry.date).getDate() === 1);
|
||||
};
|
||||
|
||||
const getColor = (count: number) => {
|
||||
if (count === -1) return "";
|
||||
if (count === 0) return COLOR_SCALE[0];
|
||||
|
||||
// Calculate thresholds based on the data range
|
||||
const range = maxCount - minCount;
|
||||
const threshold1 = minCount + range * 0.2;
|
||||
const threshold2 = minCount + range * 0.4;
|
||||
const threshold3 = minCount + range * 0.6;
|
||||
const threshold4 = minCount + range * 0.8;
|
||||
if (count === 0) return "bg-zinc-200 dark:bg-zinc-800";
|
||||
if (count <= threshold1) return "bg-green-200";
|
||||
if (count <= threshold2) return "bg-green-400";
|
||||
if (count <= threshold3) return "bg-green-500";
|
||||
if (count <= threshold4) return "bg-green-600";
|
||||
return "bg-green-800";
|
||||
|
||||
if (count <= threshold1) return COLOR_SCALE[1];
|
||||
if (count <= threshold2) return COLOR_SCALE[2];
|
||||
if (count <= threshold3) return COLOR_SCALE[3];
|
||||
if (count <= threshold4) return COLOR_SCALE[4];
|
||||
return COLOR_SCALE[5];
|
||||
};
|
||||
|
||||
const formatHeatMapData = (data: HeatMapEntry[]) => {
|
||||
@@ -86,60 +94,80 @@ export default function AssetHeatMap() {
|
||||
return chunks;
|
||||
};
|
||||
|
||||
const dayLabels = ["", "Mon", "", "Wed", "", "Fri", ""];
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="py-4 w-full">
|
||||
<h2 className="text-xl font-bold mb-4">Past Year</h2>
|
||||
{loading ? (
|
||||
<p>Loading...</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="table-auto border-separate border-spacing-1 w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
{weeksPerMonth.map((weeks, index) => (
|
||||
<th
|
||||
key={index}
|
||||
className="text-center"
|
||||
colSpan={weeks || 4}
|
||||
<div className="w-full">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="table-auto border-separate border-spacing-[3px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-8" />
|
||||
{weeksPerMonth.map((weeks, index) => (
|
||||
<th
|
||||
key={index}
|
||||
className="text-xs font-medium text-muted-foreground pb-1"
|
||||
colSpan={weeks || 4}
|
||||
>
|
||||
{months[index]}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{heatMapData[0]?.map((_, rowIndex) => (
|
||||
<tr key={rowIndex}>
|
||||
<td className="text-[10px] text-muted-foreground pr-2 text-right w-8 select-none">
|
||||
{dayLabels[rowIndex]}
|
||||
</td>
|
||||
{heatMapData.map((column, colIndex) => (
|
||||
<td
|
||||
key={colIndex}
|
||||
className={`h-[14px] w-[14px] ${getColor(column[rowIndex]?.count ?? -1)} rounded-sm transition-colors`}
|
||||
>
|
||||
{months[index]}
|
||||
</th>
|
||||
{column[rowIndex]?.date ? (
|
||||
<Tooltip
|
||||
delayDuration={0}
|
||||
content={`${column[rowIndex]?.count ?? 0} photos on ${column[rowIndex]?.date}`}
|
||||
>
|
||||
<a
|
||||
href={`${exImmichUrl}/search?query=%7B%22takenAfter%22%3A%22${column[rowIndex]?.date ?? "N/A"}T00%3A00%3A00.000Z%22%2C%22takenBefore%22%3A%22${column[rowIndex]?.date ?? "N/A"}T23%3A59%3A59.999Z%22%7D`}
|
||||
className="block h-[14px] w-[14px] rounded-sm hover:ring-2 hover:ring-foreground/20 transition-shadow"
|
||||
target="_blank"
|
||||
>
|
||||
<div className="h-[14px] w-[14px]" />
|
||||
</a>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<div className="h-[14px] w-[14px]" />
|
||||
)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{heatMapData[0]?.map((_, rowIndex) => (
|
||||
<tr key={rowIndex}>
|
||||
{heatMapData.map((column, colIndex) => (
|
||||
<td
|
||||
key={colIndex}
|
||||
className={`h-[20px] w-[20px] ${getColor(column[rowIndex]?.count ?? -1)} rounded`}
|
||||
// style={{ width: `calc(${100 / 60}%)` }}
|
||||
>
|
||||
{
|
||||
column[rowIndex]?.date ? (
|
||||
<Tooltip delayDuration={0} content={`Date: ${column[rowIndex]?.date ?? "N/A"} - Count: ${column[rowIndex]?.count ?? 0}`}>
|
||||
<a
|
||||
href={`${exImmichUrl}/search?query=%7B%22takenAfter%22%3A%22${column[rowIndex]?.date ?? "N/A"}T00%3A00%3A00.000Z%22%2C%22takenBefore%22%3A%22${column[rowIndex]?.date ?? "N/A"}T23%3A59%3A59.999Z%22%7D`}
|
||||
className="block h-[20px] max-w-[20px]"
|
||||
target="_blank"
|
||||
>
|
||||
<div
|
||||
className="h-[20px] max-w-[20px]"
|
||||
/>
|
||||
</a></Tooltip>) : <div
|
||||
className="h-[20px] max-w-[20px]"
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{/* Legend */}
|
||||
<div className="flex items-center justify-end gap-1.5 mt-3 text-[10px] text-muted-foreground select-none">
|
||||
<span>Less</span>
|
||||
{COLOR_SCALE.map((color, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`h-[12px] w-[12px] rounded-sm ${color}`}
|
||||
/>
|
||||
))}
|
||||
<span>More</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Card } from "@/components/ui/card";
|
||||
import PieChart, { IPieChartData } from "@/components/ui/pie-chart";
|
||||
import HorizontalBarChart from "@/components/ui/horizontal-bar-chart";
|
||||
import { IBarChartData } from "@/components/ui/horizontal-bar-chart";
|
||||
import { getExifDistribution, ISupportedEXIFColumns } from "@/handlers/api/analytics.handler";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { ValueType } from "recharts/types/component/DefaultTooltipContent";
|
||||
@@ -14,14 +15,20 @@ export interface IEXIFDistributionProps {
|
||||
export default function EXIFDistribution(
|
||||
{ column, title, description, tooltipValueFormatter }: IEXIFDistributionProps
|
||||
) {
|
||||
const [chartData, setChartData] = useState<IPieChartData[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [chartData, setChartData] = useState<IBarChartData[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
return getExifDistribution(column)
|
||||
.then(setChartData)
|
||||
.finally(() => setLoading(false));
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await getExifDistribution(column);
|
||||
setChartData(data);
|
||||
} catch (error: any) {
|
||||
setErrorMessage(error?.message || "Failed to load data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -29,11 +36,13 @@ export default function EXIFDistribution(
|
||||
}, [column]);
|
||||
|
||||
return (
|
||||
<Card
|
||||
title={title}
|
||||
description={description}
|
||||
>
|
||||
<PieChart data={chartData} loading={loading} errorMessage={errorMessage} tooltipValueFormatter={tooltipValueFormatter} />
|
||||
<Card title={title} description={description}>
|
||||
<HorizontalBarChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
errorMessage={errorMessage}
|
||||
tooltipValueFormatter={tooltipValueFormatter}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -27,13 +27,13 @@ export default function GeoPhotosChart() {
|
||||
return (
|
||||
<Card
|
||||
title="Geo Data"
|
||||
description="Distribution of photos with and without geo data"
|
||||
description="Photos with vs without location"
|
||||
>
|
||||
<PieChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
<PieChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
errorMessage={errorMessage}
|
||||
/>
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -27,13 +27,13 @@ export default function PeopleNamesChart() {
|
||||
return (
|
||||
<Card
|
||||
title="People Names"
|
||||
description="Distribution of people with and without names"
|
||||
description="Named vs unnamed people"
|
||||
>
|
||||
<PieChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
<PieChart
|
||||
data={chartData}
|
||||
loading={loading}
|
||||
errorMessage={errorMessage}
|
||||
/>
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { format } from 'date-fns'
|
||||
import { humanizeBytes } from '@/helpers/string.helper'
|
||||
import { useConfig } from '@/contexts/ConfigContext'
|
||||
import {
|
||||
Calendar,
|
||||
Image as ImageIcon,
|
||||
Camera,
|
||||
Aperture,
|
||||
MapPin,
|
||||
EyeOff,
|
||||
ExternalLink,
|
||||
Check,
|
||||
} from 'lucide-react'
|
||||
import API from '@/lib/api'
|
||||
import { PERSON_THUBNAIL_PATH } from '@/config/routes'
|
||||
import { updatePerson } from '@/handlers/api/people.handler'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import L from 'leaflet'
|
||||
import 'leaflet/dist/leaflet.css'
|
||||
|
||||
// Fix default marker icons for bundlers that don't support ~ aliases
|
||||
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png'
|
||||
import markerIcon from 'leaflet/dist/images/marker-icon.png'
|
||||
import markerShadow from 'leaflet/dist/images/marker-shadow.png'
|
||||
|
||||
L.Icon.Default.mergeOptions({
|
||||
iconUrl: markerIcon.src,
|
||||
iconRetinaUrl: markerIcon2x.src,
|
||||
shadowUrl: markerShadow.src,
|
||||
})
|
||||
|
||||
export interface IAssetDetail {
|
||||
id: string
|
||||
type: string
|
||||
originalPath: string
|
||||
originalFileName: string
|
||||
isFavorite: boolean
|
||||
duration: string | null
|
||||
localDateTime: string | Date
|
||||
fileCreatedAt: string | Date
|
||||
make: string | null
|
||||
model: string | null
|
||||
lensModel: string | null
|
||||
fNumber: number | null
|
||||
focalLength: number | null
|
||||
iso: number | null
|
||||
exposureTime: string | null
|
||||
fileSizeInByte: number | null
|
||||
exifImageWidth: number | null
|
||||
exifImageHeight: number | null
|
||||
orientation: string | null
|
||||
dateTimeOriginal: string | Date | null
|
||||
timeZone: string | null
|
||||
latitude: number | null
|
||||
longitude: number | null
|
||||
city: string | null
|
||||
state: string | null
|
||||
country: string | null
|
||||
description: string | null
|
||||
rating: number | null
|
||||
fps: number | null
|
||||
projectionType: string | null
|
||||
people: { personId: string; personName: string; thumbnailPath: string; isHidden: boolean }[]
|
||||
}
|
||||
|
||||
interface AssetInfoPanelProps {
|
||||
assetId: string
|
||||
}
|
||||
|
||||
function getMegapixels(width: number, height: number): string {
|
||||
const mp = (width * height) / 1_000_000
|
||||
return mp >= 1 ? `${mp.toFixed(1)} MP` : `${(mp * 1000).toFixed(0)} KP`
|
||||
}
|
||||
|
||||
function formatExposureTime(exposure: string): string {
|
||||
const val = parseFloat(exposure)
|
||||
if (isNaN(val)) return exposure
|
||||
if (val >= 1) return `${val} s`
|
||||
return `1/${Math.round(1 / val)} s`
|
||||
}
|
||||
|
||||
interface PersonChipProps {
|
||||
person: { personId: string; personName: string; thumbnailPath: string }
|
||||
exImmichUrl: string
|
||||
isHidden: boolean
|
||||
onUpdate: (updated: { personId: string; personName?: string; hidden?: boolean }) => void
|
||||
}
|
||||
|
||||
function PersonChip({ person: p, exImmichUrl, isHidden: hidden, onUpdate }: PersonChipProps) {
|
||||
const [name, setName] = useState(p.personName)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const handleRename = async () => {
|
||||
if (name === p.personName) { setOpen(false); return }
|
||||
setSaving(true)
|
||||
try {
|
||||
await updatePerson(p.personId, { name })
|
||||
onUpdate({ personId: p.personId, personName: name })
|
||||
toast({ title: "Updated", description: `Renamed to "${name}"` })
|
||||
setOpen(false)
|
||||
} catch {
|
||||
toast({ title: "Error", description: "Failed to rename", variant: "destructive" })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleHide = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
await updatePerson(p.personId, { isHidden: true })
|
||||
onUpdate({ personId: p.personId, hidden: true })
|
||||
toast({ title: "Hidden", description: `"${p.personName || 'Unknown'}" hidden` })
|
||||
setOpen(false)
|
||||
} catch {
|
||||
toast({ title: "Error", description: "Failed to hide person", variant: "destructive" })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
className="flex items-center gap-2 px-2 py-1 rounded-full bg-muted hover:bg-muted/80 transition-colors"
|
||||
>
|
||||
<div className="relative h-6 w-6 shrink-0">
|
||||
<img
|
||||
src={PERSON_THUBNAIL_PATH(p.personId)}
|
||||
alt={p.personName}
|
||||
className={`h-6 w-6 rounded-full object-cover ${hidden ? 'opacity-40' : ''}`}
|
||||
/>
|
||||
{hidden && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<EyeOff className="h-3.5 w-3.5 text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span className={`text-xs font-medium ${hidden ? 'line-through text-muted-foreground' : ''}`}>{p.personName || 'Unknown'}</span>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56 p-3 z-[10000]" side="bottom" align="start">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<img
|
||||
src={PERSON_THUBNAIL_PATH(p.personId)}
|
||||
alt={p.personName}
|
||||
className="h-16 w-16 rounded-full object-cover"
|
||||
/>
|
||||
<span className="text-sm font-medium truncate">{p.personName || 'Unknown'}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Name"
|
||||
className="h-8 text-sm"
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleRename() }}
|
||||
/>
|
||||
<Button size="sm" variant="ghost" className="h-8 w-8 p-0 shrink-0" onClick={handleRename} disabled={saving}>
|
||||
<Check className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<button
|
||||
onClick={handleHide}
|
||||
disabled={saving}
|
||||
className="flex items-center gap-2 px-2 py-1.5 text-sm rounded hover:bg-muted transition-colors w-full text-left"
|
||||
>
|
||||
<EyeOff className="h-4 w-4" /> Hide person
|
||||
</button>
|
||||
<a
|
||||
href={exImmichUrl + '/people/' + p.personId}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 px-2 py-1.5 text-sm rounded hover:bg-muted transition-colors w-full"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" /> Open in Immich
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
function MiniMap({ latitude, longitude }: { latitude: number; longitude: number }) {
|
||||
const mapContainerRef = useRef<HTMLDivElement>(null)
|
||||
const mapRef = useRef<L.Map | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!mapContainerRef.current) return
|
||||
|
||||
// Check if dark mode
|
||||
const isDark = document.documentElement.classList.contains('dark')
|
||||
|
||||
const map = L.map(mapContainerRef.current, {
|
||||
center: [latitude, longitude],
|
||||
zoom: 14,
|
||||
zoomControl: true,
|
||||
scrollWheelZoom: false,
|
||||
dragging: true,
|
||||
doubleClickZoom: true,
|
||||
attributionControl: false,
|
||||
})
|
||||
|
||||
mapRef.current = map
|
||||
|
||||
const tileLayer = isDark
|
||||
? L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
|
||||
subdomains: 'abcd',
|
||||
maxZoom: 20,
|
||||
})
|
||||
: L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
maxZoom: 20,
|
||||
})
|
||||
|
||||
tileLayer.addTo(map)
|
||||
L.marker([latitude, longitude]).addTo(map)
|
||||
|
||||
// Force resize after render
|
||||
setTimeout(() => map.invalidateSize(), 100)
|
||||
|
||||
return () => {
|
||||
map.remove()
|
||||
mapRef.current = null
|
||||
}
|
||||
}, [latitude, longitude])
|
||||
|
||||
return (
|
||||
<div className="rounded-lg overflow-hidden border h-[160px]">
|
||||
<div ref={mapContainerRef} className="h-full w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AssetInfoPanel({ assetId }: AssetInfoPanelProps) {
|
||||
const [detail, setDetail] = useState<IAssetDetail | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [hiddenIds, setHiddenIds] = useState<Set<string>>(new Set())
|
||||
const { exImmichUrl } = useConfig()
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true)
|
||||
setHiddenIds(new Set())
|
||||
API.get(`/api/assets/${assetId}/detail`)
|
||||
.then((data) => {
|
||||
setDetail(data)
|
||||
if (data?.people) {
|
||||
setHiddenIds(new Set(data.people.filter((p: any) => p.isHidden).map((p: any) => p.personId)))
|
||||
}
|
||||
})
|
||||
.catch(() => setDetail(null))
|
||||
.finally(() => setLoading(false))
|
||||
}, [assetId])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="w-[360px] min-w-[360px] bg-background border-l overflow-y-auto p-4">
|
||||
<h2 className="text-lg font-semibold mb-4">Info</h2>
|
||||
<div className="animate-pulse space-y-4">
|
||||
<div className="h-4 bg-muted rounded w-3/4" />
|
||||
<div className="h-4 bg-muted rounded w-1/2" />
|
||||
<div className="h-4 bg-muted rounded w-2/3" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!detail) {
|
||||
return (
|
||||
<div className="w-[360px] min-w-[360px] bg-background border-l overflow-y-auto p-4">
|
||||
<h2 className="text-lg font-semibold mb-4">Info</h2>
|
||||
<p className="text-sm text-muted-foreground">Unable to load asset details.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const dateStr = detail.dateTimeOriginal || detail.localDateTime
|
||||
const date = dateStr ? new Date(dateStr) : null
|
||||
|
||||
const hasLocation = detail.latitude && detail.longitude
|
||||
const locationParts = [detail.city, detail.state, detail.country].filter(Boolean)
|
||||
|
||||
const resolution = detail.exifImageWidth && detail.exifImageHeight
|
||||
? `${detail.exifImageWidth} x ${detail.exifImageHeight}`
|
||||
: null
|
||||
const megapixels = detail.exifImageWidth && detail.exifImageHeight
|
||||
? getMegapixels(detail.exifImageWidth, detail.exifImageHeight)
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="w-[360px] min-w-[360px] bg-background border-l overflow-y-auto">
|
||||
{/* Header */}
|
||||
<div className="p-4 pb-2">
|
||||
<h2 className="text-lg font-semibold">Info</h2>
|
||||
</div>
|
||||
|
||||
<div className="px-4 pb-4 space-y-4">
|
||||
{/* Description */}
|
||||
{detail.description && (
|
||||
<p className="text-sm text-muted-foreground">{detail.description}</p>
|
||||
)}
|
||||
|
||||
{/* People */}
|
||||
{detail.people && detail.people.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">People</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
{detail.people.some((p) => !p.personName && !hiddenIds.has(p.personId)) && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
const unnamed = detail.people.filter((p) => !p.personName && !hiddenIds.has(p.personId))
|
||||
try {
|
||||
await Promise.all(unnamed.map((p) => updatePerson(p.personId, { isHidden: true })))
|
||||
setHiddenIds((prev) => { const next = new Set(prev); unnamed.forEach((p) => next.add(p.personId)); return next })
|
||||
toast({ title: "Hidden", description: `Hidden ${unnamed.length} unnamed people` })
|
||||
} catch {
|
||||
toast({ title: "Error", description: "Failed to hide people", variant: "destructive" })
|
||||
}
|
||||
}}
|
||||
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
|
||||
title="Hide unnamed people"
|
||||
>
|
||||
<EyeOff className="h-3.5 w-3.5" />
|
||||
Hide unnamed
|
||||
</button>
|
||||
)}
|
||||
{detail.people.some((p) => !hiddenIds.has(p.personId)) && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
const unhidden = detail.people.filter((p) => !hiddenIds.has(p.personId))
|
||||
try {
|
||||
await Promise.all(unhidden.map((p) => updatePerson(p.personId, { isHidden: true })))
|
||||
setHiddenIds((prev) => { const next = new Set(prev); unhidden.forEach((p) => next.add(p.personId)); return next })
|
||||
toast({ title: "Hidden", description: `Hidden ${unhidden.length} people` })
|
||||
} catch {
|
||||
toast({ title: "Error", description: "Failed to hide people", variant: "destructive" })
|
||||
}
|
||||
}}
|
||||
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
|
||||
title="Hide all people"
|
||||
>
|
||||
<EyeOff className="h-3.5 w-3.5" />
|
||||
Hide all
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{detail.people.map((p) => (
|
||||
<PersonChip key={p.personId} person={p} exImmichUrl={exImmichUrl} isHidden={hiddenIds.has(p.personId)} onUpdate={(updated) => {
|
||||
if (updated.hidden) {
|
||||
setHiddenIds((prev) => new Set(prev).add(updated.personId))
|
||||
}
|
||||
if (updated.personName !== undefined) {
|
||||
setDetail((prev) => {
|
||||
if (!prev) return prev
|
||||
return { ...prev, people: prev.people.map((pp) => pp.personId === updated.personId ? { ...pp, personName: updated.personName! } : pp) }
|
||||
})
|
||||
}
|
||||
}} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<hr className="border-border" />
|
||||
|
||||
{/* Details */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-muted-foreground mb-3">Details</h3>
|
||||
<div className="space-y-3">
|
||||
{/* Date */}
|
||||
{date && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Calendar className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{format(date, 'd MMM yyyy')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{format(date, 'EEE, HH:mm:ss')}
|
||||
{detail.timeZone ? ` ${detail.timeZone}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File info */}
|
||||
<div className="flex items-start gap-3">
|
||||
<ImageIcon className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">{detail.originalFileName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{[
|
||||
megapixels,
|
||||
resolution,
|
||||
detail.fileSizeInByte ? humanizeBytes(detail.fileSizeInByte) : null,
|
||||
].filter(Boolean).join(' ')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Camera */}
|
||||
{(detail.make || detail.model) && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Camera className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{[detail.make, detail.model].filter(Boolean).join(' ')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{[
|
||||
detail.exposureTime ? formatExposureTime(detail.exposureTime) : null,
|
||||
detail.iso ? `ISO ${detail.iso}` : null,
|
||||
].filter(Boolean).join(' ')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lens */}
|
||||
{detail.lensModel && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Aperture className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<p className="text-sm font-medium truncate max-w-[280px]">{detail.lensModel}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{[
|
||||
detail.fNumber ? `f/${detail.fNumber}` : null,
|
||||
detail.focalLength ? `${detail.focalLength} mm` : null,
|
||||
].filter(Boolean).join(' ')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Location */}
|
||||
{(locationParts.length > 0 || hasLocation) && (
|
||||
<div className="flex items-start gap-3">
|
||||
<MapPin className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div>
|
||||
{locationParts.length > 0 ? (
|
||||
locationParts.map((part, i) => (
|
||||
<p key={i} className={i === 0 ? 'text-sm font-medium' : 'text-xs text-muted-foreground'}>
|
||||
{part}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{detail.latitude?.toFixed(6)}, {detail.longitude?.toFixed(6)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Map */}
|
||||
{hasLocation && (
|
||||
<MiniMap latitude={detail.latitude!} longitude={detail.longitude!} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,8 +4,16 @@
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import L, { LatLngExpression } from 'leaflet';
|
||||
|
||||
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css'; // Re-uses images from ~leaflet package
|
||||
import 'leaflet-defaulticon-compatibility';
|
||||
// Fix default marker icons for bundlers that don't support ~ aliases
|
||||
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
|
||||
import markerIcon from 'leaflet/dist/images/marker-icon.png';
|
||||
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
|
||||
|
||||
L.Icon.Default.mergeOptions({
|
||||
iconUrl: markerIcon.src,
|
||||
iconRetinaUrl: markerIcon2x.src,
|
||||
shadowUrl: markerShadow.src,
|
||||
});
|
||||
|
||||
import { MapContainer, TileLayer, useMapEvents } from "react-leaflet";
|
||||
import { useState } from "react";
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ export default function TagMissingLocationOSMSearchAndAdd(
|
||||
) {
|
||||
const { toast } = useToast();
|
||||
const [searchedPlaces, setSearchedPlaces] = useState<IPlace[] | null>(null);
|
||||
const searchTimer = useRef<NodeJS.Timeout>();
|
||||
const searchTimer = useRef<NodeJS.Timeout>(undefined);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [selectedPlace, setSelectedPlace] = useState<IPlace | null>(null);
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ export default function TagMissingLocationSearchAndAdd(
|
||||
) {
|
||||
const { toast } = useToast();
|
||||
const [searchedPlaces, setSearchedPlaces] = useState<IPlace[] | null>(null);
|
||||
const searchTimer = useRef<NodeJS.Timeout>();
|
||||
const searchTimer = useRef<NodeJS.Timeout>(undefined);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [selectedPlace, setSelectedPlace] = useState<IPlace | null>(null);
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import React from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ExternalLink, Loader2 } from "lucide-react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { getImportJob } from "@/handlers/api/import-jobs.handler";
|
||||
import { useConfig } from "@/contexts/ConfigContext";
|
||||
|
||||
const InfoRow = ({ label, value }: { label: string; value: React.ReactNode }) => (
|
||||
<div className="flex flex-col gap-1 rounded-md border border-border bg-muted/30 p-3">
|
||||
<p className="text-xs uppercase tracking-wide text-muted-foreground">{label}</p>
|
||||
<p className="text-sm font-medium text-foreground break-words">{value ?? "—"}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
const statusBadge = (status: string) => {
|
||||
const styles =
|
||||
status === "uploaded" || status === "completed"
|
||||
? "bg-emerald-500/10 text-emerald-600"
|
||||
: status === "skipped"
|
||||
? "bg-amber-500/10 text-amber-600"
|
||||
: status === "failed"
|
||||
? "bg-destructive/10 text-destructive"
|
||||
: "bg-muted text-muted-foreground";
|
||||
|
||||
return (
|
||||
<span className={`text-xs px-1.5 py-0.5 rounded ${styles}`}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
interface ImportJobDetailDialogProps {
|
||||
jobId: string | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function ImportJobDetailDialog({ jobId, onClose }: ImportJobDetailDialogProps) {
|
||||
const { exImmichUrl } = useConfig();
|
||||
|
||||
const { data: detailJob, isLoading } = useQuery({
|
||||
queryKey: ["import-job-detail", jobId],
|
||||
queryFn: () => getImportJob(jobId!),
|
||||
enabled: !!jobId,
|
||||
});
|
||||
|
||||
let dImportData: Record<string, unknown> = {};
|
||||
let dAlbumOpts: { createAlbum?: boolean; albumName?: string; addToAlbumId?: string } | undefined;
|
||||
let dError: string | null = null;
|
||||
let albumId: string | undefined;
|
||||
|
||||
if (detailJob) {
|
||||
try {
|
||||
dImportData = JSON.parse(detailJob.job.importData);
|
||||
} catch { /* ignore */ }
|
||||
dAlbumOpts = dImportData.albumOptions as typeof dAlbumOpts;
|
||||
dError = typeof dImportData.error === "string" ? dImportData.error : null;
|
||||
albumId = typeof dImportData.albumId === "string" ? dImportData.albumId : undefined;
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={!!jobId} onOpenChange={(open) => { if (!open) onClose(); }}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{detailJob && (() => {
|
||||
const dJob = detailJob.job;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dAlbumOpts?.albumName || "Import details"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<InfoRow label="Status" value={statusBadge(dJob.status)} />
|
||||
<InfoRow label="Platform" value={dJob.platform} />
|
||||
<InfoRow label="Total" value={dJob.totalCount} />
|
||||
<InfoRow label="Uploaded" value={dJob.uploadedCount} />
|
||||
<InfoRow label="Skipped" value={dJob.skippedCount} />
|
||||
<InfoRow label="Failed" value={dJob.failedCount} />
|
||||
{albumId && (
|
||||
<InfoRow label="Album" value={
|
||||
<a
|
||||
href={`${exImmichUrl}/albums/${albumId}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary hover:underline"
|
||||
>
|
||||
{dAlbumOpts?.albumName || albumId}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
} />
|
||||
)}
|
||||
{!albumId && dAlbumOpts?.albumName && (
|
||||
<InfoRow label="Album" value={dAlbumOpts.albumName} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{dError && (
|
||||
<div className="rounded-md border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive">
|
||||
{dError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-auto min-h-0 mt-2">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-background">
|
||||
<tr className="border-b text-left text-xs text-muted-foreground">
|
||||
<th className="pb-2 font-medium">Asset</th>
|
||||
<th className="pb-2 font-medium">Status</th>
|
||||
<th className="pb-2 font-medium">Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{detailJob.items.map((item) => {
|
||||
let itemData: Record<string, unknown> = {};
|
||||
try { itemData = JSON.parse(item.itemData ?? "{}"); } catch { /* ignore */ }
|
||||
const fileName = (itemData.originalFileName as string) || item.assetId;
|
||||
|
||||
return (
|
||||
<tr key={item.id}>
|
||||
<td className="py-2 pr-2 max-w-[200px] truncate" title={fileName}>
|
||||
{item.immichId ? (
|
||||
<a
|
||||
href={`${exImmichUrl}/photos/${item.immichId}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary hover:underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{fileName}
|
||||
<ExternalLink className="h-3 w-3 shrink-0" />
|
||||
</a>
|
||||
) : (
|
||||
fileName
|
||||
)}
|
||||
</td>
|
||||
<td className="py-2 pr-2">
|
||||
{statusBadge(item.status)}
|
||||
</td>
|
||||
<td className="py-2 text-xs text-muted-foreground max-w-[200px] truncate" title={item.error || ""}>
|
||||
{item.error || "—"}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -54,7 +54,7 @@ export function PersonMergeDropdown({
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [similarLoading, setSimilarLoading] = useState(true);
|
||||
const searchTimer = useRef<NodeJS.Timeout>();
|
||||
const searchTimer = useRef<NodeJS.Timeout>(undefined);
|
||||
const [selectedPeople, setSelectedPeople] = useState<IPerson[]>([]);
|
||||
const [primaryPerson, setPrimaryPerson] = useState<IPerson>(person);
|
||||
const [merging, setMerging] = useState(false);
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
import "yet-another-react-lightbox/styles.css";
|
||||
import "react-photo-album/rows.css";
|
||||
|
||||
import { IAsset } from '@/types/asset';
|
||||
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from 'react'
|
||||
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState, useCallback } from 'react'
|
||||
import Lightbox from 'yet-another-react-lightbox';
|
||||
import { Gallery } from "react-grid-gallery";
|
||||
import { RowsPhotoAlbum } from "react-photo-album";
|
||||
import type { Photo, RenderImageContext, RenderImageProps } from "react-photo-album";
|
||||
import LazyGridImage from "../ui/lazy-grid-image";
|
||||
import Download from "yet-another-react-lightbox/plugins/download";
|
||||
import Video from "yet-another-react-lightbox/plugins/video";
|
||||
import { usePhotoSelectionContext } from '@/contexts/PhotoSelectionContext';
|
||||
import { useConfig } from '@/contexts/ConfigContext';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { Heart, Info, Trash2, ExternalLink } from 'lucide-react';
|
||||
import { updateAssets } from '@/handlers/api/asset.handler';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
|
||||
const AssetInfoPanel = dynamic(() => import('@/components/asset-info/AssetInfoPanel'), { ssr: false });
|
||||
|
||||
export interface AssetPhoto extends Photo {
|
||||
id: string;
|
||||
isVideo: boolean;
|
||||
duration?: string;
|
||||
isSelected: boolean;
|
||||
}
|
||||
|
||||
interface AssetGridProps {
|
||||
assets: IAsset[];
|
||||
isInternal?: boolean;
|
||||
selectable?: boolean;
|
||||
onSelectionChange?: (ids: string[]) => void;
|
||||
onDeleteAsset?: (id: string) => void;
|
||||
onFavoriteAsset?: (id: string, isFavorite: boolean) => void;
|
||||
}
|
||||
|
||||
interface AssetGridRef {
|
||||
@@ -24,13 +40,59 @@ interface AssetGridRef {
|
||||
unselectAll: () => void;
|
||||
}
|
||||
|
||||
const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal = true, selectable = false, onSelectionChange }, ref) => {
|
||||
const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal = true, selectable = false, onSelectionChange, onDeleteAsset, onFavoriteAsset }, ref) => {
|
||||
const [index, setIndex] = useState(-1);
|
||||
const [lastSelectedIndex, setLastSelectedIndex] = useState(-1);
|
||||
const [showInfoPanel, setShowInfoPanel] = useState(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
return localStorage.getItem('assetInfoPanelOpen') === 'true'
|
||||
}
|
||||
return false
|
||||
});
|
||||
const [favoriteIds, setFavoriteIds] = useState<Set<string>>(() => new Set(assets.filter(a => a.isFavorite).map(a => a.id)));
|
||||
const { exImmichUrl } = useConfig();
|
||||
// Use context for selection state
|
||||
const { selectedIds, updateContext } = usePhotoSelectionContext();
|
||||
|
||||
// Sync favoriteIds when assets change
|
||||
useEffect(() => {
|
||||
setFavoriteIds(new Set(assets.filter(a => a.isFavorite).map(a => a.id)));
|
||||
}, [assets]);
|
||||
|
||||
const handleToggleFavorite = useCallback(async (assetId: string) => {
|
||||
const isFav = favoriteIds.has(assetId);
|
||||
const newFav = !isFav;
|
||||
// Optimistic update
|
||||
setFavoriteIds(prev => {
|
||||
const next = new Set(prev);
|
||||
newFav ? next.add(assetId) : next.delete(assetId);
|
||||
return next;
|
||||
});
|
||||
try {
|
||||
await updateAssets({ ids: [assetId], isFavorite: newFav });
|
||||
toast({ title: newFav ? "Added to favorites" : "Removed from favorites" });
|
||||
onFavoriteAsset?.(assetId, newFav);
|
||||
} catch {
|
||||
// Revert on failure
|
||||
setFavoriteIds(prev => {
|
||||
const next = new Set(prev);
|
||||
isFav ? next.add(assetId) : next.delete(assetId);
|
||||
return next;
|
||||
});
|
||||
toast({ title: "Error", description: "Failed to update favorite", variant: "destructive" });
|
||||
}
|
||||
}, [favoriteIds, onFavoriteAsset]);
|
||||
|
||||
const toggleInfoPanel = useCallback(() => {
|
||||
setShowInfoPanel((v) => {
|
||||
const next = !v
|
||||
localStorage.setItem('assetInfoPanelOpen', String(next))
|
||||
return next
|
||||
})
|
||||
}, []);
|
||||
|
||||
const currentAsset = index >= 0 && index < assets.length ? assets[index] : null;
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
getSelectedIds: () => selectedIds,
|
||||
selectAll: () => {
|
||||
@@ -45,7 +107,7 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
|
||||
}), [assets, selectedIds, updateContext]);
|
||||
|
||||
|
||||
const handleClick = (index: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
|
||||
const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => {
|
||||
if (selectedIds.length > 0) {
|
||||
handleSelect(index, asset, event);
|
||||
} else {
|
||||
@@ -53,7 +115,7 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelect = (_idx: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
|
||||
const handleSelect = (_idx: number, asset: AssetPhoto, event: React.MouseEvent) => {
|
||||
|
||||
event.stopPropagation();
|
||||
const isPresent = selectedIds.includes(asset.id);
|
||||
@@ -103,26 +165,17 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
|
||||
}));
|
||||
}, [assets]);
|
||||
|
||||
const images = useMemo(() => {
|
||||
const images: AssetPhoto[] = useMemo(() => {
|
||||
return assets.map((p) => ({
|
||||
...p,
|
||||
src: p.url as string,
|
||||
original: p.previewUrl as string,
|
||||
width: p.exifImageWidth / 10 as number,
|
||||
height: p.exifImageHeight / 10 as number,
|
||||
width: p.exifImageWidth as number,
|
||||
height: p.exifImageHeight as number,
|
||||
orientation: 1,
|
||||
isSelected: selectedIds.includes(p.id),
|
||||
isVideo: p.type === "VIDEO",
|
||||
tags: [
|
||||
{
|
||||
title: "Immich Link",
|
||||
value: (
|
||||
<a href={exImmichUrl + "/photos/" + p.id} target="_blank" rel="noopener noreferrer">
|
||||
Open in Immich
|
||||
</a>
|
||||
),
|
||||
},
|
||||
],
|
||||
duration: p.duration != null ? String(p.duration) : undefined,
|
||||
}));
|
||||
}, [assets, selectedIds, exImmichUrl]);
|
||||
|
||||
@@ -139,6 +192,73 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
|
||||
return () => window.removeEventListener("keydown", handleEsc);
|
||||
}, [images]);
|
||||
|
||||
const renderImage = (props: RenderImageProps, context: RenderImageContext<AssetPhoto>) => {
|
||||
return (
|
||||
<LazyGridImage
|
||||
imageProps={props}
|
||||
photo={context.photo}
|
||||
width={context.width}
|
||||
height={context.height}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const handleOpenInImmich = useCallback(() => {
|
||||
if (currentAsset) {
|
||||
window.open(exImmichUrl + "/photos/" + currentAsset.id, "_blank");
|
||||
}
|
||||
}, [currentAsset, exImmichUrl]);
|
||||
|
||||
const toolbarButtons = useMemo(() => {
|
||||
if (!currentAsset) return [];
|
||||
const isFav = favoriteIds.has(currentAsset.id);
|
||||
return [
|
||||
<button
|
||||
key="favorite"
|
||||
type="button"
|
||||
className="yarl__button"
|
||||
title={isFav ? "Unfavorite" : "Favorite"}
|
||||
onClick={() => handleToggleFavorite(currentAsset.id)}
|
||||
>
|
||||
<Heart
|
||||
className={`h-6 w-6 ${isFav ? 'fill-red-500 text-red-500' : 'text-white'}`}
|
||||
/>
|
||||
</button>,
|
||||
<button
|
||||
key="info"
|
||||
type="button"
|
||||
className="yarl__button"
|
||||
title="Info"
|
||||
onClick={toggleInfoPanel}
|
||||
>
|
||||
<Info className={`h-6 w-6 ${showInfoPanel ? 'text-blue-400' : 'text-white'}`} />
|
||||
</button>,
|
||||
<button
|
||||
key="open-immich"
|
||||
type="button"
|
||||
className="yarl__button"
|
||||
title="Open in Immich"
|
||||
onClick={handleOpenInImmich}
|
||||
>
|
||||
<ExternalLink className="h-6 w-6 text-white" />
|
||||
</button>,
|
||||
...(onDeleteAsset ? [
|
||||
<button
|
||||
key="delete"
|
||||
type="button"
|
||||
className="yarl__button"
|
||||
title="Delete"
|
||||
onClick={() => {
|
||||
onDeleteAsset(currentAsset.id);
|
||||
setIndex(-1);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-6 w-6 text-white" />
|
||||
</button>,
|
||||
] : []),
|
||||
];
|
||||
}, [currentAsset, showInfoPanel, onDeleteAsset, onFavoriteAsset, handleOpenInImmich, favoriteIds, handleToggleFavorite]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Lightbox
|
||||
@@ -146,14 +266,58 @@ const AssetGrid = forwardRef<AssetGridRef, AssetGridProps>(({ assets, isInternal
|
||||
plugins={[Download, Video]}
|
||||
open={index >= 0}
|
||||
index={index}
|
||||
close={() => setIndex(-1)}
|
||||
close={() => { setIndex(-1); }}
|
||||
on={{
|
||||
view: ({ index }) => setIndex(index),
|
||||
}}
|
||||
toolbar={{
|
||||
buttons: [
|
||||
...toolbarButtons,
|
||||
"download",
|
||||
"close",
|
||||
],
|
||||
}}
|
||||
render={{
|
||||
slideContainer: ({ children }) => (
|
||||
<div className="flex h-full w-full">
|
||||
<div className="flex-1 flex items-center justify-center overflow-hidden">
|
||||
{children}
|
||||
</div>
|
||||
{showInfoPanel && currentAsset && (
|
||||
<AssetInfoPanel
|
||||
assetId={currentAsset.id}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
styles={{
|
||||
container: {
|
||||
backgroundColor: "rgba(0, 0, 0, 0.95)",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Gallery
|
||||
images={images}
|
||||
onClick={handleClick}
|
||||
enableImageSelection={selectable}
|
||||
thumbnailImageComponent={LazyGridImage}
|
||||
onSelect={handleSelect}
|
||||
<RowsPhotoAlbum
|
||||
photos={images}
|
||||
targetRowHeight={150}
|
||||
rowConstraints={{ singleRowMaxHeight: 300 }}
|
||||
spacing={2}
|
||||
padding={0}
|
||||
onClick={({ index, event, photo }) => handleClick(index, photo, event)}
|
||||
render={{
|
||||
image: renderImage,
|
||||
extras: (_, { photo }) => (
|
||||
<a
|
||||
href={exImmichUrl + "/photos/" + photo.id}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="absolute bottom-1 left-1 bg-black/60 p-1 rounded"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5 text-white" />
|
||||
</a>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,70 +1,114 @@
|
||||
import React from "react";
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Link from "next/link";
|
||||
import { useConfig } from "@/contexts/ConfigContext";
|
||||
import { logoutUser } from "@/handlers/api/user.handler"
|
||||
import { logoutUser } from "@/handlers/api/user.handler";
|
||||
import { useCurrentUser } from "@/contexts/CurrentUserContext";
|
||||
import { useToast } from "../ui/use-toast";
|
||||
import { HandshakeIcon } from "lucide-react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { Tooltip } from "@/components/ui/tooltip";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { HandshakeIcon, Server, Globe, LogOut, Moon, Sun, User, Settings } from "lucide-react";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
export default function ProfileInfo() {
|
||||
const { updateContext, ...user } = useCurrentUser()
|
||||
const { updateContext, ...user } = useCurrentUser();
|
||||
const { immichURL, exImmichUrl, version } = useConfig();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const toast = useToast();
|
||||
const router = useRouter();
|
||||
|
||||
const handleLogout = () => logoutUser()
|
||||
.then(() => {
|
||||
updateContext(null)
|
||||
}).catch((error) => {
|
||||
toast.toast({
|
||||
title: "Error",
|
||||
description: error.message,
|
||||
})
|
||||
})
|
||||
|
||||
const handleLogout = () =>
|
||||
logoutUser()
|
||||
.then(() => updateContext(null))
|
||||
.catch((error) => {
|
||||
toast.toast({ title: "Error", description: error.message });
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-2 text-xs text-center py-2">
|
||||
<p className="text-muted-foreground font-mono">Connected to (External)</p>
|
||||
<Link href={exImmichUrl} target="_blank" className="font-mono">
|
||||
{exImmichUrl}
|
||||
</Link>
|
||||
<p className="text-muted-foreground font-mono">Connected to (Internal)</p>
|
||||
<Link href={immichURL} target="_blank" className="font-mono">
|
||||
{immichURL}
|
||||
</Link>
|
||||
{user && (
|
||||
<>
|
||||
<p className="text-sm">{user?.name}</p>
|
||||
<div className="flex items-center justify-between gap-2 px-2">
|
||||
{!user.isUsingAPIKey && (
|
||||
<Button variant="destructive" className="h-6 flex-1 text-xs" onClick={handleLogout}>
|
||||
Log Out
|
||||
</Button>
|
||||
)}
|
||||
<Button asChild variant="secondary" className="h-6 flex-1 text-xs flex items-center justify-center gap-2" onClick={handleLogout}>
|
||||
<Link href="https://buymeacoffee.com/varunraj" target="_blank">
|
||||
<HandshakeIcon className="w-4 h-4" />
|
||||
{/* Connection info */}
|
||||
<div className="border-t px-3 py-2 space-y-1">
|
||||
<Tooltip content={`External: ${exImmichUrl}`}>
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<Globe className="h-3 w-3 shrink-0" />
|
||||
<Link href={exImmichUrl} target="_blank" className="font-mono truncate hover:text-foreground transition-colors">
|
||||
{exImmichUrl}
|
||||
</Link>
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip content={`Internal: ${immichURL}`}>
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<Server className="h-3 w-3 shrink-0" />
|
||||
<Link href={immichURL} target="_blank" className="font-mono truncate hover:text-foreground transition-colors">
|
||||
{immichURL}
|
||||
</Link>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{/* User dropdown */}
|
||||
{user && (
|
||||
<div className="border-t px-2 py-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center gap-2 w-full px-2 py-1.5 rounded-lg hover:bg-muted transition-colors text-left">
|
||||
<div className="h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
|
||||
<User className="h-3.5 w-3.5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{user.name}</p>
|
||||
<p className="text-[10px] text-muted-foreground truncate">{user.email}</p>
|
||||
</div>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent side="top" align="start" className="w-52">
|
||||
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">{user.email}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setTheme(theme === "light" ? "dark" : "light")} className="cursor-pointer">
|
||||
{theme === "light" ? <Moon className="h-4 w-4 mr-2" /> : <Sun className="h-4 w-4 mr-2" />}
|
||||
{theme === "light" ? "Dark Mode" : "Light Mode"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => router.push("/settings")} className="cursor-pointer">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild className="cursor-pointer">
|
||||
<Link href="https://buymeacoffee.com/varunraj" target="_blank">
|
||||
<HandshakeIcon className="h-4 w-4 mr-2" />
|
||||
Support
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="border-t text-muted-foreground text-xs py-2 flex justify-between items-center px-2">
|
||||
</DropdownMenuItem>
|
||||
{!user.isUsingAPIKey && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout} className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<LogOut className="h-4 w-4 mr-2" />
|
||||
Log Out
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div className="border-t text-muted-foreground text-[10px] py-1.5 flex justify-between items-center px-3">
|
||||
<p>
|
||||
Made with <span className="text-red-500">♥</span> by{" "}
|
||||
<Link
|
||||
target="_blank"
|
||||
href="https://x.com/zathvarun"
|
||||
className="text-primary"
|
||||
>
|
||||
<Link target="_blank" href="https://x.com/zathvarun" className="text-primary">
|
||||
@zathvarun
|
||||
</Link>
|
||||
</p>
|
||||
<Link target="_blank" href={`https://github.com/varun-raj/immich-power-tools/releases/tag/v${version}`}>
|
||||
<Link target="_blank" href={`https://github.com/varun-raj/immich-power-tools/releases/tag/v${version}`} className="font-mono">
|
||||
v{version}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Dialog, DialogTitle, DialogContent, DialogHeader, DialogTrigger, Dialog
|
||||
import { Button, ButtonProps } from '../ui/button';
|
||||
import { ShareLinkFilters } from '@/types/shareLink';
|
||||
import { generateShareLink } from '@/handlers/api/shareLink.handler';
|
||||
import { createShareKey, getShareKey } from '@/handlers/api/share-key.handler';
|
||||
import { Input } from '../ui/input';
|
||||
import { Label } from '@radix-ui/react-label';
|
||||
|
||||
@@ -22,6 +23,28 @@ export default function ShareAssetsTrigger({ filters, buttonProps }: ShareAssets
|
||||
const [config, setConfig] = useState<Partial<ShareLinkFilters>>({
|
||||
expiresIn: "never"
|
||||
});
|
||||
const [endpointConfigured, setEndpointConfigured] = useState<boolean | null>(null);
|
||||
const [shareKeyExists, setShareKeyExists] = useState<boolean | null>(null);
|
||||
const [creatingKey, setCreatingKey] = useState(false);
|
||||
const [keyError, setKeyError] = useState<string | null>(null);
|
||||
|
||||
const checkShareKey = async () => {
|
||||
const data = await getShareKey();
|
||||
setEndpointConfigured(data.endpointConfigured);
|
||||
setShareKeyExists(data.exists);
|
||||
};
|
||||
|
||||
const handleCreateKey = async () => {
|
||||
setCreatingKey(true);
|
||||
setKeyError(null);
|
||||
try {
|
||||
await createShareKey();
|
||||
setShareKeyExists(true);
|
||||
} catch (err: any) {
|
||||
setKeyError(err.message ?? 'Failed to create share key');
|
||||
}
|
||||
setCreatingKey(false);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setConfig({ expiresIn: "never" });
|
||||
@@ -66,7 +89,7 @@ export default function ShareAssetsTrigger({ filters, buttonProps }: ShareAssets
|
||||
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<Dialog onOpenChange={(open) => { if (open) checkShareKey(); }}>
|
||||
<DialogTrigger asChild>
|
||||
<Button {...buttonProps}>Share</Button>
|
||||
</DialogTrigger>
|
||||
@@ -77,6 +100,24 @@ export default function ShareAssetsTrigger({ filters, buttonProps }: ShareAssets
|
||||
<DialogDescription>
|
||||
Generate a share link for the selected assets (either bunch of albums or bunch of people) and share it with your friends and family.
|
||||
</DialogDescription>
|
||||
{endpointConfigured === false && (
|
||||
<div className="rounded-md border border-red-400 bg-red-50 dark:bg-red-950 p-3">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">
|
||||
<strong>POWER_TOOLS_ENDPOINT_URL</strong> is not set. Add it to your environment variables to enable share links.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{endpointConfigured && shareKeyExists === false && (
|
||||
<div className="rounded-md border border-yellow-400 bg-yellow-50 dark:bg-yellow-950 p-3 flex flex-col gap-2">
|
||||
<p className="text-sm text-yellow-800 dark:text-yellow-200">
|
||||
Serving thumbnails on share links requires a dedicated API key. Create one now with minimal permissions.
|
||||
</p>
|
||||
{keyError && <p className="text-xs text-red-500">{keyError}</p>}
|
||||
<Button size="sm" onClick={handleCreateKey} disabled={creatingKey} className="self-start">
|
||||
{creatingKey ? 'Creating...' : 'Create API Key'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && <div className="text-red-500">{errorMessage}</div>}
|
||||
{generatedLink ? <div className="flex flex-col gap-2">
|
||||
<Label className='text-sm'>Share Link</Label>
|
||||
@@ -120,7 +161,7 @@ export default function ShareAssetsTrigger({ filters, buttonProps }: ShareAssets
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button onClick={handleGenerate} disabled={loading}>Generate Share Link</Button>
|
||||
<Button onClick={handleGenerate} disabled={loading || !endpointConfigured || !shareKeyExists}>Generate Share Link</Button>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { sidebarNavs } from "@/config/constants/sidebarNavs";
|
||||
import { sidebarGroups } from "@/config/constants/sidebarNavs";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import ProfileInfo from "./ProfileInfo";
|
||||
|
||||
const ThemeSwitcher = dynamic(() => import("@/components/shared/ThemeSwitcher"), {
|
||||
ssr: false,
|
||||
});
|
||||
const ProfileInfo = dynamic(() => import("./ProfileInfo"), { ssr: false });
|
||||
|
||||
export default function Sidebar() {
|
||||
const router = useRouter();
|
||||
@@ -29,24 +26,32 @@ export default function Sidebar() {
|
||||
/>
|
||||
<span className="">Immich Power Tools</span>
|
||||
</Link>
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<nav className="grid items-start px-2 text-sm font-medium lg:px-4">
|
||||
{sidebarNavs.map((nav) => (
|
||||
<Link
|
||||
key={nav.title}
|
||||
href={nav.link}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg py-2 text-muted-foreground transition-all hover:text-primary",
|
||||
{
|
||||
"text-primary": pathname === nav.link,
|
||||
}
|
||||
)}
|
||||
>
|
||||
{nav.icon}
|
||||
{nav.title}
|
||||
</Link>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<nav className="px-2 lg:px-4 space-y-4 py-2">
|
||||
{sidebarGroups.map((group) => (
|
||||
<div key={group.label}>
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 px-3 mb-1">
|
||||
{group.label}
|
||||
</p>
|
||||
<div className="space-y-0.5">
|
||||
{group.items.map((nav) => (
|
||||
<Link
|
||||
key={nav.title}
|
||||
href={nav.link}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg py-1.5 px-3 text-sm text-muted-foreground transition-all hover:text-primary",
|
||||
{
|
||||
"text-primary bg-primary/5 font-medium": pathname === nav.link,
|
||||
}
|
||||
)}
|
||||
>
|
||||
{nav.icon}
|
||||
{nav.title}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -45,7 +45,7 @@ const Autocomplete = React.forwardRef<HTMLInputElement, AutocompleteProps>(
|
||||
const [selectedIndex, setSelectedIndex] = React.useState(-1)
|
||||
const containerRef = React.useRef<HTMLDivElement>(null)
|
||||
const inputRef = React.useRef<HTMLInputElement>(null)
|
||||
const debounceTimeout = React.useRef<NodeJS.Timeout>()
|
||||
const debounceTimeout = React.useRef<NodeJS.Timeout>(undefined)
|
||||
|
||||
// Find the label for the current value
|
||||
const currentLabel = React.useMemo(() => {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { CHART_COLORS } from "@/config/constants/chart.constant";
|
||||
import React, { useMemo } from "react";
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
XAxis,
|
||||
YAxis,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Cell,
|
||||
} from "recharts";
|
||||
import { ValueType } from "recharts/types/component/DefaultTooltipContent";
|
||||
|
||||
export interface IBarChartData {
|
||||
label: string;
|
||||
value: number;
|
||||
valueLabel?: string;
|
||||
}
|
||||
|
||||
interface HorizontalBarChartProps {
|
||||
data: IBarChartData[];
|
||||
loading?: boolean;
|
||||
errorMessage?: string | null;
|
||||
tooltipValueFormatter?: (value: number | string | undefined | ValueType) => string;
|
||||
maxItems?: number;
|
||||
}
|
||||
|
||||
export default function HorizontalBarChart({
|
||||
data: _data,
|
||||
loading,
|
||||
errorMessage,
|
||||
tooltipValueFormatter,
|
||||
maxItems = 10,
|
||||
}: HorizontalBarChartProps) {
|
||||
const data = useMemo(() => {
|
||||
return _data.slice(0, maxItems).map((item, index) => ({
|
||||
...item,
|
||||
fill: CHART_COLORS[index % CHART_COLORS.length],
|
||||
}));
|
||||
}, [_data, maxItems]);
|
||||
|
||||
const total = useMemo(() => data.reduce((sum, d) => sum + d.value, 0), [data]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-[200px]">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (errorMessage) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-[200px] text-sm text-muted-foreground">
|
||||
{errorMessage}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data.length) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-[200px] text-sm text-muted-foreground">
|
||||
No data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{data.map((item, index) => {
|
||||
const percentage = total > 0 ? (item.value / total) * 100 : 0;
|
||||
const displayValue = tooltipValueFormatter
|
||||
? tooltipValueFormatter(item.value)
|
||||
: item.valueLabel || item.value.toLocaleString();
|
||||
|
||||
return (
|
||||
<div key={item.label} className="group">
|
||||
<div className="flex items-center justify-between text-sm mb-1">
|
||||
<span className="text-foreground truncate max-w-[60%]" title={item.label}>
|
||||
{item.label}
|
||||
</span>
|
||||
<span className="text-muted-foreground tabular-nums font-mono text-xs">
|
||||
{displayValue}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 w-full rounded-full bg-muted overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-500 ease-out"
|
||||
style={{
|
||||
width: `${Math.max(percentage, 1)}%`,
|
||||
backgroundColor: CHART_COLORS[index % CHART_COLORS.length],
|
||||
opacity: 0.85,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,16 +2,19 @@
|
||||
import { humanizeDuration } from '@/helpers/string.helper'
|
||||
import { PlayIcon } from '@radix-ui/react-icons'
|
||||
import React, { useEffect } from 'react'
|
||||
import { Image, ImageExtended, ThumbnailImageProps } from 'react-grid-gallery'
|
||||
import type { RenderImageProps } from 'react-photo-album'
|
||||
import type { AssetPhoto } from '../shared/AssetGrid'
|
||||
|
||||
interface LazyImageProps extends ThumbnailImageProps<ImageExtended<Image & { isVideo?: boolean, duration?: string }>> {}
|
||||
interface LazyGridImageProps {
|
||||
imageProps: RenderImageProps;
|
||||
photo: AssetPhoto;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
|
||||
export default function LazyGridImage(
|
||||
props: LazyImageProps
|
||||
) {
|
||||
export default function LazyGridImage({ imageProps, photo, width, height }: LazyGridImageProps) {
|
||||
const [isVisible, setIsVisible] = React.useState(false)
|
||||
const imageRef = React.useRef<HTMLImageElement>(null)
|
||||
const imageRef = React.useRef<HTMLDivElement>(null)
|
||||
|
||||
const setupObserver = () => {
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
@@ -38,15 +41,15 @@ export default function LazyGridImage(
|
||||
}, [])
|
||||
|
||||
if (!isVisible) return (
|
||||
<div style={{ height: props.height }} ref={imageRef} />
|
||||
<div style={{ height, width }} ref={imageRef} />
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<img {...props.imageProps} alt={props.imageProps.alt || ""} title="" />
|
||||
{props.item.isVideo && <div className="absolute bottom-2 right-2 bg-black/50 p-1 rounded-full flex items-center gap-1">
|
||||
<div style={{ position: 'relative', width, height }}>
|
||||
<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" />
|
||||
{!!props.item.duration && <span className="text-xs text-white">{humanizeDuration(props.item.duration)}</span>}
|
||||
{!!photo.duration && <span className="text-xs text-white">{humanizeDuration(photo.duration)}</span>}
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { FilePlus, FileEdit, Database, GitBranch, GitFork, FolderPlus, FolderInput, FolderMinus, Heart, HeartOff, Archive, Tag } from "lucide-react";
|
||||
|
||||
interface PaletteItem {
|
||||
type: string;
|
||||
subType: string;
|
||||
label: string;
|
||||
icon: any;
|
||||
color: string;
|
||||
}
|
||||
|
||||
const assetTriggerItems: PaletteItem[] = [
|
||||
{ type: "trigger", subType: "new_asset", label: "New Asset", icon: FilePlus, color: "text-green-500" },
|
||||
{ type: "trigger", subType: "asset_updated", label: "Asset Updated", icon: FileEdit, color: "text-green-500" },
|
||||
{ type: "trigger", subType: "all_assets", label: "All Assets", icon: Database, color: "text-green-500" },
|
||||
];
|
||||
|
||||
const logicItems: PaletteItem[] = [
|
||||
{ type: "logic_if", subType: "if", label: "If", icon: GitBranch, color: "text-yellow-500" },
|
||||
{ type: "logic_switch", subType: "switch", label: "Switch", icon: GitFork, color: "text-orange-500" },
|
||||
];
|
||||
|
||||
const actionItems: PaletteItem[] = [
|
||||
{ type: "action", subType: "create_album", label: "Create Album", icon: FolderPlus, color: "text-purple-500" },
|
||||
{ type: "action", subType: "add_to_album", label: "Add to Album", icon: FolderInput, color: "text-purple-500" },
|
||||
{ type: "action", subType: "remove_from_album", label: "Remove from Album", icon: FolderMinus, color: "text-purple-500" },
|
||||
{ type: "action", subType: "favorite", label: "Favorite", icon: Heart, color: "text-purple-500" },
|
||||
{ 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" },
|
||||
];
|
||||
|
||||
function PaletteGroup({ title, items }: { title: string; items: PaletteItem[] }) {
|
||||
const onDragStart = (event: React.DragEvent, item: PaletteItem) => {
|
||||
event.dataTransfer.setData("application/reactflow", JSON.stringify({
|
||||
type: item.type,
|
||||
subType: item.subType,
|
||||
}));
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-1">{title}</h3>
|
||||
<div className="space-y-1">
|
||||
{items.map((item) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<div
|
||||
key={`${item.type}-${item.subType}`}
|
||||
draggable
|
||||
onDragStart={(e) => onDragStart(e, item)}
|
||||
className="flex items-center gap-2 px-2 py-1.5 rounded cursor-grab active:cursor-grabbing hover:bg-muted transition-colors"
|
||||
>
|
||||
<Icon className={`h-3.5 w-3.5 ${item.color}`} />
|
||||
<span className="text-xs text-foreground">{item.label}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function NodePalette() {
|
||||
return (
|
||||
<div className="w-48 border-r bg-background p-3 overflow-y-auto">
|
||||
<h2 className="text-sm font-semibold mb-3">Nodes</h2>
|
||||
<PaletteGroup title="Asset Triggers" items={assetTriggerItems} />
|
||||
<PaletteGroup title="Logic" items={logicItems} />
|
||||
<PaletteGroup title="Actions" items={actionItems} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
|
||||
import { Check } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { listAlbums } from "@/handlers/api/album.handler";
|
||||
import { IAlbum } from "@/types/album";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface ActionConfigProps {
|
||||
subType: string;
|
||||
config: any;
|
||||
onChange: (config: any) => void;
|
||||
}
|
||||
|
||||
const templateVars = ["{city}", "{date}", "{person}", "{camera}", "{state}", "{country}"];
|
||||
|
||||
function AlbumPicker({ value, onChange }: { value: string | undefined; onChange: (albumId: string, albumName: string) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [albums, setAlbums] = useState<IAlbum[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedAlbum, setSelectedAlbum] = useState<IAlbum | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
listAlbums()
|
||||
.then((data) => {
|
||||
setAlbums(data);
|
||||
if (value) {
|
||||
const found = data.find((a: IAlbum) => a.id === value);
|
||||
if (found) setSelectedAlbum(found);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button type="button" className="flex items-center gap-2 h-8 px-3 w-full border rounded text-sm bg-background hover:bg-muted transition-colors text-left">
|
||||
{selectedAlbum ? (
|
||||
<span className="truncate">{selectedAlbum.albumName}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Select album...</span>
|
||||
)}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-0 z-[10000]" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search albums..." className="text-xs" />
|
||||
<CommandList>
|
||||
<CommandEmpty>{loading ? "Loading..." : "No albums found."}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{albums.map((album) => (
|
||||
<CommandItem
|
||||
key={album.id}
|
||||
value={album.albumName}
|
||||
onSelect={() => {
|
||||
setSelectedAlbum(album);
|
||||
onChange(album.id, album.albumName);
|
||||
setOpen(false);
|
||||
}}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<span className="text-xs truncate flex-1">{album.albumName}</span>
|
||||
<Check className={cn("h-3 w-3", value === album.id ? "opacity-100" : "opacity-0")} />
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ActionConfig({ subType, config, onChange }: ActionConfigProps) {
|
||||
if (subType === "create_album") {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Album Name Template</Label>
|
||||
<Input
|
||||
className="h-8 text-sm"
|
||||
placeholder="Trip to {city} - {date}"
|
||||
value={config.nameTemplate || ""}
|
||||
onChange={(e) => onChange({ ...config, nameTemplate: e.target.value })}
|
||||
/>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{templateVars.map((v) => (
|
||||
<Badge
|
||||
key={v}
|
||||
variant="outline"
|
||||
className="text-[10px] cursor-pointer hover:bg-muted"
|
||||
onClick={() => onChange({ ...config, nameTemplate: (config.nameTemplate || "") + v })}
|
||||
>
|
||||
{v}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (subType === "add_to_album" || subType === "remove_from_album") {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Album</Label>
|
||||
<AlbumPicker
|
||||
value={config.albumId}
|
||||
onChange={(albumId, albumName) => onChange({ ...config, albumId, albumName })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (subType === "tag") {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Tag Name</Label>
|
||||
<Input
|
||||
className="h-8 text-sm"
|
||||
placeholder="e.g. Vacation"
|
||||
value={config.tagName || ""}
|
||||
onChange={(e) => onChange({ ...config, tagName: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// favorite, unfavorite, archive — no config needed
|
||||
return <p className="text-xs text-muted-foreground">No configuration needed.</p>;
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
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 { listPeople } from "@/handlers/api/people.handler";
|
||||
import { IPerson } from "@/types/person";
|
||||
import { PERSON_THUBNAIL_PATH } from "@/config/routes";
|
||||
import { useEffect, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const conditionTypeLabels: Record<ConditionType, string> = {
|
||||
person: "Person",
|
||||
person_unnamed: "Unnamed People",
|
||||
city: "City",
|
||||
state: "State",
|
||||
country: "Country",
|
||||
geo_radius: "Geo Radius",
|
||||
date_range: "Date Range",
|
||||
date_relative: "Relative Date",
|
||||
day_of_week: "Day of Week",
|
||||
camera_make: "Camera Make",
|
||||
camera_model: "Camera Model",
|
||||
lens: "Lens",
|
||||
asset_type: "Asset Type",
|
||||
iso_range: "ISO Range",
|
||||
focal_length: "Focal Length",
|
||||
rating: "Rating",
|
||||
is_favorited: "Favorited",
|
||||
not_in_album: "Not in Any Album",
|
||||
not_in_specific_album: "Not in Specific Album",
|
||||
};
|
||||
|
||||
const conditionTypes = Object.keys(conditionTypeLabels) as ConditionType[];
|
||||
|
||||
interface PersonPickerProps {
|
||||
selectedIds: string[];
|
||||
onChange: (personIds: string[], personNames: string[]) => void;
|
||||
}
|
||||
|
||||
function PersonPicker({ selectedIds, onChange }: PersonPickerProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [people, setPeople] = useState<IPerson[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
listPeople({ page: 1, perPage: 500, sort: "createdAt", sortOrder: "desc", visibility: "visible", type: "named" })
|
||||
.then((res) => setPeople(res.people))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const selectedSet = new Set(selectedIds || []);
|
||||
const selectedPeople = people.filter((p) => selectedSet.has(p.id));
|
||||
|
||||
const togglePerson = (person: IPerson) => {
|
||||
let nextIds: string[];
|
||||
let nextNames: string[];
|
||||
if (selectedSet.has(person.id)) {
|
||||
nextIds = selectedIds.filter((id) => id !== person.id);
|
||||
nextNames = selectedPeople.filter((p) => p.id !== person.id).map((p) => p.name);
|
||||
} else {
|
||||
nextIds = [...selectedIds, person.id];
|
||||
nextNames = [...selectedPeople.map((p) => p.name), person.name];
|
||||
}
|
||||
onChange(nextIds, nextNames);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Selected people chips */}
|
||||
{selectedPeople.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{selectedPeople.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => togglePerson(p)}
|
||||
className="flex items-center gap-1 px-1.5 py-0.5 rounded-full bg-muted hover:bg-destructive/10 transition-colors group"
|
||||
>
|
||||
<img src={PERSON_THUBNAIL_PATH(p.id)} alt="" className="h-4 w-4 rounded-full object-cover" />
|
||||
<span className="text-[10px] font-medium">{p.name || "Unknown"}</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 people..." : "Add more..."}
|
||||
</span>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56 p-0 z-[10000]" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search people..." className="text-xs" />
|
||||
<CommandList>
|
||||
<CommandEmpty>{loading ? "Loading..." : "No people found."}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{people.map((person) => (
|
||||
<CommandItem
|
||||
key={person.id}
|
||||
value={person.name || person.id}
|
||||
onSelect={() => togglePerson(person)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<img src={PERSON_THUBNAIL_PATH(person.id)} alt="" className="h-6 w-6 rounded-full object-cover" />
|
||||
<span className="text-xs truncate flex-1">{person.name || "Unknown"}</span>
|
||||
<Check className={cn("h-3 w-3", selectedSet.has(person.id) ? "opacity-100" : "opacity-0")} />
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConditionEditorProps {
|
||||
conditions: ICondition[];
|
||||
onChange: (conditions: ICondition[]) => void;
|
||||
}
|
||||
|
||||
function ConditionFields({ condition, onChange }: { condition: ICondition; onChange: (c: ICondition) => void }) {
|
||||
switch (condition.type) {
|
||||
case "city":
|
||||
case "state":
|
||||
case "country":
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Select value={condition.match || "equals"} onValueChange={(v) => onChange({ ...condition, match: v })}>
|
||||
<SelectTrigger className="h-7 text-xs w-24"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="equals">Equals</SelectItem>
|
||||
<SelectItem value="not_equals">Not Equals</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Input className="h-7 text-xs" placeholder={condition.type} value={condition[condition.type] || ""} onChange={(e) => onChange({ ...condition, [condition.type]: e.target.value })} />
|
||||
</div>
|
||||
);
|
||||
case "camera_make":
|
||||
return <Input className="h-7 text-xs" placeholder="e.g. Apple" value={condition.make || ""} onChange={(e) => onChange({ ...condition, make: e.target.value })} />;
|
||||
case "camera_model":
|
||||
return <Input className="h-7 text-xs" placeholder="e.g. iPhone 16 Pro" value={condition.model || ""} onChange={(e) => onChange({ ...condition, model: e.target.value })} />;
|
||||
case "lens":
|
||||
return <Input className="h-7 text-xs" placeholder="Lens model" value={condition.lensModel || ""} onChange={(e) => onChange({ ...condition, lensModel: e.target.value })} />;
|
||||
case "asset_type":
|
||||
return (
|
||||
<Select value={condition.assetType || "IMAGE"} onValueChange={(v) => onChange({ ...condition, assetType: v })}>
|
||||
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="IMAGE">Image</SelectItem>
|
||||
<SelectItem value="VIDEO">Video</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
case "date_range":
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Input className="h-7 text-xs" type="date" value={condition.after || ""} onChange={(e) => onChange({ ...condition, after: e.target.value })} />
|
||||
<Input className="h-7 text-xs" type="date" value={condition.before || ""} onChange={(e) => onChange({ ...condition, before: e.target.value })} />
|
||||
</div>
|
||||
);
|
||||
case "date_relative":
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-xs text-muted-foreground">Last</span>
|
||||
<Input className="h-7 text-xs w-16" type="number" min={1} value={condition.lastDays || ""} onChange={(e) => onChange({ ...condition, lastDays: parseInt(e.target.value) || 0 })} />
|
||||
<span className="text-xs text-muted-foreground">days</span>
|
||||
</div>
|
||||
);
|
||||
case "iso_range":
|
||||
case "focal_length":
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Input className="h-7 text-xs" type="number" placeholder="Min" value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: parseFloat(e.target.value) || undefined })} />
|
||||
<Input className="h-7 text-xs" type="number" placeholder="Max" value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: parseFloat(e.target.value) || undefined })} />
|
||||
</div>
|
||||
);
|
||||
case "rating":
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Input className="h-7 text-xs w-16" type="number" min={1} max={5} placeholder="Min" value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: parseInt(e.target.value) || undefined })} />
|
||||
<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 "is_favorited":
|
||||
return (
|
||||
<Select value={condition.value === false ? "false" : "true"} onValueChange={(v) => onChange({ ...condition, value: v === "true" })}>
|
||||
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="true">Is Favorited</SelectItem>
|
||||
<SelectItem value="false">Not Favorited</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
case "person":
|
||||
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">Contains any of</SelectItem>
|
||||
<SelectItem value="contains_all">Contains all of</SelectItem>
|
||||
<SelectItem value="not_contains">Does not contain</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<PersonPicker
|
||||
selectedIds={condition.personIds || (condition.personId ? [condition.personId] : [])}
|
||||
onChange={(personIds, personNames) => onChange({ ...condition, personIds, personNames })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
case "geo_radius":
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="flex gap-2">
|
||||
<Input className="h-7 text-xs" type="number" step="any" placeholder="Latitude" value={condition.lat ?? ""} onChange={(e) => onChange({ ...condition, lat: parseFloat(e.target.value) || 0 })} />
|
||||
<Input className="h-7 text-xs" type="number" step="any" placeholder="Longitude" value={condition.lng ?? ""} onChange={(e) => onChange({ ...condition, lng: parseFloat(e.target.value) || 0 })} />
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Input className="h-7 text-xs w-20" type="number" min={1} placeholder="Radius" value={condition.radiusKm ?? ""} onChange={(e) => onChange({ ...condition, radiusKm: parseFloat(e.target.value) || 0 })} />
|
||||
<span className="text-xs text-muted-foreground">km</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case "day_of_week":
|
||||
return (
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
{["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day, i) => {
|
||||
const days: number[] = condition.days || [];
|
||||
const active = days.includes(i);
|
||||
return (
|
||||
<button
|
||||
key={day}
|
||||
type="button"
|
||||
className={`text-[10px] px-1.5 py-0.5 rounded border ${active ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
|
||||
onClick={() => {
|
||||
const next = active ? days.filter((d: number) => d !== i) : [...days, i];
|
||||
onChange({ ...condition, days: next });
|
||||
}}
|
||||
>
|
||||
{day}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
case "not_in_album":
|
||||
case "person_unnamed":
|
||||
return null;
|
||||
case "not_in_specific_album":
|
||||
return <Input className="h-7 text-xs" placeholder="Album ID" value={condition.albumId || ""} onChange={(e) => onChange({ ...condition, albumId: e.target.value })} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default function ConditionEditor({ conditions, onChange }: ConditionEditorProps) {
|
||||
const addCondition = () => {
|
||||
onChange([...conditions, { type: "city" }]);
|
||||
};
|
||||
|
||||
const removeCondition = (index: number) => {
|
||||
onChange(conditions.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const updateCondition = (index: number, condition: ICondition) => {
|
||||
const next = [...conditions];
|
||||
next[index] = condition;
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const changeType = (index: number, type: ConditionType) => {
|
||||
const next = [...conditions];
|
||||
next[index] = { type };
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{conditions.map((condition, i) => (
|
||||
<div key={i} className="p-2 border rounded space-y-2 bg-muted/30">
|
||||
<div className="flex items-center gap-1">
|
||||
<Select value={condition.type} onValueChange={(v) => changeType(i, v as ConditionType)}>
|
||||
<SelectTrigger className="h-7 text-xs flex-1"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{conditionTypes.map((t) => (
|
||||
<SelectItem key={t} value={t}>{conditionTypeLabels[t]}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => removeCondition(i)}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<ConditionFields condition={condition} onChange={(c) => updateCondition(i, c)} />
|
||||
{i < conditions.length - 1 && (
|
||||
<div className="text-center">
|
||||
<span className="text-[10px] font-medium text-muted-foreground bg-muted px-2 py-0.5 rounded">AND</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" size="sm" className="w-full h-7 text-xs" onClick={addCondition}>
|
||||
<Plus className="h-3 w-3 mr-1" />
|
||||
Add Condition
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ICondition } from "@/types/workflow";
|
||||
import ConditionEditor from "./ConditionEditor";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
interface IfConfigProps {
|
||||
config: { conditions?: ICondition[] };
|
||||
onChange: (config: any) => void;
|
||||
}
|
||||
|
||||
export default function IfConfig({ config, onChange }: IfConfigProps) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-xs">Conditions (AND)</Label>
|
||||
<p className="text-[10px] text-muted-foreground mb-2">All conditions must match for the TRUE branch.</p>
|
||||
</div>
|
||||
<ConditionEditor
|
||||
conditions={config.conditions || []}
|
||||
onChange={(conditions) => onChange({ ...config, conditions })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ICondition } from "@/types/workflow";
|
||||
import ConditionEditor from "./ConditionEditor";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Plus, X } from "lucide-react";
|
||||
|
||||
interface SwitchCase {
|
||||
label: string;
|
||||
conditions: ICondition[];
|
||||
handle: string;
|
||||
}
|
||||
|
||||
interface SwitchConfigProps {
|
||||
config: { cases?: SwitchCase[] };
|
||||
onChange: (config: any) => void;
|
||||
}
|
||||
|
||||
export default function SwitchConfig({ config, onChange }: SwitchConfigProps) {
|
||||
const cases = config.cases || [];
|
||||
|
||||
const addCase = () => {
|
||||
const handle = `case_${cases.length}`;
|
||||
onChange({
|
||||
...config,
|
||||
cases: [...cases, { label: `Case ${cases.length + 1}`, conditions: [], handle }],
|
||||
});
|
||||
};
|
||||
|
||||
const removeCase = (index: number) => {
|
||||
onChange({ ...config, cases: cases.filter((_: any, i: number) => i !== index) });
|
||||
};
|
||||
|
||||
const updateCase = (index: number, updates: Partial<SwitchCase>) => {
|
||||
const next = [...cases];
|
||||
next[index] = { ...next[index], ...updates };
|
||||
onChange({ ...config, cases: next });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-xs">Cases</Label>
|
||||
<p className="text-[10px] text-muted-foreground mb-2">First matching case wins. Non-matching assets go to Default.</p>
|
||||
</div>
|
||||
{cases.map((c: SwitchCase, i: number) => (
|
||||
<div key={c.handle} className="border rounded p-2 space-y-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
className="h-7 text-xs flex-1"
|
||||
value={c.label}
|
||||
onChange={(e) => updateCase(i, { label: e.target.value })}
|
||||
placeholder="Case label"
|
||||
/>
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => removeCase(i)}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<ConditionEditor
|
||||
conditions={c.conditions}
|
||||
onChange={(conditions) => updateCase(i, { conditions })}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" size="sm" className="w-full h-7 text-xs" onClick={addCase}>
|
||||
<Plus className="h-3 w-3 mr-1" />
|
||||
Add Case
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
interface TriggerConfigProps {
|
||||
subType: string;
|
||||
config: any;
|
||||
onChange: (config: any) => void;
|
||||
webhookToken?: string | null;
|
||||
}
|
||||
|
||||
export default function TriggerConfig({ subType, config, onChange, webhookToken }: TriggerConfigProps) {
|
||||
if (subType === "manual") {
|
||||
return <p className="text-xs text-muted-foreground">No configuration needed. Use the Run button to trigger manually.</p>;
|
||||
}
|
||||
|
||||
if (subType === "schedule") {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Cron Expression</Label>
|
||||
<Input
|
||||
className="h-8 text-sm font-mono"
|
||||
placeholder="0 */6 * * *"
|
||||
value={config.cron || ""}
|
||||
onChange={(e) => onChange({ ...config, cron: e.target.value })}
|
||||
/>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
Examples: <code>0 */6 * * *</code> (every 6h), <code>0 9 * * 1</code> (Mon 9am)
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (subType === "webhook") {
|
||||
const url = webhookToken ? `${window.location.origin}/api/webhooks/${webhookToken}` : "Save workflow first";
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Webhook URL</Label>
|
||||
<div className="flex gap-1">
|
||||
<Input className="h-8 text-xs font-mono" readOnly value={url} />
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
Configure this URL in Immich admin webhook settings.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { default as ConditionEditor } from "./ConditionEditor";
|
||||
export { default as IfConfig } from "./IfConfig";
|
||||
export { default as SwitchConfig } from "./SwitchConfig";
|
||||
export { default as ActionConfig } from "./ActionConfig";
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Handle, Position, NodeProps } from "@xyflow/react";
|
||||
import { FolderPlus, FolderInput, FolderMinus, Heart, HeartOff, Archive, Tag } from "lucide-react";
|
||||
|
||||
const actionIcons: Record<string, any> = {
|
||||
create_album: FolderPlus,
|
||||
add_to_album: FolderInput,
|
||||
remove_from_album: FolderMinus,
|
||||
favorite: Heart,
|
||||
unfavorite: HeartOff,
|
||||
archive: Archive,
|
||||
tag: Tag,
|
||||
};
|
||||
|
||||
const actionLabels: 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",
|
||||
};
|
||||
|
||||
export default function ActionNode({ data, selected }: NodeProps) {
|
||||
const subType = data.subType as string || "create_album";
|
||||
const Icon = actionIcons[subType] || FolderPlus;
|
||||
const label = actionLabels[subType] || "Action";
|
||||
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
|
||||
|
||||
return (
|
||||
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[180px] ${selected ? "border-blue-500" : "border-purple-500"}`}>
|
||||
<Handle type="target" position={Position.Top} className="!bg-purple-500 !w-3 !h-3" />
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="p-1.5 rounded bg-purple-500/10">
|
||||
<Icon className="h-4 w-4 text-purple-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-foreground">{label}</p>
|
||||
{subType === "create_album" && config.nameTemplate && (
|
||||
<p className="text-[10px] text-muted-foreground truncate max-w-[140px]">{config.nameTemplate}</p>
|
||||
)}
|
||||
{subType === "tag" && config.tagName && (
|
||||
<p className="text-[10px] text-muted-foreground">{config.tagName}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Handle, Position, NodeProps } from "@xyflow/react";
|
||||
import { GitBranch } from "lucide-react";
|
||||
|
||||
export default function IfNode({ data, selected }: NodeProps) {
|
||||
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
|
||||
const conditions = config.conditions || [];
|
||||
|
||||
return (
|
||||
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[200px] ${selected ? "border-blue-500" : "border-yellow-500"}`}>
|
||||
<Handle type="target" position={Position.Top} className="!bg-yellow-500 !w-3 !h-3" />
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<div className="p-1.5 rounded bg-yellow-500/10">
|
||||
<GitBranch className="h-4 w-4 text-yellow-500" />
|
||||
</div>
|
||||
<p className="text-xs font-medium text-foreground">IF</p>
|
||||
</div>
|
||||
{conditions.length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
{conditions.map((c: any, i: number) => (
|
||||
<p key={i} className="text-[10px] text-muted-foreground truncate">
|
||||
{c.type}{c.city ? `: ${c.city}` : ""}{c.personId ? " (person)" : ""}{c.value !== undefined ? `: ${c.value}` : ""}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-[10px] text-muted-foreground">No conditions set</p>
|
||||
)}
|
||||
<div className="flex justify-between mt-3 px-2">
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-[9px] text-green-500 font-medium">TRUE</span>
|
||||
<Handle type="source" position={Position.Bottom} id="true" className="!bg-green-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
|
||||
</div>
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-[9px] text-red-500 font-medium">FALSE</span>
|
||||
<Handle type="source" position={Position.Bottom} id="false" className="!bg-red-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Handle, Position, NodeProps } from "@xyflow/react";
|
||||
import { GitFork } from "lucide-react";
|
||||
|
||||
export default function SwitchNode({ data, selected }: NodeProps) {
|
||||
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
|
||||
const cases = config.cases || [];
|
||||
|
||||
return (
|
||||
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[220px] ${selected ? "border-blue-500" : "border-orange-500"}`}>
|
||||
<Handle type="target" position={Position.Top} className="!bg-orange-500 !w-3 !h-3" />
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<div className="p-1.5 rounded bg-orange-500/10">
|
||||
<GitFork className="h-4 w-4 text-orange-500" />
|
||||
</div>
|
||||
<p className="text-xs font-medium text-foreground">SWITCH</p>
|
||||
<span className="text-[10px] text-muted-foreground ml-auto">{cases.length} cases</span>
|
||||
</div>
|
||||
{cases.length > 0 && (
|
||||
<div className="space-y-1 mb-2">
|
||||
{cases.map((c: any, i: number) => (
|
||||
<p key={i} className="text-[10px] text-muted-foreground truncate">
|
||||
{c.label || `Case ${i + 1}`}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between mt-3 px-1 gap-2">
|
||||
{cases.map((c: any, i: number) => (
|
||||
<div key={c.handle || `case_${i}`} className="flex flex-col items-center">
|
||||
<span className="text-[9px] text-orange-500 font-medium truncate max-w-[50px]">{c.label || `C${i + 1}`}</span>
|
||||
<Handle type="source" position={Position.Bottom} id={c.handle || `case_${i}`} className="!bg-orange-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
|
||||
</div>
|
||||
))}
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-[9px] text-muted-foreground font-medium">DEF</span>
|
||||
<Handle type="source" position={Position.Bottom} id="default" className="!bg-gray-400 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Handle, Position, NodeProps } from "@xyflow/react";
|
||||
import { FilePlus, FileEdit, Database } from "lucide-react";
|
||||
|
||||
const triggerIcons: Record<string, any> = {
|
||||
new_asset: FilePlus,
|
||||
asset_updated: FileEdit,
|
||||
all_assets: Database,
|
||||
};
|
||||
|
||||
const triggerLabels: Record<string, string> = {
|
||||
new_asset: "New Asset",
|
||||
asset_updated: "Asset Updated",
|
||||
all_assets: "All Assets",
|
||||
};
|
||||
|
||||
const triggerDescriptions: Record<string, string> = {
|
||||
new_asset: "Since last run (or workflow creation)",
|
||||
asset_updated: "Since last run (or workflow creation)",
|
||||
all_assets: "Full library scan",
|
||||
};
|
||||
|
||||
export default function TriggerNode({ data, selected }: NodeProps) {
|
||||
const subType = data.subType as string || "new_asset";
|
||||
const Icon = triggerIcons[subType] || FilePlus;
|
||||
const label = triggerLabels[subType] || "Asset Trigger";
|
||||
const description = triggerDescriptions[subType] || "";
|
||||
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
|
||||
const lookbackMin = config.lookbackMinutes;
|
||||
|
||||
return (
|
||||
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[180px] ${selected ? "border-blue-500" : "border-green-500"}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="p-1.5 rounded bg-green-500/10">
|
||||
<Icon className="h-4 w-4 text-green-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-foreground">{label}</p>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
{description}
|
||||
{lookbackMin && subType !== "all_assets" ? ` + ${lookbackMin}m buffer` : ""}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Handle type="source" position={Position.Bottom} className="!bg-green-500 !w-3 !h-3" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import TriggerNode from "./TriggerNode";
|
||||
import IfNode from "./IfNode";
|
||||
import SwitchNode from "./SwitchNode";
|
||||
import ActionNode from "./ActionNode";
|
||||
|
||||
export const nodeTypes = {
|
||||
trigger: TriggerNode,
|
||||
logic_if: IfNode,
|
||||
logic_switch: SwitchNode,
|
||||
action: ActionNode,
|
||||
};
|
||||
@@ -1,63 +1,51 @@
|
||||
import { Copy, GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, Rewind, Search, Share2, User, Video } from "lucide-react";
|
||||
import { Copy, GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, PackageSearch, Rewind, Search, Settings, Share2, User, Video, Workflow } from "lucide-react";
|
||||
|
||||
export const sidebarNavs = [
|
||||
// {
|
||||
// title: "Rewind 2024",
|
||||
// link: "/rewind",
|
||||
// icon: <Rewind className="h-4 w-4" />,
|
||||
// },
|
||||
{
|
||||
title: "Find Assets",
|
||||
link: "/find",
|
||||
icon: <Search className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
title: "Manage People",
|
||||
link: "/",
|
||||
icon: <User className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
title: "Analytics",
|
||||
link: "/analytics/exif",
|
||||
icon: <ImageIcon className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
title: "Potential Albums",
|
||||
link: "/albums/potential-albums",
|
||||
icon: <GalleryVerticalEnd className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
title: "Missing Locations",
|
||||
link: "/assets/missing-locations",
|
||||
icon: <MapPinX className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
title: "Manage Albums",
|
||||
link: "/albums",
|
||||
icon: <GalleryHorizontal className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
title: "Import shared",
|
||||
link: "/assets/import-shared",
|
||||
icon: <Share2 className="h-4 w-4" />,
|
||||
},
|
||||
interface SidebarNav {
|
||||
title: string;
|
||||
link: string;
|
||||
icon: React.ReactNode;
|
||||
}
|
||||
|
||||
interface SidebarGroup {
|
||||
label: string;
|
||||
items: SidebarNav[];
|
||||
}
|
||||
|
||||
export const sidebarGroups: SidebarGroup[] = [
|
||||
{
|
||||
title: "Geo Heatmap",
|
||||
link: "/assets/geo-heatmap",
|
||||
icon: <MapPin className="h-4 w-4" />,
|
||||
label: "Library",
|
||||
items: [
|
||||
{ title: "Find Assets", link: "/find", icon: <Search className="h-4 w-4" /> },
|
||||
{ title: "Manage People", link: "/", icon: <User className="h-4 w-4" /> },
|
||||
{ title: "Manage Albums", link: "/albums", icon: <GalleryHorizontal className="h-4 w-4" /> },
|
||||
{ title: "Analytics", link: "/analytics/exif", icon: <ImageIcon className="h-4 w-4" /> },
|
||||
],
|
||||
},
|
||||
// Empty Videos
|
||||
{
|
||||
title: "Empty Videos",
|
||||
link: "/assets/empty-videos",
|
||||
icon: <Video className="h-4 w-4" />,
|
||||
label: "Tools",
|
||||
items: [
|
||||
{ title: "Potential Albums", link: "/albums/potential-albums", icon: <GalleryVerticalEnd className="h-4 w-4" /> },
|
||||
{ title: "Missing Locations", link: "/assets/missing-locations", icon: <MapPinX className="h-4 w-4" /> },
|
||||
{ title: "Empty Videos", link: "/assets/empty-videos", icon: <Video className="h-4 w-4" /> },
|
||||
{ title: "Bulk Duplicate Finder", link: "/assets/bulk-duplicate-finder", icon: <Copy className="h-4 w-4" /> },
|
||||
{ title: "Orphan Finder", link: "/assets/orphan-finder", icon: <PackageSearch className="h-4 w-4" /> },
|
||||
],
|
||||
},
|
||||
// Bulk Duplicate
|
||||
{
|
||||
title: "Bulk Duplicate Finder",
|
||||
link: "/assets/bulk-duplicate-finder",
|
||||
icon: <Copy className="h-4 w-4" />,
|
||||
label: "Automation",
|
||||
items: [
|
||||
{ title: "Workflows", link: "/workflows", icon: <Workflow className="h-4 w-4" /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Other",
|
||||
items: [
|
||||
{ title: "Geo Heatmap", link: "/assets/geo-heatmap", icon: <MapPin className="h-4 w-4" /> },
|
||||
{ title: "Import Shared", link: "/assets/import-shared", icon: <Share2 className="h-4 w-4" /> },
|
||||
{ title: "Settings", link: "/settings", icon: <Settings className="h-4 w-4" /> },
|
||||
],
|
||||
},
|
||||
|
||||
];
|
||||
|
||||
// Flat list for backward compat (mobile menu)
|
||||
export const sidebarNavs = sidebarGroups.flatMap((g) => g.items);
|
||||
@@ -15,8 +15,9 @@ export const ENV = {
|
||||
AI_API_KEY: process.env.AI_API_KEY as string,
|
||||
AI_BASE_URL: (process.env.AI_BASE_URL || 'https://api.openai.com/v1') as string,
|
||||
AI_MODEL: process.env.AI_MODEL as string,
|
||||
IMMICH_SHARE_LINK_KEY: process.env.IMMICH_SHARE_LINK_KEY as string,
|
||||
POWER_TOOLS_ENDPOINT_URL: process.env.POWER_TOOLS_ENDPOINT_URL as string,
|
||||
// App SQLite database path (defaults to ./data/app.db)
|
||||
APP_DB_PATH: process.env.APP_DB_PATH as string | undefined,
|
||||
// OAuth configuration
|
||||
OAUTH_ENABLED: process.env.OAUTH_ENABLED === 'true',
|
||||
OAUTH_BUTTON_TEXT: (process.env.OAUTH_BUTTON_TEXT || 'Login with OAuth') as string,
|
||||
|
||||
+33
-1
@@ -44,6 +44,7 @@ export const ASSET_PREVIEW_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/asset/
|
||||
export const ASSET_VIDEO_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/asset/video/" + id;
|
||||
export const ASSET_GEO_HEATMAP_PATH = BASE_API_ENDPOINT + "/assets/geo-heatmap";
|
||||
export const LIST_EMPTY_VIDEOS_PATH = BASE_API_ENDPOINT + "/assets/empty-videos";
|
||||
export const LIST_ORPHAN_ASSETS_PATH = BASE_API_ENDPOINT + "/assets/orphan-finder";
|
||||
|
||||
|
||||
|
||||
@@ -83,4 +84,35 @@ export const SHARE_LINK_PEOPLE_PATH = (token: string) => BASE_API_ENDPOINT + "/s
|
||||
export const SHARE_LINK_DOWNLOAD_PATH = (token: string) => BASE_API_ENDPOINT + "/share-link/" + token + "/download";
|
||||
export const DOWNLOAD_ASSETS_PATH = BASE_PROXY_ENDPOINT + "/download/archive";
|
||||
|
||||
export const LIST_DUPLICATES_PATH = BASE_PROXY_ENDPOINT + "/duplicates";
|
||||
export const LIST_DUPLICATES_PATH = BASE_PROXY_ENDPOINT + "/duplicates";
|
||||
|
||||
// Settings
|
||||
export const SETTINGS_API_KEYS_PATH = BASE_API_ENDPOINT + "/settings/api-keys";
|
||||
export const SETTINGS_API_KEY_PATH = (purpose: string) => BASE_API_ENDPOINT + "/settings/api-keys/" + purpose;
|
||||
|
||||
// Share Key
|
||||
export const SHARE_KEY_PATH = BASE_API_ENDPOINT + "/share-key";
|
||||
|
||||
// Import Shared
|
||||
export const IMPORT_SHARED_PATH = BASE_API_ENDPOINT + "/import-shared";
|
||||
export const IMPORT_SHARED_UPLOAD_ALL_PATH = BASE_API_ENDPOINT + "/import-shared/upload-all";
|
||||
|
||||
// Permissions
|
||||
export const VALIDATE_PERMISSIONS_PATH = BASE_API_ENDPOINT + "/validate-permissions";
|
||||
|
||||
// Import Jobs (queue)
|
||||
export const IMPORT_JOBS_PATH = BASE_API_ENDPOINT + "/import-jobs";
|
||||
export const IMPORT_JOB_PATH = (jobId: string) => BASE_API_ENDPOINT + "/import-jobs/" + jobId;
|
||||
|
||||
// Workflows
|
||||
export const LIST_WORKFLOWS_PATH = BASE_API_ENDPOINT + "/workflows";
|
||||
export const CREATE_WORKFLOW_PATH = BASE_API_ENDPOINT + "/workflows";
|
||||
export const GET_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id;
|
||||
export const UPDATE_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id;
|
||||
export const DELETE_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id;
|
||||
export const SAVE_WORKFLOW_GRAPH_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/graph";
|
||||
export const RUN_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/run";
|
||||
export const WORKFLOW_RUNS_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/runs";
|
||||
export const EXPORT_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/export";
|
||||
export const IMPORT_WORKFLOW_PATH = BASE_API_ENDPOINT + "/workflows/import";
|
||||
export const WORKFLOW_RUN_DETAIL_PATH = (id: string, runId: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/runs/" + runId;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { createClient } from "@libsql/client";
|
||||
import { drizzle } from "drizzle-orm/libsql";
|
||||
import { migrate } from "drizzle-orm/libsql/migrator";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import * as schema from "./schema";
|
||||
|
||||
const DB_PATH =
|
||||
process.env.APP_DB_PATH || path.join(process.cwd(), "data", "app.db");
|
||||
|
||||
fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
|
||||
|
||||
const client = createClient({ url: `file:${DB_PATH}` });
|
||||
|
||||
export const appDb = drizzle(client, { schema });
|
||||
|
||||
// Run pending migrations automatically on startup.
|
||||
// migrate() is idempotent — safe to call on every boot.
|
||||
export async function runMigrations() {
|
||||
await migrate(appDb, {
|
||||
migrationsFolder: path.join(process.cwd(), "src", "db", "migrations"),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE `api_keys` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`purpose` text NOT NULL,
|
||||
`key_name` text NOT NULL,
|
||||
`secret` text NOT NULL,
|
||||
`immich_key_id` text NOT NULL,
|
||||
`created_at` integer
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `settings` (
|
||||
`key` text PRIMARY KEY NOT NULL,
|
||||
`value` text NOT NULL,
|
||||
`updated_at` integer
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_keys_user_id_purpose_unique` ON `api_keys` (`user_id`,`purpose`);
|
||||
@@ -0,0 +1,28 @@
|
||||
CREATE TABLE `import_job_items` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`job_id` text NOT NULL,
|
||||
`asset_id` text NOT NULL,
|
||||
`status` text DEFAULT 'pending' NOT NULL,
|
||||
`item_data` text DEFAULT '{}' NOT NULL,
|
||||
`immich_id` text,
|
||||
`error` text,
|
||||
`created_at` integer,
|
||||
`updated_at` integer,
|
||||
FOREIGN KEY (`job_id`) REFERENCES `import_jobs`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `import_jobs` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`platform` text NOT NULL,
|
||||
`status` text DEFAULT 'pending' NOT NULL,
|
||||
`url` text NOT NULL,
|
||||
`url_config` text DEFAULT '{}' NOT NULL,
|
||||
`import_data` text DEFAULT '{}' NOT NULL,
|
||||
`total_count` integer DEFAULT 0 NOT NULL,
|
||||
`uploaded_count` integer DEFAULT 0 NOT NULL,
|
||||
`skipped_count` integer DEFAULT 0 NOT NULL,
|
||||
`failed_count` integer DEFAULT 0 NOT NULL,
|
||||
`created_at` integer,
|
||||
`updated_at` integer
|
||||
);
|
||||
@@ -0,0 +1,50 @@
|
||||
CREATE TABLE `workflow_edges` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`workflow_id` text NOT NULL,
|
||||
`source_node_id` text NOT NULL,
|
||||
`target_node_id` text NOT NULL,
|
||||
`source_handle` text,
|
||||
`created_at` integer,
|
||||
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`source_node_id`) REFERENCES `workflow_nodes`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`target_node_id`) REFERENCES `workflow_nodes`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `workflow_nodes` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`workflow_id` text NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`sub_type` text NOT NULL,
|
||||
`data` text DEFAULT '{}' NOT NULL,
|
||||
`position_x` real DEFAULT 0 NOT NULL,
|
||||
`position_y` real DEFAULT 0 NOT NULL,
|
||||
`created_at` integer,
|
||||
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `workflow_runs` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`workflow_id` text NOT NULL,
|
||||
`trigger` text NOT NULL,
|
||||
`status` text DEFAULT 'running' NOT NULL,
|
||||
`result` text DEFAULT '{}',
|
||||
`error` text,
|
||||
`started_at` integer,
|
||||
`completed_at` integer,
|
||||
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `workflows` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`owner_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text,
|
||||
`enabled` integer DEFAULT false NOT NULL,
|
||||
`cron_schedule` text,
|
||||
`webhook_token` text,
|
||||
`viewport` text DEFAULT '{"x":0,"y":0,"zoom":1}' NOT NULL,
|
||||
`created_at` integer,
|
||||
`updated_at` integer
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `workflows_webhook_token_unique` ON `workflows` (`webhook_token`);
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE `workflow_processed_assets` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`workflow_id` text NOT NULL,
|
||||
`asset_id` text NOT NULL,
|
||||
`run_id` text NOT NULL,
|
||||
`processed_at` integer,
|
||||
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`run_id`) REFERENCES `workflow_runs`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
PRAGMA foreign_keys=OFF;--> statement-breakpoint
|
||||
CREATE TABLE `__new_settings` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text NOT NULL,
|
||||
`owner_id` text,
|
||||
`updated_at` integer
|
||||
);--> statement-breakpoint
|
||||
INSERT INTO `__new_settings`("id", "key", "value", "owner_id", "updated_at") SELECT "key", "key", "value", NULL, "updated_at" FROM `settings`;--> statement-breakpoint
|
||||
DROP TABLE `settings`;--> statement-breakpoint
|
||||
ALTER TABLE `__new_settings` RENAME TO `settings`;--> statement-breakpoint
|
||||
PRAGMA foreign_keys=ON;
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "8b257fc8-972b-47da-ae98-7a83316d6df6",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"tables": {
|
||||
"api_keys": {
|
||||
"name": "api_keys",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"purpose": {
|
||||
"name": "purpose",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key_name": {
|
||||
"name": "key_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"immich_key_id": {
|
||||
"name": "immich_key_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"api_keys_user_id_purpose_unique": {
|
||||
"name": "api_keys_user_id_purpose_unique",
|
||||
"columns": [
|
||||
"user_id",
|
||||
"purpose"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
},
|
||||
"settings": {
|
||||
"name": "settings",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "bec76260-a0eb-4895-a32e-244df56b6c2e",
|
||||
"prevId": "8b257fc8-972b-47da-ae98-7a83316d6df6",
|
||||
"tables": {
|
||||
"settings": {
|
||||
"name": "settings",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"api_keys": {
|
||||
"name": "api_keys",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"purpose": {
|
||||
"name": "purpose",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key_name": {
|
||||
"name": "key_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"immich_key_id": {
|
||||
"name": "immich_key_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"api_keys_user_id_purpose_unique": {
|
||||
"name": "api_keys_user_id_purpose_unique",
|
||||
"columns": [
|
||||
"user_id",
|
||||
"purpose"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_job_items": {
|
||||
"name": "import_job_items",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"job_id": {
|
||||
"name": "job_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"item_data": {
|
||||
"name": "item_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"immich_id": {
|
||||
"name": "immich_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"import_job_items_job_id_import_jobs_id_fk": {
|
||||
"name": "import_job_items_job_id_import_jobs_id_fk",
|
||||
"tableFrom": "import_job_items",
|
||||
"tableTo": "import_jobs",
|
||||
"columnsFrom": [
|
||||
"job_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_jobs": {
|
||||
"name": "import_jobs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"platform": {
|
||||
"name": "platform",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"url": {
|
||||
"name": "url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"url_config": {
|
||||
"name": "url_config",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"import_data": {
|
||||
"name": "import_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"total_count": {
|
||||
"name": "total_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"uploaded_count": {
|
||||
"name": "uploaded_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"skipped_count": {
|
||||
"name": "skipped_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"failed_count": {
|
||||
"name": "failed_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,661 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "fcc0b754-0e0f-4a14-9375-0fce84bf107f",
|
||||
"prevId": "bec76260-a0eb-4895-a32e-244df56b6c2e",
|
||||
"tables": {
|
||||
"settings": {
|
||||
"name": "settings",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"api_keys": {
|
||||
"name": "api_keys",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"purpose": {
|
||||
"name": "purpose",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key_name": {
|
||||
"name": "key_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"immich_key_id": {
|
||||
"name": "immich_key_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"api_keys_user_id_purpose_unique": {
|
||||
"name": "api_keys_user_id_purpose_unique",
|
||||
"columns": [
|
||||
"user_id",
|
||||
"purpose"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_job_items": {
|
||||
"name": "import_job_items",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"job_id": {
|
||||
"name": "job_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"item_data": {
|
||||
"name": "item_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"immich_id": {
|
||||
"name": "immich_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"import_job_items_job_id_import_jobs_id_fk": {
|
||||
"name": "import_job_items_job_id_import_jobs_id_fk",
|
||||
"tableFrom": "import_job_items",
|
||||
"tableTo": "import_jobs",
|
||||
"columnsFrom": [
|
||||
"job_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_jobs": {
|
||||
"name": "import_jobs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"platform": {
|
||||
"name": "platform",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"url": {
|
||||
"name": "url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"url_config": {
|
||||
"name": "url_config",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"import_data": {
|
||||
"name": "import_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"total_count": {
|
||||
"name": "total_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"uploaded_count": {
|
||||
"name": "uploaded_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"skipped_count": {
|
||||
"name": "skipped_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"failed_count": {
|
||||
"name": "failed_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_edges": {
|
||||
"name": "workflow_edges",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source_node_id": {
|
||||
"name": "source_node_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"target_node_id": {
|
||||
"name": "target_node_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source_handle": {
|
||||
"name": "source_handle",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_edges_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_edges_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_edges_source_node_id_workflow_nodes_id_fk": {
|
||||
"name": "workflow_edges_source_node_id_workflow_nodes_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflow_nodes",
|
||||
"columnsFrom": [
|
||||
"source_node_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_edges_target_node_id_workflow_nodes_id_fk": {
|
||||
"name": "workflow_edges_target_node_id_workflow_nodes_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflow_nodes",
|
||||
"columnsFrom": [
|
||||
"target_node_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_nodes": {
|
||||
"name": "workflow_nodes",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"sub_type": {
|
||||
"name": "sub_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"data": {
|
||||
"name": "data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"position_x": {
|
||||
"name": "position_x",
|
||||
"type": "real",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"position_y": {
|
||||
"name": "position_y",
|
||||
"type": "real",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_nodes_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_nodes_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_nodes",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_runs": {
|
||||
"name": "workflow_runs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"trigger": {
|
||||
"name": "trigger",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'running'"
|
||||
},
|
||||
"result": {
|
||||
"name": "result",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"started_at": {
|
||||
"name": "started_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"completed_at": {
|
||||
"name": "completed_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_runs_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_runs_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_runs",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflows": {
|
||||
"name": "workflows",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"owner_id": {
|
||||
"name": "owner_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"cron_schedule": {
|
||||
"name": "cron_schedule",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"webhook_token": {
|
||||
"name": "webhook_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"viewport": {
|
||||
"name": "viewport",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{\"x\":0,\"y\":0,\"zoom\":1}'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"workflows_webhook_token_unique": {
|
||||
"name": "workflows_webhook_token_unique",
|
||||
"columns": [
|
||||
"webhook_token"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "f760ba33-ed15-4972-8578-51644001b8ed",
|
||||
"prevId": "fcc0b754-0e0f-4a14-9375-0fce84bf107f",
|
||||
"tables": {
|
||||
"settings": {
|
||||
"name": "settings",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"api_keys": {
|
||||
"name": "api_keys",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"purpose": {
|
||||
"name": "purpose",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key_name": {
|
||||
"name": "key_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"immich_key_id": {
|
||||
"name": "immich_key_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"api_keys_user_id_purpose_unique": {
|
||||
"name": "api_keys_user_id_purpose_unique",
|
||||
"columns": [
|
||||
"user_id",
|
||||
"purpose"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_job_items": {
|
||||
"name": "import_job_items",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"job_id": {
|
||||
"name": "job_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"item_data": {
|
||||
"name": "item_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"immich_id": {
|
||||
"name": "immich_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"import_job_items_job_id_import_jobs_id_fk": {
|
||||
"name": "import_job_items_job_id_import_jobs_id_fk",
|
||||
"tableFrom": "import_job_items",
|
||||
"tableTo": "import_jobs",
|
||||
"columnsFrom": [
|
||||
"job_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_jobs": {
|
||||
"name": "import_jobs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"platform": {
|
||||
"name": "platform",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"url": {
|
||||
"name": "url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"url_config": {
|
||||
"name": "url_config",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"import_data": {
|
||||
"name": "import_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"total_count": {
|
||||
"name": "total_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"uploaded_count": {
|
||||
"name": "uploaded_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"skipped_count": {
|
||||
"name": "skipped_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"failed_count": {
|
||||
"name": "failed_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_edges": {
|
||||
"name": "workflow_edges",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source_node_id": {
|
||||
"name": "source_node_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"target_node_id": {
|
||||
"name": "target_node_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source_handle": {
|
||||
"name": "source_handle",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_edges_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_edges_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_edges_source_node_id_workflow_nodes_id_fk": {
|
||||
"name": "workflow_edges_source_node_id_workflow_nodes_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflow_nodes",
|
||||
"columnsFrom": [
|
||||
"source_node_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_edges_target_node_id_workflow_nodes_id_fk": {
|
||||
"name": "workflow_edges_target_node_id_workflow_nodes_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflow_nodes",
|
||||
"columnsFrom": [
|
||||
"target_node_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_nodes": {
|
||||
"name": "workflow_nodes",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"sub_type": {
|
||||
"name": "sub_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"data": {
|
||||
"name": "data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"position_x": {
|
||||
"name": "position_x",
|
||||
"type": "real",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"position_y": {
|
||||
"name": "position_y",
|
||||
"type": "real",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_nodes_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_nodes_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_nodes",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_processed_assets": {
|
||||
"name": "workflow_processed_assets",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"run_id": {
|
||||
"name": "run_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"processed_at": {
|
||||
"name": "processed_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_processed_assets_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_processed_assets_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_processed_assets",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_processed_assets_run_id_workflow_runs_id_fk": {
|
||||
"name": "workflow_processed_assets_run_id_workflow_runs_id_fk",
|
||||
"tableFrom": "workflow_processed_assets",
|
||||
"tableTo": "workflow_runs",
|
||||
"columnsFrom": [
|
||||
"run_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_runs": {
|
||||
"name": "workflow_runs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"trigger": {
|
||||
"name": "trigger",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'running'"
|
||||
},
|
||||
"result": {
|
||||
"name": "result",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"started_at": {
|
||||
"name": "started_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"completed_at": {
|
||||
"name": "completed_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_runs_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_runs_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_runs",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflows": {
|
||||
"name": "workflows",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"owner_id": {
|
||||
"name": "owner_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"cron_schedule": {
|
||||
"name": "cron_schedule",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"webhook_token": {
|
||||
"name": "webhook_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"viewport": {
|
||||
"name": "viewport",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{\"x\":0,\"y\":0,\"zoom\":1}'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"workflows_webhook_token_unique": {
|
||||
"name": "workflows_webhook_token_unique",
|
||||
"columns": [
|
||||
"webhook_token"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,747 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "c9948313-c4b4-4db4-8975-8c409c20379e",
|
||||
"prevId": "f760ba33-ed15-4972-8578-51644001b8ed",
|
||||
"tables": {
|
||||
"settings": {
|
||||
"name": "settings",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"owner_id": {
|
||||
"name": "owner_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"api_keys": {
|
||||
"name": "api_keys",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"purpose": {
|
||||
"name": "purpose",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key_name": {
|
||||
"name": "key_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"immich_key_id": {
|
||||
"name": "immich_key_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"api_keys_user_id_purpose_unique": {
|
||||
"name": "api_keys_user_id_purpose_unique",
|
||||
"columns": [
|
||||
"user_id",
|
||||
"purpose"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_job_items": {
|
||||
"name": "import_job_items",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"job_id": {
|
||||
"name": "job_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"item_data": {
|
||||
"name": "item_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"immich_id": {
|
||||
"name": "immich_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"import_job_items_job_id_import_jobs_id_fk": {
|
||||
"name": "import_job_items_job_id_import_jobs_id_fk",
|
||||
"tableFrom": "import_job_items",
|
||||
"tableTo": "import_jobs",
|
||||
"columnsFrom": [
|
||||
"job_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"import_jobs": {
|
||||
"name": "import_jobs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"platform": {
|
||||
"name": "platform",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'pending'"
|
||||
},
|
||||
"url": {
|
||||
"name": "url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"url_config": {
|
||||
"name": "url_config",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"import_data": {
|
||||
"name": "import_data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"total_count": {
|
||||
"name": "total_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"uploaded_count": {
|
||||
"name": "uploaded_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"skipped_count": {
|
||||
"name": "skipped_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"failed_count": {
|
||||
"name": "failed_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_edges": {
|
||||
"name": "workflow_edges",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source_node_id": {
|
||||
"name": "source_node_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"target_node_id": {
|
||||
"name": "target_node_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source_handle": {
|
||||
"name": "source_handle",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_edges_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_edges_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_edges_source_node_id_workflow_nodes_id_fk": {
|
||||
"name": "workflow_edges_source_node_id_workflow_nodes_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflow_nodes",
|
||||
"columnsFrom": [
|
||||
"source_node_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_edges_target_node_id_workflow_nodes_id_fk": {
|
||||
"name": "workflow_edges_target_node_id_workflow_nodes_id_fk",
|
||||
"tableFrom": "workflow_edges",
|
||||
"tableTo": "workflow_nodes",
|
||||
"columnsFrom": [
|
||||
"target_node_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_nodes": {
|
||||
"name": "workflow_nodes",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"sub_type": {
|
||||
"name": "sub_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"data": {
|
||||
"name": "data",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"position_x": {
|
||||
"name": "position_x",
|
||||
"type": "real",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"position_y": {
|
||||
"name": "position_y",
|
||||
"type": "real",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_nodes_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_nodes_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_nodes",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_processed_assets": {
|
||||
"name": "workflow_processed_assets",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"run_id": {
|
||||
"name": "run_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"processed_at": {
|
||||
"name": "processed_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_processed_assets_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_processed_assets_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_processed_assets",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"workflow_processed_assets_run_id_workflow_runs_id_fk": {
|
||||
"name": "workflow_processed_assets_run_id_workflow_runs_id_fk",
|
||||
"tableFrom": "workflow_processed_assets",
|
||||
"tableTo": "workflow_runs",
|
||||
"columnsFrom": [
|
||||
"run_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflow_runs": {
|
||||
"name": "workflow_runs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"workflow_id": {
|
||||
"name": "workflow_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"trigger": {
|
||||
"name": "trigger",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'running'"
|
||||
},
|
||||
"result": {
|
||||
"name": "result",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": "'{}'"
|
||||
},
|
||||
"error": {
|
||||
"name": "error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"started_at": {
|
||||
"name": "started_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"completed_at": {
|
||||
"name": "completed_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"workflow_runs_workflow_id_workflows_id_fk": {
|
||||
"name": "workflow_runs_workflow_id_workflows_id_fk",
|
||||
"tableFrom": "workflow_runs",
|
||||
"tableTo": "workflows",
|
||||
"columnsFrom": [
|
||||
"workflow_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"workflows": {
|
||||
"name": "workflows",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"owner_id": {
|
||||
"name": "owner_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"cron_schedule": {
|
||||
"name": "cron_schedule",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"webhook_token": {
|
||||
"name": "webhook_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"viewport": {
|
||||
"name": "viewport",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'{\"x\":0,\"y\":0,\"zoom\":1}'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"workflows_webhook_token_unique": {
|
||||
"name": "workflows_webhook_token_unique",
|
||||
"columns": [
|
||||
"webhook_token"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": "5",
|
||||
"dialect": "sqlite",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "6",
|
||||
"when": 1774242821856,
|
||||
"tag": "0000_vengeful_kylun",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "6",
|
||||
"when": 1775227109706,
|
||||
"tag": "0001_rainy_jamie_braddock",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "6",
|
||||
"when": 1775560183481,
|
||||
"tag": "0002_thin_triton",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "6",
|
||||
"when": 1775567654903,
|
||||
"tag": "0003_spooky_lockheed",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "6",
|
||||
"when": 1775574030092,
|
||||
"tag": "0004_equal_iron_monger",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { sqliteTable, text, integer, unique } from "drizzle-orm/sqlite-core";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export const apiKeys = sqliteTable("api_keys", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
userId: text("user_id").notNull(),
|
||||
purpose: text("purpose").notNull(),
|
||||
keyName: text("key_name").notNull(),
|
||||
secret: text("secret").notNull(),
|
||||
immichKeyId: text("immich_key_id").notNull(),
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
}, (t) => [
|
||||
unique().on(t.userId, t.purpose),
|
||||
]);
|
||||
@@ -0,0 +1,34 @@
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
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'
|
||||
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.)
|
||||
importData: text("import_data").notNull().default("{}"), // JSON: album options, resolved albumId, etc.
|
||||
totalCount: integer("total_count").notNull().default(0),
|
||||
uploadedCount: integer("uploaded_count").notNull().default(0),
|
||||
skippedCount: integer("skipped_count").notNull().default(0),
|
||||
failedCount: integer("failed_count").notNull().default(0),
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
.$defaultFn(() => new Date())
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const importJobItems = sqliteTable("import_job_items", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
jobId: text("job_id").notNull().references(() => importJobs.id),
|
||||
assetId: text("asset_id").notNull(), // source platform's asset ID
|
||||
status: text("status").notNull().default("pending"), // pending | processing | uploaded | skipped | failed
|
||||
itemData: text("item_data").notNull().default("{}"), // JSON: filename, type, dates, isFavorite, etc.
|
||||
immichId: text("immich_id"), // Immich asset ID after successful upload
|
||||
error: text("error"),
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
.$defaultFn(() => new Date())
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./settings.schema";
|
||||
export * from "./apiKeys.schema";
|
||||
export * from "./importJobs.schema";
|
||||
export * from "./workflows.schema";
|
||||
@@ -0,0 +1,12 @@
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export const settings = sqliteTable("settings", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
key: text("key").notNull(),
|
||||
value: text("value").notNull(),
|
||||
ownerId: text("owner_id"),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" }).$onUpdate(
|
||||
() => new Date()
|
||||
),
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { sqliteTable, text, integer, real } from "drizzle-orm/sqlite-core";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export const workflows = sqliteTable("workflows", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
ownerId: text("owner_id").notNull(),
|
||||
name: text("name").notNull(),
|
||||
description: text("description"),
|
||||
enabled: integer("enabled", { mode: "boolean" }).notNull().default(false),
|
||||
cronSchedule: text("cron_schedule"),
|
||||
webhookToken: text("webhook_token").unique(),
|
||||
viewport: text("viewport").notNull().default('{"x":0,"y":0,"zoom":1}'),
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
.$defaultFn(() => new Date())
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const workflowNodes = sqliteTable("workflow_nodes", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
|
||||
type: text("type").notNull(),
|
||||
subType: text("sub_type").notNull(),
|
||||
data: text("data").notNull().default("{}"),
|
||||
positionX: real("position_x").notNull().default(0),
|
||||
positionY: real("position_y").notNull().default(0),
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
});
|
||||
|
||||
export const workflowEdges = sqliteTable("workflow_edges", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
|
||||
sourceNodeId: text("source_node_id").notNull().references(() => workflowNodes.id, { onDelete: "cascade" }),
|
||||
targetNodeId: text("target_node_id").notNull().references(() => workflowNodes.id, { onDelete: "cascade" }),
|
||||
sourceHandle: text("source_handle"),
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
});
|
||||
|
||||
export const workflowRuns = sqliteTable("workflow_runs", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
|
||||
trigger: text("trigger").notNull(),
|
||||
status: text("status").notNull().default("running"),
|
||||
result: text("result").default("{}"),
|
||||
error: text("error"),
|
||||
startedAt: integer("started_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
completedAt: integer("completed_at", { mode: "timestamp" }),
|
||||
});
|
||||
|
||||
export const workflowProcessedAssets = sqliteTable("workflow_processed_assets", {
|
||||
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
|
||||
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
|
||||
assetId: text("asset_id").notNull(),
|
||||
runId: text("run_id").notNull().references(() => workflowRuns.id, { onDelete: "cascade" }),
|
||||
processedAt: integer("processed_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
});
|
||||
@@ -57,4 +57,8 @@ export const deleteAlbums = async (albumIds: string[]) => {
|
||||
|
||||
export const mergeAlbums = async (primaryAlbumId: string, secondaryAlbumIds: string[]) => {
|
||||
return API.post(MERGE_ALBUMS_PATH, { primaryAlbumId, secondaryAlbumIds });
|
||||
}
|
||||
|
||||
export const createAlbumWithAssets = async (albumName: string, assetIds: string[]) => {
|
||||
return API.post(CREATE_ALBUM_PATH, { albumName, assetIds });
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
LIST_MISSING_LOCATION_DATES_PATH,
|
||||
UPDATE_ASSETS_PATH,
|
||||
LIST_DUPLICATES_PATH,
|
||||
LIST_ORPHAN_ASSETS_PATH,
|
||||
} from "@/config/routes";
|
||||
import { cleanUpAsset } from "@/helpers/asset.helper";
|
||||
import API from "@/lib/api";
|
||||
@@ -54,6 +55,7 @@ export interface IUpdateAssetsParams {
|
||||
longitude?: number;
|
||||
dateTimeOriginal?: string;
|
||||
duplicateId?: string | null;
|
||||
isFavorite?: boolean;
|
||||
}
|
||||
|
||||
export const updateAssets = async (params: IUpdateAssetsParams) => {
|
||||
@@ -101,3 +103,25 @@ export interface IAssetAlbumInfo {
|
||||
export const getAlbumsByAssetIds = async (assetIds: string[]): Promise<Record<string, IAssetAlbumInfo[]>> => {
|
||||
return API.post(ASSET_ALBUMS_BY_ASSETS_PATH, { assetIds });
|
||||
}
|
||||
|
||||
export interface IOrphanFilters {
|
||||
notInAlbum?: boolean;
|
||||
noPeople?: boolean;
|
||||
noLocation?: boolean;
|
||||
notFavorited?: boolean;
|
||||
type?: string;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export const listOrphanAssets = async (filters: IOrphanFilters): Promise<IAsset[]> => {
|
||||
const params: Record<string, string> = {};
|
||||
if (filters.notInAlbum) params.notInAlbum = "true";
|
||||
if (filters.noPeople) params.noPeople = "true";
|
||||
if (filters.noLocation) params.noLocation = "true";
|
||||
if (filters.notFavorited) params.notFavorited = "true";
|
||||
if (filters.type) params.type = filters.type;
|
||||
if (filters.limit) params.limit = String(filters.limit);
|
||||
if (filters.page) params.page = String(filters.page);
|
||||
return API.get(LIST_ORPHAN_ASSETS_PATH, params).then((assets) => assets.map(cleanUpAsset));
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { IMPORT_JOBS_PATH, IMPORT_JOB_PATH } from "@/config/routes";
|
||||
import API from "@/lib/api";
|
||||
|
||||
export interface CreateImportJobParams {
|
||||
platform: string;
|
||||
url: string;
|
||||
urlConfig: Record<string, unknown>;
|
||||
importData: Record<string, unknown>;
|
||||
assets: { id: string; [key: string]: unknown }[];
|
||||
}
|
||||
|
||||
export const createImportJob = async (params: CreateImportJobParams): Promise<{ jobId: string }> => {
|
||||
return API.post(IMPORT_JOBS_PATH, params);
|
||||
};
|
||||
|
||||
export interface ImportJobSummary {
|
||||
id: string;
|
||||
platform: string;
|
||||
status: string;
|
||||
url: string;
|
||||
importData: string;
|
||||
totalCount: number;
|
||||
uploadedCount: number;
|
||||
skippedCount: number;
|
||||
failedCount: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export const listImportJobs = async (): Promise<{ jobs: ImportJobSummary[] }> => {
|
||||
return API.get(IMPORT_JOBS_PATH);
|
||||
};
|
||||
|
||||
export interface ImportJobStatus {
|
||||
job: {
|
||||
id: string;
|
||||
status: string;
|
||||
platform: string;
|
||||
totalCount: number;
|
||||
uploadedCount: number;
|
||||
skippedCount: number;
|
||||
failedCount: number;
|
||||
importData: string;
|
||||
};
|
||||
items: {
|
||||
id: string;
|
||||
assetId: string;
|
||||
status: string;
|
||||
itemData: string;
|
||||
immichId: string | null;
|
||||
error: string | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
export const getImportJob = async (jobId: string): Promise<ImportJobStatus> => {
|
||||
return API.get(IMPORT_JOB_PATH(jobId));
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import { IMPORT_SHARED_PATH } from "@/config/routes";
|
||||
import API from "@/lib/api";
|
||||
|
||||
export const importShared = async (link: string, password?: string) => {
|
||||
return API.post(IMPORT_SHARED_PATH, { link, password: password || undefined });
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { SETTINGS_API_KEYS_PATH, SETTINGS_API_KEY_PATH } from "@/config/routes";
|
||||
import API from "@/lib/api";
|
||||
|
||||
export const getApiKeys = async () => {
|
||||
return API.get(SETTINGS_API_KEYS_PATH);
|
||||
};
|
||||
|
||||
export const deleteApiKey = async (purpose: string) => {
|
||||
return API.delete(SETTINGS_API_KEY_PATH(purpose));
|
||||
};
|
||||
|
||||
export const regenerateApiKey = async (purpose: string) => {
|
||||
return API.put(SETTINGS_API_KEY_PATH(purpose));
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { SHARE_KEY_PATH } from "@/config/routes";
|
||||
import API from "@/lib/api";
|
||||
|
||||
export const getShareKey = async () => {
|
||||
return API.get(SHARE_KEY_PATH);
|
||||
};
|
||||
|
||||
export const createShareKey = async () => {
|
||||
return API.post(SHARE_KEY_PATH);
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { VALIDATE_PERMISSIONS_PATH } from "@/config/routes";
|
||||
import API from "@/lib/api";
|
||||
|
||||
export interface PermissionsResult {
|
||||
canUpload: boolean;
|
||||
}
|
||||
|
||||
export const validatePermissions = async (): Promise<PermissionsResult> => {
|
||||
return API.get(VALIDATE_PERMISSIONS_PATH);
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
LIST_WORKFLOWS_PATH,
|
||||
CREATE_WORKFLOW_PATH,
|
||||
GET_WORKFLOW_PATH,
|
||||
UPDATE_WORKFLOW_PATH,
|
||||
DELETE_WORKFLOW_PATH,
|
||||
SAVE_WORKFLOW_GRAPH_PATH,
|
||||
RUN_WORKFLOW_PATH,
|
||||
WORKFLOW_RUNS_PATH,
|
||||
EXPORT_WORKFLOW_PATH,
|
||||
IMPORT_WORKFLOW_PATH,
|
||||
} from "@/config/routes";
|
||||
import API from "@/lib/api";
|
||||
import { IWorkflow, IWorkflowWithDetails, IWorkflowRun, IWorkflowExport } from "@/types/workflow";
|
||||
|
||||
export const listWorkflows = async (): Promise<IWorkflow[]> => {
|
||||
return API.get(LIST_WORKFLOWS_PATH);
|
||||
};
|
||||
|
||||
export const createWorkflow = async (data: { name: string; description?: string }): Promise<IWorkflow> => {
|
||||
return API.post(CREATE_WORKFLOW_PATH, data);
|
||||
};
|
||||
|
||||
export const getWorkflow = async (id: string): Promise<IWorkflowWithDetails> => {
|
||||
return API.get(GET_WORKFLOW_PATH(id));
|
||||
};
|
||||
|
||||
export const updateWorkflow = async (id: string, data: Partial<IWorkflow>): Promise<IWorkflow> => {
|
||||
return API.put(UPDATE_WORKFLOW_PATH(id), data);
|
||||
};
|
||||
|
||||
export const deleteWorkflow = async (id: string): Promise<void> => {
|
||||
return API.delete(DELETE_WORKFLOW_PATH(id));
|
||||
};
|
||||
|
||||
export const saveWorkflowGraph = async (
|
||||
id: string,
|
||||
data: { nodes: any[]; edges: any[]; viewport?: any }
|
||||
): Promise<void> => {
|
||||
return API.put(SAVE_WORKFLOW_GRAPH_PATH(id), data);
|
||||
};
|
||||
|
||||
export const runWorkflow = async (id: string, mode?: "manual" | "debug"): Promise<IWorkflowRun> => {
|
||||
return API.post(RUN_WORKFLOW_PATH(id), { mode });
|
||||
};
|
||||
|
||||
export const getWorkflowRuns = async (id: string): Promise<IWorkflowRun[]> => {
|
||||
return API.get(WORKFLOW_RUNS_PATH(id));
|
||||
};
|
||||
|
||||
export const exportWorkflow = async (id: string): Promise<IWorkflowExport> => {
|
||||
return API.get(EXPORT_WORKFLOW_PATH(id));
|
||||
};
|
||||
|
||||
export const importWorkflow = async (data: IWorkflowExport): Promise<IWorkflow> => {
|
||||
return API.post(IMPORT_WORKFLOW_PATH, data);
|
||||
};
|
||||
@@ -3,7 +3,6 @@ import { IUser } from "@/types/user"
|
||||
|
||||
export const getUserHeaders = (user: {
|
||||
isUsingAPIKey?: boolean,
|
||||
isUsingShareKey?: boolean,
|
||||
accessToken?: string
|
||||
}, otherHeaders?: {
|
||||
'Content-Type': string
|
||||
@@ -15,9 +14,7 @@ export const getUserHeaders = (user: {
|
||||
} = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if (user.isUsingShareKey) {
|
||||
headers['x-api-key'] = ENV.IMMICH_SHARE_LINK_KEY
|
||||
} else if (user.isUsingAPIKey) {
|
||||
if (user.isUsingAPIKey) {
|
||||
headers['x-api-key'] = ENV.IMMICH_API_KEY
|
||||
} else {
|
||||
headers['Authorization'] = `Bearer ${user.accessToken}`
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export async function register() {
|
||||
// Only run on the Node.js server, not in the Edge runtime or client
|
||||
if (process.env.NEXT_RUNTIME === "nodejs") {
|
||||
const { runMigrations } = await import("./db");
|
||||
await runMigrations();
|
||||
|
||||
const { resumePendingJobs } = await import("./workers/import/runner");
|
||||
await resumePendingJobs();
|
||||
|
||||
const { loadAllScheduledWorkflows } = await import("./lib/workflow/scheduler");
|
||||
await loadAllScheduledWorkflows();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { ENV } from "@/config/environment";
|
||||
import { db } from "@/config/db";
|
||||
import { appDb } from "@/db";
|
||||
import { settings } from "@/db/schema/settings.schema";
|
||||
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 { IUser } from "@/types/user";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
|
||||
export const WORKFLOW_API_KEY_SETTING = "workflow_api_key";
|
||||
|
||||
interface ActionResult {
|
||||
action: string;
|
||||
assetsProcessed: number;
|
||||
albumId?: string;
|
||||
albumName?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
async function getWorkflowApiKey(ownerId: string): Promise<string | null> {
|
||||
const [row] = await appDb
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(and(eq(settings.key, WORKFLOW_API_KEY_SETTING), eq(settings.ownerId, ownerId)));
|
||||
return row?.value || null;
|
||||
}
|
||||
|
||||
async function immichFetch(path: string, method: string, body: any, user: IUser): Promise<any> {
|
||||
const workflowApiKey = await getWorkflowApiKey(user.id);
|
||||
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (workflowApiKey) {
|
||||
headers["x-api-key"] = workflowApiKey;
|
||||
} else {
|
||||
const userHeaders = getUserHeaders(user);
|
||||
Object.assign(headers, userHeaders);
|
||||
}
|
||||
|
||||
const res = await fetch(`${ENV.IMMICH_URL}/api${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`Immich API error ${res.status}: ${text}`);
|
||||
}
|
||||
const contentType = res.headers.get("content-type");
|
||||
if (contentType?.includes("application/json")) {
|
||||
return res.json();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function resolveTemplate(template: string, assetIds: string[]): Promise<string> {
|
||||
if (!template || assetIds.length === 0) return template;
|
||||
|
||||
let result = template;
|
||||
|
||||
if (result.includes("{city}") || result.includes("{state}") || result.includes("{country}") || result.includes("{camera}")) {
|
||||
// Get most common EXIF values
|
||||
const exifRows = await db
|
||||
.select({
|
||||
city: exif.city,
|
||||
state: exif.state,
|
||||
country: exif.country,
|
||||
make: exif.make,
|
||||
model: exif.model,
|
||||
})
|
||||
.from(exif)
|
||||
.where(inArray(exif.assetId, assetIds))
|
||||
.limit(100);
|
||||
|
||||
const mostCommon = (values: (string | null)[]) => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const v of values) {
|
||||
if (v) counts.set(v, (counts.get(v) || 0) + 1);
|
||||
}
|
||||
let best = "";
|
||||
let bestCount = 0;
|
||||
for (const [v, c] of counts) {
|
||||
if (c > bestCount) { best = v; bestCount = c; }
|
||||
}
|
||||
return best || "Unknown";
|
||||
};
|
||||
|
||||
result = result.replace("{city}", mostCommon(exifRows.map((r) => r.city)));
|
||||
result = result.replace("{state}", mostCommon(exifRows.map((r) => r.state)));
|
||||
result = result.replace("{country}", mostCommon(exifRows.map((r) => r.country)));
|
||||
result = result.replace("{camera}", mostCommon(exifRows.map((r) => [r.make, r.model].filter(Boolean).join(" "))));
|
||||
}
|
||||
|
||||
if (result.includes("{date}")) {
|
||||
const today = new Date();
|
||||
result = result.replace("{date}", today.toISOString().split("T")[0]);
|
||||
}
|
||||
|
||||
if (result.includes("{person}")) {
|
||||
const faces = await db
|
||||
.select({ name: person.name })
|
||||
.from(assetFaces)
|
||||
.innerJoin(person, eq(assetFaces.personId, person.id))
|
||||
.where(inArray(assetFaces.assetId, assetIds))
|
||||
.limit(100);
|
||||
|
||||
const names = faces.map((f) => f.name).filter(Boolean);
|
||||
const mostCommon = (values: string[]) => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const v of values) counts.set(v, (counts.get(v) || 0) + 1);
|
||||
let best = "";
|
||||
let bestCount = 0;
|
||||
for (const [v, c] of counts) {
|
||||
if (c > bestCount) { best = v; bestCount = c; }
|
||||
}
|
||||
return best || "Unknown";
|
||||
};
|
||||
result = result.replace("{person}", mostCommon(names));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function executeAction(
|
||||
subType: string,
|
||||
config: any,
|
||||
assetIds: string[],
|
||||
user: IUser
|
||||
): Promise<ActionResult> {
|
||||
if (assetIds.length === 0) {
|
||||
return { action: subType, assetsProcessed: 0 };
|
||||
}
|
||||
|
||||
switch (subType) {
|
||||
case "create_album": {
|
||||
const albumName = await resolveTemplate(config.nameTemplate || "Auto Album", assetIds);
|
||||
const album = await immichFetch("/albums", "POST", { albumName, assetIds }, 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);
|
||||
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);
|
||||
return { action: "remove_from_album", assetsProcessed: assetIds.length, albumId: config.albumId };
|
||||
}
|
||||
|
||||
case "favorite": {
|
||||
await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: true }, user);
|
||||
return { action: "favorite", assetsProcessed: assetIds.length };
|
||||
}
|
||||
|
||||
case "unfavorite": {
|
||||
await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: false }, user);
|
||||
return { action: "unfavorite", assetsProcessed: assetIds.length };
|
||||
}
|
||||
|
||||
case "archive": {
|
||||
await immichFetch("/assets", "PUT", { ids: assetIds, isArchived: true }, 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);
|
||||
// Tag assets
|
||||
await immichFetch(`/tags/${tag.id}/assets`, "PUT", { ids: assetIds }, user);
|
||||
return { action: "tag", assetsProcessed: assetIds.length };
|
||||
} catch (e: any) {
|
||||
return { action: "tag", assetsProcessed: 0, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return { action: subType, assetsProcessed: 0, error: `Unknown action: ${subType}` };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { SQL, and, eq, ne, gte, lte, isNull, sql } from "drizzle-orm";
|
||||
import { assets } from "@/schema/assets.schema";
|
||||
import { exif } from "@/schema";
|
||||
import { ICondition } from "@/types/workflow";
|
||||
import { subDays } from "date-fns";
|
||||
|
||||
export function buildConditions(conditions: ICondition[], ownerId: string): SQL[] {
|
||||
const clauses: SQL[] = [
|
||||
eq(assets.ownerId, ownerId),
|
||||
eq(assets.visibility, "timeline"),
|
||||
eq(assets.status, "active"),
|
||||
isNull(assets.deletedAt),
|
||||
];
|
||||
|
||||
for (const c of conditions) {
|
||||
const clause = buildSingleCondition(c);
|
||||
if (clause) clauses.push(clause);
|
||||
}
|
||||
|
||||
return clauses;
|
||||
}
|
||||
|
||||
function buildSingleCondition(c: ICondition): SQL | undefined {
|
||||
switch (c.type) {
|
||||
case "city":
|
||||
return c.match === "not_equals"
|
||||
? ne(exif.city, c.city)
|
||||
: eq(exif.city, c.city);
|
||||
|
||||
case "state":
|
||||
return c.match === "not_equals"
|
||||
? ne(exif.state, c.state)
|
||||
: eq(exif.state, c.state);
|
||||
|
||||
case "country":
|
||||
return c.match === "not_equals"
|
||||
? ne(exif.country, c.country)
|
||||
: eq(exif.country, c.country);
|
||||
|
||||
case "camera_make":
|
||||
return eq(exif.make, c.make);
|
||||
|
||||
case "camera_model":
|
||||
return eq(exif.model, c.model);
|
||||
|
||||
case "lens":
|
||||
return eq(exif.lensModel, c.lensModel);
|
||||
|
||||
case "asset_type":
|
||||
return eq(assets.type, c.assetType || "IMAGE");
|
||||
|
||||
case "is_favorited":
|
||||
return eq(assets.isFavorite, c.value !== false);
|
||||
|
||||
case "date_range": {
|
||||
const parts: SQL[] = [];
|
||||
if (c.after) parts.push(gte(exif.dateTimeOriginal, new Date(c.after)));
|
||||
if (c.before) parts.push(lte(exif.dateTimeOriginal, new Date(c.before)));
|
||||
return parts.length > 0 ? and(...parts)! : undefined;
|
||||
}
|
||||
|
||||
case "date_relative":
|
||||
if (c.lastDays) {
|
||||
return gte(exif.dateTimeOriginal, subDays(new Date(), c.lastDays));
|
||||
}
|
||||
return undefined;
|
||||
|
||||
case "day_of_week":
|
||||
if (c.days && c.days.length > 0) {
|
||||
return sql`EXTRACT(DOW FROM ${exif.dateTimeOriginal}) IN (${sql.raw(c.days.join(","))})`;
|
||||
}
|
||||
return undefined;
|
||||
|
||||
case "iso_range": {
|
||||
const parts: SQL[] = [];
|
||||
if (c.min !== undefined) parts.push(gte(exif.iso, c.min));
|
||||
if (c.max !== undefined) parts.push(lte(exif.iso, c.max));
|
||||
return parts.length > 0 ? and(...parts)! : undefined;
|
||||
}
|
||||
|
||||
case "focal_length": {
|
||||
const parts: SQL[] = [];
|
||||
if (c.min !== undefined) parts.push(gte(exif.focalLength, c.min));
|
||||
if (c.max !== undefined) parts.push(lte(exif.focalLength, c.max));
|
||||
return parts.length > 0 ? and(...parts)! : undefined;
|
||||
}
|
||||
|
||||
case "rating": {
|
||||
const parts: SQL[] = [];
|
||||
if (c.min !== undefined) parts.push(gte(exif.rating, c.min));
|
||||
if (c.max !== undefined) parts.push(lte(exif.rating, c.max));
|
||||
return parts.length > 0 ? and(...parts)! : undefined;
|
||||
}
|
||||
|
||||
case "person": {
|
||||
const ids: string[] = c.personIds || (c.personId ? [c.personId] : []);
|
||||
if (ids.length === 0) return undefined;
|
||||
|
||||
if (c.match === "not_contains") {
|
||||
// Asset must not contain ANY of these people
|
||||
const checks = ids.map((pid: string) =>
|
||||
sql`NOT EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" = ${pid})`
|
||||
);
|
||||
return and(...checks)!;
|
||||
}
|
||||
|
||||
if (c.match === "contains_all") {
|
||||
// Asset must contain ALL of these people
|
||||
const checks = ids.map((pid: string) =>
|
||||
sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" = ${pid})`
|
||||
);
|
||||
return and(...checks)!;
|
||||
}
|
||||
|
||||
// contains_any (default) — asset contains at least one of these people
|
||||
const idList = ids.map((id: string) => `'${id}'`).join(",");
|
||||
return sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IN (${sql.raw(idList)}))`;
|
||||
}
|
||||
|
||||
case "person_unnamed":
|
||||
if (c.match === "no_unnamed") {
|
||||
return sql`NOT EXISTS (SELECT 1 FROM "asset_face" af JOIN "person" p ON af."personId" = p.id WHERE af."assetId" = ${assets.id} AND (p.name = '' OR p.name IS NULL))`;
|
||||
}
|
||||
return sql`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))`;
|
||||
|
||||
case "not_in_album":
|
||||
return sql`NOT EXISTS (SELECT 1 FROM "album_asset" aa WHERE aa."assetId" = ${assets.id})`;
|
||||
|
||||
case "not_in_specific_album":
|
||||
return sql`NOT EXISTS (SELECT 1 FROM "album_asset" aa WHERE aa."assetId" = ${assets.id} AND aa."albumId" = ${c.albumId})`;
|
||||
|
||||
case "geo_radius":
|
||||
if (c.lat !== undefined && c.lng !== undefined && c.radiusKm) {
|
||||
// Haversine approximation: 1 degree ≈ 111km
|
||||
const latDelta = c.radiusKm / 111;
|
||||
const lngDelta = c.radiusKm / (111 * Math.cos((c.lat * Math.PI) / 180));
|
||||
return and(
|
||||
gte(exif.latitude, c.lat - latDelta),
|
||||
lte(exif.latitude, c.lat + latDelta),
|
||||
gte(exif.longitude, c.lng - lngDelta),
|
||||
lte(exif.longitude, c.lng + lngDelta),
|
||||
)!;
|
||||
}
|
||||
return undefined;
|
||||
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
import { appDb } from "@/db";
|
||||
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 { buildConditions } from "./conditionBuilder";
|
||||
import { executeAction } from "./actionExecutor";
|
||||
import { IUser } from "@/types/user";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
const PREFIX = "[Workflow]";
|
||||
|
||||
function log(runId: string, ...args: any[]) {
|
||||
console.log(`${PREFIX} [run:${runId.slice(0, 8)}]`, ...args);
|
||||
}
|
||||
|
||||
function logError(runId: string, ...args: any[]) {
|
||||
console.error(`${PREFIX} [run:${runId.slice(0, 8)}]`, ...args);
|
||||
}
|
||||
|
||||
async function resolveAssetTrigger(
|
||||
subType: string,
|
||||
workflowId: string,
|
||||
userId: string,
|
||||
lookbackMinutes: number = 0,
|
||||
runId: string = "",
|
||||
): Promise<string[]> {
|
||||
// Get last successful non-debug run time
|
||||
const [lastRun] = await appDb
|
||||
.select({ completedAt: workflowRuns.completedAt })
|
||||
.from(workflowRuns)
|
||||
.where(and(
|
||||
eq(workflowRuns.workflowId, workflowId),
|
||||
eq(workflowRuns.status, "completed"),
|
||||
ne(workflowRuns.trigger, "debug"),
|
||||
))
|
||||
.orderBy(desc(workflowRuns.completedAt))
|
||||
.limit(1);
|
||||
|
||||
// Fall back to workflow creation time if no previous run
|
||||
let sinceDate = lastRun?.completedAt;
|
||||
if (!sinceDate) {
|
||||
const [wf] = await appDb
|
||||
.select({ createdAt: workflows.createdAt })
|
||||
.from(workflows)
|
||||
.where(eq(workflows.id, workflowId))
|
||||
.limit(1);
|
||||
sinceDate = wf?.createdAt || new Date();
|
||||
log(runId, `No previous run found, using workflow creation time: ${sinceDate.toISOString()}`);
|
||||
} else {
|
||||
log(runId, `Last completed run at: ${sinceDate.toISOString()}`);
|
||||
}
|
||||
|
||||
// Apply lookback buffer
|
||||
if (lookbackMinutes > 0) {
|
||||
const original = sinceDate;
|
||||
sinceDate = new Date(sinceDate.getTime() - lookbackMinutes * 60 * 1000);
|
||||
log(runId, `Lookback buffer: ${lookbackMinutes}m, adjusted sinceDate from ${original.toISOString()} to ${sinceDate.toISOString()}`);
|
||||
}
|
||||
|
||||
const baseConditions = [
|
||||
eq(assets.ownerId, userId),
|
||||
eq(assets.visibility, "timeline"),
|
||||
eq(assets.status, "active"),
|
||||
isNull(assets.deletedAt),
|
||||
];
|
||||
|
||||
// Get already-processed assets for this workflow
|
||||
let processedMap: Map<string, Date> | null = null;
|
||||
if (subType === "new_asset" || subType === "asset_updated") {
|
||||
const processed = await appDb
|
||||
.select({ assetId: workflowProcessedAssets.assetId, processedAt: workflowProcessedAssets.processedAt })
|
||||
.from(workflowProcessedAssets)
|
||||
.where(eq(workflowProcessedAssets.workflowId, workflowId));
|
||||
processedMap = new Map(processed.map((r) => [r.assetId, r.processedAt || new Date(0)]));
|
||||
log(runId, `Previously processed assets: ${processedMap.size}`);
|
||||
}
|
||||
|
||||
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 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 totalCandidates = rows.length;
|
||||
// For asset_updated: only skip if we processed it AFTER its current updatedAt
|
||||
candidateIds = rows
|
||||
.filter((r) => {
|
||||
const lastProcessed = processedMap?.get(r.id);
|
||||
if (!lastProcessed) return true; // never processed
|
||||
return r.updatedAt > lastProcessed; // updated since last processing
|
||||
})
|
||||
.map((r) => r.id);
|
||||
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);
|
||||
log(runId, `Trigger [all_assets]: ${rows.length} assets found`);
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
return candidateIds;
|
||||
}
|
||||
|
||||
interface DebugStep {
|
||||
nodeId: string;
|
||||
nodeType: string;
|
||||
subType: string;
|
||||
label: string;
|
||||
inputAssets: number;
|
||||
outputAssets: Record<string, number>;
|
||||
assetIds?: string[];
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
interface RunResult {
|
||||
matchedAssets: number;
|
||||
assetIds: string[];
|
||||
actions: any[];
|
||||
debug?: DebugStep[];
|
||||
}
|
||||
|
||||
export async function executeWorkflow(
|
||||
workflowId: string,
|
||||
trigger: "manual" | "schedule" | "webhook" | "debug",
|
||||
user: IUser
|
||||
): Promise<string> {
|
||||
const isDebug = trigger === "debug";
|
||||
|
||||
// Create run record
|
||||
const runId = randomUUID();
|
||||
await appDb.insert(workflowRuns).values({
|
||||
id: runId,
|
||||
workflowId,
|
||||
trigger,
|
||||
status: "running",
|
||||
});
|
||||
|
||||
log(runId, `=== Workflow execution started ===`);
|
||||
log(runId, `Workflow: ${workflowId}`);
|
||||
log(runId, `Trigger: ${trigger}${isDebug ? " (DRY RUN)" : ""}`);
|
||||
log(runId, `User: ${user.id}`);
|
||||
|
||||
try {
|
||||
// Load graph
|
||||
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, workflowId));
|
||||
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, workflowId));
|
||||
|
||||
log(runId, `Graph loaded: ${nodes.length} nodes, ${edges.length} edges`);
|
||||
|
||||
// Build adjacency map: nodeId -> { handle -> targetNodeId[] }
|
||||
const adjacency = new Map<string, Map<string | null, string[]>>();
|
||||
for (const edge of edges) {
|
||||
if (!adjacency.has(edge.sourceNodeId)) adjacency.set(edge.sourceNodeId, new Map());
|
||||
const handles = adjacency.get(edge.sourceNodeId)!;
|
||||
const handle = edge.sourceHandle || null;
|
||||
if (!handles.has(handle)) handles.set(handle, []);
|
||||
handles.get(handle)!.push(edge.targetNodeId);
|
||||
}
|
||||
|
||||
const nodeMap = new Map(nodes.map((n) => [n.id, n]));
|
||||
|
||||
// Find asset trigger nodes
|
||||
const triggerNodes = nodes.filter((n) => n.type === "trigger");
|
||||
if (triggerNodes.length === 0) {
|
||||
throw new Error("No asset trigger nodes found in the workflow");
|
||||
}
|
||||
|
||||
log(runId, `Found ${triggerNodes.length} trigger node(s): ${triggerNodes.map(n => n.subType).join(", ")}`);
|
||||
|
||||
const result: RunResult = { matchedAssets: 0, assetIds: [], actions: [] };
|
||||
const debugSteps: DebugStep[] = [];
|
||||
const allProcessedAssetIds = new Set<string>();
|
||||
|
||||
// BFS: process nodes with their incoming asset sets
|
||||
const queue: { nodeId: string; assetIds: string[] | null }[] = [];
|
||||
|
||||
// Resolve each asset trigger to get the initial asset set
|
||||
for (const triggerNode of triggerNodes) {
|
||||
const triggerConfig = JSON.parse(triggerNode.data || "{}");
|
||||
const lookback = triggerConfig.lookbackMinutes || 0;
|
||||
|
||||
log(runId, `--- Resolving trigger: ${triggerNode.subType} (node: ${triggerNode.id.slice(0, 8)}) ---`);
|
||||
|
||||
const assetIds = await resolveAssetTrigger(triggerNode.subType, workflowId, user.id, lookback, runId);
|
||||
result.matchedAssets += assetIds.length;
|
||||
|
||||
log(runId, `Trigger resolved: ${assetIds.length} assets`);
|
||||
|
||||
debugSteps.push({
|
||||
nodeId: triggerNode.id,
|
||||
nodeType: "trigger",
|
||||
subType: triggerNode.subType,
|
||||
label: `Asset Trigger: ${triggerNode.subType}`,
|
||||
inputAssets: 0,
|
||||
outputAssets: { out: assetIds.length },
|
||||
assetIds: assetIds.slice(0, 100),
|
||||
detail: `Lookback: ${lookback}m, Found ${assetIds.length} assets`,
|
||||
});
|
||||
|
||||
const targets = adjacency.get(triggerNode.id)?.get(null) || [];
|
||||
for (const targetId of targets) {
|
||||
queue.push({ nodeId: targetId, assetIds });
|
||||
}
|
||||
}
|
||||
|
||||
// Process queue
|
||||
let step = 0;
|
||||
while (queue.length > 0) {
|
||||
step++;
|
||||
const { nodeId, assetIds } = queue.shift()!;
|
||||
const node = nodeMap.get(nodeId);
|
||||
if (!node) {
|
||||
log(runId, `Step ${step}: Node ${nodeId.slice(0, 8)} not found, skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const config = JSON.parse(node.data || "{}");
|
||||
|
||||
log(runId, `--- Step ${step}: ${node.type}/${node.subType} (node: ${nodeId.slice(0, 8)}) | Input: ${assetIds?.length ?? "null"} assets ---`);
|
||||
|
||||
if (node.type === "logic") {
|
||||
if (node.subType === "if") {
|
||||
// Query assets matching conditions, scoped to incoming set
|
||||
const conditions = config.conditions || [];
|
||||
log(runId, `IF: ${conditions.length} conditions: ${conditions.map((c: any) => c.type).join(", ")}`);
|
||||
|
||||
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);
|
||||
const matchedSet = new Set(matchedIds);
|
||||
|
||||
let trueIds = matchedIds;
|
||||
let falseIds: string[] = [];
|
||||
|
||||
if (assetIds !== null) {
|
||||
trueIds = assetIds.filter((id) => matchedSet.has(id));
|
||||
falseIds = assetIds.filter((id) => !matchedSet.has(id));
|
||||
}
|
||||
|
||||
log(runId, `IF result: ${trueIds.length} → TRUE, ${falseIds.length} → FALSE`);
|
||||
|
||||
debugSteps.push({
|
||||
nodeId: node.id,
|
||||
nodeType: "logic",
|
||||
subType: "if",
|
||||
label: `IF (${conditions.length} conditions)`,
|
||||
inputAssets: assetIds?.length || 0,
|
||||
outputAssets: { true: trueIds.length, false: falseIds.length },
|
||||
assetIds: trueIds.slice(0, 100),
|
||||
detail: `Matched: ${trueIds.length} true, ${falseIds.length} false`,
|
||||
});
|
||||
|
||||
// Route to true/false branches
|
||||
const trueTargets = adjacency.get(nodeId)?.get("true") || [];
|
||||
const falseTargets = adjacency.get(nodeId)?.get("false") || [];
|
||||
for (const t of trueTargets) queue.push({ nodeId: t, assetIds: trueIds });
|
||||
for (const t of falseTargets) queue.push({ nodeId: t, assetIds: falseIds });
|
||||
|
||||
} else if (node.subType === "switch") {
|
||||
const cases = config.cases || [];
|
||||
let remaining = assetIds;
|
||||
|
||||
log(runId, `SWITCH: ${cases.length} cases`);
|
||||
|
||||
for (let ci = 0; ci < cases.length; ci++) {
|
||||
const c = cases[ci];
|
||||
log(runId, ` Case "${c.label || ci}": ${(c.conditions || []).length} conditions, checking against ${remaining?.length ?? "all"} assets`);
|
||||
|
||||
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);
|
||||
const matchedSet = new Set(matchedIds);
|
||||
let caseIds: string[];
|
||||
|
||||
if (remaining !== null) {
|
||||
caseIds = remaining.filter((id) => matchedSet.has(id));
|
||||
remaining = remaining.filter((id) => !matchedSet.has(id));
|
||||
} else {
|
||||
caseIds = matchedIds;
|
||||
remaining = [];
|
||||
}
|
||||
|
||||
log(runId, ` Case "${c.label || ci}" matched: ${caseIds.length} assets, ${remaining?.length ?? 0} remaining`);
|
||||
|
||||
result.matchedAssets = Math.max(result.matchedAssets, caseIds.length);
|
||||
|
||||
const caseTargets = adjacency.get(nodeId)?.get(c.handle) || [];
|
||||
for (const t of caseTargets) queue.push({ nodeId: t, assetIds: caseIds });
|
||||
}
|
||||
|
||||
const caseOutput: Record<string, number> = {};
|
||||
cases.forEach((c: any, i: number) => { caseOutput[c.label || `case_${i}`] = 0; });
|
||||
debugSteps.push({
|
||||
nodeId: node.id,
|
||||
nodeType: "logic",
|
||||
subType: "switch",
|
||||
label: `SWITCH (${cases.length} cases)`,
|
||||
inputAssets: assetIds?.length || 0,
|
||||
outputAssets: { ...caseOutput, default: (remaining || []).length },
|
||||
});
|
||||
|
||||
log(runId, `SWITCH default: ${(remaining || []).length} assets`);
|
||||
|
||||
// Default branch gets remaining
|
||||
const defaultTargets = adjacency.get(nodeId)?.get("default") || [];
|
||||
for (const t of defaultTargets) queue.push({ nodeId: t, assetIds: remaining || [] });
|
||||
}
|
||||
|
||||
} else if (node.type === "action") {
|
||||
// Execute action on the asset set
|
||||
const actionAssetIds = assetIds || [];
|
||||
actionAssetIds.forEach((id) => allProcessedAssetIds.add(id));
|
||||
|
||||
log(runId, `ACTION [${node.subType}]: ${actionAssetIds.length} assets${isDebug ? " (DRY RUN)" : ""}`);
|
||||
|
||||
debugSteps.push({
|
||||
nodeId: node.id,
|
||||
nodeType: "action",
|
||||
subType: node.subType,
|
||||
label: `Action: ${node.subType}`,
|
||||
inputAssets: actionAssetIds.length,
|
||||
outputAssets: {},
|
||||
assetIds: actionAssetIds.slice(0, 100),
|
||||
detail: isDebug ? `DRY RUN — would process ${actionAssetIds.length} assets` : `Processing ${actionAssetIds.length} assets`,
|
||||
});
|
||||
|
||||
if (!isDebug && actionAssetIds.length > 0) {
|
||||
const actionResult = await executeAction(node.subType, config, actionAssetIds, user);
|
||||
log(runId, `ACTION [${node.subType}] completed: ${actionResult.assetsProcessed} processed${actionResult.albumName ? ` → "${actionResult.albumName}"` : ""}${actionResult.error ? ` ERROR: ${actionResult.error}` : ""}`);
|
||||
result.actions.push({ ...actionResult, assetIds: actionAssetIds });
|
||||
|
||||
// Record processed assets to prevent reprocessing
|
||||
if (actionAssetIds.length > 0) {
|
||||
const batchSize = 100;
|
||||
for (let i = 0; i < actionAssetIds.length; i += batchSize) {
|
||||
const batch = actionAssetIds.slice(i, i + batchSize);
|
||||
await appDb.insert(workflowProcessedAssets).values(
|
||||
batch.map((assetId) => ({
|
||||
workflowId,
|
||||
assetId,
|
||||
runId,
|
||||
}))
|
||||
);
|
||||
}
|
||||
log(runId, `Recorded ${actionAssetIds.length} assets as processed`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finalize result
|
||||
result.assetIds = Array.from(allProcessedAssetIds);
|
||||
result.matchedAssets = result.assetIds.length;
|
||||
result.debug = debugSteps;
|
||||
|
||||
// Update run record
|
||||
await appDb.update(workflowRuns).set({
|
||||
status: "completed",
|
||||
result: JSON.stringify(result),
|
||||
completedAt: new Date(),
|
||||
}).where(eq(workflowRuns.id, runId));
|
||||
|
||||
log(runId, `=== Workflow completed: ${result.matchedAssets} assets, ${result.actions.length} actions ===`);
|
||||
|
||||
return runId;
|
||||
|
||||
} catch (error: any) {
|
||||
logError(runId, `=== Workflow FAILED: ${error.message} ===`);
|
||||
|
||||
await appDb.update(workflowRuns).set({
|
||||
status: "failed",
|
||||
error: error.message || "Unknown error",
|
||||
completedAt: new Date(),
|
||||
}).where(eq(workflowRuns.id, runId));
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import cron, { ScheduledTask } from "node-cron";
|
||||
import { appDb } from "@/db";
|
||||
import { db } from "@/config/db";
|
||||
import { workflows } from "@/db/schema/workflows.schema";
|
||||
import { users } from "@/schema/users.schema";
|
||||
import { eq, and, isNotNull } from "drizzle-orm";
|
||||
import { executeWorkflow } from "./engine";
|
||||
|
||||
const scheduledTasks = new Map<string, ScheduledTask>();
|
||||
|
||||
export async function registerWorkflow(workflowId: string, cronSchedule: string, ownerId: string) {
|
||||
// Unregister if already exists
|
||||
unregisterWorkflow(workflowId);
|
||||
|
||||
if (!cron.validate(cronSchedule)) {
|
||||
console.error(`Invalid cron expression for workflow ${workflowId}: ${cronSchedule}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const task = cron.schedule(cronSchedule, async () => {
|
||||
try {
|
||||
const [user] = await db.select().from(users).where(eq(users.id, ownerId));
|
||||
if (!user) {
|
||||
console.error(`Owner ${ownerId} not found for workflow ${workflowId}`);
|
||||
return;
|
||||
}
|
||||
await executeWorkflow(workflowId, "schedule", user as any);
|
||||
console.log(`Scheduled workflow ${workflowId} executed successfully`);
|
||||
} catch (error: any) {
|
||||
console.error(`Scheduled workflow ${workflowId} failed:`, error.message);
|
||||
}
|
||||
});
|
||||
|
||||
scheduledTasks.set(workflowId, task);
|
||||
}
|
||||
|
||||
export function unregisterWorkflow(workflowId: string) {
|
||||
const existing = scheduledTasks.get(workflowId);
|
||||
if (existing) {
|
||||
existing.stop();
|
||||
scheduledTasks.delete(workflowId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadAllScheduledWorkflows() {
|
||||
const enabledWorkflows = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(and(eq(workflows.enabled, true), isNotNull(workflows.cronSchedule)));
|
||||
|
||||
for (const w of enabledWorkflows) {
|
||||
if (w.cronSchedule) {
|
||||
await registerWorkflow(w.id, w.cronSchedule, w.ownerId);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Loaded ${enabledWorkflows.length} scheduled workflows`);
|
||||
}
|
||||
+249
-85
@@ -1,4 +1,3 @@
|
||||
import { Inter } from "next/font/google";
|
||||
import PageLayout from "@/components/layouts/PageLayout";
|
||||
import Header from "@/components/shared/Header";
|
||||
import EXIFDistribution, {
|
||||
@@ -7,8 +6,6 @@ import EXIFDistribution, {
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import AssetHeatMap from "@/components/analytics/exif/AssetHeatMap";
|
||||
import PeopleNamesChart from "@/components/analytics/exif/PeopleNamesChart";
|
||||
@@ -17,66 +14,138 @@ import AlbumPhotosChart from "@/components/analytics/exif/AlbumPhotosChart";
|
||||
import { useEffect, useState } from "react";
|
||||
import { getAssetStatistics, getLivePhotoStatistics } from "@/handlers/api/analytics.handler";
|
||||
import { humanizeBytes } from "@/helpers/string.helper";
|
||||
import {
|
||||
Camera,
|
||||
Image,
|
||||
Video,
|
||||
Aperture,
|
||||
MapPin,
|
||||
SlidersHorizontal,
|
||||
BarChart3,
|
||||
Users,
|
||||
Globe,
|
||||
FolderOpen,
|
||||
} from "lucide-react";
|
||||
|
||||
|
||||
const exifCharts: IEXIFDistributionProps[] = [
|
||||
{
|
||||
column: "storage",
|
||||
title: "Storage",
|
||||
description: "Distribution of storage",
|
||||
tooltipValueFormatter: (value) => humanizeBytes(value as number * 1000000),
|
||||
},
|
||||
const cameraCharts: IEXIFDistributionProps[] = [
|
||||
{
|
||||
column: "make",
|
||||
title: "Make",
|
||||
description: "Distribution of camera make",
|
||||
description: "Camera manufacturer breakdown",
|
||||
},
|
||||
{
|
||||
column: "model",
|
||||
title: "Model",
|
||||
description: "Distribution of camera model",
|
||||
},
|
||||
{
|
||||
column: "focal-length",
|
||||
title: "Focal Length",
|
||||
description: "Distribution of focal length",
|
||||
},
|
||||
{
|
||||
column: "city",
|
||||
title: "City",
|
||||
description: "Distribution of city",
|
||||
},
|
||||
{
|
||||
column: "state",
|
||||
title: "State",
|
||||
description: "Distribution of state",
|
||||
},
|
||||
{
|
||||
column: "country",
|
||||
title: "Country",
|
||||
description: "Distribution of country",
|
||||
},
|
||||
{
|
||||
column: "iso",
|
||||
title: "ISO",
|
||||
description: "Distribution of ISO",
|
||||
},
|
||||
{
|
||||
column: "exposureTime",
|
||||
title: "Exposure Time",
|
||||
description: "Distribution of exposure time",
|
||||
description: "Camera model breakdown",
|
||||
},
|
||||
{
|
||||
column: "lensModel",
|
||||
title: "Lens Model",
|
||||
description: "Distribution of lens model",
|
||||
description: "Lens usage across your library",
|
||||
},
|
||||
];
|
||||
|
||||
const locationCharts: IEXIFDistributionProps[] = [
|
||||
{
|
||||
column: "city",
|
||||
title: "City",
|
||||
description: "Top cities by photo count",
|
||||
},
|
||||
{
|
||||
column: "state",
|
||||
title: "State",
|
||||
description: "Top states by photo count",
|
||||
},
|
||||
{
|
||||
column: "country",
|
||||
title: "Country",
|
||||
description: "Top countries by photo count",
|
||||
},
|
||||
];
|
||||
|
||||
const technicalCharts: IEXIFDistributionProps[] = [
|
||||
{
|
||||
column: "focal-length",
|
||||
title: "Focal Length",
|
||||
description: "Focal length distribution",
|
||||
},
|
||||
{
|
||||
column: "iso",
|
||||
title: "ISO",
|
||||
description: "ISO sensitivity distribution",
|
||||
},
|
||||
{
|
||||
column: "exposureTime",
|
||||
title: "Exposure Time",
|
||||
description: "Shutter speed distribution",
|
||||
},
|
||||
{
|
||||
column: "projectionType",
|
||||
title: "Projection Type",
|
||||
description: "Distribution of projection type",
|
||||
description: "Image projection types",
|
||||
},
|
||||
];
|
||||
|
||||
const storageChart: IEXIFDistributionProps = {
|
||||
column: "storage",
|
||||
title: "Storage",
|
||||
description: "Storage usage by user",
|
||||
tooltipValueFormatter: (value) => humanizeBytes(value as number * 1000000),
|
||||
};
|
||||
|
||||
interface StatCardProps {
|
||||
label: string;
|
||||
value: number;
|
||||
loading: boolean;
|
||||
icon: React.ReactNode;
|
||||
accent: string;
|
||||
}
|
||||
|
||||
function StatCard({ label, value, loading, icon, accent }: StatCardProps) {
|
||||
return (
|
||||
<div className="group relative overflow-hidden rounded-xl border bg-card p-5 transition-all duration-300 hover:shadow-md">
|
||||
<div className={`absolute inset-0 opacity-[0.03] ${accent}`} />
|
||||
<div className="relative flex items-center justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{label}
|
||||
</p>
|
||||
<p className="text-2xl font-bold tabular-nums tracking-tight">
|
||||
{loading ? (
|
||||
<span className="inline-block h-8 w-20 animate-pulse rounded bg-muted" />
|
||||
) : (
|
||||
value.toLocaleString()
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className={`rounded-lg p-2.5 ${accent} bg-opacity-10 text-opacity-80`}>
|
||||
{icon}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SectionHeaderProps {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
function SectionHeader({ icon, title, description }: SectionHeaderProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 mb-4 mt-2">
|
||||
<div className="flex items-center justify-center rounded-lg bg-muted p-2 text-muted-foreground">
|
||||
{icon}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold tracking-tight">{title}</h2>
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ExifDataAnalytics() {
|
||||
const [statistics, setStatistics] = useState({ images: 0, videos: 0, total: 0 });
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -110,49 +179,144 @@ export default function ExifDataAnalytics() {
|
||||
|
||||
return (
|
||||
<PageLayout className="!p-0 !mb-0 relative">
|
||||
<Header leftComponent="Exif Data" />
|
||||
<div className="p-4">
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
{["Total", "Images", "Videos"].map((type, i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-center text-lg font-mono">{type}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-center text-3xl font-mono">
|
||||
{loading ? "Loading..." : statistics[type.toLowerCase() as keyof typeof statistics].toLocaleString()}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-center text-lg font-mono">Live Photos</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-center text-3xl font-mono">
|
||||
{loading ? "Loading..." : livePhotoStatistics.total.toLocaleString()}
|
||||
<Header leftComponent="Analytics" />
|
||||
<div className="p-5 space-y-8">
|
||||
{/* ── Stats ── */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<StatCard
|
||||
label="Total Assets"
|
||||
value={statistics.total}
|
||||
loading={loading}
|
||||
icon={<BarChart3 className="h-5 w-5" />}
|
||||
accent="bg-blue-500 text-blue-600"
|
||||
/>
|
||||
<StatCard
|
||||
label="Images"
|
||||
value={statistics.images}
|
||||
loading={loading}
|
||||
icon={<Image className="h-5 w-5" />}
|
||||
accent="bg-emerald-500 text-emerald-600"
|
||||
/>
|
||||
<StatCard
|
||||
label="Videos"
|
||||
value={statistics.videos}
|
||||
loading={loading}
|
||||
icon={<Video className="h-5 w-5" />}
|
||||
accent="bg-orange-500 text-orange-600"
|
||||
/>
|
||||
<StatCard
|
||||
label="Live Photos"
|
||||
value={livePhotoStatistics.total}
|
||||
loading={loading}
|
||||
icon={<Aperture className="h-5 w-5" />}
|
||||
accent="bg-violet-500 text-violet-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Activity Heatmap ── */}
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={<BarChart3 className="h-4 w-4" />}
|
||||
title="Activity"
|
||||
description="Photo capture frequency over the past year"
|
||||
/>
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="p-4">
|
||||
<AssetHeatMap />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<AssetHeatMap />
|
||||
|
||||
{/* New Analytics Charts */}
|
||||
<div className="grid grid-cols-3 gap-4 mb-6">
|
||||
<PeopleNamesChart />
|
||||
<GeoPhotosChart />
|
||||
<AlbumPhotosChart />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{exifCharts.map((chart) => (
|
||||
<EXIFDistribution
|
||||
key={chart.column}
|
||||
column={chart.column}
|
||||
title={chart.title}
|
||||
description={chart.description}
|
||||
tooltipValueFormatter={chart.tooltipValueFormatter}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
|
||||
</div>
|
||||
{/* ── Library Overview ── */}
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={<SlidersHorizontal className="h-4 w-4" />}
|
||||
title="Library Overview"
|
||||
description="High-level stats about your photo library"
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<PeopleNamesChart />
|
||||
<GeoPhotosChart />
|
||||
<AlbumPhotosChart />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ── Storage ── */}
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={<FolderOpen className="h-4 w-4" />}
|
||||
title="Storage"
|
||||
description="Disk usage breakdown across users"
|
||||
/>
|
||||
<div className="max-w-md">
|
||||
<EXIFDistribution
|
||||
column={storageChart.column}
|
||||
title={storageChart.title}
|
||||
description={storageChart.description}
|
||||
tooltipValueFormatter={storageChart.tooltipValueFormatter}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ── Camera & Gear ── */}
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={<Camera className="h-4 w-4" />}
|
||||
title="Camera & Gear"
|
||||
description="Equipment used across your photo library"
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
{cameraCharts.map((chart) => (
|
||||
<EXIFDistribution
|
||||
key={chart.column}
|
||||
column={chart.column}
|
||||
title={chart.title}
|
||||
description={chart.description}
|
||||
tooltipValueFormatter={chart.tooltipValueFormatter}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ── Location ── */}
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={<MapPin className="h-4 w-4" />}
|
||||
title="Location"
|
||||
description="Where your photos were taken"
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
{locationCharts.map((chart) => (
|
||||
<EXIFDistribution
|
||||
key={chart.column}
|
||||
column={chart.column}
|
||||
title={chart.title}
|
||||
description={chart.description}
|
||||
tooltipValueFormatter={chart.tooltipValueFormatter}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ── Technical ── */}
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={<SlidersHorizontal className="h-4 w-4" />}
|
||||
title="Technical"
|
||||
description="Camera settings and exposure data"
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{technicalCharts.map((chart) => (
|
||||
<EXIFDistribution
|
||||
key={chart.column}
|
||||
column={chart.column}
|
||||
title={chart.title}
|
||||
description={chart.description}
|
||||
tooltipValueFormatter={chart.tooltipValueFormatter}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { db } from "@/config/db";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { assets } from "@/schema/assets.schema";
|
||||
import { exif } from "@/schema";
|
||||
import { assetFaces } from "@/schema/assetFaces.schema";
|
||||
import { person } from "@/schema/person.schema";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
|
||||
if (!id) {
|
||||
return res.status(400).json({ message: "Asset ID is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch asset + exif data
|
||||
const [assetRow] = await db
|
||||
.select({
|
||||
id: assets.id,
|
||||
type: assets.type,
|
||||
originalPath: assets.originalPath,
|
||||
originalFileName: assets.originalFileName,
|
||||
isFavorite: assets.isFavorite,
|
||||
duration: assets.duration,
|
||||
localDateTime: assets.localDateTime,
|
||||
fileCreatedAt: assets.fileCreatedAt,
|
||||
// EXIF fields
|
||||
make: exif.make,
|
||||
model: exif.model,
|
||||
lensModel: exif.lensModel,
|
||||
fNumber: exif.fNumber,
|
||||
focalLength: exif.focalLength,
|
||||
iso: exif.iso,
|
||||
exposureTime: exif.exposureTime,
|
||||
fileSizeInByte: exif.fileSizeInByte,
|
||||
exifImageWidth: exif.exifImageWidth,
|
||||
exifImageHeight: exif.exifImageHeight,
|
||||
orientation: exif.orientation,
|
||||
dateTimeOriginal: exif.dateTimeOriginal,
|
||||
timeZone: exif.timeZone,
|
||||
latitude: exif.latitude,
|
||||
longitude: exif.longitude,
|
||||
city: exif.city,
|
||||
state: exif.state,
|
||||
country: exif.country,
|
||||
description: exif.description,
|
||||
rating: exif.rating,
|
||||
fps: exif.fps,
|
||||
projectionType: exif.projectionType,
|
||||
})
|
||||
.from(assets)
|
||||
.leftJoin(exif, eq(assets.id, exif.assetId))
|
||||
.where(and(
|
||||
eq(assets.id, id),
|
||||
eq(assets.ownerId, currentUser.id),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (!assetRow) {
|
||||
return res.status(404).json({ message: "Asset not found" });
|
||||
}
|
||||
|
||||
// Fetch people detected in this asset
|
||||
const faces = await db
|
||||
.select({
|
||||
personId: person.id,
|
||||
personName: person.name,
|
||||
thumbnailPath: person.thumbnailPath,
|
||||
isHidden: person.isHidden,
|
||||
})
|
||||
.from(assetFaces)
|
||||
.innerJoin(person, eq(assetFaces.personId, person.id))
|
||||
.where(eq(assetFaces.assetId, id));
|
||||
|
||||
return res.status(200).json({
|
||||
...assetRow,
|
||||
people: faces,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return res.status(500).json({ message: error?.message || "Internal server error" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { db } from "@/config/db";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { and, eq, isNull, sql, desc } from "drizzle-orm";
|
||||
import { assets } from "@/schema/assets.schema";
|
||||
import { exif } from "@/schema";
|
||||
import { isFlipped } from "@/helpers/asset.helper";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const {
|
||||
notInAlbum,
|
||||
noPeople,
|
||||
noLocation,
|
||||
notFavorited,
|
||||
type,
|
||||
limit = "100",
|
||||
page = "1",
|
||||
} = req.query as Record<string, string>;
|
||||
|
||||
const limitNum = parseInt(limit, 10);
|
||||
const pageNum = parseInt(page, 10);
|
||||
|
||||
const conditions: any[] = [
|
||||
eq(assets.ownerId, currentUser.id),
|
||||
eq(assets.visibility, "timeline"),
|
||||
eq(assets.status, "active"),
|
||||
isNull(assets.deletedAt),
|
||||
];
|
||||
|
||||
if (type && type !== "ALL") {
|
||||
conditions.push(eq(assets.type, type));
|
||||
}
|
||||
|
||||
if (notFavorited === "true") {
|
||||
conditions.push(eq(assets.isFavorite, false));
|
||||
}
|
||||
|
||||
if (noLocation === "true") {
|
||||
conditions.push(isNull(exif.latitude));
|
||||
}
|
||||
|
||||
if (notInAlbum === "true") {
|
||||
conditions.push(
|
||||
sql`NOT EXISTS (SELECT 1 FROM "album_asset" aa WHERE aa."assetId" = ${assets.id})`
|
||||
);
|
||||
}
|
||||
|
||||
if (noPeople === "true") {
|
||||
conditions.push(
|
||||
sql`NOT EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IS NOT NULL)`
|
||||
);
|
||||
}
|
||||
|
||||
const hasOrphanFilter = notInAlbum === "true" || noPeople === "true" || noLocation === "true" || notFavorited === "true";
|
||||
if (!hasOrphanFilter) {
|
||||
return res.status(400).json({ message: "At least one orphan filter is required" });
|
||||
}
|
||||
|
||||
const dbAssets = await db
|
||||
.selectDistinctOn([assets.id], {
|
||||
id: assets.id,
|
||||
deviceId: assets.deviceId,
|
||||
type: assets.type,
|
||||
originalPath: assets.originalPath,
|
||||
isFavorite: assets.isFavorite,
|
||||
duration: assets.duration,
|
||||
originalFileName: assets.originalFileName,
|
||||
deletedAt: assets.deletedAt,
|
||||
localDateTime: assets.localDateTime,
|
||||
exifImageWidth: exif.exifImageWidth,
|
||||
exifImageHeight: exif.exifImageHeight,
|
||||
ownerId: assets.ownerId,
|
||||
dateTimeOriginal: exif.dateTimeOriginal,
|
||||
orientation: exif.orientation,
|
||||
})
|
||||
.from(assets)
|
||||
.leftJoin(exif, eq(assets.id, exif.assetId))
|
||||
.where(and(...conditions))
|
||||
.orderBy(assets.id, desc(assets.localDateTime))
|
||||
.limit(limitNum)
|
||||
.offset((pageNum - 1) * limitNum);
|
||||
|
||||
const cleanedAssets = dbAssets.map((asset) => ({
|
||||
...asset,
|
||||
exifImageHeight: isFlipped(asset?.orientation) ? asset?.exifImageWidth : asset?.exifImageHeight,
|
||||
exifImageWidth: isFlipped(asset?.orientation) ? asset?.exifImageHeight : asset?.exifImageWidth,
|
||||
orientation: asset?.orientation,
|
||||
}));
|
||||
|
||||
return res.status(200).json(cleanedAssets);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
// pages/api/proxy.js
|
||||
|
||||
import { ENV } from '@/config/environment';
|
||||
import { getUserHeaders } from '@/helpers/user.helper';
|
||||
import { appDb } from '@/db';
|
||||
import { apiKeys } from '@/db/schema';
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { verify } from 'jsonwebtoken';
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
|
||||
@@ -16,18 +18,31 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
if (req.method !== 'GET') {
|
||||
return res.status(405).json({ message: 'Method Not Allowed' })
|
||||
}
|
||||
|
||||
|
||||
const { id, size, token, p } = req.query;
|
||||
if (!token) {
|
||||
return res.status(401).json({ message: 'Unauthorized' })
|
||||
}
|
||||
|
||||
let userId: string;
|
||||
try {
|
||||
verify(token as string, ENV.JWT_SECRET);
|
||||
const previewDecoded = verify(token as string, ENV.JWT_SECRET) as { token: string };
|
||||
const mainDecoded = verify(previewDecoded.token, ENV.JWT_SECRET) as { userId: string };
|
||||
userId = mainDecoded.userId;
|
||||
} catch (error) {
|
||||
return res.status(401).json({ message: 'Token is invalid' })
|
||||
}
|
||||
|
||||
const [keyRow] = await appDb
|
||||
.select({ secret: apiKeys.secret })
|
||||
.from(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, userId), eq(apiKeys.purpose, "share")))
|
||||
.limit(1);
|
||||
|
||||
if (!keyRow) {
|
||||
return res.status(403).json({ message: 'Share key not configured. Please set up sharing in Power Tools.' });
|
||||
}
|
||||
|
||||
const resource = p === "true" ? "people" : "assets";
|
||||
const baseURL = `${ENV.IMMICH_URL}/api/${resource}/${id}`;
|
||||
const version = size === "original" ? "original" : "thumbnail";
|
||||
@@ -37,9 +52,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
// Forward the request to the target API
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: getUserHeaders({ isUsingShareKey: true }, {
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
}),
|
||||
'x-api-key': keyRow.secret,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { appDb } from "@/db";
|
||||
import { importJobs, importJobItems } from "@/db/schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
import { isJobActive, runImportJob } from "@/workers/import/runner";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", "GET");
|
||||
return res.status(405).json({ error: "Method Not Allowed" });
|
||||
}
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ error: "Unauthorized" });
|
||||
|
||||
const { jobId } = req.query as { jobId: string };
|
||||
|
||||
const [job] = await appDb.select().from(importJobs).where(eq(importJobs.id, jobId));
|
||||
if (!job || job.userId !== currentUser.id) {
|
||||
return res.status(404).json({ error: "Job not found" });
|
||||
}
|
||||
|
||||
if (job.status === "pending" && !isJobActive(jobId)) {
|
||||
const headers = getUserHeaders(currentUser) as Record<string, string>;
|
||||
runImportJob(jobId, headers).catch((err) =>
|
||||
console.error("Unhandled error in runImportJob (resume)", err)
|
||||
);
|
||||
}
|
||||
|
||||
const items = await appDb
|
||||
.select()
|
||||
.from(importJobItems)
|
||||
.where(eq(importJobItems.jobId, jobId));
|
||||
|
||||
return res.status(200).json({ job, items });
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { appDb } from "@/db";
|
||||
import { importJobs, importJobItems } from "@/db/schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
import { runImportJob } from "@/workers/import/runner";
|
||||
import { getProcessor } from "@/workers/import/registry";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ error: "Unauthorized" });
|
||||
|
||||
const jobs = await appDb
|
||||
.select()
|
||||
.from(importJobs)
|
||||
.where(eq(importJobs.userId, currentUser.id))
|
||||
.orderBy(desc(importJobs.createdAt))
|
||||
.limit(20);
|
||||
|
||||
return res.status(200).json({ jobs });
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "GET, POST");
|
||||
return res.status(405).json({ error: "Method Not Allowed" });
|
||||
}
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ error: "Unauthorized" });
|
||||
|
||||
const { platform, url, urlConfig, importData, assets } = req.body;
|
||||
|
||||
if (!platform || !url || !Array.isArray(assets) || assets.length === 0) {
|
||||
return res.status(400).json({ error: "platform, url, and assets are required" });
|
||||
}
|
||||
|
||||
if (assets.some((a: unknown) => typeof (a as any).id !== "string")) {
|
||||
return res.status(400).json({ error: "Each asset must have a string id" });
|
||||
}
|
||||
|
||||
try {
|
||||
getProcessor(platform);
|
||||
} catch {
|
||||
return res.status(400).json({ error: `Unknown platform: ${platform}` });
|
||||
}
|
||||
|
||||
const [job] = await appDb
|
||||
.insert(importJobs)
|
||||
.values({
|
||||
userId: currentUser.id,
|
||||
platform,
|
||||
url,
|
||||
urlConfig: JSON.stringify(urlConfig ?? {}),
|
||||
importData: JSON.stringify(importData ?? {}),
|
||||
totalCount: assets.length,
|
||||
})
|
||||
.returning();
|
||||
|
||||
await appDb.insert(importJobItems).values(
|
||||
assets.map((asset: { id: string; [key: string]: unknown }) => ({
|
||||
jobId: job.id,
|
||||
assetId: asset.id,
|
||||
itemData: JSON.stringify(asset),
|
||||
}))
|
||||
);
|
||||
|
||||
const headers = getUserHeaders(currentUser) as Record<string, string>;
|
||||
runImportJob(job.id, headers).catch((err) =>
|
||||
console.error("Unhandled error in runImportJob", err)
|
||||
);
|
||||
|
||||
return res.status(201).json({ jobId: job.id });
|
||||
}
|
||||
@@ -134,6 +134,18 @@ const fetchJson = async <T>(url: string) => {
|
||||
headers: { accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) {
|
||||
let errorBody: { message?: string } = {};
|
||||
try { errorBody = await response.json(); } catch { /* ignore */ }
|
||||
if (response.status === 401 && errorBody.message === "Password required") {
|
||||
const err = new Error("PASSWORD_REQUIRED");
|
||||
(err as any).code = "PASSWORD_REQUIRED";
|
||||
throw err;
|
||||
}
|
||||
if (response.status === 401 && errorBody.message === "Invalid password") {
|
||||
const err = new Error("Invalid password for this shared link.");
|
||||
(err as any).code = "INVALID_PASSWORD";
|
||||
throw err;
|
||||
}
|
||||
throw new Error(`Request failed for ${url} (status ${response.status})`);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
@@ -147,6 +159,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
|
||||
const payload = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
|
||||
const link = payload?.link;
|
||||
const password = payload?.password;
|
||||
|
||||
if (!link || typeof link !== "string") {
|
||||
return respondWithError(res, 400, "A shared album link is required");
|
||||
@@ -157,9 +170,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
return respondWithError(res, 400, "Invalid Immich share link");
|
||||
}
|
||||
|
||||
const authQuery = password
|
||||
? `key=${parsed.key}&password=${encodeURIComponent(password)}`
|
||||
: `key=${parsed.key}`;
|
||||
|
||||
try {
|
||||
const sharedLink = await fetchJson<ImmichSharedLinkResponse>(
|
||||
`${parsed.origin}/api/shared-links/me?key=${parsed.key}`
|
||||
`${parsed.origin}/api/shared-links/me?${authQuery}`
|
||||
);
|
||||
|
||||
const albumId = sharedLink.album?.id;
|
||||
@@ -167,7 +184,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
|
||||
if (albumId) {
|
||||
const album = await fetchJson<ImmichAlbumResponse>(
|
||||
`${parsed.origin}/api/albums/${albumId}?key=${parsed.key}&withoutAssets=false`
|
||||
`${parsed.origin}/api/albums/${albumId}?${authQuery}&withoutAssets=false`
|
||||
);
|
||||
|
||||
const assets = (album.assets || []).map((asset) => ({
|
||||
@@ -216,6 +233,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
|
||||
return res.status(200).json(responseBody);
|
||||
} catch (error: any) {
|
||||
if (error?.code === "PASSWORD_REQUIRED") {
|
||||
return res.status(401).json({ error: "PASSWORD_REQUIRED" });
|
||||
}
|
||||
if (error?.code === "INVALID_PASSWORD") {
|
||||
return res.status(401).json({ error: error.message });
|
||||
}
|
||||
console.error("Import shared error", error);
|
||||
return respondWithError(res, 500, error?.message ?? "Failed to import shared album");
|
||||
}
|
||||
|
||||
@@ -26,7 +26,10 @@ export const ensurePowerToolsTag = async (headers: HeadersRecord) => {
|
||||
|
||||
const createResponse = await fetch(`${ENV.IMMICH_URL}/api/tags`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
headers: {
|
||||
...headers,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name: POWER_TOOLS_TAG_NAME }),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { ENV } from "@/config/environment";
|
||||
import { appDb } from "@/db";
|
||||
import { apiKeys } from "@/db/schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
const PURPOSE_CONFIG: Record<string, { keyName: string; permissions: string[] }> = {
|
||||
share: {
|
||||
keyName: "Power Tools Share Key",
|
||||
permissions: ["asset.view", "asset.download"],
|
||||
},
|
||||
};
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const { purpose } = req.query as { purpose: string };
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
const [row] = await appDb
|
||||
.select()
|
||||
.from(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, currentUser.id), eq(apiKeys.purpose, purpose)))
|
||||
.limit(1);
|
||||
|
||||
if (!row) {
|
||||
return res.status(404).json({ message: "API key not found" });
|
||||
}
|
||||
|
||||
await fetch(`${ENV.IMMICH_URL}/api/api-keys/${row.immichKeyId}`, {
|
||||
method: "DELETE",
|
||||
headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }),
|
||||
});
|
||||
|
||||
await appDb
|
||||
.delete(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, currentUser.id), eq(apiKeys.purpose, purpose)));
|
||||
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const config = PURPOSE_CONFIG[purpose];
|
||||
if (!config) {
|
||||
return res.status(400).json({ message: `Unknown purpose: ${purpose}` });
|
||||
}
|
||||
|
||||
// Delete old key from Immich if it exists
|
||||
const [existing] = await appDb
|
||||
.select()
|
||||
.from(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, currentUser.id), eq(apiKeys.purpose, purpose)))
|
||||
.limit(1);
|
||||
|
||||
if (existing) {
|
||||
await fetch(`${ENV.IMMICH_URL}/api/api-keys/${existing.immichKeyId}`, {
|
||||
method: "DELETE",
|
||||
headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }),
|
||||
});
|
||||
}
|
||||
|
||||
// Create new key in Immich
|
||||
const immichRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, {
|
||||
method: "POST",
|
||||
headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }),
|
||||
body: JSON.stringify({ name: config.keyName, permissions: config.permissions }),
|
||||
});
|
||||
|
||||
if (!immichRes.ok) {
|
||||
const err = await immichRes.json().catch(() => ({}));
|
||||
return res.status(immichRes.status).json({ message: err.message ?? "Failed to create API key in Immich" });
|
||||
}
|
||||
|
||||
const { secret, apiKey } = await immichRes.json();
|
||||
|
||||
await appDb
|
||||
.insert(apiKeys)
|
||||
.values({ userId: currentUser.id, purpose, keyName: config.keyName, secret, immichKeyId: apiKey.id })
|
||||
.onConflictDoUpdate({
|
||||
target: [apiKeys.userId, apiKeys.purpose],
|
||||
set: { secret, immichKeyId: apiKey.id, keyName: config.keyName },
|
||||
});
|
||||
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { appDb } from "@/db";
|
||||
import { apiKeys } from "@/db/schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") {
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const rows = await appDb
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
purpose: apiKeys.purpose,
|
||||
keyName: apiKeys.keyName,
|
||||
createdAt: apiKeys.createdAt,
|
||||
})
|
||||
.from(apiKeys)
|
||||
.where(eq(apiKeys.userId, currentUser.id));
|
||||
|
||||
return res.status(200).json(rows);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { appDb } from "@/db";
|
||||
import { settings } from "@/db/schema/settings.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { key } = req.query as { key: string };
|
||||
|
||||
if (req.method === "GET") {
|
||||
const [row] = await appDb
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(and(eq(settings.key, key), eq(settings.ownerId, currentUser.id)));
|
||||
if (!row) return res.status(404).json({ message: "Setting not found" });
|
||||
return res.status(200).json(row);
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { value } = req.body;
|
||||
if (value === undefined) return res.status(400).json({ message: "value is required" });
|
||||
|
||||
const [existing] = await appDb
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(and(eq(settings.key, key), eq(settings.ownerId, currentUser.id)));
|
||||
|
||||
if (existing) {
|
||||
await appDb.update(settings).set({ value }).where(eq(settings.id, existing.id));
|
||||
} else {
|
||||
await appDb.insert(settings).values({ key, value, ownerId: currentUser.id });
|
||||
}
|
||||
|
||||
const [row] = await appDb
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(and(eq(settings.key, key), eq(settings.ownerId, currentUser.id)));
|
||||
return res.status(200).json(row);
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
await appDb.delete(settings).where(and(eq(settings.key, key), eq(settings.ownerId, currentUser.id)));
|
||||
return res.status(204).end();
|
||||
}
|
||||
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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",
|
||||
];
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { apiKey } = req.body;
|
||||
if (!apiKey) return res.status(400).json({ message: "apiKey is required" });
|
||||
|
||||
try {
|
||||
// Validate by calling Immich's auth endpoint with the key
|
||||
const authRes = await fetch(`${ENV.IMMICH_URL}/api/users/me`, {
|
||||
headers: { "x-api-key": apiKey },
|
||||
});
|
||||
|
||||
if (!authRes.ok) {
|
||||
return res.status(200).json({
|
||||
valid: false,
|
||||
error: "Invalid API key — could not authenticate with Immich",
|
||||
permissions: [],
|
||||
missing: REQUIRED_PERMISSIONS,
|
||||
});
|
||||
}
|
||||
|
||||
// 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));
|
||||
|
||||
return res.status(200).json({
|
||||
valid: missing.length === 0,
|
||||
error: missing.length > 0 ? `Missing permissions: ${missing.join(", ")}` : null,
|
||||
permissions: granted,
|
||||
missing,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return res.status(200).json({
|
||||
valid: false,
|
||||
error: `Could not connect to Immich: ${error.message}`,
|
||||
permissions: [],
|
||||
missing: REQUIRED_PERMISSIONS,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { ENV } from "@/config/environment";
|
||||
import { appDb } from "@/db";
|
||||
import { apiKeys } from "@/db/schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
const PURPOSE = "share";
|
||||
const KEY_NAME = "Power Tools Share Key";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
if (req.method === "GET") {
|
||||
const [row] = await appDb
|
||||
.select({ keyName: apiKeys.keyName, createdAt: apiKeys.createdAt })
|
||||
.from(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, currentUser.id), eq(apiKeys.purpose, PURPOSE)))
|
||||
.limit(1);
|
||||
|
||||
return res.status(200).json({
|
||||
endpointConfigured: !!ENV.POWER_TOOLS_ENDPOINT_URL,
|
||||
exists: !!row,
|
||||
keyName: row?.keyName ?? null,
|
||||
createdAt: row?.createdAt ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const immichRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, {
|
||||
method: "POST",
|
||||
headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }),
|
||||
body: JSON.stringify({
|
||||
name: KEY_NAME,
|
||||
permissions: ["asset.view", "asset.download"],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!immichRes.ok) {
|
||||
const err = await immichRes.json().catch(() => ({}));
|
||||
return res.status(immichRes.status).json({ message: err.message ?? "Failed to create API key in Immich" });
|
||||
}
|
||||
|
||||
const { secret, apiKey } = await immichRes.json();
|
||||
|
||||
await appDb
|
||||
.insert(apiKeys)
|
||||
.values({
|
||||
userId: currentUser.id,
|
||||
purpose: PURPOSE,
|
||||
keyName: KEY_NAME,
|
||||
secret,
|
||||
immichKeyId: apiKey.id,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [apiKeys.userId, apiKeys.purpose],
|
||||
set: { secret, immichKeyId: apiKey.id, keyName: KEY_NAME },
|
||||
});
|
||||
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
const [row] = await appDb
|
||||
.select()
|
||||
.from(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, currentUser.id), eq(apiKeys.purpose, PURPOSE)))
|
||||
.limit(1);
|
||||
|
||||
if (!row) {
|
||||
return res.status(404).json({ message: "No share key found" });
|
||||
}
|
||||
|
||||
await fetch(`${ENV.IMMICH_URL}/api/api-keys/${row.immichKeyId}`, {
|
||||
method: "DELETE",
|
||||
headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }),
|
||||
});
|
||||
|
||||
await appDb
|
||||
.delete(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, currentUser.id), eq(apiKeys.purpose, PURPOSE)));
|
||||
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { ENV } from "@/config/environment";
|
||||
import { appDb } from "@/db";
|
||||
import { apiKeys } from "@/db/schema";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { JsonWebTokenError, verify } from "jsonwebtoken";
|
||||
import { NextApiResponse } from "next";
|
||||
|
||||
import { NextApiRequest } from "next";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
|
||||
interface ShareLinkFilters {
|
||||
personIds: string[];
|
||||
@@ -23,20 +25,31 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
|
||||
const decoded = verify(token as string, ENV.JWT_SECRET);
|
||||
const decoded = verify(token as string, ENV.JWT_SECRET) as { userId: string };
|
||||
|
||||
if (!decoded) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const [keyRow] = await appDb
|
||||
.select({ secret: apiKeys.secret })
|
||||
.from(apiKeys)
|
||||
.where(and(eq(apiKeys.userId, decoded.userId), eq(apiKeys.purpose, "share")))
|
||||
.limit(1);
|
||||
|
||||
if (!keyRow) {
|
||||
return res.status(403).json({ message: "Share key not configured. Please set up sharing in Power Tools." });
|
||||
}
|
||||
|
||||
const targetUrl = `${ENV.IMMICH_URL}/api/download/archive`;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ assetIds }),
|
||||
headers: getUserHeaders({ isUsingShareKey: true }, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
'x-api-key': keyRow.secret,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { NextApiResponse } from "next";
|
||||
|
||||
import { ENV } from "@/config/environment";
|
||||
import { ShareLinkFilters } from "@/types/shareLink";
|
||||
import { JsonWebTokenError, verify } from "jsonwebtoken";
|
||||
import { NextApiRequest } from "next";
|
||||
|
||||
@@ -13,10 +12,6 @@ export default async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
return res.status(404).json({ message: "Token not found" });
|
||||
}
|
||||
|
||||
if (!ENV.IMMICH_SHARE_LINK_KEY) {
|
||||
return res.status(401).json({ message: "Please check your link and try again. If you're the admin, check if you've enabled all the configurations in the Immich Power Tools in your environment variables" });
|
||||
}
|
||||
|
||||
const decoded = verify(token as string, ENV.JWT_SECRET);
|
||||
|
||||
|
||||
|
||||
@@ -19,15 +19,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
return res.status(401).json({ message: "The JWT_SECRET is missing in the .env file. Please add it to the .env file for generating share links" });
|
||||
}
|
||||
|
||||
if (!ENV.IMMICH_SHARE_LINK_KEY) {
|
||||
return res.status(401).json({ message: "The IMMICH_SHARE_LINK_KEY is missing in the .env file. Please add it to the .env file for generating share links" });
|
||||
}
|
||||
|
||||
if (!ENV.POWER_TOOLS_ENDPOINT_URL) {
|
||||
return res.status(401).json({ message: "The POWER_TOOLS_ENDPOINT_URL is missing in the .env file. Please add it to the .env file for generating share links" });
|
||||
}
|
||||
|
||||
const token = sign(filters, ENV.JWT_SECRET, expiresIn !== "never" ? {
|
||||
const token = sign({ ...filters, userId: currentUser.id }, ENV.JWT_SECRET, expiresIn !== "never" ? {
|
||||
expiresIn: expiresIn
|
||||
} : {});
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { ENV } from "@/config/environment";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { getUserHeaders } from "@/helpers/user.helper";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") {
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const headers = getUserHeaders(currentUser, { "Content-Type": "application/json" });
|
||||
|
||||
const result = { canUpload: false };
|
||||
|
||||
// Test asset upload permission by calling a no-op endpoint
|
||||
try {
|
||||
const response = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({ deviceAssetIds: ["permission-check"], deviceId: "immich-power-tools-check" }),
|
||||
});
|
||||
result.canUpload = response.ok;
|
||||
} catch {
|
||||
result.canUpload = false;
|
||||
}
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflows } from "@/db/schema/workflows.schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { executeWorkflow } from "@/lib/workflow/engine";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { db } from "@/config/db";
|
||||
import { users } from "@/schema/users.schema";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const { token } = req.query as { token: string };
|
||||
|
||||
const [workflow] = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(eq(workflows.webhookToken, token));
|
||||
|
||||
if (!workflow) return res.status(404).json({ message: "Webhook not found" });
|
||||
|
||||
if (!workflow.enabled) return res.status(422).json({ message: "Workflow is disabled" });
|
||||
|
||||
// Get user from Immich DB
|
||||
const [user] = await db.select().from(users).where(eq(users.id, workflow.ownerId));
|
||||
if (!user) return res.status(404).json({ message: "Owner not found" });
|
||||
|
||||
try {
|
||||
const runId = await executeWorkflow(workflow.id, "webhook", user as any);
|
||||
return res.status(200).json({ runId });
|
||||
} catch (error: any) {
|
||||
return res.status(500).json({ message: error.message || "Workflow execution failed" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflows, workflowNodes, workflowEdges } from "@/db/schema/workflows.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
|
||||
const [workflow] = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
|
||||
|
||||
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, id));
|
||||
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, id));
|
||||
|
||||
const exportData = {
|
||||
version: 1,
|
||||
name: workflow.name,
|
||||
description: workflow.description,
|
||||
viewport: workflow.viewport,
|
||||
nodes: nodes.map((n) => ({
|
||||
id: n.id,
|
||||
type: n.type,
|
||||
subType: n.subType,
|
||||
data: n.data,
|
||||
positionX: n.positionX,
|
||||
positionY: n.positionY,
|
||||
})),
|
||||
edges: edges.map((e) => ({
|
||||
id: e.id,
|
||||
sourceNodeId: e.sourceNodeId,
|
||||
targetNodeId: e.targetNodeId,
|
||||
sourceHandle: e.sourceHandle,
|
||||
})),
|
||||
};
|
||||
|
||||
return res.status(200).json(exportData);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflows, workflowNodes, workflowEdges } from "@/db/schema/workflows.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
|
||||
if (req.method !== "PUT") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const [workflow] = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
|
||||
|
||||
const { nodes, edges, viewport } = req.body;
|
||||
|
||||
await appDb.delete(workflowEdges).where(eq(workflowEdges.workflowId, id));
|
||||
await appDb.delete(workflowNodes).where(eq(workflowNodes.workflowId, id));
|
||||
|
||||
if (nodes && nodes.length > 0) {
|
||||
await appDb.insert(workflowNodes).values(
|
||||
nodes.map((n: any) => ({
|
||||
id: n.id,
|
||||
workflowId: id,
|
||||
type: n.type,
|
||||
subType: n.subType,
|
||||
data: typeof n.data === "string" ? n.data : JSON.stringify(n.data),
|
||||
positionX: n.positionX ?? n.position?.x ?? 0,
|
||||
positionY: n.positionY ?? n.position?.y ?? 0,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
if (edges && edges.length > 0) {
|
||||
await appDb.insert(workflowEdges).values(
|
||||
edges.map((e: any) => ({
|
||||
id: e.id,
|
||||
workflowId: id,
|
||||
sourceNodeId: e.sourceNodeId ?? e.source,
|
||||
targetNodeId: e.targetNodeId ?? e.target,
|
||||
sourceHandle: e.sourceHandle ?? null,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
if (viewport) {
|
||||
await appDb.update(workflows).set({
|
||||
viewport: typeof viewport === "string" ? viewport : JSON.stringify(viewport),
|
||||
}).where(eq(workflows.id, id));
|
||||
}
|
||||
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflows, workflowNodes, workflowEdges, workflowRuns } from "@/db/schema/workflows.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq, and, desc } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
|
||||
if (req.method === "GET") {
|
||||
const [workflow] = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
|
||||
|
||||
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, id));
|
||||
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, id));
|
||||
const [lastRun] = await appDb
|
||||
.select()
|
||||
.from(workflowRuns)
|
||||
.where(eq(workflowRuns.workflowId, id))
|
||||
.orderBy(desc(workflowRuns.startedAt))
|
||||
.limit(1);
|
||||
|
||||
return res.status(200).json({ ...workflow, nodes, edges, lastRun: lastRun || null });
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { name, description, enabled, cronSchedule, viewport } = req.body;
|
||||
const updates: Record<string, any> = {};
|
||||
if (name !== undefined) updates.name = name;
|
||||
if (description !== undefined) updates.description = description;
|
||||
if (enabled !== undefined) updates.enabled = enabled;
|
||||
if (cronSchedule !== undefined) updates.cronSchedule = cronSchedule;
|
||||
if (viewport !== undefined) updates.viewport = viewport;
|
||||
|
||||
await appDb.update(workflows).set(updates).where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
const [updated] = await appDb.select().from(workflows).where(eq(workflows.id, id));
|
||||
|
||||
// Re-register or unregister cron schedule
|
||||
if (enabled !== undefined || cronSchedule !== undefined) {
|
||||
const { registerWorkflow, unregisterWorkflow } = await import("@/lib/workflow/scheduler");
|
||||
if (updated.enabled && updated.cronSchedule) {
|
||||
await registerWorkflow(id, updated.cronSchedule, updated.ownerId);
|
||||
} else {
|
||||
unregisterWorkflow(id);
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(200).json(updated);
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
const { unregisterWorkflow } = await import("@/lib/workflow/scheduler");
|
||||
unregisterWorkflow(id);
|
||||
await appDb.delete(workflows).where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
return res.status(204).end();
|
||||
}
|
||||
|
||||
return res.status(405).json({ message: "Method not allowed" });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { executeWorkflow } from "@/lib/workflow/engine";
|
||||
import { appDb } from "@/db";
|
||||
import { workflowRuns } from "@/db/schema/workflows.schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
|
||||
const { mode } = req.body || {};
|
||||
const trigger = mode === "debug" ? "debug" : "manual";
|
||||
|
||||
try {
|
||||
const runId = await executeWorkflow(id, trigger as any, currentUser);
|
||||
const [run] = await appDb.select().from(workflowRuns).where(eq(workflowRuns.id, runId));
|
||||
return res.status(200).json(run);
|
||||
} catch (error: any) {
|
||||
return res.status(500).json({ message: error.message || "Workflow execution failed" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflowRuns, workflows } from "@/db/schema/workflows.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq, and, desc } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
|
||||
// Verify ownership
|
||||
const [workflow] = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
|
||||
|
||||
const runs = await appDb
|
||||
.select()
|
||||
.from(workflowRuns)
|
||||
.where(eq(workflowRuns.workflowId, id))
|
||||
.orderBy(desc(workflowRuns.startedAt))
|
||||
.limit(20);
|
||||
|
||||
return res.status(200).json(runs);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflows, workflowNodes, workflowEdges, workflowRuns } from "@/db/schema/workflows.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { id, runId } = req.query as { id: string; runId: string };
|
||||
|
||||
// Verify ownership
|
||||
const [workflow] = await appDb
|
||||
.select()
|
||||
.from(workflows)
|
||||
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
|
||||
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
|
||||
|
||||
const [run] = await appDb
|
||||
.select()
|
||||
.from(workflowRuns)
|
||||
.where(and(eq(workflowRuns.id, runId), eq(workflowRuns.workflowId, id)));
|
||||
if (!run) return res.status(404).json({ message: "Run not found" });
|
||||
|
||||
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, id));
|
||||
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, id));
|
||||
|
||||
return res.status(200).json({
|
||||
run,
|
||||
workflow: { ...workflow, nodes, edges },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { appDb } from "@/db";
|
||||
import { workflows, workflowNodes, workflowEdges } from "@/db/schema/workflows.schema";
|
||||
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
const currentUser = await getCurrentUser(req);
|
||||
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
|
||||
|
||||
const { name, description, viewport, nodes, edges } = req.body;
|
||||
|
||||
if (!nodes || !Array.isArray(nodes)) {
|
||||
return res.status(400).json({ message: "Invalid workflow format: nodes array required" });
|
||||
}
|
||||
|
||||
const workflowId = randomUUID();
|
||||
const webhookToken = randomUUID();
|
||||
|
||||
// Create ID mapping for imported nodes
|
||||
const idMap = new Map<string, string>();
|
||||
for (const node of nodes) {
|
||||
idMap.set(node.id, randomUUID());
|
||||
}
|
||||
|
||||
await appDb.insert(workflows).values({
|
||||
id: workflowId,
|
||||
ownerId: currentUser.id,
|
||||
name: name || "Imported Workflow",
|
||||
description: description || null,
|
||||
viewport: viewport || '{"x":0,"y":0,"zoom":1}',
|
||||
webhookToken,
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
if (nodes.length > 0) {
|
||||
await appDb.insert(workflowNodes).values(
|
||||
nodes.map((n: any) => ({
|
||||
id: idMap.get(n.id) || randomUUID(),
|
||||
workflowId,
|
||||
type: n.type,
|
||||
subType: n.subType,
|
||||
data: typeof n.data === "string" ? n.data : JSON.stringify(n.data || {}),
|
||||
positionX: n.positionX || 0,
|
||||
positionY: n.positionY || 0,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
if (edges && edges.length > 0) {
|
||||
await appDb.insert(workflowEdges).values(
|
||||
edges.map((e: any) => ({
|
||||
id: randomUUID(),
|
||||
workflowId,
|
||||
sourceNodeId: idMap.get(e.sourceNodeId) || e.sourceNodeId,
|
||||
targetNodeId: idMap.get(e.targetNodeId) || e.targetNodeId,
|
||||
sourceHandle: e.sourceHandle || null,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
const [created] = await appDb.select().from(workflows).where(eq(workflows.id, workflowId));
|
||||
return res.status(201).json(created);
|
||||
}
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user