Add Syllabus (Ders Programı) with station filtering and weekly auto-refresh
This commit is contained in:
parent
8acc77e441
commit
d0fd394fbd
10 changed files with 1196 additions and 3 deletions
149
src/server.ts
149
src/server.ts
|
|
@ -6,6 +6,7 @@ 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();
|
||||
|
|
@ -406,6 +407,154 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
|
|||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 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, () => {
|
||||
|
|
|
|||
|
|
@ -142,4 +142,44 @@ export class LocalDatabase {
|
|||
const student = this.cache.students[studentId];
|
||||
return student?.rememberedCredentials || null;
|
||||
}
|
||||
|
||||
public saveSyllabus(
|
||||
studentId: string,
|
||||
weekId: string,
|
||||
weekRange: string,
|
||||
schedule: Record<number, any>
|
||||
): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
const existingStation = student.syllabus?.selectedStation || null;
|
||||
|
||||
student.syllabus = {
|
||||
weekId,
|
||||
weekRange,
|
||||
selectedStation: existingStation,
|
||||
lastSynced: new Date().toISOString(),
|
||||
schedule
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
|
||||
public setStudentStation(studentId: string, station: string | null): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
if (!student.syllabus) {
|
||||
student.syllabus = {
|
||||
weekId: '',
|
||||
weekRange: '',
|
||||
selectedStation: station,
|
||||
lastSynced: null,
|
||||
schedule: {}
|
||||
};
|
||||
} else {
|
||||
student.syllabus.selectedStation = station;
|
||||
}
|
||||
this.save();
|
||||
}
|
||||
|
||||
public getSyllabus(studentId: string): any {
|
||||
const student = this.cache.students[studentId];
|
||||
return student?.syllabus || null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import axios from 'axios';
|
||||
import * as cheerio from 'cheerio';
|
||||
import crypto from 'crypto';
|
||||
import { Assignment } from '../types';
|
||||
import { Assignment, Lesson } from '../types';
|
||||
import { InsightService } from './insight';
|
||||
import { DAY_NAMES } from './syllabus';
|
||||
|
||||
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';
|
||||
|
|
@ -304,4 +305,90 @@ export class ScraperService {
|
|||
totalPages
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape the 5-day syllabus (Ders Programı) from the portal
|
||||
*/
|
||||
public static async scrapeSyllabus(cookies: string): Promise<Record<number, Lesson[]>> {
|
||||
const weeklySchedule: Record<number, Lesson[]> = {
|
||||
1: [],
|
||||
2: [],
|
||||
3: [],
|
||||
4: [],
|
||||
5: []
|
||||
};
|
||||
|
||||
for (let day = 1; day <= 5; day++) {
|
||||
try {
|
||||
const url = `${BASE_URL}/dersprogrami?gun=${day}`;
|
||||
const res = await axios.get(url, {
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT,
|
||||
'Cookie': cookies,
|
||||
'Referer': `${BASE_URL}/`
|
||||
},
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
if (res.status === 200 && typeof res.data === 'string') {
|
||||
const $ = cheerio.load(res.data);
|
||||
const dayLessons: Lesson[] = [];
|
||||
|
||||
$('.col-md-8 .kltr-card').each((_, cardEl) => {
|
||||
const card = $(cardEl);
|
||||
const periodText = card.find('h5.card-title').text().trim();
|
||||
if (!periodText) return;
|
||||
|
||||
const pNumMatch = periodText.match(/(\d+)/);
|
||||
const periodNumber = pNumMatch ? parseInt(pNumMatch[1], 10) : 0;
|
||||
|
||||
const pTags = card.find('p');
|
||||
const subject = $(pTags[0]).text().trim();
|
||||
const teacher = $(pTags[1]).text().trim();
|
||||
const time = $(pTags[2]).text().trim();
|
||||
|
||||
let stationRaw = '';
|
||||
for (let i = 3; i < pTags.length; i++) {
|
||||
const text = $(pTags[i]).text().trim();
|
||||
if (text && /[İiIı]st/i.test(text)) {
|
||||
stationRaw = text;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const station = stationRaw ? stationRaw : null;
|
||||
const teacherPhoto = card.find('img.profil-resmi').attr('src') || null;
|
||||
|
||||
let startTime = '';
|
||||
let endTime = '';
|
||||
if (time && time.includes('-')) {
|
||||
const parts = time.split('-').map(t => t.trim());
|
||||
startTime = parts[0] || '';
|
||||
endTime = parts[1] || '';
|
||||
}
|
||||
|
||||
dayLessons.push({
|
||||
period: periodText,
|
||||
periodNumber,
|
||||
subject,
|
||||
teacher,
|
||||
teacherPhoto,
|
||||
startTime,
|
||||
endTime,
|
||||
time,
|
||||
station,
|
||||
day,
|
||||
dayName: DAY_NAMES[day] || ''
|
||||
});
|
||||
});
|
||||
|
||||
weeklySchedule[day] = dayLessons;
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error(`Failed to scrape syllabus for day ${day}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return weeklySchedule;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
175
src/services/syllabus.ts
Normal file
175
src/services/syllabus.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { Lesson } from '../types';
|
||||
|
||||
export const DAY_NAMES: Record<number, string> = {
|
||||
1: 'Pazartesi',
|
||||
2: 'Salı',
|
||||
3: 'Çarşamba',
|
||||
4: 'Perşembe',
|
||||
5: 'Cuma'
|
||||
};
|
||||
|
||||
export class SyllabusService {
|
||||
/**
|
||||
* Compute ISO week and Monday-Friday date range for a given date
|
||||
*/
|
||||
public static getWeekMetadata(refDate: Date = new Date()): { weekId: string; weekRange: string; mondayDate: Date } {
|
||||
const d = new Date(refDate);
|
||||
// Find Monday of the current week
|
||||
const day = d.getDay(); // 0 is Sunday, 1 is Monday
|
||||
const diffToMonday = day === 0 ? -6 : 1 - day;
|
||||
const monday = new Date(d);
|
||||
monday.setDate(d.getDate() + diffToMonday);
|
||||
monday.setHours(0, 0, 0, 0);
|
||||
|
||||
const friday = new Date(monday);
|
||||
friday.setDate(monday.getDate() + 4);
|
||||
|
||||
// Compute ISO week number
|
||||
const target = new Date(monday);
|
||||
const dayNr = (target.getDay() + 6) % 7;
|
||||
target.setDate(target.getDate() - dayNr + 3);
|
||||
const firstThursday = target.valueOf();
|
||||
target.setMonth(0, 1);
|
||||
if (target.getDay() !== 4) {
|
||||
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
|
||||
}
|
||||
const weekNumber = 1 + Math.ceil((firstThursday - target.valueOf()) / 604800000);
|
||||
const year = monday.getFullYear();
|
||||
|
||||
const weekId = `${year}-W${String(weekNumber).padStart(2, '0')}`;
|
||||
|
||||
const fmtDate = (date: Date) => {
|
||||
const dd = String(date.getDate()).padStart(2, '0');
|
||||
const mm = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const yyyy = date.getFullYear();
|
||||
return `${dd}.${mm}.${yyyy}`;
|
||||
};
|
||||
|
||||
const weekRange = `${fmtDate(monday)} - ${fmtDate(friday)}`;
|
||||
|
||||
return { weekId, weekRange, mondayDate: monday };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize station representations (e.g. "İst4", "ist-4", "4" -> "İst-4")
|
||||
*/
|
||||
public static normalizeStation(stationStr: string | null | undefined): string | null {
|
||||
if (!stationStr) return null;
|
||||
const s = stationStr.trim().toLowerCase();
|
||||
if (s === 'all') return 'all';
|
||||
const match = s.match(/([1-5])/);
|
||||
if (match) {
|
||||
return `İst-${match[1]}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter lessons for a specific station (or show all stations without portal duplicate garbage)
|
||||
*/
|
||||
public static filterLessonsForStation(rawLessons: Lesson[], selectedStation: string | null): Lesson[] {
|
||||
if (!rawLessons || !rawLessons.length) return [];
|
||||
|
||||
const normTarget = this.normalizeStation(selectedStation);
|
||||
|
||||
// Group lessons by periodNumber
|
||||
const byPeriod: Record<number, Lesson[]> = {};
|
||||
for (const item of rawLessons) {
|
||||
if (!byPeriod[item.periodNumber]) {
|
||||
byPeriod[item.periodNumber] = [];
|
||||
}
|
||||
byPeriod[item.periodNumber].push(item);
|
||||
}
|
||||
|
||||
const result: Lesson[] = [];
|
||||
const sortedPeriodKeys = Object.keys(byPeriod).map(Number).sort((a, b) => a - b);
|
||||
|
||||
for (const pNum of sortedPeriodKeys) {
|
||||
const periodGroup = byPeriod[pNum];
|
||||
|
||||
// Check if this period has station-based lessons
|
||||
const stationLessons = periodGroup.filter(l => l.station !== null);
|
||||
|
||||
if (stationLessons.length > 0) {
|
||||
if (normTarget && normTarget !== 'all') {
|
||||
// Find the lesson matching the student's assigned station
|
||||
const matched = stationLessons.find(l => this.normalizeStation(l.station) === normTarget);
|
||||
if (matched) {
|
||||
result.push(matched);
|
||||
} else {
|
||||
// Fallback: if student station not in list, show first available
|
||||
result.push(stationLessons[0]);
|
||||
}
|
||||
} else {
|
||||
// If "All Stations" selected: keep unique station lessons (one per station)
|
||||
const seenStations = new Set<string>();
|
||||
for (const sl of stationLessons) {
|
||||
const stNorm = this.normalizeStation(sl.station) || sl.station || '';
|
||||
if (!seenStations.has(stNorm)) {
|
||||
seenStations.add(stNorm);
|
||||
result.push(sl);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Whole-class lesson (no stations): deduplicate if portal printed multiple copies
|
||||
const seenKeys = new Set<string>();
|
||||
for (const cl of periodGroup) {
|
||||
const key = `${cl.periodNumber}|${cl.subject}|${cl.teacher}|${cl.time}`;
|
||||
if (!seenKeys.has(key)) {
|
||||
seenKeys.add(key);
|
||||
result.push(cl);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine current active lesson or upcoming next lesson
|
||||
*/
|
||||
public static getCurrentLessonStatus(
|
||||
dayLessons: Lesson[],
|
||||
currentDayNumber: number,
|
||||
refDate: Date = new Date()
|
||||
): { currentLesson: Lesson | null; nextLesson: Lesson | null; statusText: string | null } {
|
||||
const todayDay = refDate.getDay(); // 1 = Mon, ..., 5 = Fri
|
||||
if (todayDay !== currentDayNumber) {
|
||||
return { currentLesson: null, nextLesson: null, statusText: null };
|
||||
}
|
||||
|
||||
const nowMinutes = refDate.getHours() * 60 + refDate.getMinutes();
|
||||
|
||||
let current: Lesson | null = null;
|
||||
let next: Lesson | null = null;
|
||||
|
||||
for (const l of dayLessons) {
|
||||
if (!l.startTime || !l.endTime) continue;
|
||||
const [sh, sm] = l.startTime.split(':').map(Number);
|
||||
const [eh, em] = l.endTime.split(':').map(Number);
|
||||
|
||||
const startMin = sh * 60 + sm;
|
||||
const endMin = eh * 60 + em;
|
||||
|
||||
if (nowMinutes >= startMin && nowMinutes <= endMin) {
|
||||
current = l;
|
||||
break;
|
||||
} else if (nowMinutes < startMin) {
|
||||
if (!next) {
|
||||
next = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let statusText: string | null = null;
|
||||
if (current) {
|
||||
statusText = `Now in session: ${current.period} — ${current.subject} (${current.time})`;
|
||||
} else if (next) {
|
||||
statusText = `Next up: ${next.period} — ${next.subject} at ${next.startTime}`;
|
||||
}
|
||||
|
||||
return { currentLesson: current, nextLesson: next, statusText };
|
||||
}
|
||||
}
|
||||
|
|
@ -45,6 +45,31 @@ export interface DashboardStats {
|
|||
bySubject: Record<string, SubjectStat>;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// Syllabus (Ders Programı) Types
|
||||
// ----------------------------------------------------
|
||||
export interface Lesson {
|
||||
period: string; // e.g. "1. Ders"
|
||||
periodNumber: number; // e.g. 1
|
||||
subject: string; // e.g. "TYT Kimya"
|
||||
teacher: string; // e.g. "ÜLKÜ ESEN"
|
||||
teacherPhoto: string | null; // image url
|
||||
startTime: string; // "09:30"
|
||||
endTime: string; // "10:05"
|
||||
time: string; // "09:30 - 10:05"
|
||||
station: string | null; // "İst1", "İst2", ..., null for whole-class
|
||||
day: number; // 1 = Pazartesi ... 5 = Cuma
|
||||
dayName: string; // "Pazartesi" ... "Cuma"
|
||||
}
|
||||
|
||||
export interface SyllabusStore {
|
||||
weekId: string; // e.g. "2026-W43"
|
||||
weekRange: string; // e.g. "19.10.2026 - 23.10.2026"
|
||||
selectedStation: string | null; // e.g. "İst-4" or null/all
|
||||
lastSynced: string | null;
|
||||
schedule: Record<number, Lesson[]>; // day (1..5) -> raw lessons
|
||||
}
|
||||
|
||||
export interface StudentStore {
|
||||
studentId: string;
|
||||
lastSynced: string | null;
|
||||
|
|
@ -53,6 +78,7 @@ export interface StudentStore {
|
|||
password: string;
|
||||
};
|
||||
assignments: Record<string, Assignment>;
|
||||
syllabus?: SyllabusStore;
|
||||
}
|
||||
|
||||
export interface DatabaseSchema {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue