diff --git a/bun.lockb b/bun.lockb index f521ce9..df9c8e4 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index 88b0984..e0f750a 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "@types/react-autosuggest": "^10.1.11", "@types/react-calendar-heatmap": "^1.6.7", "@types/react-window": "^1.8.8", + "@xyflow/react": "^12.10.2", "ai": "^6.0.86", "axios": "^1.7.4", "chrono-node": "^1.4.9", @@ -66,6 +67,7 @@ "lucide-react": "^0.428.0", "next": "14.2.5", "next-themes": "^0.3.0", + "node-cron": "^4.2.1", "pg": "^8.12.0", "qs": "^6.13.0", "react": "^18", @@ -91,6 +93,7 @@ "@types/leaflet": "^1.9.15", "@types/leaflet.heat": "^0.2.4", "@types/node": "^20", + "@types/node-cron": "^3.0.11", "@types/pg": "^8.11.6", "@types/react": "^18", "@types/react-dom": "^18", diff --git a/src/components/workflows/NodePalette.tsx b/src/components/workflows/NodePalette.tsx new file mode 100644 index 0000000..4ffc7c4 --- /dev/null +++ b/src/components/workflows/NodePalette.tsx @@ -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 ( +
+

{title}

+
+ {items.map((item) => { + const Icon = item.icon; + return ( +
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" + > + + {item.label} +
+ ); + })} +
+
+ ); +} + +export default function NodePalette() { + return ( +
+

Nodes

+ + + +
+ ); +} diff --git a/src/components/workflows/config/ActionConfig.tsx b/src/components/workflows/config/ActionConfig.tsx new file mode 100644 index 0000000..09a62cc --- /dev/null +++ b/src/components/workflows/config/ActionConfig.tsx @@ -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([]); + const [loading, setLoading] = useState(false); + const [selectedAlbum, setSelectedAlbum] = useState(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 ( + + + + + + + + + {loading ? "Loading..." : "No albums found."} + + {albums.map((album) => ( + { + setSelectedAlbum(album); + onChange(album.id, album.albumName); + setOpen(false); + }} + className="flex items-center gap-2" + > + {album.albumName} + + + ))} + + + + + + ); +} + +export default function ActionConfig({ subType, config, onChange }: ActionConfigProps) { + if (subType === "create_album") { + return ( +
+ + onChange({ ...config, nameTemplate: e.target.value })} + /> +
+ {templateVars.map((v) => ( + onChange({ ...config, nameTemplate: (config.nameTemplate || "") + v })} + > + {v} + + ))} +
+
+ ); + } + + if (subType === "add_to_album" || subType === "remove_from_album") { + return ( +
+ + onChange({ ...config, albumId, albumName })} + /> +
+ ); + } + + if (subType === "tag") { + return ( +
+ + onChange({ ...config, tagName: e.target.value })} + /> +
+ ); + } + + // favorite, unfavorite, archive — no config needed + return

No configuration needed.

; +} diff --git a/src/components/workflows/config/ConditionEditor.tsx b/src/components/workflows/config/ConditionEditor.tsx new file mode 100644 index 0000000..084e63b --- /dev/null +++ b/src/components/workflows/config/ConditionEditor.tsx @@ -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 = { + 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([]); + 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 ( +
+ {/* Selected people chips */} + {selectedPeople.length > 0 && ( +
+ {selectedPeople.map((p) => ( + + ))} +
+ )} + + {/* Picker */} + + + + + + + + + {loading ? "Loading..." : "No people found."} + + {people.map((person) => ( + togglePerson(person)} + className="flex items-center gap-2" + > + + {person.name || "Unknown"} + + + ))} + + + + + +
+ ); +} + +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 ( +
+ + onChange({ ...condition, [condition.type]: e.target.value })} /> +
+ ); + case "camera_make": + return onChange({ ...condition, make: e.target.value })} />; + case "camera_model": + return onChange({ ...condition, model: e.target.value })} />; + case "lens": + return onChange({ ...condition, lensModel: e.target.value })} />; + case "asset_type": + return ( + + ); + case "date_range": + return ( +
+ onChange({ ...condition, after: e.target.value })} /> + onChange({ ...condition, before: e.target.value })} /> +
+ ); + case "date_relative": + return ( +
+ Last + onChange({ ...condition, lastDays: parseInt(e.target.value) || 0 })} /> + days +
+ ); + case "iso_range": + case "focal_length": + return ( +
+ onChange({ ...condition, min: parseFloat(e.target.value) || undefined })} /> + onChange({ ...condition, max: parseFloat(e.target.value) || undefined })} /> +
+ ); + case "rating": + return ( +
+ onChange({ ...condition, min: parseInt(e.target.value) || undefined })} /> + onChange({ ...condition, max: parseInt(e.target.value) || undefined })} /> +
+ ); + case "is_favorited": + return ( + + ); + case "person": + return ( +
+ + onChange({ ...condition, personIds, personNames })} + /> +
+ ); + case "geo_radius": + return ( +
+
+ onChange({ ...condition, lat: parseFloat(e.target.value) || 0 })} /> + onChange({ ...condition, lng: parseFloat(e.target.value) || 0 })} /> +
+
+ onChange({ ...condition, radiusKm: parseFloat(e.target.value) || 0 })} /> + km +
+
+ ); + case "day_of_week": + return ( +
+ {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day, i) => { + const days: number[] = condition.days || []; + const active = days.includes(i); + return ( + + ); + })} +
+ ); + case "not_in_album": + case "person_unnamed": + return null; + case "not_in_specific_album": + return 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 ( +
+ {conditions.map((condition, i) => ( +
+
+ + +
+ updateCondition(i, c)} /> + {i < conditions.length - 1 && ( +
+ AND +
+ )} +
+ ))} + +
+ ); +} diff --git a/src/components/workflows/config/IfConfig.tsx b/src/components/workflows/config/IfConfig.tsx new file mode 100644 index 0000000..6bdfe43 --- /dev/null +++ b/src/components/workflows/config/IfConfig.tsx @@ -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 ( +
+
+ +

All conditions must match for the TRUE branch.

+
+ onChange({ ...config, conditions })} + /> +
+ ); +} diff --git a/src/components/workflows/config/SwitchConfig.tsx b/src/components/workflows/config/SwitchConfig.tsx new file mode 100644 index 0000000..60b8b65 --- /dev/null +++ b/src/components/workflows/config/SwitchConfig.tsx @@ -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) => { + const next = [...cases]; + next[index] = { ...next[index], ...updates }; + onChange({ ...config, cases: next }); + }; + + return ( +
+
+ +

First matching case wins. Non-matching assets go to Default.

+
+ {cases.map((c: SwitchCase, i: number) => ( +
+
+ updateCase(i, { label: e.target.value })} + placeholder="Case label" + /> + +
+ updateCase(i, { conditions })} + /> +
+ ))} + +
+ ); +} diff --git a/src/components/workflows/config/TriggerConfig.tsx b/src/components/workflows/config/TriggerConfig.tsx new file mode 100644 index 0000000..c645a22 --- /dev/null +++ b/src/components/workflows/config/TriggerConfig.tsx @@ -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

