issues.ts

13.4 KB · raw

1import type { Context, Hono } from "hono";2import { issueAttachments } from "../issues/files.ts";3import { followerCount, tellFollowers } from "../issues/followers.ts";4import { attachmentsHtml } from "../issues/pages.ts";5import { MAX_CHARS } from "../issues/spam.ts";6import {7	addEntry,8	blockedReporters,9	blockReporter,10	countIssues,11	type Entry,12	ISSUE_TYPES,13	type IssueType,14	type OperatorFilter,15	type OperatorIssue,16	operatorEntries,17	operatorIssue,18	operatorIssues,19	operatorMatch,20	replyAddresses,21	reporterBlocked,22	setClosed,23	setEntryHidden,24	setHidden,25	setManyClosed,26	setManyHidden,27	setType,28	unblockReporter,29} from "../issues/store.ts";30import { saveByPrefix } from "../mirror/queries.ts";31import { openMirror } from "../mirror/store.ts";32import { html } from "../pages/html.ts";33import { formatDate, relativeTime } from "../pages/layout.ts";34import { renderComment } from "../pages/markdown.ts";35import { type AdminContext, adminPage, formField, notice, textFields } from "./console.ts";36import { allRepos } from "./store.ts";3738const FILTERS: [filter: OperatorFilter, label: string][] = [39	["open", "open"],40	["awaiting", "awaiting reply"],41	["closed", "closed"],42	["hidden", "hidden"],43];44const BULK_ACTIONS = ["close", "reopen", "hide", "unhide"] as const;45const SAVE_PREFIX = /^[0-9a-f]{6,12}$/;46const ISSUE_PATH = "/admin/issues/:repo/:n{[0-9]{1,9}}";47const unixNow = () => Math.floor(Date.now() / 1000);4849/** §24's Issues section: every repo's issues, and the operator's actions of §23. */50export function registerIssues(app: Hono, ctx: AdminContext): void {51	// §23: followers hear of an issue's replies, closes and reopens, unless it is hidden.52	const tell = (53		issue: Pick<OperatorIssue, "id" | "repo" | "number" | "title" | "hidden">,54		text: string,55		anchor = "",56	) => {57		if (issue.hidden) return;58		const href = `/${issue.repo}/issues/${issue.number}${anchor}`;59		tellFollowers(ctx.kepr, `https://${ctx.domain}`, issue.repo, issue, { text, href });60	};61	app.get("/admin/issues", (c) => {62		const filter = FILTERS.find(([f]) => f === c.req.query("filter"))?.[0] ?? "open";63		// An unknown repo or type narrows nothing, as the public list treats an unknown type.64		const repos = allRepos(ctx.kepr).map((repo) => repo.name);65		const repo = repos.find((name) => name === c.req.query("repo")) ?? "";66		const type = ISSUE_TYPES.find((t) => t === c.req.query("type")) ?? "";67		const words = (c.req.query("q") ?? "").trim();68		// One read of every issue, so each tab's count and the list come from the same result.69		const all = operatorIssues(ctx.kepr);70		const narrowed = (f: OperatorFilter) =>71			all.filter(72				(issue) =>73					operatorMatch[f](issue) &&74					(!repo || issue.repo === repo) &&75					(!type || issue.type === type) &&76					`${issue.title}\n${issue.body}`.toLowerCase().includes(words.toLowerCase()),77			);78		const tab = ([f, label]: (typeof FILTERS)[number]) => {79			const query = new URLSearchParams({ filter: f, repo, type, q: words });80			return html`<a class="issues-tab${f === filter ? " active" : ""}"81				href="/admin/issues?${query.toString()}">82${label} <span class="muted">${narrowed(f).length}</span></a>`;83		};84		const option = (value: string, selected: string) =>85			html`<option value="${value}"${value === selected ? html` selected` : ""}>${value}</option>`;86		const issues = narrowed(filter);87		const blocked = blockedReporters(ctx.kepr);88		const body = html`<p class="issues-bar mono">${FILTERS.map(tab)}</p>89${90	blocked.length > 0 &&91	html`<details class="issue-meta mono"><summary>blocked reporters ${String(blocked.length)}</summary>92${blocked.map(93	(b) => html`<form class="issue-row" method="post" action="/admin/issues">94${formField(c)}<input type="hidden" name="action" value="unblock">95<input type="hidden" name="block" value="${String(b.id)}">96<span>from <a href="/admin/issues/${b.repo}/${String(b.number)}">${b.repo} #${String(b.number)}</a>97${relativeTime(b.blocked_at)}</span>98<button class="issues-cancel mono" type="submit">unblock</button></form>`,99)}</details>`100}101<form class="issues-filter" method="get" action="/admin/issues">102<input type="hidden" name="filter" value="${filter}">103<select class="issues-input" name="repo" aria-label="repository">104<option value="">all repos</option>105${repos.map((name) => option(name, repo))}106</select>107<select class="issues-input" name="type" aria-label="issue type">108<option value="">all types</option>109${ISSUE_TYPES.map((value) => option(value, type))}110</select>111<input class="issues-input" name="q" type="search" aria-label="search titles and text"112placeholder="search titles and text" value="${words}">113<button class="issues-submit" type="submit">filter</button>114</form>115<form class="repo-section" method="post" action="/admin/issues">116${formField(c)}<input type="hidden" name="filter" value="${filter}">117${118	issues.length > 0 &&119	html`<p class="issues-filter">120<select class="issues-input" name="action" aria-label="action for ticked issues">121${BULK_ACTIONS.map((action) => html`<option value="${action}">${action}</option>`)}122</select>123<button class="issues-submit" type="submit">apply to ticked</button></p>`124}125${126	issues.length > 0127		? issues.map(128				(issue) =>129					html`<div class="admin-select-row">130<input type="checkbox" name="issue" value="${String(issue.id)}"131aria-label="tick ${issue.repo} #${String(issue.number)}">132<a class="issue-row" href="/admin/issues/${issue.repo}/${issue.number}">133<span class="issue-title">${issue.title}${134						issue.awaiting && !issue.hidden && issue.status === "open"135							? html` <span class="issue-badge">awaiting reply</span>`136							: ""137					}</span>138<span class="issue-meta mono">${issue.repo} #${issue.number} · ${issue.type} ·139${issue.status} · ${relativeTime(issue.filed_at)}</span></a></div>`,140			)141		: html`<p class="muted mono save-empty">no issues here</p>`142}143</form>`;144		return c.html(adminPage(c, ctx, "issues", body));145	});146147	app.post("/admin/issues", async (c) => {148		const form = await c.req.parseBody({ all: true });149		const action = form.action;150		if (action === "unblock") {151			return unblockReporter(ctx.kepr, Number(form.block))152				? c.redirect("/admin/issues", 303)153				: c.notFound();154		}155		const ids = [form.issue ?? []].flat().map(Number);156		const known =157			ids.length > 0 &&158			ids.every(Number.isSafeInteger) &&159			countIssues(ctx.kepr, ids) === new Set(ids).size;160		if (!known) return c.notFound();161		switch (action) {162			case "close":163			case "reopen":164				for (const changed of setManyClosed(ctx.kepr, ids, action === "close" ? unixNow() : null)) {165					tell(changed, `"${changed.title}" was ${action === "close" ? "closed" : "reopened"}.`);166				}167				break;168			case "hide":169			case "unhide":170				setManyHidden(ctx.kepr, ids, action === "hide");171				break;172			default:173				return c.notFound();174		}175		const filter = FILTERS.find(([f]) => f === form.filter)?.[0] ?? "open";176		return c.redirect(`/admin/issues?filter=${filter}`, 303);177	});178179	app.get(ISSUE_PATH, (c) => {180		const issue = operatorIssue(ctx.kepr, c.req.param("repo"), Number(c.req.param("n")));181		return issue ? c.html(issuePage(c, ctx, issue, "")) : c.notFound();182	});183184	app.post(ISSUE_PATH, async (c) => {185		const issue = operatorIssue(ctx.kepr, c.req.param("repo"), Number(c.req.param("n")));186		if (!issue) return c.notFound();187		const fields = await textFields(c);188		const refuse = (error: string) => c.html(issuePage(c, ctx, issue, error), 400);189		switch (fields.action) {190			case "reply": {191				const body = (fields.body ?? "").trim();192				if (body === "" || body.length > MAX_CHARS) {193					return refuse(`A reply is 1 to ${MAX_CHARS.toLocaleString("en-US")} characters.`);194				}195				const entry = addEntry(ctx.kepr, issue.id, { author: "operator", body, at: unixNow() });196				tell(issue, `The operator replied:\n\n${body}`, `#entry-${entry}`);197				break;198			}199			case "close": {200				const prefix = (fields.fixed_in ?? "").trim();201				const save = SAVE_PREFIX.test(prefix)202					? saveByPrefix(openMirror(ctx.mirrorDir, issue.repo), prefix)203					: null;204				if (prefix !== "" && !save) return refuse(`No save ${prefix} in ${issue.repo}.`);205				setClosed(ctx.kepr, issue.id, unixNow(), save?.id ?? "");206				tell(issue, `"${issue.title}" was closed${save ? `, fixed in ${save.id}` : ""}.`);207				break;208			}209			case "reopen":210				setClosed(ctx.kepr, issue.id, null);211				tell(issue, `"${issue.title}" was reopened.`);212				break;213			case "hide_entry":214			case "unhide_entry": {215				const entry = Number(fields.entry);216				const hidden = fields.action === "hide_entry";217				if (!Number.isSafeInteger(entry) || !setEntryHidden(ctx.kepr, issue.id, entry, hidden)) {218					return c.notFound();219				}220				break;221			}222			case "hide":223			case "unhide":224				setHidden(ctx.kepr, issue.id, fields.action === "hide");225				break;226			case "block":227				if (blockReporter(ctx.kepr, issue.id, unixNow()) === null) {228					return refuse("This issue has no address to block.");229				}230				break;231			case "block_entry": {232				const entry = Number(fields.entry);233				if (234					!Number.isSafeInteger(entry) ||235					blockReporter(ctx.kepr, issue.id, unixNow(), entry) === null236				) {237					return refuse("This reply has no address to block.");238				}239				break;240			}241			case "type":242				if (!ISSUE_TYPES.includes(fields.type as IssueType)) return refuse("Pick a type.");243				setType(ctx.kepr, issue.id, fields.type as IssueType);244				break;245			default:246				return refuse("Unknown action.");247		}248		return c.redirect(`/admin/issues/${issue.repo}/${issue.number}`, 303);249	});250}251252function issuePage(c: Context, ctx: AdminContext, issue: OperatorIssue, error: string): string {253	const action = `/admin/issues/${issue.repo}/${issue.number}`;254	const button = (name: string, label: string) =>255		html`<form method="post" action="${action}">256${formField(c)}<input type="hidden" name="action" value="${name}">257<button class="issues-submit" type="submit">${label}</button></form>`;258	const files = issueAttachments(ctx.kepr, issue.id);259	const addresses = new Map(replyAddresses(ctx.kepr, issue.id).map((row) => [row.id, row.blocked]));260	const entryAction = (entry: Entry, name: string, label: string) =>261		html`<form method="post" action="${action}">${formField(c)}262<input type="hidden" name="action" value="${name}">263<input type="hidden" name="entry" value="${String(entry.id)}">264<button class="issues-cancel mono" type="submit">${label}</button></form>`;265	const post = (operator: boolean, at: number, text: string, entry?: Entry) =>266		html`<article class="issue-post${operator ? " issue-post--operator" : ""}">267<p class="issue-post-head mono">${268			operator269				? html`<span class="issue-badge">operator</span>`270				: html`<span class="issue-author">${271						entry ? entry.name || "anonymous" : issue.reporter_name || "anonymous"272					}</span>`273		}<span class="history-when">${formatDate(at)}</span>${274			entry?.hidden ? html`<span class="issues-error">hidden</span>` : ""275		}</p>276<div class="markdown issue-text">${renderComment(text)}</div>277${attachmentsHtml(278	`/${issue.repo}/issues/${issue.number}`,279	files.filter((file) => file.entry_id === (entry?.id ?? null)),280)}281${282	entry &&283	html`<div class="issues-actions">284${285	entry.hidden286		? entryAction(entry, "unhide_entry", "unhide")287		: entryAction(entry, "hide_entry", "hide (spam)")288}289${290	addresses.get(entry.id) === 0291		? entryAction(entry, "block_entry", "block this address")292		: addresses.get(entry.id) === 1 && html`<span class="issues-error mono">address blocked</span>`293}</div>`294}295</article>`;296	const typeOption = (type: string) =>297		html`<option value="${type}"${issue.type === type ? html` selected` : ""}>${type}</option>`;298	const body = html`${notice(error)}299<p class="issue-meta mono">${issue.repo} #${issue.number} · ${issue.status}${300		issue.fixed_in && ` · fixed in ${issue.fixed_in}`301	}${issue.hidden ? " · hidden" : ""} · ${issue.version && `v${issue.version} · `}filed ${formatDate(issue.filed_at)}302· ${followerCount(ctx.kepr, issue.id)} following by email</p>303<p class="issue-meta mono">reporter: ${issue.reporter_name || "anonymous"}304· contact: ${issue.contact_email || "none given"}${305		reporterBlocked(ctx.kepr, issue.id)306			? html` · <span class="issues-error">reporter blocked</span>`307			: ""308	}</p>309${post(false, issue.filed_at, issue.body)}310${operatorEntries(ctx.kepr, issue.id).map((entry) =>311	post(entry.author === "operator", entry.created_at, entry.body, entry),312)}313<form class="issues-form" method="post" action="${action}">${formField(c)}314<input type="hidden" name="action" value="reply">315<label class="issues-label" for="reply">reply</label>316<textarea class="issues-textarea" id="reply" name="body" rows="5" required317maxlength="${MAX_CHARS}"></textarea>318<button class="issues-submit" type="submit">reply</button>319</form>320${321	issue.status === "open"322		? html`<form class="issues-form" method="post" action="${action}">${formField(c)}323<input type="hidden" name="action" value="close">324<label class="issues-label" for="fixed-in">fixed in save325<span class="muted">(optional)</span></label>326<input class="issues-input" id="fixed-in" name="fixed_in" maxlength="12">327<button class="issues-submit" type="submit">close</button>328</form>`329		: button("reopen", "reopen")330}331<form class="issues-form" method="post" action="${action}">${formField(c)}332<input type="hidden" name="action" value="type">333<label class="issues-label" for="type">type</label>334<select class="issues-input" id="type" name="type">${ISSUE_TYPES.map(typeOption)}</select>335<button class="issues-submit" type="submit">set type</button>336</form>337${issue.hidden ? button("unhide", "unhide") : button("hide", "hide (spam)")}338${!reporterBlocked(ctx.kepr, issue.id) && button("block", "block this reporter")}`;339	return adminPage(c, ctx, issue.title, body);340}