Andrea Vos 7c49f14368 Merge branch 'refs/heads/main' into split-audit
# Conflicts:
#	pnpm-lock.yaml
2024-12-31 19:45:30 +01:00

287 lines
9.5 KiB
TypeScript

import { createCanvas, loadImage, registerFont } from 'canvas';
import { Router } from 'express';
import type { Request } from 'express';
import SQL from 'sql-template-strings';
import { ulid } from 'ulid';
import type { Translations } from '../../locale/translations.ts';
import { clearKey, handleErrorAsync } from '../../src/helpers.ts';
import type { User } from '../../src/user.ts';
import { auditLog } from '../audit.ts';
import type { Database } from '../db.ts';
import { loadSuml } from '../loader.ts';
import { registerLocaleFont } from '../localeFont.ts';
import type { SourceRow } from './sources.ts';
import type { UserRow } from './user.ts';
const translations = loadSuml('translations') as Translations;
interface NounRow {
id: string;
masc: string;
fem: string;
neutr: string;
mascPl: string;
femPl: string;
neutrPl: string;
approved: number;
base_id: string | null;
locale: string;
author_id: string | null;
deleted: number;
sources: string | null;
categories: string | null;
}
type NounRowWithAuthor = NounRow & { author: User['username'] };
const approve = async (db: Database, id: string) => {
const { base_id } = (await db.get<Pick<NounRow, 'base_id'>>(SQL`SELECT base_id FROM nouns WHERE id=${id}`))!;
if (base_id) {
await db.get(SQL`
UPDATE nouns
SET deleted=1
WHERE id = ${base_id}
`);
}
await db.get(SQL`
UPDATE nouns
SET approved = 1, base_id = NULL
WHERE id = ${id}
`);
await invalidateCache('nouns');
await invalidateCache('search', 'noun');
};
const addVersions = async (db: Database, isGranted: Request['isGranted'], nouns: NounRowWithAuthor[]) => {
const keys = new Set();
nouns.filter((s) => !!s && s.sources)
.forEach((s) => s.sources!.split(',').forEach((k) => keys.add(`'${clearKey(k.split('#')[0])}'`)));
const sources = await db.all<SourceRow & Pick<UserRow, 'username'>>(SQL`
SELECT s.*, u.username AS submitter FROM sources s
LEFT JOIN users u ON s.submitter_id = u.id
WHERE s.locale == ${global.config.locale}
AND s.deleted = 0
AND s.approved >= ${isGranted('sources') ? 0 : 1}
AND s.key IN (`.append([...keys].join(',')).append(SQL`)
`));
const sourcesMap: Record<string, SourceRow> = {};
sources.forEach((s) => sourcesMap[s.key!] = s);
return nouns.map((n) => ({
...n,
sourcesData: (n.sources ? n.sources.split(',') : []).map((s) => selectFragment(sourcesMap, s)),
}));
};
const selectFragment = (sourcesMap: Record<string, SourceRow>, keyAndFragment: string) => {
const [key, fragment] = keyAndFragment.split('#');
if (sourcesMap[key] === undefined) {
return undefined;
}
if (fragment === undefined) {
return sourcesMap[key];
}
const source = { ...sourcesMap[key] };
const fragments = source.fragments
? source.fragments.replace(/\\@/g, '###').split('@')
.map((x) => x.replace(/###/g, '@'))
: [];
source.fragments = fragments[parseInt(fragment) - 1];
return source;
};
const router = Router();
export const getNounEntries = defineCachedFunction(async (db: Database, isGranted: Request['isGranted']) => {
return await addVersions(db, isGranted, await db.all<NounRowWithAuthor>(SQL`
SELECT n.*, u.username AS author FROM nouns n
LEFT JOIN users u ON n.author_id = u.id
WHERE n.locale = ${global.config.locale}
AND n.deleted = 0
AND n.approved >= ${isGranted('nouns') ? 0 : 1}
ORDER BY n.approved, n.masc
`));
}, {
name: 'nouns',
getKey: () => 'default',
shouldBypassCache: (db, isGranted) => isGranted('nouns'),
maxAge: 24 * 60 * 60,
});
router.get('/nouns', handleErrorAsync(async (req, res) => {
return res.json(await getNounEntries(req.db, req.isGranted));
}));
router.get('/nouns/search/:term', handleErrorAsync(async (req, res) => {
const term = `%${req.params.term}%`;
return res.json(await addVersions(req.db, req.isGranted, await req.db.all(SQL`
SELECT n.*, u.username AS author FROM nouns n
LEFT JOIN users u ON n.author_id = u.id
WHERE n.locale = ${global.config.locale}
AND n.approved >= ${req.isGranted('nouns') ? 0 : 1}
AND n.deleted = 0
AND (n.masc like ${term} OR n.fem like ${term} OR n.neutr like ${term} OR n.mascPl like ${term} OR n.femPl like ${term} OR n.neutrPl like ${term})
ORDER BY n.approved, n.masc
`)));
}));
router.post('/nouns/submit', handleErrorAsync(async (req, res) => {
if (!req.user || !await req.isUserAllowedToPost()) {
return res.status(401).json({ error: 'Unauthorised' });
}
const id = ulid();
await req.db.get(SQL`
INSERT INTO nouns (id, masc, fem, neutr, mascPl, femPl, neutrPl, categories, sources, approved, base_id, locale, author_id)
VALUES (
${id},
${req.body.masc.join('|')}, ${req.body.fem.join('|')}, ${req.body.neutr.join('|')},
${req.body.mascPl.join('|')}, ${req.body.femPl.join('|')}, ${req.body.neutrPl.join('|')},
${req.body.categories.join('|')},
${req.body.sources ? req.body.sources.join(',') : null},
0, ${req.body.base}, ${global.config.locale}, ${req.user ? req.user.id : null}
)
`);
await auditLog(req, 'nouns/submitted', { ...req.body });
if (req.isGranted('nouns')) {
await approve(req.db, id);
await auditLog(req, 'nouns/approved', { id });
}
return res.json('ok');
}));
router.post('/nouns/hide/:id', handleErrorAsync(async (req, res) => {
if (!req.isGranted('nouns')) {
return res.status(401).json({ error: 'Unauthorised' });
}
await req.db.get(SQL`
UPDATE nouns
SET approved = 0
WHERE id = ${req.params.id}
`);
await invalidateCache('nouns');
await invalidateCache('search', 'noun');
await auditLog(req, 'nouns/hidden', { id: req.params.id });
return res.json('ok');
}));
router.post('/nouns/approve/:id', handleErrorAsync(async (req, res) => {
if (!req.isGranted('nouns')) {
return res.status(401).json({ error: 'Unauthorised' });
}
await approve(req.db, req.params.id);
await auditLog(req, 'nouns/approved', { id: req.params.id });
return res.json('ok');
}));
router.post('/nouns/remove/:id', handleErrorAsync(async (req, res) => {
if (!req.isGranted('nouns')) {
return res.status(401).json({ error: 'Unauthorised' });
}
await req.db.get(SQL`
UPDATE nouns
SET deleted=1
WHERE id = ${req.params.id}
`);
await invalidateCache('nouns');
await invalidateCache('search', 'noun');
await auditLog(req, 'nouns/removed', { id: req.params.id });
return res.json('ok');
}));
router.get('/nouns/:id.png', async (req, res) => {
const noun = await req.db.get<NounRow>(SQL`
SELECT * FROM nouns
WHERE locale = ${global.config.locale}
AND id = ${req.params.id}
AND approved >= ${req.isGranted('nouns') ? 0 : 1}
AND deleted = 0
`);
if (!noun) {
return res.status(404).json({ error: 'Not found' });
}
let maxItems = 0;
(['masc', 'fem', 'neutr'] as const).forEach((form) => {
let items = 0;
for (const key of ['', 'Pl'] as const) {
items += noun[`${form}${key}`].split('|').filter((x) => x.length).length;
}
if (items > maxItems) {
maxItems = items;
}
});
const padding = 48;
const width = 1200;
const height = padding * 2.5 + (maxItems + 1) * 48 + padding;
const mime = 'image/png';
const fontName = registerLocaleFont('fontHeadings', ['regular', 'bold']);
registerFont('node_modules/@fortawesome/fontawesome-pro/webfonts/fa-light-300.ttf', { family: 'FontAwesome', weight: 'regular' });
const canvas = createCanvas(width, height);
const context = canvas.getContext('2d');
const bg = await loadImage('public/bg.png');
context.drawImage(bg, 0, 0, width, height);
context.font = `bold 64pt '${fontName}'`;
for (const [column, key, icon] of [[0, 'masculine', '\uf222'], [1, 'feminine', '\uf221'], [2, 'neuter', '\uf22c']] as const) {
context.font = 'regular 24pt FontAwesome';
context.fillText(icon, column * (width - 2 * padding) / 3 + padding, padding * 1.5);
context.font = `bold 24pt '${fontName}'`;
context.fillText(translations.nouns[key], column * (width - 2 * padding) / 3 + padding + 36, padding * 1.5);
}
context.font = `regular 24pt '${fontName}'`;
(['masc', 'fem', 'neutr'] as const).forEach((form, column) => {
let i = 0;
for (const [key, symbol] of [['', '⋅'], ['Pl', '⁖']] as const) {
noun[`${form}${key}`].split('|').filter((x) => x.length)
.forEach((part) => {
context.fillText(`${symbol} ${part}`, column * (width - 2 * padding) / 3 + padding, padding * 2.5 + i * 48);
i++;
});
}
});
context.fillStyle = '#C71585';
context.font = 'regular 16pt FontAwesome';
context.fillText('\uf02c', padding, height - padding + 12);
context.font = `regular 16pt '${fontName}'`;
context.fillText(
`${translations.domain}/${global.config.nouns.routeMain || global.config.nouns.route}`,
padding + 36,
height - padding + 10,
);
return res.set('content-type', mime).send(canvas.toBuffer(mime));
});
export default router;