init
This commit is contained in:
commit
5577214005
22 changed files with 4997 additions and 0 deletions
388
src/server.ts
Normal file
388
src/server.ts
Normal 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;
|
||||
127
src/services/db.ts
Normal file
127
src/services/db.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSchema, StudentStore, Assignment } from '../types';
|
||||
|
||||
const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json');
|
||||
|
||||
export class LocalDatabase {
|
||||
private static instance: LocalDatabase;
|
||||
private cache: DatabaseSchema = { students: {} };
|
||||
private initialized = false;
|
||||
|
||||
private constructor() {
|
||||
this.ensureDbExists();
|
||||
this.load();
|
||||
}
|
||||
|
||||
public static getInstance(): LocalDatabase {
|
||||
if (!LocalDatabase.instance) {
|
||||
LocalDatabase.instance = new LocalDatabase();
|
||||
}
|
||||
return LocalDatabase.instance;
|
||||
}
|
||||
|
||||
private ensureDbExists(): void {
|
||||
const dir = path.dirname(DB_FILE);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
if (!fs.existsSync(DB_FILE)) {
|
||||
const initial: DatabaseSchema = { students: {} };
|
||||
fs.writeFileSync(DB_FILE, JSON.stringify(initial, null, 2), 'utf-8');
|
||||
}
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
try {
|
||||
if (fs.existsSync(DB_FILE)) {
|
||||
const raw = fs.readFileSync(DB_FILE, 'utf-8');
|
||||
this.cache = JSON.parse(raw) as DatabaseSchema;
|
||||
if (!this.cache.students) {
|
||||
this.cache.students = {};
|
||||
}
|
||||
}
|
||||
this.initialized = true;
|
||||
} catch (err) {
|
||||
console.error('Error loading database file, initializing empty:', err);
|
||||
this.cache = { students: {} };
|
||||
}
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
try {
|
||||
const tmpFile = `${DB_FILE}.tmp`;
|
||||
fs.writeFileSync(tmpFile, JSON.stringify(this.cache, null, 2), 'utf-8');
|
||||
fs.renameSync(tmpFile, DB_FILE);
|
||||
} catch (err) {
|
||||
console.error('Error saving database:', err);
|
||||
}
|
||||
}
|
||||
|
||||
public getStudentStore(studentId: string): StudentStore {
|
||||
if (!this.cache.students[studentId]) {
|
||||
this.cache.students[studentId] = {
|
||||
studentId,
|
||||
lastSynced: null,
|
||||
assignments: {}
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
return this.cache.students[studentId];
|
||||
}
|
||||
|
||||
public mergeAssignments(studentId: string, newAssignments: Assignment[]): StudentStore {
|
||||
const student = this.getStudentStore(studentId);
|
||||
student.lastSynced = new Date().toISOString();
|
||||
|
||||
for (const item of newAssignments) {
|
||||
const existing = student.assignments[item.id];
|
||||
if (existing) {
|
||||
// Preserve user completion status and completion timestamp
|
||||
student.assignments[item.id] = {
|
||||
...item,
|
||||
completed: existing.completed,
|
||||
completedAt: existing.completedAt
|
||||
};
|
||||
} else {
|
||||
student.assignments[item.id] = item;
|
||||
}
|
||||
}
|
||||
|
||||
this.save();
|
||||
return student;
|
||||
}
|
||||
|
||||
public toggleAssignment(studentId: string, assignmentId: string, completed?: boolean): Assignment | null {
|
||||
const student = this.getStudentStore(studentId);
|
||||
const assignment = student.assignments[assignmentId];
|
||||
if (!assignment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const newCompleted = completed !== undefined ? completed : !assignment.completed;
|
||||
assignment.completed = newCompleted;
|
||||
assignment.completedAt = newCompleted ? new Date().toISOString() : null;
|
||||
assignment.status = newCompleted ? 'completed' : assignment.status;
|
||||
|
||||
this.save();
|
||||
return assignment;
|
||||
}
|
||||
|
||||
public saveCredentials(studentId: string, password: string): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
student.rememberedCredentials = { studentId, password };
|
||||
this.save();
|
||||
}
|
||||
|
||||
public clearCredentials(studentId: string): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
delete student.rememberedCredentials;
|
||||
this.save();
|
||||
}
|
||||
|
||||
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
|
||||
const student = this.cache.students[studentId];
|
||||
return student?.rememberedCredentials || null;
|
||||
}
|
||||
}
|
||||
239
src/services/insight.ts
Normal file
239
src/services/insight.ts
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
import { Assignment, AssignmentStatus, DashboardStats, SubjectStat } from '../types';
|
||||
|
||||
export class InsightService {
|
||||
/**
|
||||
* Normalize Turkish text for consistent regex and search matching (handles I / ı / İ / i)
|
||||
*/
|
||||
public static normalizeTurkish(str: string): string {
|
||||
if (!str) return '';
|
||||
return str
|
||||
.replace(/İ/g, 'i')
|
||||
.replace(/I/g, 'ı')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Turkish date string like "20.10.2026" or "8.11.2026" into a Date object
|
||||
*/
|
||||
public static parsePortalDate(dateStr: string): Date | null {
|
||||
if (!dateStr) return null;
|
||||
const parts = dateStr.trim().split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
|
||||
const day = parseInt(parts[0], 10);
|
||||
const month = parseInt(parts[1], 10) - 1;
|
||||
const year = parseInt(parts[2], 10);
|
||||
|
||||
if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
|
||||
return new Date(year, month, day, 23, 59, 59, 999);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Date to ISO date string (YYYY-MM-DD)
|
||||
*/
|
||||
public static toISODate(date: Date | null): string | null {
|
||||
if (!date || isNaN(date.getTime())) return null;
|
||||
const y = date.getFullYear();
|
||||
const m = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const d = String(date.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan description for teacher notes regarding check dates ("kontrol tarihi")
|
||||
*/
|
||||
public static extractTeacherCheckNote(description: string): string | null {
|
||||
if (!description) return null;
|
||||
const norm = this.normalizeTurkish(description);
|
||||
|
||||
// Pattern 1: "kontrol tarihi 26-30 ekim" or "kontrol tarihi 27 ekim"
|
||||
const match1 = norm.match(/kontrol\s+tarihi\s*:?\s*([0-9]{1,2}(?:\s*-\s*[0-9]{1,2})?\s+[a-zçğıöşü]+)/);
|
||||
if (match1) {
|
||||
return match1[1].trim();
|
||||
}
|
||||
|
||||
// Pattern 2: "ödevler 26-30 ekim arasında kontrol edilecektir"
|
||||
const match2 = norm.match(/ödevler\s+([0-9]{1,2}(?:\s*-\s*[0-9]{1,2})?\s+[a-zçğıöşü]+)\s+arasında\s+kontrol/);
|
||||
if (match2) {
|
||||
return match2[1].trim();
|
||||
}
|
||||
|
||||
// Pattern 3: "26 10 kontrol" or "26/10 kontrol"
|
||||
const match3 = norm.match(/([0-9]{1,2}\s+[0-9]{1,2})\s+kontrol/);
|
||||
if (match3) {
|
||||
const parts = match3[1].split(/\s+/);
|
||||
const day = parts[0];
|
||||
const monthNum = parseInt(parts[1], 10);
|
||||
const monthNames = ['', 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'];
|
||||
const monthName = monthNames[monthNum] || parts[1];
|
||||
return `${day} ${monthName}`;
|
||||
}
|
||||
|
||||
// Pattern 4: generic "(... kontrol ...)"
|
||||
const match4 = norm.match(/\(([^)]*kontrol[^)]*)\)/);
|
||||
if (match4) {
|
||||
return match4[1].trim();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify assignment status based on official dates, teacher notes, and completion flag
|
||||
*/
|
||||
public static computeStatus(
|
||||
assignment: Omit<Assignment, 'status'>,
|
||||
refDate: Date = new Date()
|
||||
): AssignmentStatus {
|
||||
if (assignment.completed) {
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
const endDate = this.parsePortalDate(assignment.endDate);
|
||||
const startDate = this.parsePortalDate(assignment.startDate);
|
||||
|
||||
// If start date is in the future (> today + 2 days)
|
||||
const todayStart = new Date(refDate.getFullYear(), refDate.getMonth(), refDate.getDate(), 0, 0, 0);
|
||||
if (startDate && startDate.getTime() > refDate.getTime() + 86400000 * 2) {
|
||||
return 'future';
|
||||
}
|
||||
|
||||
if (!endDate) {
|
||||
return 'active';
|
||||
}
|
||||
|
||||
// Check if already overdue
|
||||
if (endDate.getTime() < todayStart.getTime()) {
|
||||
return 'overdue';
|
||||
}
|
||||
|
||||
// Current week boundaries (Monday to Sunday)
|
||||
const currentDay = refDate.getDay(); // 0 is Sunday, 1 is Monday
|
||||
const distanceToMonday = currentDay === 0 ? -6 : 1 - currentDay;
|
||||
const thisMonday = new Date(refDate);
|
||||
thisMonday.setDate(refDate.getDate() + distanceToMonday);
|
||||
thisMonday.setHours(0, 0, 0, 0);
|
||||
|
||||
const thisSunday = new Date(thisMonday);
|
||||
thisSunday.setDate(thisMonday.getDate() + 6);
|
||||
thisSunday.setHours(23, 59, 59, 999);
|
||||
|
||||
const nextMonday = new Date(thisSunday);
|
||||
nextMonday.setDate(thisSunday.getDate() + 1);
|
||||
nextMonday.setHours(0, 0, 0, 0);
|
||||
|
||||
const nextSunday = new Date(nextMonday);
|
||||
nextSunday.setDate(nextMonday.getDate() + 6);
|
||||
nextSunday.setHours(23, 59, 59, 999);
|
||||
|
||||
// Check if due in next week window
|
||||
const dueTime = endDate.getTime();
|
||||
const isNextWeek = dueTime >= nextMonday.getTime() && dueTime <= nextSunday.getTime();
|
||||
|
||||
// Check if teacher check note specifically mentions next week
|
||||
let noteIsNextWeek = false;
|
||||
if (assignment.detectedCheckDate) {
|
||||
const lower = assignment.detectedCheckDate.toLowerCase();
|
||||
const dayMatches = lower.match(/\d{1,2}/g);
|
||||
if (dayMatches) {
|
||||
for (const dm of dayMatches) {
|
||||
const d = parseInt(dm, 10);
|
||||
const nextMonDay = nextMonday.getDate();
|
||||
const nextSunDay = nextSunday.getDate();
|
||||
if (nextMonDay <= nextSunDay) {
|
||||
if (d >= nextMonDay && d <= nextSunDay) {
|
||||
noteIsNextWeek = true;
|
||||
}
|
||||
} else {
|
||||
if (d >= nextMonDay || d <= nextSunDay) {
|
||||
noteIsNextWeek = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isNextWeek || noteIsNextWeek) {
|
||||
return 'next-week';
|
||||
}
|
||||
|
||||
// Due soon: within 3 days from now
|
||||
const threeDaysFromNow = new Date(refDate);
|
||||
threeDaysFromNow.setDate(refDate.getDate() + 3);
|
||||
threeDaysFromNow.setHours(23, 59, 59, 999);
|
||||
|
||||
if (dueTime <= threeDaysFromNow.getTime()) {
|
||||
return 'due-soon';
|
||||
}
|
||||
|
||||
return 'active';
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate statistics across a list of assignments
|
||||
*/
|
||||
public static calculateStats(assignments: Assignment[]): DashboardStats {
|
||||
let completed = 0;
|
||||
let active = 0;
|
||||
let checkedNextWeek = 0;
|
||||
let dueSoon = 0;
|
||||
let overdue = 0;
|
||||
|
||||
const bySubject: Record<string, SubjectStat> = {};
|
||||
|
||||
for (const item of assignments) {
|
||||
const subj = item.subject.trim() || 'Other';
|
||||
if (!bySubject[subj]) {
|
||||
bySubject[subj] = {
|
||||
subject: subj,
|
||||
total: 0,
|
||||
completed: 0,
|
||||
active: 0,
|
||||
percentage: 0
|
||||
};
|
||||
}
|
||||
|
||||
bySubject[subj].total += 1;
|
||||
|
||||
if (item.completed) {
|
||||
completed += 1;
|
||||
bySubject[subj].completed += 1;
|
||||
} else {
|
||||
if (item.status === 'overdue') {
|
||||
overdue += 1;
|
||||
} else if (item.status === 'next-week') {
|
||||
checkedNextWeek += 1;
|
||||
active += 1;
|
||||
bySubject[subj].active += 1;
|
||||
} else if (item.status === 'due-soon') {
|
||||
dueSoon += 1;
|
||||
active += 1;
|
||||
bySubject[subj].active += 1;
|
||||
} else {
|
||||
active += 1;
|
||||
bySubject[subj].active += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate subject percentages
|
||||
for (const subj of Object.keys(bySubject)) {
|
||||
const s = bySubject[subj];
|
||||
s.percentage = s.total > 0 ? Math.round((s.completed / s.total) * 100) : 0;
|
||||
}
|
||||
|
||||
const total = assignments.length;
|
||||
const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;
|
||||
|
||||
return {
|
||||
total,
|
||||
completed,
|
||||
active,
|
||||
checkedNextWeek,
|
||||
dueSoon,
|
||||
overdue,
|
||||
completionRate,
|
||||
bySubject
|
||||
};
|
||||
}
|
||||
}
|
||||
307
src/services/scraper.ts
Normal file
307
src/services/scraper.ts
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
import axios from 'axios';
|
||||
import * as cheerio from 'cheerio';
|
||||
import crypto from 'crypto';
|
||||
import { Assignment } from '../types';
|
||||
import { InsightService } from './insight';
|
||||
|
||||
const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com';
|
||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
||||
|
||||
export interface LoginResult {
|
||||
success: boolean;
|
||||
cookies: string;
|
||||
error?: string;
|
||||
studentName?: string;
|
||||
}
|
||||
|
||||
export interface ScrapeResult {
|
||||
assignments: Assignment[];
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export class ScraperService {
|
||||
/**
|
||||
* Helper to format cookies array from set-cookie headers
|
||||
*/
|
||||
private static parseCookies(cookieHeaders: string[] | undefined): string {
|
||||
if (!cookieHeaders || !cookieHeaders.length) return '';
|
||||
return cookieHeaders
|
||||
.map(c => c.split(';')[0].trim())
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge new set-cookie headers into existing cookie string
|
||||
*/
|
||||
private static mergeCookies(currentCookies: string, newHeaders: string[] | undefined): string {
|
||||
if (!newHeaders || !newHeaders.length) return currentCookies;
|
||||
const cookieMap: Record<string, string> = {};
|
||||
|
||||
if (currentCookies) {
|
||||
currentCookies.split(';').forEach(c => {
|
||||
const [k, ...v] = c.trim().split('=');
|
||||
if (k) cookieMap[k] = v.join('=');
|
||||
});
|
||||
}
|
||||
|
||||
newHeaders.forEach(c => {
|
||||
const first = c.split(';')[0].trim();
|
||||
const [k, ...v] = first.split('=');
|
||||
if (k) cookieMap[k] = v.join('=');
|
||||
});
|
||||
|
||||
return Object.entries(cookieMap)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate against Kültür Okulları student portal
|
||||
*/
|
||||
public static async login(studentId: string, password: string): Promise<LoginResult> {
|
||||
try {
|
||||
const client = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
maxRedirects: 0,
|
||||
validateStatus: () => true // Allow handling redirects manually
|
||||
});
|
||||
|
||||
// 1. GET /Kullanici/Giris to obtain anti-forgery token and initial cookies
|
||||
const loginPageRes = await client.get('/Kullanici/Giris');
|
||||
let cookies = this.parseCookies(loginPageRes.headers['set-cookie']);
|
||||
|
||||
const $ = cheerio.load(loginPageRes.data);
|
||||
const token = $('input[name="__RequestVerificationToken"]').val() as string;
|
||||
|
||||
if (!token) {
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: 'Anti-forgery token could not be found on login page.'
|
||||
};
|
||||
}
|
||||
|
||||
// 2. POST /Kullanici/Giris with credentials
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('OgrenciId', studentId.trim());
|
||||
formData.append('Parola', password.trim());
|
||||
formData.append('__RequestVerificationToken', token);
|
||||
|
||||
const postRes = await client.post('/Kullanici/Giris', formData.toString(), {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': `${BASE_URL}/Kullanici/Giris`,
|
||||
'Cookie': cookies
|
||||
}
|
||||
});
|
||||
|
||||
cookies = this.mergeCookies(cookies, postRes.headers['set-cookie']);
|
||||
|
||||
// Check if successful login (302 redirect or has auth cookies)
|
||||
const hasAuthCookie = cookies.includes('.Ogrenci.Cookie') || cookies.includes('.AspNetCore.Cookies');
|
||||
const isRedirectSuccess = postRes.status === 302 && (postRes.headers.location === '/' || postRes.headers.location === '');
|
||||
|
||||
if (!isRedirectSuccess && !hasAuthCookie) {
|
||||
const postHtml = String(postRes.data || '');
|
||||
const $post = cheerio.load(postHtml);
|
||||
const errorMsg = $post('.text-danger').text().trim() || 'Invalid Student ID or Password.';
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: errorMsg
|
||||
};
|
||||
}
|
||||
|
||||
// Check student name if available from home page
|
||||
let studentName = '';
|
||||
try {
|
||||
const homeRes = await client.get('/', {
|
||||
headers: {
|
||||
'Cookie': cookies
|
||||
}
|
||||
});
|
||||
cookies = this.mergeCookies(cookies, homeRes.headers['set-cookie']);
|
||||
const $home = cheerio.load(homeRes.data);
|
||||
const nameCandidate = $home('.nav-link, .dropdown-toggle, .user-name').text().trim();
|
||||
if (nameCandidate) {
|
||||
studentName = nameCandidate;
|
||||
}
|
||||
} catch (homeErr) {
|
||||
// Non-critical
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
cookies,
|
||||
studentName
|
||||
};
|
||||
} catch (err: any) {
|
||||
console.error('Error during portal login:', err.message);
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: `Connection error: ${err.message}`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape homework cards from a single page
|
||||
*/
|
||||
public static async scrapePage(
|
||||
cookies: string,
|
||||
page: number = 1,
|
||||
studentId: string
|
||||
): Promise<ScrapeResult> {
|
||||
try {
|
||||
const url = `${BASE_URL}/Odev?sayfa=${page}`;
|
||||
const res = await axios.get(url, {
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT,
|
||||
'Cookie': cookies,
|
||||
'Referer': `${BASE_URL}/`
|
||||
},
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
if (res.status === 302 || res.status === 401 || (typeof res.data === 'string' && res.data.includes('girisForm'))) {
|
||||
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||
}
|
||||
|
||||
const $ = cheerio.load(res.data);
|
||||
const assignments: Assignment[] = [];
|
||||
|
||||
// Discover maximum pages from pagination
|
||||
let totalPages = 1;
|
||||
$('.pagination li a').each((_, el) => {
|
||||
const href = $(el).attr('href') || '';
|
||||
const match = href.match(/sayfa=(\d+)/i);
|
||||
if (match) {
|
||||
const p = parseInt(match[1], 10);
|
||||
if (p > totalPages) {
|
||||
totalPages = p;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Parse each assignment card
|
||||
$('.kltr-card.mb-4').each((_, cardEl) => {
|
||||
const card = $(cardEl);
|
||||
|
||||
let subject = '';
|
||||
let type = '';
|
||||
let unit = '';
|
||||
let topic = '';
|
||||
let dateRange = '';
|
||||
|
||||
card.find('.row:first-child .col-md-2, .row:first-child .col-md-3').each((_, colEl) => {
|
||||
const label = $(colEl).find('p.fw-bold').text().trim().toLowerCase();
|
||||
const val = $(colEl).find('p:not(.fw-bold)').text().trim();
|
||||
|
||||
if (label.includes('ders')) subject = val;
|
||||
else if (label.includes('tip')) type = val;
|
||||
else if (label.includes('ünite') || label.includes('unite')) unit = val;
|
||||
else if (label.includes('konu')) topic = val;
|
||||
else if (label.includes('başlangıç') || label.includes('bitiş') || label.includes('baslangic')) dateRange = val;
|
||||
});
|
||||
|
||||
// Description is in second row
|
||||
let description = '';
|
||||
const descCol = card.find('.row:nth-child(2) .col-md-12');
|
||||
if (descCol.length) {
|
||||
const descP = descCol.find('p:not(.fw-bold)');
|
||||
description = descP.text().trim();
|
||||
}
|
||||
|
||||
// Parse date range: "20.10.2026 - 26.10.2026"
|
||||
let startDate = '';
|
||||
let endDate = '';
|
||||
if (dateRange) {
|
||||
const parts = dateRange.split('-').map(s => s.trim());
|
||||
if (parts.length >= 2) {
|
||||
startDate = parts[0];
|
||||
endDate = parts[1];
|
||||
} else {
|
||||
startDate = parts[0];
|
||||
endDate = parts[0];
|
||||
}
|
||||
}
|
||||
|
||||
const parsedStartDate = InsightService.toISODate(InsightService.parsePortalDate(startDate));
|
||||
const parsedEndDate = InsightService.toISODate(InsightService.parsePortalDate(endDate));
|
||||
|
||||
// Generate deterministic ID
|
||||
const normalizedDesc = description.replace(/\s+/g, ' ').trim();
|
||||
const hashPayload = `${studentId}|${subject}|${startDate}|${endDate}|${normalizedDesc}`;
|
||||
const id = crypto.createHash('sha256').update(hashPayload).digest('hex').slice(0, 16);
|
||||
|
||||
// Detect teacher note
|
||||
const detectedCheckDate = InsightService.extractTeacherCheckNote(description);
|
||||
|
||||
const assignmentDraft: Omit<Assignment, 'status'> = {
|
||||
id,
|
||||
subject: subject || 'Genel',
|
||||
type: type || 'Ödev',
|
||||
unit,
|
||||
topic,
|
||||
startDate,
|
||||
endDate,
|
||||
parsedStartDate,
|
||||
parsedEndDate,
|
||||
description,
|
||||
detectedCheckDate,
|
||||
completed: false,
|
||||
completedAt: null,
|
||||
page
|
||||
};
|
||||
|
||||
const status = InsightService.computeStatus(assignmentDraft);
|
||||
|
||||
assignments.push({
|
||||
...assignmentDraft,
|
||||
status
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
assignments,
|
||||
totalPages
|
||||
};
|
||||
} catch (err: any) {
|
||||
console.error(`Error scraping page ${page}:`, err.message);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape multiple pages (e.g. pages 1 to maxPages)
|
||||
*/
|
||||
public static async scrapeMultiplePages(
|
||||
cookies: string,
|
||||
studentId: string,
|
||||
maxPages: number = 2
|
||||
): Promise<ScrapeResult> {
|
||||
const firstPage = await this.scrapePage(cookies, 1, studentId);
|
||||
let allAssignments = [...firstPage.assignments];
|
||||
const totalPages = firstPage.totalPages;
|
||||
|
||||
const pagesToFetch = Math.min(totalPages, maxPages);
|
||||
|
||||
for (let p = 2; p <= pagesToFetch; p++) {
|
||||
try {
|
||||
const next = await this.scrapePage(cookies, p, studentId);
|
||||
allAssignments.push(...next.assignments);
|
||||
} catch (err: any) {
|
||||
console.error(`Failed to scrape page ${p}, continuing:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
assignments: allAssignments,
|
||||
totalPages
|
||||
};
|
||||
}
|
||||
}
|
||||
58
src/types/index.ts
Normal file
58
src/types/index.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
export type AssignmentStatus =
|
||||
| 'completed'
|
||||
| 'next-week'
|
||||
| 'due-soon'
|
||||
| 'active'
|
||||
| 'overdue'
|
||||
| 'future';
|
||||
|
||||
export interface Assignment {
|
||||
id: string; // SHA-256 deterministic hash
|
||||
subject: string; // e.g. "AYT Kimya" (Turkish original)
|
||||
type: string; // e.g. "Yayın" (Turkish original)
|
||||
unit: string;
|
||||
topic: string;
|
||||
startDate: string; // raw string e.g. "20.10.2026"
|
||||
endDate: string; // raw string e.g. "26.10.2026"
|
||||
parsedStartDate: string | null; // ISO "2026-10-20"
|
||||
parsedEndDate: string | null; // ISO "2026-10-26"
|
||||
description: string; // original Turkish text
|
||||
detectedCheckDate: string | null; // e.g. "26-30 Ekim"
|
||||
status: AssignmentStatus;
|
||||
completed: boolean;
|
||||
completedAt: string | null;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export interface SubjectStat {
|
||||
subject: string;
|
||||
total: number;
|
||||
completed: number;
|
||||
active: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface DashboardStats {
|
||||
total: number;
|
||||
completed: number;
|
||||
active: number;
|
||||
checkedNextWeek: number;
|
||||
dueSoon: number;
|
||||
overdue: number;
|
||||
completionRate: number;
|
||||
bySubject: Record<string, SubjectStat>;
|
||||
}
|
||||
|
||||
export interface StudentStore {
|
||||
studentId: string;
|
||||
lastSynced: string | null;
|
||||
rememberedCredentials?: {
|
||||
studentId: string;
|
||||
password: string;
|
||||
};
|
||||
assignments: Record<string, Assignment>;
|
||||
}
|
||||
|
||||
export interface DatabaseSchema {
|
||||
students: Record<string, StudentStore>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue