Store challenge frames plus MediaRecorder stream for human review, and soft-gate dating/coffee/meetup until liveness passes. Co-authored-by: Cursor <cursoragent@cursor.com>
1427 lines
41 KiB
Python
1427 lines
41 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]:
|
||
SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
conn = _connect(SOCIAL_DB_PATH)
|
||
try:
|
||
try:
|
||
conn.execute("PRAGMA busy_timeout=5000")
|
||
except Exception:
|
||
pass
|
||
yield conn
|
||
if commit:
|
||
conn.commit()
|
||
except Exception:
|
||
conn.rollback()
|
||
raise
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
_DB_READY = False
|
||
|
||
|
||
def 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")
|
||
# 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)."""
|
||
init_db()
|
||
with db(commit=False) as conn:
|
||
meta = conn.execute(
|
||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||
).fetchone()
|
||
if meta:
|
||
return max(0, int(meta["next_seq"]) - 1)
|
||
row = conn.execute(
|
||
"SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,)
|
||
).fetchone()
|
||
return int(row["m"] or 0)
|
||
|
||
|
||
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."""
|
||
init_db()
|
||
with db(commit=False) as conn:
|
||
meta = conn.execute(
|
||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||
).fetchone()
|
||
if meta:
|
||
seq = max(0, int(meta["next_seq"]) - 1)
|
||
else:
|
||
row = conn.execute(
|
||
"SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,)
|
||
).fetchone()
|
||
seq = int(row["m"] or 0)
|
||
recv = read = 0
|
||
if guest_id:
|
||
mark = conn.execute(
|
||
"""
|
||
SELECT recv_seq, read_seq FROM channel_read
|
||
WHERE guest_id = ? AND channel_id = ?
|
||
""",
|
||
(guest_id, channel_id),
|
||
).fetchone()
|
||
if mark:
|
||
recv = int(mark["recv_seq"] or 0)
|
||
read = int(mark["read_seq"] or 0)
|
||
peers = online_peers(channel_id)
|
||
return {
|
||
"channelId": channel_id,
|
||
"seq": seq,
|
||
"recv": recv,
|
||
"read": read,
|
||
"unread": max(0, seq - read),
|
||
"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)."""
|
||
lim = max(1, min(int(limit or 100), 500))
|
||
needle = (q or "").strip()[:80]
|
||
with db(commit=False) as conn:
|
||
if needle:
|
||
like = f"%{needle}%"
|
||
rows = conn.execute(
|
||
f"""
|
||
SELECT {_MSG_COLS}
|
||
FROM messages
|
||
WHERE channel_id = ?
|
||
AND COALESCE(json_extract(meta, '$.recalled'), 0) = 0
|
||
AND (text LIKE ? OR author LIKE ?)
|
||
ORDER BY COALESCE(seq, 0) DESC, rowid DESC
|
||
LIMIT ?
|
||
""",
|
||
(channel_id, like, like, lim),
|
||
).fetchall()
|
||
return [_row_message(r) for r in reversed(rows)]
|
||
if since is not None and since > 0:
|
||
rows = conn.execute(
|
||
f"""
|
||
SELECT {_MSG_COLS}
|
||
FROM messages
|
||
WHERE channel_id = ? AND seq IS NOT NULL AND seq > ?
|
||
ORDER BY seq ASC
|
||
LIMIT ?
|
||
""",
|
||
(channel_id, since, lim),
|
||
).fetchall()
|
||
return [_row_message(r) for r in rows]
|
||
if before is not None and before > 0:
|
||
rows = conn.execute(
|
||
f"""
|
||
SELECT {_MSG_COLS}
|
||
FROM messages
|
||
WHERE channel_id = ? AND seq IS NOT NULL AND seq < ?
|
||
ORDER BY seq DESC
|
||
LIMIT ?
|
||
""",
|
||
(channel_id, before, lim),
|
||
).fetchall()
|
||
return [_row_message(r) for r in reversed(rows)]
|
||
rows = conn.execute(
|
||
f"""
|
||
SELECT {_MSG_COLS}
|
||
FROM messages
|
||
WHERE channel_id = ?
|
||
ORDER BY COALESCE(seq, 0) DESC, rowid DESC
|
||
LIMIT ?
|
||
""",
|
||
(channel_id, lim),
|
||
).fetchall()
|
||
return [_row_message(r) for r in reversed(rows)]
|
||
|
||
|
||
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
|
||
|
||
msg_id = (
|
||
"msg_"
|
||
+ hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]
|
||
if client_id
|
||
else _uid("msg")
|
||
)
|
||
item = {
|
||
"id": msg_id,
|
||
"channelId": channel_id,
|
||
"author": (author or "游民").strip()[:48] or "游民",
|
||
"text": body,
|
||
"guestId": guest_id,
|
||
"at": _now(),
|
||
"seq": 0,
|
||
}
|
||
with db() as conn:
|
||
existing = _get_message(conn, msg_id)
|
||
if existing:
|
||
if existing["text"] != item["text"] or existing["author"] != item["author"]:
|
||
raise ValueError("同一请求标识不能用于不同消息")
|
||
out = _row_message(existing)
|
||
if client_id:
|
||
out["clientId"] = client_id
|
||
return out
|
||
|
||
ch_meta = conn.execute(
|
||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||
).fetchone()
|
||
if ch_meta:
|
||
seq = int(ch_meta["next_seq"])
|
||
conn.execute(
|
||
"UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?",
|
||
(seq + 1, channel_id),
|
||
)
|
||
else:
|
||
seq = 1
|
||
conn.execute(
|
||
"INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)",
|
||
(channel_id, 2),
|
||
)
|
||
item["seq"] = seq
|
||
conn.execute(
|
||
f"""
|
||
INSERT INTO messages({_MSG_COLS})
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
""",
|
||
(
|
||
item["id"],
|
||
item["channelId"],
|
||
item["author"],
|
||
item["text"],
|
||
guest_id,
|
||
item["at"],
|
||
seq,
|
||
client_id,
|
||
_dump_meta(meta),
|
||
),
|
||
)
|
||
out = {**item, **{k: v for k, v in {
|
||
"clientId": client_id,
|
||
"replyTo": reply,
|
||
"attachments": atts or None,
|
||
"mentions": mention_list or None,
|
||
}.items() if v}}
|
||
return out
|
||
|
||
|
||
def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]:
|
||
body = (text or "").strip()[:2000]
|
||
if not body:
|
||
raise ValueError("empty text")
|
||
with db() as conn:
|
||
row = _get_message(conn, msg_id)
|
||
if not row or row["channel_id"] != channel_id:
|
||
raise ValueError("message not found")
|
||
if row["guest_id"] != guest_id:
|
||
raise ValueError("not your message")
|
||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||
if meta.get("recalled"):
|
||
raise ValueError("recalled")
|
||
meta["editedAt"] = _now()
|
||
conn.execute(
|
||
"UPDATE messages SET text = ?, meta = ? WHERE id = ?",
|
||
(body, _dump_meta(meta), msg_id),
|
||
)
|
||
row = _get_message(conn, msg_id)
|
||
return _row_message(row) # type: ignore[arg-type]
|
||
|
||
|
||
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."""
|
||
with db() as conn:
|
||
row = _get_message(conn, msg_id)
|
||
if not row or row["channel_id"] != channel_id:
|
||
raise ValueError("message not found")
|
||
if row["guest_id"] != guest_id:
|
||
raise ValueError("not your message")
|
||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||
meta["recalled"] = True
|
||
meta["recalledAt"] = _now()
|
||
meta.pop("attachments", None)
|
||
meta.pop("reactions", None)
|
||
conn.execute(
|
||
"UPDATE messages SET text = '', meta = ? WHERE id = ?",
|
||
(_dump_meta(meta), msg_id),
|
||
)
|
||
row = _get_message(conn, msg_id)
|
||
return _row_message(row) # type: ignore[arg-type]
|
||
|
||
|
||
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)."""
|
||
key = (emoji or "").strip()[:16]
|
||
if not key:
|
||
raise ValueError("empty emoji")
|
||
with db() as conn:
|
||
row = _get_message(conn, msg_id)
|
||
if not row or row["channel_id"] != channel_id:
|
||
raise ValueError("message not found")
|
||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||
if meta.get("recalled"):
|
||
raise ValueError("recalled")
|
||
reactions: dict[str, list[str]] = dict(meta.get("reactions") or {})
|
||
holders = list(reactions.get(key) or [])
|
||
if guest_id in holders:
|
||
holders = [g for g in holders if g != guest_id]
|
||
else:
|
||
holders.append(guest_id)
|
||
if holders:
|
||
reactions[key] = holders[:64]
|
||
else:
|
||
reactions.pop(key, None)
|
||
if reactions:
|
||
meta["reactions"] = reactions
|
||
else:
|
||
meta.pop("reactions", None)
|
||
conn.execute(
|
||
"UPDATE messages SET meta = ? WHERE id = ?",
|
||
(_dump_meta(meta), msg_id),
|
||
)
|
||
row = _get_message(conn, msg_id)
|
||
return _row_message(row) # type: ignore[arg-type]
|
||
|
||
|
||
def pin_message(
|
||
channel_id: str, msg_id: str, guest_id: str, pinned: bool = True
|
||
) -> dict[str, Any]:
|
||
with db() as conn:
|
||
row = _get_message(conn, msg_id)
|
||
if not row or row["channel_id"] != channel_id:
|
||
raise ValueError("message not found")
|
||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||
if meta.get("recalled"):
|
||
raise ValueError("recalled")
|
||
if pinned:
|
||
meta["pinned"] = True
|
||
meta["pinnedAt"] = _now()
|
||
meta["pinnedBy"] = guest_id
|
||
else:
|
||
meta.pop("pinned", None)
|
||
meta.pop("pinnedAt", None)
|
||
meta.pop("pinnedBy", None)
|
||
conn.execute(
|
||
"UPDATE messages SET meta = ? WHERE id = ?",
|
||
(_dump_meta(meta), msg_id),
|
||
)
|
||
row = _get_message(conn, msg_id)
|
||
return _row_message(row) # type: ignore[arg-type]
|
||
|
||
|
||
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
|
||
|
||
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)
|
||
item = {
|
||
"id": file_id,
|
||
"kind": kind,
|
||
"name": safe_name,
|
||
"mime": (mime or "application/octet-stream")[:120],
|
||
"size": len(data),
|
||
"url": f"/api/social/v1/files/{file_id}",
|
||
}
|
||
with db() as conn:
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO files(id, channel_id, guest_id, kind, name, mime, size, path, created_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
""",
|
||
(
|
||
file_id,
|
||
channel_id,
|
||
guest_id,
|
||
kind,
|
||
safe_name,
|
||
item["mime"],
|
||
item["size"],
|
||
str(path),
|
||
_now(),
|
||
),
|
||
)
|
||
return item
|
||
|
||
|
||
def get_file(file_id: str) -> dict[str, Any] | None:
|
||
with db() as conn:
|
||
row = conn.execute("SELECT * FROM files WHERE id = ?", (file_id,)).fetchone()
|
||
if not row:
|
||
return None
|
||
return {
|
||
"id": row["id"],
|
||
"channelId": row["channel_id"],
|
||
"kind": row["kind"],
|
||
"name": row["name"],
|
||
"mime": row["mime"],
|
||
"size": row["size"],
|
||
"path": row["path"],
|
||
}
|
||
|
||
|
||
# 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]:
|
||
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)
|
||
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]:
|
||
with db() as conn:
|
||
row = _get_message(conn, msg_id)
|
||
if not row or row["channel_id"] != channel_id:
|
||
raise ValueError("message not found")
|
||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||
reporters = list(meta.get("reporters") or [])
|
||
if guest_id not in reporters:
|
||
reporters.append(guest_id)
|
||
meta["reported"] = True
|
||
meta["reporters"] = reporters[:64]
|
||
meta["reportReason"] = (reason or "").strip()[:240]
|
||
meta["reportedAt"] = _now()
|
||
conn.execute(
|
||
"UPDATE messages SET meta = ? WHERE id = ?",
|
||
(_dump_meta(meta), msg_id),
|
||
)
|
||
row = _get_message(conn, msg_id)
|
||
return _row_message(row) # type: ignore[arg-type]
|
||
|
||
|
||
def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]:
|
||
"""Persist recv/read watermark (Tinode {note})."""
|
||
what = (what or "").strip().lower()
|
||
if what not in {"recv", "read"}:
|
||
raise ValueError("what must be recv or read")
|
||
seq = max(0, int(seq))
|
||
init_db()
|
||
now = _now()
|
||
with db() as conn:
|
||
row = conn.execute(
|
||
"""
|
||
SELECT recv_seq, read_seq FROM channel_read
|
||
WHERE guest_id = ? AND channel_id = ?
|
||
""",
|
||
(guest_id, channel_id),
|
||
).fetchone()
|
||
recv = int(row["recv_seq"]) if row else 0
|
||
read = int(row["read_seq"]) if row else 0
|
||
if what == "recv":
|
||
recv = max(recv, seq)
|
||
else:
|
||
read = max(read, seq)
|
||
recv = max(recv, read)
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO channel_read(guest_id, channel_id, recv_seq, read_seq, updated_at)
|
||
VALUES (?, ?, ?, ?, ?)
|
||
ON CONFLICT(guest_id, channel_id) DO UPDATE SET
|
||
recv_seq = excluded.recv_seq,
|
||
read_seq = excluded.read_seq,
|
||
updated_at = excluded.updated_at
|
||
""",
|
||
(guest_id, channel_id, recv, read, now),
|
||
)
|
||
return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read}
|
||
|
||
|
||
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 _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:
|
||
with db() as conn:
|
||
r = conn.execute("SELECT * FROM roster WHERE guest_id = ?", (guest_id,)).fetchone()
|
||
if not r:
|
||
return None
|
||
return _roster_row_to_dict(r, public=False)
|
||
|
||
|
||
def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||
"""Insert/update roster. Returns (row, is_first_profile)."""
|
||
updated = _now()
|
||
avatar = str(payload.get("avatar") or "").strip()[:500]
|
||
if avatar and not (
|
||
avatar.startswith("https://")
|
||
or avatar.startswith("http://")
|
||
or avatar.startswith("/api/social/")
|
||
):
|
||
avatar = ""
|
||
intents_raw = payload.get("intents")
|
||
if isinstance(intents_raw, list):
|
||
intents = ",".join(str(x).strip() for x in intents_raw if str(x).strip())[:240]
|
||
else:
|
||
intents = str(intents_raw or "").strip()[:240]
|
||
status = str(payload.get("status") or "online").strip()[:32] or "online"
|
||
if status not in {"online", "away", "offline", "here", "available"}:
|
||
status = "online"
|
||
looking = str(
|
||
payload.get("lookingFor") or payload.get("looking_for") or ""
|
||
).strip()[:200]
|
||
if not looking and intents:
|
||
looking = intents.replace(",", " · ")[:200]
|
||
discoverable = payload.get("discoverable")
|
||
if discoverable is None:
|
||
discoverable = 1
|
||
else:
|
||
discoverable = 1 if str(discoverable).lower() not in {"0", "false", "no", "off"} else 0
|
||
|
||
existing = get_roster(guest_id)
|
||
is_first = existing is None
|
||
onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "")
|
||
|
||
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],
|
||
"avatar": avatar,
|
||
"gender": str(payload.get("gender") or "").strip()[:16],
|
||
"intents": intents,
|
||
"availability": str(payload.get("availability") or "").strip()[:120],
|
||
"status": status,
|
||
"lookingFor": looking,
|
||
"relationship": str(payload.get("relationship") or "").strip()[:32],
|
||
"education": str(payload.get("education") or "").strip()[:32],
|
||
"graduation": str(payload.get("graduation") or "").strip()[:32],
|
||
"wechat": str(payload.get("wechat") or "").strip()[:64],
|
||
"discoverable": discoverable,
|
||
"onboardedAt": onboarded_at,
|
||
"updatedAt": updated,
|
||
"isFirstProfile": is_first,
|
||
}
|
||
with db() as conn:
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO roster(
|
||
guest_id, name, title, city, phone, linktree, skills, bio, avatar,
|
||
gender, intents, availability, status, looking_for,
|
||
relationship, education, graduation, wechat, discoverable, onboarded_at, 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,
|
||
avatar=excluded.avatar,
|
||
gender=excluded.gender,
|
||
intents=excluded.intents,
|
||
availability=excluded.availability,
|
||
status=excluded.status,
|
||
looking_for=excluded.looking_for,
|
||
relationship=excluded.relationship,
|
||
education=excluded.education,
|
||
graduation=excluded.graduation,
|
||
wechat=excluded.wechat,
|
||
discoverable=excluded.discoverable,
|
||
onboarded_at=COALESCE(roster.onboarded_at, excluded.onboarded_at),
|
||
updated_at=excluded.updated_at
|
||
""",
|
||
(
|
||
guest_id,
|
||
row["name"],
|
||
row["title"],
|
||
row["city"],
|
||
row["phone"],
|
||
row["linktree"],
|
||
row["skills"],
|
||
row["bio"],
|
||
row["avatar"],
|
||
row["gender"],
|
||
row["intents"],
|
||
row["availability"],
|
||
row["status"],
|
||
row["lookingFor"],
|
||
row["relationship"],
|
||
row["education"],
|
||
row["graduation"],
|
||
row["wechat"],
|
||
row["discoverable"],
|
||
row["onboardedAt"],
|
||
updated,
|
||
),
|
||
)
|
||
return row
|
||
|
||
|
||
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)."""
|
||
limit = max(1, min(int(limit or 48), 100))
|
||
viewer = get_roster(viewer_guest_id) if viewer_guest_id else None
|
||
with db() as conn:
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT * FROM roster
|
||
WHERE COALESCE(discoverable, 1) = 1
|
||
AND TRIM(COALESCE(name, '')) != ''
|
||
ORDER BY updated_at DESC
|
||
LIMIT 400
|
||
"""
|
||
).fetchall()
|
||
items: list[dict[str, Any]] = []
|
||
city_f = _norm_city(city)
|
||
for r in rows:
|
||
if exclude_self and viewer_guest_id and r["guest_id"] == viewer_guest_id:
|
||
continue
|
||
item = _roster_row_to_dict(r, public=True)
|
||
if city_f:
|
||
ic = _norm_city(item.get("city") or "")
|
||
if not ic or (city_f not in ic and ic not in city_f):
|
||
continue
|
||
item["score"] = score_discovery(viewer, item)
|
||
items.append(item)
|
||
items.sort(
|
||
key=lambda x: (-int(x.get("score") or 0), str(x.get("updatedAt") or "")),
|
||
)
|
||
return items[:limit]
|
||
|
||
|
||
def city_recommendations(
|
||
guest_id: str,
|
||
*,
|
||
limit: int = 3,
|
||
) -> list[dict[str, Any]]:
|
||
"""Top same-city (then tag-matched) people for onboarding push."""
|
||
return list_discovery_roster(
|
||
viewer_guest_id=guest_id,
|
||
limit=limit,
|
||
exclude_self=True,
|
||
)
|
||
|
||
|
||
def mark_face_photo(guest_id: str, avatar_url: str) -> None:
|
||
"""Album/selfie photo passed face presence — liveness still required."""
|
||
with db() as conn:
|
||
row = conn.execute(
|
||
"SELECT guest_id FROM roster WHERE guest_id=?", (guest_id,)
|
||
).fetchone()
|
||
if not row:
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar,
|
||
face_ok, liveness_status, updated_at)
|
||
VALUES (?, '游民', '', '', '', '', '', '', ?, 1, 'none', ?)
|
||
""",
|
||
(guest_id, avatar_url[:500], _now()),
|
||
)
|
||
return
|
||
conn.execute(
|
||
"""
|
||
UPDATE roster SET avatar=?, face_ok=1,
|
||
liveness_status=CASE
|
||
WHEN COALESCE(liveness_status,'') IN ('verified','pending') THEN liveness_status
|
||
ELSE 'none'
|
||
END,
|
||
updated_at=?
|
||
WHERE guest_id=?
|
||
""",
|
||
(avatar_url[:500], _now(), guest_id),
|
||
)
|
||
|
||
|
||
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]:
|
||
"""Store challenge frames + full camera recording for human review."""
|
||
import json
|
||
|
||
now = _now()
|
||
item = {
|
||
"id": _uid("live"),
|
||
"guestId": guest_id,
|
||
"avatarUrl": avatar_url,
|
||
"frontUrl": front_url,
|
||
"turnUrl": turn_url,
|
||
"videoUrl": video_url,
|
||
"videoSize": int(video_size or 0),
|
||
"similarity": similarity,
|
||
"yawDelta": yaw_delta,
|
||
"status": "pending",
|
||
"createdAt": now,
|
||
}
|
||
with db() as conn:
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO liveness_audits(
|
||
id, guest_id, avatar_url, front_url, turn_url, video_url, video_size,
|
||
similarity, yaw_delta, status, meta_json, created_at
|
||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
""",
|
||
(
|
||
item["id"],
|
||
guest_id,
|
||
avatar_url[:500],
|
||
front_url[:500],
|
||
turn_url[:500],
|
||
video_url[:500],
|
||
item["videoSize"],
|
||
similarity,
|
||
yaw_delta,
|
||
"pending",
|
||
json.dumps(meta or {}, ensure_ascii=False)[:4000],
|
||
now,
|
||
),
|
||
)
|
||
# Auto-pass machine challenge → verified; video kept for spot-check
|
||
conn.execute(
|
||
"""
|
||
UPDATE roster SET
|
||
avatar=COALESCE(NULLIF(?, ''), avatar),
|
||
face_ok=1,
|
||
liveness_status='verified',
|
||
liveness_at=?,
|
||
liveness_video_url=?,
|
||
liveness_front_url=?,
|
||
liveness_turn_url=?,
|
||
updated_at=?
|
||
WHERE guest_id=?
|
||
""",
|
||
(
|
||
avatar_url[:500],
|
||
now,
|
||
video_url[:500],
|
||
front_url[:500],
|
||
turn_url[:500],
|
||
now,
|
||
guest_id,
|
||
),
|
||
)
|
||
# Ensure roster row exists if guest only uploaded challenge
|
||
if not conn.execute(
|
||
"SELECT 1 FROM roster WHERE guest_id=?", (guest_id,)
|
||
).fetchone():
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO roster(
|
||
guest_id, name, avatar, face_ok, liveness_status, liveness_at,
|
||
liveness_video_url, liveness_front_url, liveness_turn_url, updated_at
|
||
) VALUES (?, '游民', ?, 1, 'verified', ?, ?, ?, ?, ?)
|
||
""",
|
||
(
|
||
guest_id,
|
||
avatar_url[:500],
|
||
now,
|
||
video_url[:500],
|
||
front_url[:500],
|
||
turn_url[:500],
|
||
now,
|
||
),
|
||
)
|
||
item["status"] = "verified"
|
||
return item
|
||
|
||
|
||
def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]:
|
||
limit = max(1, min(int(limit or 50), 200))
|
||
with db() as conn:
|
||
if status:
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT * FROM liveness_audits WHERE status=?
|
||
ORDER BY created_at DESC LIMIT ?
|
||
""",
|
||
(status, limit),
|
||
).fetchall()
|
||
else:
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT * FROM liveness_audits
|
||
ORDER BY created_at DESC LIMIT ?
|
||
""",
|
||
(limit,),
|
||
).fetchall()
|
||
out = []
|
||
for r in rows:
|
||
out.append(
|
||
{
|
||
"id": r["id"],
|
||
"guestId": r["guest_id"],
|
||
"avatarUrl": r["avatar_url"] or "",
|
||
"frontUrl": r["front_url"] or "",
|
||
"turnUrl": r["turn_url"] or "",
|
||
"videoUrl": r["video_url"] or "",
|
||
"videoSize": r["video_size"] or 0,
|
||
"similarity": r["similarity"],
|
||
"yawDelta": r["yaw_delta"],
|
||
"status": r["status"],
|
||
"createdAt": r["created_at"],
|
||
}
|
||
)
|
||
return out
|
||
|
||
|
||
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, request_id: str | None = None) -> dict[str, Any]:
|
||
item = {
|
||
"id": ("app_" + hashlib.sha256(json.dumps([guest_id, gig_id, request_id]).encode()).hexdigest()[:32]) if request_id else _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 OR IGNORE 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"]),
|
||
)
|
||
row = conn.execute("SELECT * FROM gig_apps WHERE id = ?", (item["id"],)).fetchone()
|
||
if (row["name"], row["contact"], row["note"]) != (item["name"], item["contact"], item["note"]):
|
||
raise ValueError("同一请求标识不能用于不同申请")
|
||
item["at"] = row["created_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,
|
||
}
|