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

+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)