feat: auto-assign new Immich albums via keyword rules

Auto-assignment rules were only applied when an admin clicked
"Regeln jetzt anwenden". New albums created in Immich therefore
never reached editorials automatically.

- applyAllRules() syncs every active editorial's keywords against the
  full album list in one pass and grants matches as system actor
- in-process scheduler (src/instrumentation.ts) runs the sync every
  AUTO_RULE_SYNC_INTERVAL_SECONDS (default 120s)
- POST /api/cron/album-sync allows external triggers via CRON_SECRET
- overlapping sync runs coalesce to avoid duplicate grants/emails
This commit is contained in:
Leon Tonhäuser committed 2026-08-25 01:05:04 +02:00
1 parent a3dc56778d
commit dd60fd6ee6
14 files changed
+613 -36

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import "server-only";
import { env } from "@/config/env";
import { autoRuleService } from "./auto-rules";
const DEFAULT_INTERVAL_SECONDS = 120;
const INITIAL_DELAY_MS = 15_000;
const globalForScheduler = globalThis as typeof globalThis & {
__albumAutoRuleSchedulerStarted?: boolean;
};
export function autoRuleSyncIntervalMs(): number {
const seconds = env.AUTO_RULE_SYNC_INTERVAL_SECONDS ?? DEFAULT_INTERVAL_SECONDS;
return Math.max(30, seconds) * 1000;
}
/**
* Periodically applies all album auto-assignment rules so a newly created
* Immich album whose name matches a keyword is granted to the matching
* editorial accounts without any manual step.
*/
export function startAutoRuleScheduler(): void {
if (globalForScheduler.__albumAutoRuleSchedulerStarted) {
return;
}
globalForScheduler.__albumAutoRuleSchedulerStarted = true;
const intervalMs = autoRuleSyncIntervalMs();
const tick = async () => {
try {
const result = await autoRuleService.applyAllRules();
if (result.granted > 0) {
console.log(`[auto-rule-sync] granted ${result.granted} album(s) via auto rules`);
}
} catch (error) {
console.error("[auto-rule-sync] failed:", error);
}
};
const initialTimeout = setTimeout(tick, INITIAL_DELAY_MS);
const interval = setInterval(tick, intervalMs);
// Never keep the Node process alive just for these timers.
initialTimeout.unref?.();
interval.unref?.();
}
+255
View File
@@ -0,0 +1,255 @@
import { beforeEach, expect, test, vi } from "vitest";
import type { AutoRuleRepository, EditorialAutoRule } from "./auto-rules";
import { createAutoRuleService } from "./auto-rules";
import type { AlbumGrantRepository } from "./grants";
vi.mock("@/modules/email/service", () => ({
emailService: {
sendNewAlbumNotification: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock("@/db/client", () => ({ db: {} }));
import { emailService } from "@/modules/email/service";
const editorialA = "1111111a-1111-4111-8111-11111111111a";
const editorialB = "1111111b-1111-4111-8111-11111111111b";
const albumFcBayern = "2222222a-2222-4222-8222-22222222222a";
const albumDfbPokal = "2222222b-2222-4222-8222-22222222222b";
const albumUnrelated = "2222222c-2222-4222-8222-22222222222c";
const adminUuid = "3333333c-3333-4333-8333-33333333333c";
function album(id: string, albumName: string) {
return {
id,
albumName,
description: null,
albumThumbnailAssetId: null,
assetCount: 3,
};
}
type FakeGrant = { editorialId: string; albumId: string };
function createFakeGrantService(initial: FakeGrant[] = []) {
const grants = [...initial];
const grantInputs: Array<{ editorialId: string; immichAlbumId: string; adminUserId: string | null }> = [];
const repository: AlbumGrantRepository = {
async listActiveAlbumIds(editorialId) {
return grants
.filter((grant) => grant.editorialId === editorialId)
.map((grant) => grant.albumId);
},
async grant(input) {
grantInputs.push({
editorialId: input.editorialId,
immichAlbumId: input.immichAlbumId,
adminUserId: input.adminUserId,
});
if (
grants.some(
(grant) =>
grant.editorialId === input.editorialId &&
grant.albumId.toLowerCase() === input.immichAlbumId.toLowerCase(),
)
) {
return false;
}
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId });
return true;
},
async revoke() {
return false;
},
};
return { repository, grants, grantInputs };
}
function createFakeRepository(rules: EditorialAutoRule[]): AutoRuleRepository {
return {
async listRules() {
return [];
},
async listEligibleRules() {
return rules;
},
async createRule() {},
async deleteRule() {},
};
}
function setup(options: {
rules: EditorialAutoRule[];
albums: Array<ReturnType<typeof album>>;
existingGrants?: FakeGrant[];
}) {
const grantService = createFakeGrantService(options.existingGrants);
const immich = {
listAlbums: vi.fn().mockResolvedValue(options.albums),
};
const service = createAutoRuleService({
repository: createFakeRepository(options.rules),
grantService: {
getGrantedAlbumIds: (editorialId: string) =>
grantService.repository.listActiveAlbumIds(editorialId),
grantAlbum: async (input) => {
await grantService.repository.grant(input);
// Mirror the real service: unknown albums are not assignable.
},
},
immich,
});
return { service, grantService, immich };
}
beforeEach(() => {
vi.mocked(emailService.sendNewAlbumNotification).mockClear();
});
test("applyAllRules grants a new keyword-matching album to every eligible editorial", async () => {
const { service, grantService } = setup({
rules: [
{ editorialId: editorialA, loginEmail: "a@test.de", keyword: "FC Bayern" },
{ editorialId: editorialB, loginEmail: "b@test.de", keyword: "FC Bayern" },
],
albums: [
album(albumFcBayern, "FC Bayern - Dortmund 2026"),
album(albumUnrelated, "Urlaub 2026"),
],
});
await expect(service.applyAllRules()).resolves.toEqual({ granted: 2 });
expect(grantService.grants.map((grant) => `${grant.editorialId}:${grant.albumId}`)).toEqual([
`${editorialA}:${albumFcBayern}`,
`${editorialB}:${albumFcBayern}`,
]);
});
test("applyAllRules matches case-insensitively and skips already granted albums", async () => {
const { service, grantService } = setup({
rules: [{ editorialId: editorialA, loginEmail: "a@test.de", keyword: "fc bayern" }],
albums: [album(albumFcBayern, "FC BAYERN Heimspiel")],
existingGrants: [{ editorialId: editorialA, albumId: albumFcBayern }],
});
await expect(service.applyAllRules()).resolves.toEqual({ granted: 0 });
expect(grantService.grantInputs).toHaveLength(0);
expect(emailService.sendNewAlbumNotification).not.toHaveBeenCalled();
});
test("applyAllRules sends exactly one bundled notification per editorial", async () => {
const { service } = setup({
rules: [
{ editorialId: editorialA, loginEmail: "a@test.de", keyword: "Bayern" },
{ editorialId: editorialB, loginEmail: "b@test.de", keyword: "Pokal" },
],
albums: [
album(albumFcBayern, "FC Bayern - Stuttgart"),
album(albumDfbPokal, "DFB Pokal Finale"),
],
});
await expect(service.applyAllRules()).resolves.toEqual({ granted: 2 });
expect(emailService.sendNewAlbumNotification).toHaveBeenCalledTimes(2);
expect(emailService.sendNewAlbumNotification).toHaveBeenCalledWith("a@test.de", [
"FC Bayern - Stuttgart",
]);
expect(emailService.sendNewAlbumNotification).toHaveBeenCalledWith("b@test.de", [
"DFB Pokal Finale",
]);
});
test("applyAllRules attributes automated grants as system actor (adminUserId null)", async () => {
const { service, grantService } = setup({
rules: [{ editorialId: editorialA, loginEmail: "a@test.de", keyword: "Bayern" }],
albums: [album(albumFcBayern, "FC Bayern Auswärtsspiel")],
});
await service.applyAllRules();
expect(grantService.grantInputs[0]).toMatchObject({
editorialId: editorialA,
immichAlbumId: albumFcBayern,
adminUserId: null,
});
});
test("applyAllRules does nothing when no rules exist or Immich is unavailable", async () => {
const empty = setup({ rules: [], albums: [album(albumFcBayern, "FC Bayern")] });
await expect(empty.service.applyAllRules()).resolves.toEqual({ granted: 0 });
expect(empty.immich.listAlbums).not.toHaveBeenCalled();
const unavailable = setup({
rules: [{ editorialId: editorialA, loginEmail: "a@test.de", keyword: "Bayern" }],
albums: [],
});
unavailable.immich.listAlbums.mockRejectedValue(new Error("immich down"));
await expect(unavailable.service.applyAllRules()).resolves.toEqual({ granted: 0 });
expect(unavailable.grantService.grantInputs).toHaveLength(0);
});
test("concurrent applyAllRules runs coalesce into one sync pass", async () => {
let resolveAlbums: ((albums: ReturnType<typeof album>[]) => void) | undefined;
const { service, grantService, immich } = setup({
rules: [{ editorialId: editorialA, loginEmail: "a@test.de", keyword: "Bayern" }],
albums: [],
});
immich.listAlbums.mockReturnValue(
new Promise((resolve) => {
resolveAlbums = resolve;
}),
);
const first = service.applyAllRules();
const second = service.applyAllRules();
resolveAlbums!([album(albumFcBayern, "FC Bayern Test")]);
await expect(Promise.all([first, second])).resolves.toEqual([
{ granted: 1 },
{ granted: 1 },
]);
expect(immich.listAlbums).toHaveBeenCalledTimes(1);
expect(grantService.grantInputs).toHaveLength(1);
});
test("applyRules keeps admin attribution for the manual per-editorial run", async () => {
const grantInputs: unknown[] = [];
const immich = {
listAlbums: vi.fn().mockResolvedValue([album(albumFcBayern, "FC Bayern Spiel")]),
};
const service = createAutoRuleService({
repository: {
async listRules(editorialId) {
return editorialId === editorialA
? [
{
id: "rule-1",
editorialAccountId: editorialA,
keyword: "Bayern",
createdAt: new Date(),
createdByUserId: null,
},
]
: [];
},
async listEligibleRules() {
return [];
},
async createRule() {},
async deleteRule() {},
},
grantService: {
getGrantedAlbumIds: vi.fn().mockResolvedValue([]),
grantAlbum: async (input) => {
grantInputs.push(input);
},
},
immich,
});
await expect(service.applyRules(editorialA, adminUuid)).resolves.toEqual({ granted: 1 });
expect(grantInputs).toEqual([
{ editorialId: editorialA, immichAlbumId: albumFcBayern, adminUserId: adminUuid },
]);
});
+158 -31
View File
@@ -1,6 +1,6 @@
import "server-only";
import { eq, sql } from "drizzle-orm";
import { and, eq, isNull } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
@@ -8,7 +8,7 @@ import { albumAutoRules, editorialAccounts } from "@/db/schema";
import type * as schema from "@/db/schema";
import { albumGrantService } from "./grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichClient } from "@/modules/immich/types";
import type { ImmichAlbumSummary, ImmichClient } from "@/modules/immich/types";
import { emailService } from "@/modules/email/service";
export type AutoRule = {
@@ -19,8 +19,18 @@ export type AutoRule = {
createdByUserId: string | null;
};
/** Rule joined with its owner, restricted to auto-sync eligible editorials. */
export type EditorialAutoRule = {
editorialId: string;
loginEmail: string;
keyword: string;
};
export type SyncResult = { granted: number };
export type AutoRuleRepository = {
listRules(editorialId: string): Promise<AutoRule[]>;
listEligibleRules(): Promise<EditorialAutoRule[]>;
createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise<void>;
deleteRule(input: { ruleId: string; adminUserId: string }): Promise<void>;
};
@@ -34,6 +44,56 @@ export function createAutoRuleService({
grantService: Pick<typeof albumGrantService, "getGrantedAlbumIds" | "grantAlbum">;
immich: Pick<ImmichClient, "listAlbums">;
}) {
// Coalesces overlapping runs (scheduler tick + manual trigger) so one album
// never produces duplicate grants or notification emails.
let inFlightSync: Promise<SyncResult> | null = null;
async function loadAlbumsSafely(): Promise<ImmichAlbumSummary[] | null> {
try {
return await immich.listAlbums();
} catch {
return null;
}
}
async function syncEditorial(input: {
editorialId: string;
loginEmail: string | undefined;
keywords: string[];
albums: ImmichAlbumSummary[];
adminUserId: string | null;
}): Promise<number> {
const matching = matchAlbumsToKeywords(input.albums, input.keywords);
if (matching.length === 0) {
return 0;
}
const grantedAlbumIds = new Set(await grantService.getGrantedAlbumIds(input.editorialId));
const newlyGrantedAlbumNames: string[] = [];
for (const album of matching) {
if (grantedAlbumIds.has(album.id)) continue;
try {
await grantService.grantAlbum({
editorialId: input.editorialId,
immichAlbumId: album.id,
adminUserId: input.adminUserId,
});
grantedAlbumIds.add(album.id);
newlyGrantedAlbumNames.push(album.albumName);
} catch {
// Skip this album for now; the next sync run retries it.
}
}
if (newlyGrantedAlbumNames.length > 0 && input.loginEmail) {
await emailService
.sendNewAlbumNotification(input.loginEmail, newlyGrantedAlbumNames)
.catch(() => {});
}
return newlyGrantedAlbumNames.length;
}
return {
async listRules(editorialId: string): Promise<AutoRule[]> {
return repository.listRules(editorialId);
@@ -47,23 +107,21 @@ export function createAutoRuleService({
await repository.deleteRule(input);
},
async applyRules(editorialId: string, adminUserId: string): Promise<{ granted: number }> {
/**
* Applies every active keyword rule of ONE editorial. Used by the admin
* "Regeln jetzt anwenden" button; attribution goes to the acting admin.
*/
async applyRules(editorialId: string, adminUserId: string): Promise<SyncResult> {
const rules = await repository.listRules(editorialId);
if (rules.length === 0) {
return { granted: 0 };
}
let albums;
try {
albums = await immich.listAlbums();
} catch (error) {
const albums = await loadAlbumsSafely();
if (!albums) {
return { granted: 0 };
}
const grantedAlbumIds = new Set(await grantService.getGrantedAlbumIds(editorialId));
let newlyGranted = 0;
const newlyGrantedAlbumNames: string[] = [];
let editorialEmail: string | undefined;
try {
const [editorial] = await db
@@ -72,39 +130,89 @@ export function createAutoRuleService({
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
editorialEmail = editorial?.email;
} catch (e) {
// Ignore DB error
} catch {
// Ignore DB error; granting still works without the notification mail.
}
for (const album of albums) {
if (grantedAlbumIds.has(album.id)) {
continue;
const granted = await syncEditorial({
editorialId,
loginEmail: editorialEmail,
keywords: rules.map((rule) => rule.keyword),
albums,
adminUserId,
});
return { granted };
},
/**
* Applies ALL auto-assignment rules across ALL eligible editorials against
* the current Immich album list. Runs automatically on a schedule and via
* the cron endpoint, so a newly created Immich album whose name contains a
* rule keyword is granted without any manual step.
*/
async applyAllRules(): Promise<SyncResult> {
if (inFlightSync) {
return inFlightSync;
}
inFlightSync = (async () => {
const rules = await repository.listEligibleRules();
if (rules.length === 0) {
return { granted: 0 };
}
const albumNameLower = album.albumName.toLowerCase();
const matchesRule = rules.some((rule) => albumNameLower.includes(rule.keyword.toLowerCase()));
const albums = await loadAlbumsSafely();
if (!albums || albums.length === 0) {
return { granted: 0 };
}
if (matchesRule) {
try {
await grantService.grantAlbum({ editorialId, immichAlbumId: album.id, adminUserId });
newlyGranted++;
grantedAlbumIds.add(album.id);
newlyGrantedAlbumNames.push(album.albumName);
} catch (error) {
// Ignore individual album grant failures
// Group rules per editorial so each editorial gets exactly one pass
// and one bundled notification email.
const rulesByEditorial = new Map<string, { loginEmail: string; keywords: string[] }>();
for (const rule of rules) {
const entry = rulesByEditorial.get(rule.editorialId);
if (entry) {
entry.keywords.push(rule.keyword);
} else {
rulesByEditorial.set(rule.editorialId, {
loginEmail: rule.loginEmail,
keywords: [rule.keyword],
});
}
}
}
if (newlyGrantedAlbumNames.length > 0 && editorialEmail) {
await emailService.sendNewAlbumNotification(editorialEmail, newlyGrantedAlbumNames).catch(() => {});
}
let totalGranted = 0;
for (const [editorialId, entry] of rulesByEditorial) {
totalGranted += await syncEditorial({
editorialId,
loginEmail: entry.loginEmail,
keywords: entry.keywords,
albums,
adminUserId: null,
});
}
return { granted: totalGranted };
})();
return { granted: newlyGranted };
try {
return await inFlightSync;
} finally {
inFlightSync = null;
}
},
};
}
function matchAlbumsToKeywords(
albums: ImmichAlbumSummary[],
keywords: string[],
): ImmichAlbumSummary[] {
const normalizedKeywords = keywords.map((keyword) => keyword.toLowerCase());
return albums.filter((album) => {
const albumNameLower = album.albumName.toLowerCase();
return normalizedKeywords.some((keyword) => albumNameLower.includes(keyword));
});
}
export function createAutoRuleRepository(
database: NodePgDatabase<typeof schema>,
): AutoRuleRepository {
@@ -116,6 +224,25 @@ export function createAutoRuleRepository(
.where(eq(albumAutoRules.editorialAccountId, editorialId));
},
async listEligibleRules() {
return database
.select({
editorialId: editorialAccounts.id,
loginEmail: editorialAccounts.loginEmail,
keyword: albumAutoRules.keyword,
})
.from(albumAutoRules)
.innerJoin(
editorialAccounts,
eq(albumAutoRules.editorialAccountId, editorialAccounts.id),
)
// Automated sync only touches editorials that may actually use the
// portal right now; suspended/archived accounts are skipped.
.where(
and(eq(editorialAccounts.status, "active"), isNull(editorialAccounts.archivedAt)),
);
},
async createRule({ editorialId, keyword, adminUserId }) {
await database
.insert(albumAutoRules)
+1 -1
View File
@@ -13,7 +13,7 @@ import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null };
type Audit = {
eventType: string;
actorUserId: string;
actorUserId: string | null;
editorialId: string;
albumId: string;
previousValues: Record<string, unknown>;
+6 -4
View File
@@ -15,7 +15,8 @@ export type AssignableAlbum = ImmichAlbumSummary & { isGranted: boolean };
export type AlbumGrantInput = {
editorialId: string;
immichAlbumId: string;
adminUserId: string;
/** Admin user for audit attribution; null marks an automated (system) grant. */
adminUserId: string | null;
};
export type AlbumGrantRepository = {
@@ -157,7 +158,7 @@ export function createAlbumGrantRepository(
await transaction.insert(auditEvents).values({
eventType: "album_granted",
actorUserId: input.adminUserId,
actorType: "admin",
actorType: input.adminUserId ? "admin" : "system",
entityType: "album_grant",
entityId: input.immichAlbumId,
previousValues: {
@@ -199,7 +200,7 @@ export function createAlbumGrantRepository(
await transaction.insert(auditEvents).values({
eventType: "album_revoked",
actorUserId: input.adminUserId,
actorType: "admin",
actorType: input.adminUserId ? "admin" : "system",
entityType: "album_grant",
entityId: input.immichAlbumId,
previousValues: {
@@ -232,7 +233,8 @@ function normalizeInput(input: AlbumGrantInput): AlbumGrantInput {
return {
editorialId: normalizeIdentifier(input.editorialId),
immichAlbumId: normalizeIdentifier(input.immichAlbumId),
adminUserId: normalizeIdentifier(input.adminUserId),
adminUserId:
input.adminUserId === null ? null : normalizeIdentifier(input.adminUserId),
};
}