No configuration needed. Use the Run button to trigger manually.

; + } + + if (subType === "schedule") { + return ( +
+ + onChange({ ...config, cron: e.target.value })} + /> +

+ Examples: 0 */6 * * * (every 6h), 0 9 * * 1 (Mon 9am) +

+
+ ); + } + + if (subType === "webhook") { + const url = webhookToken ? `${window.location.origin}/api/webhooks/${webhookToken}` : "Save workflow first"; + return ( +
+ +
+ +
+

+ Configure this URL in Immich admin webhook settings. +

+
+ ); + } + + return null; +} diff --git a/src/components/workflows/config/index.ts b/src/components/workflows/config/index.ts new file mode 100644 index 0000000..59e61d1 --- /dev/null +++ b/src/components/workflows/config/index.ts @@ -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"; diff --git a/src/components/workflows/nodes/ActionNode.tsx b/src/components/workflows/nodes/ActionNode.tsx new file mode 100644 index 0000000..290d7d4 --- /dev/null +++ b/src/components/workflows/nodes/ActionNode.tsx @@ -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 = { + create_album: FolderPlus, + add_to_album: FolderInput, + remove_from_album: FolderMinus, + favorite: Heart, + unfavorite: HeartOff, + archive: Archive, + tag: Tag, +}; + +const actionLabels: Record = { + create_album: "Create Album", + add_to_album: "Add to Album", + remove_from_album: "Remove from Album", + favorite: "Favorite", + unfavorite: "Unfavorite", + archive: "Archive", + tag: "Add Tag", +}; + +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 ( +
+ +
+
+ +
+
+

{label}

