Release / release (push) Successful in 3m49s
Settings -> Downloads lets you scan the models folder every 2 minutes (default, as before), hourly, daily, weekly, monthly at a chosen local time, or only manually, with a Scan now button and the last/next scan. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
122 lines
5.3 KiB
TypeScript
122 lines
5.3 KiB
TypeScript
// When the worker scans the models folder for importable folders (Settings → Downloads). Pure;
|
||
// shared by the settings API, the settings page and the worker. Times are wall-clock times in the
|
||
// time zone the schedule was saved in (the browser's), so "03:00" means 03:00 for the user.
|
||
|
||
export const SCAN_SCHEDULE_KEY = "scan.schedule";
|
||
|
||
export const SCAN_FREQUENCIES = ["2min", "hourly", "daily", "weekly", "monthly", "manual"] as const;
|
||
export type ScanFrequency = (typeof SCAN_FREQUENCIES)[number];
|
||
|
||
export type ScanSchedule = {
|
||
every: ScanFrequency;
|
||
/** "HH:MM"; hourly uses only the minutes. */
|
||
time: string;
|
||
/** weekly: 0 = Sunday … 6 = Saturday. */
|
||
weekday: number;
|
||
/** monthly: 1–28 (every month has those). */
|
||
monthDay: number;
|
||
/** IANA time zone, e.g. "Europe/Berlin". */
|
||
tz: string;
|
||
};
|
||
|
||
/** Before this setting existed the worker scanned every 2 minutes; that stays the default. */
|
||
export const DEFAULT_SCAN_SCHEDULE: ScanSchedule = { every: "2min", time: "03:00", weekday: 1, monthDay: 1, tz: "UTC" };
|
||
|
||
export const FREQUENCY_LABEL: Record<ScanFrequency, string> = {
|
||
"2min": "Every 2 minutes",
|
||
hourly: "Hourly",
|
||
daily: "Daily",
|
||
weekly: "Weekly",
|
||
monthly: "Monthly",
|
||
manual: "Only when I click Scan now",
|
||
};
|
||
|
||
export class ScanScheduleError extends Error {}
|
||
|
||
export function validTimeZone(tz: string): boolean {
|
||
try {
|
||
new Intl.DateTimeFormat("en-US", { timeZone: tz });
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/** Validate input from the settings form; throws ScanScheduleError. */
|
||
export function validateScanSchedule(input: unknown): ScanSchedule {
|
||
const o = (input ?? {}) as Record<string, unknown>;
|
||
const every = o.every as ScanFrequency;
|
||
if (!SCAN_FREQUENCIES.includes(every)) throw new ScanScheduleError(`Frequency must be one of: ${SCAN_FREQUENCIES.join(", ")}.`);
|
||
const time = typeof o.time === "string" ? o.time.trim() : "";
|
||
const m = time.match(/^([01]\d|2[0-3]):([0-5]\d)$/);
|
||
if (!m) throw new ScanScheduleError('Time must be "HH:MM" (24 hours).');
|
||
const weekday = Number(o.weekday ?? 1);
|
||
if (!Number.isInteger(weekday) || weekday < 0 || weekday > 6) throw new ScanScheduleError("Weekday must be 0 (Sunday) to 6 (Saturday).");
|
||
const monthDay = Number(o.monthDay ?? 1);
|
||
if (!Number.isInteger(monthDay) || monthDay < 1 || monthDay > 28) throw new ScanScheduleError("Day of the month must be 1–28.");
|
||
const tz = typeof o.tz === "string" && o.tz ? o.tz : "UTC";
|
||
if (!validTimeZone(tz)) throw new ScanScheduleError(`Unknown time zone "${tz}".`);
|
||
return { every, time, weekday, monthDay, tz };
|
||
}
|
||
|
||
/** The stored schedule; anything invalid falls back to the default rather than stopping scans. */
|
||
export function parseScanSchedule(stored: unknown): ScanSchedule {
|
||
try {
|
||
return validateScanSchedule(stored);
|
||
} catch {
|
||
return DEFAULT_SCAN_SCHEDULE;
|
||
}
|
||
}
|
||
|
||
type Parts = { y: number; mo: number; d: number; h: number; mi: number; wd: number };
|
||
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||
|
||
/** Wall-clock date and time of `t` in `tz`. */
|
||
function partsIn(t: number, tz: string): Parts {
|
||
const f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", weekday: "short" });
|
||
const p = Object.fromEntries(f.formatToParts(new Date(t)).map((x) => [x.type, x.value]));
|
||
return { y: Number(p.year), mo: Number(p.month), d: Number(p.day), h: Number(p.hour), mi: Number(p.minute), wd: WEEKDAYS.indexOf(p.weekday) };
|
||
}
|
||
|
||
/** The instant a wall-clock time in `tz` happens (in a DST gap: shortly after). */
|
||
function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, tz: string): number {
|
||
const wall = Date.UTC(y, mo - 1, d, h, mi);
|
||
const offsetAt = (t: number) => {
|
||
const p = partsIn(t, tz);
|
||
return Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi) - Math.floor(t / 60_000) * 60_000;
|
||
};
|
||
let t = wall - offsetAt(wall);
|
||
t = wall - offsetAt(t);
|
||
return t;
|
||
}
|
||
|
||
/** The first scheduled scan strictly after `after`; null for manual-only. */
|
||
export function nextScanAt(s: ScanSchedule, after: Date): Date | null {
|
||
const from = after.getTime();
|
||
if (s.every === "manual") return null;
|
||
if (s.every === "2min") return new Date(from + 2 * 60_000);
|
||
const [hh, mm] = s.time.split(":").map(Number);
|
||
const start = partsIn(from, s.tz);
|
||
// Walk local calendar days from `after`'s day on; 62 covers a month plus DST and edge cases.
|
||
for (let i = 0; i <= 62; i++) {
|
||
const day = new Date(Date.UTC(start.y, start.mo - 1, start.d + i));
|
||
const [y, mo, d, wd] = [day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), day.getUTCDay()];
|
||
if (s.every === "weekly" && wd !== s.weekday) continue;
|
||
if (s.every === "monthly" && d !== s.monthDay) continue;
|
||
const hours = s.every === "hourly" ? Array.from({ length: 24 }, (_, h) => h) : [hh];
|
||
for (const h of hours) {
|
||
const t = zonedToUtc(y, mo, d, h, mm, s.tz);
|
||
if (t > from) return new Date(t);
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** Is a scheduled scan due? Never scanned: yes (the import list would stay empty otherwise). */
|
||
export function scanDue(s: ScanSchedule, lastScanAt: Date | null, now: Date): boolean {
|
||
if (s.every === "manual") return false;
|
||
if (!lastScanAt) return true;
|
||
const next = nextScanAt(s, lastScanAt);
|
||
return !!next && next.getTime() <= now.getTime();
|
||
}
|