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: [], }; /** * Per-TV morning routine, run by the Shield photo app (com.dayline.photos) on each TV: * wake the TV, set the volume, start a YouTube Music playlist, then bring up the calendar. * `id` is the TV's Android ID, reported by the app when it checks in. */ export type TvSetting = { id: string; name: string; wake: { enabled: boolean; time: string; days: number[] }; music: { enabled: boolean; playlistId: string }; volume: { enabled: boolean; level: number }; }; export const MAX_TVS = 10; export const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6]; export function validTvId(value: unknown) { return typeof value === "string" && /^[a-f0-9]{8,32}$/.test(value) ? value : null; } /** Accepts a YouTube / YouTube Music playlist link or a bare playlist ID; returns the ID. */ export function validPlaylistId(value: unknown) { const text = String(value ?? "").trim(); if (/^[A-Za-z0-9_-]{10,64}$/.test(text)) return text; let url: URL; try { url = new URL(text); } catch { return null; } if (url.protocol !== "https:" || !["music.youtube.com", "www.youtube.com", "youtube.com", "m.youtube.com"].includes(url.hostname)) return null; const list = url.searchParams.get("list") ?? ""; return /^[A-Za-z0-9_-]{10,64}$/.test(list) ? list : null; } export const playlistUrl = (playlistId: string) => `https://music.youtube.com/playlist?list=${playlistId}`; function validTime(value: unknown) { return typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value) ? value : null; } function normalizeTvs(raw: unknown): TvSetting[] { const seen = new Set(); return (Array.isArray(raw) ? raw : []) .map((entry) => { const id = validTvId(entry?.id); if (!id || seen.has(id)) return null; seen.add(id); const days = Array.isArray(entry.wake?.days) ? [...new Set((entry.wake.days as unknown[]).map(Number).filter((day) => Number.isInteger(day) && day >= 0 && day <= 6))].sort() : ALL_DAYS; const level = Number(entry.volume?.level); return { id, name: typeof entry.name === "string" ? entry.name.trim().slice(0, 40) : "", wake: { enabled: entry.wake?.enabled === true, time: validTime(entry.wake?.time) ?? "06:30", days }, music: { enabled: entry.music?.enabled === true, playlistId: validPlaylistId(entry.music?.playlistId) ?? "" }, volume: { enabled: entry.volume?.enabled === true, level: Number.isFinite(level) ? Math.min(100, Math.max(0, Math.round(level))) : 40 }, } satisfies TvSetting; }) .filter((entry): entry is TvSetting => entry !== null) .slice(0, MAX_TVS); } export type Settings = { schema: 1; updatedAt: string; calendars: CalendarSetting[]; photos: PhotoSettings; tvs: TvSetting[]; }; /** 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; 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; 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), tvs: normalizeTvs(value.tvs), }; } 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 = Promise.resolve(); function serialized(task: () => Promise) { const run = writeQueue.then(task, task); writeQueue = run.catch(() => undefined); return run; } export async function readSettings(): Promise { 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>, note: string) { return serialized(async () => { const current = await readSettings(); const calendars = patch.calendars ?? current.calendars; const photos = patch.photos ?? current.photos; const tvs = patch.tvs ?? current.tvs; 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, tvs }); await writeJsonAtomic(settingsPath(), next); return next; }); } export async function listHistory(): Promise { 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 { const raw = (await readJson(authPath())) as Partial; 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)); }