"""Social data access via online PocketBase (no SQLite).""" from __future__ import annotations import time import uuid import hashlib import json from pathlib import Path from typing import Any from nomadro_pb import ensure_once, get_pb, pb_quote C_ROSTER = "social_roster" C_LIVENESS = "social_liveness_audits" C_SKILLS = "social_skill_posts" C_REVIEWS = "social_meetup_reviews" C_BLOCKS = "social_blocks" C_REPORTS = "social_reports" C_MESSAGES = "social_messages" C_CHMETA = "social_channel_meta" C_CAFE = "social_cafe_reviews" C_FEEDBACK = "social_feedback" C_JOIN_LEADS = "social_join_leads" C_GIGS = "social_gig_apps" C_READS = "social_channel_reads" C_FILES = "social_files" C_ARCHIVES = "social_archives" # Live collection names keyed by admin entity ENTITY_COLLECTIONS = { "roster": C_ROSTER, "messages": C_MESSAGES, "reviews": C_CAFE, "gigApps": C_GIGS, "feedback": C_FEEDBACK, "joinLeads": C_JOIN_LEADS, "skills": C_SKILLS, "liveness": C_LIVENESS, "meetupReviews": C_REVIEWS, "reports": C_REPORTS, "blocks": C_BLOCKS, "files": C_FILES, "trips": "social_trips", "coffeeBookings": "coffee_bookings", } 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()) def init_pb() -> None: ensure_once() def archive_snapshot( *, entity: str, entity_id: str, action: str, payload: dict[str, Any] | None, guest_id: str = "", note: str = "", ) -> dict[str, Any]: """Append-only archive. Never overwrite; never hard-delete archives.""" init_pb() body = { "entity": (entity or "unknown")[:64], "entity_id": str(entity_id or "")[:120], "guest_id": str(guest_id or "")[:120], "action": (action or "update")[:48], "payload": payload if isinstance(payload, dict) else {"raw": payload}, "note": (note or "")[:500], "created_at": _now(), } return get_pb().create(C_ARCHIVES, body) def _soft_deleted_ids(entity: str) -> set[str]: """Entity ids with a soft_delete archive (latest wins conceptually).""" init_pb() rows = get_pb().list_all( C_ARCHIVES, filter=f"entity={pb_quote(entity)} && action={pb_quote('soft_delete')}", hard_limit=5000, ) return {str(r.get("entity_id") or "") for r in rows if r.get("entity_id")} def soft_delete_record( *, entity: str, entity_id: str, live_collection: str, record: dict[str, Any] | None = None, guest_id: str = "", note: str = "", ) -> bool: """Soft-delete: full snapshot → archive, then hide live row (never PB delete).""" init_pb() pb = get_pb() rec = record if rec is None: try: rec = pb.request( "GET", f"/api/collections/{live_collection}/records/{entity_id}", admin=True ) except Exception: # roster keyed by guest_id if entity == "roster": rec = pb.first(live_collection, filter=f"guest_id={pb_quote(entity_id)}") else: rec = None if not rec: return False rid = str(rec.get("id") or entity_id) gid = guest_id or str(rec.get("guest_id") or "") archive_snapshot( entity=entity, entity_id=str(entity_id or rid), action="soft_delete", payload=dict(rec), guest_id=gid, note=note or "admin soft delete", ) # Hide without destroying bytes patch: dict[str, Any] = {"updated_at": _now()} if entity == "roster": patch.update({"discoverable": False, "status": "deleted"}) elif entity == "messages": patch.update({"recalled": True, "text": "", "reactions": {}}) elif entity in {"reviews", "gigApps", "feedback", "skills"}: # status field exists on skills; others get note marker in archive only if "status" in rec or entity == "skills": patch["status"] = "deleted" try: pb.update(live_collection, rid, patch) except Exception: # Field may be missing on older PB schema — archive already persisted. pass return True def health() -> dict[str, Any]: pb = get_pb() ok = pb.health_ok() return { "ok": ok, "backend": "pocketbase", "pb": pb.base_url, "db": pb.base_url, "dbBytes": 0, } # —— roster —— def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, Any]: status = (r.get("status") or "online").strip() or "online" skills = r.get("skills") or "" intents = r.get("intents") or "" tags = [t.strip() for t in skills.replace(",", ",").replace("、", ",").split(",") if t.strip()][:8] item: dict[str, Any] = { "guestId": r.get("guest_id") or "", "email": r.get("email") or "", "name": r.get("name") or "游民", "title": r.get("title") or "", "city": r.get("city") or "", "skills": skills, "bio": r.get("bio") or "", "avatar": r.get("avatar") or "", "gender": r.get("gender") or "", "intents": intents, "availability": r.get("availability") or "", "status": status, "lookingFor": r.get("looking_for") or "", "updatedAt": r.get("updated_at") or "", "online": status in {"online", "here", "available"}, "tags": tags, "faceOk": bool(r.get("face_ok")), "livenessStatus": r.get("liveness_status") or "none", "livenessAt": r.get("liveness_at") or "", "livenessVideoUrl": r.get("liveness_video_url") or "", "onboardedAt": r.get("onboarded_at") or "", "_id": r.get("id") or "", } if not public: item.update( { "phone": r.get("phone") or "", "linktree": r.get("linktree") or "", "relationship": r.get("relationship") or "", "education": r.get("education") or "", "graduation": r.get("graduation") or "", "wechat": r.get("wechat") or "", "discoverable": bool(r.get("discoverable", True)), "livenessFrontUrl": r.get("liveness_front_url") or "", "livenessTurnUrl": r.get("liveness_turn_url") or "", } ) return item def get_roster(guest_id: str) -> dict[str, Any] | None: init_pb() rec = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") return _roster_from_rec(rec, public=False) if rec else None def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: init_pb() existing = get_roster(guest_id) is_first = existing is None 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 = True else: discoverable = str(discoverable).lower() not in {"0", "false", "no", "off"} onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "") email_n = str(payload.get("email") or "").strip().lower()[:160] body = { "guest_id": guest_id, "email": email_n or str((existing or {}).get("email") or "").strip().lower()[:160], "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, "looking_for": 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, "onboarded_at": onboarded_at, "updated_at": updated, } # Preserve face/liveness unless caller overwrites avatar via mark_face if existing: body.setdefault("face_ok", existing.get("faceOk", False)) body.setdefault("liveness_status", existing.get("livenessStatus") or "none") body.setdefault("liveness_at", existing.get("livenessAt") or "") body.setdefault("liveness_video_url", existing.get("livenessVideoUrl") or "") body.setdefault("liveness_front_url", existing.get("livenessFrontUrl") or "") body.setdefault("liveness_turn_url", existing.get("livenessTurnUrl") or "") if not avatar and existing.get("avatar"): body["avatar"] = existing["avatar"] if existing: archive_snapshot( entity="roster", entity_id=guest_id, action="update", payload=dict(existing), guest_id=guest_id, note="roster upsert before-write", ) try: get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) except Exception: # PB 尚无 email 字段时降级 body.pop("email", None) get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) row = get_roster(guest_id) or {} row["isFirstProfile"] = is_first archive_snapshot( entity="roster", entity_id=guest_id, action="create" if is_first else "update_after", payload=dict(body), guest_id=guest_id, note="roster upsert after-write", ) return row def mark_face_photo( guest_id: str, avatar_url: str, *, face_ok: bool = True, ) -> None: """Album/selfie → avatar. face_ok only when detector saw a real face.""" init_pb() existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") url = avatar_url[:500] now = _now() if not existing: get_pb().create( C_ROSTER, { "guest_id": guest_id, "name": "游民", "avatar": url, "face_ok": bool(face_ok), "liveness_status": "none", "discoverable": True, "status": "online", "updated_at": now, }, ) return live = (existing.get("liveness_status") or "").strip() get_pb().update( C_ROSTER, existing["id"], { "avatar": url, "face_ok": bool(face_ok), "liveness_status": live if live in {"verified", "pending"} else "none", "updated_at": now, }, ) def save_liveness_audit( guest_id: 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, email: str = "", ) -> dict[str, Any]: """Live capture audit only — never overwrites roster.avatar.""" init_pb() now = _now() email_n = (email or "").strip().lower()[:160] meta_body = dict(meta or {}) if email_n: meta_body["email"] = email_n item = { "id": _uid("live"), "guestId": guest_id, "email": email_n, "frontUrl": front_url, "turnUrl": turn_url, "videoUrl": video_url, "videoSize": int(video_size or 0), "similarity": similarity, "yawDelta": yaw_delta, "status": "verified", "createdAt": now, } body = { "guest_id": guest_id, "avatar_url": "", # not an avatar "front_url": front_url[:500], "turn_url": turn_url[:500], "video_url": (video_url or "")[:500], "video_size": item["videoSize"], "similarity": similarity, "yaw_delta": yaw_delta, "status": "verified", "meta": meta_body, "created_at": now, } if email_n: body["email"] = email_n try: rec = get_pb().create(C_LIVENESS, body) except Exception: body.pop("email", None) rec = get_pb().create(C_LIVENESS, body) item["id"] = rec.get("id") or item["id"] existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") patch = { # face_ok stays album-avatar only — live frames are not an avatar "liveness_status": "verified", "liveness_at": now, "liveness_video_url": (video_url or "")[:500], "liveness_front_url": front_url[:500], "liveness_turn_url": turn_url[:500], "updated_at": now, } if email_n: patch["email"] = email_n if existing: get_pb().update(C_ROSTER, existing["id"], patch) else: # Placeholder only — not discoverable until profile + avatar submitted create_body = { "guest_id": guest_id, "name": "游民", "avatar": "", "discoverable": False, "face_ok": False, "status": "offline", **patch, } if email_n: create_body["email"] = email_n try: get_pb().create(C_ROSTER, create_body) except Exception: create_body.pop("email", None) get_pb().create(C_ROSTER, create_body) return item def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]: init_pb() filt = f"status={pb_quote(status)}" if status else None rows = get_pb().list_all(C_LIVENESS, filter=filt, sort="-created_at", hard_limit=limit) out: list[dict[str, Any]] = [] for r in rows: meta = r.get("meta") if isinstance(r.get("meta"), dict) else {} out.append( { "id": r.get("id"), "guestId": r.get("guest_id"), "email": r.get("email") or meta.get("email") or "", "frontUrl": r.get("front_url") or "", "turnUrl": r.get("turn_url") or "", "videoUrl": r.get("video_url") or "", "videoSize": r.get("video_size") or 0, "status": r.get("status"), "meta": meta, "createdAt": r.get("created_at"), } ) return out def list_discovery_roster( *, viewer_guest_id: str | None = None, city: str = "", limit: int = 48, exclude_self: bool = True, require_face: bool = False, ) -> list[dict[str, Any]]: init_pb() rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=400) city_f = "".join((city or "").strip().lower().split()) viewer = get_roster(viewer_guest_id) if viewer_guest_id else None items: list[dict[str, Any]] = [] for r in rows: if exclude_self and viewer_guest_id and r.get("guest_id") == viewer_guest_id: continue if r.get("discoverable") is False: continue if not (r.get("name") or "").strip(): continue # Dating / 约会: no face in avatar → never show if require_face: face_raw = r.get("face_ok") face_ok = face_raw is True or face_raw == 1 or str(face_raw).lower() in { "1", "true", "yes", } avatar = str(r.get("avatar") or "").strip() if not face_ok: continue if not avatar: continue # reject placeholder / broken relative junk if "nomadro.webp" in avatar or avatar.startswith("data:"): continue if not ( avatar.startswith("https://") or avatar.startswith("http://") or avatar.startswith("/api/social/") ): continue item = _roster_from_rec(r, public=True) if city_f and city_f not in "".join((item.get("city") or "").lower().split()): # still allow if no city filter strict — filter when city provided if city_f: continue items.append(item) def score(it: dict[str, Any]) -> float: s = 0.0 if viewer and viewer.get("city") and viewer["city"] and viewer["city"] in (it.get("city") or ""): s += 100 if it.get("online"): s += 20 return s items.sort(key=score, reverse=True) return items[: max(1, min(int(limit or 48), 100))] def city_recommendations(guest_id: str, *, limit: int = 3) -> list[dict[str, Any]]: return list_discovery_roster( viewer_guest_id=guest_id, limit=limit, exclude_self=True ) def clear_liveness_for_guest(guest_id: str) -> dict[str, Any]: """Soft-clear live audits (archive each) and reset liveness fields; keep album avatar.""" init_pb() pb = get_pb() audits = pb.list_all(C_LIVENESS, filter=f"guest_id={pb_quote(guest_id)}") for a in audits: soft_delete_record( entity="liveness", entity_id=str(a.get("id")), live_collection=C_LIVENESS, record=a, guest_id=guest_id, note="clear_liveness_for_guest", ) rec = pb.first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") if rec: archive_snapshot( entity="roster", entity_id=guest_id, action="liveness_reset", payload=dict(rec), guest_id=guest_id, ) pb.update( C_ROSTER, rec["id"], { "liveness_status": "none", "liveness_at": "", "liveness_video_url": "", "liveness_front_url": "", "liveness_turn_url": "", "updated_at": _now(), }, ) return {"ok": True, "deletedAudits": len(audits), "soft": True} # —— channel messages —— def _ch_meta(channel_id: str) -> dict[str, Any] | None: return get_pb().first(C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}") def channel_seq(channel_id: str) -> int: init_pb() meta = _ch_meta(channel_id) if meta: return max(0, int(meta.get("seq") or 0)) rows = get_pb().list_all( C_MESSAGES, filter=f"channel_id={pb_quote(channel_id)}", sort="-seq", hard_limit=1, ) return int(rows[0].get("seq") or 0) if rows else 0 def _avatars_for_guests(guest_ids: list[str]) -> dict[str, str]: """Batch roster.avatar for chat bubbles (guest_id → url).""" ids = sorted({str(g or "").strip() for g in guest_ids if str(g or "").strip()}) if not ids: return {} init_pb() out: dict[str, str] = {} pb = get_pb() for i in range(0, len(ids), 40): chunk = ids[i : i + 40] filt = " || ".join(f"guest_id={pb_quote(g)}" for g in chunk) try: rows = pb.list_all(C_ROSTER, filter=filt, hard_limit=len(chunk) + 8) except Exception: rows = [] for r in rows: gid = str(r.get("guest_id") or "").strip() av = str(r.get("avatar") or "").strip()[:500] if gid and av: out[gid] = av return out def _public_message(item: dict[str, Any], *, avatar: str = "") -> dict[str, Any]: """Flatten PB message for clients: at + avatar for chat UI.""" created = str(item.get("createdAt") or item.get("at") or "").strip() out = dict(item) out["at"] = created out["createdAt"] = created av = (avatar or str(item.get("avatar") or "")).strip()[:500] if av: out["avatar"] = av else: out.setdefault("avatar", "") return out 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]]: init_pb() lim = max(1, min(int(limit or 100), 500)) rows = get_pb().list_all( C_MESSAGES, filter=(f"channel_id={pb_quote(channel_id)}" + (f" && seq>{int(since)}" if since is not None and since > 0 else '') + (f" && seq<{int(before)}" if before is not None and before > 0 else '')), sort="-seq,-created_at,-id", hard_limit=2000, ) needle = (q or "").strip().lower() out: list[dict[str, Any]] = [] for r in rows: seq = int(r.get("seq") or 0) if since is not None and since > 0 and seq <= since: continue if before is not None and before > 0 and seq >= before: continue text = r.get("text") or "" nick = r.get("nick") or "" if needle and needle not in text.lower() and needle not in nick.lower(): continue if r.get("recalled"): continue out.append( { "id": r.get("id"), "channelId": channel_id, "seq": seq, "guestId": r.get("guest_id"), "author": nick or "游民", "text": text, "kind": r.get("kind") or "text", "meta": r.get("meta") or {}, "attachments": r.get("attachments") or [], "replyTo": r.get("reply_to"), "reactions": r.get("reactions") or {}, "pinned": bool(r.get("pinned")), "createdAt": r.get("created_at"), "editedAt": r.get("edited_at") or "", } ) out = list(reversed(out[:lim])) avatars = _avatars_for_guests([str(m.get("guestId") or "") for m in out]) return [ _public_message(m, avatar=avatars.get(str(m.get("guestId") or ""), "")) for m in out ] def add_message( channel_id: str, author: str, text: str, guest_id: str, *, client_id: str | None = None, kind: str = "text", meta: dict[str, Any] | None = None, attachments: list[Any] | None = None, reply_to: dict[str, Any] | None = None, ) -> dict[str, Any]: init_pb() pb = get_pb() stable_id = None request_meta = dict(meta or {}) fingerprint = hashlib.sha256(json.dumps( [author, text, kind, meta or {}, attachments or [], reply_to], sort_keys=True, ensure_ascii=False, separators=(',', ':'), ).encode()).hexdigest() if client_id: stable_id = hashlib.sha256(json.dumps([channel_id, guest_id, client_id]).encode()).hexdigest()[:15] request_meta.update({'clientId': client_id, 'requestFingerprint': fingerprint}) existing = pb.first(C_MESSAGES, filter=f'id={pb_quote(stable_id)}') if existing: if (existing.get('meta') or {}).get('requestFingerprint') != fingerprint: raise ValueError('同一请求标识不能用于不同消息') return get_message(stable_id) or {} # Replays must not consume quota or fail after the original exhausted it. from social_svc.trial_gate import assert_chat_trial_ok from social_svc.im import check_rate assert_chat_trial_ok(guest_id) check_rate(guest_id) seq = channel_seq(channel_id) + 1 now = _now() body = { "channel_id": channel_id, "seq": seq, "guest_id": guest_id, "nick": (author or "游民")[:48], "text": (text or "")[:4000], "kind": kind or "text", "meta": request_meta, "attachments": attachments or [], "reply_to": reply_to, "reactions": {}, "pinned": False, "recalled": False, "created_at": now, "edited_at": "", } if stable_id: body['id'] = stable_id try: rec = pb.create(C_MESSAGES, body) except Exception: if not stable_id: raise existing = pb.first(C_MESSAGES, filter=f'id={pb_quote(stable_id)}') if not existing: raise if (existing.get('meta') or {}).get('requestFingerprint') != fingerprint: raise ValueError('同一请求标识不能用于不同消息') return get_message(stable_id) or {} meta_rec = _ch_meta(channel_id) if meta_rec: pb.update(C_CHMETA, meta_rec["id"], {"seq": seq, "updated_at": now}) else: pb.create( C_CHMETA, { "channel_id": channel_id, "seq": seq, "pins": [], "presence": {}, "updated_at": now, }, ) saved = get_message(str(rec.get('id') or '')) if saved: return saved avatars = _avatars_for_guests([guest_id]) return _public_message( { "id": rec.get("id"), "channelId": channel_id, "seq": seq, "guestId": guest_id, "author": body["nick"], "text": body["text"], "kind": body["kind"], "meta": body["meta"], "attachments": body["attachments"], "replyTo": reply_to, "reactions": {}, "pinned": False, "createdAt": now, }, avatar=avatars.get(guest_id, ""), ) def get_message(msg_id: str) -> dict[str, Any] | None: init_pb() try: r = get_pb().request( "GET", f"/api/collections/{C_MESSAGES}/records/{msg_id}", admin=True ) except Exception: return None gid = str(r.get("guest_id") or "") avatars = _avatars_for_guests([gid]) if gid else {} return _public_message( { "id": r.get("id"), "channelId": r.get("channel_id"), "seq": int(r.get("seq") or 0), "guestId": r.get("guest_id"), "author": r.get("nick") or "游民", "text": r.get("text") or "", "kind": r.get("kind") or "text", "meta": r.get("meta") or {}, "attachments": r.get("attachments") or [], "replyTo": r.get("reply_to"), "reactions": r.get("reactions") or {}, "pinned": bool(r.get("pinned")), "recalled": bool(r.get("recalled")), "createdAt": r.get("created_at"), "editedAt": r.get("edited_at") or "", }, avatar=avatars.get(gid, ""), ) def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("guestId") != guest_id: raise ValueError("not your message") if m.get("recalled"): raise ValueError("recalled") now = _now() get_pb().update( C_MESSAGES, msg_id, {"text": (text or "").strip()[:2000], "edited_at": now}, ) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("guestId") != guest_id: raise ValueError("not your message") get_pb().update( C_MESSAGES, msg_id, {"text": "", "recalled": True, "attachments": [], "reactions": {}}, ) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def react_message( channel_id: str, msg_id: str, guest_id: str, emoji: str ) -> dict[str, Any]: key = (emoji or "").strip()[:16] if not key: raise ValueError("empty emoji") m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("recalled"): raise ValueError("recalled") reactions: dict[str, list[str]] = dict(m.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) get_pb().update(C_MESSAGES, msg_id, {"reactions": reactions}) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def pin_message( channel_id: str, msg_id: str, guest_id: str, pinned: bool = True ) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("recalled"): raise ValueError("recalled") meta = dict(m.get("meta") or {}) now = _now() 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) get_pb().update(C_MESSAGES, msg_id, {"pinned": bool(pinned), "meta": meta}) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def report_message( channel_id: str, msg_id: str, guest_id: str, reason: str = "" ) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") meta = dict(m.get("meta") or {}) 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() get_pb().update(C_MESSAGES, msg_id, {"meta": meta}) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]: 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_pb() pb = get_pb() filt = f"guest_id={pb_quote(guest_id)} && channel_id={pb_quote(channel_id)}" existing = pb.first(C_READS, filter=filt) recv = int((existing or {}).get("recv_seq") or 0) read = int((existing or {}).get("read_seq") or 0) if what == "recv": recv = max(recv, seq) else: read = max(read, seq) recv = max(recv, read) now = _now() pb.upsert( C_READS, filter=filt, payload={ "guest_id": guest_id, "channel_id": channel_id, "recv_seq": recv, "read_seq": read, "updated_at": now, }, ) return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read} def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]: init_pb() seq = channel_seq(channel_id) recv = read = 0 if guest_id: mark = get_pb().first( C_READS, filter=f"guest_id={pb_quote(guest_id)} && channel_id={pb_quote(channel_id)}", ) if mark: recv = int(mark.get("recv_seq") or 0) read = int(mark.get("read_seq") or 0) return { "channelId": channel_id, "seq": seq, "recv": recv, "read": read, "unread": max(0, seq - read), } def save_file_meta( file_id: str, channel_id: str, guest_id: str, *, kind: str, name: str, mime: str, size: int, path: str, ) -> dict[str, Any]: init_pb() now = _now() get_pb().upsert( C_FILES, filter=f"file_id={pb_quote(file_id)}", payload={ "file_id": file_id, "channel_id": channel_id, "guest_id": guest_id, "kind": kind, "name": name, "mime": mime, "size": size, "path": path, "created_at": now, }, ) return { "id": file_id, "kind": kind, "name": name, "mime": mime, "size": size, "url": f"/api/social/v1/files/{file_id}", } def get_file(file_id: str) -> dict[str, Any] | None: init_pb() row = get_pb().first(C_FILES, filter=f"file_id={pb_quote(file_id)}") if not row: return None return { "id": row.get("file_id") or file_id, "channelId": row.get("channel_id"), "kind": row.get("kind"), "name": row.get("name"), "mime": row.get("mime"), "size": int(row.get("size") or 0), "path": row.get("path"), } def list_cafe_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]: init_pb() lim = max(1, min(int(limit or 50), 200)) rows = get_pb().list_all( C_CAFE, filter=f"cafe_id={pb_quote(cafe_id)}" if cafe_id else None, sort="-created_at", hard_limit=lim, ) return [ { "id": r.get("id"), "cafeId": r.get("cafe_id"), "author": r.get("author"), "score": r.get("score"), "text": r.get("text"), "photoNote": r.get("photo_note") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in rows[:lim] ] def add_cafe_review( cafe_id: str, author: str, score: int, text: str, photo_note: str, guest_id: str, ) -> dict[str, Any]: init_pb() now = _now() body = { "cafe_id": cafe_id, "guest_id": guest_id, "author": (author or "游民").strip()[:48] or "游民", "score": max(1, min(int(score or 5), 5)), "text": (text or "").strip()[:2000], "photo_note": (photo_note or "").strip()[:200], "created_at": now, } rec = get_pb().create(C_CAFE, body) return { "id": rec.get("id"), "cafeId": cafe_id, "author": body["author"], "score": body["score"], "text": body["text"], "photoNote": body["photo_note"], "guestId": guest_id, "at": now, } def _feedback_local_path() -> Path: from social_svc.config import SOCIAL_DB_PATH return Path(SOCIAL_DB_PATH).resolve().parent / "feedback.json" def _feedback_local_append(row: dict[str, Any]) -> None: path = _feedback_local_path() path.parent.mkdir(parents=True, exist_ok=True) items: list[dict[str, Any]] = [] if path.is_file(): try: raw = json.loads(path.read_text(encoding="utf-8")) if isinstance(raw, dict) and isinstance(raw.get("items"), list): items = list(raw["items"]) elif isinstance(raw, list): items = list(raw) except Exception: items = [] items.insert(0, row) path.write_text( json.dumps({"items": items[:2000]}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) def _feedback_local_list() -> list[dict[str, Any]]: path = _feedback_local_path() if not path.is_file(): return [] try: raw = json.loads(path.read_text(encoding="utf-8")) if isinstance(raw, dict) and isinstance(raw.get("items"), list): return [x for x in raw["items"] if isinstance(x, dict)] if isinstance(raw, list): return [x for x in raw if isinstance(x, dict)] except Exception: return [] return [] def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: now = _now() body = { "guest_id": guest_id, "kind": kind if kind in {"反馈", "建议"} else "建议", "text": (text or "").strip()[:4000], "contact": (contact or "").strip()[:120], "created_at": now, } if not body["text"]: raise ValueError("请填写内容") try: init_pb() rec = get_pb().create(C_FEEDBACK, body) return { "id": rec.get("id"), "kind": body["kind"], "text": body["text"], "contact": body["contact"], "guestId": guest_id, "at": now, "stored": "pocketbase", } except Exception: # PB 挂了仍要接住反馈(本地 / 离线) fid = f"fb_local_{uuid.uuid4().hex[:12]}" row = { "id": fid, "kind": body["kind"], "text": body["text"], "contact": body["contact"], "guestId": guest_id, "at": now, "source": "api-local", } _feedback_local_append(row) return {**row, "stored": "local"} _JOIN_FACE_STAGES = frozenset( { "profile_done", "liveness_verified", "liveness_failed", "liveness_skipped", "join_done", } ) _JOIN_EARLY_STAGES = frozenset({"email_submit", "pay_launched"}) def _sanitize_join_lead_item(item: dict[str, Any]) -> dict[str, Any]: """Strip false 已付 / 已过 / 假「加入完成」from dirty leftovers.""" stage = str(item.get("stage") or "") payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} stages: set[str] = set() raw_stages = payload.get("stages") if isinstance(raw_stages, list): stages.update(str(s) for s in raw_stages if s) hist = item.get("history") if isinstance(hist, list): for h in hist: if isinstance(h, dict) and h.get("stage"): stages.add(str(h["stage"])) stages.add(stage) has_face = bool(stages & _JOIN_FACE_STAGES) paid = str(item.get("paid") or "") price = payload.get("priceFen") is_free_intent = ( payload.get("intent") == "free" or price == 0 or (isinstance(price, (int, float)) and price <= 0) ) if paid == "1": if is_free_intent and "pay_confirmed" not in stages: paid = "free" elif stage in _JOIN_EARLY_STAGES and "pay_confirmed" not in stages: paid = "" out = dict(item) out["paid"] = paid # 跳过自拍却写成 join_done → 纠正为 liveness_skipped(后台勿显示「加入完成」) live = str(item.get("livenessStatus") or item.get("liveness_status") or "") if stage == "join_done" and live != "verified" and payload.get("liveness") != "verified": if "liveness_verified" not in stages: out["stage"] = "liveness_skipped" stage = "liveness_skipped" # 当前停在只填邮箱 / 发起支付:绝不可能已核验(浏览器串号 faceOk 一律丢掉) if stage in _JOIN_EARLY_STAGES: out["faceOk"] = "" out["livenessStatus"] = "none" elif not has_face: out["faceOk"] = "" out["livenessStatus"] = "none" return out def _join_leads_local_path() -> Path: from social_svc.config import SOCIAL_DB_PATH # Prefer portal data/join-leads.json next to repo root root = Path(SOCIAL_DB_PATH).resolve().parents[1] candidates = [ root / "data" / "join-leads.json", Path.cwd() / "data" / "join-leads.json", ] for p in candidates: if p.is_file(): return p return candidates[0] def _join_leads_local_list() -> list[dict[str, Any]]: path = _join_leads_local_path() if not path.is_file(): return [] try: raw = json.loads(path.read_text(encoding="utf-8")) items = raw.get("items") if isinstance(raw, dict) else raw if not isinstance(items, list): return [] out: list[dict[str, Any]] = [] for it in items: if not isinstance(it, dict): continue out.append( { "id": it.get("id") or it.get("email") or "", "email": it.get("email") or "", "guestId": it.get("guestId") or it.get("guest_id") or "", "stage": it.get("stage") or "", "name": it.get("name") or "", "paid": it.get("paid") or "", "faceOk": it.get("faceOk") or it.get("face_ok") or "", "livenessStatus": it.get("livenessStatus") or it.get("liveness_status") or "", "ua": it.get("ua") or "", "payload": it.get("payload") if isinstance(it.get("payload"), dict) else {}, "createdAt": it.get("createdAt") or it.get("created_at") or "", "updatedAt": it.get("updatedAt") or it.get("updated_at") or "", "history": it.get("history") if isinstance(it.get("history"), list) else [], } ) return out except Exception: return [] def upsert_join_lead( *, email: str, guest_id: str, stage: str = "email_submit", name: str = "", payload: dict[str, Any] | None = None, ua: str = "", paid: str = "", face_ok: str = "", liveness_status: str = "", ) -> dict[str, Any]: """Archive every join funnel event; upsert live lead row for admin list.""" init_pb() now = _now() email_n = (email or "").strip().lower()[:160] if not email_n or "@" not in email_n: raise ValueError("invalid email") gid = (guest_id or "")[:120] stage_n = (stage or "email_submit")[:48] body_payload = payload if isinstance(payload, dict) else {} allow_face = stage_n in _JOIN_FACE_STAGES # email_submit 等禁止写入浏览器残留核验,避免串号 face_in = (face_ok or "")[:8] if allow_face else "" live_in = (liveness_status or "")[:24] if allow_face else "" early = stage_n in {"email_submit", "pay_launched"} paid_in = (paid or "")[:8] intent = str(body_payload.get("intent") or "") if early: # 只填邮箱:最多记 free,绝不能记已付 if paid_in == "free" or intent == "free" or body_payload.get("priceFen") == 0: paid_in = "free" else: paid_in = "" snap = { "email": email_n, "guestId": gid, "stage": stage_n, "name": (name or "")[:64], "paid": paid_in, "faceOk": face_in, "livenessStatus": live_in or ("none" if not allow_face else ""), "ua": (ua or "")[:240], "payload": body_payload, "at": now, } try: archive_snapshot( entity="join_leads", entity_id=email_n, action=stage_n, payload=snap, guest_id=gid, note=f"join:{stage_n}", ) except Exception: # PB 不可用时仍接受线索(门户 data/join-leads.json 已落盘) pass lead_id = email_n try: pb = get_pb() existing = pb.first(C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}") if existing and existing.get("id"): face_val = face_in or (existing.get("face_ok") or "") if allow_face else (existing.get("face_ok") or "") live_val = ( live_in or (existing.get("liveness_status") or "none") if allow_face else (existing.get("liveness_status") or "none") ) else: face_val = face_in live_val = live_in or "none" prev_paid = str((existing or {}).get("paid") or "") if stage_n == "pay_confirmed" and (paid_in == "1" or not paid_in): paid_val = "1" elif paid_in == "free" or prev_paid == "free": # 临时免费贯穿全程;除非真回调 pay_confirmed paid_val = "free" elif early: # 只填邮箱 / 发起支付:禁止写成已付 paid_val = "" else: paid_val = paid_in or prev_paid row = { "email": email_n, "guest_id": gid or ((existing or {}).get("guest_id") or ""), "stage": stage_n, "name": (name or "")[:64] or ((existing or {}).get("name") or ""), "payload": body_payload, "ua": (ua or "")[:240], "paid": paid_val, "face_ok": face_val, "liveness_status": live_val, "updated_at": now, } if existing and existing.get("id"): old_p = existing.get("payload") if isinstance(existing.get("payload"), dict) else {} row["payload"] = { **old_p, **body_payload, "stages": list({*list(old_p.get("stages") or []), stage_n}), } if not row.get("guest_id") and existing.get("guest_id"): row["guest_id"] = existing.get("guest_id") rec = pb.update(C_JOIN_LEADS, str(existing["id"]), row) else: row["created_at"] = now row["payload"] = {**body_payload, "stages": [stage_n]} rec = pb.create(C_JOIN_LEADS, row) lead_id = str(rec.get("id") or email_n) except Exception: # Collection may not exist yet — archive is enough for admin list fallback lead_id = email_n return { "ok": True, "id": lead_id, "email": email_n, "guestId": gid, "stage": stage_n, "at": now, } def admin_list_join_leads( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Prefer live social_join_leads; fall back to social_archives entity=join_leads.""" lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) needle = (q or "").strip().lower() items: list[dict[str, Any]] = [] try: init_pb() rows = get_pb().list_all(C_JOIN_LEADS, sort="-updated_at", hard_limit=5000) for r in rows: items.append( { "id": r.get("id"), "email": r.get("email") or "", "guestId": r.get("guest_id") or "", "stage": r.get("stage") or "", "name": r.get("name") or "", "paid": r.get("paid") or "", "faceOk": r.get("face_ok") or "", "livenessStatus": r.get("liveness_status") or "", "ua": r.get("ua") or "", "payload": r.get("payload") or {}, "createdAt": r.get("created_at") or "", "updatedAt": r.get("updated_at") or "", } ) except Exception: items = [] if not items: # Aggregate latest archive snapshot per email try: arch = get_pb().list_all( C_ARCHIVES, filter=f"entity={pb_quote('join_leads')}", sort="-created_at", hard_limit=5000, ) by_email: dict[str, dict[str, Any]] = {} for a in arch: payload = a.get("payload") if isinstance(a.get("payload"), dict) else {} email = str( payload.get("email") or a.get("entity_id") or "" ).strip().lower() if not email or email in by_email: continue by_email[email] = { "id": a.get("id") or email, "email": email, "guestId": payload.get("guestId") or a.get("guest_id") or "", "stage": payload.get("stage") or a.get("action") or "", "name": payload.get("name") or "", "paid": payload.get("paid") or "", "faceOk": payload.get("faceOk") or "", "livenessStatus": payload.get("livenessStatus") or "", "ua": payload.get("ua") or "", "payload": payload, "createdAt": a.get("created_at") or "", "updatedAt": a.get("created_at") or "", } items = list(by_email.values()) except Exception: items = [] # Merge portal local file (dev / offline) — newer updatedAt wins per email local_items = _join_leads_local_list() if local_items: by_email: dict[str, dict[str, Any]] = {} for r in items: em = str(r.get("email") or "").strip().lower() if em: by_email[em] = r for r in local_items: em = str(r.get("email") or "").strip().lower() if not em: continue prev = by_email.get(em) if not prev or str(r.get("updatedAt") or "") >= str(prev.get("updatedAt") or ""): by_email[em] = r items = list(by_email.values()) items = [_sanitize_join_lead_item(r) for r in items] items.sort(key=lambda r: str(r.get("updatedAt") or ""), reverse=True) if needle: items = [ r for r in items if needle in str(r.get("email") or "").lower() or needle in str(r.get("guestId") or "").lower() or needle in str(r.get("name") or "").lower() or needle in str(r.get("stage") or "").lower() ] total = len(items) page = items[off : off + lim] return {"ok": True, "total": total, "items": page} def add_gig_app( gig_id: str, name: str, contact: str, note: str, guest_id: str, request_id: str | None = None, ) -> dict[str, Any]: import hashlib import json as _json init_pb() now = _now() stable_id = None if request_id: stable_id = ( "app_" + hashlib.sha256( _json.dumps([guest_id, gig_id, request_id]).encode() ).hexdigest()[:32] ) body = { "gig_id": gig_id, "guest_id": guest_id, "name": (name or "").strip()[:64], "contact": (contact or "").strip()[:120], "note": (note or "").strip()[:2000], "request_id": request_id or "", "created_at": now, } pb = get_pb() if stable_id: existing = pb.first( C_GIGS, filter=f"request_id={pb_quote(request_id or '')} && guest_id={pb_quote(guest_id)} && gig_id={pb_quote(gig_id)}", ) if existing: if ( (existing.get("name"), existing.get("contact"), existing.get("note")) != (body["name"], body["contact"], body["note"]) ): raise ValueError("同一请求标识不能用于不同申请") return { "id": existing.get("id"), "gigId": gig_id, "name": existing.get("name"), "contact": existing.get("contact"), "note": existing.get("note") or "", "guestId": guest_id, "at": existing.get("created_at") or now, } rec = pb.create(C_GIGS, body) return { "id": rec.get("id") or stable_id, "gigId": gig_id, "name": body["name"], "contact": body["contact"], "note": body["note"], "guestId": guest_id, "at": now, } # —— admin / ugc helpers —— def _safe_count(pb: Any, collection: str) -> int: try: return len(pb.list_all(collection, hard_limit=5000)) except Exception: return 0 def admin_overview() -> dict[str, Any]: init_pb() pb = get_pb() counts = { "messages": _safe_count(pb, C_MESSAGES), "roster": _safe_count(pb, C_ROSTER), "reviews": _safe_count(pb, C_CAFE), "gigApps": _safe_count(pb, C_GIGS), "feedback": _safe_count(pb, C_FEEDBACK), "joinLeads": _safe_count(pb, C_JOIN_LEADS), "skills": _safe_count(pb, C_SKILLS), "liveness": _safe_count(pb, C_LIVENESS), "meetupReviews": _safe_count(pb, C_REVIEWS), "reports": _safe_count(pb, C_REPORTS), "blocks": _safe_count(pb, C_BLOCKS), "files": _safe_count(pb, C_FILES), "trips": _safe_count(pb, "social_trips"), "coffeeBookings": _safe_count(pb, "coffee_bookings"), "archives": _safe_count(pb, C_ARCHIVES), } return { "ok": pb.health_ok(), "backend": "pocketbase", "path": pb.base_url, "exists": True, "bytes": 0, "writable": True, "counts": counts, } def admin_list_messages( *, channel_id: str = "", q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) filt = f"channel_id={pb_quote(channel_id)}" if channel_id.strip() else None rows = get_pb().list_all(C_MESSAGES, filter=filt, sort="-created_at", hard_limit=5000) needle = q.strip().lower() if needle: rows = [ r for r in rows if needle in (r.get("nick") or "").lower() or needle in (r.get("text") or "").lower() or needle in (r.get("guest_id") or "").lower() ] total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "channelId": r.get("channel_id"), "author": r.get("nick") or "游民", "text": r.get("text") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_message(message_id: str) -> bool: return soft_delete_record( entity="messages", entity_id=message_id, live_collection=C_MESSAGES, ) def admin_list_roster( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=5000) needle = q.strip().lower() if needle: rows = [ r for r in rows if needle in (r.get("name") or "").lower() or needle in (r.get("city") or "").lower() or needle in (r.get("title") or "").lower() or needle in (r.get("guest_id") or "").lower() or needle in (r.get("bio") or "").lower() ] total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "guestId": r.get("guest_id"), "name": r.get("name"), "title": r.get("title") or "", "city": r.get("city") or "", "phone": r.get("phone") or "", "linktree": r.get("linktree") or "", "skills": r.get("skills") or "", "bio": r.get("bio") or "", "updatedAt": r.get("updated_at"), } for r in page ], } def admin_update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: init_pb() existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") if not existing: return None archive_snapshot( entity="roster", entity_id=guest_id, action="admin_update", payload=dict(existing), guest_id=guest_id, ) fields = { "name": str(patch.get("name", existing.get("name") or ""))[:64] or "游民", "title": str(patch.get("title", existing.get("title") or ""))[:80], "city": str(patch.get("city", existing.get("city") or ""))[:64], "phone": str(patch.get("phone", existing.get("phone") or ""))[:32], "linktree": str(patch.get("linktree", existing.get("linktree") or ""))[:240], "skills": str(patch.get("skills", existing.get("skills") or ""))[:200], "bio": str(patch.get("bio", existing.get("bio") or ""))[:2000], "updated_at": _now(), } # Admin restore from soft-delete if patch.get("restore"): fields["status"] = str(patch.get("status") or "online")[:32] fields["discoverable"] = True get_pb().update(C_ROSTER, existing["id"], fields) out = { **{k: fields[k] for k in ("name", "title", "city", "phone", "linktree", "skills", "bio")}, "guestId": guest_id, "updatedAt": fields["updated_at"], } archive_snapshot( entity="roster", entity_id=guest_id, action="admin_update_after", payload=dict(fields), guest_id=guest_id, ) return out def admin_delete_roster(guest_id: str) -> bool: return soft_delete_record( entity="roster", entity_id=guest_id, live_collection=C_ROSTER, guest_id=guest_id, ) def admin_list_cafe_reviews( *, cafe_id: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) filt = f"cafe_id={pb_quote(cafe_id)}" if cafe_id.strip() else None rows = get_pb().list_all(C_CAFE, filter=filt, sort="-created_at", hard_limit=5000) total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "cafeId": r.get("cafe_id"), "author": r.get("author"), "score": r.get("score"), "text": r.get("text"), "photoNote": r.get("photo_note") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_cafe_review(review_id: str) -> bool: return soft_delete_record( entity="reviews", entity_id=review_id, live_collection=C_CAFE, ) def admin_list_gig_apps( *, gig_id: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) filt = f"gig_id={pb_quote(gig_id)}" if gig_id.strip() else None rows = get_pb().list_all(C_GIGS, filter=filt, sort="-created_at", hard_limit=5000) total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "gigId": r.get("gig_id"), "name": r.get("name"), "contact": r.get("contact"), "note": r.get("note") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_gig_app(app_id: str) -> bool: return soft_delete_record( entity="gigApps", entity_id=app_id, live_collection=C_GIGS, ) def admin_list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) items: list[dict[str, Any]] = [] try: init_pb() rows = get_pb().list_all(C_FEEDBACK, sort="-created_at", hard_limit=5000) items = [ { "id": r.get("id"), "kind": r.get("kind"), "text": r.get("text"), "contact": r.get("contact") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in rows ] except Exception: items = [] # Merge API-local + portal-local offline files seen = {str(x.get("id") or "") for x in items} for src in (_feedback_local_list(),): for r in src: rid = str(r.get("id") or "") if rid and rid in seen: continue if rid: seen.add(rid) items.append( { "id": r.get("id"), "kind": r.get("kind"), "text": r.get("text"), "contact": r.get("contact") or "", "guestId": r.get("guestId") or r.get("guest_id") or "", "at": r.get("at") or r.get("created_at") or "", } ) # Also portal data/feedback.json try: portal_fb = Path.cwd() / "data" / "feedback.json" root_fb = Path(__file__).resolve().parents[4] / "data" / "feedback.json" for p in (portal_fb, root_fb): if not p.is_file(): continue raw = json.loads(p.read_text(encoding="utf-8")) rows = raw.get("items") if isinstance(raw, dict) else raw if not isinstance(rows, list): continue for r in rows: if not isinstance(r, dict): continue rid = str(r.get("id") or "") if rid and rid in seen: continue if rid: seen.add(rid) items.append( { "id": r.get("id"), "kind": r.get("kind"), "text": r.get("text"), "contact": r.get("contact") or "", "guestId": r.get("guestId") or "", "at": r.get("at") or "", } ) except Exception: pass items.sort(key=lambda r: str(r.get("at") or ""), reverse=True) total = len(items) return {"ok": True, "total": total, "items": items[off : off + lim]} def admin_delete_feedback(fid: str) -> bool: return soft_delete_record( entity="feedback", entity_id=fid, live_collection=C_FEEDBACK, ) def _page_rows(rows: list[dict[str, Any]], *, limit: int, offset: int) -> dict[str, Any]: lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) total = len(rows) return {"ok": True, "total": total, "items": rows[off : off + lim]} def admin_list_skills(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_SKILLS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "author": r.get("author") or "", "city": r.get("city") or "", "offer": r.get("offer") or "", "want": r.get("want") or "", "note": r.get("note") or "", "status": r.get("status") or "", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("author") or "").lower() or needle in str(x.get("city") or "").lower() or needle in str(x.get("offer") or "").lower() or needle in str(x.get("want") or "").lower() or needle in str(x.get("guestId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_liveness(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_LIVENESS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() def _abs(u: str) -> str: s = (u or "").strip() if not s: return "" if s.startswith(("http://", "https://", "data:")): return s if s.startswith("/api/social/"): return f"https://api.nomadro.com{s}" if s.startswith("/"): return f"https://nomadro.com{s}" return s items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "status": r.get("status") or "", "similarity": r.get("similarity"), "yawDelta": r.get("yaw_delta"), "frontUrl": _abs(str(r.get("front_url") or "")), "turnUrl": _abs(str(r.get("turn_url") or "")), "videoUrl": _abs(str(r.get("video_url") or "")), "avatarUrl": _abs(str(r.get("avatar_url") or "")), "videoSize": r.get("video_size") or 0, "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("guestId") or "").lower() or needle in str(x.get("status") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_meetup_reviews( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_REVIEWS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "bookingId": r.get("booking_id") or "", "fromGuest": r.get("from_guest") or "", "toGuest": r.get("to_guest") or "", "toName": r.get("to_name") or "", "punctuality": r.get("punctuality"), "chemistry": r.get("chemistry"), "professionalism": r.get("professionalism"), "text": r.get("text") or "", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("toName") or "").lower() or needle in str(x.get("text") or "").lower() or needle in str(x.get("fromGuest") or "").lower() or needle in str(x.get("toGuest") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_reports(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_REPORTS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "targetGuest": r.get("target_guest") or "", "targetName": r.get("target_name") or "", "reason": r.get("reason") or "", "detail": r.get("detail") or "", "status": r.get("status") or "", "resultNote": r.get("result_note") or "", "at": r.get("created_at") or "", "resolvedAt": r.get("resolved_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("reason") or "").lower() or needle in str(x.get("targetName") or "").lower() or needle in str(x.get("status") or "").lower() or needle in str(x.get("guestId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_blocks(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_BLOCKS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "blockedGuest": r.get("blocked_guest") or "", "reason": r.get("reason") or "", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("guestId") or "").lower() or needle in str(x.get("blockedGuest") or "").lower() or needle in str(x.get("reason") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_trips(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() try: rows = get_pb().list_all("social_trips", sort="-updated_at", hard_limit=5000) except Exception: rows = [] needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "cityId": r.get("city_id") or "", "city": r.get("city") or "", "country": r.get("country") or "", "lat": r.get("lat"), "lng": r.get("lng"), "arrivalDate": r.get("arrival_date") or "", "departureDate": r.get("departure_date") or "", "visibility": r.get("visibility") or "", "status": r.get("status") or "", "updatedAt": r.get("updated_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("city") or "").lower() or needle in str(x.get("country") or "").lower() or needle in str(x.get("guestId") or "").lower() or needle in str(x.get("status") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def _file_public_url(r: dict[str, Any]) -> str: path = str(r.get("path") or "") file_id = str(r.get("file_id") or r.get("id") or "") if path.startswith("http://") or path.startswith("https://"): return path if path.startswith("/api/"): return path # 状态埋点占位 path(pending:// / uploading:// …)不是可播地址 if "://" in path: return "" if path.startswith("/var/") or path.startswith("/www/"): return f"/api/social/v1/files/{file_id}" if file_id else "" return f"/api/social/v1/files/{file_id}" if file_id else "" _ROOM_ARCHIVE_STATUSES = { "pending", "recording", "uploading", "uploaded", "failed", "denied", } def _room_archive_status_from_row(r: dict[str, Any]) -> str: path = str(r.get("path") or "") low = path.lower() for st in ("pending", "recording", "uploading", "failed", "denied"): if low.startswith(f"{st}://"): return st if path.startswith("http://") or path.startswith("https://") or path.startswith("/api/"): return "uploaded" if path.startswith("/var/") or path.startswith("/www/"): return "uploaded" if (r.get("size") or 0) and path: return "uploaded" return "pending" def _room_archive_meta_path( status: str, session_id: str, *, room_id: str = "", error: str = "", path: str = "", duration_sec: int = 0, started_at: str = "", ) -> str: st = (status or "pending").strip().lower() if st == "uploaded" and path and ( path.startswith("http://") or path.startswith("https://") or path.startswith("/api/") or path.startswith("/var/") or path.startswith("/www/") ): return path q = [] if room_id: q.append(f"room={room_id[:80]}") if error: q.append(f"err={error[:120]}") if duration_sec and int(duration_sec) > 0: q.append(f"dur={int(duration_sec)}") if started_at: q.append(f"t0={started_at[:40]}") tail = ("?" + "&".join(q)) if q else "" return f"{st}://room-archive/{session_id}{tail}" def _parse_meta_qs(path: str) -> dict[str, str]: if "://" not in path or "?" not in path: # uploaded S3 URL may embed nothing; try name later return {} try: from urllib.parse import parse_qs, urlparse return {k: (v[0] if v else "") for k, v in parse_qs(urlparse(path).query).items()} except Exception: return {} def _fmt_duration(sec: int) -> str: s = max(0, int(sec or 0)) if s < 60: return f"{s}秒" m, r = divmod(s, 60) if m < 60: return f"{m}分{r}秒" if r else f"{m}分钟" h, m = divmod(m, 60) return f"{h}小时{m}分" def _duration_from_row(r: dict[str, Any]) -> int: path = str(r.get("path") or "") qs = _parse_meta_qs(path) if qs.get("dur"): try: return max(0, int(qs["dur"])) except Exception: pass name = str(r.get("name") or "") # room-xxx__45s.webm import re m = re.search(r"__(\d+)s(?:\.|$)", name) if m: try: return max(0, int(m.group(1))) except Exception: pass # live recording: estimate from t0 or created_at t0 = qs.get("t0") or str(r.get("created_at") or "") st = _room_archive_status_from_row(r) if st in {"recording", "uploading", "pending"} and t0: try: from datetime import datetime, timezone raw = t0.replace("Z", "+00:00") if raw.isdigit(): start = datetime.fromtimestamp(int(raw) / (1000 if len(raw) > 10 else 1), tz=timezone.utc) else: start = datetime.fromisoformat(raw) now = datetime.now(timezone.utc) if start.tzinfo is None: start = start.replace(tzinfo=timezone.utc) return max(0, int((now - start).total_seconds())) except Exception: pass return 0 def _room_id_from_row(r: dict[str, Any]) -> str: qs = _parse_meta_qs(str(r.get("path") or "")) if qs.get("room"): return qs["room"][:120] name = str(r.get("name") or "") if name.startswith("room-") and ".webm" in name: core = name[5:].split(".webm")[0] core = core.split("__")[0] return core[:120] return "" def _is_room_archive_row(r: dict[str, Any]) -> bool: name = str(r.get("name") or "").lower() path = str(r.get("path") or "").lower() kind = str(r.get("kind") or "").lower() if kind in {"room-archive", "room-archive-session"}: return True if name.startswith("room-") or "room-archive" in name: return True if "room-archive" in path or "/room-archive/" in path: return True if kind == "video" and ("room-" in name or "meetup" in name): return True return False def upsert_room_archive_event( *, session_id: str, channel_id: str, guest_id: str, room_id: str = "", status: str = "pending", name: str = "", mime: str = "video/webm", size: int = 0, path: str = "", error: str = "", seq: int = 0, duration_sec: int = 0, started_at: str = "", ) -> dict[str, Any]: """进厅埋点 → 后台立刻可见;状态:pending/recording/uploading/uploaded/failed/denied。""" init_pb() now = _now() sid = (session_id or "").strip()[:80] or _uid("arc") st = (status or "pending").strip().lower() if st not in _ROOM_ARCHIVE_STATUSES: st = "pending" gid = (guest_id or "")[:120] ch = (channel_id or "meetup-live")[:80] room = (room_id or "")[:120] dur = max(0, int(duration_sec or 0)) t0 = (started_at or "").strip()[:40] fname = (name or "").strip()[:160] or f"room-{room or ch}-{sid}.webm" if dur > 0 and "__" not in fname and fname.endswith(".webm"): fname = fname[:-5] + f"__{dur}s.webm" existing = get_pb().first(C_FILES, filter=f"file_id={pb_quote(sid)}") prev_qs = _parse_meta_qs(str((existing or {}).get("path") or "")) if not t0: t0 = prev_qs.get("t0") or "" if not dur: try: dur = max(0, int(prev_qs.get("dur") or 0)) except Exception: dur = 0 if not t0 and st in {"pending", "recording"}: t0 = now final_path = _room_archive_meta_path( st, sid, room_id=room, error=error, path=path, duration_sec=dur, started_at=t0, ) snap = { "sessionId": sid, "channelId": ch, "guestId": gid, "roomId": room, "status": st, "name": fname, "size": int(size or 0), "path": final_path, "error": (error or "")[:240], "seq": int(seq or 0), "durationSec": dur, "startedAt": t0, "at": now, } try: archive_snapshot( entity="room_archives", entity_id=sid, action=st, payload=snap, guest_id=gid, note=f"room-archive:{st}", ) except Exception: pass body: dict[str, Any] = { "file_id": sid, "channel_id": ch, "guest_id": gid or str((existing or {}).get("guest_id") or ""), "kind": "room-archive", "name": fname or str((existing or {}).get("name") or ""), "mime": (mime or "video/webm")[:120], "size": int(size or 0) or int((existing or {}).get("size") or 0), "path": final_path, } if not existing: body["created_at"] = now else: body["created_at"] = str((existing or {}).get("created_at") or now) prev_st = _room_archive_status_from_row(existing or {}) prev_path = str((existing or {}).get("path") or "") if prev_st == "uploaded" and st != "uploaded": body["path"] = prev_path body["name"] = str((existing or {}).get("name") or body["name"]) st = "uploaded" final_path = prev_path if st == "uploaded" and not ( final_path.startswith("http") or final_path.startswith("/api/") or final_path.startswith("/var") or final_path.startswith("/www") ): body["path"] = prev_path or final_path # 已上传真文件时把时长烙进文件名,方便列表展示 if st == "uploaded" and dur > 0: nm = str(body.get("name") or "") if nm.endswith(".webm") and "__" not in nm: body["name"] = nm[:-5] + f"__{dur}s.webm" get_pb().upsert(C_FILES, filter=f"file_id={pb_quote(sid)}", payload=body) play = "" if st == "uploaded": play = _file_public_url({**body, "file_id": sid}) if "://" in play and not play.startswith("http") and not play.startswith("/api/"): play = "" return { "ok": True, "sessionId": sid, "status": st, "channelId": ch, "guestId": gid, "roomId": room, "name": body.get("name") or fname, "size": body["size"], "durationSec": dur, "durationLabel": _fmt_duration(dur) if dur else "", "startedAt": t0, "url": play, "videoUrl": play, "at": body.get("created_at") or now, } def admin_list_files(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "fileId": r.get("file_id") or r.get("id") or "", "channelId": r.get("channel_id") or "", "guestId": r.get("guest_id") or "", "kind": r.get("kind") or "", "name": r.get("name") or "", "mime": r.get("mime") or "", "size": r.get("size") or 0, "path": r.get("path") or "", "url": _file_public_url(r), "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("name") or "").lower() or needle in str(x.get("kind") or "").lower() or needle in str(x.get("guestId") or "").lower() or needle in str(x.get("channelId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_room_archives( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """语音厅静默录像:含待上传/上传中/已上传全状态。""" init_pb() rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=5000) rows = [r for r in rows if _is_room_archive_row(r)] gone = _soft_deleted_ids("files") | _soft_deleted_ids("room_archives") needle = (q or "").strip().lower() items = [] for r in rows: fid = str(r.get("file_id") or r.get("id") or "") rid = str(r.get("id") or "") if fid in gone or rid in gone: continue gid = str(r.get("guest_id") or "") # 开发冒烟假数据不进运营列表 if gid.startswith( ("guest_debug", "guest_funnel", "guest_cdp", "guest_browserlike") ) or fid.startswith(("arc_smoke_", "arc_cdp_", "arc_live_")): continue st = _room_archive_status_from_row(r) dur = _duration_from_row(r) # 空壳「上传中」超过 2 分钟视为失败(离厅未真正传完) if st == "uploading" and int(r.get("size") or 0) <= 0: try: from datetime import datetime, timezone raw = str(r.get("created_at") or "").replace("Z", "+00:00") start = datetime.fromisoformat(raw) if start.tzinfo is None: start = start.replace(tzinfo=timezone.utc) age = (datetime.now(timezone.utc) - start).total_seconds() if age > 120: st = "failed" except Exception: pass play = "" if st == "uploaded": play = _file_public_url(r) if play.startswith("pending://") or ( "://" in play and not play.startswith("http") and not play.startswith("/api/") ): play = "" items.append( { "id": r.get("id"), "fileId": r.get("file_id") or r.get("id") or "", "sessionId": r.get("file_id") or r.get("id") or "", "channelId": r.get("channel_id") or "", "guestId": r.get("guest_id") or "", "roomId": _room_id_from_row(r), "kind": "room-archive", "status": st, "statusLabel": { "pending": "待上传", "recording": "录制中", "uploading": "上传中", "uploaded": "已上传", "failed": "失败", "denied": "未开摄像头", }.get(st, st), "name": r.get("name") or "", "mime": r.get("mime") or "video/webm", "size": r.get("size") or 0, "durationSec": dur, "durationLabel": _fmt_duration(dur) if dur else "", "path": r.get("path") or "", "url": play, "videoUrl": play, "at": r.get("created_at") or "", } ) if needle: items = [ x for x in items if needle in str(x.get("name") or "").lower() or needle in str(x.get("guestId") or "").lower() or needle in str(x.get("channelId") or "").lower() or needle in str(x.get("status") or "").lower() or needle in str(x.get("statusLabel") or "").lower() or needle in str(x.get("url") or "").lower() or needle in str(x.get("roomId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_coffee_bookings( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Coffeechat bookings — PB coffee_bookings.""" init_pb() try: rows = get_pb().list_all("coffee_bookings", sort="-created_at", hard_limit=5000) except Exception: rows = [] needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "uid": r.get("uid") or "", "hostId": r.get("host_id") or "", "eventTypeId": r.get("event_type_id") or "", "title": r.get("title") or "", "status": r.get("status") or "", "startUtc": r.get("start_utc") or "", "endUtc": r.get("end_utc") or "", "location": r.get("location") or "", "notes": r.get("notes") or "", "attendeeName": r.get("attendee_name") or "", "attendeeEmail": r.get("attendee_email") or "", "attendeeTimezone": r.get("attendee_timezone") or "", "at": r.get("created_at") or "", "cancelledAt": r.get("cancelled_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("title") or "").lower() or needle in str(x.get("attendeeName") or "").lower() or needle in str(x.get("attendeeEmail") or "").lower() or needle in str(x.get("status") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_stats() -> dict[str, Any]: """Dashboard aggregates for admin visualization.""" init_pb() pb = get_pb() counts = admin_overview().get("counts") or {} soft = { "roster": len(_soft_deleted_ids("roster")), "messages": len(_soft_deleted_ids("messages")), "reviews": len(_soft_deleted_ids("reviews")), "gigApps": len(_soft_deleted_ids("gigApps")), "feedback": len(_soft_deleted_ids("feedback")), "skills": len(_soft_deleted_ids("skills")), } # city breakdown from live roster (exclude soft-deleted) gone = _soft_deleted_ids("roster") roster = [ r for r in pb.list_all(C_ROSTER, hard_limit=5000) if str(r.get("guest_id") or "") not in gone and (r.get("status") or "") != "deleted" ] by_city: dict[str, int] = {} by_day: dict[str, int] = {} for r in roster: city = (r.get("city") or "未填").strip() or "未填" by_city[city] = by_city.get(city, 0) + 1 day = str(r.get("updated_at") or r.get("onboarded_at") or "")[:10] if day: by_day[day] = by_day.get(day, 0) + 1 city_top = sorted(by_city.items(), key=lambda x: -x[1])[:12] day_series = sorted(by_day.items())[-30:] return { "ok": True, "counts": counts, "softDeleted": soft, "activeRoster": len(roster), "byCity": [{"name": k, "value": v} for k, v in city_top], "rosterByDay": [{"date": d, "value": n} for d, n in day_series], } def _join_lead_public(r: dict[str, Any]) -> dict[str, Any]: return _sanitize_join_lead_item( { "id": r.get("id"), "email": r.get("email") or "", "guestId": r.get("guest_id") or "", "stage": r.get("stage") or "", "name": r.get("name") or "", "paid": r.get("paid") or "", "faceOk": r.get("face_ok") or "", "livenessStatus": r.get("liveness_status") or "", "ua": r.get("ua") or "", "payload": r.get("payload") or {}, "createdAt": r.get("created_at") or "", "updatedAt": r.get("updated_at") or "", } ) def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: """Human join funnel detail: lead + stage timeline + roster media + liveness clips.""" init_pb() pb = get_pb() key = (lead_id or "").strip() if not key: return None rec = None try: rec = pb.request( "GET", f"/api/collections/{C_JOIN_LEADS}/records/{key}", admin=True ) except Exception: rec = None if not rec: email_n = key.lower() rec = pb.first(C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}") if not rec: # Archive-only fallback: latest snapshot for this email / id arch = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote('join_leads')} && entity_id={pb_quote(key.lower())}", sort="-created_at", hard_limit=1, ) if not arch: return None a0 = arch[0] payload = a0.get("payload") if isinstance(a0.get("payload"), dict) else {} item = _sanitize_join_lead_item( { "id": a0.get("id") or key, "email": payload.get("email") or a0.get("entity_id") or key, "guestId": payload.get("guestId") or a0.get("guest_id") or "", "stage": payload.get("stage") or a0.get("action") or "", "name": payload.get("name") or "", "paid": payload.get("paid") or "", "faceOk": payload.get("faceOk") or "", "livenessStatus": payload.get("livenessStatus") or "", "ua": payload.get("ua") or "", "payload": payload.get("payload") if isinstance(payload.get("payload"), dict) else payload, "createdAt": a0.get("created_at") or "", "updatedAt": a0.get("created_at") or "", } ) else: item = _join_lead_public(rec) email = str(item.get("email") or "").strip().lower() gid = str(item.get("guestId") or "").strip() hist_rows = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote('join_leads')} && entity_id={pb_quote(email)}", sort="-created_at", hard_limit=100, ) history = [ { "id": h.get("id"), "action": h.get("action"), "at": h.get("created_at"), "note": h.get("note") or "", "payload": h.get("payload") or {}, } for h in hist_rows ] own_face_stages = { "profile_done", "liveness_verified", "liveness_failed", "liveness_skipped", "join_done", } hist_actions = {str(h.get("action") or "") for h in history} hist_actions.add(str(item.get("stage") or "")) # 只有本线索历史里真的做过核验,才允许挂自拍/视频;join_done 可能是「稍后再说」 own_liveness = "liveness_verified" in hist_actions own_profile = bool(hist_actions & {"profile_done", "join_done"}) # 花名册:优先按 email;guest 串号且 email 对不上 → 丢弃,禁止显示别人头像/自拍 roster: dict[str, Any] | None = None if email: try: rec_by_email = pb.first(C_ROSTER, filter=f"email={pb_quote(email)}") if rec_by_email: roster = _roster_from_rec(rec_by_email, public=False) except Exception: roster = None if roster is None and gid: cand = get_roster(gid) if cand: remail = str(cand.get("email") or "").strip().lower() if remail and remail == email: roster = cand elif not remail and own_liveness: roster = cand else: roster = None audits: list[dict[str, Any]] = [] try: for a in list_liveness_audits(limit=80): meta = a.get("meta") if isinstance(a.get("meta"), dict) else {} a_email = str(a.get("email") or meta.get("email") or "").strip().lower() a_gid = str(a.get("guestId") or "") if email and a_email and a_email == email: audits.append(a) elif own_liveness and gid and a_gid == gid and (not a_email or a_email == email): audits.append(a) if len(audits) >= 8: break except Exception: audits = [] # 本线索从未核验:清空串来的 audit;roster 无本邮箱绑定也不挂媒体 stage_now = str(item.get("stage") or "") if not own_liveness and stage_now not in own_face_stages: audits = [] if roster and str(roster.get("email") or "").strip().lower() not in {"", email}: roster = None if roster and not own_liveness and stage_now in {"email_submit", "pay_launched"}: # 只填邮箱阶段:绝不展示任何媒体 roster = None audits = [] def _abs_media(url: str) -> str: u = (url or "").strip() if not u: return "" if u.startswith("https://") or u.startswith("http://") or u.startswith("data:"): return u if u.startswith("/api/social/"): return f"https://api.nomadro.com{u}" if u.startswith("/"): return f"https://nomadro.com{u}" return u def _pick_url(*vals: Any) -> str: for v in vals: if isinstance(v, str) and v.strip(): return _abs_media(v.strip()) return "" # 只从「本邮箱」真正走过的资料/核验阶段收割媒体;email_submit 脏 payload 一律忽略 _MEDIA_STAGES = frozenset( {"profile_done", "liveness_verified", "join_done"} ) harvested: dict[str, str] = { "avatar": "", "livenessFrontUrl": "", "livenessTurnUrl": "", "livenessVideoUrl": "", } if own_profile or own_liveness: harvest_blobs: list[dict[str, Any]] = [] if str(item.get("stage") or "") in _MEDIA_STAGES: lead_payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} if lead_payload: harvest_blobs.append(lead_payload) for h in history: if str(h.get("action") or "") not in _MEDIA_STAGES: continue blob = h.get("payload") if isinstance(blob, dict): harvest_blobs.append(blob) for blob in harvest_blobs: nested = blob.get("payload") if isinstance(blob.get("payload"), dict) else {} sources = (blob, nested) if not harvested["avatar"]: harvested["avatar"] = _pick_url( *(s.get("avatarUrl") or s.get("avatar") for s in sources) ) if own_liveness and not harvested["livenessFrontUrl"]: harvested["livenessFrontUrl"] = _pick_url( *(s.get("frontUrl") or s.get("livenessFrontUrl") for s in sources) ) if own_liveness and not harvested["livenessTurnUrl"]: harvested["livenessTurnUrl"] = _pick_url( *(s.get("turnUrl") or s.get("livenessTurnUrl") for s in sources) ) if own_liveness and not harvested["livenessVideoUrl"]: harvested["livenessVideoUrl"] = _pick_url( *(s.get("videoUrl") or s.get("livenessVideoUrl") for s in sources) ) if own_liveness and audits: a0 = audits[0] if not harvested["livenessFrontUrl"]: harvested["livenessFrontUrl"] = _abs_media(str(a0.get("frontUrl") or "")) if not harvested["livenessTurnUrl"]: harvested["livenessTurnUrl"] = _abs_media(str(a0.get("turnUrl") or "")) if not harvested["livenessVideoUrl"]: harvested["livenessVideoUrl"] = _abs_media(str(a0.get("videoUrl") or "")) roster_email_ok = bool( roster and email and str(roster.get("email") or "").strip().lower() == email ) # 只填邮箱 / 未填资料:媒体与 roster 全部清空,禁止串 Eric 等别人的脸 early_only = stage_now in {"email_submit", "pay_launched"} or ( not own_profile and not own_liveness ) if early_only: roster = None audits = [] media = { "avatar": "", "livenessFrontUrl": "", "livenessTurnUrl": "", "livenessVideoUrl": "", "audits": [], } else: # 无本邮箱绑定的 roster:共用 guest 上的头像/自拍一律不信 if not roster_email_ok: avatar_url = "" live_front = "" live_turn = "" live_video = "" audits = [] else: avatar_url = harvested["avatar"] if own_profile else "" if not avatar_url and own_profile: avatar_url = _abs_media(str(roster.get("avatar") or "")) live_front = harvested["livenessFrontUrl"] if own_liveness else "" live_turn = harvested["livenessTurnUrl"] if own_liveness else "" live_video = harvested["livenessVideoUrl"] if own_liveness else "" if own_liveness: live_front = live_front or _abs_media(str(roster.get("livenessFrontUrl") or "")) live_turn = live_turn or _abs_media(str(roster.get("livenessTurnUrl") or "")) live_video = live_video or _abs_media(str(roster.get("livenessVideoUrl") or "")) media = { "avatar": avatar_url, "livenessFrontUrl": live_front, "livenessTurnUrl": live_turn, "livenessVideoUrl": live_video, "audits": [ { **a, "frontUrl": _abs_media(str(a.get("frontUrl") or "")), "turnUrl": _abs_media(str(a.get("turnUrl") or "")), "videoUrl": _abs_media(str(a.get("videoUrl") or "")), } for a in (audits if own_liveness and roster_email_ok else []) ], } # 时间线里早期阶段的脏 URL 也剥掉,避免详情页 timeline 再画出别人的脸 _MEDIA_KEYS = ( "avatar", "avatarUrl", "frontUrl", "turnUrl", "videoUrl", "livenessFrontUrl", "livenessTurnUrl", "livenessVideoUrl", ) def _strip_media_payload(payload: Any, *, keep: bool) -> Any: if not isinstance(payload, dict): return payload out = dict(payload) if not keep: for k in _MEDIA_KEYS: out.pop(k, None) nested = out.get("payload") if isinstance(nested, dict): nest = dict(nested) for k in _MEDIA_KEYS: nest.pop(k, None) out["payload"] = nest return out clean_history = [] for h in history: act = str(h.get("action") or "") keep = act in _MEDIA_STAGES and (own_profile or own_liveness) if act in {"liveness_verified"} and not own_liveness: keep = False clean_history.append({**h, "payload": _strip_media_payload(h.get("payload"), keep=keep)}) clean_item = dict(item) if early_only: clean_item["payload"] = _strip_media_payload(clean_item.get("payload"), keep=False) clean_item["faceOk"] = "" clean_item["livenessStatus"] = "none" return { "ok": True, "entity": "joinLeads", "id": str(item.get("id") or email or key), "item": {**clean_item, "media": media, "roster": roster or {}}, "softDeleted": False, "history": clean_history, "media": media, "roster": roster or {}, } def admin_get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: if entity == "joinLeads": return admin_get_join_lead(entity_id) init_pb() pb = get_pb() coll = ENTITY_COLLECTIONS.get(entity) if not coll: return None rec = None if entity == "roster": raw = pb.first(coll, filter=f"guest_id={pb_quote(entity_id)}") rec = _roster_from_rec(raw, public=False) if raw else None else: try: rec = pb.request( "GET", f"/api/collections/{coll}/records/{entity_id}", admin=True ) except Exception: rec = None if not rec: return None # files / 语音厅录像:补可播 URL(S3 直链优先) if entity == "files" and isinstance(rec, dict): pub = _file_public_url(rec) if pub: rec = { **rec, "url": pub, "videoUrl": pub if str(rec.get("mime") or "").startswith("video") or str(rec.get("name") or "").lower().endswith((".webm", ".mp4", ".mov")) or _is_room_archive_row(rec) else rec.get("videoUrl") or "", } hist = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote(entity)} && entity_id={pb_quote(entity_id)}", sort="-created_at", hard_limit=50, ) return { "ok": True, "entity": entity, "id": entity_id, "item": rec, "softDeleted": entity_id in _soft_deleted_ids(entity) or (rec.get("status") == "deleted"), "history": [ { "id": h.get("id"), "action": h.get("action"), "at": h.get("created_at"), "note": h.get("note") or "", "payload": h.get("payload") or {}, } for h in hist ], } def admin_list_archives( *, entity: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Default list excludes join_leads (those live under 加入线索 detail timeline).""" init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) entity_n = (entity or "").strip() filt = f"entity={pb_quote(entity_n)}" if entity_n else None rows = get_pb().list_all( C_ARCHIVES, filter=filt, sort="-created_at", hard_limit=5000 ) if not entity_n: rows = [r for r in rows if str(r.get("entity") or "") != "join_leads"] total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "entity": r.get("entity"), "entityId": r.get("entity_id"), "guestId": r.get("guest_id") or "", "action": r.get("action"), "note": r.get("note") or "", "at": r.get("created_at"), "payload": r.get("payload") or {}, } for r in page ], }