import { existsSync } from "node:fs"; import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSite, isValidSiteId, siteConfigFile, withSiteLock, type Site, } from "yt-dlp-transcript-common/lib/site"; import { DEFAULT_GROUP_FALLBACK_ID, FALLBACK_GROUP, parseChannelGroups, } from "yt-dlp-transcript-common/lib/channelGroups"; import { channelExists, isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; import { saveSiteFromForm } from "../../../sites/lib/saveSiteForm"; import { SITE_OPS_FIELDS, SiteFieldError, applySiteFields, readChannels, siteToFormData, } from "../../../sites/lib/siteFormData"; import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib"; export const dynamic = "force-dynamic"; // POST { siteId, siteTitle, …the site form's fields…, update? } // -> { ok, siteId, created, site } // // THE NEW SITE FORM, OVER HTTP (lane editor-gaps; 9 Nov an agent had to call // writeSite from a tsx script to make a site). The body's keys are the form's // fields (app/sites/lib/siteFormData.ts SITE_OPS_FIELDS), built into the // FormData the form posts and saved by the form's own action — saveSiteAction, // so writeSite — with its validation and its sentences: a bad site id or a // reserved one, no title, a wordmark lead that is not how the header starts, // a URL that is not absolute, an unknown accent, audience or publish policy, a // group list with none, a deploying policy with no Pages project. // // A CREATE IS PRIVATE AND UNLISTED unless the body says otherwise ("audience": // "public", "listed": true) — the form defaults the other way because a // person at it is building a public site; a script making one is usually // making a reading copy. "headerTitle" defaults to "siteTitle". Every other // key is the form's default: one inline group, no channels, search, archives, // duplicates and transcript downloads on, publish off. // // AN EXISTING ID IS REFUSED (409) unless "update": true, which is the site // page's Save with the given keys changed: the stored site is the form, the // body's keys are laid over it, every key not named stays (the published page // list is the Reports tab's and is always kept). "update" on a site that does // not exist is a 404. // // Refused before anything is written, beside the action's own refusals: an // unknown key, a key of the wrong type, a channel (or cited channel) that does // not exist. export async function POST(request: Request) { return ops(request, ["siteId", "update", ...SITE_OPS_FIELDS], async (body) => { const siteId = reqString(body, "siteId").trim(); if (!isValidSiteId(siteId)) { throw new OpsInputError(`"${siteId}" is not a valid site id (lowercase letters, numbers and hyphens)`); } const update = optBool(body, "update") === true; const paths = getPaths(); if (!update && typeof body.siteTitle !== "string") { throw new OpsInputError('a new site needs a "siteTitle"'); } await refuseUnknownChannels(body); const fields: Record = {}; for (const key of SITE_OPS_FIELDS) if (body[key] !== undefined) fields[key] = body[key]; if (!update && fields.headerTitle === undefined) fields.headerTitle = fields.siteTitle; // ONE READ-MODIFY-WRITE, under the site's lock (lib/site.ts withSiteLock): // whether the site exists, the stored site an update starts from, and the // form's save — so a concurrent edit of the site (a Reports-tab pages // patch, a channel delete's membership patch) is never written over with // the copy read here, and two creates of one id cannot both pass. return withSiteLock(siteId, () => createOrUpdate(siteId, update, fields), paths); }); } async function createOrUpdate( siteId: string, update: boolean, fields: Record, ): Promise { const paths = getPaths(); const exists = existsSync(siteConfigFile(paths, siteId)); if (exists && !update) { return opsFail( `Site "${siteId}" already exists. "update": true saves the keys given over it, as its form's Save does ` + `(site-config sets its cited channels and publish policy alone).`, 409, ); } if (!exists && update) { return opsFail(`Site "${siteId}" not found — leave out "update" to create it`, 404); } const fd = siteToFormData(update ? getSite(siteId, paths) : blankSite(siteId)); try { applySiteFields(fd, fields); refuseUnknownGroups(fd); } catch (e) { if (e instanceof SiteFieldError) return opsFail(e.message); throw e; } const saved = await saveSiteFromForm(fd); if (!saved.ok) return opsFail(saved.error); return NextResponse.json({ ok: true, siteId, created: !update, site: getSite(siteId, paths) }); } // A channel's groupId that names no group of the site: the parser would drop // it without a word (the channel falls into the default group). The form only // offers the site's groups; over ops it is said. function refuseUnknownGroups(fd: FormData): void { const groups = parseChannelGroups(JSON.parse(String(fd.get("groupsJson") ?? "[]"))); const ids = new Set(groups.map((g) => g.id)); const channels = JSON.parse(String(fd.get("channelsJson") ?? "[]")) as { slug?: unknown; groupId?: unknown }[]; for (const c of channels) { if (typeof c.groupId === "string" && c.groupId && !ids.has(c.groupId)) { throw new SiteFieldError( `"channels": "${String(c.slug)}" names group "${c.groupId}", which is not one of the site's groups ` + `(${[...ids].map((id) => `"${id}"`).join(", ") || "none"})`, ); } } } // What /sites/new starts from, private and unlisted. function blankSite(siteId: string): Site { return { siteId, siteTitle: "", siteDescription: "", headerTitle: "", homeTagline: "", groups: [{ ...FALLBACK_GROUP }], defaultGroupId: DEFAULT_GROUP_FALLBACK_ID, channels: [], audience: "private", listed: false, }; } // The form offers only channels that exist; a slug here is checked the same. async function refuseUnknownChannels(body: Record): Promise { const slugs: string[] = []; try { if (body.channels !== undefined) slugs.push(...readChannels(body.channels).map((c) => c.slug)); } catch (e) { if (e instanceof SiteFieldError) throw new OpsInputError(e.message); throw e; } if (Array.isArray(body.citedChannels)) { slugs.push(...body.citedChannels.filter((s): s is string => typeof s === "string").map((s) => s.trim())); } const paths = getPaths(); const missing: string[] = []; for (const slug of new Set(slugs)) { if (!isValidChannelSlug(slug)) { throw new OpsInputError(`"${slug}" is not a valid channel slug`); } if (!(await channelExists(paths, slug))) missing.push(slug); } if (missing.length > 0) { throw new OpsInputError(`not a channel: ${missing.map((s) => `"${s}"`).join(", ")}`); } }