nomadro/apps/api/services/ebook_svc/routers/memo.py
Eric 3f7528f824 Add VIP knowledge community and device shop with native weapp UX.
Document memo/shop admin routes, deploy scripts, and cache-first feed performance in README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 16:58:17 +08:00

315 lines
9.9 KiB
Python

"""VIP 知识社群公开 API — 知识星球风格阅读 + 互动。"""
from __future__ import annotations
import mimetypes
import uuid
from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from ebook_svc.config import settings
from ebook_svc.core.deps import get_current_openid
from ebook_svc.services.memo_store import memo_store
from ebook_svc.services.store import store
from ebook_svc.services.vip_config import read_vip_config
router = APIRouter(prefix="/memo", tags=["memo"])
VIP_BOOK_ID = "__vip__"
UPLOAD_DIR = Path(settings.sqlite_path).resolve().parent / "uploads" / "memo"
def _require_vip(openid: str) -> None:
cfg = read_vip_config()
s = memo_store.get_settings()
if not s.get("requireVip"):
return
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
return
if not store.is_unlocked(openid, VIP_BOOK_ID):
raise HTTPException(403, "开通 VIP 后可进入知识社群")
def _nick(openid: str) -> str:
u = store.get_user(openid)
if u and (u.get("nickname") or "").strip():
return str(u["nickname"]).strip()[:32]
return f"会员{openid[-4:]}" if openid else "会员"
def _gate_enabled() -> dict[str, Any]:
s = memo_store.get_settings()
if not s.get("enabled"):
raise HTTPException(403, "社群暂未开放")
return s
@router.get("/settings")
async def public_settings(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
s = memo_store.get_settings()
return {
"ok": True,
"enabled": bool(s.get("enabled")),
"canPost": bool(s.get("canPost")) and not bool(s.get("adminOnlyPost")),
"canComment": bool(s.get("canComment")),
"canLike": bool(s.get("canLike")),
"canFavorite": bool(s.get("canFavorite", True)),
"canUpload": bool(s.get("canUpload", True)),
"adminOnlyPost": bool(s.get("adminOnlyPost")),
"planetName": s.get("planetName") or "知识社群",
"planetDesc": s.get("planetDesc") or "",
"notice": s.get("notice") or "",
"maxContentLen": int(s.get("maxContentLen") or 20000),
"maxImages": int(s.get("maxImages") or 9),
}
@router.get("/tags")
async def tags(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
_gate_enabled()
return {"ok": True, "items": memo_store.list_tags()}
@router.get("/feed")
async def feed(
openid: str = Depends(get_current_openid),
limit: int = Query(30, ge=1, le=100),
offset: int = Query(0, ge=0),
q: str = "",
tag: str = "",
tab: str = "all",
) -> dict[str, Any]:
_require_vip(openid)
_gate_enabled()
tab_n = (tab or "all").strip().lower()
if tab_n not in {"all", "featured", "latest", "mine"}:
tab_n = "all"
featured = True if tab_n == "featured" else None
favorited_by = openid if tab_n == "mine" else ""
items = memo_store.list_memos(
openid=openid,
limit=limit,
offset=offset,
q=q,
tag=tag,
featured=featured,
favorited_by=favorited_by,
)
if tab_n == "latest":
items = sorted(items, key=lambda x: float(x.get("createdAt") or 0), reverse=True)
return {"ok": True, "items": items, "offline": False}
@router.get("/memos/{memo_id}")
async def memo_detail(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
_gate_enabled()
memo = memo_store.get_memo(memo_id, openid=openid)
if not memo:
raise HTTPException(404, "帖子不存在")
comments = memo_store.list_comments(memo_id)
return {"ok": True, "memo": memo, "comments": comments}
class ResourceIn(BaseModel):
type: str = "image"
url: str = Field(..., min_length=4)
class PostBody(BaseModel):
content: str = ""
title: str = ""
resources: list[ResourceIn] = Field(default_factory=list)
def _save_local_bytes(
data: bytes,
*,
filename: str,
content_type: str,
max_size: int,
) -> dict[str, Any]:
if not data:
raise HTTPException(400, "空文件")
if len(data) > max_size:
raise HTTPException(400, f"文件不能超过 {max_size // 1024 // 1024}MB")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
suffix = Path(filename or "img.jpg").suffix.lower() or ".jpg"
if suffix not in {".jpg", ".jpeg", ".png", ".gif", ".webp"}:
suffix = ".jpg"
name = f"{uuid.uuid4().hex}{suffix}"
path = UPLOAD_DIR / name
path.write_bytes(data)
base = (settings.public_api_base or "https://api.nomadro.cn").rstrip("/")
url = f"{base}/api/ebook/memo/files/{name}"
return {
"ok": True,
"url": url,
"object_key": name,
"size": len(data),
"content_type": content_type or "image/jpeg",
}
@router.post("/upload")
async def upload_image(
file: UploadFile = File(...),
openid: str = Depends(get_current_openid),
) -> dict[str, Any]:
_require_vip(openid)
s = _gate_enabled()
if not s.get("canUpload", True):
raise HTTPException(403, "当前不允许上传图片")
ctype = (file.content_type or "").lower()
if not ctype.startswith("image/"):
raise HTTPException(400, "仅支持图片")
data = await file.read()
try:
from community_svc.services import s3_storage
# community S3 path when running unified apps/api
class _MemFile:
def __init__(self, raw: bytes, name: str, content_type: str):
self.filename = name
self.content_type = content_type
self._raw = raw
async def read(self):
return self._raw
result = await s3_storage.upload_file(
_MemFile(data, file.filename or "img.jpg", file.content_type or "image/jpeg"), # type: ignore[arg-type]
purpose="memo",
max_size=10 * 1024 * 1024,
)
return {
"ok": True,
"url": result.url,
"object_key": result.object_key,
"size": result.size,
"content_type": result.content_type,
}
except Exception:
return _save_local_bytes(
data,
filename=file.filename or "img.jpg",
content_type=file.content_type or "image/jpeg",
max_size=10 * 1024 * 1024,
)
@router.get("/files/{name}")
async def get_uploaded_file(name: str):
safe = Path(name).name
if safe != name or ".." in name:
raise HTTPException(400, "非法文件名")
path = UPLOAD_DIR / safe
if not path.is_file():
raise HTTPException(404, "文件不存在")
media = mimetypes.guess_type(safe)[0] or "application/octet-stream"
return FileResponse(path, media_type=media)
@router.post("/memos")
async def create_memo(body: PostBody, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
s = _gate_enabled()
if s.get("adminOnlyPost") or not s.get("canPost"):
raise HTTPException(403, "当前仅博主可发帖")
resources = [r.model_dump() for r in (body.resources or [])]
try:
memo = memo_store.create_memo(
openid=openid,
content=body.content or "",
title=body.title or "",
nickname=_nick(openid),
resources=resources,
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
return {"ok": True, "memo": memo}
@router.delete("/memos/{memo_id}")
async def delete_memo(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
try:
ok = memo_store.delete_memo(memo_id, openid=openid, admin=False)
except ValueError as e:
raise HTTPException(403, str(e)) from e
if not ok:
raise HTTPException(404, "帖子不存在")
return {"ok": True}
@router.post("/memos/{memo_id}/like")
async def like_memo(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
s = _gate_enabled()
if not s.get("canLike"):
raise HTTPException(403, "当前不允许点赞")
try:
memo = memo_store.toggle_like(memo_id, openid)
except ValueError as e:
raise HTTPException(400, str(e)) from e
return {"ok": True, "memo": memo}
@router.post("/memos/{memo_id}/favorite")
async def favorite_memo(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_require_vip(openid)
s = _gate_enabled()
if not s.get("canFavorite", True):
raise HTTPException(403, "当前不允许收藏")
try:
memo = memo_store.toggle_favorite(memo_id, openid)
except ValueError as e:
raise HTTPException(400, str(e)) from e
return {"ok": True, "memo": memo}
class CommentBody(BaseModel):
content: str = Field(..., min_length=1, max_length=1000)
@router.post("/memos/{memo_id}/comments")
async def comment_memo(
memo_id: str,
body: CommentBody,
openid: str = Depends(get_current_openid),
) -> dict[str, Any]:
_require_vip(openid)
s = _gate_enabled()
if not s.get("canComment"):
raise HTTPException(403, "当前不允许评论")
try:
c = memo_store.add_comment(
memo_id,
openid=openid,
content=body.content,
nickname=_nick(openid),
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
return {"ok": True, "comment": c}
@router.delete("/comments/{comment_id}")
async def delete_comment(
comment_id: str,
openid: str = Depends(get_current_openid),
) -> dict[str, Any]:
_require_vip(openid)
try:
ok = memo_store.delete_comment(comment_id, openid=openid, admin=False)
except ValueError as e:
raise HTTPException(403, str(e)) from e
if not ok:
raise HTTPException(404, "评论不存在")
return {"ok": True}