269 lines
8.2 KiB
TypeScript
269 lines
8.2 KiB
TypeScript
import "server-only";
|
|
|
|
import { and, eq, isNull } from "drizzle-orm";
|
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
|
|
import { db } from "@/db/client";
|
|
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 { ImmichAlbumSummary, ImmichClient } from "@/modules/immich/types";
|
|
import { emailService } from "@/modules/email/service";
|
|
|
|
export type AutoRule = {
|
|
id: string;
|
|
editorialAccountId: string;
|
|
keyword: string;
|
|
createdAt: Date;
|
|
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>;
|
|
};
|
|
|
|
export function createAutoRuleService({
|
|
repository,
|
|
grantService,
|
|
immich,
|
|
}: {
|
|
repository: AutoRuleRepository;
|
|
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,
|
|
source: "auto_rule",
|
|
});
|
|
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);
|
|
},
|
|
|
|
async createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise<void> {
|
|
await repository.createRule(input);
|
|
},
|
|
|
|
async deleteRule(input: { ruleId: string; adminUserId: string }): Promise<void> {
|
|
await repository.deleteRule(input);
|
|
},
|
|
|
|
/**
|
|
* 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 };
|
|
}
|
|
|
|
const albums = await loadAlbumsSafely();
|
|
if (!albums) {
|
|
return { granted: 0 };
|
|
}
|
|
|
|
let editorialEmail: string | undefined;
|
|
try {
|
|
const [editorial] = await db
|
|
.select({ email: editorialAccounts.loginEmail })
|
|
.from(editorialAccounts)
|
|
.where(eq(editorialAccounts.id, editorialId))
|
|
.limit(1);
|
|
editorialEmail = editorial?.email;
|
|
} catch {
|
|
// Ignore DB error; granting still works without the notification mail.
|
|
}
|
|
|
|
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 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 };
|
|
})();
|
|
|
|
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 {
|
|
return {
|
|
async listRules(editorialId: string) {
|
|
return database
|
|
.select()
|
|
.from(albumAutoRules)
|
|
.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)
|
|
.values({
|
|
editorialAccountId: editorialId,
|
|
keyword,
|
|
createdByUserId: adminUserId,
|
|
})
|
|
.onConflictDoNothing();
|
|
},
|
|
|
|
async deleteRule({ ruleId, adminUserId }) {
|
|
await database.delete(albumAutoRules).where(eq(albumAutoRules.id, ruleId));
|
|
},
|
|
};
|
|
}
|
|
|
|
export const autoRuleService = createAutoRuleService({
|
|
repository: createAutoRuleRepository(db),
|
|
grantService: albumGrantService,
|
|
immich: immichClient,
|
|
});
|