"""Isolated SQLite store for 游民社区 — never touches community/PB tables.""" from __future__ import annotations import json import sqlite3 import time import uuid from contextlib import contextmanager from pathlib import Path from typing import Any, Iterator from .config import SOCIAL_DB_PATH try: from ebook_svc.core.sqlite_util import connect as _connect except Exception: # pragma: no cover def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection: p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) c = sqlite3.connect(str(p), timeout=timeout) c.row_factory = sqlite3.Row c.execute("PRAGMA journal_mode=WAL") return c def _uid(prefix: str) -> str: return f"{prefix}_{uuid.uuid4().hex[:12]}" def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) @contextmanager def db() -> Iterator[sqlite3.Connection]: SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True) conn = _connect(SOCIAL_DB_PATH) try: yield conn conn.commit() except Exception: conn.rollback() raise finally: conn.close() def init_db() -> None: with db() as conn: conn.executescript( """ CREATE TABLE IF NOT EXISTS messages ( id TEXT PRIMARY KEY, channel_id TEXT NOT NULL, author TEXT NOT NULL, text TEXT NOT NULL, guest_id TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, created_at); CREATE TABLE IF NOT EXISTS cafe_reviews ( id TEXT PRIMARY KEY, cafe_id TEXT NOT NULL, author TEXT NOT NULL, score INTEGER NOT NULL, text TEXT NOT NULL, photo_note TEXT, guest_id TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_reviews_cafe ON cafe_reviews(cafe_id, created_at); CREATE TABLE IF NOT EXISTS roster ( guest_id TEXT PRIMARY KEY, name TEXT NOT NULL, title TEXT, city TEXT, phone TEXT, linktree TEXT, skills TEXT, bio TEXT, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS feedback ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, text TEXT NOT NULL, contact TEXT, guest_id TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS gig_apps ( id TEXT PRIMARY KEY, gig_id TEXT NOT NULL, name TEXT NOT NULL, contact TEXT NOT NULL, note TEXT, guest_id TEXT NOT NULL, created_at TEXT NOT NULL ); """ ) def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]: with db() as conn: rows = conn.execute( """ SELECT id, channel_id, author, text, guest_id, created_at FROM messages WHERE channel_id = ? ORDER BY created_at ASC LIMIT ? """, (channel_id, max(1, min(limit, 500))), ).fetchall() return [ { "id": r["id"], "channelId": r["channel_id"], "author": r["author"], "text": r["text"], "guestId": r["guest_id"], "at": r["created_at"], } for r in rows ] def add_message(channel_id: str, author: str, text: str, guest_id: str) -> dict[str, Any]: item = { "id": _uid("msg"), "channelId": channel_id, "author": (author or "游民").strip()[:48] or "游民", "text": text.strip()[:2000], "guestId": guest_id, "at": _now(), } with db() as conn: conn.execute( """ INSERT INTO messages(id, channel_id, author, text, guest_id, created_at) VALUES (?, ?, ?, ?, ?, ?) """, (item["id"], item["channelId"], item["author"], item["text"], guest_id, item["at"]), ) return item def list_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]: with db() as conn: rows = conn.execute( """ SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at FROM cafe_reviews WHERE cafe_id = ? ORDER BY created_at DESC LIMIT ? """, (cafe_id, max(1, min(limit, 200))), ).fetchall() return [ { "id": r["id"], "cafeId": r["cafe_id"], "author": r["author"], "score": r["score"], "text": r["text"], "photoNote": r["photo_note"] or "", "guestId": r["guest_id"], "at": r["created_at"], } for r in rows ] def add_review( cafe_id: str, author: str, score: int, text: str, photo_note: str, guest_id: str, ) -> dict[str, Any]: item = { "id": _uid("rv"), "cafeId": cafe_id, "author": (author or "游民").strip()[:48] or "游民", "score": max(1, min(int(score or 5), 5)), "text": text.strip()[:2000], "photoNote": (photo_note or "").strip()[:200], "guestId": guest_id, "at": _now(), } with db() as conn: conn.execute( """ INSERT INTO cafe_reviews(id, cafe_id, author, score, text, photo_note, guest_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, ( item["id"], item["cafeId"], item["author"], item["score"], item["text"], item["photoNote"], guest_id, item["at"], ), ) return item def get_roster(guest_id: str) -> dict[str, Any] | None: with db() as conn: r = conn.execute("SELECT * FROM roster WHERE guest_id = ?", (guest_id,)).fetchone() if not r: return None return { "guestId": r["guest_id"], "name": r["name"], "title": r["title"] or "", "city": r["city"] or "", "phone": r["phone"] or "", "linktree": r["linktree"] or "", "skills": r["skills"] or "", "bio": r["bio"] or "", "updatedAt": r["updated_at"], } def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: updated = _now() row = { "guestId": guest_id, "name": str(payload.get("name") or "").strip()[:64] or "游民", "title": str(payload.get("title") or "").strip()[:80], "city": str(payload.get("city") or "").strip()[:64], "phone": str(payload.get("phone") or "").strip()[:32], "linktree": str(payload.get("linktree") or "").strip()[:240], "skills": str(payload.get("skills") or "").strip()[:200], "bio": str(payload.get("bio") or "").strip()[:2000], "updatedAt": updated, } with db() as conn: conn.execute( """ INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(guest_id) DO UPDATE SET name=excluded.name, title=excluded.title, city=excluded.city, phone=excluded.phone, linktree=excluded.linktree, skills=excluded.skills, bio=excluded.bio, updated_at=excluded.updated_at """, ( guest_id, row["name"], row["title"], row["city"], row["phone"], row["linktree"], row["skills"], row["bio"], updated, ), ) return row def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: item = { "id": _uid("fb"), "kind": kind if kind in {"反馈", "建议"} else "建议", "text": text.strip()[:4000], "contact": (contact or "").strip()[:120], "guestId": guest_id, "at": _now(), } with db() as conn: conn.execute( """ INSERT INTO feedback(id, kind, text, contact, guest_id, created_at) VALUES (?, ?, ?, ?, ?, ?) """, (item["id"], item["kind"], item["text"], item["contact"], guest_id, item["at"]), ) return item def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str) -> dict[str, Any]: item = { "id": _uid("app"), "gigId": gig_id, "name": name.strip()[:64], "contact": contact.strip()[:120], "note": (note or "").strip()[:2000], "guestId": guest_id, "at": _now(), } with db() as conn: conn.execute( """ INSERT INTO gig_apps(id, gig_id, name, contact, note, guest_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) """, (item["id"], item["gigId"], item["name"], item["contact"], item["note"], guest_id, item["at"]), ) return item def health() -> dict[str, Any]: init_db() exists = SOCIAL_DB_PATH.exists() size = SOCIAL_DB_PATH.stat().st_size if exists else 0 return { "ok": True, "module": "social", "db": str(SOCIAL_DB_PATH), "dbBytes": size, "isolated": True, }