"""SQLite storage for chat history.""" import os import sqlite3 import time from pathlib import Path DB_PATH = Path(os.environ.get("DB_PATH", "./smeta-web.db")) _CREATE = """ CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, username TEXT NOT NULL, tab_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, timestamp REAL NOT NULL ); CREATE INDEX IF NOT EXISTS idx_session ON messages(username, tab_id); CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', verified INTEGER NOT NULL DEFAULT 0, blocked INTEGER NOT NULL DEFAULT 0, verify_code TEXT, verify_expires REAL, created_at REAL NOT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email); CREATE TABLE IF NOT EXISTS invites ( id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, created_by TEXT NOT NULL, used_by TEXT, created_at REAL NOT NULL, expires_at REAL NOT NULL ); """ def _conn() -> sqlite3.Connection: conn = sqlite3.connect(str(DB_PATH)) conn.row_factory = sqlite3.Row return conn def init_db(): with _conn() as conn: conn.executescript(_CREATE) # Migration: add blocked column if missing try: conn.execute("SELECT blocked FROM users LIMIT 1") except sqlite3.OperationalError: conn.execute("ALTER TABLE users ADD COLUMN blocked INTEGER NOT NULL DEFAULT 0") def save_message(username: str, tab_id: str, role: str, content: str): """Save a user or assistant message.""" with _conn() as conn: conn.execute( "INSERT INTO messages (session_id, username, tab_id, role, content, timestamp) " "VALUES (?, ?, ?, ?, ?, ?)", (f"{username}/{tab_id}", username, tab_id, role, content, time.time()), ) def get_history(username: str, tab_id: str, limit: int = 100) -> list[dict]: """Get chat history for a specific tab.""" with _conn() as conn: rows = conn.execute( "SELECT role, content, timestamp FROM messages " "WHERE username = ? AND tab_id = ? ORDER BY id DESC LIMIT ?", (username, tab_id, limit), ).fetchall() return [dict(r) for r in reversed(rows)] # === Users === def create_user(email: str, password_hash: str, role: str = "user") -> int: with _conn() as conn: cur = conn.execute( "INSERT INTO users (email, password_hash, role, created_at) VALUES (?, ?, ?, ?)", (email.lower().strip(), password_hash, role, time.time()), ) return cur.lastrowid def get_user_by_email(email: str) -> dict | None: with _conn() as conn: row = conn.execute( "SELECT * FROM users WHERE email = ?", (email.lower().strip(),) ).fetchone() return dict(row) if row else None def set_verify_code(email: str, code: str, expires_in: int = 600): with _conn() as conn: conn.execute( "UPDATE users SET verify_code = ?, verify_expires = ? WHERE email = ?", (code, time.time() + expires_in, email.lower().strip()), ) def verify_user(email: str, code: str) -> bool: with _conn() as conn: user = conn.execute( "SELECT verify_code, verify_expires FROM users WHERE email = ?", (email.lower().strip(),), ).fetchone() if not user or user["verify_code"] != code: return False if user["verify_expires"] and time.time() > user["verify_expires"]: return False conn.execute( "UPDATE users SET verified = 1, verify_code = NULL WHERE email = ?", (email.lower().strip(),), ) return True def list_users() -> list[dict]: with _conn() as conn: rows = conn.execute( "SELECT id, email, role, verified, blocked, created_at FROM users ORDER BY created_at DESC" ).fetchall() return [dict(r) for r in rows] def block_user(email: str, blocked: bool = True): with _conn() as conn: conn.execute("UPDATE users SET blocked = ? WHERE email = ?", (1 if blocked else 0, email.lower().strip())) def delete_user(email: str): with _conn() as conn: conn.execute("DELETE FROM users WHERE email = ?", (email.lower().strip(),)) def set_user_role(email: str, role: str): if role not in ("admin", "user"): return with _conn() as conn: conn.execute("UPDATE users SET role = ? WHERE email = ?", (role, email.lower().strip())) def admin_verify_user(email: str): with _conn() as conn: conn.execute("UPDATE users SET verified = 1, verify_code = NULL WHERE email = ?", (email.lower().strip(),)) # === Invites === def create_invite(token: str, created_by: str, expires_hours: int = 72) -> int: with _conn() as conn: cur = conn.execute( "INSERT INTO invites (token, created_by, created_at, expires_at) VALUES (?, ?, ?, ?)", (token, created_by, time.time(), time.time() + expires_hours * 3600), ) return cur.lastrowid def use_invite(token: str, used_by: str) -> bool: with _conn() as conn: invite = conn.execute( "SELECT * FROM invites WHERE token = ? AND used_by IS NULL", (token,), ).fetchone() if not invite: return False if time.time() > invite["expires_at"]: return False conn.execute( "UPDATE invites SET used_by = ? WHERE token = ?", (used_by, token), ) return True def list_invites() -> list[dict]: with _conn() as conn: rows = conn.execute( "SELECT token, created_by, used_by, created_at, expires_at FROM invites ORDER BY created_at DESC LIMIT 50" ).fetchall() return [dict(r) for r in rows] def list_sessions(username: str) -> list[dict]: """List all chat sessions for a user with last message preview.""" with _conn() as conn: rows = conn.execute( "SELECT tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, " "(SELECT content FROM messages m2 WHERE m2.username = messages.username " " AND m2.tab_id = messages.tab_id AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question " "FROM messages WHERE username = ? GROUP BY tab_id ORDER BY last_ts DESC", (username,), ).fetchall() return [dict(r) for r in rows]