BeKultur/src/services/db.ts

815 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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

import '../utils/time';
import { toIstanbulIsoString } from '../utils/time';
import fs from 'fs';
import path from 'path';
import Database from 'better-sqlite3';
import {
StudentStore,
Assignment,
PrivateLesson,
PrivateLessonFormMeta,
PrivateLessonsStore,
ExamReportDetail,
ExamStore,
ExamTopicWeakness,
ExamQuestionItem,
SyllabusStore
} from '../types';
import {
encryptCredential,
decryptCredentialWithInfo,
syncSecretsWithDatabase
} from './secrets';
const DEFAULT_DB_FILE = path.resolve(process.cwd(), 'data', 'bekultur.db');
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;
private_lessons_json: string | null;
exams_json: string | null;
}
interface AssignmentRow {
student_id: string;
id: string;
subject: string;
type: string;
unit: string;
topic: string;
start_date: string;
end_date: string;
parsed_start_date: string | null;
parsed_end_date: string | null;
description: string;
detected_check_date: string | null;
status: string;
completed: number;
completed_at: string | null;
excluded: number;
page: number | null;
}
export class LocalDatabase {
private static instance: LocalDatabase | null = null;
private sqlite: Database.Database;
private dbPath: string;
public constructor(customDbPath?: string) {
this.dbPath = customDbPath || process.env.DB_PATH || DEFAULT_DB_FILE;
const dir = path.dirname(this.dbPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
this.sqlite = new Database(this.dbPath);
this.initSchema();
this.syncPersistentSecrets();
this.sanitizeStoredCredentials();
}
/**
* Synchronize persistent default secrets between SQLite meta table and .secrets.json
*/
private syncPersistentSecrets(): void {
const getMetaStmt = this.sqlite.prepare('SELECT value FROM meta WHERE key = ?');
const setMetaStmt = this.sqlite.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)');
syncSecretsWithDatabase(
(key: string) => {
const row = getMetaStmt.get(key) as { value: string } | undefined;
return row?.value;
},
(key: string, value: string) => {
setMetaStmt.run(key, value);
}
);
}
/**
* Verify all stored passwords on startup:
* - Re-encrypt any valid passwords that were encrypted with legacy/fallback keys onto the persistent primary key
* - Delete any undecryptable / zombie passwords from old unknown secrets so they never trap sessions
*/
public sanitizeStoredCredentials(): { upgradedCount: number; purgedCount: number } {
const stats = { upgradedCount: 0, purgedCount: 0 };
try {
const rows = this.sqlite
.prepare('SELECT student_id, remembered_password FROM students WHERE remembered_password IS NOT NULL')
.all() as Array<{ student_id: string; remembered_password: string }>;
const nowIso = toIstanbulIsoString();
const updateStmt = this.sqlite.prepare(
'UPDATE students SET remembered_password = ?, updated_at = ? WHERE student_id = ?'
);
for (const row of rows) {
const info = decryptCredentialWithInfo(row.remembered_password);
if (info && info.plaintext) {
if (!info.usedPrimaryKey) {
updateStmt.run(encryptCredential(info.plaintext), nowIso, row.student_id);
stats.upgradedCount++;
}
} else {
// Undecryptable zombie password -> delete it immediately
updateStmt.run(null, nowIso, row.student_id);
stats.purgedCount++;
}
}
} catch (err) {
console.error('Error sanitizing stored credentials:', err);
}
return stats;
}
public static getInstance(): LocalDatabase {
if (!LocalDatabase.instance) {
LocalDatabase.instance = new LocalDatabase();
}
return LocalDatabase.instance;
}
public static resetInstance(): void {
if (LocalDatabase.instance) {
LocalDatabase.instance.close();
LocalDatabase.instance = null;
}
}
public getSqliteDb(): Database.Database {
return this.sqlite;
}
public getDbPath(): string {
return this.dbPath;
}
private initSchema(): void {
this.sqlite.pragma('journal_mode = WAL');
this.sqlite.pragma('synchronous = FULL');
this.sqlite.pragma('foreign_keys = ON');
this.sqlite.pragma('busy_timeout = 5000');
this.sqlite.exec(`
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
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,
private_lessons_json TEXT,
exams_json TEXT,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS assignments (
student_id TEXT NOT NULL,
id TEXT NOT NULL,
subject TEXT NOT NULL,
type TEXT NOT NULL,
unit TEXT NOT NULL DEFAULT '',
topic TEXT NOT NULL DEFAULT '',
start_date TEXT NOT NULL DEFAULT '',
end_date TEXT NOT NULL DEFAULT '',
parsed_start_date TEXT,
parsed_end_date TEXT,
description TEXT NOT NULL DEFAULT '',
detected_check_date TEXT,
status TEXT NOT NULL DEFAULT 'active',
completed INTEGER NOT NULL DEFAULT 0,
completed_at TEXT,
excluded INTEGER NOT NULL DEFAULT 0,
page INTEGER,
PRIMARY KEY (student_id, id),
FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_assignments_student ON assignments(student_id);
CREATE TABLE IF NOT EXISTS sessions (
sid TEXT PRIMARY KEY,
sess TEXT NOT NULL,
expire INTEGER NOT NULL
);
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');
}
}
private ensureStudentRow(studentId: string): StudentRow {
const existing = this.sqlite
.prepare('SELECT * FROM students WHERE student_id = ?')
.get(studentId) as StudentRow | undefined;
if (existing) {
return existing;
}
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, NULL, ?)
`)
.run(studentId, now);
return {
student_id: studentId,
last_synced: null,
last_login_at: null,
remembered_password: null,
advisory_teacher: null,
syllabus_json: null,
private_lessons_json: null,
exams_json: null
};
}
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,
subject: row.subject,
type: row.type,
unit: row.unit,
topic: row.topic,
startDate: row.start_date,
endDate: row.end_date,
parsedStartDate: row.parsed_start_date,
parsedEndDate: row.parsed_end_date,
description: row.description,
detectedCheckDate: row.detected_check_date,
status: row.status as Assignment['status'],
completed: row.completed === 1,
completedAt: row.completed_at,
excluded: row.excluded === 1,
page: row.page ?? undefined
};
}
public getStudentStore(studentId: string): StudentStore {
const row = this.ensureStudentRow(studentId);
const assignmentRows = this.sqlite
.prepare('SELECT * FROM assignments WHERE student_id = ?')
.all(studentId) as AssignmentRow[];
const assignments: Record<string, Assignment> = {};
for (const r of assignmentRows) {
assignments[r.id] = this.mapAssignmentRow(r);
}
const store: StudentStore = {
studentId: row.student_id,
lastSynced: row.last_synced,
assignments
};
if (row.remembered_password) {
store.rememberedCredentials = {
studentId: row.student_id,
password: row.remembered_password
};
}
if (row.advisory_teacher) {
store.advisoryTeacher = row.advisory_teacher;
}
if (row.syllabus_json) {
try {
store.syllabus = JSON.parse(row.syllabus_json) as SyllabusStore;
} catch {
// Ignore malformed JSON
}
}
if (row.private_lessons_json) {
try {
store.privateLessons = JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
} catch {
// Ignore malformed JSON
}
}
if (row.exams_json) {
try {
store.exams = JSON.parse(row.exams_json) as ExamStore;
} catch {
// Ignore malformed JSON
}
}
return store;
}
public mergeAssignments(studentId: string, newAssignments: Assignment[], syncedAt?: string): StudentStore {
this.ensureStudentRow(studentId);
const now = syncedAt || toIstanbulIsoString();
const updateStudentSync = this.sqlite.prepare(
'UPDATE students SET last_synced = ?, updated_at = ? WHERE student_id = ?'
);
const upsertStmt = this.sqlite.prepare(`
INSERT INTO assignments (
student_id,
id,
subject,
type,
unit,
topic,
start_date,
end_date,
parsed_start_date,
parsed_end_date,
description,
detected_check_date,
status,
completed,
completed_at,
excluded,
page
) VALUES (
@student_id,
@id,
@subject,
@type,
@unit,
@topic,
@start_date,
@end_date,
@parsed_start_date,
@parsed_end_date,
@description,
@detected_check_date,
@status,
@completed,
@completed_at,
@excluded,
@page
)
ON CONFLICT(student_id, id) DO UPDATE SET
subject = excluded.subject,
type = excluded.type,
unit = excluded.unit,
topic = excluded.topic,
start_date = excluded.start_date,
end_date = excluded.end_date,
parsed_start_date = excluded.parsed_start_date,
parsed_end_date = excluded.parsed_end_date,
description = excluded.description,
detected_check_date = excluded.detected_check_date,
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
`);
const tx = this.sqlite.transaction(() => {
updateStudentSync.run(now, now, studentId);
for (const item of newAssignments) {
const isCompleted = Boolean(item.completed);
upsertStmt.run({
student_id: studentId,
id: item.id,
subject: item.subject,
type: item.type,
unit: item.unit || '',
topic: item.topic || '',
start_date: item.startDate || '',
end_date: item.endDate || '',
parsed_start_date: item.parsedStartDate || null,
parsed_end_date: item.parsedEndDate || null,
description: item.description || '',
detected_check_date: item.detectedCheckDate || null,
status: isCompleted ? 'completed' : item.status,
completed: isCompleted ? 1 : 0,
completed_at: item.completedAt || null,
excluded: item.excluded ? 1 : 0,
page: item.page ?? null
});
}
});
tx();
return this.getStudentStore(studentId);
}
public toggleExcludeAssignment(
studentId: string,
assignmentId: string,
excluded?: boolean
): Assignment | null {
this.ensureStudentRow(studentId);
const existing = this.sqlite
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
.get(studentId, assignmentId) as AssignmentRow | undefined;
if (!existing) {
return null;
}
const newExcluded = excluded !== undefined ? excluded : existing.excluded !== 1;
this.sqlite
.prepare('UPDATE assignments SET excluded = ? WHERE student_id = ? AND id = ?')
.run(newExcluded ? 1 : 0, studentId, assignmentId);
const updated = this.sqlite
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
.get(studentId, assignmentId) as AssignmentRow;
return this.mapAssignmentRow(updated);
}
public toggleAssignment(
studentId: string,
assignmentId: string,
completed?: boolean
): Assignment | null {
this.ensureStudentRow(studentId);
const existing = this.sqlite
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
.get(studentId, assignmentId) as AssignmentRow | undefined;
if (!existing) {
return null;
}
const newCompleted = completed !== undefined ? completed : existing.completed !== 1;
const completedAt = newCompleted ? toIstanbulIsoString() : null;
const newStatus = newCompleted ? 'completed' : existing.status;
this.sqlite
.prepare(
'UPDATE assignments SET completed = ?, completed_at = ?, status = ? WHERE student_id = ? AND id = ?'
)
.run(newCompleted ? 1 : 0, completedAt, newStatus, studentId, assignmentId);
const updated = this.sqlite
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
.get(studentId, assignmentId) as AssignmentRow;
return this.mapAssignmentRow(updated);
}
public saveCredentials(studentId: string, password: string): void {
this.ensureStudentRow(studentId);
const encryptedPassword = encryptCredential(password);
this.sqlite
.prepare('UPDATE students SET remembered_password = ?, updated_at = ? WHERE student_id = ?')
.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(toIstanbulIsoString(), studentId);
}
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
const row = this.sqlite
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
.get(studentId) as { remembered_password: string | null } | undefined;
if (!row?.remembered_password) {
return null;
}
const info = decryptCredentialWithInfo(row.remembered_password);
if (!info || !info.plaintext) {
// Delete undecryptable / old-secret password immediately to prevent zombie passwords
this.clearCredentials(studentId);
return null;
}
if (!info.usedPrimaryKey) {
// Upgrade to canonical persistent secret
this.saveCredentials(studentId, info.plaintext);
}
return {
studentId,
password: info.plaintext
};
}
public getRawEncryptedPassword(studentId: string): string | null {
const row = this.sqlite
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
.get(studentId) as { remembered_password: string | null } | undefined;
return row?.remembered_password || null;
}
public saveSyllabus(
studentId: string,
weekId: string,
weekRange: string,
schedule: Record<number, any>,
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 hasNewLessons =
schedule &&
Object.values(schedule).some(arr => Array.isArray(arr) && arr.length > 0);
const hasExistingLessons =
existingSyllabus?.schedule &&
Object.values(existingSyllabus.schedule).some(arr => Array.isArray(arr) && arr.length > 0);
const effectiveSchedule = !hasNewLessons && hasExistingLessons ? existingSyllabus!.schedule : schedule;
const syllabus: SyllabusStore = {
weekId,
weekRange,
selectedStation: existingStation,
advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null,
lastSynced: now,
schedule: effectiveSchedule
};
this.sqlite
.prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?')
.run(JSON.stringify(syllabus), now, studentId);
}
public setStudentStation(studentId: string, station: string | null): void {
const row = this.ensureStudentRow(studentId);
let syllabus: SyllabusStore;
if (row.syllabus_json) {
syllabus = JSON.parse(row.syllabus_json) as SyllabusStore;
syllabus.selectedStation = station;
} else {
syllabus = {
weekId: '',
weekRange: '',
selectedStation: station,
lastSynced: null,
schedule: {}
};
}
this.sqlite
.prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?')
.run(JSON.stringify(syllabus), toIstanbulIsoString(), studentId);
}
public getSyllabus(studentId: string): SyllabusStore | null {
const row = this.sqlite
.prepare('SELECT syllabus_json FROM students WHERE student_id = ?')
.get(studentId) as { syllabus_json: string | null } | undefined;
if (!row?.syllabus_json) return null;
try {
return JSON.parse(row.syllabus_json) as SyllabusStore;
} catch {
return null;
}
}
public savePrivateLessons(
studentId: string,
lessons: PrivateLesson[],
formMeta?: PrivateLessonFormMeta,
detectedAdvisor?: string
): void {
const row = this.ensureStudentRow(studentId);
const existing = row.private_lessons_json
? (JSON.parse(row.private_lessons_json) as PrivateLessonsStore)
: null;
const privateLessons: PrivateLessonsStore = {
lastSynced: toIstanbulIsoString(),
lessons,
formMeta: formMeta || existing?.formMeta,
detectedAdvisor: detectedAdvisor || existing?.detectedAdvisor
};
let newAdvisor = row.advisory_teacher;
let updatedSyllabusJson = row.syllabus_json;
if (detectedAdvisor && !newAdvisor) {
newAdvisor = detectedAdvisor;
if (updatedSyllabusJson) {
try {
const syl = JSON.parse(updatedSyllabusJson) as SyllabusStore;
syl.advisoryTeacher = detectedAdvisor;
updatedSyllabusJson = JSON.stringify(syl);
} catch {
// ignore
}
}
}
this.sqlite
.prepare(
'UPDATE students SET private_lessons_json = ?, advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?'
)
.run(
JSON.stringify(privateLessons),
newAdvisor,
updatedSyllabusJson,
toIstanbulIsoString(),
studentId
);
}
public getPrivateLessons(studentId: string): PrivateLessonsStore | null {
const row = this.sqlite
.prepare('SELECT private_lessons_json FROM students WHERE student_id = ?')
.get(studentId) as { private_lessons_json: string | null } | undefined;
if (!row?.private_lessons_json) return null;
try {
return JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
} catch {
return null;
}
}
public setStudentAdvisoryTeacher(studentId: string, teacher: string | null): void {
const row = this.ensureStudentRow(studentId);
let updatedSyllabusJson = row.syllabus_json;
if (updatedSyllabusJson) {
try {
const syl = JSON.parse(updatedSyllabusJson) as SyllabusStore;
syl.advisoryTeacher = teacher;
updatedSyllabusJson = JSON.stringify(syl);
} catch {
// ignore
}
}
this.sqlite
.prepare('UPDATE students SET advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?')
.run(teacher, updatedSyllabusJson, toIstanbulIsoString(), studentId);
}
public getStudentAdvisoryTeacher(studentId: string): string | null {
const row = this.sqlite
.prepare('SELECT advisory_teacher, private_lessons_json FROM students WHERE student_id = ?')
.get(studentId) as { advisory_teacher: string | null; private_lessons_json: string | null } | undefined;
if (!row) return null;
if (row.advisory_teacher) return row.advisory_teacher;
if (row.private_lessons_json) {
try {
const pl = JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
return pl.detectedAdvisor || null;
} catch {
return null;
}
}
return null;
}
// ----------------------------------------------------
// Exam Reports (Sınav Rapor) Store
// ----------------------------------------------------
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<string, ExamReportDetail> = existing?.reports ? { ...existing.reports } : {};
const now = syncedAt || toIstanbulIsoString();
reports.forEach(r => {
reportsMap[r.summary.id] = r;
});
const exams: ExamStore = {
lastSynced: now,
reports: reportsMap,
topicWeaknesses: existing?.topicWeaknesses || {},
questions: existing?.questions || {}
};
this.sqlite
.prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
.run(JSON.stringify(exams), now, studentId);
}
public getExamReports(studentId: string): ExamStore | null {
const row = this.sqlite
.prepare('SELECT exams_json FROM students WHERE student_id = ?')
.get(studentId) as { exams_json: string | null } | undefined;
if (!row?.exams_json) return null;
try {
return JSON.parse(row.exams_json) as ExamStore;
} catch {
return null;
}
}
public saveTopicWeaknesses(studentId: string, examId: string, weaknesses: ExamTopicWeakness[]): void {
const row = this.ensureStudentRow(studentId);
const exams: ExamStore = row.exams_json
? (JSON.parse(row.exams_json) as ExamStore)
: {
lastSynced: toIstanbulIsoString(),
reports: {},
topicWeaknesses: {},
questions: {}
};
if (!exams.topicWeaknesses) {
exams.topicWeaknesses = {};
}
exams.topicWeaknesses[examId] = weaknesses;
this.sqlite
.prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
.run(JSON.stringify(exams), toIstanbulIsoString(), studentId);
}
public getTopicWeaknesses(studentId: string, examId: string): ExamTopicWeakness[] | null {
const exams = this.getExamReports(studentId);
return exams?.topicWeaknesses?.[examId] || null;
}
public saveExamQuestions(studentId: string, examId: string, questions: ExamQuestionItem[]): void {
const row = this.ensureStudentRow(studentId);
const exams: ExamStore = row.exams_json
? (JSON.parse(row.exams_json) as ExamStore)
: {
lastSynced: toIstanbulIsoString(),
reports: {},
topicWeaknesses: {},
questions: {}
};
if (!exams.questions) {
exams.questions = {};
}
exams.questions[examId] = questions;
this.sqlite
.prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
.run(JSON.stringify(exams), toIstanbulIsoString(), studentId);
}
public getExamQuestions(studentId: string, examId: string): ExamQuestionItem[] | null {
const exams = this.getExamReports(studentId);
return exams?.questions?.[examId] || null;
}
public close(): void {
try {
if (this.sqlite && this.sqlite.open) {
try {
this.sqlite.pragma('wal_checkpoint(TRUNCATE)');
} catch {
// Ignore checkpoint errors
}
this.sqlite.close();
}
} catch {
// Ignore close errors
}
}
}