Document test9 tag 2026-11-02 for upload; POST config pull + WS, fixed dark home, no debug bar. Co-authored-by: Cursor <cursoragent@cursor.com>
180 lines
5.7 KiB
Python
180 lines
5.7 KiB
Python
"""门户社区运营 — meetups / discussions / gigs(JSON 兜底;有 community_svc 则走其 store)。"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import time
|
||
import uuid
|
||
from copy import deepcopy
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException
|
||
from pydantic import BaseModel, Field
|
||
|
||
from ebook_svc.core.security import require_admin
|
||
|
||
router = APIRouter(prefix="/api/admin/community", tags=["community-admin"])
|
||
|
||
_DEFAULT_PATH = Path(
|
||
os.getenv(
|
||
"COMMUNITY_STORE_PATH",
|
||
"/var/www/nomadro-data/community/community_store.json",
|
||
)
|
||
)
|
||
|
||
|
||
def _seed() -> dict[str, Any]:
|
||
try:
|
||
from community_svc.data import community_data as cd # type: ignore
|
||
|
||
return {
|
||
"seeded": True,
|
||
"seed_version": 4,
|
||
"meetups": deepcopy(getattr(cd, "MEETUPS", []) or []),
|
||
"discussions": deepcopy(getattr(cd, "DISCUSSIONS", []) or []),
|
||
"gigs": deepcopy(getattr(cd, "GIGS", []) or []),
|
||
"meetup_rsvps": [],
|
||
"gig_applications": [],
|
||
"discussion_replies": [],
|
||
}
|
||
except Exception:
|
||
return {
|
||
"seeded": True,
|
||
"seed_version": 1,
|
||
"meetups": [],
|
||
"discussions": [],
|
||
"gigs": [],
|
||
"meetup_rsvps": [],
|
||
"gig_applications": [],
|
||
"discussion_replies": [],
|
||
}
|
||
|
||
|
||
def _path() -> Path:
|
||
return Path(os.getenv("COMMUNITY_STORE_PATH", str(_DEFAULT_PATH))).resolve()
|
||
|
||
|
||
def _load() -> dict[str, Any]:
|
||
path = _path()
|
||
if path.is_file():
|
||
try:
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
if isinstance(data, dict):
|
||
return data
|
||
except Exception:
|
||
pass
|
||
# try community_svc live store
|
||
try:
|
||
from community_svc.services import community_store as cs # type: ignore
|
||
|
||
return {
|
||
"ok": True,
|
||
"source": "community_svc",
|
||
"meetups": cs.list_meetups(upcoming=False),
|
||
"discussions": cs.list_discussions(),
|
||
"gigs": cs.list_gigs(),
|
||
"stats": cs.stats_overview(),
|
||
}
|
||
except Exception:
|
||
pass
|
||
return _seed()
|
||
|
||
|
||
def _save(data: dict[str, Any]) -> None:
|
||
path = _path()
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
data["updatedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||
|
||
|
||
@router.get("/overview")
|
||
async def overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||
data = _load()
|
||
if data.get("source") == "community_svc":
|
||
return {
|
||
"ok": True,
|
||
"source": "community_svc",
|
||
"path": str(_path()),
|
||
"stats": data.get("stats")
|
||
or {
|
||
"meetups": len(data.get("meetups") or []),
|
||
"discussions": len(data.get("discussions") or []),
|
||
"gigs": len(data.get("gigs") or []),
|
||
},
|
||
}
|
||
return {
|
||
"ok": True,
|
||
"source": "json",
|
||
"path": str(_path()),
|
||
"exists": _path().is_file(),
|
||
"stats": {
|
||
"meetups": len(data.get("meetups") or []),
|
||
"discussions": len(data.get("discussions") or []),
|
||
"gigs": len(data.get("gigs") or []),
|
||
"rsvps": len(data.get("meetup_rsvps") or []),
|
||
"gigApps": len(data.get("gig_applications") or []),
|
||
},
|
||
}
|
||
|
||
|
||
def _list_key(key: str) -> list[dict[str, Any]]:
|
||
data = _load()
|
||
items = data.get(key)
|
||
return items if isinstance(items, list) else []
|
||
|
||
|
||
@router.get("/{collection}")
|
||
async def list_collection(collection: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||
if collection not in {"meetups", "discussions", "gigs", "meetup_rsvps", "gig_applications"}:
|
||
raise HTTPException(404, "unknown collection")
|
||
items = _list_key(collection)
|
||
return {"ok": True, "items": items, "total": len(items)}
|
||
|
||
|
||
class ItemBody(BaseModel):
|
||
item: dict[str, Any] = Field(default_factory=dict)
|
||
|
||
|
||
@router.post("/{collection}")
|
||
async def upsert_item(
|
||
collection: str, body: ItemBody, _: str = Depends(require_admin)
|
||
) -> dict[str, Any]:
|
||
if collection not in {"meetups", "discussions", "gigs"}:
|
||
raise HTTPException(400, "仅支持 meetups/discussions/gigs 写入")
|
||
data = _load()
|
||
if data.get("source") == "community_svc":
|
||
raise HTTPException(501, "community_svc 在线写入请改用门户 API;本后台仅管 JSON 兜底库")
|
||
items = list(data.get(collection) or [])
|
||
item = dict(body.item or {})
|
||
iid = str(item.get("id") or "").strip() or f"{collection[:3]}_{uuid.uuid4().hex[:10]}"
|
||
item["id"] = iid
|
||
found = False
|
||
for i, old in enumerate(items):
|
||
if isinstance(old, dict) and str(old.get("id")) == iid:
|
||
items[i] = {**old, **item}
|
||
found = True
|
||
break
|
||
if not found:
|
||
items.insert(0, item)
|
||
data[collection] = items
|
||
_save(data)
|
||
return {"ok": True, "item": item}
|
||
|
||
|
||
@router.delete("/{collection}/{item_id}")
|
||
async def delete_item(
|
||
collection: str, item_id: str, _: str = Depends(require_admin)
|
||
) -> dict[str, Any]:
|
||
if collection not in {"meetups", "discussions", "gigs", "meetup_rsvps", "gig_applications"}:
|
||
raise HTTPException(404, "unknown collection")
|
||
data = _load()
|
||
if data.get("source") == "community_svc":
|
||
raise HTTPException(501, "community_svc 在线删除请改用门户 API")
|
||
items = [x for x in (data.get(collection) or []) if not (isinstance(x, dict) and str(x.get("id")) == item_id)]
|
||
if len(items) == len(data.get(collection) or []):
|
||
raise HTTPException(404, "不存在")
|
||
data[collection] = items
|
||
_save(data)
|
||
return {"ok": True}
|