+ {subType === "create_album" && config.nameTemplate && ( +

{config.nameTemplate}

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

{config.tagName}

+ )} +
+
+
+ ); +} diff --git a/src/components/workflows/nodes/IfNode.tsx b/src/components/workflows/nodes/IfNode.tsx new file mode 100644 index 0000000..4f64aea --- /dev/null +++ b/src/components/workflows/nodes/IfNode.tsx @@ -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 ( +
+ +
+
+ +
+

IF

+
+ {conditions.length > 0 ? ( +
+ {conditions.map((c: any, i: number) => ( +

+ {c.type}{c.city ? `: ${c.city}` : ""}{c.personId ? " (person)" : ""}{c.value !== undefined ? `: ${c.value}` : ""} +

+ ))} +
+ ) : ( +

No conditions set

+ )} +
+
+ TRUE + +
+
+ FALSE + +
+
+
+ ); +} diff --git a/src/components/workflows/nodes/SwitchNode.tsx b/src/components/workflows/nodes/SwitchNode.tsx new file mode 100644 index 0000000..2e70f10 --- /dev/null +++ b/src/components/workflows/nodes/SwitchNode.tsx @@ -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 ( +
+ +
+
+ +
+

SWITCH

+ {cases.length} cases +
+ {cases.length > 0 && ( +
+ {cases.map((c: any, i: number) => ( +

+ {c.label || `Case ${i + 1}`} +

+ ))} +
+ )} +
+ {cases.map((c: any, i: number) => ( +
+ {c.label || `C${i + 1}`} + +
+ ))} +
+ DEF + +
+
+
+ ); +} diff --git a/src/components/workflows/nodes/TriggerNode.tsx b/src/components/workflows/nodes/TriggerNode.tsx new file mode 100644 index 0000000..91e2bdb --- /dev/null +++ b/src/components/workflows/nodes/TriggerNode.tsx @@ -0,0 +1,47 @@ +import { Handle, Position, NodeProps } from "@xyflow/react"; +import { FilePlus, FileEdit, Database } from "lucide-react"; + +const triggerIcons: Record = { + new_asset: FilePlus, + asset_updated: FileEdit, + all_assets: Database, +}; + +const triggerLabels: Record = { + new_asset: "New Asset", + asset_updated: "Asset Updated", + all_assets: "All Assets", +}; + +const triggerDescriptions: Record = { + 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 ( +
+
+
+ +
+
+

{label}

+

+ {description} + {lookbackMin && subType !== "all_assets" ? ` + ${lookbackMin}m buffer` : ""} +

+
+
+ +
+ ); +} diff --git a/src/components/workflows/nodes/index.ts b/src/components/workflows/nodes/index.ts new file mode 100644 index 0000000..7227b8a --- /dev/null +++ b/src/components/workflows/nodes/index.ts @@ -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, +}; diff --git a/src/config/constants/sidebarNavs.tsx b/src/config/constants/sidebarNavs.tsx index 7d84e7f..ebb74b1 100644 --- a/src/config/constants/sidebarNavs.tsx +++ b/src/config/constants/sidebarNavs.tsx @@ -1,4 +1,4 @@ -import { Copy, GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, PackageSearch, Rewind, Search, Settings, 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 = [ // { @@ -59,6 +59,11 @@ export const sidebarNavs = [ link: "/assets/bulk-duplicate-finder", icon: , }, + { + title: "Workflows", + link: "/workflows", + icon: , + }, { title: "Orphan Finder", link: "/assets/orphan-finder", diff --git a/src/config/routes.ts b/src/config/routes.ts index 180cfcf..5ecd930 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -102,4 +102,17 @@ export const VALIDATE_PERMISSIONS_PATH = BASE_API_ENDPOINT + "/validate-permissi // 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; \ No newline at end of file +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; \ No newline at end of file diff --git a/src/db/migrations/0002_thin_triton.sql b/src/db/migrations/0002_thin_triton.sql new file mode 100644 index 0000000..ad576f7 --- /dev/null +++ b/src/db/migrations/0002_thin_triton.sql @@ -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`); \ No newline at end of file diff --git a/src/db/migrations/0003_spooky_lockheed.sql b/src/db/migrations/0003_spooky_lockheed.sql new file mode 100644 index 0000000..fd5957d --- /dev/null +++ b/src/db/migrations/0003_spooky_lockheed.sql @@ -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 +); diff --git a/src/db/migrations/meta/0002_snapshot.json b/src/db/migrations/meta/0002_snapshot.json new file mode 100644 index 0000000..5c49fa1 --- /dev/null +++ b/src/db/migrations/meta/0002_snapshot.json @@ -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": {} + } +} \ No newline at end of file diff --git a/src/db/migrations/meta/0003_snapshot.json b/src/db/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..6a8aa04 --- /dev/null +++ b/src/db/migrations/meta/0003_snapshot.json @@ -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": {} + } +} \ No newline at end of file diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json index 05662f3..82c82f6 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -15,6 +15,20 @@ "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 } ] } \ No newline at end of file diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index df0931d..3b76777 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -1,3 +1,4 @@ export * from "./settings.schema"; export * from "./apiKeys.schema"; export * from "./importJobs.schema"; +export * from "./workflows.schema"; diff --git a/src/db/schema/workflows.schema.ts b/src/db/schema/workflows.schema.ts new file mode 100644 index 0000000..d7e30ab --- /dev/null +++ b/src/db/schema/workflows.schema.ts @@ -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()), +}); diff --git a/src/handlers/api/workflow.handler.ts b/src/handlers/api/workflow.handler.ts new file mode 100644 index 0000000..42c06f6 --- /dev/null +++ b/src/handlers/api/workflow.handler.ts @@ -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 => { + return API.get(LIST_WORKFLOWS_PATH); +}; + +export const createWorkflow = async (data: { name: string; description?: string }): Promise => { + return API.post(CREATE_WORKFLOW_PATH, data); +}; + +export const getWorkflow = async (id: string): Promise => { + return API.get(GET_WORKFLOW_PATH(id)); +}; + +export const updateWorkflow = async (id: string, data: Partial): Promise => { + return API.put(UPDATE_WORKFLOW_PATH(id), data); +}; + +export const deleteWorkflow = async (id: string): Promise => { + return API.delete(DELETE_WORKFLOW_PATH(id)); +}; + +export const saveWorkflowGraph = async ( + id: string, + data: { nodes: any[]; edges: any[]; viewport?: any } +): Promise => { + return API.put(SAVE_WORKFLOW_GRAPH_PATH(id), data); +}; + +export const runWorkflow = async (id: string, mode?: "manual" | "debug"): Promise => { + return API.post(RUN_WORKFLOW_PATH(id), { mode }); +}; + +export const getWorkflowRuns = async (id: string): Promise => { + return API.get(WORKFLOW_RUNS_PATH(id)); +}; + +export const exportWorkflow = async (id: string): Promise => { + return API.get(EXPORT_WORKFLOW_PATH(id)); +}; + +export const importWorkflow = async (data: IWorkflowExport): Promise => { + return API.post(IMPORT_WORKFLOW_PATH, data); +}; diff --git a/src/lib/workflow/actionExecutor.ts b/src/lib/workflow/actionExecutor.ts new file mode 100644 index 0000000..342810a --- /dev/null +++ b/src/lib/workflow/actionExecutor.ts @@ -0,0 +1,168 @@ +import { ENV } from "@/config/environment"; +import { db } from "@/config/db"; +import { exif } from "@/schema"; +import { assets } from "@/schema/assets.schema"; +import { person } from "@/schema/person.schema"; +import { assetFaces } from "@/schema/assetFaces.schema"; +import { eq, inArray, sql, desc } from "drizzle-orm"; +import { IUser } from "@/types/user"; +import { getUserHeaders } from "@/helpers/user.helper"; + +interface ActionResult { + action: string; + assetsProcessed: number; + albumId?: string; + albumName?: string; + error?: string; +} + +async function immichFetch(path: string, method: string, body: any, user: IUser): Promise { + const res = await fetch(`${ENV.IMMICH_URL}/api${path}`, { + method, + headers: { + ...getUserHeaders(user), + "Content-Type": "application/json", + }, + 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 { + 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(); + 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(); + 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 { + 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}` }; + } +} diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts new file mode 100644 index 0000000..e695515 --- /dev/null +++ b/src/lib/workflow/conditionBuilder.ts @@ -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; + } +} diff --git a/src/lib/workflow/engine.ts b/src/lib/workflow/engine.ts new file mode 100644 index 0000000..bd63860 --- /dev/null +++ b/src/lib/workflow/engine.ts @@ -0,0 +1,357 @@ +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"; + +async function resolveAssetTrigger( + subType: string, + workflowId: string, + userId: string, + lookbackMinutes: number = 0, +): Promise { + // 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(); + } + + // Apply lookback buffer + if (lookbackMinutes > 0) { + sinceDate = new Date(sinceDate.getTime() - lookbackMinutes * 60 * 1000); + } + + 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 | 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)])); + } + + 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); + // For new_asset: skip any asset we've ever processed + candidateIds = rows.map((r) => r.id).filter((id) => !processedMap?.has(id)); + } 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); + // 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); + } else { + // all_assets — no dedup + const rows = await db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .where(and(...baseConditions)) + .limit(10000); + return rows.map((r) => r.id); + } + + return candidateIds; +} + +interface DebugStep { + nodeId: string; + nodeType: string; + subType: string; + label: string; + inputAssets: number; + outputAssets: Record; + 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 { + const isDebug = trigger === "debug"; + + // Create run record + const runId = randomUUID(); + await appDb.insert(workflowRuns).values({ + id: runId, + workflowId, + trigger, + status: "running", + }); + + 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)); + + // Build adjacency map: nodeId -> { handle -> targetNodeId[] } + const adjacency = new Map>(); + 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"); + } + + const result: RunResult = { matchedAssets: 0, assetIds: [], actions: [] }; + const debugSteps: DebugStep[] = []; + const allProcessedAssetIds = new Set(); + + // 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; + const assetIds = await resolveAssetTrigger(triggerNode.subType, workflowId, user.id, lookback); + result.matchedAssets += assetIds.length; + + 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 + while (queue.length > 0) { + const { nodeId, assetIds } = queue.shift()!; + const node = nodeMap.get(nodeId); + if (!node) continue; + + const config = JSON.parse(node.data || "{}"); + + if (node.type === "logic") { + if (node.subType === "if") { + // Query assets matching conditions, scoped to incoming set + const conditions = config.conditions || []; + 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)); + } + + 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; + + for (const c of cases) { + 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 = []; + } + + 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 = {}; + cases.forEach((c: any, i: number) => { caseOutput[c.label || `case_${i}`] = 0; }); + // Already routed above, just log + debugSteps.push({ + nodeId: node.id, + nodeType: "logic", + subType: "switch", + label: `SWITCH (${cases.length} cases)`, + inputAssets: assetIds?.length || 0, + outputAssets: { ...caseOutput, default: (remaining || []).length }, + }); + + // 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)); + + 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); + 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, + })) + ); + } + } + } + } + } + + // 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)); + + return runId; + + } catch (error: any) { + await appDb.update(workflowRuns).set({ + status: "failed", + error: error.message || "Unknown error", + completedAt: new Date(), + }).where(eq(workflowRuns.id, runId)); + + throw error; + } +} diff --git a/src/lib/workflow/scheduler.ts b/src/lib/workflow/scheduler.ts new file mode 100644 index 0000000..fe1ba7e --- /dev/null +++ b/src/lib/workflow/scheduler.ts @@ -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(); + +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`); +} diff --git a/src/pages/api/webhooks/[token].ts b/src/pages/api/webhooks/[token].ts new file mode 100644 index 0000000..952b00b --- /dev/null +++ b/src/pages/api/webhooks/[token].ts @@ -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" }); + } +} diff --git a/src/pages/api/workflows/[id]/export.ts b/src/pages/api/workflows/[id]/export.ts new file mode 100644 index 0000000..93da9ca --- /dev/null +++ b/src/pages/api/workflows/[id]/export.ts @@ -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); +} diff --git a/src/pages/api/workflows/[id]/graph.ts b/src/pages/api/workflows/[id]/graph.ts new file mode 100644 index 0000000..12cabee --- /dev/null +++ b/src/pages/api/workflows/[id]/graph.ts @@ -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 }); +} diff --git a/src/pages/api/workflows/[id]/index.ts b/src/pages/api/workflows/[id]/index.ts new file mode 100644 index 0000000..a12311f --- /dev/null +++ b/src/pages/api/workflows/[id]/index.ts @@ -0,0 +1,52 @@ +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 = {}; + 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)); + return res.status(200).json(updated); + } + + if (req.method === "DELETE") { + 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" }); +} diff --git a/src/pages/api/workflows/[id]/run.ts b/src/pages/api/workflows/[id]/run.ts new file mode 100644 index 0000000..a611ed3 --- /dev/null +++ b/src/pages/api/workflows/[id]/run.ts @@ -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" }); + } +} diff --git a/src/pages/api/workflows/[id]/runs.ts b/src/pages/api/workflows/[id]/runs.ts new file mode 100644 index 0000000..3b96401 --- /dev/null +++ b/src/pages/api/workflows/[id]/runs.ts @@ -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); +} diff --git a/src/pages/api/workflows/[id]/runs/[runId].ts b/src/pages/api/workflows/[id]/runs/[runId].ts new file mode 100644 index 0000000..42f3f96 --- /dev/null +++ b/src/pages/api/workflows/[id]/runs/[runId].ts @@ -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 }, + }); +} diff --git a/src/pages/api/workflows/import.ts b/src/pages/api/workflows/import.ts new file mode 100644 index 0000000..31ea081 --- /dev/null +++ b/src/pages/api/workflows/import.ts @@ -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(); + 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); +} diff --git a/src/pages/api/workflows/index.ts b/src/pages/api/workflows/index.ts new file mode 100644 index 0000000..3245468 --- /dev/null +++ b/src/pages/api/workflows/index.ts @@ -0,0 +1,37 @@ +import { appDb } from "@/db"; +import { workflows } from "@/db/schema/workflows.schema"; +import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; +import { eq, desc } from "drizzle-orm"; +import { NextApiRequest, NextApiResponse } from "next"; +import { randomUUID } from "crypto"; + +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 rows = await appDb + .select() + .from(workflows) + .where(eq(workflows.ownerId, currentUser.id)) + .orderBy(desc(workflows.updatedAt)); + return res.status(200).json(rows); + } + + if (req.method === "POST") { + const { name, description } = req.body; + const id = randomUUID(); + const webhookToken = randomUUID(); + await appDb.insert(workflows).values({ + id, + ownerId: currentUser.id, + name: name || "Untitled Workflow", + description: description || null, + webhookToken, + }); + const [row] = await appDb.select().from(workflows).where(eq(workflows.id, id)); + return res.status(201).json(row); + } + + return res.status(405).json({ message: "Method not allowed" }); +} diff --git a/src/pages/workflows/[id].tsx b/src/pages/workflows/[id].tsx new file mode 100644 index 0000000..1063b96 --- /dev/null +++ b/src/pages/workflows/[id].tsx @@ -0,0 +1,547 @@ +import "@xyflow/react/dist/style.css"; + +import { useRouter } from "next/router"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + ReactFlow, + Background, + Controls, + addEdge, + useNodesState, + useEdgesState, + Connection, + Node, + Edge, + ReactFlowProvider, + useReactFlow, +} from "@xyflow/react"; +import { nodeTypes } from "@/components/workflows/nodes"; +import NodePalette from "@/components/workflows/NodePalette"; +import { IfConfig, SwitchConfig, ActionConfig } from "@/components/workflows/config"; +import { getWorkflow, saveWorkflowGraph, updateWorkflow, runWorkflow, getWorkflowRuns } from "@/handlers/api/workflow.handler"; +import { IWorkflowWithDetails } from "@/types/workflow"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Switch } from "@/components/ui/switch"; +import { toast } from "@/components/ui/use-toast"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Label } from "@/components/ui/label"; +import { Badge } from "@/components/ui/badge"; +import { ASSET_THUMBNAIL_PATH } from "@/config/routes"; +import { IWorkflowRun } from "@/types/workflow"; +import { ArrowLeft, Play, Save, Clock, Webhook, History, ChevronUp, ChevronDown, Bug } from "lucide-react"; +import { format } from "date-fns"; +import Link from "next/link"; +import Loader from "@/components/ui/loader"; + +function generateId() { + return Math.random().toString(36).substring(2, 15); +} + +// Map DB node to React Flow node +function dbNodeToFlowNode(n: any): Node { + let flowType = "trigger"; + if (n.type === "logic") flowType = n.subType === "switch" ? "logic_switch" : "logic_if"; + else if (n.type === "action") flowType = "action"; + + const config = typeof n.data === "string" ? JSON.parse(n.data || "{}") : (n.data || {}); + + return { + id: n.id, + type: flowType, + position: { x: n.positionX, y: n.positionY }, + data: { subType: n.subType, config, label: n.subType }, + }; +} + +// Map DB edge to React Flow edge +function dbEdgeToFlowEdge(e: any): Edge { + return { + id: e.id, + source: e.sourceNodeId, + target: e.targetNodeId, + sourceHandle: e.sourceHandle || undefined, + animated: true, + }; +} + +// Map React Flow node back to DB format +function flowNodeToDb(n: Node) { + let dbType = "trigger"; + let dbSubType = (n.data?.subType as string) || "manual"; + if (n.type === "logic_if") { dbType = "logic"; dbSubType = "if"; } + else if (n.type === "logic_switch") { dbType = "logic"; dbSubType = "switch"; } + else if (n.type === "action") { dbType = "action"; } + + return { + id: n.id, + type: dbType, + subType: dbSubType, + data: JSON.stringify(n.data?.config || {}), + positionX: n.position.x, + positionY: n.position.y, + }; +} + +function flowEdgeToDb(e: Edge) { + return { + id: e.id, + sourceNodeId: e.source, + targetNodeId: e.target, + sourceHandle: e.sourceHandle || null, + }; +} + +function WorkflowEditorInner() { + const router = useRouter(); + const { id } = router.query as { id: string }; + const reactFlowWrapper = useRef(null); + const { screenToFlowPosition } = useReactFlow(); + + const [workflow, setWorkflow] = useState(null); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [running, setRunning] = useState(false); + const [workflowName, setWorkflowName] = useState(""); + const [enabled, setEnabled] = useState(false); + const [cronSchedule, setCronSchedule] = useState(""); + const [webhookToken, setWebhookToken] = useState(null); + const [selectedNode, setSelectedNode] = useState(null); + const [runs, setRuns] = useState([]); + const [showRuns, setShowRuns] = useState(false); + const [expandedRunId, setExpandedRunId] = useState(null); + + const [nodes, setNodes, onNodesChange] = useNodesState([] as Node[]); + const [edges, setEdges, onEdgesChange] = useEdgesState([] as Edge[]); + + useEffect(() => { + if (!id) return; + setLoading(true); + getWorkflow(id) + .then((data) => { + setWorkflow(data); + setWorkflowName(data.name); + setEnabled(data.enabled); + setCronSchedule(data.cronSchedule || ""); + setWebhookToken(data.webhookToken || null); + setNodes(data.nodes.map(dbNodeToFlowNode)); + setEdges(data.edges.map(dbEdgeToFlowEdge)); + }) + .catch(() => { + toast({ title: "Error", description: "Failed to load workflow", variant: "destructive" }); + }) + .finally(() => setLoading(false)); + + getWorkflowRuns(id).then(setRuns).catch(() => {}); + }, [id]); + + const onConnect = useCallback((connection: Connection) => { + setEdges((eds) => addEdge({ ...connection, animated: true }, eds)); + }, [setEdges]); + + const onDragOver = useCallback((event: React.DragEvent) => { + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + }, []); + + const onDrop = useCallback((event: React.DragEvent) => { + event.preventDefault(); + const data = event.dataTransfer.getData("application/reactflow"); + if (!data) return; + + const { type, subType } = JSON.parse(data); + const position = screenToFlowPosition({ x: event.clientX, y: event.clientY }); + + let flowType = type; + if (type === "logic_if" || type === "logic_switch") flowType = type; + + const newNode: Node = { + id: generateId(), + type: flowType, + position, + data: { subType, config: {}, label: subType }, + }; + + setNodes((nds) => [...nds, newNode]); + }, [screenToFlowPosition, setNodes]); + + const onNodeClick = useCallback((_: any, node: Node) => { + setSelectedNode(node); + }, []); + + const onPaneClick = useCallback(() => { + setSelectedNode(null); + }, []); + + const updateNodeConfig = useCallback((config: any) => { + if (!selectedNode) return; + setNodes((nds) => + nds.map((n) => + n.id === selectedNode.id + ? { ...n, data: { ...n.data, config } } + : n + ) + ); + setSelectedNode((prev) => prev ? { ...prev, data: { ...prev.data, config } } : null); + }, [selectedNode, setNodes]); + + const handleSave = async () => { + if (!id) return; + setSaving(true); + try { + const viewport = JSON.stringify({ x: 0, y: 0, zoom: 1 }); + await saveWorkflowGraph(id, { + nodes: nodes.map(flowNodeToDb), + edges: edges.map(flowEdgeToDb), + viewport, + }); + await updateWorkflow(id, { + name: workflowName, + enabled, + cronSchedule: cronSchedule || null, + } as any); + toast({ title: "Saved", description: "Workflow saved" }); + } catch { + toast({ title: "Error", description: "Failed to save workflow", variant: "destructive" }); + } + setSaving(false); + }; + + const handleRun = async (mode: "manual" | "debug" = "manual") => { + if (!id) return; + setRunning(true); + try { + await runWorkflow(id, mode); + toast({ + title: mode === "debug" ? "Debug Complete" : "Run Complete", + description: mode === "debug" ? "Dry run finished — no actions were executed" : "Workflow execution finished", + }); + getWorkflowRuns(id).then(setRuns).catch(() => {}); + setShowRuns(true); + } catch { + toast({ title: "Error", description: "Failed to run workflow", variant: "destructive" }); + } + setRunning(false); + }; + + const renderConfigPanel = () => { + if (!selectedNode) return ( +
+ Select a node to configure it. +
+ ); + + const { subType, config } = selectedNode.data as { subType: string; config: any }; + const nodeType = selectedNode.type; + + const typeLabel = nodeType === "trigger" ? "Asset Trigger" : nodeType === "logic_if" ? "If" : nodeType === "logic_switch" ? "Switch" : "Action"; + + return ( +
+

{typeLabel}: {subType}

+ {nodeType === "trigger" && ( +
+

+ {subType === "new_asset" && "Selects assets created since the last successful run. On first run, uses workflow creation time."} + {subType === "asset_updated" && "Selects assets updated since the last successful run. On first run, uses workflow creation time."} + {subType === "all_assets" && "Selects all assets in your library. Use with caution on large libraries."} +

+ {subType !== "all_assets" && ( +
+ +
+ updateNodeConfig({ ...config, lookbackMinutes: parseInt(e.target.value) || 0 })} + /> + minutes before last run +
+

+ Extends the time window backwards to catch assets that may have been missed. Set to 0 or leave empty for exact last run time. +

+
+ )} + {workflow?.lastRun?.completedAt ? ( +

+ Last run: {new Date(workflow.lastRun.completedAt).toLocaleString()} +

+ ) : workflow?.createdAt ? ( +

+ No previous runs. Will use since: {new Date(workflow.createdAt).toLocaleString()} +

+ ) : null} +
+ )} + {nodeType === "logic_if" && ( + + )} + {nodeType === "logic_switch" && ( + + )} + {nodeType === "action" && ( + + )} +
+ ); + }; + + if (loading) { + return ( +
+ +
+ ); + } + + return ( +
+ {/* Top bar */} +
+ + + + setWorkflowName(e.target.value)} + /> +
+ Enabled + +
+ +
+ + {/* Schedule config */} + + + + + +
+ + setCronSchedule(e.target.value)} + /> +

