fixes and patches n stuff
This commit is contained in:
parent
7c7ae8e051
commit
1af973d001
14 changed files with 571 additions and 268 deletions
499
src/server.ts
499
src/server.ts
|
|
@ -8,7 +8,7 @@ import { LocalDatabase } from './services/db';
|
|||
import { InsightService } from './services/insight';
|
||||
import { SyllabusService, DAY_NAMES } from './services/syllabus';
|
||||
import { ExamService } from './services/exam';
|
||||
import { Assignment } from './types';
|
||||
import { Assignment, ExamReportDetail } from './types';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
|
|
@ -26,7 +26,7 @@ app.set('views', viewsPath);
|
|||
// Middleware
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use(cookieParser(SESSION_SECRET));
|
||||
|
||||
// Custom Service Worker route with proper scope and no-cache headers
|
||||
app.get('/sw.js', (req: Request, res: Response) => {
|
||||
|
|
@ -49,7 +49,10 @@ app.use(
|
|||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days
|
||||
maxAge: 14 * 24 * 60 * 60 * 1000, // 14 days
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: process.env.NODE_ENV === 'production'
|
||||
}
|
||||
})
|
||||
);
|
||||
|
|
@ -70,8 +73,11 @@ 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;
|
||||
|
||||
const isAjax = req.path.startsWith('/api/') || req.xhr || req.headers.accept?.includes('application/json');
|
||||
|
||||
// Check if studentId remembered in signed cookie (tamper-proof)
|
||||
const rememberedId = req.signedCookies?.bekultur_student_id;
|
||||
if (rememberedId) {
|
||||
const creds = db.getRememberedCredentials(rememberedId);
|
||||
if (creds) {
|
||||
|
|
@ -84,17 +90,91 @@ function requireAuth(req: Request, res: Response, next: NextFunction) {
|
|||
return next();
|
||||
} else {
|
||||
res.clearCookie('bekultur_student_id');
|
||||
if (isAjax) {
|
||||
return res.status(401).json({ success: false, error: 'Session expired. Please log in again.' });
|
||||
}
|
||||
return res.redirect('/');
|
||||
}
|
||||
}).catch(() => {
|
||||
if (isAjax) {
|
||||
return res.status(401).json({ success: false, error: 'Connection error during auto-login.' });
|
||||
}
|
||||
return res.redirect('/');
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Clear unsigned or untrusted cookie if present without valid signature
|
||||
if (req.cookies?.bekultur_student_id && !rememberedId) {
|
||||
res.clearCookie('bekultur_student_id');
|
||||
}
|
||||
|
||||
if (isAjax) {
|
||||
return res.status(401).json({ success: false, error: 'Authentication required. Please log in.' });
|
||||
}
|
||||
|
||||
res.redirect('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to obtain active portal cookies from session or remembered credentials
|
||||
*/
|
||||
async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise<string | undefined> {
|
||||
if (req.session.portalCookies) {
|
||||
return req.session.portalCookies;
|
||||
}
|
||||
const creds = db.getRememberedCredentials(studentId);
|
||||
if (creds) {
|
||||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||||
if (loginRes.success) {
|
||||
req.session.portalCookies = loginRes.cookies;
|
||||
req.session.studentName = loginRes.studentName || req.session.studentName;
|
||||
return loginRes.cookies;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute scraper action with automatic session-recovery retry
|
||||
*/
|
||||
async function executeWithPortalSession<T>(
|
||||
req: Request,
|
||||
studentId: string,
|
||||
action: (cookies: string) => Promise<T>
|
||||
): Promise<T> {
|
||||
let cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||
if (!cookies) {
|
||||
throw new Error('Session expired. Please log in again.');
|
||||
}
|
||||
|
||||
try {
|
||||
return await action(cookies);
|
||||
} catch (err: any) {
|
||||
const isSessionErr =
|
||||
err?.message?.includes('Session expired') ||
|
||||
err?.message?.includes('unauthorized') ||
|
||||
err?.message?.includes('girisForm') ||
|
||||
err?.response?.status === 401 ||
|
||||
err?.response?.status === 302;
|
||||
|
||||
if (isSessionErr) {
|
||||
req.session.portalCookies = undefined;
|
||||
const creds = db.getRememberedCredentials(studentId);
|
||||
if (creds) {
|
||||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||||
if (loginRes.success) {
|
||||
req.session.portalCookies = loginRes.cookies;
|
||||
req.session.studentName = loginRes.studentName || req.session.studentName;
|
||||
return await action(loginRes.cookies);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// Routes
|
||||
// ----------------------------------------------------
|
||||
|
|
@ -108,7 +188,7 @@ app.get('/', (req: Request, res: Response) => {
|
|||
return res.redirect('/dashboard');
|
||||
}
|
||||
|
||||
const rememberedId = req.cookies.bekultur_student_id || '';
|
||||
const rememberedId = req.signedCookies?.bekultur_student_id || '';
|
||||
const error = (req.query.error as string) || null;
|
||||
|
||||
res.render('login', {
|
||||
|
|
@ -152,8 +232,11 @@ app.post('/login', async (req: Request, res: Response) => {
|
|||
if (rememberMe) {
|
||||
db.saveCredentials(studentId, password);
|
||||
res.cookie('bekultur_student_id', studentId, {
|
||||
signed: true,
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
httpOnly: true
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: process.env.NODE_ENV === 'production'
|
||||
});
|
||||
} else {
|
||||
db.clearCredentials(studentId);
|
||||
|
|
@ -183,6 +266,7 @@ app.post('/login', async (req: Request, res: Response) => {
|
|||
* POST /logout
|
||||
*/
|
||||
app.post('/logout', (req: Request, res: Response) => {
|
||||
res.clearCookie('bekultur_student_id');
|
||||
req.session.destroy(() => {
|
||||
res.redirect('/');
|
||||
});
|
||||
|
|
@ -192,6 +276,7 @@ app.post('/logout', (req: Request, res: Response) => {
|
|||
* GET /logout (convenience)
|
||||
*/
|
||||
app.get('/logout', (req: Request, res: Response) => {
|
||||
res.clearCookie('bekultur_student_id');
|
||||
req.session.destroy(() => {
|
||||
res.redirect('/');
|
||||
});
|
||||
|
|
@ -321,29 +406,11 @@ app.post('/api/exclude', requireAuth, (req: Request, res: Response) => {
|
|||
*/
|
||||
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);
|
||||
const scrapeRes = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await ScraperService.scrapeMultiplePages(cookies, studentId, 2);
|
||||
});
|
||||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||||
|
||||
const store = db.getStudentStore(studentId);
|
||||
|
|
@ -361,7 +428,8 @@ app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
|
|||
});
|
||||
} catch (err: any) {
|
||||
console.error('API sync error:', err.message);
|
||||
res.status(500).json({
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: `Sync failed: ${err.message}`
|
||||
});
|
||||
|
|
@ -374,29 +442,12 @@ app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
|
|||
*/
|
||||
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);
|
||||
const scrapeRes = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await ScraperService.scrapeMultiplePages(cookies, studentId, 20);
|
||||
});
|
||||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||||
|
||||
const store = db.getStudentStore(studentId);
|
||||
|
|
@ -415,7 +466,8 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
|
|||
});
|
||||
} catch (err: any) {
|
||||
console.error('API sync-all error:', err.message);
|
||||
res.status(500).json({
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: `Full history sync failed: ${err.message}`
|
||||
});
|
||||
|
|
@ -434,26 +486,14 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
|
|||
|
||||
// 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);
|
||||
}
|
||||
try {
|
||||
const schedule = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await ScraperService.scrapeSyllabus(cookies);
|
||||
});
|
||||
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
|
||||
syllabusStore = db.getSyllabus(studentId);
|
||||
} catch (err: any) {
|
||||
console.warn('Auto-syncing weekly syllabus note (using cached if available):', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -550,29 +590,12 @@ app.post('/api/syllabus/advisory-teacher', requireAuth, (req: Request, res: Resp
|
|||
*/
|
||||
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);
|
||||
const schedule = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await ScraperService.scrapeSyllabus(cookies);
|
||||
});
|
||||
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
|
||||
|
||||
const store = db.getSyllabus(studentId);
|
||||
|
|
@ -594,7 +617,8 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
|
|||
});
|
||||
} catch (err: any) {
|
||||
console.error('API syllabus sync error:', err.message);
|
||||
res.status(500).json({
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: `Syllabus sync failed: ${err.message}`
|
||||
});
|
||||
|
|
@ -615,30 +639,17 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) =>
|
|||
|
||||
// If not yet synced or formMeta missing, try auto-syncing
|
||||
if (!store || !store.lessons || !store.formMeta) {
|
||||
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 [privateRes, formMeta] = await Promise.all([
|
||||
try {
|
||||
const [privateRes, formMeta] = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await Promise.all([
|
||||
ScraperService.scrapePrivateLessons(cookies),
|
||||
ScraperService.fetchPrivateLessonFormMeta(studentId)
|
||||
]);
|
||||
|
||||
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
|
||||
store = db.getPrivateLessons(studentId);
|
||||
} catch (err: any) {
|
||||
console.error('Error auto-syncing private lessons:', err.message);
|
||||
}
|
||||
});
|
||||
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
|
||||
store = db.getPrivateLessons(studentId);
|
||||
} catch (err: any) {
|
||||
console.warn('Auto-syncing private lessons warning (using cached if available):', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -742,31 +753,14 @@ app.post('/api/private-lessons/request', requireAuth, async (req: Request, res:
|
|||
*/
|
||||
app.post('/api/private-lessons/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 private lessons.'
|
||||
});
|
||||
}
|
||||
|
||||
const [privateRes, formMeta] = await Promise.all([
|
||||
ScraperService.scrapePrivateLessons(cookies),
|
||||
ScraperService.fetchPrivateLessonFormMeta(studentId)
|
||||
]);
|
||||
const [privateRes, formMeta] = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await Promise.all([
|
||||
ScraperService.scrapePrivateLessons(cookies),
|
||||
ScraperService.fetchPrivateLessonFormMeta(studentId)
|
||||
]);
|
||||
});
|
||||
|
||||
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
|
||||
const store = db.getPrivateLessons(studentId);
|
||||
|
|
@ -780,7 +774,8 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res
|
|||
});
|
||||
} catch (err: any) {
|
||||
console.error('API private-lessons sync error:', err.message);
|
||||
res.status(500).json({
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: `Private lessons sync failed: ${err.message}`
|
||||
});
|
||||
|
|
@ -791,24 +786,6 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res
|
|||
// Exam Reports (Sınav Rapor) Routes
|
||||
// ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Helper to ensure active portal cookies
|
||||
*/
|
||||
async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise<string | undefined> {
|
||||
if (req.session.portalCookies) {
|
||||
return req.session.portalCookies;
|
||||
}
|
||||
const creds = db.getRememberedCredentials(studentId);
|
||||
if (creds) {
|
||||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||||
if (loginRes.success) {
|
||||
req.session.portalCookies = loginRes.cookies;
|
||||
return loginRes.cookies;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /rapor/sinav
|
||||
* Official portal alias redirect
|
||||
|
|
@ -827,21 +804,26 @@ app.get('/exams', requireAuth, async (req: Request, res: Response) => {
|
|||
|
||||
// If no cached exams or empty, sync now
|
||||
if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) {
|
||||
const cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||
if (cookies) {
|
||||
try {
|
||||
try {
|
||||
await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
const examList = await ScraperService.scrapeExamList(cookies);
|
||||
if (examList.length > 0) {
|
||||
const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id));
|
||||
const details = (await Promise.all(detailPromises)).filter(
|
||||
(d): d is NonNullable<typeof d> => d !== null
|
||||
);
|
||||
db.saveExamReports(studentId, details);
|
||||
examStore = db.getExamReports(studentId);
|
||||
const details: ExamReportDetail[] = [];
|
||||
const batchSize = 3;
|
||||
for (let i = 0; i < examList.length; i += batchSize) {
|
||||
const batch = examList.slice(i, i + batchSize);
|
||||
const batchRes = await Promise.all(batch.map(item => ScraperService.scrapeExamDetail(cookies, item.id)));
|
||||
batchRes.forEach(d => { if (d) details.push(d); });
|
||||
}
|
||||
if (details.length > 0) {
|
||||
db.saveExamReports(studentId, details);
|
||||
examStore = db.getExamReports(studentId);
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Initial exam scrape error:', err.message);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.warn('Initial exam scrape warning (using cached if available):', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -884,13 +866,17 @@ app.get('/api/exams/:id', requireAuth, async (req: Request, res: Response) => {
|
|||
let exam = examStore?.reports?.[examId];
|
||||
|
||||
if (!exam) {
|
||||
const cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||
if (cookies) {
|
||||
const fetched = await ScraperService.scrapeExamDetail(cookies, examId);
|
||||
if (fetched) {
|
||||
db.saveExamReports(studentId, [fetched]);
|
||||
examStore = db.getExamReports(studentId);
|
||||
}
|
||||
try {
|
||||
await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
const fetched = await ScraperService.scrapeExamDetail(cookies, examId);
|
||||
if (fetched) {
|
||||
db.saveExamReports(studentId, [fetched]);
|
||||
examStore = db.getExamReports(studentId);
|
||||
}
|
||||
return fetched;
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.warn(`Could not fetch exam detail ${examId}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -916,15 +902,38 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
|
|||
const ogrenciDonemId = (req.query.ogrenciDonemId as string) || '';
|
||||
const tip = ((req.query.tip as string) || 'Y').toUpperCase() as 'D' | 'Y' | 'B';
|
||||
|
||||
const cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||
if (!cookies) {
|
||||
return res.status(401).json({ success: false, error: 'Session expired' });
|
||||
const cacheKey = `${examId}_${tip}`;
|
||||
|
||||
// If specific subject requested, fetch directly with portal session
|
||||
if (dersId && ogrenciDonemId) {
|
||||
try {
|
||||
const questions = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip);
|
||||
});
|
||||
return res.json({ success: true, questions });
|
||||
} catch (err: any) {
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
return res.status(status).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
// If specific subject requested, fetch directly
|
||||
if (dersId && ogrenciDonemId) {
|
||||
const questions = await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip);
|
||||
return res.json({ success: true, questions });
|
||||
// Check if all questions for this exam and tip are cached in db.json
|
||||
const cachedQuestions = db.getExamQuestions(studentId, cacheKey);
|
||||
if (cachedQuestions && cachedQuestions.length > 0) {
|
||||
const subjectsMap: Record<string, { subjectName: string; subjectId: string; questions: any[] }> = {};
|
||||
cachedQuestions.forEach(q => {
|
||||
const sName = q.subjectName || 'Genel';
|
||||
if (!subjectsMap[sName]) {
|
||||
subjectsMap[sName] = { subjectName: sName, subjectId: q.subjectId || '', questions: [] };
|
||||
}
|
||||
subjectsMap[sName].questions.push(q);
|
||||
});
|
||||
return res.json({
|
||||
success: true,
|
||||
totalMistakes: cachedQuestions.length,
|
||||
subjects: Object.values(subjectsMap),
|
||||
cached: true
|
||||
});
|
||||
}
|
||||
|
||||
// Otherwise, inspect exam details and fetch questions for all subjects with mistakes
|
||||
|
|
@ -935,37 +944,55 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
|
|||
return res.status(404).json({ success: false, error: 'Exam detail not cached' });
|
||||
}
|
||||
|
||||
const subjectQuestionsList: Array<{
|
||||
subjectName: string;
|
||||
subjectId: string;
|
||||
questions: any[];
|
||||
}> = [];
|
||||
try {
|
||||
const subjectQuestionsList: Array<{
|
||||
subjectName: string;
|
||||
subjectId: string;
|
||||
questions: any[];
|
||||
}> = [];
|
||||
const allScrapedQuestions: any[] = [];
|
||||
|
||||
for (const subject of exam.subjects) {
|
||||
const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true;
|
||||
if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) {
|
||||
const q = await ScraperService.scrapeExamQuestions(
|
||||
cookies,
|
||||
examId,
|
||||
subject.ogrenciDonemId,
|
||||
subject.subjectId,
|
||||
tip
|
||||
);
|
||||
if (q.length > 0) {
|
||||
subjectQuestionsList.push({
|
||||
subjectName: subject.subjectName,
|
||||
subjectId: subject.subjectId,
|
||||
questions: q
|
||||
});
|
||||
await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
for (const subject of exam.subjects) {
|
||||
const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true;
|
||||
if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) {
|
||||
const q = await ScraperService.scrapeExamQuestions(
|
||||
cookies,
|
||||
examId,
|
||||
subject.ogrenciDonemId,
|
||||
subject.subjectId,
|
||||
tip
|
||||
);
|
||||
if (q.length > 0) {
|
||||
q.forEach(item => {
|
||||
item.subjectName = subject.subjectName;
|
||||
allScrapedQuestions.push(item);
|
||||
});
|
||||
subjectQuestionsList.push({
|
||||
subjectName: subject.subjectName,
|
||||
subjectId: subject.subjectId,
|
||||
questions: q
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0),
|
||||
subjects: subjectQuestionsList
|
||||
});
|
||||
if (allScrapedQuestions.length > 0) {
|
||||
db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0),
|
||||
subjects: subjectQuestionsList
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch questions:', err.message);
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
@ -981,15 +1008,16 @@ app.get('/api/exams/:id/weaknesses', requireAuth, async (req: Request, res: Resp
|
|||
return res.json({ success: true, weaknesses: cached });
|
||||
}
|
||||
|
||||
const cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||
if (!cookies) {
|
||||
return res.status(401).json({ success: false, error: 'Session expired' });
|
||||
try {
|
||||
const weaknesses = await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
return await ScraperService.scrapeTopicWeaknesses(cookies, examId);
|
||||
});
|
||||
db.saveTopicWeaknesses(studentId, examId, weaknesses);
|
||||
res.json({ success: true, weaknesses });
|
||||
} catch (err: any) {
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({ success: false, error: err.message });
|
||||
}
|
||||
|
||||
const weaknesses = await ScraperService.scrapeTopicWeaknesses(cookies, examId);
|
||||
db.saveTopicWeaknesses(studentId, examId, weaknesses);
|
||||
|
||||
res.json({ success: true, weaknesses });
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
@ -998,27 +1026,29 @@ app.get('/api/exams/:id/weaknesses', requireAuth, async (req: Request, res: Resp
|
|||
*/
|
||||
app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => {
|
||||
const studentId = req.session.studentId!;
|
||||
const cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||
|
||||
if (!cookies) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Session expired. Please log in again to sync exams.'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const examList = await ScraperService.scrapeExamList(cookies);
|
||||
if (!examList || examList.length === 0) {
|
||||
return res.json({ success: true, count: 0, message: 'No exams found on portal.' });
|
||||
}
|
||||
await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||
const examList = await ScraperService.scrapeExamList(cookies);
|
||||
if (!examList || examList.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id));
|
||||
const details = (await Promise.all(detailPromises)).filter(
|
||||
(d): d is NonNullable<typeof d> => d !== null
|
||||
);
|
||||
// Batch requests in chunks of 3 to avoid overwhelming portal
|
||||
const details: ExamReportDetail[] = [];
|
||||
const batchSize = 3;
|
||||
for (let i = 0; i < examList.length; i += batchSize) {
|
||||
const batch = examList.slice(i, i + batchSize);
|
||||
const batchRes = await Promise.all(batch.map(item => ScraperService.scrapeExamDetail(cookies, item.id)));
|
||||
batchRes.forEach(d => { if (d) details.push(d); });
|
||||
}
|
||||
|
||||
if (details.length > 0) {
|
||||
db.saveExamReports(studentId, details);
|
||||
}
|
||||
return details;
|
||||
});
|
||||
|
||||
db.saveExamReports(studentId, details);
|
||||
const updatedStore = db.getExamReports(studentId);
|
||||
const rawDetails = updatedStore?.reports ? Object.values(updatedStore.reports) : [];
|
||||
const processed = ExamService.computeDeltasAndRatings(rawDetails);
|
||||
|
|
@ -1033,7 +1063,8 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) =>
|
|||
});
|
||||
} catch (err: any) {
|
||||
console.error('API exams sync error:', err.message);
|
||||
res.status(500).json({
|
||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: `Exams sync failed: ${err.message}`
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import {
|
||||
DatabaseSchema,
|
||||
StudentStore,
|
||||
|
|
@ -9,11 +10,54 @@ import {
|
|||
PrivateLessonsStore,
|
||||
ExamReportDetail,
|
||||
ExamStore,
|
||||
ExamTopicWeakness
|
||||
ExamTopicWeakness,
|
||||
ExamQuestionItem
|
||||
} from '../types';
|
||||
|
||||
const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json');
|
||||
|
||||
// Derive 32-byte AES key from environment secret
|
||||
function getEncryptionKey(): Buffer {
|
||||
const secret = process.env.ENCRYPTION_SECRET || process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
|
||||
return crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
|
||||
}
|
||||
|
||||
function encryptCredential(plaintext: string): string {
|
||||
try {
|
||||
const key = getEncryptionKey();
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
const authTag = cipher.getAuthTag().toString('hex');
|
||||
return `enc:${iv.toString('hex')}:${authTag}:${encrypted}`;
|
||||
} catch (err) {
|
||||
console.error('Failed to encrypt credential:', err);
|
||||
return plaintext;
|
||||
}
|
||||
}
|
||||
|
||||
function decryptCredential(stored: string): string {
|
||||
if (!stored || !stored.startsWith('enc:')) {
|
||||
// Legacy plaintext support
|
||||
return stored;
|
||||
}
|
||||
try {
|
||||
const parts = stored.split(':');
|
||||
if (parts.length !== 4) return stored;
|
||||
const [, ivHex, authTagHex, ciphertextHex] = parts;
|
||||
const key = getEncryptionKey();
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
|
||||
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
||||
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
||||
decrypted += decipher.final('utf8');
|
||||
return decrypted;
|
||||
} catch (err) {
|
||||
console.error('Failed to decrypt credential:', err);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalDatabase {
|
||||
private static instance: LocalDatabase;
|
||||
private cache: DatabaseSchema = { students: {} };
|
||||
|
|
@ -60,7 +104,7 @@ export class LocalDatabase {
|
|||
|
||||
private save(): void {
|
||||
try {
|
||||
const tmpFile = `${DB_FILE}.tmp`;
|
||||
const tmpFile = `${DB_FILE}.${process.pid}.${Date.now()}.tmp`;
|
||||
fs.writeFileSync(tmpFile, JSON.stringify(this.cache, null, 2), 'utf-8');
|
||||
fs.renameSync(tmpFile, DB_FILE);
|
||||
} catch (err) {
|
||||
|
|
@ -138,7 +182,8 @@ export class LocalDatabase {
|
|||
|
||||
public saveCredentials(studentId: string, password: string): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
student.rememberedCredentials = { studentId, password };
|
||||
const encryptedPassword = encryptCredential(password);
|
||||
student.rememberedCredentials = { studentId, password: encryptedPassword };
|
||||
this.save();
|
||||
}
|
||||
|
||||
|
|
@ -150,7 +195,11 @@ export class LocalDatabase {
|
|||
|
||||
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
|
||||
const student = this.cache.students[studentId];
|
||||
return student?.rememberedCredentials || null;
|
||||
if (!student?.rememberedCredentials) return null;
|
||||
return {
|
||||
studentId: student.rememberedCredentials.studentId,
|
||||
password: decryptCredential(student.rememberedCredentials.password)
|
||||
};
|
||||
}
|
||||
|
||||
public saveSyllabus(
|
||||
|
|
@ -285,4 +334,26 @@ export class LocalDatabase {
|
|||
const student = this.cache.students[studentId];
|
||||
return student?.exams?.topicWeaknesses?.[examId] || null;
|
||||
}
|
||||
|
||||
public saveExamQuestions(studentId: string, examId: string, questions: ExamQuestionItem[]): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
if (!student.exams) {
|
||||
student.exams = {
|
||||
lastSynced: new Date().toISOString(),
|
||||
reports: {},
|
||||
topicWeaknesses: {},
|
||||
questions: {}
|
||||
};
|
||||
}
|
||||
if (!student.exams.questions) {
|
||||
student.exams.questions = {};
|
||||
}
|
||||
student.exams.questions[examId] = questions;
|
||||
this.save();
|
||||
}
|
||||
|
||||
public getExamQuestions(studentId: string, examId: string): ExamQuestionItem[] | null {
|
||||
const student = this.cache.students[studentId];
|
||||
return student?.exams?.questions?.[examId] || null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import { DAY_NAMES } from './syllabus';
|
|||
const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com';
|
||||
const BILGI_BASE_URL = 'https://bilgi.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';
|
||||
const REQUEST_TIMEOUT_MS = 12000;
|
||||
|
||||
export interface LoginResult {
|
||||
success: boolean;
|
||||
|
|
@ -77,6 +78,7 @@ export class ScraperService {
|
|||
headers: {
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 0,
|
||||
validateStatus: () => true // Allow handling redirects manually
|
||||
});
|
||||
|
|
@ -112,6 +114,15 @@ export class ScraperService {
|
|||
|
||||
cookies = this.mergeCookies(cookies, postRes.headers['set-cookie']);
|
||||
|
||||
// Check if server error
|
||||
if (postRes.status >= 500) {
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: `School portal returned error ${postRes.status}. The portal may be under maintenance.`
|
||||
};
|
||||
}
|
||||
|
||||
// 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 === '');
|
||||
|
|
@ -176,6 +187,7 @@ export class ScraperService {
|
|||
'Cookie': cookies,
|
||||
'Referer': `${BASE_URL}/`
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
|
|
@ -338,6 +350,7 @@ export class ScraperService {
|
|||
'Cookie': cookies,
|
||||
'Referer': `${BASE_URL}/`
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
|
|
@ -419,6 +432,7 @@ export class ScraperService {
|
|||
'User-Agent': USER_AGENT,
|
||||
'Cookie': cookies
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
|
|
@ -504,6 +518,7 @@ export class ScraperService {
|
|||
try {
|
||||
const client = axios.create({
|
||||
headers: { 'User-Agent': USER_AGENT },
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
|
|
@ -559,7 +574,8 @@ export class ScraperService {
|
|||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'User-Agent': USER_AGENT
|
||||
}
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -592,7 +608,8 @@ export class ScraperService {
|
|||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'User-Agent': USER_AGENT
|
||||
}
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -643,6 +660,7 @@ export class ScraperService {
|
|||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 5,
|
||||
validateStatus: () => true
|
||||
}
|
||||
|
|
@ -686,6 +704,7 @@ export class ScraperService {
|
|||
'Cookie': cookies,
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 5,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
|
@ -725,6 +744,7 @@ export class ScraperService {
|
|||
'Cookie': cookies,
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 5,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
|
@ -893,6 +913,7 @@ export class ScraperService {
|
|||
'Cookie': cookies,
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 5,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
|
@ -959,6 +980,7 @@ export class ScraperService {
|
|||
'Cookie': cookies,
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 5,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
|
@ -984,6 +1006,7 @@ export class ScraperService {
|
|||
'Cookie': updatedCookies,
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
maxRedirects: 5,
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
|
|
|||
|
|
@ -192,6 +192,7 @@ export interface ExamStore {
|
|||
lastSynced: string;
|
||||
reports: Record<string, ExamReportDetail>;
|
||||
topicWeaknesses?: Record<string, ExamTopicWeakness[]>;
|
||||
questions?: Record<string, ExamQuestionItem[]>;
|
||||
}
|
||||
|
||||
export interface StudentStore {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue