Study/server/routes/library.ts
Elijah 3e74ecd843 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>
2026-11-11 08:16:41 -07:00

564 lines
22 KiB
TypeScript

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;
}