Files
hobbs-iac/tv app/Hobbs-Family-Organizer-Self-Hosted-v1.0.0/app/_lib/store.ts
T
jeremy c2e5c1d9dc feat(hobbs-organizer): v1.2.0 photo frame (/photo) with Google Photos shared albums
- /photo full-screen slideshow (crossfade, blurred backdrop or fill, shuffle, date)
- admin Photos tab: add shared-album links (check, sync now, status/stale warnings),
  slideshow options, browser-resized uploads
- 6-hourly album sync scraping the share page (Library API no longer exposes
  user albums), caches 1920px + 64px copies in /data/photos
- /api/health/photos -> 503 when an album has not synced for 48h
- history/restore covers photo settings; min admin password length 6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E9NnVEico3WvFxLyjy1iW3
2026-11-04 19:18:02 -06:00

244 lines
8.8 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
export const CALENDAR_TONES = ["cyan", "amber", "violet", "emerald", "rose"] as const;
export type CalendarTone = (typeof CALENDAR_TONES)[number];
export const MAX_CALENDARS = 10;
const HISTORY_LIMIT = 20;
export type CalendarSetting = {
id: string;
/** Display name override; empty means "use the feed's own name". */
name: string;
url: string;
tone: CalendarTone;
enabled: boolean;
};
export type PhotoAlbum = {
id: string;
/** Display name override; empty means "use the album's own title". */
name: string;
shareUrl: string;
enabled: boolean;
};
export type PhotoDisplay = {
intervalSeconds: number;
shuffle: boolean;
showDate: boolean;
fit: "contain-blur" | "cover";
includeUploads: boolean;
};
export type PhotoSettings = PhotoDisplay & { albums: PhotoAlbum[] };
export const MAX_ALBUMS = 10;
export const DEFAULT_PHOTO_SETTINGS: PhotoSettings = {
intervalSeconds: 20,
shuffle: true,
showDate: true,
fit: "contain-blur",
includeUploads: true,
albums: [],
};
export type Settings = {
schema: 1;
updatedAt: string;
calendars: CalendarSetting[];
photos: PhotoSettings;
};
/** Accepts photos.app.goo.gl short links and photos.google.com/share links. */
export function validAlbumUrl(value: unknown) {
let url: URL;
try {
url = new URL(String(value).trim());
} catch {
return null;
}
if (url.protocol !== "https:") return null;
if (url.hostname === "photos.app.goo.gl" && /^\/[A-Za-z0-9_-]{6,64}$/.test(url.pathname)) return `https://photos.app.goo.gl${url.pathname}`;
if (url.hostname === "photos.google.com" && /^\/share\/[A-Za-z0-9_-]{10,200}$/.test(url.pathname)) return url.toString();
return null;
}
export function maskAlbumUrl(url: string) {
const parsed = new URL(url);
const id = parsed.pathname.split("/").pop() || "";
return `${parsed.hostname}/…${id.slice(-4)}`;
}
function normalizePhotos(raw: unknown): PhotoSettings {
const value = (raw ?? {}) as Partial<PhotoSettings>;
const interval = Number(value.intervalSeconds);
return {
intervalSeconds: Number.isFinite(interval) ? Math.min(3600, Math.max(5, Math.round(interval))) : DEFAULT_PHOTO_SETTINGS.intervalSeconds,
shuffle: value.shuffle !== false,
showDate: value.showDate !== false,
fit: value.fit === "cover" ? "cover" : "contain-blur",
includeUploads: value.includeUploads !== false,
albums: (Array.isArray(value.albums) ? value.albums : [])
.map((entry) => {
const shareUrl = validAlbumUrl(entry?.shareUrl);
if (!shareUrl) return null;
return {
id: typeof entry.id === "string" && /^[A-Za-z0-9-]{8,64}$/.test(entry.id) ? entry.id : randomUUID(),
name: typeof entry.name === "string" ? entry.name.trim().slice(0, 60) : "",
shareUrl,
enabled: entry.enabled !== false,
} satisfies PhotoAlbum;
})
.filter((entry): entry is PhotoAlbum => entry !== null)
.slice(0, MAX_ALBUMS),
};
}
export type AuthState = {
passwordHash: string;
sessionSecret: string;
};
const dataDir = () => process.env.ORGANIZER_DATA_DIR || "/data";
const settingsPath = () => path.join(dataDir(), "settings.json");
const authPath = () => path.join(dataDir(), "auth.json");
const historyDir = () => path.join(dataDir(), "history");
export function validCalendarUrl(value: unknown) {
let url: URL;
try {
url = new URL(String(value).trim());
} catch {
return null;
}
if (url.protocol !== "https:" || url.hostname !== "calendar.google.com" || !url.pathname.endsWith("/basic.ics")) return null;
if (!/^\/calendar\/ical\/[A-Za-z0-9._~%+@-]+\/(private-[A-Za-z0-9._~%+@-]+|public)\/basic\.ics$/.test(url.pathname)) return null;
return url.toString();
}
/** "…/ical/fam…%40group…/private-••••3854/basic.ics" — enough to tell feeds apart, not enough to use one. */
export function maskCalendarUrl(url: string) {
const match = /\/calendar\/ical\/([^/]+)\/(private-[^/]+|public)\/basic\.ics$/.exec(new URL(url).pathname);
if (!match) return "calendar.google.com/…";
const owner = decodeURIComponent(match[1]);
const shortOwner = owner.length > 18 ? `${owner.slice(0, 8)}…${owner.slice(owner.indexOf("@"))}` : owner;
const key = match[2] === "public" ? "public" : `private-••••${match[2].slice(-4)}`;
return `${shortOwner} · ${key}`;
}
function normalizeSettings(raw: unknown): Settings {
const value = (raw ?? {}) as Partial<Settings>;
const calendars = Array.isArray(value.calendars) ? value.calendars : [];
return {
schema: 1,
updatedAt: typeof value.updatedAt === "string" ? value.updatedAt : new Date(0).toISOString(),
calendars: calendars
.map((entry) => {
const url = validCalendarUrl(entry?.url);
if (!url) return null;
return {
id: typeof entry.id === "string" && entry.id ? entry.id : randomUUID(),
name: typeof entry.name === "string" ? entry.name.trim().slice(0, 50) : "",
url,
tone: CALENDAR_TONES.includes(entry.tone as CalendarTone) ? (entry.tone as CalendarTone) : "cyan",
enabled: entry.enabled !== false,
} satisfies CalendarSetting;
})
.filter((entry): entry is CalendarSetting => entry !== null)
.slice(0, MAX_CALENDARS),
photos: normalizePhotos(value.photos),
};
}
async function readJson(file: string) {
return JSON.parse(await readFile(file, "utf8")) as unknown;
}
async function writeJsonAtomic(file: string, value: unknown) {
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
await rename(temporary, file);
}
// All writes go through one queue so concurrent saves cannot interleave.
let writeQueue: Promise<unknown> = Promise.resolve();
function serialized<T>(task: () => Promise<T>) {
const run = writeQueue.then(task, task);
writeQueue = run.catch(() => undefined);
return run;
}
export async function readSettings(): Promise<Settings> {
try {
return normalizeSettings(await readJson(settingsPath()));
} catch {
return normalizeSettings({});
}
}
export type HistoryEntry = { id: string; savedAt: string; calendarCount: number; albumCount: number; note: string };
async function pruneHistory() {
const files = (await readdir(historyDir())).filter((name) => name.endsWith(".json")).sort();
for (const name of files.slice(0, Math.max(0, files.length - HISTORY_LIMIT))) {
await unlink(path.join(historyDir(), name)).catch(() => undefined);
}
}
/** Saves new settings (only the parts given), first snapshotting the current ones into history. */
export function saveSettings(patch: Partial<Pick<Settings, "calendars" | "photos">>, note: string) {
return serialized(async () => {
const current = await readSettings();
const calendars = patch.calendars ?? current.calendars;
const photos = patch.photos ?? current.photos;
const stamp = new Date().toISOString();
const snapshotId = `${stamp.replace(/[:.]/g, "-")}`;
await writeJsonAtomic(path.join(historyDir(), `${snapshotId}.json`), { ...current, note });
await pruneHistory();
const next = normalizeSettings({ schema: 1, updatedAt: stamp, calendars, photos });
await writeJsonAtomic(settingsPath(), next);
return next;
});
}
export async function listHistory(): Promise<HistoryEntry[]> {
const files = (await readdir(historyDir()).catch(() => [] as string[])).filter((name) => name.endsWith(".json")).sort().reverse();
const entries: HistoryEntry[] = [];
for (const name of files) {
try {
const raw = (await readJson(path.join(historyDir(), name))) as Settings & { note?: string };
entries.push({
id: name.slice(0, -5),
savedAt: raw.updatedAt,
calendarCount: Array.isArray(raw.calendars) ? raw.calendars.length : 0,
albumCount: Array.isArray(raw.photos?.albums) ? raw.photos.albums.length : 0,
note: typeof raw.note === "string" ? raw.note : "",
});
} catch {
// Skip an unreadable snapshot.
}
}
return entries;
}
export async function readHistorySnapshot(id: string) {
if (!/^[0-9TZ-]+$/.test(id)) return null;
try {
return normalizeSettings(await readJson(path.join(historyDir(), `${id}.json`)));
} catch {
return null;
}
}
export async function readAuth(): Promise<AuthState> {
const raw = (await readJson(authPath())) as Partial<AuthState>;
if (typeof raw.sessionSecret !== "string" || raw.sessionSecret.length < 32) throw new Error("auth.json is missing a session secret");
return { passwordHash: typeof raw.passwordHash === "string" ? raw.passwordHash : "", sessionSecret: raw.sessionSecret };
}
export function writeAuth(next: AuthState) {
return serialized(() => writeJsonAtomic(authPath(), next));
}