"""游民社区 UGC 管理 — 直连 social.db(US 生产;软删除 + social_archives)。 默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db """ from __future__ import annotations import json import os import sqlite3 import time import uuid from contextlib import contextmanager from pathlib import Path from typing import Any, Iterator from app.core.sqlite_util import connect as _connect _DEFAULT = Path("/var/www/nomadro-data/social/social.db") SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve() ENTITY_TABLES = { "roster": ("roster", "guest_id"), "messages": ("messages", "id"), "reviews": ("cafe_reviews", "id"), "gigApps": ("gig_apps", "id"), "feedback": ("feedback", "id"), } def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) def _uid(prefix: str = "arc") -> str: return f"{prefix}_{uuid.uuid4().hex[:12]}" @contextmanager def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]: SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True) if readonly and SOCIAL_DB_PATH.is_file(): uri = f"file:{SOCIAL_DB_PATH.as_posix()}?mode=ro" conn = sqlite3.connect(uri, uri=True, timeout=30.0) conn.row_factory = sqlite3.Row else: conn = _connect(SOCIAL_DB_PATH) try: if not readonly: _ensure_schema(conn) yield conn if not readonly: conn.commit() except Exception: if not readonly: conn.rollback() raise finally: conn.close() def _ensure_schema(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TABLE IF NOT EXISTS social_archives ( id TEXT PRIMARY KEY, entity TEXT NOT NULL, entity_id TEXT NOT NULL, guest_id TEXT DEFAULT '', action TEXT NOT NULL, note TEXT DEFAULT '', payload TEXT DEFAULT '{}', created_at TEXT NOT NULL ) """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_social_archives_entity ON social_archives(entity, entity_id, created_at)" ) conn.execute( """ CREATE TABLE IF NOT EXISTS join_leads ( id TEXT PRIMARY KEY, email TEXT NOT NULL, guest_id TEXT DEFAULT '', stage TEXT DEFAULT '', name TEXT DEFAULT '', paid TEXT DEFAULT '', face_ok TEXT DEFAULT '', liveness_status TEXT DEFAULT '', ua TEXT DEFAULT '', payload TEXT DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL ) """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_join_leads_email ON join_leads(email)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_join_leads_updated ON join_leads(updated_at)" ) # soft-delete markers on live tables (idempotent) for table, _pk in { "roster": "guest_id", "messages": "id", "cafe_reviews": "id", "gig_apps": "id", "feedback": "id", }.items(): cols = {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()} if "deleted_at" not in cols: try: conn.execute(f"ALTER TABLE {table} ADD COLUMN deleted_at TEXT") except sqlite3.OperationalError: pass if table == "roster" and "status" not in cols: try: conn.execute("ALTER TABLE roster ADD COLUMN status TEXT DEFAULT ''") except sqlite3.OperationalError: pass def _row_dict(row: sqlite3.Row | None) -> dict[str, Any] | None: if row is None: return None return {k: row[k] for k in row.keys()} def _archive( conn: sqlite3.Connection, *, entity: str, entity_id: str, action: str, payload: dict[str, Any] | None, guest_id: str = "", note: str = "", ) -> str: aid = _uid("arc") conn.execute( """ INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at) VALUES(?,?,?,?,?,?,?,?) """, ( aid, entity, entity_id, guest_id or "", action, note or "", json.dumps(payload or {}, ensure_ascii=False), _now(), ), ) return aid def _soft_delete( conn: sqlite3.Connection, *, entity: str, entity_id: str, table: str, pk: str, guest_id: str = "", ) -> bool: row = conn.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone() if not row: return False payload = _row_dict(row) or {} if payload.get("deleted_at"): return True _archive( conn, entity=entity, entity_id=entity_id, action="soft_delete", payload=payload, guest_id=guest_id or str(payload.get("guest_id") or ""), ) if table == "roster": conn.execute( "UPDATE roster SET deleted_at=?, status='deleted', updated_at=? WHERE guest_id=?", (_now(), _now(), entity_id), ) else: conn.execute( f"UPDATE {table} SET deleted_at=? WHERE {pk}=?", (_now(), entity_id), ) return True def _alive_clause(alias: str = "") -> str: col = f"{alias}.deleted_at" if alias else "deleted_at" return f"({col} IS NULL OR {col}='')" def available() -> dict[str, Any]: exists = SOCIAL_DB_PATH.is_file() size = SOCIAL_DB_PATH.stat().st_size if exists else 0 writable = False if exists: try: writable = os.access(SOCIAL_DB_PATH, os.W_OK) except Exception: writable = False return { "ok": True, "path": str(SOCIAL_DB_PATH), "exists": exists, "bytes": size, "writable": writable, "backend": "sqlite", } def overview() -> dict[str, Any]: info = available() counts = { "messages": 0, "roster": 0, "reviews": 0, "gigApps": 0, "feedback": 0, } if not info["exists"]: return {**info, "counts": counts} try: with _db() as c: counts["messages"] = c.execute( f"SELECT COUNT(*) AS n FROM messages WHERE {_alive_clause()}" ).fetchone()["n"] counts["roster"] = c.execute( f"SELECT COUNT(*) AS n FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'" ).fetchone()["n"] counts["reviews"] = c.execute( f"SELECT COUNT(*) AS n FROM cafe_reviews WHERE {_alive_clause()}" ).fetchone()["n"] counts["gigApps"] = c.execute( f"SELECT COUNT(*) AS n FROM gig_apps WHERE {_alive_clause()}" ).fetchone()["n"] counts["feedback"] = c.execute( f"SELECT COUNT(*) AS n FROM feedback WHERE {_alive_clause()}" ).fetchone()["n"] except Exception as e: return {**info, "counts": counts, "error": str(e)} return {**info, "counts": counts} def list_messages( *, channel_id: str = "", q: str = "", limit: int = 100, offset: int = 0, ) -> dict[str, Any]: limit = max(1, min(int(limit or 100), 500)) offset = max(0, int(offset or 0)) clauses: list[str] = [_alive_clause()] params: list[Any] = [] if channel_id.strip(): clauses.append("channel_id=?") params.append(channel_id.strip()) if q.strip(): clauses.append("(author LIKE ? OR text LIKE ? OR guest_id LIKE ?)") like = f"%{q.strip()}%" params.extend([like, like, like]) where = f" WHERE {' AND '.join(clauses)}" with _db() as c: total = c.execute(f"SELECT COUNT(*) AS n FROM messages{where}", tuple(params)).fetchone()["n"] rows = c.execute( f""" SELECT id, channel_id, author, text, guest_id, created_at, deleted_at FROM messages{where} ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ? """, (*params, limit, offset), ).fetchall() items = [ { "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 ] return {"ok": True, "total": total, "items": items} def delete_message(message_id: str) -> bool: with _db() as c: return _soft_delete( c, entity="messages", entity_id=message_id, table="messages", pk="id" ) def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: limit = max(1, min(int(limit or 100), 500)) offset = max(0, int(offset or 0)) clauses: list[str] = [_alive_clause(), "IFNULL(status,'')!='deleted'"] params: list[Any] = [] if q.strip(): clauses.append("(name LIKE ? OR city LIKE ? OR title LIKE ? OR guest_id LIKE ? OR bio LIKE ?)") like = f"%{q.strip()}%" params.extend([like, like, like, like, like]) where = f" WHERE {' AND '.join(clauses)}" with _db() as c: total = c.execute(f"SELECT COUNT(*) AS n FROM roster{where}", tuple(params)).fetchone()["n"] rows = c.execute( f""" SELECT guest_id, name, title, city, phone, linktree, skills, bio, updated_at, status, deleted_at FROM roster{where} ORDER BY updated_at DESC LIMIT ? OFFSET ? """, (*params, limit, offset), ).fetchall() items = [ { "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"], "status": r["status"] or "", } for r in rows ] return {"ok": True, "total": total, "items": items} def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: with _db() as c: row = c.execute("SELECT * FROM roster WHERE guest_id=?", (guest_id,)).fetchone() if not row: return None restore = bool(patch.get("restore")) fields = { "name": str(patch.get("name", row["name"] or ""))[:64] or "游民", "title": str(patch.get("title", row["title"] or ""))[:80], "city": str(patch.get("city", row["city"] or ""))[:64], "phone": str(patch.get("phone", row["phone"] or ""))[:32], "linktree": str(patch.get("linktree", row["linktree"] or ""))[:240], "skills": str(patch.get("skills", row["skills"] or ""))[:200], "bio": str(patch.get("bio", row["bio"] or ""))[:2000], } status = str(patch.get("status", row["status"] if "status" in row.keys() else "") or "") deleted_at = row["deleted_at"] if "deleted_at" in row.keys() else None if restore: status = "" deleted_at = None _archive( c, entity="roster", entity_id=guest_id, action="restore", payload=_row_dict(row), guest_id=guest_id, ) updated = _now() c.execute( """ UPDATE roster SET name=?, title=?, city=?, phone=?, linktree=?, skills=?, bio=?, status=?, deleted_at=?, updated_at=? WHERE guest_id=? """, ( fields["name"], fields["title"], fields["city"], fields["phone"], fields["linktree"], fields["skills"], fields["bio"], status, deleted_at, updated, guest_id, ), ) _archive( c, entity="roster", entity_id=guest_id, action="update", payload={**fields, "status": status}, guest_id=guest_id, ) return { **fields, "guestId": guest_id, "updatedAt": updated, "status": status, } def delete_roster(guest_id: str) -> bool: with _db() as c: return _soft_delete( c, entity="roster", entity_id=guest_id, table="roster", pk="guest_id", guest_id=guest_id, ) def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: limit = max(1, min(int(limit or 100), 500)) offset = max(0, int(offset or 0)) clauses: list[str] = [_alive_clause()] params: list[Any] = [] if cafe_id.strip(): clauses.append("cafe_id=?") params.append(cafe_id.strip()) where = f" WHERE {' AND '.join(clauses)}" with _db() as c: total = c.execute( f"SELECT COUNT(*) AS n FROM cafe_reviews{where}", tuple(params) ).fetchone()["n"] rows = c.execute( f""" SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at FROM cafe_reviews{where} ORDER BY created_at DESC LIMIT ? OFFSET ? """, (*params, limit, offset), ).fetchall() items = [ { "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 ] return {"ok": True, "total": total, "items": items} def delete_review(review_id: str) -> bool: with _db() as c: return _soft_delete( c, entity="reviews", entity_id=review_id, table="cafe_reviews", pk="id" ) def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: limit = max(1, min(int(limit or 100), 500)) offset = max(0, int(offset or 0)) clauses: list[str] = [_alive_clause()] params: list[Any] = [] if gig_id.strip(): clauses.append("gig_id=?") params.append(gig_id.strip()) where = f" WHERE {' AND '.join(clauses)}" with _db() as c: total = c.execute( f"SELECT COUNT(*) AS n FROM gig_apps{where}", tuple(params) ).fetchone()["n"] rows = c.execute( f""" SELECT id, gig_id, name, contact, note, guest_id, created_at FROM gig_apps{where} ORDER BY created_at DESC LIMIT ? OFFSET ? """, (*params, limit, offset), ).fetchall() items = [ { "id": r["id"], "gigId": r["gig_id"], "name": r["name"], "contact": r["contact"], "note": r["note"] or "", "guestId": r["guest_id"], "at": r["created_at"], } for r in rows ] return {"ok": True, "total": total, "items": items} def delete_gig_app(app_id: str) -> bool: with _db() as c: return _soft_delete( c, entity="gigApps", entity_id=app_id, table="gig_apps", pk="id" ) def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: limit = max(1, min(int(limit or 100), 500)) offset = max(0, int(offset or 0)) where = f" WHERE {_alive_clause()}" with _db() as c: total = c.execute(f"SELECT COUNT(*) AS n FROM feedback{where}").fetchone()["n"] rows = c.execute( f""" SELECT id, kind, text, contact, guest_id, created_at FROM feedback{where} ORDER BY created_at DESC LIMIT ? OFFSET ? """, (limit, offset), ).fetchall() items = [ { "id": r["id"], "kind": r["kind"], "text": r["text"], "contact": r["contact"] or "", "guestId": r["guest_id"], "at": r["created_at"], } for r in rows ] return {"ok": True, "total": total, "items": items} def delete_feedback(fid: str) -> bool: with _db() as c: return _soft_delete( c, entity="feedback", entity_id=fid, table="feedback", pk="id" ) def stats() -> dict[str, Any]: with _db() as c: def cnt(sql: str) -> int: return int(c.execute(sql).fetchone()[0]) counts = { "messages": cnt(f"SELECT COUNT(*) FROM messages WHERE {_alive_clause()}"), "roster": cnt( f"SELECT COUNT(*) FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'" ), "reviews": cnt(f"SELECT COUNT(*) FROM cafe_reviews WHERE {_alive_clause()}"), "gigApps": cnt(f"SELECT COUNT(*) FROM gig_apps WHERE {_alive_clause()}"), "feedback": cnt(f"SELECT COUNT(*) FROM feedback WHERE {_alive_clause()}"), "archives": cnt("SELECT COUNT(*) FROM social_archives"), } soft = { "roster": cnt( "SELECT COUNT(*) FROM roster WHERE (deleted_at IS NOT NULL AND deleted_at!='') OR status='deleted'" ), "messages": cnt( "SELECT COUNT(*) FROM messages WHERE deleted_at IS NOT NULL AND deleted_at!=''" ), "reviews": cnt( "SELECT COUNT(*) FROM cafe_reviews WHERE deleted_at IS NOT NULL AND deleted_at!=''" ), "gigApps": cnt( "SELECT COUNT(*) FROM gig_apps WHERE deleted_at IS NOT NULL AND deleted_at!=''" ), "feedback": cnt( "SELECT COUNT(*) FROM feedback WHERE deleted_at IS NOT NULL AND deleted_at!=''" ), } rows = c.execute( f""" SELECT IFNULL(NULLIF(TRIM(city),''),'未填') AS city, COUNT(*) AS n FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted' GROUP BY 1 ORDER BY n DESC LIMIT 12 """ ).fetchall() by_city = [{"name": r["city"], "value": int(r["n"])} for r in rows] day_rows = c.execute( f""" SELECT substr(updated_at,1,10) AS d, COUNT(*) AS n FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted' AND updated_at IS NOT NULL AND updated_at!='' GROUP BY 1 ORDER BY 1 """ ).fetchall() day_series = [{"date": r["d"], "value": int(r["n"])} for r in day_rows][-30:] return { "ok": True, "counts": counts, "softDeleted": soft, "activeRoster": counts["roster"], "byCity": by_city, "rosterByDay": day_series, "backend": "sqlite", } def get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: meta = ENTITY_TABLES.get(entity) if not meta: return None table, pk = meta with _db() as c: row = c.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone() if not row: return None item = _row_dict(row) or {} hist = c.execute( """ SELECT id, action, note, payload, created_at FROM social_archives WHERE entity=? AND entity_id=? ORDER BY created_at DESC LIMIT 50 """, (entity, entity_id), ).fetchall() soft = bool(item.get("deleted_at")) or item.get("status") == "deleted" history = [] for h in hist: try: payload = json.loads(h["payload"] or "{}") except Exception: payload = {} history.append( { "id": h["id"], "action": h["action"], "at": h["created_at"], "note": h["note"] or "", "payload": payload, } ) return { "ok": True, "entity": entity, "id": entity_id, "item": item, "softDeleted": soft, "history": history, } def upsert_join_lead( *, email: str, guest_id: str = "", stage: str = "email_submit", name: str = "", payload: dict[str, Any] | None = None, ua: str = "", paid: str = "", face_ok: str = "", liveness_status: str = "", ) -> dict[str, Any]: email_n = (email or "").strip().lower()[:160] if not email_n or "@" not in email_n: raise ValueError("invalid email") now = _now() stage_n = (stage or "email_submit")[:48] body = payload if isinstance(payload, dict) else {} with _db() as c: existing = c.execute( "SELECT * FROM join_leads WHERE email=?", (email_n,) ).fetchone() if existing: new_payload = {} try: new_payload = json.loads(existing["payload"] or "{}") except Exception: new_payload = {} if isinstance(new_payload, dict): stages = list(new_payload.get("stages") or []) if stage_n not in stages: stages.append(stage_n) new_payload = {**new_payload, **body, "stages": stages} else: new_payload = {**body, "stages": [stage_n]} c.execute( """ UPDATE join_leads SET guest_id=COALESCE(NULLIF(?,''), guest_id), stage=?, name=COALESCE(NULLIF(?,''), name), paid=COALESCE(NULLIF(?,''), paid), face_ok=COALESCE(NULLIF(?,''), face_ok), liveness_status=COALESCE(NULLIF(?,''), liveness_status), ua=COALESCE(NULLIF(?,''), ua), payload=?, updated_at=? WHERE email=? """, ( (guest_id or "")[:120], stage_n, (name or "")[:64], (paid or "")[:8], (face_ok or "")[:8], (liveness_status or "")[:24], (ua or "")[:240], json.dumps(new_payload, ensure_ascii=False), now, email_n, ), ) rid = existing["id"] else: rid = _uid("jl") c.execute( """ INSERT INTO join_leads( id, email, guest_id, stage, name, paid, face_ok, liveness_status, ua, payload, created_at, updated_at ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) """, ( rid, email_n, (guest_id or "")[:120], stage_n, (name or "")[:64], (paid or "")[:8], (face_ok or "")[:8], (liveness_status or "")[:24], (ua or "")[:240], json.dumps({**body, "stages": [stage_n]}, ensure_ascii=False), now, now, ), ) # also archive snapshot c.execute( """ INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at) VALUES (?,?,?,?,?,?,?,?) """, ( _uid("arc"), "join_leads", email_n, (guest_id or "")[:120], stage_n, f"join:{stage_n}", json.dumps( { "email": email_n, "guestId": guest_id, "stage": stage_n, "name": name, "paid": paid, "faceOk": face_ok, "livenessStatus": liveness_status, "ua": ua, "payload": body, }, ensure_ascii=False, ), now, ), ) return { "ok": True, "id": rid, "email": email_n, "guestId": guest_id, "stage": stage_n, "at": now, } def list_join_leads(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) needle = (q or "").strip().lower() with _db(readonly=True) as c: rows = c.execute( "SELECT * FROM join_leads ORDER BY updated_at DESC" ).fetchall() items = [] for r in rows: try: payload = json.loads(r["payload"] or "{}") except Exception: payload = {} item = { "id": r["id"], "email": r["email"] or "", "guestId": r["guest_id"] or "", "stage": r["stage"] or "", "name": r["name"] or "", "paid": r["paid"] or "", "faceOk": r["face_ok"] or "", "livenessStatus": r["liveness_status"] or "", "ua": r["ua"] or "", "payload": payload, "createdAt": r["created_at"] or "", "updatedAt": r["updated_at"] or "", } if needle: blob = " ".join( [ item["email"], item["guestId"], item["name"], item["stage"], ] ).lower() if needle not in blob: continue items.append(item) total = len(items) return {"ok": True, "total": total, "items": items[off : off + lim]} def list_archives( *, entity: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) clauses: list[str] = [] params: list[Any] = [] if entity.strip(): clauses.append("entity=?") params.append(entity.strip()) where = f" WHERE {' AND '.join(clauses)}" if clauses else "" with _db() as c: total = c.execute( f"SELECT COUNT(*) AS n FROM social_archives{where}", tuple(params) ).fetchone()["n"] rows = c.execute( f""" SELECT id, entity, entity_id, guest_id, action, note, payload, created_at FROM social_archives{where} ORDER BY created_at DESC LIMIT ? OFFSET ? """, (*params, lim, off), ).fetchall() items = [] for r in rows: try: payload = json.loads(r["payload"] or "{}") except Exception: payload = {} items.append( { "id": r["id"], "entity": r["entity"], "entityId": r["entity_id"], "guestId": r["guest_id"] or "", "action": r["action"], "note": r["note"] or "", "at": r["created_at"], "payload": payload, } ) return {"ok": True, "total": total, "items": items}