nomadro/apps/api/services/hub_svc/routers/api.py
Eric d971a1f3e6 Lock Hub to China-only cities and document the cn audience gate.
Hard-enable hubCnOnly, drop foreign cities from default seeds/map/coffeechat, and keep intl cities in separate INT L catalogs until globalization reopens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-29 00:03:11 +08:00

1638 lines
50 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""游民社区 API — 前缀 /api/hub/v1,与 /api/v1 社群隔离。"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from fastapi import APIRouter, File, Form, Header, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from starlette.concurrency import run_in_threadpool
from hub_svc import live, store
from hub_svc.config import HUB_ENABLED, HUB_UPLOAD_MAX_BYTES
from hub_svc.realtime import (
issue_connection_token,
publish_chat_message,
publish_chat_note,
publish_live_event,
)
router = APIRouter(tags=["social"])
def _guest(
x_hub_guest_id: str | None,
guest_q: str | None = None,
) -> str:
gid = (x_hub_guest_id or guest_q or "").strip()
if not gid or len(gid) > 80:
raise HTTPException(status_code=400, detail="missing X-Hub-Guest-Id")
return gid
class ReplyToIn(BaseModel):
id: str = Field(min_length=1, max_length=80)
author: str = Field(default="游民", max_length=48)
text: str = Field(default="", max_length=240)
seq: int | None = Field(default=None, ge=0)
class AttachmentIn(BaseModel):
id: str = Field(default="", max_length=80)
kind: str = Field(default="file", max_length=16)
url: str = Field(min_length=1, max_length=800)
name: str = Field(default="file", max_length=160)
mime: str = Field(default="application/octet-stream", max_length=120)
size: int = Field(default=0, ge=0, le=50 * 1024 * 1024)
class MessageIn(BaseModel):
author: str = Field(default="游民", max_length=48)
text: str = Field(default="", max_length=2000)
clientId: str | None = Field(default=None, min_length=1, max_length=80)
replyTo: ReplyToIn | None = None
attachments: list[AttachmentIn] = Field(default_factory=list)
mentions: list[str] = Field(default_factory=list)
class EditMessageIn(BaseModel):
text: str = Field(min_length=1, max_length=2000)
class ReactIn(BaseModel):
emoji: str = Field(min_length=1, max_length=16)
class PinIn(BaseModel):
pinned: bool = True
class ReportIn(BaseModel):
reason: str = Field(default="", max_length=240)
class PresenceIn(BaseModel):
nick: str = Field(default="游民", max_length=48)
city: str = Field(default="", max_length=64)
avatar: str = Field(default="", max_length=500)
softStatusSync: bool = False
class HubPresenceIn(BaseModel):
"""Global / city who's-online heartbeat (not tied to a chat channel)."""
nick: str = Field(default="游民", max_length=48)
city: str = Field(default="", max_length=64)
avatar: str = Field(default="", max_length=500)
softStatusSync: bool = True
class NoteIn(BaseModel):
"""Tinode {note}: recv / read / kp (typing keepalive)."""
what: str = Field(min_length=2, max_length=8)
seq: int = Field(default=0, ge=0)
class ReviewIn(BaseModel):
author: str = Field(default="游民", max_length=48)
score: int = Field(default=5, ge=1, le=5)
text: str = Field(min_length=1, max_length=2000)
photoNote: str = Field(default="", max_length=200)
class RosterIn(BaseModel):
name: str = Field(default="", max_length=64)
title: str = Field(default="", max_length=80)
city: str = Field(default="", max_length=64)
phone: str = Field(default="", max_length=32)
linktree: str = Field(default="", max_length=240)
skills: str = Field(default="", max_length=200)
bio: str = Field(default="", max_length=2000)
avatar: str = Field(default="", max_length=500)
gender: str = Field(default="", max_length=16)
relationship: str = Field(default="", max_length=32)
education: str = Field(default="", max_length=32)
graduation: str = Field(default="", max_length=32)
wechat: str = Field(default="", max_length=64)
intents: str = Field(default="", max_length=240)
availability: str = Field(default="", max_length=120)
status: str = Field(default="online", max_length=32)
lookingFor: str = Field(default="", max_length=200)
discoverable: bool | int | str = True
updatedAt: str = Field(default="", max_length=40)
class FeedbackIn(BaseModel):
kind: str = Field(default="建议", max_length=8)
text: str = Field(min_length=1, max_length=4000)
contact: str = Field(default="", max_length=120)
images: list[str] = Field(default_factory=list)
meta: dict | None = None
class JoinLeadIn(BaseModel):
email: str = Field(min_length=3, max_length=160)
stage: str = Field(default="email_submit", max_length=48)
name: str = Field(default="", max_length=64)
paid: str = Field(default="", max_length=8)
faceOk: str = Field(default="", max_length=8)
livenessStatus: str = Field(default="", max_length=24)
payload: dict | None = None
ua: str = Field(default="", max_length=240)
class GigAppIn(BaseModel):
name: str = Field(min_length=1, max_length=64)
contact: str = Field(min_length=1, max_length=120)
note: str = Field(default="", max_length=2000)
resumeUrl: str = Field(default="", max_length=800)
resumeName: str = Field(default="", max_length=200)
requestId: str | None = Field(default=None, min_length=1, max_length=80)
@router.get("/health")
async def hub_health():
if not HUB_ENABLED:
return {"ok": False, "module": "hub", "enabled": False}
h = store.health()
from hub_svc.config import CENTRIFUGO_ENABLED
from hub_svc.contract import IM_FEATURES, IM_PROTOCOL
h["centrifugo"] = bool(CENTRIFUGO_ENABLED)
h["imProtocol"] = IM_PROTOCOL
h["imFeatures"] = list(IM_FEATURES)
h["uiAgnostic"] = True
return h
@router.get("/features")
async def hub_features_catalog():
"""门户/后台可读的 Hub 超级能力目录(离线客户端也可硬编码兜底)。"""
return {
"ok": True,
"module": "hub",
"features": [
{"id": "commandPalette", "title": "⌘K 快速跳转", "surface": "shell"},
{"id": "shortcutsHelp", "title": "快捷键说明", "surface": "shell"},
{"id": "offlineBanner", "title": "离线提示条", "surface": "shell"},
{"id": "announceDismiss", "title": "公告可关闭", "surface": "shell"},
{"id": "todayActions", "title": "今日行动清单", "surface": "home"},
{"id": "intentQuiz", "title": "三秒意图选择", "surface": "home"},
{"id": "livePulse", "title": "在线心跳条", "surface": "home"},
{"id": "newJoiners", "title": "刚刚在线", "surface": "home"},
{"id": "tonightBookmark", "title": "语音厅收藏", "surface": "home"},
{"id": "jumpRail", "title": "快捷芯片", "surface": "home"},
{"id": "momentum", "title": "社区温度", "surface": "home"},
{"id": "featuredCity", "title": "本周城市", "surface": "home"},
{"id": "recentRail", "title": "最近去过", "surface": "home"},
{"id": "welcomeBack", "title": "回访连续天数", "surface": "home"},
{"id": "tagCloud", "title": "热门标签云", "surface": "home"},
{"id": "shareInvite", "title": "复制邀请链接", "surface": "home"},
{"id": "digest", "title": "本周摘要偏好", "surface": "home"},
{"id": "focusMode", "title": "专注模式", "surface": "home"},
{"id": "pulseSound", "title": "在线提示音", "surface": "home"},
{"id": "muteSections", "title": "本机隐藏模块", "surface": "home"},
{"id": "belowWays", "title": "连接方式以下模块总开关", "surface": "home"},
{"id": "waysLiveBadge", "title": "入口卡实时角标", "surface": "home"},
{"id": "wayDestChrome", "title": "五入口落地页共用顶栏", "surface": "ways"},
{"id": "meetupNextCard", "title": "语音厅下一场置顶", "surface": "meetup"},
{"id": "meetupSoonFilter", "title": "语音厅即将筛选", "surface": "meetup"},
{"id": "createHubRail", "title": "共创页招聘/技能跳转", "surface": "ebook"},
{"id": "placesWayChrome", "title": "城市页入口导航", "surface": "places"},
{"id": "dateWayChrome", "title": "约会页入口导航", "surface": "date"},
{"id": "chatWayChrome", "title": "聊天页入口导航", "surface": "chat"},
{"id": "navFlags", "title": "远程导航开关", "surface": "shell"},
{"id": "hubLive", "title": "hubLive 实时开关", "surface": "flags"},
{"id": "hubCnOnly", "title": "中文受众锁(屏蔽多语言/全球化 UI)", "surface": "flags"},
],
}
@router.get("/ways-meta")
async def hub_ways_meta():
"""首页五入口角标摘要;门户以本地 catalog 为主,此接口作在线增强。"""
meetups: list = []
gigs: list = []
try:
from hub_svc import store as hub_store
if hasattr(hub_store, "list_meetups"):
meetups = list(hub_store.list_meetups() or [])
if hasattr(hub_store, "list_gigs"):
gigs = list(hub_store.list_gigs() or [])
except Exception:
meetups, gigs = [], []
next_meetup = meetups[0] if meetups else None
return {
"ok": True,
"meetupCount": len(meetups),
"gigCount": len(gigs),
"nextMeetup": next_meetup,
"offlineFallback": not bool(meetups or gigs),
}
@router.get("/realtime/token")
async def realtime_token(
channel_id: str = Query(default="lobby"),
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
return issue_connection_token(peer, channel_id)
@router.get("/channels/{channel_id}/desc")
def get_channel_desc(
channel_id: str,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Tinode-like topic desc: seq + recv/read/unread for current peer."""
peer = None
try:
peer = _guest(x_hub_guest_id, guest)
except HTTPException:
peer = None
return store.channel_desc(channel_id, peer)
@router.get("/channels/{channel_id}/messages")
def get_messages(
channel_id: str,
limit: int = 100,
since: int | None = Query(default=None, ge=0),
before: int | None = Query(default=None, ge=0),
q: str | None = Query(default=None, max_length=80),
):
store.init_db()
items = store.list_messages(
channel_id, limit, since=since, before=before, q=q
)
return {"items": items, "seq": store.channel_seq(channel_id)}
async def _publish_msg(channel_id: str, saved: dict[str, Any]) -> None:
try:
await publish_chat_message(channel_id, saved)
except Exception:
pass
@router.post("/channels/{channel_id}/messages")
async def post_message(
channel_id: str,
body: MessageIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
if not body.text.strip() and not body.attachments:
raise HTTPException(status_code=400, detail="empty message")
def persist():
store.init_db()
return store.add_message(
channel_id,
body.author,
body.text,
peer,
body.clientId,
reply_to=body.replyTo.model_dump() if body.replyTo else None,
attachments=[a.model_dump() for a in body.attachments],
mentions=body.mentions,
)
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
detail = str(exc)
if "过快" in detail:
code = 429
elif "trial exhausted" in detail:
code = 402
elif "empty" in detail:
code = 400
else:
code = 409
raise HTTPException(status_code=code, detail=detail) from exc
await _publish_msg(channel_id, saved)
return saved
@router.patch("/channels/{channel_id}/messages/{msg_id}")
async def patch_message(
channel_id: str,
msg_id: str,
body: EditMessageIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
def persist():
store.init_db()
return store.edit_message(channel_id, msg_id, peer, body.text)
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
detail = str(exc)
code = 403 if "not your" in detail else 404 if "not found" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
await _publish_msg(channel_id, saved)
return saved
@router.post("/channels/{channel_id}/messages/{msg_id}/recall")
async def recall_message(
channel_id: str,
msg_id: str,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
def persist():
store.init_db()
return store.recall_message(channel_id, msg_id, peer)
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
detail = str(exc)
code = 403 if "not your" in detail else 404 if "not found" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
await _publish_msg(channel_id, saved)
return saved
@router.post("/channels/{channel_id}/messages/{msg_id}/react")
async def react_message(
channel_id: str,
msg_id: str,
body: ReactIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
def persist():
store.init_db()
return store.react_message(channel_id, msg_id, peer, body.emoji)
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
detail = str(exc)
code = 404 if "not found" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
await _publish_msg(channel_id, saved)
return saved
@router.post("/channels/{channel_id}/messages/{msg_id}/pin")
async def pin_message(
channel_id: str,
msg_id: str,
body: PinIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
def persist():
store.init_db()
return store.pin_message(channel_id, msg_id, peer, body.pinned)
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
detail = str(exc)
code = 404 if "not found" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
await _publish_msg(channel_id, saved)
return saved
@router.post("/channels/{channel_id}/messages/{msg_id}/report")
async def report_message(
channel_id: str,
msg_id: str,
body: ReportIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
def persist():
store.init_db()
return store.report_message(channel_id, msg_id, peer, body.reason)
try:
return await run_in_threadpool(persist)
except ValueError as exc:
detail = str(exc)
code = 404 if "not found" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
@router.post("/channels/{channel_id}/presence")
async def post_presence(
channel_id: str,
body: PresenceIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
return store.touch_presence(
channel_id,
peer,
body.nick,
city=body.city,
avatar=body.avatar,
soft_status_sync=bool(body.softStatusSync),
)
@router.post("/roster/presence")
async def post_roster_presence(
body: HubPresenceIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Global social presence heartbeat — powers「谁在线」strip + city count."""
peer = _guest(x_hub_guest_id, guest)
return store.touch_presence(
store.HUB_GLOBAL_ROOM,
peer,
body.nick,
city=body.city,
avatar=body.avatar,
soft_status_sync=bool(body.softStatusSync),
)
@router.get("/roster/online")
def get_roster_online(
city: str = Query(default=""),
limit: int = Query(default=48, ge=1, le=64),
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Who's online now (TTL presence). Offline clients get empty + UI fallback."""
_ = _guest(x_hub_guest_id, guest)
return store.list_social_online(city=(city or "").strip(), limit=limit)
@router.post("/upload")
async def upload_media(
file: UploadFile = File(...),
purpose: str = Form(default="avatar"),
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Guest-friendly upload → SeaweedFS S3 (fallback local).
- purpose=avatar|roster|profile: image + optional face gate
- purpose=resume|cv|gig-resume: PDF/DOC/DOCX/图片简历,跳过人脸检测
"""
peer = _guest(x_hub_guest_id, guest)
purpose_norm = (purpose or "avatar")[:40]
is_resume = purpose_norm.lower() in {"resume", "cv", "gig-resume"}
ctype = (file.content_type or "").lower()
raw = await file.read()
if not raw:
raise HTTPException(status_code=400, detail="空文件")
if is_resume:
name = (file.filename or "resume.pdf").strip() or "resume.pdf"
suffix = ("." + name.rsplit(".", 1)[-1].lower()) if "." in name else ""
ok_suffix = {".pdf", ".doc", ".docx", ".txt", ".rtf", ".png", ".jpg", ".jpeg", ".webp"}
if suffix and suffix not in ok_suffix and not ctype.startswith("image/"):
raise HTTPException(
status_code=400,
detail="简历仅支持 PDF / Word / 图片",
)
max_bytes = min(HUB_UPLOAD_MAX_BYTES, 10 * 1024 * 1024)
def persist_resume():
from hub_svc.s3_upload import upload_bytes
return upload_bytes(
raw,
filename=name,
content_type=file.content_type or "application/octet-stream",
purpose="resume",
guest_id=peer,
max_size=max_bytes,
)
try:
result = await run_in_threadpool(persist_resume)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail=f"上传失败: {exc}") from exc
return {
"ok": True,
"success": True,
"url": result.url,
"object_key": result.object_key,
"size": result.size,
"content_type": result.content_type,
"storage": result.storage,
"name": name[:200],
"faceOk": False,
"faceCheckEnabled": False,
"livenessRequired": False,
}
if not ctype.startswith("image/"):
raise HTTPException(status_code=400, detail="仅支持图片")
max_avatar = min(HUB_UPLOAD_MAX_BYTES, 8 * 1024 * 1024)
def persist():
from hub_svc.face_check import (
assert_avatar_has_face,
check_face,
face_check_enabled,
)
from hub_svc.s3_upload import upload_bytes
gate_on = face_check_enabled(purpose_norm)
# Always soft-detect so dating can hide no-face avatars.
# Gate on → hard reject; gate off → still upload but face_ok=false.
if gate_on:
face_meta = assert_avatar_has_face(raw, require_liveness=False)
else:
face_meta = check_face(raw, require_liveness=False)
uploaded = upload_bytes(
raw,
filename=file.filename or "avatar.jpg",
content_type=file.content_type or "image/jpeg",
purpose=purpose_norm,
guest_id=peer,
max_size=max_avatar,
)
has_face = bool(face_meta and face_meta.ok)
# Only avatar/roster/profile photos belong on the face roster.
if purpose_norm in {"avatar", "roster", "profile"}:
try:
store.mark_face_photo(peer, uploaded.url, face_ok=has_face)
except Exception as roster_exc: # pragma: no cover
import logging
logging.getLogger("hub_svc.upload").warning(
"mark_face_photo failed for %s: %s", peer, roster_exc
)
return uploaded, face_meta, gate_on, has_face
try:
result, face_meta, face_gate_on, has_face = await run_in_threadpool(persist)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail=f"上传失败: {exc}") from exc
payload = {
"ok": True,
"success": True,
"url": result.url,
"object_key": result.object_key,
"size": result.size,
"content_type": result.content_type,
"storage": result.storage,
# Dating feed uses this — only true when detector saw a face.
"faceOk": has_face,
"faceCheckEnabled": face_gate_on,
"livenessRequired": True,
}
if face_meta is not None:
face_payload = {
"ok": face_meta.ok,
"faces": face_meta.faces,
"engine": face_meta.engine,
"require_liveness": True,
}
if face_meta.is_live is not None:
face_payload["is_live"] = face_meta.is_live
if face_meta.live_score is not None:
face_payload["live_score"] = face_meta.live_score
payload["face"] = face_payload
return payload
@router.post("/avatar/challenge")
async def avatar_pose_challenge(
front: UploadFile = File(...),
turn: UploadFile = File(...),
video: UploadFile | None = File(default=None),
email: str | None = Form(default=None),
x_hub_guest_id: str | None = Header(default=None),
x_social_email: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Live selfie: front + turn frames + optional full camera recording for audit."""
peer = _guest(x_hub_guest_id, guest)
email_n = (email or x_social_email or "").strip().lower()[:160]
front_raw = await front.read()
turn_raw = await turn.read()
video_raw = await video.read() if video is not None else b""
if not front_raw or not turn_raw:
raise HTTPException(status_code=400, detail="空文件")
max_avatar = min(HUB_UPLOAD_MAX_BYTES, 8 * 1024 * 1024)
max_video = min(HUB_UPLOAD_MAX_BYTES, 40 * 1024 * 1024)
if len(front_raw) > max_avatar or len(turn_raw) > max_avatar:
raise HTTPException(status_code=400, detail="图片过大")
if video_raw and len(video_raw) > max_video:
raise HTTPException(status_code=400, detail="录制视频过大")
def work():
from hub_svc.face_check import verify_pose_challenge
from hub_svc.s3_upload import upload_bytes
challenge = verify_pose_challenge(front_raw, turn_raw)
if not challenge.ok:
raise ValueError(challenge.detail or "真人核验失败")
# Live frames are audit-only — never purpose=avatar
front_up = upload_bytes(
front_raw,
filename=front.filename or "liveness-front.jpg",
content_type=front.content_type or "image/jpeg",
purpose="liveness-front",
guest_id=peer,
max_size=max_avatar,
)
turn_up = upload_bytes(
turn_raw,
filename=turn.filename or "liveness-turn.jpg",
content_type=turn.content_type or "image/jpeg",
purpose="liveness-turn",
guest_id=peer,
max_size=max_avatar,
)
video_url = ""
video_size = 0
if video_raw:
vname = (video.filename if video else None) or "liveness.webm"
vctype = (video.content_type if video else None) or "video/webm"
video_up = upload_bytes(
video_raw,
filename=vname,
content_type=vctype,
purpose="liveness-video",
guest_id=peer,
max_size=max_video,
)
video_url = video_up.url
video_size = video_up.size
audit = store.save_liveness_audit(
peer,
front_url=front_up.url,
turn_url=turn_up.url,
video_url=video_url,
video_size=video_size,
similarity=challenge.similarity,
yaw_delta=challenge.yaw_delta,
email=email_n,
meta={
"front_engine": challenge.front.engine if challenge.front else "",
"turn_engine": challenge.turn.engine if challenge.turn else "",
"has_video": bool(video_url),
"email": email_n,
},
)
roster = store.get_roster(peer) or {}
return front_up, turn_up, video_url, video_size, challenge, audit, roster
try:
front_up, turn_up, video_url, video_size, challenge, audit, roster = (
await run_in_threadpool(work)
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail=f"核验失败: {exc}") from exc
# Do not return live frame as avatar url — keep existing album/selfie avatar
avatar_url = (roster.get("avatar") or "").strip()
return {
"ok": True,
"success": True,
"url": avatar_url,
"avatarUrl": avatar_url,
"livenessStatus": "verified",
"faceOk": True,
"videoUrl": video_url,
"videoSize": video_size,
"frontUrl": front_up.url,
"turnUrl": turn_up.url,
"auditId": audit.get("id"),
"challenge": {
"similarity": challenge.similarity,
"yaw_delta": challenge.yaw_delta,
"front": {
"faces": challenge.front.faces if challenge.front else 0,
"engine": challenge.front.engine if challenge.front else "",
"is_live": challenge.front.is_live if challenge.front else None,
},
"turn": {
"faces": challenge.turn.faces if challenge.turn else 0,
"engine": challenge.turn.engine if challenge.turn else "",
"is_live": challenge.turn.is_live if challenge.turn else None,
},
},
}
@router.get("/files/avatar/{name}")
def get_local_avatar(name: str):
"""Serve locally-fallback avatar files when S3 is unavailable."""
from hub_svc.config import HUB_UPLOAD_DIR
safe = Path(name).name
if safe != name or ".." in name:
raise HTTPException(status_code=400, detail="非法文件名")
path = HUB_UPLOAD_DIR / "avatars" / safe
if not path.is_file():
raise HTTPException(status_code=404, detail="not found")
return FileResponse(path)
@router.get("/files/liveness/{name}")
def get_local_liveness(name: str):
"""Serve locally-stored liveness audit videos / frames."""
from hub_svc.config import HUB_UPLOAD_DIR
safe = Path(name).name
if safe != name or ".." in name:
raise HTTPException(status_code=400, detail="非法文件名")
path = HUB_UPLOAD_DIR / "liveness" / safe
if not path.is_file():
raise HTTPException(status_code=404, detail="not found")
return FileResponse(path)
@router.get("/files/resume/{name}")
def get_local_resume(name: str):
"""Serve locally-fallback resume attachments when S3 is unavailable."""
from hub_svc.config import HUB_UPLOAD_DIR
safe = Path(name).name
if safe != name or ".." in name:
raise HTTPException(status_code=400, detail="非法文件名")
path = HUB_UPLOAD_DIR / "resumes" / safe
if not path.is_file():
raise HTTPException(status_code=404, detail="not found")
return FileResponse(path)
@router.get("/liveness/audits")
def liveness_audits(
status: str = Query(default=""),
limit: int = Query(default=40, ge=1, le=200),
x_hub_guest_id: str | None = Header(default=None),
):
"""Admin-oriented list of liveness recordings (guest header still required)."""
_guest(x_hub_guest_id)
store.init_db()
return {
"ok": True,
"items": store.list_liveness_audits(status=(status or "").strip(), limit=limit),
}
class RoomArchiveEventIn(BaseModel):
sessionId: str = Field(min_length=4, max_length=80)
channelId: str = Field(default="meetup-live", max_length=80)
roomId: str = Field(default="", max_length=120)
status: str = Field(default="pending", max_length=24)
name: str = Field(default="", max_length=160)
mime: str = Field(default="video/webm", max_length=120)
size: int = Field(default=0, ge=0)
path: str = Field(default="", max_length=800)
error: str = Field(default="", max_length=240)
seq: int = Field(default=0, ge=0)
durationSec: int = Field(default=0, ge=0)
startedAt: str = Field(default="", max_length=40)
nick: str = Field(default="", max_length=64)
email: str = Field(default="", max_length=120)
@router.post("/room-archives/events")
async def room_archive_event(
body: RoomArchiveEventIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""语音厅埋点:进厅即落库,后台立刻出「待上传/上传中/已上传」。"""
peer = _guest(x_hub_guest_id, guest)
def persist():
store.init_db()
return store.upsert_room_archive_event(
session_id=body.sessionId,
channel_id=body.channelId or "meetup-live",
guest_id=peer,
room_id=body.roomId,
status=body.status,
name=body.name,
mime=body.mime,
size=body.size,
path=body.path,
error=body.error,
seq=body.seq,
duration_sec=body.durationSec,
started_at=body.startedAt,
nick=body.nick,
email=body.email,
)
try:
return await run_in_threadpool(persist)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail=f"room archive event failed: {exc}") from exc
@router.post("/channels/{channel_id}/upload")
async def upload_file(
channel_id: str,
file: UploadFile = File(...),
kind: str = Form(default="file"),
session_id: str = Form(default=""),
session_id_q: str | None = Query(default=None, alias="session_id"),
kind_q: str | None = Query(default=None, alias="kind"),
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
raw = await file.read()
if not raw:
raise HTTPException(status_code=400, detail="empty file")
if len(raw) > HUB_UPLOAD_MAX_BYTES:
raise HTTPException(status_code=413, detail="file too large")
mime = file.content_type or "application/octet-stream"
# Form 丢字段时用 query 兜底(本地 Next rewrite → 线上 API 曾丢 session_id)
kind = (kind or kind_q or "file").strip() or "file"
guessed = kind
if guessed in {"room-archive", "meetup-archive"}:
guessed = "video"
if guessed == "file":
if mime.startswith("image/"):
guessed = "image"
elif mime.startswith("video/"):
guessed = "video"
elif mime.startswith("audio/"):
guessed = "audio"
sid = ((session_id or session_id_q or "").strip())[:80]
# 语音/视频厅静默存档 → SeaweedFS S3;元数据 path 写公网 URL
if kind in {"room-archive", "meetup-archive"} or (
guessed == "video" and (file.filename or "").startswith("room-")
):
# 无 session 时:挂到该 guest 最近一条未完成的 room-archive,避免孤儿「已上传」
if not sid:
try:
store.init_db()
sid = store.find_open_room_archive_session(
guest_id=peer, channel_id=channel_id, filename=file.filename or ""
) or ""
except Exception:
sid = ""
if sid:
try:
store.init_db()
store.upsert_room_archive_event(
session_id=sid,
channel_id=channel_id,
guest_id=peer,
status="uploading",
name=file.filename or "room-archive.webm",
mime=mime if mime.startswith("video/") else "video/webm",
size=len(raw),
)
except Exception:
pass
def persist_s3():
from hub_svc.s3_upload import upload_bytes
up = upload_bytes(
raw,
filename=file.filename or f"room-{channel_id}.webm",
content_type=mime if mime.startswith("video/") else "video/webm",
purpose="room-archive",
guest_id=peer,
max_size=HUB_UPLOAD_MAX_BYTES,
)
store.init_db()
file_id = sid or f"file_{int(__import__('time').time() * 1000)}_{peer[:8]}"
return store.upsert_room_archive_event(
session_id=file_id,
channel_id=channel_id,
guest_id=peer,
status="uploaded",
name=file.filename or "room-archive.webm",
mime=up.content_type,
size=up.size,
path=up.url,
) | {
"id": file_id,
"kind": "room-archive",
"mime": up.content_type,
"size": up.size,
"url": up.url,
"storage": up.storage,
"object_key": up.object_key,
}
try:
return await run_in_threadpool(persist_s3)
except ValueError as exc:
if sid:
try:
store.upsert_room_archive_event(
session_id=sid,
channel_id=channel_id,
guest_id=peer,
status="failed",
error=str(exc)[:240],
)
except Exception:
pass
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception:
pass # fall through to local persist
def persist():
store.init_db()
saved = store.save_upload(
channel_id,
peer,
kind=guessed,
name=file.filename or "file",
mime=mime,
data=raw,
)
if sid or kind in {"room-archive", "meetup-archive"} or (
file.filename or ""
).startswith("room-"):
file_id = sid or str(saved.get("id") or "")
if file_id:
return store.upsert_room_archive_event(
session_id=file_id,
channel_id=channel_id,
guest_id=peer,
status="uploaded",
name=file.filename or "room-archive.webm",
mime=mime,
size=len(raw),
path=str(saved.get("url") or saved.get("path") or ""),
) | saved
return saved
try:
return await run_in_threadpool(persist)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.get("/files/{file_id}")
def get_file(file_id: str):
store.init_db()
meta = store.get_file(file_id)
if not meta:
raise HTTPException(status_code=404, detail="file not found")
stored = str(meta.get("path") or "")
if stored.startswith("http://") or stored.startswith("https://"):
from fastapi.responses import RedirectResponse
return RedirectResponse(stored, status_code=302)
path = Path(stored)
if not path.is_file():
raise HTTPException(status_code=404, detail="file missing")
return FileResponse(
path,
media_type=meta["mime"],
filename=meta["name"],
)
@router.post("/channels/{channel_id}/notes")
async def post_note(
channel_id: str,
body: NoteIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Tinode {note}: recv/read persist; kp (typing) is fan-out only."""
peer = _guest(x_hub_guest_id, guest)
what = body.what.strip().lower()
if what == "kp":
try:
await publish_chat_note(channel_id, what="kp", seq=0, guest_id=peer)
except Exception:
pass
return {"ok": True, "what": "kp"}
if what not in {"recv", "read"}:
raise HTTPException(status_code=400, detail="what must be recv|read|kp")
try:
saved = await run_in_threadpool(
lambda: store.set_note(channel_id, peer, what, body.seq)
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
try:
await publish_chat_note(
channel_id, what=what, seq=saved["seq"], guest_id=peer
)
except Exception:
pass
return saved
@router.get("/cafes/{cafe_id}/reviews")
def get_reviews(cafe_id: str, limit: int = 50):
store.init_db()
return {"items": store.list_reviews(cafe_id, limit)}
@router.post("/cafes/{cafe_id}/reviews")
def post_review(
cafe_id: str,
body: ReviewIn,
x_hub_guest_id: str | None = Header(default=None),
):
guest = _guest(x_hub_guest_id)
store.init_db()
return store.add_review(
cafe_id,
body.author,
body.score,
body.text,
body.photoNote,
guest,
)
@router.get("/roster/me")
def get_my_roster(x_hub_guest_id: str | None = Header(default=None)):
guest = _guest(x_hub_guest_id)
store.init_db()
return {"item": store.get_roster(guest)}
@router.get("/roster/discovery")
def roster_discovery(
city: str = Query(default=""),
limit: int = Query(default=48, ge=1, le=100),
require_face: bool = Query(default=True, alias="requireFace"),
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Public discovery feed: same-city → online → tag match (no phone/wechat).
requireFace=1 for 约会/dating — hide profiles whose avatar has no face.
"""
peer = _guest(x_hub_guest_id, guest)
store.init_db()
items = store.list_discovery_roster(
viewer_guest_id=peer,
city=(city or "").strip(),
limit=limit,
exclude_self=True,
require_face=bool(require_face),
)
viewer = store.get_roster(peer)
return {
"ok": True,
"viewerCity": (viewer or {}).get("city") or "",
"items": items,
"count": len(items),
"requireFace": bool(require_face),
}
@router.put("/roster/me")
def put_my_roster(
body: RosterIn,
x_hub_guest_id: str | None = Header(default=None),
):
guest = _guest(x_hub_guest_id)
store.init_db()
row = store.upsert_roster(guest, body.model_dump())
onboarding = None
if row.get("isFirstProfile"):
try:
from hub_svc.onboarding import fire_join_onboarding
recs = store.city_recommendations(guest, limit=3)
onboarding = fire_join_onboarding(
guest_id=guest,
name=str(row.get("name") or ""),
city=str(row.get("city") or ""),
recs=recs,
)
except Exception as exc: # noqa: BLE001 — never block profile save
onboarding = {"ok": False, "error": str(exc)[:160]}
# Same-city online ping (best-effort, capped)
try:
status = str(row.get("status") or "")
city = str(row.get("city") or "").strip()
if city and status in {"online", "here", "available"}:
from hub_svc.notify_bridge import notify_city_online
peers = store.city_recommendations(guest, limit=3)
for p in peers:
pid = str(p.get("guestId") or p.get("id") or "")
if pid and pid != guest:
notify_city_online(pid, city, str(row.get("name") or "游民"))
except Exception:
pass
out = {k: v for k, v in row.items() if k != "isFirstProfile"}
if onboarding is not None:
out["onboarding"] = onboarding
return out
@router.post("/feedback")
def post_feedback(
body: FeedbackIn,
x_hub_guest_id: str | None = Header(default=None),
x_social_email: str | None = Header(default=None),
user_agent: str | None = Header(default=None, alias="User-Agent"),
):
guest = _guest(x_hub_guest_id)
store.init_db()
meta = dict(body.meta) if isinstance(body.meta, dict) else {}
email = (x_social_email or "").strip()[:160]
if email and not meta.get("email"):
meta["email"] = email
if user_agent and "serverUserAgent" not in meta:
meta["serverUserAgent"] = (user_agent or "")[:400]
try:
return store.add_feedback(
body.kind,
body.text,
body.contact,
guest,
images=list(body.images or []),
meta=meta,
)
except ValueError as exc:
detail = str(exc)
code = 429 if "最多" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
@router.post("/join/leads")
def post_join_lead(
request: Request,
body: JoinLeadIn,
x_hub_guest_id: str | None = Header(default=None),
user_agent: str | None = Header(default=None, alias="User-Agent"),
x_forwarded_for: str | None = Header(default=None, alias="X-Forwarded-For"),
):
"""Test-phase: archive email+click (and later funnel stages) for admin."""
guest = _guest(x_hub_guest_id)
store.init_db()
client_ip = ""
if x_forwarded_for:
client_ip = x_forwarded_for.split(",")[0].strip()
elif request.client:
client_ip = request.client.host or ""
try:
return store.upsert_join_lead(
email=body.email,
guest_id=guest,
stage=body.stage or "email_submit",
name=body.name,
payload=body.payload if isinstance(body.payload, dict) else {},
ua=(body.ua or user_agent or "")[:240],
paid=body.paid,
face_ok=body.faceOk,
liveness_status=body.livenessStatus,
client_ip=client_ip,
)
except ValueError as exc:
detail = str(exc)
code = 403 if "封禁" in detail else 400
raise HTTPException(status_code=code, detail=detail) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail=f"存档失败: {exc}") from exc
@router.post("/gigs/{gig_id}/apply")
def post_gig_apply(
gig_id: str,
body: GigAppIn,
x_hub_guest_id: str | None = Header(default=None),
):
guest = _guest(x_hub_guest_id)
if not body.name.strip() or not body.contact.strip():
raise HTTPException(status_code=400, detail="请填写称呼和联系方式")
store.init_db()
try:
return store.add_gig_app(
gig_id,
body.name,
body.contact,
body.note,
guest,
body.requestId,
resume_url=body.resumeUrl,
resume_name=body.resumeName,
)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
class LiveJoinIn(BaseModel):
nick: str = Field(default="游民", max_length=32)
@router.post("/live/rooms/{room_id}/join")
async def live_join(
room_id: str,
body: LiveJoinIn,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None, alias="guest"),
):
"""微信原生 LivePusher/LivePlayer 进厅:下发 RTMP 推流 + FLV 拉流。"""
peer = _guest(x_hub_guest_id, guest)
try:
payload = live.join_room(room_id, peer, body.nick)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
try:
await publish_live_event(
payload["channelId"],
"peer_join",
{
"roomId": payload["roomId"],
"peer": {
"peerId": payload["peerId"],
"nick": payload["nick"],
"playUrl": payload["playUrl"],
"stream": payload["stream"],
},
},
)
except Exception:
pass
# 附带实时通道 token,前端可订 live 频道
payload["realtime"] = issue_connection_token(peer, payload["channelId"])
# Best-effort: tell other peers a room went live
try:
from hub_svc.notify_bridge import notify_room_live
for other in live.list_peers(payload.get("roomId") or room_id):
oid = str(other.get("peerId") or other.get("guestId") or "")
if oid and oid != peer:
notify_room_live(oid, f"视频厅 {payload.get('roomId') or room_id}")
except Exception:
pass
return payload
@router.post("/live/rooms/{room_id}/heartbeat")
async def live_heartbeat(
room_id: str,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
try:
return live.heartbeat(room_id, peer)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.get("/live/rooms/{room_id}/peers")
async def live_peers(room_id: str):
return {"ok": True, "roomId": room_id, "peers": live.list_peers(room_id)}
@router.post("/live/rooms/{room_id}/leave")
async def live_leave(
room_id: str,
x_hub_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
peer = _guest(x_hub_guest_id, guest)
out = live.leave_room(room_id, peer)
try:
await publish_live_event(
f"live-{out['roomId']}",
"peer_leave",
{"roomId": out["roomId"], "peerId": peer},
)
except Exception:
pass
return out
# —— Skill swap · reviews · moderation · wrapped · digests ——
class SkillPostIn(BaseModel):
author: str = Field(default="游民", max_length=64)
city: str = Field(default="", max_length=64)
offer: str = Field(min_length=1, max_length=200)
want: str = Field(min_length=1, max_length=200)
note: str = Field(default="", max_length=800)
class MeetupReviewIn(BaseModel):
toGuest: str = Field(min_length=1, max_length=80)
toName: str = Field(default="", max_length=64)
bookingId: str = Field(default="", max_length=80)
punctuality: int = Field(ge=1, le=5)
chemistry: int = Field(ge=1, le=5)
professionalism: int = Field(ge=1, le=5)
text: str = Field(default="", max_length=800)
class BlockIn(BaseModel):
blockedGuest: str = Field(min_length=1, max_length=80)
reason: str = Field(default="", max_length=200)
class ReportIn(BaseModel):
targetGuest: str = Field(min_length=1, max_length=80)
targetName: str = Field(default="", max_length=64)
reason: str = Field(min_length=1, max_length=80)
detail: str = Field(default="", max_length=1000)
class ReportResolveIn(BaseModel):
status: str = Field(default="resolved", max_length=20)
resultNote: str = Field(default="", max_length=500)
class HubLikeIn(BaseModel):
toGuest: str = Field(min_length=1, max_length=80)
fromName: str = Field(default="游民", max_length=64)
class DigestIn(BaseModel):
city: str = Field(default="", max_length=64)
weekly: bool = False
@router.get("/skills")
def list_skills(
city: str = Query(default=""),
limit: int = Query(default=60, ge=1, le=120),
):
from hub_svc import community_board as board
store.init_db()
return {"ok": True, "items": board.list_skill_posts(city=city, limit=limit)}
@router.post("/skills")
def create_skill(
body: SkillPostIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
try:
item = board.create_skill_post(
guest,
author=body.author,
city=body.city,
offer=body.offer,
want=body.want,
note=body.note,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return item
@router.post("/skills/{post_id}/close")
def close_skill(
post_id: str,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
try:
return board.close_skill_post(guest, post_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.post("/meetup-reviews")
@router.post("/reviews")
def post_meetup_review(
body: MeetupReviewIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
try:
return board.create_meetup_review(
guest,
to_guest=body.toGuest,
to_name=body.toName,
booking_id=body.bookingId,
punctuality=body.punctuality,
chemistry=body.chemistry,
professionalism=body.professionalism,
text=body.text,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.get("/meetup-reviews/{guest_id}")
@router.get("/reviews/{guest_id}")
def get_meetup_reviews(
guest_id: str, limit: int = Query(default=40, ge=1, le=100)
):
from hub_svc import community_board as board
store.init_db()
return {"ok": True, **board.reviews_for_guest(guest_id, limit=limit)}
@router.post("/blocks")
def post_block(
body: BlockIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
try:
return board.block_user(guest, body.blockedGuest, body.reason)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.delete("/blocks/{blocked_guest}")
def delete_block(
blocked_guest: str,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
return board.unblock_user(guest, blocked_guest)
@router.get("/blocks")
def get_blocks(x_hub_guest_id: str | None = Header(default=None)):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
return {"ok": True, "items": board.list_blocks(guest)}
@router.post("/reports")
def post_report(
body: ReportIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
try:
return board.create_report(
guest,
target_guest=body.targetGuest,
target_name=body.targetName,
reason=body.reason,
detail=body.detail,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.post("/reports/{report_id}/resolve")
def resolve_report(
report_id: str,
body: ReportResolveIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
from hub_svc.notify_bridge import notify_report_result
_guest(x_hub_guest_id)
store.init_db()
try:
item = board.resolve_report(
report_id, status=body.status, result_note=body.resultNote
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
try:
notify_report_result(
item["guestId"],
body.resultNote or f"举报已处理:{body.status}",
body.status,
)
except Exception:
pass
return item
@router.get("/reports")
def get_reports(
status: str = Query(default="open"),
limit: int = Query(default=40, ge=1, le=100),
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
_guest(x_hub_guest_id)
store.init_db()
return {"ok": True, "items": board.list_reports(status=status, limit=limit)}
@router.post("/social-events/like")
def hub_like_event(
body: HubLikeIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc.notify_bridge import notify_like
_guest(x_hub_guest_id)
try:
notify_like(body.toGuest, body.fromName)
except Exception as exc:
raise HTTPException(status_code=503, detail=str(exc)[:160]) from exc
return {"ok": True}
class BoardJoinEventIn(BaseModel):
ownerGuest: str = Field(min_length=1, max_length=80)
actorName: str = Field(default="游民", max_length=64)
boardTitle: str = Field(default="看板", max_length=120)
@router.post("/social-events/board-join")
def hub_board_join_event(
body: BoardJoinEventIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc.notify_bridge import notify_board_join
_guest(x_hub_guest_id)
try:
notify_board_join(body.ownerGuest, body.actorName, body.boardTitle)
except Exception as exc:
raise HTTPException(status_code=503, detail=str(exc)[:160]) from exc
return {"ok": True}
@router.get("/wrapped")
def get_wrapped(
year: int | None = Query(default=None),
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
guest = _guest(x_hub_guest_id)
store.init_db()
return {"ok": True, **board.wrapped_stats(guest, year=year)}
@router.post("/digests/city")
def post_city_digest(
body: DigestIn,
x_hub_guest_id: str | None = Header(default=None),
):
from hub_svc import community_board as board
from hub_svc.notify_bridge import fire_city_digest
guest = _guest(x_hub_guest_id)
store.init_db()
payload = board.city_digest_payload(body.city)
fire_city_digest(
guest,
payload["city"],
payload["digestText"],
weekly=body.weekly,
)
return {"ok": True, **payload}