Start Study Desk V2: remove V1 sources, add backend foundation

V1 remains intact on main and in history. This branch replaces it with a new
application: node:sqlite storage with migrations, scrypt auth and sessions,
content/SRS/attempt/stats services, document extraction and chunking, a
provider-neutral AI layer (OpenAI, Anthropic, Gemini, OpenAI-compatible,
Ollama), the generation pipeline and the tool-using assistant.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:16:41 -07:00
parent 7bd0a9aad4
commit 3e74ecd843
268 changed files with 17740 additions and 55423 deletions

564
server/routes/library.ts Normal file
View file

@ -0,0 +1,564 @@
import fs from 'node:fs';
import path from 'node:path';
import { Hono } from 'hono';
import { z } from 'zod';
import { CLASS_COLORS, deckCreateSchema, descriptionSchema, questionToDraft, quizCreateSchema, titleSchema } from '../../shared/content.ts';
import { exportDeck, exportQuiz } from '../../shared/importer.ts';
import { badRequest, idParam, notFound, readBody, type AppContext } from '../http.ts';
import { getAppSettings } from '../settings.ts';
import { listAttempts } from '../services/attempts.ts';
import {
classInputSchema,
createClass,
createDeck,
createFolder,
createNote,
createQuiz,
duplicateDeck,
duplicateQuiz,
getClass,
getDeck,
getFolder,
getNote,
getQuiz,
insertCards,
insertQuestions,
listCards,
listQuestions,
mapClass,
mapDeck,
mapFolder,
mapNote,
mapQuiz,
resolveFolder,
updateCard,
updateQuestion,
type ClassRow,
type DeckRow,
type FolderRow,
type NoteRow,
type QuizRow,
} from '../services/content.ts';
import { deckStats, dueCounts, resetCards } from '../services/srs.ts';
import { questionStats } from '../services/stats.ts';
import { now, parseJson, slugify } from '../util.ts';
function download(c: import('hono').Context, filename: string, data: unknown) {
c.header('Content-Disposition', `attachment; filename="${filename}"`);
return c.json(data);
}
export function shareFor(app: AppContext, kind: string, targetId: string) {
const row = app.db.get<{ id: string; token: string; enabled: number; view_count: number; last_viewed_at: number | null; created_at: number }>(
'SELECT * FROM shares WHERE kind = ? AND target_id = ?',
kind,
targetId,
);
return row
? { id: row.id, token: row.token, enabled: Boolean(row.enabled), viewCount: row.view_count, lastViewedAt: row.last_viewed_at, createdAt: row.created_at }
: null;
}
export function libraryRoutes(app: AppContext): Hono {
const { db } = app;
const r = new Hono();
const settings = () => getAppSettings(db, app.config.timezone);
/* ------------------------------ classes ------------------------------ */
r.get('/classes', (c) => {
const rows = db.all<ClassRow>('SELECT * FROM classes ORDER BY archived, sort_order, created_at');
const count = (table: string) =>
new Map(db.all<{ class_id: string; n: number }>(`SELECT class_id, COUNT(*) AS n FROM ${table} GROUP BY class_id`).map((x) => [x.class_id, x.n]));
const quizzes = count('quizzes');
const decks = count('decks');
const documents = count('documents');
const notes = count('notes');
const s = settings();
return c.json({
classes: rows.map((row) => ({
...mapClass(row),
counts: { quizzes: quizzes.get(row.id) ?? 0, decks: decks.get(row.id) ?? 0, documents: documents.get(row.id) ?? 0, notes: notes.get(row.id) ?? 0 },
due: row.archived ? 0 : dueCounts(db, { classId: row.id }, s).total,
})),
});
});
r.post('/classes', async (c) => {
const body = await readBody(c, classInputSchema);
return c.json({ class: mapClass(createClass(db, body)) }, 201);
});
r.post('/classes/reorder', async (c) => {
const { ids } = await readBody(c, z.object({ ids: z.array(z.string()).max(500) }));
db.tx(() => ids.forEach((id, i) => db.run('UPDATE classes SET sort_order = ? WHERE id = ?', i, id)));
return c.json({ ok: true });
});
r.get('/classes/:id', (c) => {
const cls = getClass(db, idParam(c));
const s = settings();
const shares = new Map(
db.all<{ kind: string; target_id: string; enabled: number }>('SELECT kind, target_id, enabled FROM shares').map((x) => [`${x.kind}:${x.target_id}`, Boolean(x.enabled)]),
);
const shared = (kind: string, id: string) => shares.get(`${kind}:${id}`) ?? false;
const quizzes = db.all<QuizRow & { qn: number; attempts: number; last_score: number | null; last_max: number | null; last_at: number | null; active_id: string | null }>(
`SELECT z.*,
(SELECT COUNT(*) FROM questions q WHERE q.quiz_id = z.id) AS qn,
(SELECT COUNT(*) FROM attempts a WHERE a.quiz_id = z.id AND a.status = 'completed') AS attempts,
(SELECT a.score FROM attempts a WHERE a.quiz_id = z.id AND a.status = 'completed' AND a.kind = 'full' ORDER BY a.completed_at DESC LIMIT 1) AS last_score,
(SELECT a.max_score FROM attempts a WHERE a.quiz_id = z.id AND a.status = 'completed' AND a.kind = 'full' ORDER BY a.completed_at DESC LIMIT 1) AS last_max,
(SELECT a.completed_at FROM attempts a WHERE a.quiz_id = z.id AND a.status = 'completed' ORDER BY a.completed_at DESC LIMIT 1) AS last_at,
(SELECT a.id FROM attempts a WHERE a.quiz_id = z.id AND a.status = 'active' ORDER BY a.updated_at DESC LIMIT 1) AS active_id
FROM quizzes z WHERE z.class_id = ?`,
cls.id,
);
const decks = db.all<DeckRow & { cn: number }>(`SELECT d.*, (SELECT COUNT(*) FROM cards c WHERE c.deck_id = d.id) AS cn FROM decks d WHERE d.class_id = ?`, cls.id);
const documents = db.all<Record<string, any>>(
'SELECT id, folder_id, title, filename, kind, size, status, error, progress, page_count, token_count, needs_ocr, created_at, updated_at FROM documents WHERE class_id = ?',
cls.id,
);
const notes = db.all<NoteRow>('SELECT * FROM notes WHERE class_id = ?', cls.id);
const items = [
...quizzes.map((q) => ({
kind: 'quiz' as const,
id: q.id,
title: q.title,
description: q.description,
folderId: q.folder_id,
createdAt: q.created_at,
updatedAt: q.updated_at,
shared: shared('quiz', q.id),
questionCount: q.qn,
attempts: q.attempts,
lastPercent: q.last_max ? Math.round(((q.last_score ?? 0) / q.last_max) * 100) : null,
lastStudiedAt: q.last_at,
activeAttemptId: q.active_id,
})),
...decks.map((d) => {
const st = deckStats(db, d.id, s);
return {
kind: 'deck' as const,
id: d.id,
title: d.title,
description: d.description,
folderId: d.folder_id,
createdAt: d.created_at,
updatedAt: d.updated_at,
shared: shared('deck', d.id),
cardCount: d.cn,
dueCount: st.dueNow,
newCount: st.new,
learnedCount: st.young + st.mature,
};
}),
...documents.map((d) => ({
kind: 'document' as const,
id: d.id as string,
title: d.title as string,
description: '',
folderId: d.folder_id as string | null,
createdAt: d.created_at as number,
updatedAt: d.updated_at as number,
shared: shared('document', d.id),
docKind: d.kind as string,
filename: d.filename as string,
size: d.size as number,
status: d.status as string,
error: d.error as string,
progress: d.progress as number,
pageCount: d.page_count as number | null,
tokenCount: d.token_count as number,
needsOcr: Boolean(d.needs_ocr),
})),
...notes.map((n) => ({
kind: 'note' as const,
id: n.id,
title: n.title,
description: n.content.replace(/[#*_>`|-]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160),
folderId: n.folder_id,
createdAt: n.created_at,
updatedAt: n.updated_at,
shared: shared('note', n.id),
noteKind: n.kind,
})),
];
const folders = db.all<FolderRow>('SELECT * FROM folders WHERE class_id = ? ORDER BY sort_order, created_at', cls.id);
return c.json({
class: mapClass(cls),
folders: folders.map((f) => ({ ...mapFolder(f), shared: shared('folder', f.id) })),
items,
due: dueCounts(db, { classId: cls.id }, s),
share: shareFor(app, 'class', cls.id),
});
});
r.patch('/classes/:id', async (c) => {
const cls = getClass(db, idParam(c));
const body = await readBody(
c,
z.object({
name: z.string().trim().min(1).max(120).optional(),
code: z.string().trim().max(40).optional(),
description: z.string().max(2000).optional(),
color: z.enum(CLASS_COLORS).optional(),
archived: z.boolean().optional(),
}),
);
db.run(
'UPDATE classes SET name = ?, code = ?, description = ?, color = ?, archived = ?, updated_at = ? WHERE id = ?',
body.name ?? cls.name,
body.code ?? cls.code,
body.description ?? cls.description,
body.color ?? cls.color,
body.archived === undefined ? cls.archived : body.archived ? 1 : 0,
now(),
cls.id,
);
return c.json({ class: mapClass(getClass(db, cls.id)) });
});
r.delete('/classes/:id', (c) => {
const cls = getClass(db, idParam(c));
const files = db.all<{ storage_name: string }>('SELECT storage_name FROM documents WHERE class_id = ?', cls.id);
db.tx(() => {
db.run(
`DELETE FROM shares WHERE (kind = 'class' AND target_id = ?)
OR (kind = 'folder' AND target_id IN (SELECT id FROM folders WHERE class_id = ?))
OR (kind = 'quiz' AND target_id IN (SELECT id FROM quizzes WHERE class_id = ?))
OR (kind = 'deck' AND target_id IN (SELECT id FROM decks WHERE class_id = ?))
OR (kind = 'note' AND target_id IN (SELECT id FROM notes WHERE class_id = ?))
OR (kind = 'document' AND target_id IN (SELECT id FROM documents WHERE class_id = ?))`,
cls.id,
cls.id,
cls.id,
cls.id,
cls.id,
cls.id,
);
db.run('DELETE FROM classes WHERE id = ?', cls.id);
});
for (const f of files) fs.rmSync(path.join(app.config.uploadsDir, path.basename(f.storage_name)), { force: true });
return c.json({ ok: true });
});
/* ------------------------------ folders ------------------------------ */
r.post('/classes/:id/folders', async (c) => {
const { name } = await readBody(c, z.object({ name: z.string().trim().min(1).max(120) }));
return c.json({ folder: mapFolder(createFolder(db, idParam(c), name)) }, 201);
});
r.patch('/folders/:id', async (c) => {
const folder = getFolder(db, idParam(c));
const { name } = await readBody(c, z.object({ name: z.string().trim().min(1).max(120) }));
db.run('UPDATE folders SET name = ?, updated_at = ? WHERE id = ?', name, now(), folder.id);
return c.json({ folder: mapFolder(getFolder(db, folder.id)) });
});
r.delete('/folders/:id', (c) => {
const folder = getFolder(db, idParam(c));
db.tx(() => {
db.run(`DELETE FROM shares WHERE kind = 'folder' AND target_id = ?`, folder.id);
db.run('DELETE FROM folders WHERE id = ?', folder.id);
});
return c.json({ ok: true });
});
r.post('/classes/:id/folders/reorder', async (c) => {
const classId = idParam(c);
const { ids } = await readBody(c, z.object({ ids: z.array(z.string()).max(500) }));
db.tx(() => ids.forEach((id, i) => db.run('UPDATE folders SET sort_order = ? WHERE id = ? AND class_id = ?', i, id, classId)));
return c.json({ ok: true });
});
/* ------------------------------ move (any kind) ------------------------------ */
const TABLES = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents' } as const;
r.post('/items/move', async (c) => {
const body = await readBody(
c,
z.object({
items: z.array(z.object({ kind: z.enum(['quiz', 'deck', 'note', 'document']), id: z.string() })).min(1).max(500),
classId: z.string(),
folderId: z.string().nullish(),
}),
);
getClass(db, body.classId);
const folderId = resolveFolder(db, body.classId, body.folderId);
db.tx(() => {
for (const item of body.items) {
const table = TABLES[item.kind];
db.run(`UPDATE ${table} SET class_id = ?, folder_id = ?, updated_at = ? WHERE id = ?`, body.classId, folderId, now(), item.id);
if (item.kind === 'document') db.run('UPDATE chunks SET class_id = ? WHERE document_id = ?', body.classId, item.id);
}
});
return c.json({ ok: true });
});
/* ------------------------------ quizzes ------------------------------ */
r.post('/quizzes', async (c) => {
const body = await readBody(c, quizCreateSchema);
const quiz = createQuiz(db, body);
return c.json({ quiz: mapQuiz(quiz) }, 201);
});
r.get('/quizzes/:id', (c) => {
const quiz = getQuiz(db, idParam(c));
const cls = getClass(db, quiz.class_id);
const history = listAttempts(db, { quizId: quiz.id, status: 'completed', limit: 100 });
const active = listAttempts(db, { quizId: quiz.id, status: 'active', limit: 1 })[0] ?? null;
return c.json({
quiz: mapQuiz(quiz),
class: mapClass(cls),
questions: listQuestions(db, quiz.id),
questionStats: questionStats(db, quiz.id),
history,
activeAttempt: active,
share: shareFor(app, 'quiz', quiz.id),
});
});
const itemPatch = z.object({ title: titleSchema.optional(), description: descriptionSchema.optional(), folderId: z.string().nullish() });
r.patch('/quizzes/:id', async (c) => {
const quiz = getQuiz(db, idParam(c));
const body = await readBody(c, itemPatch);
db.run(
'UPDATE quizzes SET title = ?, description = ?, folder_id = ?, updated_at = ? WHERE id = ?',
body.title ?? quiz.title,
body.description ?? quiz.description,
body.folderId === undefined ? quiz.folder_id : resolveFolder(db, quiz.class_id, body.folderId),
now(),
quiz.id,
);
return c.json({ quiz: mapQuiz(getQuiz(db, quiz.id)) });
});
r.delete('/quizzes/:id', (c) => {
const quiz = getQuiz(db, idParam(c));
db.tx(() => {
db.run(`DELETE FROM shares WHERE kind = 'quiz' AND target_id = ?`, quiz.id);
db.run(`DELETE FROM attempts WHERE quiz_id = ? AND status = 'active'`, quiz.id);
db.run('DELETE FROM quizzes WHERE id = ?', quiz.id);
});
return c.json({ ok: true });
});
const duplicateSchema = z.object({ classId: z.string().optional(), folderId: z.string().nullish(), title: titleSchema.optional() }).optional();
r.post('/quizzes/:id/duplicate', async (c) => {
const body = await c.req.json().catch(() => ({}));
const target = duplicateSchema.parse(body) ?? {};
return c.json({ quiz: mapQuiz(duplicateQuiz(db, idParam(c), target)) }, 201);
});
r.get('/quizzes/:id/export', (c) => {
const quiz = getQuiz(db, idParam(c));
const data = exportQuiz({ title: quiz.title, description: quiz.description, questions: listQuestions(db, quiz.id).map(questionToDraft) });
return download(c, `${slugify(quiz.title)}.quiz.json`, data);
});
r.post('/quizzes/:id/questions', async (c) => {
const quiz = getQuiz(db, idParam(c));
const body = await readBody(c, z.object({ questions: z.array(z.unknown()).min(1).max(1000), index: z.number().int().min(0).optional() }));
return c.json({ questions: insertQuestions(db, quiz.id, body.questions, body.index) }, 201);
});
r.post('/quizzes/:id/questions/reorder', async (c) => {
const quiz = getQuiz(db, idParam(c));
const { ids } = await readBody(c, z.object({ ids: z.array(z.string()).max(2000) }));
db.tx(() => ids.forEach((id, i) => db.run('UPDATE questions SET sort_order = ? WHERE id = ? AND quiz_id = ?', i, id, quiz.id)));
return c.json({ ok: true });
});
r.patch('/questions/:id', async (c) => {
const body = await c.req.json().catch(() => {
throw badRequest('Request body must be JSON');
});
return c.json({ question: updateQuestion(db, idParam(c), body) });
});
r.delete('/questions/:id', (c) => {
const { changes } = db.run('DELETE FROM questions WHERE id = ?', idParam(c));
if (!changes) throw notFound('Question');
return c.json({ ok: true });
});
r.post('/questions/delete', async (c) => {
const { ids } = await readBody(c, z.object({ ids: z.array(z.string()).min(1).max(2000) }));
db.tx(() => ids.forEach((id) => db.run('DELETE FROM questions WHERE id = ?', id)));
return c.json({ ok: true });
});
/* ------------------------------ decks ------------------------------ */
r.post('/decks', async (c) => {
const body = await readBody(c, deckCreateSchema);
return c.json({ deck: mapDeck(createDeck(db, body)) }, 201);
});
r.get('/decks/:id', (c) => {
const deck = getDeck(db, idParam(c));
const session = db.get<{ state: string; updated_at: number }>('SELECT state, updated_at FROM deck_sessions WHERE deck_id = ?', deck.id);
return c.json({
deck: mapDeck(deck),
class: mapClass(getClass(db, deck.class_id)),
cards: listCards(db, deck.id),
stats: deckStats(db, deck.id, settings()),
due: dueCounts(db, { deckId: deck.id }, settings()),
session: session ? { state: parseJson<unknown>(session.state, null), updatedAt: session.updated_at } : null,
share: shareFor(app, 'deck', deck.id),
});
});
r.patch('/decks/:id', async (c) => {
const deck = getDeck(db, idParam(c));
const body = await readBody(c, itemPatch);
db.run(
'UPDATE decks SET title = ?, description = ?, folder_id = ?, updated_at = ? WHERE id = ?',
body.title ?? deck.title,
body.description ?? deck.description,
body.folderId === undefined ? deck.folder_id : resolveFolder(db, deck.class_id, body.folderId),
now(),
deck.id,
);
return c.json({ deck: mapDeck(getDeck(db, deck.id)) });
});
r.delete('/decks/:id', (c) => {
const deck = getDeck(db, idParam(c));
db.tx(() => {
db.run(`DELETE FROM shares WHERE kind = 'deck' AND target_id = ?`, deck.id);
db.run('DELETE FROM decks WHERE id = ?', deck.id);
});
return c.json({ ok: true });
});
r.post('/decks/:id/duplicate', async (c) => {
const body = await c.req.json().catch(() => ({}));
const target = duplicateSchema.parse(body) ?? {};
return c.json({ deck: mapDeck(duplicateDeck(db, idParam(c), target)) }, 201);
});
r.get('/decks/:id/export', (c) => {
const deck = getDeck(db, idParam(c));
const data = exportDeck({ title: deck.title, description: deck.description, cards: listCards(db, deck.id).map((x) => ({ front: x.front, back: x.back, hint: x.hint, tags: x.tags })) });
return download(c, `${slugify(deck.title)}.deck.json`, data);
});
r.post('/decks/:id/cards', async (c) => {
const deck = getDeck(db, idParam(c));
const body = await readBody(c, z.object({ cards: z.array(z.unknown()).min(1).max(5000) }));
return c.json({ cards: insertCards(db, deck.id, body.cards) }, 201);
});
r.post('/decks/:id/cards/reorder', async (c) => {
const deck = getDeck(db, idParam(c));
const { ids } = await readBody(c, z.object({ ids: z.array(z.string()).max(10000) }));
db.tx(() => ids.forEach((id, i) => db.run('UPDATE cards SET sort_order = ? WHERE id = ? AND deck_id = ?', i, id, deck.id)));
return c.json({ ok: true });
});
r.post('/decks/:id/reset', (c) => {
const deck = getDeck(db, idParam(c));
return c.json({ reset: resetCards(db, { deckId: deck.id }) });
});
r.put('/decks/:id/session', async (c) => {
const deck = getDeck(db, idParam(c));
const body = await readBody(c, z.object({ state: z.unknown() }));
const json = JSON.stringify(body.state ?? null);
if (json.length > 2_000_000) throw badRequest('Session state is too large');
db.run(
'INSERT INTO deck_sessions (deck_id, state, updated_at) VALUES (?, ?, ?) ON CONFLICT(deck_id) DO UPDATE SET state = excluded.state, updated_at = excluded.updated_at',
deck.id,
json,
now(),
);
return c.json({ ok: true });
});
r.delete('/decks/:id/session', (c) => {
db.run('DELETE FROM deck_sessions WHERE deck_id = ?', idParam(c));
return c.json({ ok: true });
});
r.patch('/cards/:id', async (c) => {
const id = idParam(c);
const body = (await c.req.json().catch(() => {
throw badRequest('Request body must be JSON');
})) as Record<string, unknown>;
if (typeof body.suspended === 'boolean') {
const { changes } = db.run('UPDATE cards SET suspended = ?, updated_at = ? WHERE id = ?', body.suspended ? 1 : 0, now(), id);
if (!changes) throw notFound('Card');
}
if (body.reset === true) resetCards(db, { cardId: id });
if (body.front !== undefined || body.back !== undefined) return c.json({ card: updateCard(db, id, body) });
const row = db.get<{ deck_id: string }>('SELECT deck_id FROM cards WHERE id = ?', id);
if (!row) throw notFound('Card');
return c.json({ card: listCards(db, row.deck_id).find((x) => x.id === id) });
});
r.delete('/cards/:id', (c) => {
const { changes } = db.run('DELETE FROM cards WHERE id = ?', idParam(c));
if (!changes) throw notFound('Card');
return c.json({ ok: true });
});
r.post('/cards/delete', async (c) => {
const { ids } = await readBody(c, z.object({ ids: z.array(z.string()).min(1).max(10000) }));
db.tx(() => ids.forEach((id) => db.run('DELETE FROM cards WHERE id = ?', id)));
return c.json({ ok: true });
});
/* ------------------------------ notes ------------------------------ */
r.post('/notes', async (c) => {
const body = await readBody(
c,
z.object({
classId: z.string(),
folderId: z.string().nullish(),
title: titleSchema,
content: z.string().max(400000).optional().default(''),
kind: z.enum(['note', 'guide', 'summary']).optional().default('note'),
}),
);
return c.json({ note: mapNote(createNote(db, body)) }, 201);
});
r.get('/notes/:id', (c) => {
const note = getNote(db, idParam(c));
return c.json({ note: mapNote(note), class: mapClass(getClass(db, note.class_id)), share: shareFor(app, 'note', note.id) });
});
r.patch('/notes/:id', async (c) => {
const note = getNote(db, idParam(c));
const body = await readBody(c, z.object({ title: titleSchema.optional(), content: z.string().max(400000).optional(), folderId: z.string().nullish() }));
db.run(
'UPDATE notes SET title = ?, content = ?, folder_id = ?, updated_at = ? WHERE id = ?',
body.title ?? note.title,
body.content ?? note.content,
body.folderId === undefined ? note.folder_id : resolveFolder(db, note.class_id, body.folderId),
now(),
note.id,
);
return c.json({ note: mapNote(getNote(db, note.id)) });
});
r.delete('/notes/:id', (c) => {
const note = getNote(db, idParam(c));
db.tx(() => {
db.run(`DELETE FROM shares WHERE kind = 'note' AND target_id = ?`, note.id);
db.run('DELETE FROM notes WHERE id = ?', note.id);
});
return c.json({ ok: true });
});
return r;
}

260
server/routes/shares.ts Normal file
View file

@ -0,0 +1,260 @@
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',
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
'Cache-Control': 'private, no-store',
'X-Robots-Tag': 'noindex, nofollow',
},
});
});
return r;
}

