feat(hobbs-organizer): v1.4.0 per-TV morning routine (admin TVs tab) + photo app 1.2.1

- Admin TVs tab: wake time/days, YouTube Music playlist, Shield volume per TV,
  pushed via 5-min TV check-ins (/api/tv/config, /api/tv/report, LAN-only)
- com.dayline.photos 1.2.1: MorningActivity (screen on, volume, playlist),
  calendar alarm at wake time, Doze-safe chained check-ins
- Both TVs configured for 06:30 daily with the family playlist

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E9NnVEico3WvFxLyjy1iW3
This commit is contained in:
2026-11-04 22:48:50 -06:00
parent 2d16ded0c1
commit 6e94a0c998
22 changed files with 1083 additions and 18 deletions
@@ -44,11 +44,76 @@ export const DEFAULT_PHOTO_SETTINGS: PhotoSettings = {
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<string>();
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. */
@@ -149,6 +214,7 @@ function normalizeSettings(raw: unknown): Settings {
.filter((entry): entry is CalendarSetting => entry !== null)
.slice(0, MAX_CALENDARS),
photos: normalizePhotos(value.photos),
tvs: normalizeTvs(value.tvs),
};
}
@@ -188,16 +254,17 @@ async function pruneHistory() {
}
/** 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) {
export function saveSettings(patch: Partial<Pick<Settings, "calendars" | "photos" | "tvs">>, 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 });
const next = normalizeSettings({ schema: 1, updatedAt: stamp, calendars, photos, tvs });
await writeJsonAtomic(settingsPath(), next);
return next;
});
@@ -0,0 +1,125 @@
import { createHash } from "node:crypto";
import { readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { playlistUrl, type TvSetting } from "./store";
/*
* TV check-ins. Each Shield's photo app polls GET /api/tv/config every few minutes with its
* Android ID; the server answers with that TV's morning-routine settings and records what the
* TV last reported (so the admin page can show "applied" vs "waiting for the TV").
* Status is runtime data, kept apart from settings.json so it never lands in settings history.
*/
/** How often the app checks in (the app uses this value; keep in sync with the APK default). */
export const CHECK_IN_MINUTES = 5;
/** Music starts this many seconds before the wake time; the calendar comes up at the wake time. */
export const MUSIC_LEAD_SECONDS = 30;
const MAX_STATUS_ENTRIES = 20;
export type TvEvent = { at: number; kind: string; ok: boolean; detail: string };
export type TvStatus = {
id: string;
deviceName: string;
model: string;
ip: string;
appVersion: string;
lastSeenAt: number;
appliedVersion: string;
lastEvent: TvEvent | null;
};
const statusPath = () => path.join(process.env.ORGANIZER_DATA_DIR || "/data", "tv-status.json");
let queue: Promise<unknown> = Promise.resolve();
function serialized<T>(task: () => Promise<T>) {
const run = queue.then(task, task);
queue = run.catch(() => undefined);
return run;
}
export async function readTvStatus(): Promise<Record<string, TvStatus>> {
try {
const raw = JSON.parse(await readFile(statusPath(), "utf8")) as Record<string, TvStatus>;
return raw && typeof raw === "object" ? raw : {};
} catch {
return {};
}
}
async function writeTvStatus(next: Record<string, TvStatus>) {
const temporary = `${statusPath()}.${process.pid}.tmp`;
await writeFile(temporary, JSON.stringify(next), { mode: 0o600 });
await rename(temporary, statusPath());
}
const clean = (value: unknown, max: number) =>
String(value ?? "")
.replace(/[^\x20-\x7e]/g, "")
.trim()
.slice(0, max);
/** Records a check-in (and optionally an event such as the morning routine's result). */
export function recordTvCheckIn(
id: string,
report: { deviceName?: unknown; model?: unknown; appVersion?: unknown; appliedVersion?: unknown; ip: string },
event?: Omit<TvEvent, "at">,
knownIds: Set<string> = new Set(),
) {
return serialized(async () => {
const all = await readTvStatus();
const previous = all[id];
// Unknown TVs are remembered (so admin can add them) but capped, oldest dropped first.
if (!previous && Object.keys(all).length >= MAX_STATUS_ENTRIES) {
const evictable = Object.values(all)
.filter((entry) => !knownIds.has(entry.id))
.sort((left, right) => left.lastSeenAt - right.lastSeenAt);
if (!evictable.length) return;
delete all[evictable[0].id];
}
all[id] = {
id,
deviceName: clean(report.deviceName, 60) || previous?.deviceName || "",
model: clean(report.model, 60) || previous?.model || "",
ip: report.ip,
appVersion: clean(report.appVersion, 20) || previous?.appVersion || "",
lastSeenAt: Date.now(),
appliedVersion: clean(report.appliedVersion, 20) || previous?.appliedVersion || "",
lastEvent: event ? { ...event, kind: clean(event.kind, 20), detail: clean(event.detail, 200), at: Date.now() } : (previous?.lastEvent ?? null),
};
await writeTvStatus(all);
});
}
export function forgetTvStatus(id: string) {
return serialized(async () => {
const all = await readTvStatus();
if (!all[id]) return;
delete all[id];
await writeTvStatus(all);
});
}
/** What the TV app receives. Unknown TVs get everything disabled. */
export function tvConfig(setting: TvSetting | undefined) {
const body = {
registered: Boolean(setting),
name: setting?.name ?? "",
wake: setting?.wake ?? { enabled: false, time: "06:30", days: [] as number[] },
music: {
enabled: Boolean(setting?.music.enabled && setting.music.playlistId),
// watch?list= starts playback; playlist?list= would only open the playlist page.
url: setting?.music.playlistId ? `https://music.youtube.com/watch?list=${setting.music.playlistId}` : "",
},
volume: setting?.volume ?? { enabled: false, level: 40 },
musicLeadSeconds: MUSIC_LEAD_SECONDS,
checkInMinutes: CHECK_IN_MINUTES,
calendarPackage: "com.dayline.tv",
};
return { ...body, version: configVersion(body) };
}
export function configVersion(body: unknown) {
return createHash("sha1").update(JSON.stringify(body)).digest("hex").slice(0, 12);
}
export { playlistUrl };