-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
676 lines (585 loc) · 28.8 KB
/
Copy pathserver.js
File metadata and controls
676 lines (585 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
const express = require('express');
const Database = require('better-sqlite3');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const path = require('path');
const crypto = require('crypto');
const os = require('os');
const fs = require('fs');
const AdmZip = require('adm-zip');
const { computeSM2, addDays, todayUTC, nextRecurDate, toResponse, sanitizeCards } = require('./public/shared-utils');
const app = express();
const dbPath = process.env.DB_PATH || path.join(__dirname, 'recall.db');
const db = new Database(dbPath);
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'recall-dev-secret-please-change-in-production';
const JWT_EXPIRES = '7d';
const SALT_ROUNDS = 12;
// ── Schema ────────────────────────────────────────────────────────────────────
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL DEFAULT '',
topic TEXT NOT NULL,
studied_date TEXT NOT NULL,
notes TEXT DEFAULT '',
subject TEXT DEFAULT '',
reviews TEXT NOT NULL
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS links (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
from_id TEXT NOT NULL,
to_id TEXT NOT NULL,
relation TEXT NOT NULL DEFAULT 'related'
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS decks (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
session_id TEXT NOT NULL,
name TEXT NOT NULL,
cards TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS attachments (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
session_id TEXT NOT NULL,
file_id TEXT NOT NULL,
filename TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL,
created_at TEXT NOT NULL
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
title TEXT NOT NULL,
category TEXT DEFAULT '',
time_of_day TEXT DEFAULT '',
due_date TEXT DEFAULT NULL,
priority TEXT NOT NULL DEFAULT 'none',
notes TEXT DEFAULT '',
session_id TEXT DEFAULT NULL,
done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
)
`);
// Migrations
try { db.exec(`ALTER TABLE sessions ADD COLUMN subject TEXT DEFAULT ''`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN user_id TEXT NOT NULL DEFAULT ''`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN ease_factor REAL DEFAULT 2.5`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN review_streak INTEGER DEFAULT 0`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN recurrence_rule TEXT DEFAULT NULL`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN recurrence_id TEXT DEFAULT NULL`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN tags TEXT DEFAULT '[]'`); } catch {}
// ── Middleware ────────────────────────────────────────────────────────────────
app.use(express.json({ limit: '25mb' }));
// index.html must never be served from browser or proxy cache — always fresh
app.get(['/', '/index.html'], (req, res) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Serve auth page at root if no token — the SPA handles this on the client side;
// we still serve all static files normally.
app.use(express.static(path.join(__dirname, 'public')));
function requireAuth(req, res, next) {
const header = req.headers['authorization'];
if (!header || !header.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
try {
req.user = jwt.verify(header.slice(7), JWT_SECRET);
next();
} catch {
return res.status(401).json({ error: 'Invalid or expired token' });
}
}
// ── Attachment helpers ────────────────────────────────────────────────────────
const UPLOADS_DIR = process.env.UPLOADS_DIR || path.join(__dirname, 'uploads');
const ATT_TYPES = { '.pdf': 'application/pdf', '.html': 'text/html', '.htm': 'text/html' };
// Map of session_id → [{id, filename, mime, size}] for one user
function attachmentsBySession(userId) {
const rows = db.prepare(
'SELECT id, session_id, filename, mime, size FROM attachments WHERE user_id = ?'
).all(userId);
const map = {};
rows.forEach(a => {
(map[a.session_id] = map[a.session_id] || []).push(
{ id: a.id, filename: a.filename, mime: a.mime, size: a.size }
);
});
return map;
}
// Delete the disk file once no attachment row references it anymore
function removeFileIfOrphaned(userId, fileId) {
const still = db.prepare('SELECT 1 FROM attachments WHERE file_id = ? LIMIT 1').get(fileId);
if (!still) {
try { fs.unlinkSync(path.join(UPLOADS_DIR, userId, fileId)); } catch {}
}
}
// ── Recurrence helpers ────────────────────────────────────────────────────────
// Build a reviews array from a studied date using the user's custom intervals
function buildReviewsForDate(studiedDate, userId) {
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(`${userId}:intervals`);
const ivs = row ? JSON.parse(row.value) : [1, 3, 7, 14, 30];
return ivs.map(days => ({ date: addDays(studiedDate, days), done: false }));
}
// Auto-create any due recurring sessions; returns count of newly created rows
function createRecurrences(userId) {
const today = todayUTC();
const recurring = db.prepare(
`SELECT * FROM sessions WHERE user_id = ? AND recurrence_id IS NOT NULL ORDER BY studied_date ASC`
).all(userId);
if (!recurring.length) return 0;
// Find the latest session per recurrence series
const latestBySeries = {};
recurring.forEach(s => {
const rid = s.recurrence_id;
if (!latestBySeries[rid] || s.studied_date > latestBySeries[rid].studied_date) {
latestBySeries[rid] = s;
}
});
const insert = db.prepare(
`INSERT INTO sessions
(id, user_id, topic, subject, notes, studied_date, reviews, ease_factor, review_streak, recurrence_rule, recurrence_id)
VALUES (?, ?, ?, ?, ?, ?, ?, 2.5, 0, ?, ?)`
);
let created = 0;
const MAX_PER_SERIES = 14; // safety: at most 14 catch-up instances per load
for (const s of Object.values(latestBySeries)) {
let nextDate = nextRecurDate(s.studied_date, s.recurrence_rule);
let count = 0;
while (nextDate && nextDate <= today && count < MAX_PER_SERIES) {
const exists = db.prepare(
`SELECT id FROM sessions WHERE recurrence_id = ? AND studied_date = ? AND user_id = ?`
).get(s.recurrence_id, nextDate, userId);
if (!exists) {
const reviews = buildReviewsForDate(nextDate, userId);
const newId = crypto.randomUUID();
insert.run(
newId, userId,
s.topic, s.subject || '', s.notes || '',
nextDate, JSON.stringify(reviews),
s.recurrence_rule, s.recurrence_id
);
// Carry attachments over — new metadata rows sharing the same file on disk
const atts = db.prepare(
'SELECT * FROM attachments WHERE session_id = ? AND user_id = ?'
).all(s.id, userId);
const insertAtt = db.prepare(
`INSERT INTO attachments (id, user_id, session_id, file_id, filename, mime, size, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
);
atts.forEach(a => insertAtt.run(
crypto.randomUUID(), userId, newId, a.file_id, a.filename, a.mime, a.size,
new Date().toISOString()
));
created++;
}
nextDate = nextRecurDate(nextDate, s.recurrence_rule);
count++;
}
}
return created;
}
// ── Auth routes ───────────────────────────────────────────────────────────────
// POST /api/auth/register
app.post('/api/auth/register', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
if (password.length < 8) {
return res.status(400).json({ error: 'Password must be at least 8 characters' });
}
const exists = db.prepare('SELECT id FROM users WHERE email = ?').get(email.toLowerCase().trim());
if (exists) {
return res.status(409).json({ error: 'An account with that email already exists' });
}
const id = crypto.randomUUID();
const hash = await bcrypt.hash(password, SALT_ROUNDS);
db.prepare('INSERT INTO users (id, email, password_hash, created_at) VALUES (?, ?, ?, ?)')
.run(id, email.toLowerCase().trim(), hash, new Date().toISOString());
const token = jwt.sign({ id, email: email.toLowerCase().trim() }, JWT_SECRET, { expiresIn: JWT_EXPIRES });
res.json({ token, user: { id, email: email.toLowerCase().trim() } });
});
// POST /api/auth/login
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
const user = db.prepare('SELECT * FROM users WHERE email = ?').get(email.toLowerCase().trim());
if (!user) {
return res.status(401).json({ error: 'Invalid email or password' });
}
const match = await bcrypt.compare(password, user.password_hash);
if (!match) {
return res.status(401).json({ error: 'Invalid email or password' });
}
const token = jwt.sign({ id: user.id, email: user.email }, JWT_SECRET, { expiresIn: JWT_EXPIRES });
res.json({ token, user: { id: user.id, email: user.email } });
});
// GET /api/auth/me — verify token and return user info
app.get('/api/auth/me', requireAuth, (req, res) => {
const user = db.prepare('SELECT id, email, created_at FROM users WHERE id = ?').get(req.user.id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json({ user });
});
// ── Settings (per-user) ───────────────────────────────────────────────────────
app.get('/api/settings', requireAuth, (req, res) => {
const key = `${req.user.id}:intervals`;
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key);
res.json({ intervals: row ? JSON.parse(row.value) : [1, 3, 7, 14, 30] });
});
app.put('/api/settings', requireAuth, (req, res) => {
const { intervals } = req.body;
if (!Array.isArray(intervals) || intervals.length < 1 ||
intervals.some(n => !Number.isInteger(n) || n < 1)) {
return res.status(400).json({ error: 'intervals must be an array of positive integers' });
}
const key = `${req.user.id}:intervals`;
db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)')
.run(key, JSON.stringify(intervals));
res.json({ ok: true });
});
// ── Study Sessions (per-user) ─────────────────────────────────────────────────
app.get('/api/sessions', requireAuth, (req, res) => {
// Auto-create any due recurring sessions before returning
const newRecurrences = createRecurrences(req.user.id);
const rows = db.prepare(
'SELECT * FROM sessions WHERE user_id = ? ORDER BY studied_date DESC'
).all(req.user.id);
const attMap = attachmentsBySession(req.user.id);
res.json({
sessions: rows.map(r => toResponse({
...r,
tags: r.tags ? JSON.parse(r.tags) : [],
reviews: JSON.parse(r.reviews),
recurrence_rule: r.recurrence_rule ? JSON.parse(r.recurrence_rule) : null,
attachments: attMap[r.id] || [],
})),
newRecurrences
});
});
app.post('/api/sessions', requireAuth, (req, res) => {
const { id, topic, studiedDate, notes, subject, tags, reviews, recurrenceRule, recurrenceId } = req.body;
if (!id || !topic || !studiedDate || !Array.isArray(reviews)) {
return res.status(400).json({ error: 'Missing required fields' });
}
const tagsJson = Array.isArray(tags) ? JSON.stringify(tags.map(t => String(t).trim()).filter(Boolean)) : '[]';
db.prepare(
`INSERT INTO sessions (id, user_id, topic, studied_date, notes, subject, tags, reviews, recurrence_rule, recurrence_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).run(
id, req.user.id, topic, studiedDate, notes || '', subject || '', tagsJson, JSON.stringify(reviews),
recurrenceRule ? JSON.stringify(recurrenceRule) : null,
recurrenceRule ? (recurrenceId || crypto.randomUUID()) : null
);
res.json({ ok: true });
});
app.patch('/api/sessions/:id/reviews/:index', requireAuth, (req, res) => {
const session = db.prepare('SELECT * FROM sessions WHERE id = ? AND user_id = ?')
.get(req.params.id, req.user.id);
if (!session) return res.status(404).json({ error: 'Session not found' });
const reviews = JSON.parse(session.reviews);
const idx = parseInt(req.params.index, 10);
if (idx < 0 || idx >= reviews.length) return res.status(400).json({ error: 'Invalid index' });
// ── Drag-to-reschedule: just update the date, skip SM-2 ──
if (req.body?.newDate) {
const nd = req.body.newDate;
if (!/^\d{4}-\d{2}-\d{2}$/.test(nd)) return res.status(400).json({ error: 'Invalid date format' });
reviews[idx].date = nd;
db.prepare('UPDATE sessions SET reviews = ? WHERE id = ? AND user_id = ?')
.run(JSON.stringify(reviews), req.params.id, req.user.id);
return res.json({ ok: true, reviews });
}
const done = req.body?.done !== undefined ? Boolean(req.body.done) : true;
const confidence = req.body?.confidence ? parseInt(req.body.confidence, 10) : null;
const rescheduleFromToday = Boolean(req.body?.rescheduleFromToday);
reviews[idx].done = done;
if (done && confidence) reviews[idx].confidence = confidence;
else if (!done) delete reviews[idx].confidence;
let easeFactor = parseFloat(session.ease_factor) || 2.5;
let reviewStreak = parseInt(session.review_streak, 10) || 0;
if (done && idx + 1 < reviews.length) {
if (confidence) {
// SM-2: use scheduled interval (original due dates) as the rep interval
const prevDate = idx === 0 ? session.studied_date : reviews[idx - 1].date;
const [py,pm,pd] = prevDate.split('-').map(Number);
const [ty,tm,td] = reviews[idx].date.split('-').map(Number);
const intervalDays = Math.max(1, Math.round(
(Date.UTC(ty, tm-1, td) - Date.UTC(py, pm-1, pd)) / 86400000
));
const sm2 = computeSM2(confidence, easeFactor, intervalDays);
easeFactor = sm2.easeFactor;
reviewStreak = sm2.pass ? reviewStreak + 1 : 0;
// Anchor next review to today (if late/opted-in) or to scheduled due date
const base = rescheduleFromToday ? todayUTC() : reviews[idx].date;
reviews[idx + 1].date = addDays(base, sm2.nextInterval);
reviews[idx + 1].done = false;
delete reviews[idx + 1].confidence;
} else if (rescheduleFromToday) {
// Skipped rating but wants late recovery — preserve original gap, shift base to today
const [ay,am,ad] = reviews[idx].date.split('-').map(Number);
const [by,bm,bd] = reviews[idx + 1].date.split('-').map(Number);
const originalGap = Math.max(1, Math.round(
(Date.UTC(by, bm-1, bd) - Date.UTC(ay, am-1, ad)) / 86400000
));
reviews[idx + 1].date = addDays(todayUTC(), originalGap);
}
} else if (!done) {
// Undo: roll streak back one step (floor at 0)
reviewStreak = Math.max(0, reviewStreak - 1);
}
db.prepare('UPDATE sessions SET reviews = ?, ease_factor = ?, review_streak = ? WHERE id = ? AND user_id = ?')
.run(JSON.stringify(reviews), easeFactor, reviewStreak, req.params.id, req.user.id);
res.json({ ok: true, reviews, easeFactor, reviewStreak });
});
app.put('/api/sessions/:id', requireAuth, (req, res) => {
const { topic, subject, notes, tags } = req.body;
if (!topic) return res.status(400).json({ error: 'topic required' });
const tagsJson = Array.isArray(tags) ? JSON.stringify(tags.map(t => String(t).trim()).filter(Boolean)) : '[]';
const result = db.prepare(
'UPDATE sessions SET topic = ?, subject = ?, notes = ?, tags = ? WHERE id = ? AND user_id = ?'
).run(topic, subject || '', notes || '', tagsJson, req.params.id, req.user.id);
if (result.changes === 0) return res.status(404).json({ error: 'Not found' });
res.json({ ok: true });
});
app.delete('/api/sessions/:id', requireAuth, (req, res) => {
db.prepare('DELETE FROM sessions WHERE id = ? AND user_id = ?')
.run(req.params.id, req.user.id);
// Also remove any links referencing this session
db.prepare('DELETE FROM links WHERE user_id = ? AND (from_id = ? OR to_id = ?)')
.run(req.user.id, req.params.id, req.params.id);
// And its attachments (+ files nothing else references)
const atts = db.prepare('SELECT * FROM attachments WHERE session_id = ? AND user_id = ?')
.all(req.params.id, req.user.id);
db.prepare('DELETE FROM attachments WHERE session_id = ? AND user_id = ?')
.run(req.params.id, req.user.id);
atts.forEach(a => removeFileIfOrphaned(req.user.id, a.file_id));
res.json({ ok: true });
});
// ── Attachments ───────────────────────────────────────────────────────────────
// POST /api/sessions/:id/attachments?filename=… — raw file bytes
app.post('/api/sessions/:id/attachments', requireAuth,
express.raw({ type: '*/*', limit: '25mb' }),
(req, res) => {
const session = db.prepare('SELECT id FROM sessions WHERE id = ? AND user_id = ?')
.get(req.params.id, req.user.id);
if (!session) return res.status(404).json({ error: 'Session not found' });
if (!req.body || !req.body.length) return res.status(400).json({ error: 'No file data received' });
const filename = String(req.query.filename || 'file').slice(0, 200);
const mime = ATT_TYPES[path.extname(filename).toLowerCase()];
if (!mime) return res.status(400).json({ error: 'Only .pdf and .html files are supported' });
const fileId = crypto.randomUUID();
const dir = path.join(UPLOADS_DIR, req.user.id);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, fileId), req.body);
const id = crypto.randomUUID();
db.prepare(
`INSERT INTO attachments (id, user_id, session_id, file_id, filename, mime, size, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
).run(id, req.user.id, req.params.id, fileId, filename, mime, req.body.length,
new Date().toISOString());
res.json({ attachment: { id, filename, mime, size: req.body.length } });
}
);
app.get('/api/attachments/:id', requireAuth, (req, res) => {
const att = db.prepare('SELECT * FROM attachments WHERE id = ? AND user_id = ?')
.get(req.params.id, req.user.id);
if (!att) return res.status(404).json({ error: 'Not found' });
const file = path.join(UPLOADS_DIR, req.user.id, att.file_id);
if (!fs.existsSync(file)) return res.status(404).json({ error: 'File missing on disk' });
res.setHeader('Content-Type', att.mime);
res.setHeader('X-Content-Type-Options', 'nosniff');
// uploaded HTML must never execute with access to our origin
res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'");
res.setHeader('Content-Disposition', `inline; filename="${att.filename.replace(/["\r\n]/g, '')}"`);
res.sendFile(file);
});
app.delete('/api/attachments/:id', requireAuth, (req, res) => {
const att = db.prepare('SELECT * FROM attachments WHERE id = ? AND user_id = ?')
.get(req.params.id, req.user.id);
if (!att) return res.status(404).json({ error: 'Not found' });
db.prepare('DELETE FROM attachments WHERE id = ?').run(att.id);
removeFileIfOrphaned(req.user.id, att.file_id);
res.json({ ok: true });
});
// ── Links ─────────────────────────────────────────────────────────────────────
app.get('/api/links', requireAuth, (req, res) => {
const rows = db.prepare('SELECT * FROM links WHERE user_id = ?').all(req.user.id);
res.json({ links: rows });
});
app.post('/api/links', requireAuth, (req, res) => {
const { fromId, toId, relation } = req.body;
if (!fromId || !toId || fromId === toId) {
return res.status(400).json({ error: 'Invalid link: fromId and toId required and must differ' });
}
const valid = ['related', 'builds-on', 'prerequisite', 'see-also'];
const rel = valid.includes(relation) ? relation : 'related';
// Prevent duplicate links in either direction
const exists = db.prepare(
`SELECT id FROM links WHERE user_id = ? AND
((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))`
).get(req.user.id, fromId, toId, toId, fromId);
if (exists) return res.status(409).json({ error: 'A link between these sessions already exists' });
const id = crypto.randomUUID();
db.prepare('INSERT INTO links (id, user_id, from_id, to_id, relation) VALUES (?, ?, ?, ?, ?)')
.run(id, req.user.id, fromId, toId, rel);
res.json({ ok: true, id });
});
app.delete('/api/links/:id', requireAuth, (req, res) => {
db.prepare('DELETE FROM links WHERE id = ? AND user_id = ?')
.run(req.params.id, req.user.id);
res.json({ ok: true });
});
// ── Anki HTML stripper ───────────────────────────────────────────────────────
function stripAnkiHtml(html) {
return html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.trim();
}
// ── Flashcard Decks ───────────────────────────────────────────────────────────
app.get('/api/decks', requireAuth, (req, res) => {
const rows = db.prepare('SELECT * FROM decks WHERE user_id = ?').all(req.user.id);
res.json({ decks: rows.map(r => ({ ...r, cards: JSON.parse(r.cards) })) });
});
app.post('/api/decks', requireAuth, (req, res) => {
const { id, sessionId, name, cards } = req.body;
if (!id || !sessionId || !name || !Array.isArray(cards)) {
return res.status(400).json({ error: 'Missing required fields' });
}
const sanitized = sanitizeCards(cards, () => crypto.randomUUID());
db.prepare('INSERT INTO decks (id, user_id, session_id, name, cards, created_at) VALUES (?, ?, ?, ?, ?, ?)')
.run(id, req.user.id, sessionId, name, JSON.stringify(sanitized), new Date().toISOString());
res.json({ ok: true });
});
app.put('/api/decks/:id', requireAuth, (req, res) => {
const { name, cards } = req.body;
if (!name || !Array.isArray(cards)) return res.status(400).json({ error: 'name and cards required' });
const sanitized = sanitizeCards(cards, () => crypto.randomUUID());
const result = db.prepare('UPDATE decks SET name = ?, cards = ? WHERE id = ? AND user_id = ?')
.run(name, JSON.stringify(sanitized), req.params.id, req.user.id);
if (result.changes === 0) return res.status(404).json({ error: 'Not found' });
res.json({ ok: true });
});
app.delete('/api/decks/:id', requireAuth, (req, res) => {
db.prepare('DELETE FROM decks WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
res.json({ ok: true });
});
// POST /api/decks/parse-apkg — receive raw .apkg bytes, return parsed cards
app.post('/api/decks/parse-apkg', requireAuth,
express.raw({ type: '*/*', limit: '100mb' }),
(req, res) => {
if (!req.body || !req.body.length) {
return res.status(400).json({ error: 'No file data received' });
}
const tmpPath = path.join(os.tmpdir(), `recall-anki-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
try {
const zip = new AdmZip(req.body);
const entry = zip.getEntry('collection.anki21') || zip.getEntry('collection.anki2');
if (!entry) return res.status(400).json({ error: 'Not a valid .apkg file — no collection database found' });
fs.writeFileSync(tmpPath, entry.getData());
const ankiDb = new Database(tmpPath, { readonly: true, fileMustExist: true });
const notes = ankiDb.prepare('SELECT flds FROM notes').all();
ankiDb.close();
const SEP = '\x1f';
const cards = notes
.map(n => {
const fields = n.flds.split(SEP);
return { front: stripAnkiHtml(fields[0] || ''), back: stripAnkiHtml(fields[1] || '') };
})
.filter(c => c.front || c.back);
res.json({ cards });
} catch (err) {
res.status(400).json({ error: 'Failed to parse .apkg: ' + (err.message || 'unknown error') });
} finally {
try { fs.unlinkSync(tmpPath); } catch {}
}
}
);
// ── Tasks ─────────────────────────────────────────────────────────────────────
const TASK_TOD = ['', 'morning', 'afternoon', 'evening'];
const TASK_PRIO = ['none', 'low', 'medium', 'high'];
app.get('/api/tasks', requireAuth, (req, res) => {
const rows = db.prepare('SELECT * FROM tasks WHERE user_id = ? ORDER BY created_at DESC').all(req.user.id);
res.json({ tasks: rows.map(r => ({ ...r, done: !!r.done })) });
});
app.post('/api/tasks', requireAuth, (req, res) => {
const { title, category, timeOfDay, dueDate, priority, notes, sessionId } = req.body;
if (!title) return res.status(400).json({ error: 'title required' });
const id = crypto.randomUUID();
db.prepare(
`INSERT INTO tasks (id, user_id, title, category, time_of_day, due_date, priority, notes, session_id, done, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`
).run(
id, req.user.id, title,
category || '',
TASK_TOD.includes(timeOfDay) ? timeOfDay : '',
dueDate || null,
TASK_PRIO.includes(priority) ? priority : 'none',
notes || '',
sessionId || null,
new Date().toISOString()
);
res.json({ ok: true, id });
});
app.put('/api/tasks/:id', requireAuth, (req, res) => {
const task = db.prepare('SELECT * FROM tasks WHERE id = ? AND user_id = ?').get(req.params.id, req.user.id);
if (!task) return res.status(404).json({ error: 'Not found' });
const title = req.body.title !== undefined ? req.body.title : task.title;
if (!title) return res.status(400).json({ error: 'title required' });
const category = req.body.category !== undefined ? (req.body.category || '') : task.category;
const timeOfDay = req.body.timeOfDay !== undefined ? (TASK_TOD.includes(req.body.timeOfDay) ? req.body.timeOfDay : '') : task.time_of_day;
const dueDate = req.body.dueDate !== undefined ? (req.body.dueDate || null) : task.due_date;
const priority = req.body.priority !== undefined ? (TASK_PRIO.includes(req.body.priority) ? req.body.priority : 'none') : task.priority;
const notes = req.body.notes !== undefined ? (req.body.notes || '') : task.notes;
const sessionId = req.body.sessionId !== undefined ? (req.body.sessionId || null) : task.session_id;
const done = req.body.done !== undefined ? Boolean(req.body.done) : !!task.done;
db.prepare(
`UPDATE tasks SET title = ?, category = ?, time_of_day = ?, due_date = ?, priority = ?, notes = ?, session_id = ?, done = ?
WHERE id = ? AND user_id = ?`
).run(title, category, timeOfDay, dueDate, priority, notes, sessionId, done ? 1 : 0, req.params.id, req.user.id);
res.json({ ok: true });
});
app.delete('/api/tasks/:id', requireAuth, (req, res) => {
db.prepare('DELETE FROM tasks WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
res.json({ ok: true });
});
// ── Start ─────────────────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Recall running at http://localhost:${PORT}`);
});