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
This commit is contained in:
2026-11-04 19:18:02 -06:00
parent 8715589cbb
commit c2e5c1d9dc
24 changed files with 1215 additions and 27 deletions
@@ -54,7 +54,7 @@ export async function PUT(request: Request) {
}
if (new Set(next.map((calendar) => calendar.url)).size !== next.length) return json({ error: "The same calendar is listed twice." }, 400);
const saved = await saveSettings(next, `Saved ${next.length} calendar(s)`);
const saved = await saveSettings({ calendars: next }, `Saved ${next.length} calendar(s)`);
console.log(`[admin] calendars saved (${saved.calendars.length})`);
return json({ calendars: publicView(saved.calendars), updatedAt: saved.updatedAt });
}
@@ -1,4 +1,5 @@
import { json, readJsonBody, requireAdmin } from "../../../_lib/auth";
import { syncAll } from "../../../_lib/photos";
import { listHistory, readHistorySnapshot, saveSettings } from "../../../_lib/store";
export const dynamic = "force-dynamic";
@@ -9,14 +10,15 @@ export async function GET(request: Request) {
return json({ history: await listHistory() });
}
/** Reverts calendars to a snapshot. The current state is itself snapshotted first, so a revert can be undone. */
/** Reverts calendars and photo settings to a snapshot. The current state is itself snapshotted first, so a revert can be undone. */
export async function POST(request: Request) {
const denied = await requireAdmin(request, { mutating: true });
if (denied) return denied;
const body = await readJsonBody<{ id?: string }>(request);
const snapshot = body?.id ? await readHistorySnapshot(body.id) : null;
if (!snapshot) return json({ error: "That version no longer exists." }, 404);
const saved = await saveSettings(snapshot.calendars, `Reverted to version from ${snapshot.updatedAt}`);
console.log(`[admin] calendars reverted to ${body?.id}`);
const saved = await saveSettings({ calendars: snapshot.calendars, photos: snapshot.photos }, `Reverted to version from ${snapshot.updatedAt}`);
console.log(`[admin] settings reverted to ${body?.id}`);
void syncAll(); // re-fetch any album the restored version brings back
return json({ ok: true, updatedAt: saved.updatedAt });
}
@@ -0,0 +1,27 @@
import { json, readJsonBody, requireAdmin } from "../../../../_lib/auth";
import { MAX_PHOTOS_PER_ALBUM, scrapeAlbum } from "../../../../_lib/photos";
import { validAlbumUrl } from "../../../../_lib/store";
export const dynamic = "force-dynamic";
/** Reads a share link without saving it: album title and how many photos/videos it has. */
export async function POST(request: Request) {
const denied = await requireAdmin(request, { mutating: true });
if (denied) return denied;
const body = await readJsonBody<{ shareUrl?: string }>(request);
const shareUrl = validAlbumUrl(body?.shareUrl);
if (!shareUrl) return json({ ok: false, error: "Not a Google Photos share link." }, 400);
try {
const album = await scrapeAlbum(shareUrl);
const videos = album.items.filter((item) => item.video).length;
return json({
ok: true,
title: album.title,
photos: album.items.length - videos,
videos,
truncated: album.hasMorePages || album.items.length - videos > MAX_PHOTOS_PER_ALBUM,
});
} catch (error) {
return json({ ok: false, error: error instanceof Error ? error.message : "Could not read the album." });
}
}
@@ -0,0 +1,83 @@
import { randomUUID } from "node:crypto";
import { json, readJsonBody, requireAdmin } from "../../../_lib/auth";
import { isSyncing, readIndex, removeOrphanedAlbumFolders, STALE_AFTER_MS, syncAlbum, UPLOADS_DIR } from "../../../_lib/photos";
import { MAX_ALBUMS, maskAlbumUrl, type PhotoAlbum, type PhotoSettings, readSettings, saveSettings, validAlbumUrl } from "../../../_lib/store";
export const dynamic = "force-dynamic";
async function view(photos: PhotoSettings) {
const { albums, ...display } = photos;
const uploads = await readIndex(UPLOADS_DIR);
return {
display,
albums: await Promise.all(
albums.map(async (album) => {
const index = await readIndex(album.id);
return {
id: album.id,
name: album.name,
enabled: album.enabled,
masked: maskAlbumUrl(album.shareUrl),
title: index.title,
photoCount: index.photos.length,
lastSuccessAt: index.lastSuccessAt,
lastAttemptAt: index.lastAttemptAt,
lastError: index.lastError,
truncated: index.truncated,
stale: album.enabled && Date.now() - (index.lastSuccessAt ?? (index.firstAttemptAt || Date.now())) > STALE_AFTER_MS,
syncing: isSyncing(album.id),
};
}),
),
uploads: uploads.photos.map((photo) => ({ key: photo.key, thumb: `/api/photos/img/${UPLOADS_DIR}/${photo.key}.t.jpg`, src: `/api/photos/img/${UPLOADS_DIR}/${photo.key}.jpg` })),
};
}
export async function GET(request: Request) {
const denied = await requireAdmin(request);
if (denied) return denied;
return json(await view((await readSettings()).photos));
}
type IncomingAlbum = { id?: string; name?: string; enabled?: boolean; shareUrl?: string };
type Incoming = { display?: Partial<Omit<PhotoSettings, "albums">>; albums?: IncomingAlbum[] };
export async function PUT(request: Request) {
const denied = await requireAdmin(request, { mutating: true });
if (denied) return denied;
const body = await readJsonBody<Incoming>(request);
if (!body || !Array.isArray(body.albums)) return json({ error: "Expected albums and display settings." }, 400);
if (body.albums.length > MAX_ALBUMS) return json({ error: `At most ${MAX_ALBUMS} albums.` }, 400);
const current = (await readSettings()).photos;
const existing = new Map(current.albums.map((album) => [album.id, album]));
const albums: PhotoAlbum[] = [];
const toSync: PhotoAlbum[] = [];
for (const [position, entry] of body.albums.entries()) {
const label = entry.name?.trim() || `Album ${position + 1}`;
const previous = entry.id ? existing.get(entry.id) : undefined;
if (entry.id && !previous) return json({ error: `${label}: unknown album; reload the page.` }, 409);
const supplied = typeof entry.shareUrl === "string" && entry.shareUrl.trim() ? validAlbumUrl(entry.shareUrl) : null;
if (entry.shareUrl?.trim() && !supplied) return json({ error: `${label}: paste a Google Photos share link (https://photos.app.goo.gl/… or https://photos.google.com/share/…).` }, 400);
const shareUrl = supplied ?? previous?.shareUrl;
if (!shareUrl) return json({ error: `${label}: a share link is required.` }, 400);
const album: PhotoAlbum = {
id: previous?.id ?? randomUUID(),
name: typeof entry.name === "string" ? entry.name.trim().slice(0, 60) : "",
shareUrl,
enabled: entry.enabled !== false,
};
albums.push(album);
if (album.enabled && (!previous || previous.shareUrl !== shareUrl || !previous.enabled)) toSync.push(album);
}
if (new Set(albums.map((album) => album.shareUrl)).size !== albums.length) return json({ error: "The same album is listed twice." }, 400);
const saved = await saveSettings({ photos: { ...current, ...(body.display ?? {}), albums } }, `Saved photo settings (${albums.length} album(s))`);
console.log(`[admin] photo settings saved (${albums.length} album(s))`);
// Fetch new/changed albums now, and drop cache folders of removed ones, without making the browser wait.
void (async () => {
await removeOrphanedAlbumFolders();
for (const album of toSync) await syncAlbum(album);
})();
return json(await view(saved.photos));
}
@@ -0,0 +1,20 @@
import { json, readJsonBody, requireAdmin } from "../../../../_lib/auth";
import { syncAlbum, syncAll } from "../../../../_lib/photos";
import { readSettings } from "../../../../_lib/store";
export const dynamic = "force-dynamic";
/** Syncs one album ({ id }) or all of them, and waits for the result. */
export async function POST(request: Request) {
const denied = await requireAdmin(request, { mutating: true });
if (denied) return denied;
const body = await readJsonBody<{ id?: string }>(request);
if (body?.id) {
const album = (await readSettings()).photos.albums.find((entry) => entry.id === body.id);
if (!album) return json({ error: "Unknown album." }, 404);
const index = await syncAlbum(album);
return json({ ok: !index.lastError || index.photos.length > 0, photoCount: index.photos.length, lastError: index.lastError });
}
await syncAll();
return json({ ok: true });
}
@@ -0,0 +1,44 @@
import { json, requireAdmin } from "../../../../_lib/auth";
import { addUpload, isJpeg, removeUpload } from "../../../../_lib/photos";
export const dynamic = "force-dynamic";
/**
* The admin page resizes photos in the browser (max 1920px JPEG plus a 64px thumbnail)
* before sending them, so the server only validates and stores.
*/
export async function POST(request: Request) {
const denied = await requireAdmin(request, { mutating: true });
if (denied) return denied;
let form: FormData;
try {
form = await request.formData();
} catch {
return json({ error: "Expected a photo upload." }, 400);
}
const photo = form.get("photo");
const thumb = form.get("thumb");
if (!(photo instanceof Blob) || !(thumb instanceof Blob)) return json({ error: "Missing photo." }, 400);
if (photo.size > 8 * 1024 * 1024 || thumb.size > 256 * 1024) return json({ error: "Photo is too large." }, 413);
const photoBytes = new Uint8Array(await photo.arrayBuffer());
const thumbBytes = new Uint8Array(await thumb.arrayBuffer());
if (!isJpeg(photoBytes) || !isJpeg(thumbBytes)) return json({ error: "Photos must be JPEG." }, 415);
const takenAt = Number(form.get("takenAt"));
try {
const result = await addUpload(photoBytes, thumbBytes, {
takenAt: Number.isFinite(takenAt) && takenAt > 0 ? takenAt : null,
width: Math.max(0, Math.round(Number(form.get("width")) || 0)),
height: Math.max(0, Math.round(Number(form.get("height")) || 0)),
});
return json({ ok: true, ...result });
} catch (error) {
return json({ error: error instanceof Error ? error.message : "Upload failed." }, 400);
}
}
export async function DELETE(request: Request) {
const denied = await requireAdmin(request, { mutating: true });
if (denied) return denied;
const key = new URL(request.url).searchParams.get("key") || "";
return (await removeUpload(key)) ? json({ ok: true }) : json({ error: "Not found." }, 404);
}