'use strict'; const path = require('path'); const { Database } = require('node-sqlite3-wasm'); const DB_PATH = path.join(__dirname, '../filemanager.db'); let db; function getDb () { if (!db) { db = new Database(DB_PATH); db.exec('PRAGMA journal_mode = WAL'); db.exec('PRAGMA foreign_keys = ON'); } return db; } function initDb () { const d = getDb(); d.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, uploader TEXT NOT NULL DEFAULT '', downloaders TEXT NOT NULL DEFAULT '[]', watched_by TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS auth_sessions ( session_id TEXT PRIMARY KEY, username TEXT NOT NULL, ip TEXT NOT NULL, region TEXT NOT NULL, fp_hash TEXT NOT NULL, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, revoked_at INTEGER ); CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username); CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at); CREATE TABLE IF NOT EXISTS share_tokens ( token TEXT PRIMARY KEY, file_path TEXT NOT NULL, is_dir INTEGER NOT NULL DEFAULT 0, created_by TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_share_tokens_expires ON share_tokens(expires_at); `); const fileMetaCols = d.prepare('PRAGMA table_info(file_meta)').all(); const hasWatchedBy = fileMetaCols.some((col) => String(col.name || '') === 'watched_by'); if (!hasWatchedBy) { d.exec("ALTER TABLE file_meta ADD COLUMN watched_by TEXT NOT NULL DEFAULT '{}'"); } } function closeDb () { if (db) { db.close(); db = null; } } module.exports = { getDb, initDb, closeDb };