+ e.g. 0 */6 * * * (every 6h), 0 9 * * 1 (Mon 9am). Leave empty to disable. +

+
+
+
+ + {/* Webhook URL */} + + + + + +
+ + +

+ Configure this URL in Immich admin webhook settings to trigger this workflow on events. +

+
+
+
+ +
+ + + +
+
+ + {/* Main area */} +
+ {/* Left: Node palette */} + + + {/* Center: Canvas */} +
+ + + + +
+ + {/* Right: Config panel */} +
+ {renderConfigPanel()} +
+
+ + {/* Runs panel */} +
+ + {showRuns && ( +
+ {runs.length === 0 ? ( +

No runs yet. Click Run to execute the workflow.

+ ) : ( +
+ {runs.map((run) => { + const result = run.result ? (typeof run.result === "string" ? JSON.parse(run.result) : run.result) : {}; + const isExpanded = expandedRunId === run.id; + return ( +
+ + {isExpanded && ( +
+ {run.error && ( +

{run.error}

+ )} + {result.actions && result.actions.length > 0 && ( +
+

Actions:

+ {result.actions.map((a: any, i: number) => ( +
+ {a.action}: {a.assetsProcessed} assets + {a.albumName && ` → "${a.albumName}"`} + {a.error && ({a.error})} +
+ ))} +
+ )} + {result.debug && result.debug.length > 0 && ( +
+

Debug Steps:

+
+ {result.debug.map((step: any, i: number) => ( +
+
+ {step.nodeType} + {step.label} +
+ {step.detail &&

{step.detail}

} +
+ In: {step.inputAssets} + {Object.entries(step.outputAssets).map(([k, v]) => ( + {k}: {v as number} + ))} +
+ {step.assetIds && step.assetIds.length > 0 && ( +
+ {step.assetIds.slice(0, 20).map((aid: string) => ( + + ))} + {step.assetIds.length > 20 && +{step.assetIds.length - 20}} +
+ )} +
+ ))} +
+
+ )} + {result.assetIds && result.assetIds.length > 0 && ( +
+

Assets ({result.assetIds.length}):

+
+ {result.assetIds.slice(0, 50).map((assetId: string) => ( + + ))} + {result.assetIds.length > 50 && ( + +{result.assetIds.length - 50} more + )} +
+
+ )} +
+ )} +
+ ); + })} +
+ )} +
+ )} +
+
+ ); +} + +export default function WorkflowEditorPage() { + return ( + + + + ); +} diff --git a/src/pages/workflows/[id]/runs/[runId].tsx b/src/pages/workflows/[id]/runs/[runId].tsx new file mode 100644 index 0000000..bfa1a9b --- /dev/null +++ b/src/pages/workflows/[id]/runs/[runId].tsx @@ -0,0 +1,367 @@ +import "@xyflow/react/dist/style.css"; + +import { useRouter } from "next/router"; +import { useEffect, useMemo, useState } from "react"; +import { + ReactFlow, + Background, + Controls, + Node, + Edge, + ReactFlowProvider, +} from "@xyflow/react"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { ASSET_THUMBNAIL_PATH } from "@/config/routes"; +import { ArrowLeft, CheckCircle, XCircle, Clock, Bug } from "lucide-react"; +import { format } from "date-fns"; +import Link from "next/link"; +import Loader from "@/components/ui/loader"; +import API from "@/lib/api"; +import { Handle, Position, NodeProps } from "@xyflow/react"; +import { + FilePlus, FileEdit, Database, GitBranch, GitFork, + FolderPlus, FolderInput, FolderMinus, Heart, HeartOff, Archive, Tag, +} from "lucide-react"; + +// ---- Annotated Node Components (read-only, with run data) ---- + +function AnnotatedTriggerNode({ data, selected }: NodeProps) { + const subType = data.subType as string; + const step = data.runStep as any; + const icons: Record = { new_asset: FilePlus, asset_updated: FileEdit, all_assets: Database }; + const labels: Record = { new_asset: "New Asset", asset_updated: "Asset Updated", all_assets: "All Assets" }; + const Icon = icons[subType] || FilePlus; + + return ( +
+
+
+ +
+
+

