nomadro/apps/api/services/social_svc/store.py
Eric ffa456afdf Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 02:25:05 +08:00

989 lines
28 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() -> 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 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")
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)
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_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() 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() 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 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
keys = set(r.keys())
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 "",
"avatar": (r["avatar"] if "avatar" in keys else "") or "",
"updatedAt": r["updated_at"],
}
def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
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 = ""
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,
"updatedAt": updated,
}
with db() as conn:
conn.execute(
"""
INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar, 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,
updated_at=excluded.updated_at
""",
(
guest_id,
row["name"],
row["title"],
row["city"],
row["phone"],
row["linktree"],
row["skills"],
row["bio"],
row["avatar"],
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, 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,
}