260 lines
12 KiB
TypeScript
260 lines
12 KiB
TypeScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { Hono } from 'hono';
|
|
import { z } from 'zod';
|
|
import { HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
|
|
import { listCards, listQuestions } from '../services/content.ts';
|
|
import { newId, newToken, now } from '../util.ts';
|
|
|
|
const KINDS = ['quiz', 'deck', 'folder', 'class', 'note', 'document'] as const;
|
|
type ShareKind = (typeof KINDS)[number];
|
|
|
|
interface ShareRow {
|
|
id: string;
|
|
token: string;
|
|
kind: ShareKind;
|
|
target_id: string;
|
|
enabled: number;
|
|
view_count: number;
|
|
last_viewed_at: number | null;
|
|
created_at: number;
|
|
updated_at: number;
|
|
}
|
|
|
|
const TABLE: Record<ShareKind, { table: string; title: string }> = {
|
|
quiz: { table: 'quizzes', title: 'title' },
|
|
deck: { table: 'decks', title: 'title' },
|
|
note: { table: 'notes', title: 'title' },
|
|
document: { table: 'documents', title: 'title' },
|
|
folder: { table: 'folders', title: 'name' },
|
|
class: { table: 'classes', title: 'name' },
|
|
};
|
|
|
|
function mapShare(row: ShareRow) {
|
|
return {
|
|
id: row.id,
|
|
token: row.token,
|
|
kind: row.kind,
|
|
targetId: row.target_id,
|
|
enabled: Boolean(row.enabled),
|
|
viewCount: row.view_count,
|
|
lastViewedAt: row.last_viewed_at,
|
|
createdAt: row.created_at,
|
|
};
|
|
}
|
|
|
|
/* ------------------------------ admin ------------------------------ */
|
|
|
|
export function shareRoutes(app: AppContext): Hono {
|
|
const { db } = app;
|
|
const r = new Hono();
|
|
|
|
r.get('/shares', (c) => {
|
|
const rows = db.all<ShareRow>('SELECT * FROM shares ORDER BY created_at DESC');
|
|
const out = [];
|
|
for (const row of rows) {
|
|
const meta = TABLE[row.kind];
|
|
const target = db.get<{ title: string; class_id?: string }>(
|
|
`SELECT ${meta.title} AS title${row.kind === 'class' ? '' : ', class_id'} FROM ${meta.table} WHERE id = ?`,
|
|
row.target_id,
|
|
);
|
|
if (!target) {
|
|
db.run('DELETE FROM shares WHERE id = ?', row.id);
|
|
continue;
|
|
}
|
|
const classId = row.kind === 'class' ? row.target_id : target.class_id;
|
|
const cls = classId ? db.get<{ name: string; color: string }>('SELECT name, color FROM classes WHERE id = ?', classId) : undefined;
|
|
out.push({ ...mapShare(row), title: target.title, classId: classId ?? null, className: cls?.name ?? '', classColor: cls?.color ?? 'slate' });
|
|
}
|
|
return c.json({ shares: out });
|
|
});
|
|
|
|
r.post('/shares', async (c) => {
|
|
const body = await readBody(c, z.object({ kind: z.enum(KINDS), targetId: z.string() }));
|
|
const meta = TABLE[body.kind];
|
|
if (!db.get(`SELECT id FROM ${meta.table} WHERE id = ?`, body.targetId)) throw notFound('Item');
|
|
const existing = db.get<ShareRow>('SELECT * FROM shares WHERE kind = ? AND target_id = ?', body.kind, body.targetId);
|
|
const at = now();
|
|
if (existing) {
|
|
db.run('UPDATE shares SET enabled = 1, updated_at = ? WHERE id = ?', at, existing.id);
|
|
return c.json({ share: mapShare({ ...existing, enabled: 1 }) });
|
|
}
|
|
const id = newId();
|
|
db.run('INSERT INTO shares (id, token, kind, target_id, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?)', id, newToken(), body.kind, body.targetId, at, at);
|
|
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) }, 201);
|
|
});
|
|
|
|
r.patch('/shares/:id', async (c) => {
|
|
const id = idParam(c);
|
|
const body = await readBody(c, z.object({ enabled: z.boolean() }));
|
|
const { changes } = db.run('UPDATE shares SET enabled = ?, updated_at = ? WHERE id = ?', body.enabled ? 1 : 0, now(), id);
|
|
if (!changes) throw notFound('Share link');
|
|
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
|
|
});
|
|
|
|
/** Issues a new token: the old link stops working immediately. */
|
|
r.post('/shares/:id/rotate', (c) => {
|
|
const id = idParam(c);
|
|
const { changes } = db.run('UPDATE shares SET token = ?, view_count = 0, last_viewed_at = NULL, updated_at = ? WHERE id = ?', newToken(), now(), id);
|
|
if (!changes) throw notFound('Share link');
|
|
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
|
|
});
|
|
|
|
r.delete('/shares/:id', (c) => {
|
|
const { changes } = db.run('DELETE FROM shares WHERE id = ?', idParam(c));
|
|
if (!changes) throw notFound('Share link');
|
|
return c.json({ ok: true });
|
|
});
|
|
|
|
return r;
|
|
}
|
|
|
|
/* ------------------------------ public (no auth) ------------------------------ */
|
|
|
|
const gone = () => new HttpError(404, 'share_not_found', 'This link is no longer available');
|
|
|
|
function publicQuiz(app: AppContext, id: string) {
|
|
const quiz = app.db.get<{ id: string; title: string; description: string; class_id: string }>('SELECT id, title, description, class_id FROM quizzes WHERE id = ?', id);
|
|
if (!quiz) throw gone();
|
|
return {
|
|
kind: 'quiz' as const,
|
|
id: quiz.id,
|
|
title: quiz.title,
|
|
description: quiz.description,
|
|
questions: listQuestions(app.db, quiz.id).map((q) => ({
|
|
id: q.id,
|
|
type: q.type,
|
|
stem: q.stem,
|
|
options: q.options,
|
|
rationale: q.rationale,
|
|
topic: q.topic,
|
|
difficulty: q.difficulty,
|
|
})),
|
|
};
|
|
}
|
|
|
|
function publicDeck(app: AppContext, id: string) {
|
|
const deck = app.db.get<{ id: string; title: string; description: string }>('SELECT id, title, description FROM decks WHERE id = ?', id);
|
|
if (!deck) throw gone();
|
|
return {
|
|
kind: 'deck' as const,
|
|
id: deck.id,
|
|
title: deck.title,
|
|
description: deck.description,
|
|
cards: listCards(app.db, deck.id).map((c) => ({ id: c.id, front: c.front, back: c.back, hint: c.hint })),
|
|
};
|
|
}
|
|
|
|
function publicNote(app: AppContext, id: string) {
|
|
const note = app.db.get<{ id: string; title: string; content: string; updated_at: number }>('SELECT id, title, content, updated_at FROM notes WHERE id = ?', id);
|
|
if (!note) throw gone();
|
|
return { kind: 'note' as const, id: note.id, title: note.title, content: note.content, updatedAt: note.updated_at };
|
|
}
|
|
|
|
function publicDocument(app: AppContext, id: string) {
|
|
const doc = app.db.get<Record<string, any>>('SELECT id, title, filename, kind, size, page_count, mime FROM documents WHERE id = ?', id);
|
|
if (!doc) throw gone();
|
|
return { kind: 'document' as const, id: doc.id as string, title: doc.title as string, filename: doc.filename as string, docKind: doc.kind as string, size: doc.size as number, pageCount: doc.page_count as number | null };
|
|
}
|
|
|
|
/** Quizzes, decks and notes inside a class or folder. Uploaded documents are never included in a collection share. */
|
|
function collectionItems(app: AppContext, share: ShareRow) {
|
|
const { db } = app;
|
|
const byFolder = share.kind === 'folder';
|
|
const where = byFolder ? 'folder_id = ?' : 'class_id = ?';
|
|
const quizzes = db.all<Record<string, any>>(
|
|
`SELECT z.id, z.title, z.description, z.folder_id, (SELECT COUNT(*) FROM questions q WHERE q.quiz_id = z.id) AS n FROM quizzes z WHERE z.${where} ORDER BY z.sort_order, z.created_at`,
|
|
share.target_id,
|
|
);
|
|
const decks = db.all<Record<string, any>>(
|
|
`SELECT d.id, d.title, d.description, d.folder_id, (SELECT COUNT(*) FROM cards c WHERE c.deck_id = d.id) AS n FROM decks d WHERE d.${where} ORDER BY d.sort_order, d.created_at`,
|
|
share.target_id,
|
|
);
|
|
const notes = db.all<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE ${where} ORDER BY sort_order, created_at`, share.target_id);
|
|
return [
|
|
...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number })),
|
|
...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number })),
|
|
...notes.map((n) => ({ kind: 'note' as const, id: n.id as string, title: n.title as string, description: '', folderId: n.folder_id as string | null, count: 0 })),
|
|
];
|
|
}
|
|
|
|
export function publicRoutes(app: AppContext): Hono {
|
|
const { db } = app;
|
|
const r = new Hono();
|
|
|
|
const load = (token: string): ShareRow => {
|
|
if (!token || token.length < 16 || token.length > 64) throw gone();
|
|
const share = db.get<ShareRow>('SELECT * FROM shares WHERE token = ?', token);
|
|
if (!share || !share.enabled) throw gone();
|
|
return share;
|
|
};
|
|
|
|
r.get('/:token', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
db.run('UPDATE shares SET view_count = view_count + 1, last_viewed_at = ? WHERE id = ?', now(), share.id);
|
|
c.header('Cache-Control', 'no-store');
|
|
c.header('X-Robots-Tag', 'noindex, nofollow');
|
|
switch (share.kind) {
|
|
case 'quiz':
|
|
return c.json(publicQuiz(app, share.target_id));
|
|
case 'deck':
|
|
return c.json(publicDeck(app, share.target_id));
|
|
case 'note':
|
|
return c.json(publicNote(app, share.target_id));
|
|
case 'document':
|
|
return c.json(publicDocument(app, share.target_id));
|
|
case 'folder': {
|
|
const folder = db.get<{ id: string; name: string; class_id: string }>('SELECT id, name, class_id FROM folders WHERE id = ?', share.target_id);
|
|
if (!folder) throw gone();
|
|
const cls = db.get<{ name: string; color: string }>('SELECT name, color FROM classes WHERE id = ?', folder.class_id);
|
|
return c.json({ kind: 'collection' as const, title: folder.name, subtitle: cls?.name ?? '', color: cls?.color ?? 'cobalt', folders: [], items: collectionItems(app, share) });
|
|
}
|
|
case 'class': {
|
|
const cls = db.get<{ id: string; name: string; code: string; description: string; color: string }>('SELECT * FROM classes WHERE id = ?', share.target_id);
|
|
if (!cls) throw gone();
|
|
const folders = db.all<{ id: string; name: string }>('SELECT id, name FROM folders WHERE class_id = ? ORDER BY sort_order, created_at', cls.id);
|
|
return c.json({ kind: 'collection' as const, title: cls.name, subtitle: cls.code, description: cls.description, color: cls.color, folders, items: collectionItems(app, share) });
|
|
}
|
|
default:
|
|
throw gone();
|
|
}
|
|
});
|
|
|
|
/** One item inside a shared class or folder. Membership is re-checked on every request. */
|
|
r.get('/:token/items/:kind/:id', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
|
const kind = c.req.param('kind');
|
|
const id = c.req.param('id');
|
|
const allowed = collectionItems(app, share).some((i) => i.kind === kind && i.id === id);
|
|
if (!allowed) throw gone();
|
|
c.header('Cache-Control', 'no-store');
|
|
c.header('X-Robots-Tag', 'noindex, nofollow');
|
|
if (kind === 'quiz') return c.json(publicQuiz(app, id));
|
|
if (kind === 'deck') return c.json(publicDeck(app, id));
|
|
return c.json(publicNote(app, id));
|
|
});
|
|
|
|
/** Download for an explicitly shared document. */
|
|
r.get('/:token/file', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
if (share.kind !== 'document') throw gone();
|
|
const doc = db.get<{ filename: string; mime: string; storage_name: string }>('SELECT filename, mime, storage_name FROM documents WHERE id = ?', share.target_id);
|
|
if (!doc) throw gone();
|
|
const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name));
|
|
if (!fs.existsSync(file)) throw gone();
|
|
const inline = doc.mime === 'application/pdf' || doc.mime.startsWith('image/');
|
|
return new Response(fs.readFileSync(file), {
|
|
headers: {
|
|
'Content-Type': doc.mime || 'application/octet-stream',
|
|
'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(doc.filename)}`,
|
|
'X-Content-Type-Options': 'nosniff',
|
|
...(inline ? {} : { 'Content-Security-Policy': "default-src 'none'; sandbox" }),
|
|
'Cache-Control': 'private, no-store',
|
|
'X-Robots-Tag': 'noindex, nofollow',
|
|
},
|
|
});
|
|
});
|
|
|
|
return r;
|
|
}
|