import "server-only"; import { eq } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { settings, workerState } from "@/lib/db/schema"; import { isLabelColor } from "@/lib/colors"; import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles"; import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit"; import { nextScanAt, parseScanSchedule, SCAN_SCHEDULE_KEY, type ScanSchedule, ScanScheduleError, validateScanSchedule } from "@/lib/folder-scan"; import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend"; const FILE_ROLES_KEY = "labels.fileRoles"; export const FILE_ROLE_LABEL_MAX = 24; type StoredRoles = Partial>; async function read(key: string): Promise { try { const row = await db().query.settings.findFirst({ where: eq(settings.key, key) }); return (row?.value as T) ?? null; } catch { return null; // table missing before the first migration } } async function write(key: string, value: unknown) { await db() .insert(settings) .values({ key, value }) .onConflictDoUpdate({ target: settings.key, set: { value, updatedAt: new Date() } }); } /** Label text and color per file role: defaults merged with what was saved in Settings. */ export async function getFileRoleStyles(): Promise { const stored = (await read(FILE_ROLES_KEY)) ?? {}; const out = {} as FileRoleStyles; for (const role of FILE_ROLE_ORDER) { const s = stored[role] ?? {}; out[role] = { label: typeof s.label === "string" && s.label.trim() ? s.label.trim() : FILE_ROLES[role].label, color: isLabelColor(s.color) ? s.color : FILE_ROLES[role].color, }; } return out; } export class SettingsError extends Error { status = 400; code = "invalid"; } /** Save label/color overrides. Values equal to the default are not stored. */ export async function saveFileRoleStyles(input: Record): Promise { const stored: StoredRoles = {}; for (const [role, v] of Object.entries(input)) { if (!(role in FILE_ROLES)) throw new SettingsError(`Unknown file label "${role}".`); const def = FILE_ROLES[role as FileRole]; const entry: { label?: string; color?: string } = {}; if (v.label !== undefined) { if (typeof v.label !== "string" || !v.label.trim() || v.label.trim().length > FILE_ROLE_LABEL_MAX) { throw new SettingsError(`Label for "${role}" must be 1–${FILE_ROLE_LABEL_MAX} characters.`); } if (v.label.trim() !== def.label) entry.label = v.label.trim(); } if (v.color !== undefined) { if (!isLabelColor(v.color)) throw new SettingsError(`Unknown color "${String(v.color)}".`); if (v.color !== def.color) entry.color = v.color; } if (entry.label || entry.color) stored[role as FileRole] = entry; } await write(FILE_ROLES_KEY, stored); return getFileRoleStyles(); } const RECOMMENDED_KEY = "downloads.recommendedRoles"; /** File kinds picked automatically along with model weights (Settings → Downloads). */ export async function getRecommendedRoles(): Promise { const stored = await read(RECOMMENDED_KEY); if (!Array.isArray(stored)) return DEFAULT_RECOMMENDED_ROLES; return RECOMMENDABLE_ROLES.filter((r) => stored.includes(r)); } export async function saveRecommendedRoles(roles: string[]): Promise { const unknown = roles.find((r) => !RECOMMENDABLE_ROLES.includes(r as FileRole)); if (unknown) throw new SettingsError(`"${unknown}" can't be recommended.`); await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r))); return getRecommendedRoles(); } /** Download speed limit in bytes per second (Settings → Downloads), or null for no limit. */ export async function getDownloadSpeedLimit(): Promise { return parseSpeedLimit(await read(SPEED_LIMIT_KEY)); } export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Promise { if (bytesPerSecond != null && (!Number.isFinite(bytesPerSecond) || bytesPerSecond < MIN_SPEED_LIMIT)) { throw new SettingsError("The speed limit must be at least 0.1 MB/s, or empty for no limit."); } if (bytesPerSecond == null) await db().delete(settings).where(eq(settings.key, SPEED_LIMIT_KEY)); else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond)); return getDownloadSpeedLimit(); } /** When the worker scans the models folder for importable folders (Settings → Downloads). */ export async function getScanSchedule(): Promise { return parseScanSchedule(await read(SCAN_SCHEDULE_KEY)); } export async function saveScanSchedule(input: unknown): Promise { try { await write(SCAN_SCHEDULE_KEY, validateScanSchedule(input)); } catch (err) { if (err instanceof ScanScheduleError) throw new SettingsError(err.message); throw err; } return getScanSchedule(); } export type ScanStatus = { schedule: ScanSchedule; lastScanAt: number | null; lastScanFound: number | null; /** A "Scan now" the worker hasn't started yet. */ requested: boolean; nextScanAt: number | null; }; export async function getScanStatus(): Promise { const [schedule, ws] = await Promise.all([ getScanSchedule(), db().query.workerState.findFirst({ columns: { lastScanAt: true, lastScanFound: true, scanRequestedAt: true }, where: eq(workerState.id, "worker") }), ]); const last = ws?.lastScanAt ?? null; const next = schedule.every === "manual" ? null : last ? nextScanAt(schedule, last) : new Date(); return { schedule, lastScanAt: last?.getTime() ?? null, lastScanFound: ws?.lastScanFound ?? null, requested: !!ws?.scanRequestedAt && (!last || ws.scanRequestedAt > last), nextScanAt: next?.getTime() ?? null, }; }