diff --git a/.env.example b/.env.example index bd16fbb..eee0066 100644 --- a/.env.example +++ b/.env.example @@ -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=replace-with-a-long-random-secret diff --git a/AI_MEMORY.md b/AI_MEMORY.md index 1ece790..511860b 100644 --- a/AI_MEMORY.md +++ b/AI_MEMORY.md @@ -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. diff --git a/compose.yaml b/compose.yaml index 3909d04..2a0799b 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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: diff --git a/docs/operations.md b/docs/operations.md index 8248eda..dabc51f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -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` | --- diff --git a/src/app/api/cron/album-sync/album-sync-handler.ts b/src/app/api/cron/album-sync/album-sync-handler.ts new file mode 100644 index 0000000..230d55a --- /dev/null +++ b/src/app/api/cron/album-sync/album-sync-handler.ts @@ -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 { + 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 }, + ); + } + }; +} diff --git a/src/app/api/cron/album-sync/route.test.ts b/src/app/api/cron/album-sync/route.test.ts new file mode 100644 index 0000000..6c72dba --- /dev/null +++ b/src/app/api/cron/album-sync/route.test.ts @@ -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, headers: Record) { + 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(); +}); diff --git a/src/app/api/cron/album-sync/route.ts b/src/app/api/cron/album-sync/route.ts new file mode 100644 index 0000000..b62347d --- /dev/null +++ b/src/app/api/cron/album-sync/route.ts @@ -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, +}); diff --git a/src/config/env.ts b/src/config/env.ts index 45d2676..3cc25e8 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -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(schema: T) { + return z.preprocess((value) => (value === "" ? undefined : value), schema); +} + export type ServerEnv = z.infer; export function parseServerEnv(input: NodeJS.ProcessEnv): ServerEnv; diff --git a/src/instrumentation.ts b/src/instrumentation.ts new file mode 100644 index 0000000..726e813 --- /dev/null +++ b/src/instrumentation.ts @@ -0,0 +1,7 @@ +export async function register(): Promise { + if (process.env.NEXT_RUNTIME !== "nodejs") { + return; + } + const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler"); + startAutoRuleScheduler(); +} diff --git a/src/modules/albums/auto-rule-scheduler.ts b/src/modules/albums/auto-rule-scheduler.ts new file mode 100644 index 0000000..814b6cd --- /dev/null +++ b/src/modules/albums/auto-rule-scheduler.ts @@ -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?.(); +} diff --git a/src/modules/albums/auto-rules.test.ts b/src/modules/albums/auto-rules.test.ts new file mode 100644 index 0000000..277618e --- /dev/null +++ b/src/modules/albums/auto-rules.test.ts @@ -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>; + 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[]) => 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 }, + ]); +}); diff --git a/src/modules/albums/auto-rules.ts b/src/modules/albums/auto-rules.ts index a125c1d..689722d 100644 --- a/src/modules/albums/auto-rules.ts +++ b/src/modules/albums/auto-rules.ts @@ -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; + listEligibleRules(): Promise; createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise; deleteRule(input: { ruleId: string; adminUserId: string }): Promise; }; @@ -34,6 +44,56 @@ export function createAutoRuleService({ grantService: Pick; immich: Pick; }) { + // Coalesces overlapping runs (scheduler tick + manual trigger) so one album + // never produces duplicate grants or notification emails. + let inFlightSync: Promise | null = null; + + async function loadAlbumsSafely(): Promise { + 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 { + 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 { 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 { 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 { + 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(); + 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, ): 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) diff --git a/src/modules/albums/grants.test.ts b/src/modules/albums/grants.test.ts index fc86878..3fa5e8f 100644 --- a/src/modules/albums/grants.test.ts +++ b/src/modules/albums/grants.test.ts @@ -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; diff --git a/src/modules/albums/grants.ts b/src/modules/albums/grants.ts index 15c46b5..637cf1f 100644 --- a/src/modules/albums/grants.ts +++ b/src/modules/albums/grants.ts @@ -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), }; }