forked from Charushi06/StudyPlan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
511 lines (442 loc) · 18.1 KB
/
server.js
File metadata and controls
511 lines (442 loc) · 18.1 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const { db, initDb } = require('./database');
const { GoogleGenAI } = require('@google/genai');
const path = require('path');
const csvDownloadRouter = require('./backend/routers/csvDownload.router.js');
const app = express();
app.use(cors());
app.use(express.json());
const page404Path = path.join(__dirname, '404.html');
const page500Path = path.join(__dirname, 'error.html');
// Static
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/js', express.static(path.join(__dirname, 'js')));
app.use(express.static(__dirname));
initDb();
const ai = process.env.GEMINI_API_KEY
? new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY })
: null;
// ============================================================
// INLINE NLP FALLBACK
// ============================================================
function nlpAddDays(date, n) {
const d = new Date(date); d.setDate(d.getDate() + n); return d;
}
function nlpStartOf(date) {
const d = new Date(date); d.setHours(23, 59, 0, 0); return d;
}
function nlpWithTime(dateStr, t) {
const d = new Date(dateStr);
if (t) d.setHours(t.hours, t.minutes, 0, 0);
return d.toISOString();
}
function nlpExtractTime(lower) {
if (/\bmidnight\b/.test(lower)) return { hours: 23, minutes: 59 };
if (/\bnoon\b/.test(lower)) return { hours: 12, minutes: 0 };
let m = lower.match(/\b(\d{1,2}):(\d{2})\s*(am|pm)?\b/);
if (m) {
let h = parseInt(m[1]); const min = parseInt(m[2]); const mer = m[3];
if (mer === 'pm' && h < 12) h += 12;
if (mer === 'am' && h === 12) h = 0;
return { hours: h, minutes: min };
}
m = lower.match(/\b(\d{1,2})\s*(am|pm)\b/);
if (m) {
let h = parseInt(m[1]); const mer = m[2];
if (mer === 'pm' && h < 12) h += 12;
if (mer === 'am' && h === 12) h = 0;
return { hours: h, minutes: 0 };
}
return null;
}
const NLP_WEEKDAYS = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'];
const NLP_MONTHS = {
jan:0,january:0,feb:1,february:1,mar:2,march:2,apr:3,april:3,may:4,
jun:5,june:5,jul:6,july:6,aug:7,august:7,sep:8,september:8,
oct:9,october:9,nov:10,november:10,dec:11,december:11
};
function nlpResolveYear(now, month, day, explicitYear = null) {
if (explicitYear) return new Date(explicitYear, month, day);
const c = new Date(now.getFullYear(), month, day);
if (c < now) c.setFullYear(c.getFullYear() + 1);
return c;
}
function nlpExtractDate(text, now = new Date()) {
const lower = text.toLowerCase();
const time = nlpExtractTime(lower);
if (/\btoday\b/.test(lower)) return nlpWithTime(nlpStartOf(now).toISOString(), time);
if (/\bday after tomorrow\b/.test(lower)) return nlpWithTime(nlpStartOf(nlpAddDays(now, 2)).toISOString(), time);
if (/\btomorrow\b/.test(lower)) return nlpWithTime(nlpStartOf(nlpAddDays(now, 1)).toISOString(), time);
let m = lower.match(/\bin\s+(\d+|a|an|one|two|three|four|five|six|seven)\s+(day|days|week|weeks|month|months)\b/);
if (m) {
const wm = { a:1,an:1,one:1,two:2,three:3,four:4,five:5,six:6,seven:7 };
const n = isNaN(m[1]) ? (wm[m[1]] || 1) : parseInt(m[1]);
let d = new Date(now);
if (m[2].startsWith('day')) d = nlpAddDays(d, n);
else if (m[2].startsWith('week')) d = nlpAddDays(d, n * 7);
else d.setMonth(d.getMonth() + n);
return nlpWithTime(nlpStartOf(d).toISOString(), time);
}
const wdPattern = new RegExp(`\\b(next|this|on|coming)?\\s*(${NLP_WEEKDAYS.join('|')})\\b`);
m = lower.match(wdPattern);
if (m) {
const target = NLP_WEEKDAYS.indexOf(m[2]);
const cur = now.getDay();
let diff = target - cur;
if (diff <= 0) diff += 7;
return nlpWithTime(nlpStartOf(nlpAddDays(now, diff)).toISOString(), time);
}
const monthNames = Object.keys(NLP_MONTHS).join('|');
const ord = `(\\d{1,2})(?:st|nd|rd|th)?`;
m = lower.match(new RegExp(`\\b(${monthNames})\\s+${ord}\\b`));
if (m) return nlpWithTime(nlpStartOf(nlpResolveYear(now, NLP_MONTHS[m[1]], parseInt(m[2]))).toISOString(), time);
m = lower.match(new RegExp(`\\b${ord}\\s+(${monthNames})\\b`));
if (m) return nlpWithTime(nlpStartOf(nlpResolveYear(now, NLP_MONTHS[m[2]], parseInt(m[1]))).toISOString(), time);
m = lower.match(/\b(\d{1,2})[\/\-\.](\d{1,2})(?:[\/\-\.](\d{2,4}))?\b/);
if (m) {
const day = parseInt(m[1]), month = parseInt(m[2]) - 1;
const yr = m[3] ? (m[3].length === 2 ? 2000 + parseInt(m[3]) : parseInt(m[3])) : null;
return nlpWithTime(nlpStartOf(nlpResolveYear(now, month, day, yr)).toISOString(), time);
}
if (/\bend of (the\s+)?week\b/.test(lower) || /\bby (the\s+)?weekend\b/.test(lower)) {
const d = new Date(now); d.setDate(d.getDate() + (7 - d.getDay()));
return nlpStartOf(d).toISOString();
}
if (/\bend of (the\s+)?month\b/.test(lower)) {
return nlpStartOf(new Date(now.getFullYear(), now.getMonth() + 1, 0)).toISOString();
}
if (/\bnext month\b/.test(lower)) {
const d = new Date(now); d.setMonth(d.getMonth() + 1);
return nlpStartOf(d).toISOString();
}
return null;
}
const NLP_SUBJECT_KEYWORDS = {
'Computer Science': ['cs','computer science','programming','code','coding','algorithm','data structure','software','python','java','javascript','html','database','sql','network','operating system','os','web','scheduling','lab report','assignment'],
'Mathematics': ['maths','math','mathematics','calculus','algebra','statistics','probability','theorem','equation','integral','derivative','matrix','vector','problem set','pset','worksheet','integration'],
'English Lit': ['english','literature','essay','novel','poem','poetry','shakespeare','writing','prose','narrative','analysis','literary','book report','reading','thesis','draft','revision'],
'Physics': ['physics','mechanics','thermodynamics','optics','velocity','acceleration','force','energy','momentum','lab','experiment','wave','circuit','resistance','voltage'],
};
function nlpDetectSubject(text) {
const lower = text.toLowerCase();
const scores = {};
for (const [sub, kws] of Object.entries(NLP_SUBJECT_KEYWORDS)) {
scores[sub] = 0;
for (const kw of kws) {
const re = new RegExp(`\\b${kw.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')}\\b`, 'gi');
const hits = lower.match(re);
if (hits) scores[sub] += hits.length * (kw.length > 5 ? 2 : 1);
}
}
const best = Object.entries(scores).sort((a, b) => b[1] - a[1])[0];
return best && best[1] > 0 ? best[0] : null;
}
const NLP_TASK_VERBS = ['submit','finish','complete','hand in','turn in','upload','send','write','prepare','present','review','read','study','draft','revise'];
function nlpSplitSegments(text) {
return text.split(/[\n\r]+|(?<=\.)\s+(?=[A-Z])|\d+[.)]\s*/)
.map(s => s.trim()).filter(s => s.length > 8);
}
function nlpTaskScore(seg) {
const lower = seg.toLowerCase();
let s = 0;
for (const v of NLP_TASK_VERBS) if (lower.includes(v)) { s += 30; break; }
const sigs = ['due','deadline','by','before','submit','tomorrow','next','today','week','month',
'monday','tuesday','wednesday','thursday','friday','saturday','sunday',
/\d+\/\d+/, /\d{1,2}(st|nd|rd|th)/];
for (const sig of sigs) if (sig instanceof RegExp ? sig.test(lower) : lower.includes(sig)) { s += 25; break; }
if (seg.length > 15 && seg.length < 300) s += 15;
if (nlpDetectSubject(seg)) s += 20;
const fillers = ['hi ','hello','hey ','dear ','regards','thanks','sincerely'];
for (const f of fillers) if (lower.startsWith(f)) { s -= 40; break; }
return Math.max(0, Math.min(100, s));
}
function nlpCleanTitle(seg) {
return seg
.replace(/^(please|kindly|remember to|don't forget to|make sure to)\s+/i, '')
.replace(/\s+(by|before|due|on|at)\s+.*/i, '')
.trim().substring(0, 80);
}
function nlpFallbackDate() {
const d = new Date(); d.setDate(d.getDate() + 7); d.setHours(23, 59, 0, 0);
return d.toISOString();
}
function nlpExtractTasksFromText(text) {
const now = new Date();
const segs = nlpSplitSegments(text);
const results = [];
const seen = new Set();
for (const seg of segs) {
if (nlpTaskScore(seg) < 30) continue;
const due_at = nlpExtractDate(seg, now) || nlpFallbackDate();
const subjectName = nlpDetectSubject(seg);
const rawTitle = nlpCleanTitle(seg);
if (!rawTitle || rawTitle.length < 4) continue;
const key = rawTitle.toLowerCase().substring(0, 20);
if (seen.has(key)) continue;
seen.add(key);
const confidence = Math.min(95, nlpTaskScore(seg) + (nlpExtractDate(seg, now) ? 10 : 0) + (subjectName ? 10 : 0));
results.push({
title: rawTitle.charAt(0).toUpperCase() + rawTitle.slice(1),
subject_name: subjectName || 'General',
due_at,
notes: 'Extracted by heuristic NLP parser.',
icon: { 'Computer Science':'💻','Mathematics':'📐','English Lit':'📖','Physics':'⚗️' }[subjectName] || '📚',
confidence_score: confidence,
priority: confidence > 70 ? 'high' : 'medium',
});
}
if (results.length === 0 && text.trim().length > 5) {
results.push({
title: text.trim().substring(0, 60),
subject_name: 'General',
due_at: nlpFallbackDate(),
notes: 'Could not parse details — please edit manually.',
icon: '❓',
confidence_score: 30,
priority: 'medium',
});
}
return results.slice(0, 10);
}
// ============================================================
// ================= SUBJECTS =================
app.get('/api/subjects', (req, res) => {
db.all('SELECT * FROM subjects', (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
const ALLOWED_SUBJECT_COLORS = new Set([
'var(--color-text-info)',
'var(--color-text-success)',
'var(--color-text-purple)',
'var(--color-text-warning)',
'var(--color-text-danger)',
'var(--color-text-secondary)',
]);
app.post('/api/subjects', (req, res) => {
const name = String(req.body?.name || '').trim();
let color = String(req.body?.color || '').trim() || 'var(--color-text-info)';
if (!name) {
return res.status(400).json({ error: 'Subject name is required' });
}
if (!ALLOWED_SUBJECT_COLORS.has(color)) {
color = 'var(--color-text-info)';
}
const shortCode = name.replace(/[^a-zA-Z0-9]/g, '').toUpperCase().slice(0, 4) || 'SUB';
const id = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
db.run(
'INSERT INTO subjects (id, name, short_code, color) VALUES (?, ?, ?, ?)',
[id, name, shortCode, color],
function (err) {
if (err) return res.status(500).json({ error: err.message });
res.status(201).json({ id, name, short_code: shortCode, color });
}
);
});
// ================= TASKS =================
app.get('/api/tasks', (req, res) => {
db.all('SELECT * FROM tasks ORDER BY due_at ASC', (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
// ================= ADD TASKS =================
app.post('/api/tasks', (req, res) => {
try {
const tasks = Array.isArray(req.body) ? req.body : [req.body];
if (!tasks || tasks.length === 0) {
return res.status(400).json({ success: false, message: "No tasks provided" });
}
let inserted = 0;
let duplicates = [];
let errors = [];
const stmt = db.prepare(`INSERT INTO tasks
(id, subject_id, title, due_at, status, priority, confidence_score, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
let pending = tasks.length;
tasks.forEach(t => {
if (!t.title || !t.due_at || !t.subject_id) {
errors.push({ task: t, error: "Missing title, subject or due date" });
pending--;
if (pending === 0) {
stmt.finalize(() => res.status(400).json({ success: false, inserted, duplicates, errors, message: "All tasks invalid" }));
}
return;
}
db.get(
`SELECT * FROM tasks WHERE LOWER(title) = LOWER(?) AND subject_id = ? AND DATE(due_at) = DATE(?)`,
[t.title, t.subject_id, t.due_at],
(err, existing) => {
if (err) {
errors.push({ task: t, error: err.message });
} else if (existing) {
duplicates.push({
title: t.title,
due_at: t.due_at,
subject_id: t.subject_id
});
} else {
const id = 'task_' + Date.now() + Math.random().toString(36).substr(2, 5);
stmt.run(
id,
t.subject_id,
t.title,
t.due_at,
t.status || 'Not Started',
t.priority || 'medium',
t.confidence_score || 100,
t.notes || '',
function (insertErr) {
if (insertErr) {
errors.push({ task: t, error: insertErr.message });
} else {
inserted++;
}
}
);
}
pending--;
if (pending === 0) {
stmt.finalize((finalErr) => {
if (finalErr) return res.status(500).json({ success: false, message: "Database error", error: finalErr.message });
return res.json({
success: true,
inserted,
duplicates,
errors,
message:
errors.length > 0 && duplicates.length > 0
? "Some tasks failed and some duplicates were skipped"
: errors.length > 0
? "Some tasks failed to add"
: duplicates.length > 0
? "Duplicate tasks were skipped"
: "All tasks added successfully"
});
});
}
}
);
});
} catch (e) {
return res.status(500).json({ success: false, message: "Unexpected server error", error: e.message });
}
});
// ================= UPDATE =================
app.put('/api/tasks/:id', (req, res) => {
const { status, archived, title, subject_id, due_at, notes, priority } = req.body;
let query = 'UPDATE tasks SET ';
const params = [];
const updates = [];
if (status !== undefined) { updates.push('status = ?'); params.push(status); }
if (archived !== undefined) { updates.push('archived = ?'); params.push(archived); }
if (title !== undefined) { updates.push('title = ?'); params.push(title); }
if (subject_id !== undefined) { updates.push('subject_id = ?'); params.push(subject_id); }
if (due_at !== undefined) { updates.push('due_at = ?'); params.push(due_at); }
if (notes !== undefined) { updates.push('notes = ?'); params.push(notes); }
if (priority !== undefined) { updates.push('priority = ?'); params.push(priority); }
if (updates.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
query += updates.join(', ') + ' WHERE id = ?';
params.push(req.params.id);
db.run(query, params, function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true, changes: this.changes });
});
});
// ================= DELETE =================
app.delete('/api/tasks/:id', (req, res) => {
db.run(
'DELETE FROM tasks WHERE id = ?',
[req.params.id],
function (err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true, changes: this.changes });
}
);
});
// ================= AI EXTRACTION =================
app.post('/api/extract', async (req, res) => {
const { text } = req.body;
if (!text) return res.status(400).json({ error: 'Text is required' });
if (ai) {
try {
const prompt = `
You are an AI study planner assistant. Extract ALL tasks and deadlines from the text below.
Return ONLY a raw JSON array (no markdown, no backticks, no explanation).
Each object must have: title (string), subject_name (string), due_at (ISO 8601 datetime), notes (string), confidence_score (number 0-100), priority ("low"|"medium"|"high"), icon (emoji).
Text: "${text}"
`;
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: prompt
});
let rawText = (typeof response.text === 'function' ? response.text() : response.text).trim();
if (rawText.startsWith('```')) rawText = rawText.replace(/```json|```/g, '').trim();
const data = JSON.parse(rawText);
return res.json(data);
} catch (e) {
console.error('Gemini failed, falling back to NLP heuristic:', e.message);
}
}
// NLP heuristic fallback (no API key, or Gemini failed)
const tasks = nlpExtractTasksFromText(text);
return res.json(tasks);
});
// ================= AUTH =================
const users = {}; // Simple in-memory user store
app.post('/api/auth/signup', (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
if (users[email]) {
return res.status(400).json({ error: 'User already exists' });
}
users[email] = { email, password };
res.json({ success: true, message: 'Account created successfully' });
});
app.post('/api/auth/login', (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
const user = users[email];
if (!user || user.password !== password) {
return res.status(401).json({ error: 'Invalid email or password' });
}
res.json({ success: true, email: user.email });
});
// Intentional test route for verifying server error page behavior.
app.get('/debug/force-error', (req, res, next) => {
next(new Error('Intentional test error'));
});
app.use('/api', csvDownloadRouter);
app.use('/api', (req, res) => {
return res.status(404).json({ error: 'API route not found' });
});
app.use((req, res, next) => {
if (req.method !== 'GET') {
return next();
}
return res.status(404).sendFile(page404Path);
});
app.use((err, req, res, next) => {
console.error('Unhandled server error:', err);
if (res.headersSent) {
return next(err);
}
if (req.path.startsWith('/api')) {
return res.status(500).json({ error: 'Internal server error' });
}
return res.status(500).sendFile(page500Path);
});
// ================= SERVER =================
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server running on port ' + PORT);
});