diff --git a/Dockerfile b/Dockerfile index d3ae1fd..dbacf51 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ FROM node:18-alpine AS builder WORKDIR /app -RUN apk add --no-cache python3 make g++ +RUN apk add --no-cache python3 make g++ tzdata COPY package*.json ./ RUN npm ci @@ -25,8 +25,11 @@ FROM node:18-alpine AS runner WORKDIR /app +RUN apk add --no-cache tzdata + ENV NODE_ENV=production ENV PORT=3000 +ENV TZ=Europe/Istanbul COPY package*.json ./ COPY --from=builder /app/node_modules ./node_modules diff --git a/docker-compose.yml b/docker-compose.yml index 06c6613..76766e6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,7 @@ services: restart: unless-stopped environment: - PORT=3000 + - TZ=Europe/Istanbul - SESSION_SECRET=${SESSION_SECRET:-} - ENCRYPTION_SECRET=${ENCRYPTION_SECRET:-} - NODE_ENV=production diff --git a/public/js/exams.js b/public/js/exams.js index d0ac813..106d5ba 100644 --- a/public/js/exams.js +++ b/public/js/exams.js @@ -435,6 +435,7 @@ document.addEventListener('DOMContentLoaded', () => { const isWrong = q.status === 'wrong'; const studentClass = isWrong ? 'answer-student-wrong' : 'answer-student-empty'; const studentText = isWrong ? q.studentAnswer : t('exams.emptyAnswerText'); + const imgSrc = toProxiedImageUrl(q.imageUrl); html += `
@@ -453,10 +454,10 @@ document.addEventListener('DOMContentLoaded', () => {
${ - q.imageUrl + imgSrc ? `
- Soru ${q.questionNumber} + Soru ${q.questionNumber}
` : `
${escapeHtml(t('exams.noImage'))}
` @@ -503,8 +504,17 @@ document.addEventListener('DOMContentLoaded', () => { } // ---------------------------------------------------- - // Utility: Escape HTML + // Utility: Proxy Portal Images & Escape HTML // ---------------------------------------------------- + function toProxiedImageUrl(rawUrl) { + if (!rawUrl) return ''; + if (rawUrl.startsWith('/api/image-proxy?url=')) return rawUrl; + if (rawUrl.includes('ozelbursakulturokullari.com')) { + return `/api/image-proxy?url=${encodeURIComponent(rawUrl)}`; + } + return rawUrl; + } + function escapeHtml(str) { if (!str) return ''; return str diff --git a/public/sw.js b/public/sw.js index bd6063e..d9ff697 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,4 +1,4 @@ -const CACHE_NAME = 'bekultur-v3'; +const CACHE_NAME = 'bekultur-v4'; const STATIC_ASSETS = [ '/', @@ -57,19 +57,52 @@ self.addEventListener('fetch', (event) => { const url = new URL(req.url); - // Allow caching question images from panel.ozelbursakulturokullari.com - const isQuestionImage = - url.origin.includes('ozelbursakulturokullari.com') && - (url.pathname.endsWith('.png') || url.pathname.endsWith('.jpg') || url.pathname.endsWith('.jpeg') || url.pathname.includes('/soru/')); + // Check if this is an E-Kültür portal image (either direct or via same-origin proxy) + const isDirectPortalAsset = + url.hostname === 'ozelbursakulturokullari.com' || + url.hostname.endsWith('.ozelbursakulturokullari.com'); - // Ignore cross-origin external analytics or fonts - if (url.origin !== self.location.origin && !isQuestionImage) { + const isProxiedImage = + url.origin === self.location.origin && + url.pathname === '/api/image-proxy'; + + // Ignore unrelated cross-origin requests + if (url.origin !== self.location.origin && !isDirectPortalAsset) { return; } - // 1. Static Assets & Question Images -> Cache-First + // 1. Portal Images (Direct or Proxied) -> Route via /api/image-proxy, Cache Verified 200 OK Images + if (isDirectPortalAsset || isProxiedImage) { + const proxyUrl = isDirectPortalAsset + ? `${self.location.origin}/api/image-proxy?url=${encodeURIComponent(req.url)}` + : req.url; + const proxyReq = new Request(proxyUrl, { credentials: 'same-origin' }); + + event.respondWith( + caches.match(proxyReq).then((cachedResponse) => { + if (cachedResponse && cachedResponse.status === 200) { + return cachedResponse; + } + return fetch(proxyReq) + .then((networkResponse) => { + if (networkResponse && networkResponse.ok && networkResponse.status === 200) { + const clone = networkResponse.clone(); + caches.open(CACHE_NAME).then((cache) => cache.put(proxyReq, clone)); + } + return networkResponse; + }) + .catch(async () => { + const fallback = await caches.match(proxyReq); + if (fallback) return fallback; + return new Response('', { status: 404, statusText: 'Image unavailable offline' }); + }); + }) + ); + return; + } + + // 2. Local Static Assets -> Cache-First (only caching verified 200 OK responses) const isStatic = - isQuestionImage || url.pathname.startsWith('/css/') || url.pathname.startsWith('/js/') || url.pathname.startsWith('/icons/') || @@ -81,25 +114,22 @@ self.addEventListener('fetch', (event) => { if (isStatic) { event.respondWith( caches.match(req).then((cachedResponse) => { - if (cachedResponse) { + if (cachedResponse && cachedResponse.status === 200) { return cachedResponse; } return fetch(req).then((networkResponse) => { - if (networkResponse && (networkResponse.status === 200 || networkResponse.type === 'opaque')) { + if (networkResponse && networkResponse.ok && networkResponse.status === 200) { const clone = networkResponse.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(req, clone)); } return networkResponse; - }).catch(() => { - // If question image fails offline and not cached, return empty placeholder - return new Response('', { status: 404, statusText: 'Not found offline' }); }); }) ); return; } - // 2. Navigation Pages & API GETs -> Network-First with Cache Fallback + // 3. Navigation Pages & API GETs -> Network-First with Cache Fallback event.respondWith( fetch(req) .then((networkResponse) => { diff --git a/src/server.ts b/src/server.ts index e23b4b2..b9fbc75 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,8 +1,17 @@ +import './utils/time'; +import { + toIstanbulIsoString, + formatIstanbulTime, + formatIstanbulDate, + getIstanbulParts, + isBeforeCurrentMondayInIstanbul +} from './utils/time'; import express, { Request, Response, NextFunction } from 'express'; import session from 'express-session'; import cookieParser from 'cookie-parser'; import helmet from 'helmet'; import rateLimit from 'express-rate-limit'; +import axios from 'axios'; import path from 'path'; import dotenv from 'dotenv'; import { ScraperService } from './services/scraper'; @@ -49,10 +58,15 @@ app.use( imgSrc: [ "'self'", 'data:', + 'blob:', + 'https://*.ozelbursakulturokullari.com', + 'http://*.ozelbursakulturokullari.com' + ], + connectSrc: [ + "'self'", 'https://*.ozelbursakulturokullari.com', 'http://*.ozelbursakulturokullari.com' ], - connectSrc: ["'self'"], fontSrc: ["'self'", 'data:'], objectSrc: ["'none'"], frameAncestors: ["'none'"], @@ -89,6 +103,10 @@ app.use((req: Request, res: Response, next: NextFunction) => { res.locals.t = t; res.locals.i18nJson = JSON.stringify(getClientDictionary(lang)); res.locals.activePage = ''; + res.locals.formatTime = (val: any) => formatIstanbulTime(val, lang); + res.locals.formatDate = (val: any) => formatIstanbulDate(val, lang); + res.locals.istanbulDayOfWeek = getIstanbulParts().dayOfWeek; + res.locals.proxyImage = (url: string | null | undefined) => ScraperService.toProxiedImageUrl(url) || ''; next(); }); @@ -111,7 +129,8 @@ app.use(express.static(publicPath)); const db = LocalDatabase.getInstance(); const sessionStore = new SQLiteSessionStore({ db: db.getSqliteDb(), - ttlMs: 14 * 24 * 60 * 60 * 1000 + ttlMs: 14 * 24 * 60 * 60 * 1000, + pruneIntervalMs: require.main === module && process.env.NODE_ENV !== 'test' ? 15 * 60 * 1000 : 0 }); app.use( @@ -130,6 +149,65 @@ app.use( }) ); +// Same-Origin Image Proxy for E-Kültür Portal Images (fixes PWA Mixed Content, 403 HTTP, & SW CORS caching) +app.get('/api/image-proxy', async (req: Request, res: Response) => { + const rawUrl = typeof req.query.url === 'string' ? req.query.url.trim() : ''; + if (!rawUrl) { + return res.status(400).send('Missing url parameter'); + } + + const normalized = ScraperService.normalizeImageUrl(rawUrl); + if (!normalized) { + return res.status(400).send('Invalid url parameter'); + } + + let parsedUrl: URL; + try { + parsedUrl = new URL(normalized); + } catch { + return res.status(400).send('Malformed url parameter'); + } + + // Strict domain allowlist to prevent SSRF + const host = parsedUrl.hostname.toLowerCase(); + if (host !== 'ozelbursakulturokullari.com' && !host.endsWith('.ozelbursakulturokullari.com')) { + return res.status(403).send('Forbidden image host'); + } + + // Always upgrade portal image fetches to HTTPS (HTTP returns 403 on panel.ozelbursakulturokullari.com) + parsedUrl.protocol = 'https:'; + + try { + const reqHeaders: Record = { + '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', + 'Referer': 'https://ogrenci.ozelbursakulturokullari.com/', + 'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8' + }; + if (req.session?.portalCookies) { + reqHeaders['Cookie'] = req.session.portalCookies; + } + + const imgRes = await axios.get(parsedUrl.toString(), { + responseType: 'arraybuffer', + timeout: 12000, + headers: reqHeaders, + validateStatus: () => true + }); + + if (imgRes.status !== 200 || !imgRes.data) { + return res.status(imgRes.status || 404).end(); + } + + const rawContentType = imgRes.headers['content-type']; + const contentType = typeof rawContentType === 'string' ? rawContentType : 'image/jpeg'; + res.setHeader('Content-Type', contentType); + res.setHeader('Cache-Control', 'public, max-age=604800, stale-while-revalidate=86400'); + return res.send(Buffer.from(imgRes.data)); + } catch (err: any) { + return res.status(502).end(); + } +}); + // Rate Limiters for Production Hardening const isTestEnv = process.env.NODE_ENV === 'test'; @@ -144,6 +222,7 @@ const loginLimiter = rateLimit({ const apiLimiter = rateLimit({ windowMs: 1 * 60 * 1000, // 1 minute max: isTestEnv ? 5000 : 120, + skip: (req) => req.path === '/image-proxy', standardHeaders: true, legacyHeaders: false, message: { success: false, error: 'Çok fazla istek gönderildi. Lütfen biraz bekleyiniz.' } @@ -157,9 +236,74 @@ declare module 'express-session' { studentId?: string; portalCookies?: string; studentName?: string; + loginAt?: string; } } +const weeklySyncInFlight = new Map>(); + +/** + * Determine whether a student's login or cached data predates the start of the current week's Monday (00:00 Istanbul time) + */ +export function shouldTriggerMondayWeeklySync( + studentId: string, + loginTimestampOrRefDate?: string | Date | null, + refDate: Date = new Date() +): boolean { + const currentDb = LocalDatabase.getInstance(); + const loginTimestamp = loginTimestampOrRefDate instanceof Date ? null : loginTimestampOrRefDate; + const effectiveRefDate = loginTimestampOrRefDate instanceof Date ? loginTimestampOrRefDate : refDate; + + const effectiveLoginAt = loginTimestamp || currentDb.getLastLogin(studentId); + return isBeforeCurrentMondayInIstanbul(effectiveLoginAt, effectiveRefDate); +} + +/** + * Automatically sync recent homework, exams, and weekly syllabus when a user's login + * was before the start of Monday (00:00 Europe/Istanbul). + */ +export async function syncWeeklyStudentData( + studentId: string, + cookies: string, + refDate: Date = new Date() +): Promise { + const existingPromise = weeklySyncInFlight.get(studentId); + if (existingPromise) { + return existingPromise; + } + + const syncTask = (async () => { + const currentDb = LocalDatabase.getInstance(); + const nowIso = toIstanbulIsoString(refDate); + currentDb.updateLastLogin(studentId, nowIso); + + const currentWeek = SyllabusService.getWeekMetadata(refDate); + + await Promise.allSettled([ + // 1. Sync recent homework (pages 1-2) + (async () => { + const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2); + currentDb.mergeAssignments(studentId, scrapeRes.assignments, nowIso); + })(), + // 2. Sync weekly syllabus + (async () => { + const schedule = await ScraperService.scrapeSyllabus(cookies); + currentDb.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule, nowIso); + })(), + // 3. Sync exam reports + (async () => { + const details = await ScraperService.scrapeAllExamDetails(cookies); + currentDb.saveExamReports(studentId, details, nowIso); + })() + ]); + })().finally(() => { + weeklySyncInFlight.delete(studentId); + }); + + weeklySyncInFlight.set(studentId, syncTask); + return syncTask; +} + // Language Switcher Endpoints app.get('/lang/:locale', (req: Request, res: Response) => { const locale = normalizeLocale(req.params.locale); @@ -193,23 +337,48 @@ app.post('/api/preferences/lang', (req: Request, res: Response) => { // Auth guard helper function requireAuth(req: Request, res: Response, next: NextFunction) { + const isAjax = req.path.startsWith('/api/') || req.xhr || req.headers.accept?.includes('application/json'); + if (req.session && req.session.studentId) { + const activeStudentId = req.session.studentId; + if (shouldTriggerMondayWeeklySync(activeStudentId, req.session.loginAt)) { + getOrRefreshPortalCookies(req, activeStudentId) + .then(async (cookies) => { + if (cookies) { + await syncWeeklyStudentData(activeStudentId, cookies); + req.session.loginAt = toIstanbulIsoString(); + } + next(); + }) + .catch(() => next()); + return; + } return next(); } - 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) { - // Auto re-login in background - ScraperService.login(creds.studentId, creds.password).then(loginRes => { + const prevLoginAt = db.getLastLogin(creds.studentId); + // Auto re-login + ScraperService.login(creds.studentId, creds.password).then(async loginRes => { if (loginRes.success) { req.session.studentId = creds.studentId; req.session.portalCookies = loginRes.cookies; req.session.studentName = loginRes.studentName; + const nowIso = toIstanbulIsoString(); + if (shouldTriggerMondayWeeklySync(creds.studentId, prevLoginAt)) { + try { + await syncWeeklyStudentData(creds.studentId, loginRes.cookies); + } catch (syncErr: any) { + console.warn('Monday auto-sync warning during auto-login:', syncErr.message); + } + } else { + db.updateLastLogin(creds.studentId, nowIso); + } + req.session.loginAt = nowIso; return next(); } else { res.clearCookie('bekultur_student_id'); @@ -299,15 +468,10 @@ async function executeWithPortalSession( } // ---------------------------------------------------- -// Routes & Official E-Kültür Aliases +// Routes (English Page Paths Only) // ---------------------------------------------------- app.get('/login', (req: Request, res: Response) => res.redirect('/')); -app.get('/Kullanici/Giris', (req: Request, res: Response) => res.redirect('/')); -app.get('/giris', (req: Request, res: Response) => res.redirect('/')); -app.get('/Odev', (req: Request, res: Response) => res.redirect('/dashboard')); -app.get('/odev', (req: Request, res: Response) => res.redirect('/dashboard')); -app.get('/dersprogrami', (req: Request, res: Response) => res.redirect('/syllabus')); /** * GET / @@ -361,9 +525,14 @@ app.post('/login', loginLimiter, async (req: Request, res: Response) => { }); } + const prevLoginAt = db.getLastLogin(cleanStudentId); + const needsMondaySync = shouldTriggerMondayWeeklySync(cleanStudentId, prevLoginAt); + const nowIso = toIstanbulIsoString(); + req.session.studentId = cleanStudentId; req.session.portalCookies = loginRes.cookies; req.session.studentName = loginRes.studentName; + req.session.loginAt = nowIso; // Handle "Remember Me" if (rememberMe) { @@ -380,10 +549,16 @@ app.post('/login', loginLimiter, async (req: Request, res: Response) => { res.clearCookie('bekultur_student_id'); } - // Scrape recent pages (1-2) + // If previous login (or cached homework/exams/syllabus) was before Monday 00:00 Istanbul time, + // sync recent homework, exams, and syllabus automatically. Otherwise sync recent homework. try { - const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2); - db.mergeAssignments(cleanStudentId, scrapeRes.assignments); + if (needsMondaySync) { + await syncWeeklyStudentData(cleanStudentId, loginRes.cookies); + } else { + db.updateLastLogin(cleanStudentId, nowIso); + const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2); + db.mergeAssignments(cleanStudentId, scrapeRes.assignments); + } } catch (scrapeErr: any) { console.warn('Initial scrape warning (cached data will be used if available):', scrapeErr.message); } @@ -643,8 +818,8 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => { const selectedStation = syllabusStore?.selectedStation || 'İst-4'; const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId); - // Active day: 1 = Mon .. 5 = Fri (if weekend, default to Mon) - const todayDay = new Date().getDay(); + // Active day: 1 = Mon .. 5 = Fri in Europe/Istanbul (if weekend, default to Mon) + const todayDay = getIstanbulParts().dayOfWeek; const defaultDay = todayDay >= 1 && todayDay <= 5 ? todayDay : 1; const parsedQueryDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay; const activeDay = parsedQueryDay >= 1 && parsedQueryDay <= 5 ? parsedQueryDay : defaultDay; @@ -822,13 +997,6 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) => }); }); -/** - * Redirect shortcuts - */ -app.get('/ozelders', (req: Request, res: Response) => res.redirect('/private-lessons')); -app.get('/OzelDers', (req: Request, res: Response) => res.redirect('/private-lessons')); -app.get('/ozeldersistek', (req: Request, res: Response) => res.redirect('/private-lessons')); - /** * GET /api/private-lessons/units * Dynamic units for course @@ -932,17 +1100,9 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res }); // ---------------------------------------------------- -// Exam Reports (Sınav Rapor) Routes +// Exam Reports Routes // ---------------------------------------------------- -/** - * GET /rapor/sinav - * Official portal alias redirect - */ -app.get('/rapor/sinav', (req: Request, res: Response) => { - res.redirect('/exams'); -}); - /** * GET /exams * Main Exam Reports Dashboard @@ -956,19 +1116,10 @@ app.get('/exams', requireAuth, async (req: Request, res: Response) => { if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) { try { await executeWithPortalSession(req, studentId, async (cookies) => { - const examList = await ScraperService.scrapeExamList(cookies); - if (examList.length > 0) { - 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); - } + const details = await ScraperService.scrapeAllExamDetails(cookies); + if (details.length > 0) { + db.saveExamReports(studentId, details); + examStore = db.getExamReports(studentId); } return null; }); @@ -1061,7 +1212,11 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo const questions = await executeWithPortalSession(req, studentId, async (cookies) => { return await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip); }); - return res.json({ success: true, questions }); + const proxiedQuestions = questions.map(q => ({ + ...q, + imageUrl: ScraperService.toProxiedImageUrl(q.imageUrl) || q.imageUrl + })); + return res.json({ success: true, questions: proxiedQuestions }); } 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 }); @@ -1077,7 +1232,10 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo if (!subjectsMap[sName]) { subjectsMap[sName] = { subjectName: sName, subjectId: q.subjectId || '', questions: [] }; } - subjectsMap[sName].questions.push(q); + subjectsMap[sName].questions.push({ + ...q, + imageUrl: ScraperService.toProxiedImageUrl(q.imageUrl) || q.imageUrl + }); }); return res.json({ success: true, @@ -1115,14 +1273,18 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo tip ); if (q.length > 0) { - q.forEach(item => { + const proxiedList = q.map(item => { item.subjectName = subject.subjectName; - allScrapedQuestions.push(item); + allScrapedQuestions.push({ ...item }); + return { + ...item, + imageUrl: ScraperService.toProxiedImageUrl(item.imageUrl) || item.imageUrl + }; }); subjectQuestionsList.push({ subjectName: subject.subjectName, subjectId: subject.subjectId, - questions: q + questions: proxiedList }); } } @@ -1180,20 +1342,7 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => try { await executeWithPortalSession(req, studentId, async (cookies) => { - const examList = await ScraperService.scrapeExamList(cookies); - if (!examList || examList.length === 0) { - return []; - } - - // 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); }); - } - + const details = await ScraperService.scrapeAllExamDetails(cookies); if (details.length > 0) { db.saveExamReports(studentId, details); } @@ -1223,7 +1372,7 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => }); // Start Server & Graceful Shutdown -if (process.env.NODE_ENV !== 'test') { +if (require.main === module && process.env.NODE_ENV !== 'test') { const server = app.listen(PORT, () => { console.log(`=========================================`); console.log(` BeKultur (Better E-Kultur) Server`); diff --git a/src/services/db.ts b/src/services/db.ts index bdc531f..12ad964 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -1,3 +1,5 @@ +import '../utils/time'; +import { toIstanbulIsoString } from '../utils/time'; import fs from 'fs'; import path from 'path'; import crypto from 'crypto'; @@ -28,6 +30,7 @@ const SYNTHETIC_TEST_ID_REGEX = /^(test_student_|audit_)/i; interface StudentRow { student_id: string; last_synced: string | null; + last_login_at: string | null; remembered_password: string | null; advisory_teacher: string | null; syllabus_json: string | null; @@ -123,6 +126,7 @@ export class LocalDatabase { CREATE TABLE IF NOT EXISTS students ( student_id TEXT PRIMARY KEY, last_synced TEXT, + last_login_at TEXT, remembered_password TEXT, advisory_teacher TEXT, syllabus_json TEXT, @@ -163,6 +167,12 @@ export class LocalDatabase { CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire); `); + + // Ensure last_login_at column exists on pre-existing databases without data loss + const studentCols = this.sqlite.pragma('table_info(students)') as Array<{ name: string }>; + if (!studentCols.some(col => col.name === 'last_login_at')) { + this.sqlite.exec('ALTER TABLE students ADD COLUMN last_login_at TEXT'); + } } /** @@ -289,7 +299,7 @@ export class LocalDatabase { INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?) `); - const nowIso = new Date().toISOString(); + const nowIso = toIstanbulIsoString(); const runMigration = this.sqlite.transaction(() => { for (const [studentId, store] of Object.entries(studentsMap)) { @@ -368,25 +378,27 @@ export class LocalDatabase { return existing; } - const now = new Date().toISOString(); + const now = toIstanbulIsoString(); this.sqlite .prepare(` INSERT INTO students ( student_id, last_synced, + last_login_at, remembered_password, advisory_teacher, syllabus_json, private_lessons_json, exams_json, updated_at - ) VALUES (?, NULL, NULL, NULL, NULL, NULL, NULL, ?) + ) VALUES (?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?) `) .run(studentId, now); return { student_id: studentId, last_synced: null, + last_login_at: null, remembered_password: null, advisory_teacher: null, syllabus_json: null, @@ -395,6 +407,21 @@ export class LocalDatabase { }; } + public getLastLogin(studentId: string): string | null { + const row = this.sqlite + .prepare('SELECT last_login_at, last_synced FROM students WHERE student_id = ?') + .get(studentId) as { last_login_at: string | null; last_synced: string | null } | undefined; + if (!row) return null; + return row.last_login_at || row.last_synced || null; + } + + public updateLastLogin(studentId: string, loginAt: string = toIstanbulIsoString()): void { + this.ensureStudentRow(studentId); + this.sqlite + .prepare('UPDATE students SET last_login_at = ?, updated_at = ? WHERE student_id = ?') + .run(loginAt, loginAt, studentId); + } + private mapAssignmentRow(row: AssignmentRow): Assignment { return { id: row.id, @@ -471,18 +498,14 @@ export class LocalDatabase { return store; } - public mergeAssignments(studentId: string, newAssignments: Assignment[]): StudentStore { + public mergeAssignments(studentId: string, newAssignments: Assignment[], syncedAt?: string): StudentStore { this.ensureStudentRow(studentId); - const now = new Date().toISOString(); + const now = syncedAt || toIstanbulIsoString(); const updateStudentSync = this.sqlite.prepare( 'UPDATE students SET last_synced = ?, updated_at = ? WHERE student_id = ?' ); - const getExistingStmt = this.sqlite.prepare( - 'SELECT completed, completed_at, excluded FROM assignments WHERE student_id = ? AND id = ?' - ); - const upsertStmt = this.sqlite.prepare(` INSERT INTO assignments ( student_id, @@ -532,10 +555,10 @@ export class LocalDatabase { parsed_end_date = excluded.parsed_end_date, description = excluded.description, detected_check_date = excluded.detected_check_date, - status = excluded.status, - completed = excluded.completed, - completed_at = excluded.completed_at, - excluded = excluded.excluded, + status = CASE WHEN assignments.completed = 1 THEN 'completed' ELSE excluded.status END, + completed = CASE WHEN assignments.completed = 1 THEN 1 ELSE excluded.completed END, + completed_at = COALESCE(assignments.completed_at, excluded.completed_at), + excluded = CASE WHEN assignments.excluded = 1 THEN 1 ELSE excluded.excluded END, page = excluded.page `); @@ -543,15 +566,7 @@ export class LocalDatabase { updateStudentSync.run(now, now, studentId); for (const item of newAssignments) { - const existing = getExistingStmt.get(studentId, item.id) as - | { completed: number; completed_at: string | null; excluded: number } - | undefined; - - const isCompleted = existing ? existing.completed === 1 : Boolean(item.completed); - const completedAt = existing ? existing.completed_at : (item.completedAt || null); - const isExcluded = existing ? existing.excluded === 1 : Boolean(item.excluded); - const status = isCompleted ? 'completed' : item.status; - + const isCompleted = Boolean(item.completed); upsertStmt.run({ student_id: studentId, id: item.id, @@ -565,10 +580,10 @@ export class LocalDatabase { parsed_end_date: item.parsedEndDate || null, description: item.description || '', detected_check_date: item.detectedCheckDate || null, - status, + status: isCompleted ? 'completed' : item.status, completed: isCompleted ? 1 : 0, - completed_at: completedAt, - excluded: isExcluded ? 1 : 0, + completed_at: item.completedAt || null, + excluded: item.excluded ? 1 : 0, page: item.page ?? null }); } @@ -619,7 +634,7 @@ export class LocalDatabase { } const newCompleted = completed !== undefined ? completed : existing.completed !== 1; - const completedAt = newCompleted ? new Date().toISOString() : null; + const completedAt = newCompleted ? toIstanbulIsoString() : null; const newStatus = newCompleted ? 'completed' : existing.status; this.sqlite @@ -640,14 +655,14 @@ export class LocalDatabase { const encryptedPassword = encryptCredential(password); this.sqlite .prepare('UPDATE students SET remembered_password = ?, updated_at = ? WHERE student_id = ?') - .run(encryptedPassword, new Date().toISOString(), studentId); + .run(encryptedPassword, toIstanbulIsoString(), studentId); } public clearCredentials(studentId: string): void { this.ensureStudentRow(studentId); this.sqlite .prepare('UPDATE students SET remembered_password = NULL, updated_at = ? WHERE student_id = ?') - .run(new Date().toISOString(), studentId); + .run(toIstanbulIsoString(), studentId); } public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null { @@ -675,24 +690,26 @@ export class LocalDatabase { studentId: string, weekId: string, weekRange: string, - schedule: Record + schedule: Record, + syncedAt?: string ): void { const row = this.ensureStudentRow(studentId); const existingSyllabus = row.syllabus_json ? (JSON.parse(row.syllabus_json) as SyllabusStore) : null; const existingStation = existingSyllabus?.selectedStation || null; + const now = syncedAt || toIstanbulIsoString(); const syllabus: SyllabusStore = { weekId, weekRange, selectedStation: existingStation, advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null, - lastSynced: new Date().toISOString(), + lastSynced: now, schedule }; this.sqlite .prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?') - .run(JSON.stringify(syllabus), new Date().toISOString(), studentId); + .run(JSON.stringify(syllabus), now, studentId); } public setStudentStation(studentId: string, station: string | null): void { @@ -713,7 +730,7 @@ export class LocalDatabase { this.sqlite .prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?') - .run(JSON.stringify(syllabus), new Date().toISOString(), studentId); + .run(JSON.stringify(syllabus), toIstanbulIsoString(), studentId); } public getSyllabus(studentId: string): SyllabusStore | null { @@ -741,7 +758,7 @@ export class LocalDatabase { : null; const privateLessons: PrivateLessonsStore = { - lastSynced: new Date().toISOString(), + lastSynced: toIstanbulIsoString(), lessons, formMeta: formMeta || existing?.formMeta, detectedAdvisor: detectedAdvisor || existing?.detectedAdvisor @@ -771,7 +788,7 @@ export class LocalDatabase { JSON.stringify(privateLessons), newAdvisor, updatedSyllabusJson, - new Date().toISOString(), + toIstanbulIsoString(), studentId ); } @@ -804,7 +821,7 @@ export class LocalDatabase { this.sqlite .prepare('UPDATE students SET advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?') - .run(teacher, updatedSyllabusJson, new Date().toISOString(), studentId); + .run(teacher, updatedSyllabusJson, toIstanbulIsoString(), studentId); } public getStudentAdvisoryTeacher(studentId: string): string | null { @@ -829,17 +846,18 @@ export class LocalDatabase { // Exam Reports (Sınav Rapor) Store // ---------------------------------------------------- - public saveExamReports(studentId: string, reports: ExamReportDetail[]): void { + public saveExamReports(studentId: string, reports: ExamReportDetail[], syncedAt?: string): void { const row = this.ensureStudentRow(studentId); const existing = row.exams_json ? (JSON.parse(row.exams_json) as ExamStore) : null; const reportsMap: Record = existing?.reports ? { ...existing.reports } : {}; + const now = syncedAt || toIstanbulIsoString(); reports.forEach(r => { reportsMap[r.summary.id] = r; }); const exams: ExamStore = { - lastSynced: new Date().toISOString(), + lastSynced: now, reports: reportsMap, topicWeaknesses: existing?.topicWeaknesses || {}, questions: existing?.questions || {} @@ -847,7 +865,7 @@ export class LocalDatabase { this.sqlite .prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?') - .run(JSON.stringify(exams), new Date().toISOString(), studentId); + .run(JSON.stringify(exams), now, studentId); } public getExamReports(studentId: string): ExamStore | null { @@ -868,7 +886,7 @@ export class LocalDatabase { const exams: ExamStore = row.exams_json ? (JSON.parse(row.exams_json) as ExamStore) : { - lastSynced: new Date().toISOString(), + lastSynced: toIstanbulIsoString(), reports: {}, topicWeaknesses: {}, questions: {} @@ -881,7 +899,7 @@ export class LocalDatabase { this.sqlite .prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?') - .run(JSON.stringify(exams), new Date().toISOString(), studentId); + .run(JSON.stringify(exams), toIstanbulIsoString(), studentId); } public getTopicWeaknesses(studentId: string, examId: string): ExamTopicWeakness[] | null { @@ -894,7 +912,7 @@ export class LocalDatabase { const exams: ExamStore = row.exams_json ? (JSON.parse(row.exams_json) as ExamStore) : { - lastSynced: new Date().toISOString(), + lastSynced: toIstanbulIsoString(), reports: {}, topicWeaknesses: {}, questions: {} @@ -907,7 +925,7 @@ export class LocalDatabase { this.sqlite .prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?') - .run(JSON.stringify(exams), new Date().toISOString(), studentId); + .run(JSON.stringify(exams), toIstanbulIsoString(), studentId); } public getExamQuestions(studentId: string, examId: string): ExamQuestionItem[] | null { diff --git a/src/services/insight.ts b/src/services/insight.ts index 65a9c7a..ecfc633 100644 --- a/src/services/insight.ts +++ b/src/services/insight.ts @@ -1,3 +1,5 @@ +import '../utils/time'; +import { getIstanbulParts } from '../utils/time'; import { Assignment, AssignmentStatus, DashboardStats, SubjectStat } from '../types'; export class InsightService { @@ -92,9 +94,10 @@ export class InsightService { const endDate = this.parsePortalDate(assignment.endDate); const startDate = this.parsePortalDate(assignment.startDate); + const istParts = getIstanbulParts(refDate); // 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) { + const todayStart = new Date(istParts.year, istParts.month - 1, istParts.day, 0, 0, 0); + if (startDate && startDate.getTime() > todayStart.getTime() + 86400000 * 3) { return 'future'; } @@ -107,12 +110,10 @@ export class InsightService { return 'overdue'; } - // Current week boundaries (Monday to Sunday) - const currentDay = refDate.getDay(); // 0 is Sunday, 1 is Monday + // Current week boundaries (Monday to Sunday) in Istanbul time + const currentDay = istParts.dayOfWeek; // 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 thisMonday = new Date(istParts.year, istParts.month - 1, istParts.day + distanceToMonday, 0, 0, 0, 0); const thisSunday = new Date(thisMonday); thisSunday.setDate(thisMonday.getDate() + 6); @@ -157,10 +158,8 @@ export class InsightService { 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); + // Due soon: within 3 days from now in Istanbul time + const threeDaysFromNow = new Date(istParts.year, istParts.month - 1, istParts.day + 3, 23, 59, 59, 999); if (dueTime <= threeDaysFromNow.getTime()) { return 'due-soon'; diff --git a/src/services/scraper.ts b/src/services/scraper.ts index 1697a4e..1ef3b04 100644 --- a/src/services/scraper.ts +++ b/src/services/scraper.ts @@ -1,3 +1,5 @@ +import '../utils/time'; +import { getIstanbulParts } from '../utils/time'; import axios from 'axios'; import * as cheerio from 'cheerio'; import crypto from 'crypto'; @@ -33,6 +35,59 @@ export interface ScrapeResult { } export class ScraperService { + /** + * Normalize portal image URLs (upgrades http:// to https:// and resolves relative paths) + */ + public static normalizeImageUrl(rawUrl: string | undefined | null): string | null { + if (!rawUrl) return null; + let url = rawUrl.trim(); + if (!url) return null; + if (url.startsWith('/api/image-proxy')) return url; + if (url.startsWith('//')) { + url = `https:${url}`; + } else if (url.startsWith('/')) { + url = `https://panel.ozelbursakulturokullari.com${url}`; + } else if (url.startsWith('http://')) { + try { + const parsed = new URL(url); + if ( + parsed.hostname === 'ozelbursakulturokullari.com' || + parsed.hostname.endsWith('.ozelbursakulturokullari.com') + ) { + parsed.protocol = 'https:'; + url = parsed.toString(); + } + } catch { + // leave as is if invalid URL + } + } + return url; + } + + /** + * Convert a portal image URL into a same-origin proxied URL (/api/image-proxy?url=...) + * so that PWA standalone mode and Service Worker caching work without Mixed Content or CORS issues. + */ + public static toProxiedImageUrl(rawUrl: string | undefined | null): string | null { + const normalized = this.normalizeImageUrl(rawUrl); + if (!normalized) return null; + if (normalized.startsWith('/api/image-proxy') || normalized.startsWith('data:')) { + return normalized; + } + try { + const parsed = new URL(normalized); + if ( + parsed.hostname === 'ozelbursakulturokullari.com' || + parsed.hostname.endsWith('.ozelbursakulturokullari.com') + ) { + return `/api/image-proxy?url=${encodeURIComponent(normalized)}`; + } + } catch { + // Non-absolute or external test URL; return normalized as-is + } + return normalized; + } + /** * Helper to format cookies array from set-cookie headers */ @@ -381,7 +436,7 @@ export class ScraperService { } const station = stationRaw ? stationRaw : null; - const teacherPhoto = card.find('img.profil-resmi').attr('src') || null; + const teacherPhoto = this.normalizeImageUrl(card.find('img.profil-resmi').attr('src')); let startTime = ''; let endTime = ''; @@ -467,7 +522,7 @@ export class ScraperService { const pElements = card.find('p.my-1'); const teacherName = pElements.eq(0).text().trim(); const dateStr = pElements.eq(1).text().trim(); // e.g. "26.10.2026" - const teacherPhoto = card.find('img.profil-resmi').attr('src') || ''; + const teacherPhoto = this.normalizeImageUrl(card.find('img.profil-resmi').attr('src')) || ''; if (!subject || !teacherName || !dateStr) return; @@ -478,9 +533,11 @@ export class ScraperService { const parsedObj = InsightService.parsePortalDate(dateStr); const parsedDate = InsightService.toISODate(parsedObj) || ''; - // Check if upcoming: has border-success class OR date is in future/today + // Check if upcoming: has border-success class OR date is in future/today (in Istanbul time) const hasSuccessBorder = card.hasClass('border-success') || (card.attr('class') || '').includes('border-success'); - const isDateUpcoming = parsedObj ? parsedObj.getTime() >= new Date().setHours(0, 0, 0, 0) : false; + const istNow = getIstanbulParts(); + const todayStartMs = new Date(istNow.year, istNow.month - 1, istNow.day, 0, 0, 0, 0).getTime(); + const isDateUpcoming = parsedObj ? parsedObj.getTime() >= todayStartMs : false; const isUpcoming = hasSuccessBorder || isDateUpcoming; const id = crypto.createHash('sha256').update(key).digest('hex').slice(0, 16); @@ -530,7 +587,7 @@ export class ScraperService { const pTags = $('.alert-info p'); const schoolName = pTags.eq(1).text().trim(); const className = pTags.eq(2).text().trim(); - const photoUrl = $('.alert-info img.profil-resmi').attr('src') || undefined; + const photoUrl = this.normalizeImageUrl($('.alert-info img.profil-resmi').attr('src')) || undefined; const ogrenciDonemId = ($('input#OgrenciDonemId').val() as string) || ''; const okulId = ($('input#OkulId').val() as string) || ''; @@ -734,6 +791,28 @@ export class ScraperService { } } + /** + * Scrape all exam details in batches of 3 + */ + public static async scrapeAllExamDetails(cookies: string): Promise { + const examList = await this.scrapeExamList(cookies); + if (!examList || examList.length === 0) { + return []; + } + + 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 => this.scrapeExamDetail(cookies, item.id))); + batchRes.forEach(d => { + if (d) details.push(d); + }); + } + + return details; + } + /** * Scrape exam scorecard, rankings, and subject breakdown from /rapor/sinavkarne/:id */ @@ -934,12 +1013,7 @@ export class ScraperService { const dogruMatch = text.match(/Doğru\s*Cevap:\s*([A-E\-]+)/i); const ogrenciMatch = text.match(/Öğrenci\s*Cevap:\s*([A-E\-]+)/i); - let imgUrl = $(el).find('img').attr('src') || ''; - if (imgUrl.startsWith('//')) { - imgUrl = `https:${imgUrl}`; - } else if (imgUrl.startsWith('/')) { - imgUrl = `https://panel.ozelbursakulturokullari.com${imgUrl}`; - } + const imgUrl = this.normalizeImageUrl($(el).find('img').attr('src')) || ''; const questionNumber = noMatch ? parseInt(noMatch[1], 10) : 0; const correctAnswer = dogruMatch ? dogruMatch[1].trim() : '-'; diff --git a/src/services/syllabus.ts b/src/services/syllabus.ts index 240edaf..f00bcaf 100644 --- a/src/services/syllabus.ts +++ b/src/services/syllabus.ts @@ -1,3 +1,5 @@ +import '../utils/time'; +import { getIstanbulParts } from '../utils/time'; import { Lesson } from '../types'; import { InsightService } from './insight'; import { SupportedLocale, translate } from './i18n'; @@ -15,9 +17,10 @@ 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); + const parts = getIstanbulParts(refDate); + const d = new Date(parts.year, parts.month - 1, parts.day, 12, 0, 0, 0); // Find Monday of the current week - const day = d.getDay(); // 0 is Sunday, 1 is Monday + const day = parts.dayOfWeek; // 0 is Sunday, 1 is Monday const diffToMonday = day === 0 ? -6 : 1 - day; const monday = new Date(d); monday.setDate(d.getDate() + diffToMonday); @@ -171,12 +174,13 @@ export class SyllabusService { refDate: Date = new Date(), locale: SupportedLocale = 'tr' ): { currentLesson: Lesson | null; nextLesson: Lesson | null; statusText: string | null } { - const todayDay = refDate.getDay(); // 1 = Mon, ..., 5 = Fri + const parts = getIstanbulParts(refDate); + const todayDay = parts.dayOfWeek; // 1 = Mon, ..., 5 = Fri if (todayDay !== currentDayNumber) { return { currentLesson: null, nextLesson: null, statusText: null }; } - const nowMinutes = refDate.getHours() * 60 + refDate.getMinutes(); + const nowMinutes = parts.hour * 60 + parts.minute; let current: Lesson | null = null; let next: Lesson | null = null; diff --git a/src/utils/time.ts b/src/utils/time.ts new file mode 100644 index 0000000..c845c83 --- /dev/null +++ b/src/utils/time.ts @@ -0,0 +1,165 @@ +// Force Node.js process timezone to Europe/Istanbul (UTC+3, permanent) +process.env.TZ = 'Europe/Istanbul'; + +export const ISTANBUL_TIMEZONE = 'Europe/Istanbul'; + +const WEEKDAY_MAP: Record = { + Sun: 0, + Mon: 1, + Tue: 2, + Wed: 3, + Thu: 4, + Fri: 5, + Sat: 6 +}; + +export interface IstanbulDateParts { + year: number; + month: number; // 1-12 + day: number; // 1-31 + hour: number; // 0-23 + minute: number; // 0-59 + second: number; // 0-59 + dayOfWeek: number; // 0 (Sun) - 6 (Sat) +} + +const ISTANBUL_PARTS_FORMATTER = new Intl.DateTimeFormat('en-US', { + timeZone: ISTANBUL_TIMEZONE, + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + hour12: false, + weekday: 'short' +}); + +const ISTANBUL_TIME_FORMATTERS: Record<'tr' | 'en', Intl.DateTimeFormat> = { + tr: new Intl.DateTimeFormat('tr-TR', { + timeZone: ISTANBUL_TIMEZONE, + hour: '2-digit', + minute: '2-digit', + hour12: false + }), + en: new Intl.DateTimeFormat('en-GB', { + timeZone: ISTANBUL_TIMEZONE, + hour: '2-digit', + minute: '2-digit', + hour12: false + }) +}; + +const ISTANBUL_DATE_FORMATTERS: Record<'tr' | 'en', Intl.DateTimeFormat> = { + tr: new Intl.DateTimeFormat('tr-TR', { + timeZone: ISTANBUL_TIMEZONE, + day: '2-digit', + month: '2-digit', + year: 'numeric' + }), + en: new Intl.DateTimeFormat('en-GB', { + timeZone: ISTANBUL_TIMEZONE, + day: '2-digit', + month: '2-digit', + year: 'numeric' + }) +}; + +/** + * Extract date/time components explicitly in Europe/Istanbul timezone + */ +export function getIstanbulParts(refDate: Date = new Date()): IstanbulDateParts { + const parts = ISTANBUL_PARTS_FORMATTER.formatToParts(refDate); + const map: Record = {}; + for (const p of parts) { + if (p.type !== 'literal') { + map[p.type] = p.value; + } + } + + let hour = parseInt(map.hour || '0', 10); + if (hour === 24) hour = 0; + + return { + year: parseInt(map.year || '1970', 10), + month: parseInt(map.month || '1', 10), + day: parseInt(map.day || '1', 10), + hour, + minute: parseInt(map.minute || '0', 10), + second: parseInt(map.second || '0', 10), + dayOfWeek: WEEKDAY_MAP[map.weekday] ?? refDate.getDay() + }; +} + +/** + * Format a Date as an ISO-8601 timestamp in Europe/Istanbul (+03:00) + */ +export function toIstanbulIsoString(refDate: Date = new Date()): string { + const p = getIstanbulParts(refDate); + const ms = String(refDate.getMilliseconds()).padStart(3, '0'); + const yyyy = String(p.year).padStart(4, '0'); + const mm = String(p.month).padStart(2, '0'); + const dd = String(p.day).padStart(2, '0'); + const hh = String(p.hour).padStart(2, '0'); + const min = String(p.minute).padStart(2, '0'); + const ss = String(p.second).padStart(2, '0'); + return `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}.${ms}+03:00`; +} + +/** + * Format time (HH:mm) strictly in Europe/Istanbul timezone + */ +export function formatIstanbulTime( + value: string | number | Date | null | undefined, + locale: string = 'tr' +): string { + if (!value) return ''; + const d = value instanceof Date ? value : new Date(value); + if (isNaN(d.getTime())) return ''; + const fmt = locale === 'en' ? ISTANBUL_TIME_FORMATTERS.en : ISTANBUL_TIME_FORMATTERS.tr; + return fmt.format(d); +} + +/** + * Format date (DD.MM.YYYY) strictly in Europe/Istanbul timezone + */ +export function formatIstanbulDate( + value: string | number | Date | null | undefined, + locale: string = 'tr' +): string { + if (!value) return ''; + const d = value instanceof Date ? value : new Date(value); + if (isNaN(d.getTime())) return ''; + const fmt = locale === 'en' ? ISTANBUL_DATE_FORMATTERS.en : ISTANBUL_DATE_FORMATTERS.tr; + return fmt.format(d); +} + +/** + * Compute the exact Date corresponding to Monday 00:00:00.000 in Europe/Istanbul (+03:00) + * for the ISO week (Mon-Sun) containing refDate. + */ +export function getIstanbulMondayStart(refDate: Date = new Date()): Date { + const p = getIstanbulParts(refDate); + // In ISO week, Monday = 1 ... Sunday = 0 (which is 6 days after Monday) + const daysSinceMonday = p.dayOfWeek === 0 ? 6 : p.dayOfWeek - 1; + // 00:00:00.000 in Europe/Istanbul (UTC+3) is -3 hours from Date.UTC midnight + const utcMidnightMs = Date.UTC(p.year, p.month - 1, p.day - daysSinceMonday, 0, 0, 0, 0); + const istanbulOffsetMs = 3 * 60 * 60 * 1000; + return new Date(utcMidnightMs - istanbulOffsetMs); +} + +/** + * Returns true if the given timestamp (e.g., last login or last sync) occurred + * strictly before Monday 00:00:00.000 (Istanbul time) of the current week, + * or if the timestamp is missing/invalid. + */ +export function isBeforeCurrentMondayInIstanbul( + timestamp: string | number | Date | null | undefined, + refDate: Date = new Date() +): boolean { + if (!timestamp) return true; + const parsed = timestamp instanceof Date ? timestamp : new Date(timestamp); + if (isNaN(parsed.getTime())) return true; + const mondayStart = getIstanbulMondayStart(refDate); + return parsed.getTime() < mondayStart.getTime(); +} diff --git a/test/run-tests.ts b/test/run-tests.ts index 448a3d2..fbbfea8 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -10,20 +10,32 @@ import { InsightService } from '../src/services/insight'; import { ScraperService } from '../src/services/scraper'; import { SyllabusService } from '../src/services/syllabus'; import { ExamService } from '../src/services/exam'; +import { + ISTANBUL_TIMEZONE, + getIstanbulParts, + toIstanbulIsoString, + formatIstanbulTime, + formatIstanbulDate, + getIstanbulMondayStart, + isBeforeCurrentMondayInIstanbul +} from '../src/utils/time'; import { Assignment, Lesson, ExamReportDetail } from '../src/types'; +// Configure isolated temporary directory BEFORE any server/db singleton initialization +const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-')); +const testDbPath = path.join(tempDir, 'test-bekultur.db'); +const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json'); +process.env.NODE_ENV = 'test'; +process.env.DB_PATH = testDbPath; +process.env.LEGACY_JSON_PATH = testLegacyJsonPath; + +import { shouldTriggerMondayWeeklySync, syncWeeklyStudentData } from '../src/server'; + async function runAllTests() { console.log('========================================================'); console.log(' BeKultur - Automated Test Suite'); console.log('========================================================\n'); - // Use an isolated temporary directory so tests never pollute production data/ - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-')); - const testDbPath = path.join(tempDir, 'test-bekultur.db'); - const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json'); - process.env.DB_PATH = testDbPath; - process.env.LEGACY_JSON_PATH = testLegacyJsonPath; - let passed = 0; let failed = 0; @@ -1014,6 +1026,13 @@ async function runAllTests() { assert.strictEqual(translate('en', 'nav.homework'), 'Homework'); assert.strictEqual(translate('en', 'exams.kpiAcrossExams', { count: 4 }), 'Across all 4 exams'); assert.strictEqual(translate('tr', 'exams.kpiAcrossExams', { count: 4 }), 'Toplam 4 sınav içinde'); + + // Verify all served page routes in server.ts are strictly English (no Turkish route aliases) + const serverContent = fs.readFileSync(path.resolve(__dirname, '../src/server.ts'), 'utf-8'); + const disallowedRoutes = ['/Kullanici/Giris', '/giris', '/Odev', '/odev', '/dersprogrami', '/ozelders', '/OzelDers', '/ozeldersistek', '/rapor/sinav']; + for (const route of disallowedRoutes) { + assert(!serverContent.includes(`'${route}'`), `Route ${route} must not be served; all page paths must be English`); + } }); await test('UI & Dark Theme: header.ejs and style.css implement modern color-scheme, theme toggle, and language switcher', () => { @@ -1067,6 +1086,210 @@ async function runAllTests() { assert(swContent.includes("url.pathname.startsWith('/private-lessons')"), 'sw.js must have route fallback for private lessons'); }); + // 11. Fixed Istanbul Timezone (Europe/Istanbul) Tests + await test('Istanbul Time Utility: always enforces Europe/Istanbul (UTC+3) regardless of host timezone', () => { + assert.strictEqual(ISTANBUL_TIMEZONE, 'Europe/Istanbul'); + assert.strictEqual(process.env.TZ, 'Europe/Istanbul'); + + // 2026-10-25T20:51:45.000Z in UTC is 23:51:45 on Sunday 25.10.2026 in Istanbul (UTC+3) + const utcSundayNight = '2026-10-25T20:51:45.000Z'; + assert.strictEqual(formatIstanbulTime(utcSundayNight), '23:51'); + assert.strictEqual(formatIstanbulDate(utcSundayNight), '25.10.2026'); + + // 2026-10-25T21:30:00.000Z in UTC is 00:30:00 on Monday 26.10.2026 in Istanbul (UTC+3) + const utcMondayEarly = new Date('2026-10-25T21:30:00.000Z'); + const parts = getIstanbulParts(utcMondayEarly); + assert.strictEqual(parts.year, 2026); + assert.strictEqual(parts.month, 10); + assert.strictEqual(parts.day, 26); + assert.strictEqual(parts.hour, 0); + assert.strictEqual(parts.minute, 30); + assert.strictEqual(parts.dayOfWeek, 1, '00:30 Istanbul time must be Monday (dayOfWeek = 1)'); + assert.strictEqual(formatIstanbulDate(utcMondayEarly), '26.10.2026'); + assert(toIstanbulIsoString(utcMondayEarly).endsWith('+03:00'), 'ISO timestamp must carry +03:00 Istanbul offset'); + }); + + await test('Istanbul Time Utility: getIstanbulMondayStart and isBeforeCurrentMondayInIstanbul accurately detect Monday 00:00:00+03:00 boundary', () => { + // Suppose current time is Wednesday 28 Oct 2026 14:00 Istanbul time (11:00 UTC) + const wednesdayNow = new Date('2026-10-28T11:00:00.000Z'); + const mondayStart = getIstanbulMondayStart(wednesdayNow); + + // Monday 26 Oct 2026 00:00:00+03:00 is 2026-10-25T21:00:00.000Z + assert.strictEqual(mondayStart.toISOString(), '2026-10-25T21:00:00.000Z'); + + // Sunday 25 Oct 2026 23:59:59+03:00 (1 second before Monday start in Istanbul) + const sundayLastSecond = '2026-10-25T20:59:59.000Z'; + assert.strictEqual(isBeforeCurrentMondayInIstanbul(sundayLastSecond, wednesdayNow), true); + + // Monday 26 Oct 2026 00:00:00+03:00 (exact start of Monday in Istanbul) + const mondayFirstSecond = '2026-10-25T21:00:00.000Z'; + assert.strictEqual(isBeforeCurrentMondayInIstanbul(mondayFirstSecond, wednesdayNow), false); + + // Null/empty timestamp must return true (needs sync) + assert.strictEqual(isBeforeCurrentMondayInIstanbul(null, wednesdayNow), true); + }); + + // 12. PWA Image Proxy & URL Normalization Tests + await test('PWA Image Fix: ScraperService normalizes HTTP portal URLs to HTTPS and routes through /api/image-proxy', () => { + const rawHttpProfile = 'http://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg'; + const normalized = ScraperService.normalizeImageUrl(rawHttpProfile); + assert.strictEqual( + normalized, + 'https://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg', + 'HTTP portal profile photo must upgrade to HTTPS' + ); + + const proxied = ScraperService.toProxiedImageUrl(rawHttpProfile); + assert.strictEqual( + proxied, + '/api/image-proxy?url=' + encodeURIComponent('https://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg'), + 'Portal image must be rewritten to same-origin /api/image-proxy' + ); + + // Relative question image URL + const relQuestion = '/uploads/soru/9988.png'; + assert.strictEqual( + ScraperService.normalizeImageUrl(relQuestion), + 'https://panel.ozelbursakulturokullari.com/uploads/soru/9988.png' + ); + + // Verify sw.js upgrades to bekultur-v4, uses /api/image-proxy, and never caches opaque failed responses + const swContent = fs.readFileSync(path.resolve(__dirname, '../public/sw.js'), 'utf-8'); + assert(swContent.includes("CACHE_NAME = 'bekultur-v4'"), 'sw.js must use bumped cache version bekultur-v4'); + assert(swContent.includes('/api/image-proxy'), 'sw.js must route portal images through /api/image-proxy'); + assert(!swContent.includes("networkResponse.type === 'opaque'"), 'sw.js must NOT cache opaque error responses'); + }); + + // 13. Automatic Monday Weekly Sync on Login Tests + await test('Weekly Monday Login Sync: automatically syncs recent homework, exams, and syllabus when previous login was before Monday 00:00 Istanbul time', async () => { + const db = LocalDatabase.getInstance(); + const studentId = 'monday_sync_student_415'; + + // Simulate a student who last logged in on Sunday 25 Oct 2026 at 22:00 Istanbul time (+03:00) + const sundayLogin = '2026-10-25T22:00:00.000+03:00'; + db.updateLastLogin(studentId, sundayLogin); + assert.strictEqual(db.getLastLogin(studentId), sundayLogin); + + // Current time: Monday 26 Oct 2026 at 08:30 Istanbul time (+03:00) + const mondayMorning = new Date('2026-10-26T08:30:00.000+03:00'); + assert.strictEqual( + shouldTriggerMondayWeeklySync(studentId, mondayMorning), + true, + 'Login on Monday morning after Sunday login must trigger weekly sync' + ); + + // Mock ScraperService methods to verify syncWeeklyStudentData orchestrates all 3 syncs + const origScrapeRecent = ScraperService.scrapeMultiplePages; + const origScrapeExams = ScraperService.scrapeAllExamDetails; + const origScrapeSyllabus = ScraperService.scrapeSyllabus; + + let recentCalled = 0; + let examsCalled = 0; + let syllabusCalled = 0; + + ScraperService.scrapeMultiplePages = async () => { + recentCalled++; + return { + totalPages: 2, + assignments: [ + { + id: 'monday_hw_1', + subject: 'AYT Fizik', + type: 'Yayın', + unit: 'Modern Fizik', + topic: 'Fotoelektrik', + startDate: '26.10.2026', + endDate: '02.11.2026', + parsedStartDate: '2026-10-26', + parsedEndDate: '2026-11-02', + description: 'Sayfa 10-20', + detectedCheckDate: null, + status: 'active', + completed: false, + completedAt: null + } + ] + }; + }; + + ScraperService.scrapeAllExamDetails = async () => { + examsCalled++; + return [ + { + summary: { + id: '4001', + name: '12 YKS-05 MF', + examType: 'TYT', + totalQuestions: 120, + totalCorrect: 95, + totalWrong: 12, + totalEmpty: 13, + totalNet: 92.0, + totalScore: 92.0, + generalRank: 4 + }, + subjects: [], + hasAnswerKey: true + } + ]; + }; + + ScraperService.scrapeSyllabus = async () => { + syllabusCalled++; + return { + 1: [ + { + period: '1. Ders', + periodNumber: 1, + subject: 'TYT Matematik', + teacher: 'BİRKAN BOZKURT', + teacherPhoto: 'https://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg', + startTime: '09:30', + endTime: '10:05', + time: '09:30 - 10:05', + station: null, + day: 1, + dayName: 'Pazartesi' + } + ], + 2: [], + 3: [], + 4: [], + 5: [] + }; + }; + + try { + await syncWeeklyStudentData(studentId, 'mock_cookie=1', mondayMorning); + + assert.strictEqual(recentCalled, 1, 'scrapeMultiplePages must be called once'); + assert.strictEqual(examsCalled, 1, 'scrapeAllExamDetails must be called once'); + assert.strictEqual(syllabusCalled, 1, 'scrapeSyllabus must be called once'); + + // Verify all 3 stores and last_login_at were updated in SQLite + const updatedStore = db.getStudentStore(studentId); + assert(updatedStore.assignments['monday_hw_1'], 'Recent homework must be saved to SQLite'); + + const updatedExams = db.getExamReports(studentId); + assert(updatedExams?.reports['4001'], 'Recent exam report must be saved to SQLite'); + + const updatedSyllabus = db.getSyllabus(studentId); + assert.strictEqual(updatedSyllabus?.schedule[1]?.length, 1, 'Updated syllabus must be saved to SQLite'); + + // Verify subsequent request on the same Monday does NOT re-trigger weekly sync + const mondayAfternoon = new Date('2026-10-26T15:00:00.000+03:00'); + assert.strictEqual( + shouldTriggerMondayWeeklySync(studentId, mondayAfternoon), + false, + 'Subsequent login/request in the same week must NOT re-trigger Monday sync' + ); + } finally { + ScraperService.scrapeMultiplePages = origScrapeRecent; + ScraperService.scrapeAllExamDetails = origScrapeExams; + ScraperService.scrapeSyllabus = origScrapeSyllabus; + } + }); + // Optional Live Portal Test (via environment variables only) const testStudentId = process.env.TEST_STUDENT_ID; const testPassword = process.env.TEST_PASSWORD; diff --git a/views/dashboard.ejs b/views/dashboard.ejs index 78f3a9e..d27cfcc 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -10,7 +10,7 @@ • <% if (lastSynced) { %> - <%= t('dashboard.lastSynced') %> <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + <%= t('dashboard.lastSynced') %> <%= formatTime(lastSynced) %> <% } else { %> <%= t('dashboard.notSynced') %> <% } %> @@ -234,7 +234,7 @@
<% if (item.completed && item.completedAt) { %> - <%= t('dashboard.completedOn') %> <%= new Date(item.completedAt).toLocaleDateString() %> + <%= t('dashboard.completedOn') %> <%= formatDate(item.completedAt) %> <% } %> #<%= item.id %>
diff --git a/views/exams.ejs b/views/exams.ejs index 8e791cb..25cd8a0 100644 --- a/views/exams.ejs +++ b/views/exams.ejs @@ -8,7 +8,7 @@

<%= t('exams.subtitle') %> <% if (lastSynced) { %> - • <%= t('exams.syncedLabel') %> <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + • <%= t('exams.syncedLabel') %> <%= formatTime(lastSynced) %> <% } %>

diff --git a/views/partials/header.ejs b/views/partials/header.ejs index 915458e..3ec7724 100644 --- a/views/partials/header.ejs +++ b/views/partials/header.ejs @@ -59,10 +59,10 @@ <% if (typeof studentId !== 'undefined' && studentId) { %> <% } %> diff --git a/views/private-lessons.ejs b/views/private-lessons.ejs index 6dc4fbe..2f3cdf9 100644 --- a/views/private-lessons.ejs +++ b/views/private-lessons.ejs @@ -8,7 +8,7 @@

<%= t('privateLessons.subtitle') %> <% if (lastSynced) { %> - • <%= t('privateLessons.syncedLabel') %> <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + • <%= t('privateLessons.syncedLabel') %> <%= formatTime(lastSynced) %> <% } %>

@@ -27,7 +27,7 @@
<% if (formMeta.photoUrl) { %> - <%= formMeta.studentName %> + <%= formMeta.studentName %> <% } %>

<%= formMeta.studentName %>

@@ -148,7 +148,7 @@
<% if (item.teacherPhoto) { %> - <%= item.teacherName %> + <%= item.teacherName %> <% } else { %>
<%= item.teacherName ? item.teacherName[0] : 'Ö' %>
<% } %> @@ -184,7 +184,7 @@
<% if (item.teacherPhoto) { %> - <%= item.teacherName %> + <%= item.teacherName %> <% } else { %>
<%= item.teacherName ? item.teacherName[0] : 'Ö' %>
<% } %> diff --git a/views/syllabus.ejs b/views/syllabus.ejs index 12e0ff5..56e540a 100644 --- a/views/syllabus.ejs +++ b/views/syllabus.ejs @@ -10,7 +10,7 @@ • <% if (lastSynced) { %> - <%= t('syllabus.syncedLabel') %> <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + <%= t('syllabus.syncedLabel') %> <%= formatTime(lastSynced) %> <% } else { %> <%= t('syllabus.notSynced') %> <% } %> @@ -73,7 +73,7 @@
<% [1, 2, 3, 4, 5].forEach(function(d) { %> - <% const isToday = (new Date().getDay() === d); %> + <% const isToday = (istanbulDayOfWeek === d); %>
<% if (l.teacherPhoto) { %> - <%= l.teacher %> + <%= l.teacher %> <% } %> <%= l.teacher %>
@@ -138,7 +138,7 @@ <%= t('syllabus.periodHeader') %> <% [1, 2, 3, 4, 5].forEach(function(d) { %> - <% const isToday = (new Date().getDay() === d); %> + <% const isToday = (istanbulDayOfWeek === d); %> <%= DAY_NAMES[d] %> <% if (isToday) { %><%= t('syllabus.todayBadge') %><% } %>