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:
1 parent
a3dc56778d
commit
dd60fd6ee6
14 files changed
+615
-38
No files matched your search
@@ -20,3 +20,9 @@ SMTP_FROM=portal@example.com
|
||||
LEGAL_IMPRINT_URL=https://leon-tonhaeuser.de/impressum
|
||||
LEGAL_PRIVACY_URL=https://leon-tonhaeuser.de/datenschutz
|
||||
LEGAL_TERMS_URL=https://leon-tonhaeuser.de/agb
|
||||
|
||||
# Album auto-rule sync: runs automatically every N seconds (default 120).
|
||||
# AUTO_RULE_SYNC_INTERVAL_SECONDS=120
|
||||
# Optional bearer token to trigger the sync externally via
|
||||
# POST /api/cron/album-sync (Authorization: Bearer <CRON_SECRET>).
|
||||
# CRON_SECRET=replace-with-a-long-random-secret
|
||||
@@ -37,6 +37,7 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
|
||||
- **Bulk Downloads:** Zip-Downloads (`archiver`) von mehreren Bildern nutzen Node.js Streams (`PassThrough`). Da Next.js die Response direkt an den Browser streamt, muss sichergestellt werden, dass der Stream nicht blockiert wird (`Readable.toWeb`). Siehe `src/app/api/lightbox/bulk-download/route.ts`.
|
||||
- **WICHTIG (archiver v8):** `require("archiver")` ist ab v8 **keine Funktion mehr**, sondern ein Objekt `{ Archiver, ZipArchive, TarArchive, JsonArchive }`. `archiver('zip', opts)` wirft `TypeError: archiver is not a function` → 500. Korrekt: `new archiver.ZipArchive(opts)` (gleiche `pipe`/`append`/`finalize`/`abort`-API). Dieser Fehler war lange durch den früheren 404 ("No valid assets found", leere Map) maskiert, bevor die Mitgliedschaftsprüfung repariert war.
|
||||
- **E-Mail-Benachrichtigungen bei Auto-Regeln:** Die Funktion für E-Mail-Benachrichtigungen bei Auto-Regeln (`src/modules/albums/auto-rules.ts`) verschickt *gebündelte* E-Mails. Wenn mehrere Alben gleichzeitig greifen, erhält die Redaktion genau **eine** E-Mail mit einer Auflistung aller Alben, anstatt für jedes Album einzeln benachrichtigt zu werden (`emailService.sendNewAlbumNotification` akzeptiert Arrays).
|
||||
- **Automatischer Auto-Regel-Sync (Stand 2026):** `autoRuleService.applyAllRules()` wendet die Keyword-Regeln **aller** aktiven, nicht archivierten Redaktionen auf die komplette Immich-Albenliste an (ein einziger `listAlbums`-Call pro Lauf; Grants mit `adminUserId: null` → Audit `actorType: "system"`). Trigger: (1) In-Prozess-Scheduler via `src/instrumentation.ts` + `src/modules/albums/auto-rule-scheduler.ts` (Intervall `AUTO_RULE_SYNC_INTERVAL_SECONDS`, Default 120s, erste Ausführung 15s nach Serverstart), (2) geschützter Endpoint `POST /api/cron/album-sync` (Bearer `CRON_SECRET`; ohne Secret antwortet er mit 404), (3) manueller Admin-Button „Regeln jetzt anwenden" (pro Redaktion, `applyRules`). Gleichzeitige Läufe werden über eine In-Memory-Mutex in `createAutoRuleService` koalesziert, damit es keine doppelten Grants/E-Mails gibt.
|
||||
|
||||
## 6. Admin-Bereich & Freigaben
|
||||
- **Redaktions-Freigabe:** Wenn eine Redaktion den Status `pending_approval` hat, wird sie im Admin-Detail-Dashboard über die `ApproveForm` freigegeben. In diesem Schritt *muss* der Admin zwingend einen individuellen Nettopreis für die Redaktion festlegen. Ohne das Setzen des Preises bleibt die Redaktion gesperrt.
|
||||
@@ -15,6 +15,8 @@ x-portal-env: &portal-env
|
||||
LEGAL_IMPRINT_URL: ${LEGAL_IMPRINT_URL:-https://leon-tonhaeuser.de/impressum}
|
||||
LEGAL_PRIVACY_URL: ${LEGAL_PRIVACY_URL:-https://leon-tonhaeuser.de/datenschutz}
|
||||
LEGAL_TERMS_URL: ${LEGAL_TERMS_URL:-https://leon-tonhaeuser.de/agb}
|
||||
CRON_SECRET: ${CRON_SECRET:-}
|
||||
AUTO_RULE_SYNC_INTERVAL_SECONDS: ${AUTO_RULE_SYNC_INTERVAL_SECONDS:-}
|
||||
|
||||
services:
|
||||
portal-db:
|
||||
|
||||
@@ -34,6 +34,8 @@ All production configuration is provided via environment variables (e.g. `.env`
|
||||
| `LEGAL_IMPRINT_URL` | Public Impressum link | `https://leon-tonhaeuser.de/impressum` |
|
||||
| `LEGAL_PRIVACY_URL` | Public Datenschutz link | `https://leon-tonhaeuser.de/datenschutz` |
|
||||
| `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://leon-tonhaeuser.de/agb` |
|
||||
| `AUTO_RULE_SYNC_INTERVAL_SECONDS` | Interval of the album auto-rule sync in seconds (min 30) | `120` (default) |
|
||||
| `CRON_SECRET` | Optional bearer token for `POST /api/cron/album-sync`; unset disables the endpoint | `openssl rand -hex 32` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import "server-only";
|
||||
|
||||
import type { autoRuleService } from "@/modules/albums/auto-rules";
|
||||
|
||||
const noStoreHeaders = { "cache-control": "private, no-store" } as const;
|
||||
|
||||
export type AlbumSyncHandlerDependencies = {
|
||||
applyAllRules: typeof autoRuleService.applyAllRules;
|
||||
cronSecret: string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Manual/external trigger for the album auto-rule sync (e.g. an uptime
|
||||
* monitor cron hitting this endpoint). Protected via CRON_SECRET bearer
|
||||
* token; disabled when no secret is configured.
|
||||
*/
|
||||
export function createAlbumSyncHandler({
|
||||
applyAllRules,
|
||||
cronSecret,
|
||||
}: AlbumSyncHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
if (!cronSecret) {
|
||||
return Response.json(
|
||||
{ code: "SYNC_DISABLED" },
|
||||
{ status: 404, headers: noStoreHeaders },
|
||||
);
|
||||
}
|
||||
|
||||
const authorization = request.headers.get("authorization");
|
||||
if (authorization !== `Bearer ${cronSecret}`) {
|
||||
return Response.json(
|
||||
{ code: "FORBIDDEN" },
|
||||
{ status: 403, headers: noStoreHeaders },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await applyAllRules();
|
||||
return Response.json(result, { headers: noStoreHeaders });
|
||||
} catch (error) {
|
||||
console.error("[album-sync] failed:", error);
|
||||
return Response.json(
|
||||
{ code: "SYNC_FAILED" },
|
||||
{ status: 503, headers: noStoreHeaders },
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createAlbumSyncHandler } from "./album-sync-handler";
|
||||
|
||||
const secret = "cron-secret-at-least-16-chars";
|
||||
|
||||
function post(handler: ReturnType<typeof createAlbumSyncHandler>, headers: Record<string, string>) {
|
||||
return handler(
|
||||
new Request("http://portal.test/api/cron/album-sync", {
|
||||
method: "POST",
|
||||
headers,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
test("runs the sync and reports the granted count with a valid bearer token", async () => {
|
||||
const applyAllRules = vi.fn().mockResolvedValue({ granted: 3 });
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret });
|
||||
|
||||
const response = await post(handler, { authorization: `Bearer ${secret}` });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({ granted: 3 });
|
||||
expect(applyAllRules).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("rejects a missing or wrong bearer token without running the sync", async () => {
|
||||
const applyAllRules = vi.fn();
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret });
|
||||
|
||||
const missing = await post(handler, {});
|
||||
const wrong = await post(handler, { authorization: "Bearer nope" });
|
||||
|
||||
expect(missing.status).toBe(403);
|
||||
expect(wrong.status).toBe(403);
|
||||
expect(applyAllRules).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("reports the endpoint as disabled when no cron secret is configured", async () => {
|
||||
const applyAllRules = vi.fn();
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: undefined });
|
||||
|
||||
const response = await post(handler, { authorization: `Bearer ${secret}` });
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(applyAllRules).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("maps sync failures to a retryable upstream error", async () => {
|
||||
const applyAllRules = vi.fn().mockRejectedValue(new Error("db down"));
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret });
|
||||
|
||||
const response = await post(handler, { authorization: `Bearer ${secret}` });
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
await expect(response.json()).resolves.toEqual({ code: "SYNC_FAILED" });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import "server-only";
|
||||
|
||||
import { autoRuleService } from "@/modules/albums/auto-rules";
|
||||
import { env } from "@/config/env";
|
||||
|
||||
import { createAlbumSyncHandler } from "./album-sync-handler";
|
||||
|
||||
export const POST = createAlbumSyncHandler({
|
||||
applyAllRules: (...args) => autoRuleService.applyAllRules(...args),
|
||||
cronSecret: env.CRON_SECRET,
|
||||
});
|
||||
@@ -20,8 +20,18 @@ const serverEnvSchema = z.object({
|
||||
.url()
|
||||
.default("https://leon-tonhaeuser.de/datenschutz"),
|
||||
LEGAL_TERMS_URL: z.url().default("https://leon-tonhaeuser.de/agb"),
|
||||
/** Bearer token for the /api/cron/album-sync endpoint; unset disables it. */
|
||||
CRON_SECRET: emptyToUndefined(z.string().min(16)).optional(),
|
||||
/** How often the album auto-rule sync runs, in seconds (min 30). */
|
||||
AUTO_RULE_SYNC_INTERVAL_SECONDS: emptyToUndefined(z.coerce.number().int().min(30)).optional(),
|
||||
});
|
||||
|
||||
// Docker Compose passes undeclared vars as empty strings; treat those as
|
||||
// unset so optional settings stay optional.
|
||||
function emptyToUndefined<T extends z.ZodType>(schema: T) {
|
||||
return z.preprocess((value) => (value === "" ? undefined : value), schema);
|
||||
}
|
||||
|
||||
export type ServerEnv = z.infer<typeof serverEnvSchema>;
|
||||
|
||||
export function parseServerEnv(input: NodeJS.ProcessEnv): ServerEnv;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export async function register(): Promise<void> {
|
||||
if (process.env.NEXT_RUNTIME !== "nodejs") {
|
||||
return;
|
||||
}
|
||||
const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler");
|
||||
startAutoRuleScheduler();
|
||||
}
|
||||
@@ -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?.();
|
||||
}
|
||||
@@ -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 },
|
||||
]);
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
// 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],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
})();
|
||||
|
||||
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
|
||||
return await inFlightSync;
|
||||
} finally {
|
||||
inFlightSync = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newlyGrantedAlbumNames.length > 0 && editorialEmail) {
|
||||
await emailService.sendNewAlbumNotification(editorialEmail, newlyGrantedAlbumNames).catch(() => {});
|
||||
}
|
||||
|
||||
return { granted: newlyGranted };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user