BeKultur/src/server.ts

568 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { SyllabusService, DAY_NAMES } from './services/syllabus';
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/exclude
* Toggle assignment disinclude/exclude state
*/
app.post('/api/exclude', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { assignmentId, excluded } = req.body;
if (!assignmentId) {
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
}
const updated = db.toggleExcludeAssignment(studentId, assignmentId, excluded);
if (!updated) {
return res.status(404).json({ success: false, error: 'Assignment not found' });
}
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}`
});
}
});
/**
* GET /syllabus
* Syllabus (Ders Programı) View with station filtering & weekly updates
*/
app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const currentWeek = SyllabusService.getWeekMetadata();
let syllabusStore = db.getSyllabus(studentId);
// If syllabus missing or belongs to an older week, auto-sync from portal!
if (!syllabusStore || !syllabusStore.weekId || syllabusStore.weekId !== currentWeek.weekId) {
let cookies = req.session.portalCookies;
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) {
try {
const schedule = await ScraperService.scrapeSyllabus(cookies);
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
syllabusStore = db.getSyllabus(studentId);
} catch (err: any) {
console.error('Failed auto-syncing weekly syllabus:', err.message);
}
}
}
// Selected station (default to İst-4 if not chosen yet)
const selectedStation = syllabusStore?.selectedStation || 'İst-4';
// Active day: 1 = Mon .. 5 = Fri (if weekend, default to Mon)
const todayDay = new Date().getDay();
const defaultDay = todayDay >= 1 && todayDay <= 5 ? todayDay : 1;
const activeDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay;
// Compute filtered schedule for selected station
const rawSchedule = syllabusStore?.schedule || {};
const filteredSchedule: Record<number, any[]> = {};
for (let d = 1; d <= 5; d++) {
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation);
}
const currentStatus = SyllabusService.getCurrentLessonStatus(
filteredSchedule[activeDay] || [],
activeDay
);
res.render('syllabus', {
title: 'Syllabus - BeKultur',
studentId,
weekId: currentWeek.weekId,
weekRange: currentWeek.weekRange,
selectedStation,
activeDay,
filteredSchedule,
currentStatus,
lastSynced: syllabusStore?.lastSynced || null,
DAY_NAMES
});
});
/**
* POST /api/syllabus/station
* Update selected station
*/
app.post('/api/syllabus/station', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { station } = req.body;
db.setStudentStation(studentId, station || null);
const syllabusStore = db.getSyllabus(studentId);
const rawSchedule = syllabusStore?.schedule || {};
const filteredSchedule: Record<number, any[]> = {};
for (let d = 1; d <= 5; d++) {
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null);
}
res.json({
success: true,
selectedStation: station,
filteredSchedule
});
});
/**
* POST /api/syllabus/sync
* Manually refresh syllabus across all 5 days from portal
*/
app.post('/api/syllabus/sync', 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 syllabus.'
});
}
const currentWeek = SyllabusService.getWeekMetadata();
const schedule = await ScraperService.scrapeSyllabus(cookies);
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
const store = db.getSyllabus(studentId);
const selectedStation = store?.selectedStation || 'İst-4';
const filteredSchedule: Record<number, any[]> = {};
for (let d = 1; d <= 5; d++) {
filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation);
}
res.json({
success: true,
weekId: currentWeek.weekId,
weekRange: currentWeek.weekRange,
lastSynced: store?.lastSynced,
filteredSchedule
});
} catch (err: any) {
console.error('API syllabus sync error:', err.message);
res.status(500).json({
success: false,
error: `Syllabus 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;