{labels[subType] || "Trigger"}

+ {step &&

{step.detail}

} +
+ {step && ( + + {step.outputAssets?.out || 0} + + )} +
+ {step?.assetIds && step.assetIds.length > 0 && ( +
+ {step.assetIds.slice(0, 8).map((id: string) => ( + + ))} + {step.assetIds.length > 8 && +{step.assetIds.length - 8}} +
+ )} + +
+ ); +} + +function AnnotatedIfNode({ data }: NodeProps) { + const step = data.runStep as any; + + return ( +
+ +
+
+ +
+

IF

+ {step && in: {step.inputAssets}} +
+ {step && ( +
+ true: {step.outputAssets?.true || 0} + false: {step.outputAssets?.false || 0} +
+ )} + {step?.assetIds && step.assetIds.length > 0 && ( +
+ {step.assetIds.slice(0, 6).map((id: string) => ( + + ))} + {step.assetIds.length > 6 && +{step.assetIds.length - 6}} +
+ )} +
+ + +
+
+ ); +} + +function AnnotatedSwitchNode({ data }: NodeProps) { + const step = data.runStep as any; + const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {}; + const cases = config.cases || []; + + return ( +
+ +
+
+ +
+

SWITCH

+ {step && in: {step.inputAssets}} +
+ {step && ( +
+ {Object.entries(step.outputAssets || {}).map(([k, v]) => ( + {k}: {v as number} + ))} +
+ )} +
+ {cases.map((c: any, i: number) => ( + + ))} + +
+
+ ); +} + +function AnnotatedActionNode({ data }: NodeProps) { + const subType = data.subType as string; + const step = data.runStep as any; + const icons: Record = { + create_album: FolderPlus, add_to_album: FolderInput, remove_from_album: FolderMinus, + favorite: Heart, unfavorite: HeartOff, archive: Archive, tag: Tag, + }; + const labels: Record = { + create_album: "Create Album", add_to_album: "Add to Album", remove_from_album: "Remove from Album", + favorite: "Favorite", unfavorite: "Unfavorite", archive: "Archive", tag: "Add Tag", + }; + const Icon = icons[subType] || FolderPlus; + const isDryRun = step?.detail?.includes("DRY RUN"); + + return ( +
+ +
+
+ +
+
+

{labels[subType] || "Action"}

+ {step &&

{step.detail}

} +
+ {step && ( + + {step.inputAssets} + + )} +
+ {step?.assetIds && step.assetIds.length > 0 && ( +
+ {step.assetIds.slice(0, 8).map((id: string) => ( + + ))} + {step.assetIds.length > 8 && +{step.assetIds.length - 8}} +
+ )} +
+ ); +} + +const annotatedNodeTypes = { + trigger: AnnotatedTriggerNode, + logic_if: AnnotatedIfNode, + logic_switch: AnnotatedSwitchNode, + action: AnnotatedActionNode, +}; + +// ---- Page Component ---- + +function dbNodeToFlowNode(n: any, debugSteps: any[]): Node { + let flowType = "trigger"; + if (n.type === "logic") flowType = n.subType === "switch" ? "logic_switch" : "logic_if"; + else if (n.type === "action") flowType = "action"; + + const config = typeof n.data === "string" ? JSON.parse(n.data || "{}") : (n.data || {}); + const runStep = debugSteps.find((s: any) => s.nodeId === n.id) || null; + + return { + id: n.id, + type: flowType, + position: { x: n.positionX, y: n.positionY }, + data: { subType: n.subType, config, label: n.subType, runStep }, + draggable: false, + connectable: false, + selectable: false, + }; +} + +function dbEdgeToFlowEdge(e: any): Edge { + return { + id: e.id, + source: e.sourceNodeId, + target: e.targetNodeId, + sourceHandle: e.sourceHandle || undefined, + animated: true, + }; +} + +function RunDetailInner() { + const router = useRouter(); + const { id, runId } = router.query as { id: string; runId: string }; + + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const [selectedNodeAssets, setSelectedNodeAssets] = useState(null); + + useEffect(() => { + if (!id || !runId) return; + setLoading(true); + API.get(`/api/workflows/${id}/runs/${runId}`) + .then(setData) + .catch(() => {}) + .finally(() => setLoading(false)); + }, [id, runId]); + + const { nodes, edges, run, result } = useMemo(() => { + if (!data) return { nodes: [], edges: [], run: null, result: null }; + + const runData = data.run; + const resultParsed = runData.result ? (typeof runData.result === "string" ? JSON.parse(runData.result) : runData.result) : {}; + const debugSteps = resultParsed.debug || resultParsed.actions?.map((a: any) => ({ + nodeId: "", + nodeType: "action", + subType: a.action, + label: `Action: ${a.action}`, + inputAssets: a.assetsProcessed, + outputAssets: {}, + assetIds: a.assetIds, + })) || []; + + const flowNodes = data.workflow.nodes.map((n: any) => dbNodeToFlowNode(n, debugSteps)); + const flowEdges = data.workflow.edges.map((e: any) => dbEdgeToFlowEdge(e)); + + return { nodes: flowNodes, edges: flowEdges, run: runData, result: resultParsed }; + }, [data]); + + if (loading) { + return
; + } + + if (!data || !run) { + return ( +
+

Run not found

+ +
+ ); + } + + const statusIcon = run.status === "completed" + ? + : run.status === "failed" + ? + : ; + + return ( +
+ {/* Top bar */} +
+ + + + Run Detail +
+ {statusIcon} + + {run.status} + + {run.trigger === "debug" && ( + + + Debug (Dry Run) + + )} +
+ + {run.startedAt ? format(new Date(run.startedAt), "MMM d, yyyy HH:mm:ss") : ""} + + + {result?.matchedAssets || 0} assets processed + +
+ + {/* Main area */} +
+ {/* Graph */} +
+ { + const step = node.data?.runStep as any; + if (step?.assetIds && step.assetIds.length > 0) { + setSelectedNodeAssets(step.assetIds); + } else { + setSelectedNodeAssets(null); + } + }} + onPaneClick={() => setSelectedNodeAssets(null)} + > + + + +
+ + {/* Side panel — asset list for selected node */} + {selectedNodeAssets && ( +
+
+

Assets ({selectedNodeAssets.length})

+ +
+
+ {selectedNodeAssets.map((assetId) => ( + + ))} +
+
+ )} +
+ + {/* Error bar */} + {run.error && ( +
+

{run.error}

+
+ )} +
+ ); +} + +export default function RunDetailPage() { + return ( + + + + ); +} diff --git a/src/pages/workflows/index.tsx b/src/pages/workflows/index.tsx new file mode 100644 index 0000000..188a1b2 --- /dev/null +++ b/src/pages/workflows/index.tsx @@ -0,0 +1,175 @@ +import PageLayout from "@/components/layouts/PageLayout"; +import Header from "@/components/shared/Header"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { AlertDialog } from "@/components/ui/alert-dialog"; +import Loader from "@/components/ui/loader"; +import { listWorkflows, createWorkflow, deleteWorkflow, exportWorkflow, importWorkflow } from "@/handlers/api/workflow.handler"; +import { IWorkflow } from "@/types/workflow"; +import { Plus, Download, Upload, Trash2, Pencil, Workflow } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { useRouter } from "next/router"; +import { toast } from "@/components/ui/use-toast"; +import { format } from "date-fns"; + +export default function WorkflowsPage() { + const router = useRouter(); + const [workflows, setWorkflows] = useState([]); + const [loading, setLoading] = useState(true); + const fileInputRef = useRef(null); + + const fetchWorkflows = async () => { + setLoading(true); + try { + const data = await listWorkflows(); + setWorkflows(data); + } catch { + toast({ title: "Error", description: "Failed to load workflows", variant: "destructive" }); + } + setLoading(false); + }; + + useEffect(() => { + fetchWorkflows(); + }, []); + + const handleCreate = async () => { + try { + const workflow = await createWorkflow({ name: "Untitled Workflow" }); + router.push(`/workflows/${workflow.id}`); + } catch { + toast({ title: "Error", description: "Failed to create workflow", variant: "destructive" }); + } + }; + + const handleDelete = async (id: string) => { + try { + await deleteWorkflow(id); + setWorkflows((prev) => prev.filter((w) => w.id !== id)); + toast({ title: "Deleted", description: "Workflow deleted" }); + } catch { + toast({ title: "Error", description: "Failed to delete workflow", variant: "destructive" }); + } + }; + + const handleExport = async (id: string, name: string) => { + try { + const data = await exportWorkflow(id); + const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${name.replace(/[^a-zA-Z0-9]/g, "_")}.workflow.json`; + a.click(); + URL.revokeObjectURL(url); + } catch { + toast({ title: "Error", description: "Failed to export workflow", variant: "destructive" }); + } + }; + + const handleImport = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + try { + const text = await file.text(); + const data = JSON.parse(text); + const workflow = await importWorkflow(data); + setWorkflows((prev) => [workflow, ...prev]); + toast({ title: "Imported", description: `Workflow "${workflow.name}" imported` }); + } catch { + toast({ title: "Error", description: "Failed to import workflow. Check the file format.", variant: "destructive" }); + } + if (fileInputRef.current) fileInputRef.current.value = ""; + }; + + return ( + +
+ + + +
+ } + /> + + {loading ? ( +
+ ) : workflows.length === 0 ? ( +
+ +

No workflows yet

+

+ Create your first workflow to start automating your library organization. +

+ +
+ ) : ( +
+ {workflows.map((w) => ( + + +
+
+ {w.name} + {w.description && ( + {w.description} + )} +
+ + {w.enabled ? "Enabled" : "Disabled"} + +
+
+ +
+ {w.cronSchedule && Scheduled} + {w.webhookToken && Webhook} + + {w.updatedAt ? format(new Date(w.updatedAt), "MMM d, yyyy") : ""} + +
+
+ + + handleDelete(w.id)} + > + + +
+
+
+ ))} +
+ )} + + ); +} diff --git a/src/types/workflow.d.ts b/src/types/workflow.d.ts new file mode 100644 index 0000000..fd1367b --- /dev/null +++ b/src/types/workflow.d.ts @@ -0,0 +1,85 @@ +export interface IWorkflow { + id: string; + ownerId: string; + name: string; + description: string | null; + enabled: boolean; + cronSchedule: string | null; + webhookToken: string | null; + viewport: string; + createdAt: Date; + updatedAt: Date; +} + +export interface IWorkflowNode { + id: string; + workflowId: string; + type: "trigger" | "logic" | "action"; + subType: string; + data: string; + positionX: number; + positionY: number; + createdAt: Date; +} + +export interface IWorkflowEdge { + id: string; + workflowId: string; + sourceNodeId: string; + targetNodeId: string; + sourceHandle: string | null; + createdAt: Date; +} + +export interface IWorkflowRun { + id: string; + workflowId: string; + trigger: "manual" | "schedule" | "webhook"; + status: "running" | "completed" | "failed"; + result: string; + error: string | null; + startedAt: Date; + completedAt: Date | null; +} + +export interface IWorkflowWithDetails extends IWorkflow { + nodes: IWorkflowNode[]; + edges: IWorkflowEdge[]; + lastRun?: IWorkflowRun | null; +} + +export type ConditionType = + | "person" | "person_unnamed" + | "city" | "state" | "country" | "geo_radius" + | "date_range" | "date_relative" | "day_of_week" + | "camera_make" | "camera_model" | "lens" + | "asset_type" | "iso_range" | "focal_length" + | "rating" | "is_favorited" + | "not_in_album" | "not_in_specific_album"; + +export interface ICondition { + type: ConditionType; + [key: string]: any; +} + +export interface IManualTriggerData {} +export interface IScheduleTriggerData { cron: string; } +export interface IWebhookTriggerData { token: string; } + +export interface IIfNodeData { conditions: ICondition[]; } +export interface ISwitchCase { label: string; conditions: ICondition[]; handle: string; } +export interface ISwitchNodeData { cases: ISwitchCase[]; } + +export interface ICreateAlbumActionData { nameTemplate: string; } +export interface IAddToAlbumActionData { albumId: string; } +export interface IRemoveFromAlbumActionData { albumId: string; } +export interface ITagActionData { tagName: string; } + +export interface IWorkflowExport { + version: number; + name: string; + description: string | null; + viewport: string; + nodes: Omit[]; + edges: Omit[]; +}