This commit is contained in:
tyuXX 2026-10-21 17:27:53 +00:00
commit 5577214005
22 changed files with 4997 additions and 0 deletions

388
src/server.ts Normal file
View file

@ -0,0 +1,388 @@
import express, { Request, Response, NextFunction } from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import path from 'path';
import dotenv from 'dotenv';
import { ScraperService } from './services/scraper';
import { LocalDatabase } from './services/db';
import { InsightService } from './services/insight';
import { Assignment } from './types';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const SESSION_SECRET = process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
// View engine setup
app.set('view engine', 'ejs');
// Support running from both ts-node (src/../views) and dist (dist/views)
const viewsPath = path.resolve(__dirname, '../views');
const publicPath = path.resolve(__dirname, '../public');
app.set('views', viewsPath);
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(publicPath));
app.use(
session({
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days
}
})
);
// Augment express-session
declare module 'express-session' {
interface SessionData {
studentId?: string;
portalCookies?: string;
studentName?: string;
}
}
const db = LocalDatabase.getInstance();
// Auth guard helper
function requireAuth(req: Request, res: Response, next: NextFunction) {
if (req.session && req.session.studentId) {
return next();
}
// Check if studentId remembered in cookie
const rememberedId = req.cookies.bekultur_student_id;
if (rememberedId) {
const creds = db.getRememberedCredentials(rememberedId);
if (creds) {
// Auto re-login in background
ScraperService.login(creds.studentId, creds.password).then(loginRes => {
if (loginRes.success) {
req.session.studentId = creds.studentId;
req.session.portalCookies = loginRes.cookies;
req.session.studentName = loginRes.studentName;
return next();
} else {
res.clearCookie('bekultur_student_id');
return res.redirect('/');
}
}).catch(() => {
return res.redirect('/');
});
return;
}
}
res.redirect('/');
}
// ----------------------------------------------------
// Routes
// ----------------------------------------------------
/**
* GET /
* Login Page
*/
app.get('/', (req: Request, res: Response) => {
if (req.session && req.session.studentId) {
return res.redirect('/dashboard');
}
const rememberedId = req.cookies.bekultur_student_id || '';
const error = (req.query.error as string) || null;
res.render('login', {
error,
rememberedId,
title: 'Login - BeKultur (Better E-Kultur)'
});
});
/**
* POST /login
* Authenticate against portal and scrape recent assignments
*/
app.post('/login', async (req: Request, res: Response) => {
const { studentId, password, rememberMe } = req.body;
if (!studentId || !password) {
return res.render('login', {
error: 'Please enter both Student ID and Password.',
rememberedId: studentId || '',
title: 'Login - BeKultur'
});
}
try {
const loginRes = await ScraperService.login(studentId, password);
if (!loginRes.success) {
return res.render('login', {
error: loginRes.error || 'Authentication failed. Please check your credentials.',
rememberedId: studentId,
title: 'Login - BeKultur'
});
}
req.session.studentId = studentId;
req.session.portalCookies = loginRes.cookies;
req.session.studentName = loginRes.studentName;
// Handle "Remember Me"
if (rememberMe) {
db.saveCredentials(studentId, password);
res.cookie('bekultur_student_id', studentId, {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true
});
} else {
db.clearCredentials(studentId);
res.clearCookie('bekultur_student_id');
}
// Scrape recent pages (1-2)
try {
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, studentId, 2);
db.mergeAssignments(studentId, scrapeRes.assignments);
} catch (scrapeErr: any) {
console.warn('Initial scrape warning (cached data will be used if available):', scrapeErr.message);
}
res.redirect('/dashboard');
} catch (err: any) {
console.error('Login route error:', err);
res.render('login', {
error: 'An unexpected server error occurred during login.',
rememberedId: studentId,
title: 'Login - BeKultur'
});
}
});
/**
* POST /logout
*/
app.post('/logout', (req: Request, res: Response) => {
req.session.destroy(() => {
res.redirect('/');
});
});
/**
* GET /logout (convenience)
*/
app.get('/logout', (req: Request, res: Response) => {
req.session.destroy(() => {
res.redirect('/');
});
});
/**
* GET /dashboard
* English dashboard with stats and checkable assignments
*/
app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const studentStore = db.getStudentStore(studentId);
// Recalculate status for each assignment relative to current date
const rawList = Object.values(studentStore.assignments);
const updatedAssignments: Assignment[] = rawList.map(item => {
const status = InsightService.computeStatus(item);
return {
...item,
status
};
});
// Calculate statistics
const stats = InsightService.calculateStats(updatedAssignments);
// Unique list of subjects for filter
const subjects = Array.from(new Set(updatedAssignments.map(a => a.subject))).sort();
// Sort assignments:
// 1. Not completed first
// 2. Priority: next-week & due-soon first, then active, then overdue, then completed
const statusPriority: Record<string, number> = {
'due-soon': 1,
'next-week': 2,
'active': 3,
'future': 4,
'overdue': 5,
'completed': 6
};
updatedAssignments.sort((a, b) => {
const pA = statusPriority[a.status] || 99;
const pB = statusPriority[b.status] || 99;
if (pA !== pB) return pA - pB;
// secondary sort by end date descending
return (b.parsedEndDate || '').localeCompare(a.parsedEndDate || '');
});
res.render('dashboard', {
title: 'Dashboard - BeKultur',
studentId,
studentName: req.session.studentName || `Student ${studentId}`,
lastSynced: studentStore.lastSynced,
stats,
assignments: updatedAssignments,
subjects
});
});
/**
* POST /api/toggle
* Toggle assignment completion state
*/
app.post('/api/toggle', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { assignmentId, completed } = req.body;
if (!assignmentId) {
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
}
const updated = db.toggleAssignment(studentId, assignmentId, completed);
if (!updated) {
return res.status(404).json({ success: false, error: 'Assignment not found' });
}
// Recalculate fresh stats
const studentStore = db.getStudentStore(studentId);
const list = Object.values(studentStore.assignments).map(a => ({
...a,
status: InsightService.computeStatus(a)
}));
const stats = InsightService.calculateStats(list);
res.json({
success: true,
assignment: updated,
stats
});
});
/**
* POST /api/sync
* Sync recent pages (1-2)
*/
app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try {
// If session cookies missing, attempt re-login using remembered credentials
if (!cookies) {
const creds = db.getRememberedCredentials(studentId);
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync.'
});
}
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2);
db.mergeAssignments(studentId, scrapeRes.assignments);
const store = db.getStudentStore(studentId);
const list = Object.values(store.assignments).map(a => ({
...a,
status: InsightService.computeStatus(a)
}));
const stats = InsightService.calculateStats(list);
res.json({
success: true,
count: scrapeRes.assignments.length,
lastSynced: store.lastSynced,
stats
});
} catch (err: any) {
console.error('API sync error:', err.message);
res.status(500).json({
success: false,
error: `Sync failed: ${err.message}`
});
}
});
/**
* POST /api/sync-all
* Sync all historical pages (pages 1 to 7+)
*/
app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try {
if (!cookies) {
const creds = db.getRememberedCredentials(studentId);
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync full history.'
});
}
// Scrape up to 20 pages (portal currently has ~7 pages)
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 20);
db.mergeAssignments(studentId, scrapeRes.assignments);
const store = db.getStudentStore(studentId);
const list = Object.values(store.assignments).map(a => ({
...a,
status: InsightService.computeStatus(a)
}));
const stats = InsightService.calculateStats(list);
res.json({
success: true,
count: scrapeRes.assignments.length,
totalPages: scrapeRes.totalPages,
lastSynced: store.lastSynced,
stats
});
} catch (err: any) {
console.error('API sync-all error:', err.message);
res.status(500).json({
success: false,
error: `Full history sync failed: ${err.message}`
});
}
});
// Start Server
if (process.env.NODE_ENV !== 'test') {
app.listen(PORT, () => {
console.log(`=========================================`);
console.log(` BeKultur (Better E-Kultur) Server`);
console.log(` Running at: http://localhost:${PORT}`);
console.log(`=========================================`);
});
}
export default app;