"""微信后台 · 游民社区 UGC 增删查改""" from __future__ import annotations from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query from pydantic import BaseModel, Field from ebook_svc.core.security import require_admin from ebook_svc.services import social_ugc as ugc router = APIRouter(prefix="/api/admin/social/ugc", tags=["social-ugc-admin"]) class RosterPatch(BaseModel): name: str | None = None title: str | None = None city: str | None = None phone: str | None = None linktree: str | None = None skills: str | None = None bio: str | None = None restore: bool | None = None status: str | None = None @router.get("/overview") async def get_overview(_: str = Depends(require_admin)) -> dict[str, Any]: return ugc.overview() @router.get("/presence") async def get_presence( city: str = "", limit: int = Query(48, ge=1, le=64), _: str = Depends(require_admin), ) -> dict[str, Any]: """Live who's-online for admin pulse. Production: portal heartbeats land in ``nomadro-social`` (:8020). This process (``nomadmini-api``) must NOT read in-process ``_PRESENCE`` — that map is empty. Prefer HTTP to social; fall back to in-process store for unified local API. """ import json import os import urllib.error import urllib.parse import urllib.request qs = urllib.parse.urlencode( {"limit": str(limit), **({"city": city.strip()} if (city or "").strip() else {})} ) bases = [] for raw in ( os.environ.get("SOCIAL_INTERNAL_URL"), os.environ.get("SOCIAL_API_URL"), "http://127.0.0.1:8020", "http://127.0.0.1:8080", ): b = (raw or "").strip().rstrip("/") if b and b not in bases: bases.append(b) last_err: Exception | None = None for base in bases: url = f"{base}/api/social/v1/roster/online?{qs}" try: req = urllib.request.Request( url, headers={"X-Social-Guest-Id": "admin-presence", "Accept": "application/json"}, method="GET", ) with urllib.request.urlopen(req, timeout=4) as res: data = json.loads(res.read().decode("utf-8", "replace") or "{}") if isinstance(data, dict) and (data.get("ok") is not False): return { "ok": True, "online": int(data.get("online") or 0), "peers": data.get("peers") if isinstance(data.get("peers"), list) else [], "cityOnline": int(data.get("cityOnline") or 0), "cityPeers": data.get("cityPeers") if isinstance(data.get("cityPeers"), list) else [], "source": base, } except Exception as e: # noqa: BLE001 — try next upstream last_err = e continue try: from social_svc import store as social_store data = social_store.list_social_online(city=(city or "").strip(), limit=limit) return {**data, "ok": True, "source": "inprocess"} except Exception as e: raise HTTPException( 503, f"presence unavailable: {last_err or e}" ) from e @router.get("/stats") async def get_stats(_: str = Depends(require_admin)) -> dict[str, Any]: """Dashboard visualization payload (counts, city bars, day series, soft-delete).""" try: return ugc.stats() except Exception as e: raise HTTPException(503, f"social stats unavailable: {e}") from e @router.get("/archives") async def get_archives( entity: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_archives(entity=entity, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"archives unavailable: {e}") from e @router.get("/messages") async def get_messages( channelId: str = "", q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_messages(channel_id=channelId, q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"social db unavailable: {e}") from e @router.delete("/messages/{message_id}") async def del_message(message_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_message(message_id): raise HTTPException(404, "消息不存在") return {"ok": True, "soft": True, "archived": True} @router.get("/roster") async def get_roster( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_roster(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"social db unavailable: {e}") from e @router.put("/roster/{guest_id}") async def put_roster( guest_id: str, body: RosterPatch, _: str = Depends(require_admin) ) -> dict[str, Any]: item = ugc.update_roster(guest_id, body.model_dump(exclude_none=True)) if not item: raise HTTPException(404, "介绍不存在") return {"ok": True, "item": item} @router.delete("/roster/{guest_id}") async def del_roster(guest_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_roster(guest_id): raise HTTPException(404, "介绍不存在") return {"ok": True, "soft": True, "archived": True} @router.get("/reviews") async def get_reviews( cafeId: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_reviews(cafe_id=cafeId, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"social db unavailable: {e}") from e @router.delete("/reviews/{review_id}") async def del_review(review_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_review(review_id): raise HTTPException(404, "评价不存在") return {"ok": True, "soft": True, "archived": True} @router.get("/gig-apps") async def get_gig_apps( gigId: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_gig_apps(gig_id=gigId, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"social db unavailable: {e}") from e @router.delete("/gig-apps/{app_id}") async def del_gig_app(app_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_gig_app(app_id): raise HTTPException(404, "申请不存在") return {"ok": True, "soft": True, "archived": True} @router.get("/feedback") async def get_feedback( limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), userKey: str = Query(""), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_feedback( limit=limit, offset=offset, user_key=userKey ) except Exception as e: raise HTTPException(503, f"social db unavailable: {e}") from e @router.get("/join-leads") async def get_join_leads( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: """Test-phase join funnel: email click → pay → profile → liveness archives.""" try: return ugc.list_join_leads(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"join leads unavailable: {e}") from e @router.post("/join-leads/dedupe") async def post_join_leads_dedupe( dryRun: bool = False, _: str = Depends(require_admin), ) -> dict[str, Any]: """Hard-delete duplicate social_join_leads (keep newest per email).""" try: return ugc.dedupe_join_leads(dry_run=dryRun) except Exception as e: raise HTTPException(503, f"join leads dedupe unavailable: {e}") from e @router.get("/skills") async def get_skills( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_skills(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"skills unavailable: {e}") from e @router.get("/liveness") async def get_liveness( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_liveness(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"liveness unavailable: {e}") from e @router.get("/meetup-reviews") async def get_meetup_reviews( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_meetup_reviews(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"meetup reviews unavailable: {e}") from e @router.get("/reports") async def get_reports( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_reports(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"reports unavailable: {e}") from e @router.get("/blocks") async def get_blocks( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_blocks(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"blocks unavailable: {e}") from e @router.get("/trips") async def get_trips( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_trips(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"trips unavailable: {e}") from e @router.get("/files") async def get_files( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_files(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"files unavailable: {e}") from e @router.get("/room-archives") async def get_room_archives( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: """语音厅静默录像列表(S3 / 本地兜底)。""" try: return ugc.list_room_archives(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"room archives unavailable: {e}") from e @router.get("/coffee-bookings") async def get_coffee_bookings( q: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), _: str = Depends(require_admin), ) -> dict[str, Any]: try: return ugc.list_coffee_bookings(q=q, limit=limit, offset=offset) except Exception as e: raise HTTPException(503, f"coffee bookings unavailable: {e}") from e @router.delete("/feedback/{fid}") async def del_feedback(fid: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_feedback(fid): raise HTTPException(404, "反馈不存在") return {"ok": True, "soft": True, "archived": True} class CatalogBody(BaseModel): meetups: list[dict[str, Any]] | None = None gigs: list[dict[str, Any]] | None = None cafes: list[dict[str, Any]] | None = None roster: list[dict[str, Any]] | None = None ebooks: list[dict[str, Any]] | None = None videos: list[dict[str, Any]] | None = None class ExperienceBody(BaseModel): expectedVersion: int | None = Field(default=None, ge=0) experience: dict[str, Any] = Field(default_factory=dict) @router.get("/experience") async def get_experience(_: str = Depends(require_admin)) -> dict[str, Any]: from ebook_svc.services import social_experience as experience return experience.read_experience() @router.put("/experience") async def put_experience( body: ExperienceBody, _: str = Depends(require_admin) ) -> dict[str, Any]: from ebook_svc.services import social_experience as experience return experience.write_experience(body.expectedVersion, body.experience) @router.get("/catalog") async def get_catalog(_: str = Depends(require_admin)) -> dict[str, Any]: from ebook_svc.services.social_ops import _read_raw raw = _read_raw() copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {} catalogs = copy.get("socialCatalogs") if isinstance(copy.get("socialCatalogs"), dict) else {} return { "ok": True, "version": raw.get("version"), "catalogs": { "meetups": catalogs.get("meetups") if isinstance(catalogs.get("meetups"), list) else [], "gigs": catalogs.get("gigs") if isinstance(catalogs.get("gigs"), list) else [], "cafes": catalogs.get("cafes") if isinstance(catalogs.get("cafes"), list) else [], "roster": catalogs.get("roster") if isinstance(catalogs.get("roster"), list) else [], "ebooks": catalogs.get("ebooks") if isinstance(catalogs.get("ebooks"), list) else [], "videos": catalogs.get("videos") if isinstance(catalogs.get("videos"), list) else [], }, } @router.put("/catalog") async def put_catalog(body: CatalogBody, _: str = Depends(require_admin)) -> dict[str, Any]: """深合并 socialCatalogs 数组键;不碰其它配置。""" from ebook_svc.services.social_ops import _read_raw, _write_raw raw = _read_raw() out = dict(raw) if raw else {"version": 1, "modules": {}, "copy": {}} copy = dict(out.get("copy") or {}) catalogs = dict(copy.get("socialCatalogs") or {}) if isinstance(copy.get("socialCatalogs"), dict) else {} patch = body.model_dump(exclude_none=True) for key, val in patch.items(): if isinstance(val, list): catalogs[key] = val copy["socialCatalogs"] = catalogs out["copy"] = copy _write_raw(out) return { "ok": True, "version": out.get("version"), "catalogs": { "meetups": catalogs.get("meetups") if isinstance(catalogs.get("meetups"), list) else [], "gigs": catalogs.get("gigs") if isinstance(catalogs.get("gigs"), list) else [], "cafes": catalogs.get("cafes") if isinstance(catalogs.get("cafes"), list) else [], "roster": catalogs.get("roster") if isinstance(catalogs.get("roster"), list) else [], "ebooks": catalogs.get("ebooks") if isinstance(catalogs.get("ebooks"), list) else [], "videos": catalogs.get("videos") if isinstance(catalogs.get("videos"), list) else [], }, } @router.get("/detail/{entity}/{entity_id}") async def get_entity_detail( entity: str, entity_id: str, _: str = Depends(require_admin) ) -> dict[str, Any]: """Detail page: live record + archive history. Soft-delete never erases payload.""" allowed = { "roster", "messages", "reviews", "gigApps", "feedback", "joinLeads", "skills", "liveness", "meetupReviews", "reports", "blocks", "trips", "files", "coffeeBookings", } if entity not in allowed: raise HTTPException(404, "unknown entity") item = ugc.get_detail(entity, entity_id) if not item: raise HTTPException(404, "记录不存在(或仅存于存档,请查 /archives)") return item