201
server/routes/study.ts Normal file
View file

@ -0,0 +1,201 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { badRequest, idParam, readBody, type AppContext } from '../http.ts';
import { getAppSettings } from '../settings.ts';
import {
attemptCreateSchema,
attemptPatchSchema,
completeAttempt,
createAttempt,
deleteAttempt,
getAttempt,
listAttempts,
missedQuestionIds,
patchAttempt,
} from '../services/attempts.ts';
import { answerCard, buildQueue, dueCounts, forecast, logCram, undoReview, type RatingValue } from '../services/srs.ts';
import { accuracyTrend, activityByDay, computeStreak, topicStats, totals, weakTopics } from '../services/stats.ts';
import { ftsQuery } from '../util.ts';
export function studyRoutes(app: AppContext): Hono {
const { db } = app;
const r = new Hono();
const settings = () => getAppSettings(db, app.config.timezone);
/* ------------------------------ quiz sessions ------------------------------ */
r.post('/attempts', async (c) => {
const body = await readBody(c, attemptCreateSchema);
const id = createAttempt(db, body, settings().sataScoring);
return c.json({ attempt: getAttempt(db, id) }, 201);
});
r.get('/attempts', (c) => {
const status = c.req.query('status');
return c.json({
attempts: listAttempts(db, {
status: status === 'active' || status === 'completed' ? status : undefined,
quizId: c.req.query('quizId') || undefined,
classId: c.req.query('classId') || undefined,
limit: Number(c.req.query('limit') ?? 50) || 50,
}),
});
});
r.get('/attempts/:id', (c) => c.json({ attempt: getAttempt(db, idParam(c)) }));
r.patch('/attempts/:id', async (c) => {
const body = await readBody(c, attemptPatchSchema);
return c.json({ attempt: patchAttempt(db, idParam(c), body) });
});
r.post('/attempts/:id/complete', async (c) => {
const body = (await c.req.json().catch(() => ({}))) as { elapsedSec?: unknown };
const elapsed = typeof body.elapsedSec === 'number' && Number.isFinite(body.elapsedSec) ? Math.max(0, Math.round(body.elapsedSec)) : undefined;
return c.json({ attempt: completeAttempt(db, idParam(c), elapsed) });
});
r.delete('/attempts/:id', (c) => {
deleteAttempt(db, idParam(c));
return c.json({ ok: true });
});
/* ------------------------------ spaced repetition ------------------------------ */
r.get('/review/queue', (c) => {
const scope = { deckId: c.req.query('deckId') || undefined, classId: c.req.query('classId') || undefined };
const limit = Math.min(Number(c.req.query('limit') ?? 100) || 100, 300);
return c.json(buildQueue(db, scope, settings(), limit));
});
r.post('/review/answer', async (c) => {
const body = await readBody(c, z.object({ cardId: z.string(), rating: z.number().int().min(1).max(4) }));
return c.json({ result: answerCard(db, body.cardId, body.rating as RatingValue, settings()) });
});
r.post('/review/undo', async (c) => {
const body = await readBody(c, z.object({ cardId: z.string() }));
return c.json({ result: undoReview(db, body.cardId, settings()) });
});
r.post('/review/cram', async (c) => {
const body = await readBody(c, z.object({ cardId: z.string(), known: z.boolean() }));
logCram(db, body.cardId, body.known);
return c.json({ ok: true });
});
/* ------------------------------ dashboards ------------------------------ */
r.get('/overview', (c) => {
const s = settings();
const days = activityByDay(db, s, 26 * 7);
return c.json({
settings: s,
due: dueCounts(db, {}, s),
streak: computeStreak(days, s.dailyGoal),
activity: days,
activeAttempts: listAttempts(db, { status: 'active', limit: 6 }),
recentAttempts: listAttempts(db, { status: 'completed', limit: 6 }),
weakTopics: weakTopics(db, {}, 6),
missedCount: missedQuestionIds(db, {}, 500).length,
totals: totals(db, s, {}, 7),
forecast: forecast(db, {}, s, 7),
});
});
r.get('/insights', (c) => {
const s = settings();
const classId = c.req.query('classId') || undefined;
const range = Math.min(Math.max(Number(c.req.query('days') ?? 30) || 30, 7), 365);
const scope = { classId };
const days = activityByDay(db, s, 53 * 7, scope);
return c.json({
range,
totals: totals(db, s, scope, range),
streak: computeStreak(activityByDay(db, s, 53 * 7), s.dailyGoal),
activity: days,
accuracy: accuracyTrend(db, s, range, scope),
topics: topicStats(db, scope, range),
forecast: forecast(db, scope, s, 14),
due: dueCounts(db, scope, s),
missedCount: missedQuestionIds(db, scope, 500).length,
recentAttempts: listAttempts(db, { status: 'completed', classId, limit: 15 }),
});
});
/* ------------------------------ search ------------------------------ */
r.get('/search', (c) => {
const q = (c.req.query('q') ?? '').trim().slice(0, 120);
if (q.length < 2) return c.json({ query: q, results: [] });
const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`;
const classId = c.req.query('classId') || null;
const scoped = (col: string) => (classId ? `AND ${col} = ?` : '');
const p = (...base: string[]) => (classId ? [...base, classId] : base);
type Hit = { kind: string; id: string; title: string; snippet: string; classId: string; className: string; classColor: string; parentId?: string; page?: number | null };
const results: Hit[] = [];
for (const row of db.all<Record<string, string>>(`SELECT id, name, color FROM classes WHERE name LIKE ? ESCAPE '\\' OR code LIKE ? ESCAPE '\\' LIMIT 5`, like, like)) {
results.push({ kind: 'class', id: row.id, title: row.name, snippet: '', classId: row.id, className: row.name, classColor: row.color });
}
const simple = (kind: string, table: string) => {
for (const row of db.all<Record<string, string>>(
`SELECT t.id, t.title, k.id AS class_id, k.name AS class_name, k.color AS class_color FROM ${table} t JOIN classes k ON k.id = t.class_id
WHERE t.title LIKE ? ESCAPE '\\' ${scoped('t.class_id')} ORDER BY t.updated_at DESC LIMIT 8`,
...p(like),
)) {
results.push({ kind, id: row.id, title: row.title, snippet: '', classId: row.class_id, className: row.class_name, classColor: row.class_color });
}
};
simple('quiz', 'quizzes');
simple('deck', 'decks');
simple('note', 'notes');
simple('document', 'documents');
for (const row of db.all<Record<string, string>>(
`SELECT q.id, q.stem, z.id AS quiz_id, z.title AS quiz_title, k.id AS class_id, k.name AS class_name, k.color AS class_color
FROM questions q JOIN quizzes z ON z.id = q.quiz_id JOIN classes k ON k.id = z.class_id
WHERE (q.stem LIKE ? ESCAPE '\\' OR q.topic LIKE ? ESCAPE '\\') ${scoped('z.class_id')} LIMIT 10`,
...p(like, like),
)) {
results.push({ kind: 'question', id: row.id, parentId: row.quiz_id, title: row.stem.slice(0, 140), snippet: row.quiz_title, classId: row.class_id, className: row.class_name, classColor: row.class_color });
}
for (const row of db.all<Record<string, string>>(
`SELECT c.id, c.front, c.back, d.id AS deck_id, d.title AS deck_title, k.id AS class_id, k.name AS class_name, k.color AS class_color
FROM cards c JOIN decks d ON d.id = c.deck_id JOIN classes k ON k.id = d.class_id
WHERE (c.front LIKE ? ESCAPE '\\' OR c.back LIKE ? ESCAPE '\\') ${scoped('d.class_id')} LIMIT 10`,
...p(like, like),
)) {
results.push({ kind: 'card', id: row.id, parentId: row.deck_id, title: row.front.slice(0, 140), snippet: row.deck_title, classId: row.class_id, className: row.class_name, classColor: row.class_color });
}
const match = ftsQuery(q, 'and');
if (match) {
try {
for (const row of db.all<Record<string, any>>(
`SELECT ch.id, ch.page_start, d.id AS doc_id, d.title AS doc_title, k.id AS class_id, k.name AS class_name, k.color AS class_color,
snippet(chunks_fts, 0, '', '', ' … ', 18) AS snip
FROM chunks_fts JOIN chunks ch ON ch.id = chunks_fts.rowid JOIN documents d ON d.id = ch.document_id JOIN classes k ON k.id = d.class_id
WHERE chunks_fts MATCH ? ${scoped('d.class_id')} ORDER BY bm25(chunks_fts) LIMIT 10`,
...p(match),
)) {
results.push({ kind: 'passage', id: String(row.id), parentId: row.doc_id, page: row.page_start, title: row.doc_title, snippet: row.snip, classId: row.class_id, className: row.class_name, classColor: row.class_color });
}
} catch {
/* a malformed FTS query should never break search */
}
}
return c.json({ query: q, results });
});
r.get('/topics', (c) => {
const classId = c.req.query('classId');
if (!classId) throw badRequest('classId is required');
const rows = db.all<{ topic: string; n: number }>(
`SELECT q.topic AS topic, COUNT(*) AS n FROM questions q JOIN quizzes z ON z.id = q.quiz_id WHERE z.class_id = ? AND q.topic != '' GROUP BY q.topic ORDER BY n DESC`,
classId,
);
return c.json({ topics: rows });
});
return r;
}