admin.nomadro.com gets sidebar L1/L2 social ops (paginated lists + entity detail); API adds soft-delete archives/stats and shared nomadro_pb for social/coffee/notify/work. Co-authored-by: Cursor <cursoragent@cursor.com>
864 lines
24 KiB
Python
864 lines
24 KiB
Python
"""Isolated SQLite store for 游民社区 — never touches community/PB tables."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import hashlib
|
||
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, SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES
|
||
|
||
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(*, commit: bool = True) -> Iterator[sqlite3.Connection]:
|
||
"""SQLite removed — use PocketBase via social_svc.pb_data / nomadro_pb."""
|
||
raise RuntimeError(
|
||
"social_svc SQLite disabled; use PocketBase via social_svc.pb_data / nomadro_pb"
|
||
)
|
||
yield # pragma: no cover
|
||
|
||
|
||
_DB_READY = False
|
||
|
||
|
||
def init_db() -> None:
|
||
"""PocketBase online SoT — no SQLite."""
|
||
try:
|
||
from nomadro_pb import ensure_once
|
||
|
||
ensure_once()
|
||
except Exception:
|
||
pass
|
||
return
|
||
# legacy sqlite bootstrap kept below for reference but unreachable
|
||
_legacy_init_db()
|
||
|
||
|
||
def _legacy_init_db() -> None:
|
||
global _DB_READY
|
||
if _DB_READY:
|
||
return
|
||
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 channel_meta (
|
||
channel_id TEXT PRIMARY KEY,
|
||
next_seq INTEGER NOT NULL DEFAULT 1
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS channel_read (
|
||
guest_id TEXT NOT NULL,
|
||
channel_id TEXT NOT NULL,
|
||
recv_seq INTEGER NOT NULL DEFAULT 0,
|
||
read_seq INTEGER NOT NULL DEFAULT 0,
|
||
updated_at TEXT NOT NULL,
|
||
PRIMARY KEY (guest_id, channel_id)
|
||
);
|
||
|
||
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,
|
||
avatar 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
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS trips (
|
||
id TEXT PRIMARY KEY,
|
||
guest_id TEXT NOT NULL,
|
||
city_id TEXT,
|
||
city TEXT NOT NULL,
|
||
country TEXT,
|
||
lat REAL,
|
||
lng REAL,
|
||
h3_cell TEXT,
|
||
arrival_date TEXT,
|
||
departure_date TEXT,
|
||
visibility TEXT NOT NULL DEFAULT 'public',
|
||
status TEXT NOT NULL DEFAULT 'planned',
|
||
updated_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_trips_guest ON trips(guest_id);
|
||
CREATE INDEX IF NOT EXISTS idx_trips_city ON trips(city_id);
|
||
CREATE INDEX IF NOT EXISTS idx_trips_vis ON trips(visibility, status);
|
||
"""
|
||
)
|
||
# migrate older DBs missing seq / client_id / meta
|
||
cols = {r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()}
|
||
if "seq" not in cols:
|
||
conn.execute("ALTER TABLE messages ADD COLUMN seq INTEGER")
|
||
if "client_id" not in cols:
|
||
conn.execute("ALTER TABLE messages ADD COLUMN client_id TEXT")
|
||
if "meta" not in cols:
|
||
conn.execute("ALTER TABLE messages ADD COLUMN meta TEXT")
|
||
conn.execute(
|
||
"CREATE INDEX IF NOT EXISTS idx_messages_channel_seq ON messages(channel_id, seq)"
|
||
)
|
||
roster_cols = {r[1] for r in conn.execute("PRAGMA table_info(roster)").fetchall()}
|
||
if "avatar" not in roster_cols:
|
||
conn.execute("ALTER TABLE roster ADD COLUMN avatar TEXT")
|
||
try:
|
||
from social_svc.community_board import ensure_community_tables
|
||
|
||
ensure_community_tables()
|
||
except Exception:
|
||
pass
|
||
# P0 cold-start profile fields (join → discovery ranking)
|
||
for col, decl in (
|
||
("gender", "TEXT"),
|
||
("intents", "TEXT"),
|
||
("availability", "TEXT"),
|
||
("status", "TEXT"),
|
||
("looking_for", "TEXT"),
|
||
("relationship", "TEXT"),
|
||
("education", "TEXT"),
|
||
("graduation", "TEXT"),
|
||
("wechat", "TEXT"),
|
||
("discoverable", "INTEGER DEFAULT 1"),
|
||
("onboarded_at", "TEXT"),
|
||
("face_ok", "INTEGER DEFAULT 0"),
|
||
("liveness_status", "TEXT"),
|
||
("liveness_at", "TEXT"),
|
||
("liveness_video_url", "TEXT"),
|
||
("liveness_front_url", "TEXT"),
|
||
("liveness_turn_url", "TEXT"),
|
||
):
|
||
if col not in roster_cols:
|
||
conn.execute(f"ALTER TABLE roster ADD COLUMN {col} {decl}")
|
||
conn.execute(
|
||
"CREATE INDEX IF NOT EXISTS idx_roster_city ON roster(city)"
|
||
)
|
||
conn.executescript(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS liveness_audits (
|
||
id TEXT PRIMARY KEY,
|
||
guest_id TEXT NOT NULL,
|
||
avatar_url TEXT,
|
||
front_url TEXT,
|
||
turn_url TEXT,
|
||
video_url TEXT,
|
||
video_size INTEGER,
|
||
similarity REAL,
|
||
yaw_delta REAL,
|
||
status TEXT NOT NULL DEFAULT 'pending',
|
||
meta_json TEXT,
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_liveness_guest ON liveness_audits(guest_id, created_at);
|
||
CREATE INDEX IF NOT EXISTS idx_liveness_status ON liveness_audits(status, created_at);
|
||
"""
|
||
)
|
||
conn.executescript(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS files (
|
||
id TEXT PRIMARY KEY,
|
||
channel_id TEXT NOT NULL,
|
||
guest_id TEXT NOT NULL,
|
||
kind TEXT NOT NULL,
|
||
name TEXT NOT NULL,
|
||
mime TEXT NOT NULL,
|
||
size INTEGER NOT NULL,
|
||
path TEXT NOT NULL,
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_files_channel ON files(channel_id, created_at);
|
||
"""
|
||
)
|
||
_backfill_seq(conn)
|
||
_DB_READY = True
|
||
try:
|
||
from . import geo_pb
|
||
|
||
geo_pb.ensure_collection()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _parse_meta(raw: str | None) -> dict[str, Any]:
|
||
if not raw:
|
||
return {}
|
||
try:
|
||
data = json.loads(raw)
|
||
return data if isinstance(data, dict) else {}
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
def _dump_meta(meta: dict[str, Any] | None) -> str:
|
||
return json.dumps(meta or {}, ensure_ascii=False, separators=(",", ":"))
|
||
|
||
|
||
_MSG_COLS = "id, channel_id, author, text, guest_id, created_at, seq, client_id, meta"
|
||
|
||
|
||
def _backfill_seq(conn: sqlite3.Connection) -> None:
|
||
"""Assign monotonic seq to legacy rows (Tinode-style topic seq)."""
|
||
channels = conn.execute(
|
||
"SELECT DISTINCT channel_id FROM messages WHERE seq IS NULL OR seq = 0"
|
||
).fetchall()
|
||
for ch in channels:
|
||
cid = ch["channel_id"]
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT id FROM messages
|
||
WHERE channel_id = ? AND (seq IS NULL OR seq = 0)
|
||
ORDER BY created_at ASC, rowid ASC
|
||
""",
|
||
(cid,),
|
||
).fetchall()
|
||
if not rows:
|
||
continue
|
||
meta = conn.execute(
|
||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (cid,)
|
||
).fetchone()
|
||
start = int(meta["next_seq"]) if meta else 1
|
||
for i, r in enumerate(rows):
|
||
conn.execute("UPDATE messages SET seq = ? WHERE id = ?", (start + i, r["id"]))
|
||
nxt = start + len(rows)
|
||
if meta:
|
||
cur = int(meta["next_seq"] or 1)
|
||
if nxt > cur:
|
||
conn.execute(
|
||
"UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?",
|
||
(nxt, cid),
|
||
)
|
||
else:
|
||
conn.execute(
|
||
"INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)",
|
||
(cid, nxt),
|
||
)
|
||
|
||
|
||
def _row_message(r: sqlite3.Row) -> dict[str, Any]:
|
||
item: dict[str, Any] = {
|
||
"id": r["id"],
|
||
"channelId": r["channel_id"],
|
||
"author": r["author"],
|
||
"text": r["text"],
|
||
"guestId": r["guest_id"],
|
||
"at": r["created_at"],
|
||
"seq": int(r["seq"] or 0),
|
||
}
|
||
try:
|
||
cid = r["client_id"]
|
||
except (IndexError, KeyError):
|
||
cid = None
|
||
if cid:
|
||
item["clientId"] = cid
|
||
try:
|
||
meta_raw = r["meta"]
|
||
except (IndexError, KeyError):
|
||
meta_raw = None
|
||
meta = _parse_meta(meta_raw)
|
||
# Element-like fields flattened for clients
|
||
if meta.get("replyTo"):
|
||
item["replyTo"] = meta["replyTo"]
|
||
if meta.get("attachments"):
|
||
item["attachments"] = meta["attachments"]
|
||
if meta.get("reactions"):
|
||
item["reactions"] = meta["reactions"]
|
||
if meta.get("mentions"):
|
||
item["mentions"] = meta["mentions"]
|
||
if meta.get("editedAt"):
|
||
item["editedAt"] = meta["editedAt"]
|
||
if meta.get("recalled"):
|
||
item["recalled"] = True
|
||
item["text"] = ""
|
||
if meta.get("pinned"):
|
||
item["pinned"] = True
|
||
if meta.get("pinnedAt"):
|
||
item["pinnedAt"] = meta["pinnedAt"]
|
||
if meta.get("reported"):
|
||
item["reported"] = True
|
||
return item
|
||
|
||
|
||
def _get_message(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | None:
|
||
return conn.execute(
|
||
f"SELECT {_MSG_COLS} FROM messages WHERE id = ?", (msg_id,)
|
||
).fetchone()
|
||
|
||
|
||
def _get_message_row(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | None:
|
||
return _get_message(conn, msg_id)
|
||
|
||
|
||
def channel_seq(channel_id: str) -> int:
|
||
"""Latest message seq for a channel (cheap; no presence / read marks)."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.channel_seq(channel_id)
|
||
|
||
|
||
def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]:
|
||
"""Tinode-like topic desc: latest seq + caller's recv/read watermarks."""
|
||
from social_svc import pb_data
|
||
|
||
base = pb_data.channel_desc(channel_id, guest_id)
|
||
peers = online_peers(channel_id)
|
||
return {
|
||
**base,
|
||
"online": len(peers),
|
||
"peers": peers,
|
||
}
|
||
|
||
|
||
def list_messages(
|
||
channel_id: str,
|
||
limit: int = 100,
|
||
*,
|
||
since: int | None = None,
|
||
before: int | None = None,
|
||
q: str | None = None,
|
||
) -> list[dict[str, Any]]:
|
||
"""History with Tinode-style seq cursors (since exclusive, before exclusive)."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.list_messages(
|
||
channel_id, limit, since=since, before=before, q=q
|
||
)
|
||
|
||
|
||
def _normalize_reply(reply_to: dict[str, Any] | None) -> dict[str, Any] | None:
|
||
if not reply_to or not isinstance(reply_to, dict):
|
||
return None
|
||
rid = str(reply_to.get("id") or "").strip()
|
||
if not rid:
|
||
return None
|
||
return {
|
||
"id": rid[:80],
|
||
"author": str(reply_to.get("author") or "游民").strip()[:48] or "游民",
|
||
"text": str(reply_to.get("text") or "").strip()[:240],
|
||
"seq": int(reply_to.get("seq") or 0) or None,
|
||
}
|
||
|
||
|
||
def _normalize_attachments(items: list[Any] | None) -> list[dict[str, Any]]:
|
||
out: list[dict[str, Any]] = []
|
||
for raw in (items or [])[:8]:
|
||
if not isinstance(raw, dict):
|
||
continue
|
||
url = str(raw.get("url") or "").strip()
|
||
kind = str(raw.get("kind") or "file").strip().lower()
|
||
if kind not in {"image", "video", "file", "audio"}:
|
||
kind = "file"
|
||
if not url or len(url) > 800:
|
||
continue
|
||
out.append(
|
||
{
|
||
"id": str(raw.get("id") or _uid("att"))[:80],
|
||
"kind": kind,
|
||
"url": url,
|
||
"name": str(raw.get("name") or "file").strip()[:160] or "file",
|
||
"mime": str(raw.get("mime") or "application/octet-stream").strip()[:120],
|
||
"size": max(0, min(int(raw.get("size") or 0), 50 * 1024 * 1024)),
|
||
}
|
||
)
|
||
return out
|
||
|
||
|
||
def add_message(
|
||
channel_id: str,
|
||
author: str,
|
||
text: str,
|
||
guest_id: str,
|
||
client_id: str | None = None,
|
||
*,
|
||
reply_to: dict[str, Any] | None = None,
|
||
attachments: list[Any] | None = None,
|
||
mentions: list[Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
from social_svc.im import check_rate
|
||
|
||
check_rate(guest_id)
|
||
body = (text or "").strip()[:2000]
|
||
atts = _normalize_attachments(attachments)
|
||
if not body and not atts:
|
||
raise ValueError("empty message")
|
||
reply = _normalize_reply(reply_to)
|
||
mention_list = [
|
||
str(m).strip()[:48]
|
||
for m in (mentions or [])[:12]
|
||
if str(m).strip()
|
||
]
|
||
meta: dict[str, Any] = {}
|
||
if reply:
|
||
meta["replyTo"] = reply
|
||
if atts:
|
||
meta["attachments"] = atts
|
||
if mention_list:
|
||
meta["mentions"] = mention_list
|
||
|
||
from social_svc import pb_data
|
||
|
||
out = pb_data.add_message(
|
||
channel_id,
|
||
author,
|
||
body,
|
||
guest_id,
|
||
kind="text",
|
||
meta=meta,
|
||
attachments=atts,
|
||
reply_to=reply,
|
||
)
|
||
if client_id:
|
||
out["clientId"] = client_id
|
||
if mention_list:
|
||
out["mentions"] = mention_list
|
||
out["at"] = out.get("createdAt") or _now()
|
||
return out
|
||
|
||
|
||
def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]:
|
||
from social_svc import pb_data
|
||
|
||
body = (text or "").strip()[:2000]
|
||
if not body:
|
||
raise ValueError("empty text")
|
||
return pb_data.edit_message(channel_id, msg_id, guest_id, body)
|
||
|
||
|
||
def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]:
|
||
"""Element-style redact: clear body, keep shell for timeline continuity."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.recall_message(channel_id, msg_id, guest_id)
|
||
|
||
|
||
def react_message(
|
||
channel_id: str, msg_id: str, guest_id: str, emoji: str
|
||
) -> dict[str, Any]:
|
||
"""Toggle annotation reaction (Element / Matrix m.annotation pattern)."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.react_message(channel_id, msg_id, guest_id, emoji)
|
||
|
||
|
||
def pin_message(
|
||
channel_id: str, msg_id: str, guest_id: str, pinned: bool = True
|
||
) -> dict[str, Any]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.pin_message(channel_id, msg_id, guest_id, pinned)
|
||
|
||
|
||
def save_upload(
|
||
channel_id: str,
|
||
guest_id: str,
|
||
*,
|
||
kind: str,
|
||
name: str,
|
||
mime: str,
|
||
data: bytes,
|
||
) -> dict[str, Any]:
|
||
from social_svc.config import SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES
|
||
from social_svc import pb_data
|
||
|
||
if len(data) > SOCIAL_UPLOAD_MAX_BYTES:
|
||
raise ValueError("file too large")
|
||
if kind not in {"image", "video", "file", "audio"}:
|
||
kind = "file"
|
||
file_id = _uid("file")
|
||
safe_name = "".join(c for c in (name or "file") if c.isalnum() or c in "._- ")[:120] or "file"
|
||
root = SOCIAL_UPLOAD_DIR / channel_id
|
||
root.mkdir(parents=True, exist_ok=True)
|
||
path = root / f"{file_id}_{safe_name}"
|
||
path.write_bytes(data)
|
||
return pb_data.save_file_meta(
|
||
file_id,
|
||
channel_id,
|
||
guest_id,
|
||
kind=kind,
|
||
name=safe_name,
|
||
mime=(mime or "application/octet-stream")[:120],
|
||
size=len(data),
|
||
path=str(path),
|
||
)
|
||
|
||
|
||
def get_file(file_id: str) -> dict[str, Any] | None:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.get_file(file_id)
|
||
|
||
|
||
# Element-like soft presence (TTL heartbeat; UI-agnostic)
|
||
_PRESENCE: dict[str, dict[str, dict[str, Any]]] = {}
|
||
_PRESENCE_TTL_SEC = 45
|
||
|
||
|
||
def touch_presence(
|
||
channel_id: str, guest_id: str, nick: str = ""
|
||
) -> dict[str, Any]:
|
||
"""Soft presence: process-local TTL map (fast path). PB ch_meta.presence is best-effort mirror."""
|
||
now = time.time()
|
||
room = _PRESENCE.setdefault(channel_id, {})
|
||
room[guest_id] = {
|
||
"guestId": guest_id,
|
||
"nick": (nick or "游民").strip()[:48] or "游民",
|
||
"at": now,
|
||
}
|
||
# prune
|
||
dead = [gid for gid, meta in room.items() if now - float(meta["at"]) > _PRESENCE_TTL_SEC]
|
||
for gid in dead:
|
||
room.pop(gid, None)
|
||
peers = online_peers(channel_id)
|
||
try:
|
||
from social_svc import pb_data
|
||
from nomadro_pb import get_pb, pb_quote
|
||
|
||
pb_data.init_pb()
|
||
meta = get_pb().first(
|
||
pb_data.C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}"
|
||
)
|
||
presence = {
|
||
p["guestId"]: {"nick": p["nick"], "at": now} for p in peers
|
||
}
|
||
if meta:
|
||
get_pb().update(
|
||
pb_data.C_CHMETA, meta["id"], {"presence": presence, "updated_at": _now()}
|
||
)
|
||
else:
|
||
get_pb().create(
|
||
pb_data.C_CHMETA,
|
||
{
|
||
"channel_id": channel_id,
|
||
"seq": 0,
|
||
"pins": [],
|
||
"presence": presence,
|
||
"updated_at": _now(),
|
||
},
|
||
)
|
||
except Exception:
|
||
pass
|
||
return {"channelId": channel_id, "online": len(peers), "peers": peers}
|
||
|
||
|
||
def online_peers(channel_id: str) -> list[dict[str, Any]]:
|
||
now = time.time()
|
||
room = _PRESENCE.get(channel_id) or {}
|
||
out: list[dict[str, Any]] = []
|
||
for gid, meta in list(room.items()):
|
||
if now - float(meta["at"]) > _PRESENCE_TTL_SEC:
|
||
room.pop(gid, None)
|
||
continue
|
||
out.append({"guestId": gid, "nick": meta.get("nick") or "游民"})
|
||
out.sort(key=lambda p: p["nick"])
|
||
return out[:64]
|
||
|
||
|
||
def report_message(
|
||
channel_id: str, msg_id: str, guest_id: str, reason: str = ""
|
||
) -> dict[str, Any]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.report_message(channel_id, msg_id, guest_id, reason)
|
||
|
||
|
||
def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]:
|
||
"""Persist recv/read watermark (Tinode {note})."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.set_note(channel_id, guest_id, what, seq)
|
||
|
||
|
||
def list_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.list_cafe_reviews(cafe_id, limit)
|
||
|
||
|
||
def add_review(
|
||
cafe_id: str,
|
||
author: str,
|
||
score: int,
|
||
text: str,
|
||
photo_note: str,
|
||
guest_id: str,
|
||
) -> dict[str, Any]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.add_cafe_review(
|
||
cafe_id, author, score, text, photo_note, guest_id
|
||
)
|
||
|
||
|
||
def _norm_city(city: str) -> str:
|
||
return "".join(str(city or "").strip().lower().split())
|
||
|
||
|
||
def _split_tags(raw: str) -> list[str]:
|
||
return [
|
||
t.strip()
|
||
for t in str(raw or "").replace(",", ",").replace("、", ",").split(",")
|
||
if t.strip()
|
||
]
|
||
|
||
|
||
def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]:
|
||
keys = set(r.keys())
|
||
intents = (r["intents"] if "intents" in keys else "") or ""
|
||
skills = r["skills"] or ""
|
||
status = ((r["status"] if "status" in keys else "") or "online").strip() or "online"
|
||
item: dict[str, Any] = {
|
||
"guestId": r["guest_id"],
|
||
"name": r["name"],
|
||
"title": r["title"] or "",
|
||
"city": r["city"] or "",
|
||
"skills": skills,
|
||
"bio": r["bio"] or "",
|
||
"avatar": (r["avatar"] if "avatar" in keys else "") or "",
|
||
"gender": (r["gender"] if "gender" in keys else "") or "",
|
||
"intents": intents,
|
||
"availability": (r["availability"] if "availability" in keys else "") or "",
|
||
"status": status,
|
||
"lookingFor": (r["looking_for"] if "looking_for" in keys else "") or "",
|
||
"updatedAt": r["updated_at"],
|
||
"online": status in {"online", "here", "available"},
|
||
"tags": _split_tags(skills)[:8],
|
||
}
|
||
if not public:
|
||
item.update(
|
||
{
|
||
"phone": r["phone"] or "",
|
||
"linktree": r["linktree"] or "",
|
||
"relationship": (r["relationship"] if "relationship" in keys else "") or "",
|
||
"education": (r["education"] if "education" in keys else "") or "",
|
||
"graduation": (r["graduation"] if "graduation" in keys else "") or "",
|
||
"wechat": (r["wechat"] if "wechat" in keys else "") or "",
|
||
"discoverable": int(r["discoverable"] if "discoverable" in keys and r["discoverable"] is not None else 1),
|
||
"onboardedAt": (r["onboarded_at"] if "onboarded_at" in keys else "") or "",
|
||
"faceOk": bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)),
|
||
"livenessStatus": (r["liveness_status"] if "liveness_status" in keys else "") or "none",
|
||
"livenessAt": (r["liveness_at"] if "liveness_at" in keys else "") or "",
|
||
"livenessVideoUrl": (r["liveness_video_url"] if "liveness_video_url" in keys else "") or "",
|
||
}
|
||
)
|
||
else:
|
||
item["linktree"] = r["linktree"] or ""
|
||
item["faceOk"] = bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0))
|
||
item["livenessStatus"] = (r["liveness_status"] if "liveness_status" in keys else "") or "none"
|
||
return item
|
||
|
||
|
||
def get_roster(guest_id: str) -> dict[str, Any] | None:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.get_roster(guest_id)
|
||
|
||
|
||
def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||
"""Insert/update roster on PocketBase."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.upsert_roster(guest_id, payload)
|
||
|
||
|
||
def score_discovery(
|
||
viewer: dict[str, Any] | None,
|
||
item: dict[str, Any],
|
||
) -> int:
|
||
"""Higher = better: same city >> online >> tag/intent overlap."""
|
||
score = 0
|
||
v_city = _norm_city((viewer or {}).get("city") or "")
|
||
i_city = _norm_city(item.get("city") or "")
|
||
if v_city and i_city and v_city == i_city:
|
||
score += 1000
|
||
elif v_city and i_city and (v_city in i_city or i_city in v_city):
|
||
score += 600
|
||
if item.get("online"):
|
||
score += 200
|
||
v_tags = set(
|
||
t.lower()
|
||
for t in (
|
||
_split_tags((viewer or {}).get("skills") or "")
|
||
+ _split_tags((viewer or {}).get("intents") or "")
|
||
)
|
||
)
|
||
i_tags = set(
|
||
t.lower()
|
||
for t in (
|
||
list(item.get("tags") or [])
|
||
+ _split_tags(item.get("intents") or "")
|
||
+ _split_tags(item.get("lookingFor") or "")
|
||
)
|
||
)
|
||
score += min(120, 40 * len(v_tags & i_tags))
|
||
# fresher profiles float a bit
|
||
updated = str(item.get("updatedAt") or "")
|
||
if updated:
|
||
score += min(50, max(0, len(updated)))
|
||
return score
|
||
|
||
|
||
def list_discovery_roster(
|
||
*,
|
||
viewer_guest_id: str | None = None,
|
||
city: str = "",
|
||
limit: int = 48,
|
||
exclude_self: bool = True,
|
||
) -> list[dict[str, Any]]:
|
||
"""Public discovery cards ranked for viewer (same-city + online + tags)."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.list_discovery_roster(
|
||
viewer_guest_id=viewer_guest_id,
|
||
city=city,
|
||
limit=limit,
|
||
exclude_self=exclude_self,
|
||
)
|
||
|
||
|
||
def city_recommendations(
|
||
guest_id: str,
|
||
*,
|
||
limit: int = 3,
|
||
) -> list[dict[str, Any]]:
|
||
"""Top same-city (then tag-matched) people for onboarding push."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.city_recommendations(guest_id, limit=limit)
|
||
|
||
|
||
def mark_face_photo(guest_id: str, avatar_url: str) -> None:
|
||
"""Album/selfie → avatar + face_ok. Does not verify liveness."""
|
||
from social_svc import pb_data
|
||
|
||
pb_data.mark_face_photo(guest_id, avatar_url)
|
||
|
||
|
||
def save_liveness_audit(
|
||
guest_id: str,
|
||
*,
|
||
avatar_url: str = "",
|
||
front_url: str,
|
||
turn_url: str,
|
||
video_url: str,
|
||
video_size: int,
|
||
similarity: float | None,
|
||
yaw_delta: float | None,
|
||
meta: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Live capture audit only — never overwrites roster.avatar."""
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.save_liveness_audit(
|
||
guest_id,
|
||
front_url=front_url,
|
||
turn_url=turn_url,
|
||
video_url=video_url,
|
||
video_size=video_size,
|
||
similarity=similarity,
|
||
yaw_delta=yaw_delta,
|
||
meta=meta,
|
||
)
|
||
|
||
|
||
def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.list_liveness_audits(status=status, limit=limit)
|
||
|
||
|
||
def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.add_feedback(kind, text, contact, guest_id)
|
||
|
||
|
||
def add_gig_app(
|
||
gig_id: str,
|
||
name: str,
|
||
contact: str,
|
||
note: str,
|
||
guest_id: str,
|
||
request_id: str | None = None,
|
||
) -> dict[str, Any]:
|
||
from social_svc import pb_data
|
||
|
||
return pb_data.add_gig_app(gig_id, name, contact, note, guest_id, request_id)
|
||
|
||
|
||
def health() -> dict[str, Any]:
|
||
init_db()
|
||
from social_svc import pb_data
|
||
|
||
h = pb_data.health()
|
||
return {
|
||
"ok": bool(h.get("ok")),
|
||
"module": "social",
|
||
"backend": "pocketbase",
|
||
"db": h.get("pb") or h.get("db") or "",
|
||
"dbBytes": 0,
|
||
"isolated": True,
|
||
}
|