nomadro/apps/api/services/ebook_svc/routers/memo.py
Eric d0262eb58d Ship WeChat audit mode, package-size fixes, and live VIP switches.
Harden weapp for review: silent audit book, no flashy module defaults, safe-area PX, subpackages/lazyCodeLoading, and CDN nav icons. Document pre3 and move next work to pre4.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 15:12:06 +08:00

364 lines
12 KiB
Python
Raw Permalink 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.

"""VIP 知识社群公开 API — 试读浏览 + VIP 互动。"""
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 _is_vip(openid: str) -> bool:
"""付费方案下查 unlocks(__vip__);免费方案 / requireVip=false 视为全员 VIP。"""
cfg = read_vip_config()
s = memo_store.get_settings()
if not s.get("requireVip"):
return True
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
return True
return store.is_unlocked(openid, VIP_BOOK_ID)
def _require_vip(openid: str) -> None:
if not _is_vip(openid):
raise HTTPException(403, "开通 VIP 后可互动")
def _allow_browse(openid: str) -> bool:
"""列表/详情浏览:VIP 或 allowTrialBrowse。"""
if _is_vip(openid):
return True
s = memo_store.get_settings()
return bool(s.get("allowTrialBrowse", True))
def _require_browse(openid: str) -> None:
if not _allow_browse(openid):
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
def _public_settings_payload(openid: str) -> dict[str, Any]:
s = memo_store.get_settings()
is_vip = _is_vip(openid)
allow_browse = is_vip or bool(s.get("allowTrialBrowse", True))
return {
"ok": True,
"enabled": bool(s.get("enabled")),
"isVip": is_vip,
"allowTrialBrowse": bool(s.get("allowTrialBrowse", True)),
"defaultTrial": bool(s.get("defaultTrial", True)),
"trialComments": bool(s.get("trialComments", False)),
"requireVip": bool(s.get("requireVip", True)),
"canBrowse": allow_browse,
"canPost": bool(is_vip)
and bool(s.get("canPost"))
and not bool(s.get("adminOnlyPost")),
"canComment": bool(is_vip) and bool(s.get("canComment")),
"canLike": bool(is_vip) and bool(s.get("canLike")),
"canFavorite": bool(is_vip) and bool(s.get("canFavorite", True)),
"canUpload": bool(is_vip) and 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),
"unlockHint": "开通 VIP 后可读全文并参与讨论",
# 前端轮询:隐藏/发帖/改配置后变化 → 立刻重拉列表
"contentRevision": int(s.get("_contentRevision") or 0),
}
@router.get("/settings")
async def public_settings(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
"""社群配置 + 当前用户 VIP/试读策略(不强制 enabled,前端可展示关闭态)。"""
return _public_settings_payload(openid)
@router.get("/tags")
async def tags(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
_gate_enabled()
_require_browse(openid)
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]:
"""
试读策略:
- allowTrialBrowse + 未付费:可拉列表;trial 帖保留正文,vip 帖仅摘要(locked)
- 未开 allowTrialBrowse:非 VIP 403
"""
_gate_enabled()
_require_browse(openid)
is_vip = _is_vip(openid)
tab_n = (tab or "all").strip().lower()
if tab_n not in {"all", "featured", "latest", "mine"}:
tab_n = "all"
if tab_n == "mine" and not is_vip:
return {"ok": True, "items": [], "offline": False, "isVip": False}
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,
safe_search=not is_vip,
)
if tab_n == "latest":
items = sorted(items, key=lambda x: float(x.get("createdAt") or 0), reverse=True)
items = [memo_store.apply_access(x, is_vip=is_vip) for x in items]
return {
"ok": True,
"items": items,
"offline": False,
"isVip": is_vip,
"contentRevision": memo_store.content_revision(),
}
@router.get("/memos/{memo_id}")
async def memo_detail(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
"""试读帖全文;会员帖未付费 → locked + excerpt;评论默认仅 VIP。"""
s = _gate_enabled()
_require_browse(openid)
is_vip = _is_vip(openid)
memo = memo_store.get_memo(memo_id, openid=openid)
if not memo:
raise HTTPException(404, "帖子不存在")
memo = memo_store.apply_access(memo, is_vip=is_vip)
show_comments = is_vip or (
bool(memo.get("trial")) and bool(s.get("trialComments", False))
)
comments = memo_store.list_comments(memo_id) if show_comments else []
return {
"ok": True,
"memo": memo,
"comments": comments,
"isVip": is_vip,
"commentsLocked": not show_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
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),
visibility="vip",
resources=resources,
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
return {"ok": True, "memo": memo_store.apply_access(memo, is_vip=True)}
@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_store.apply_access(memo, is_vip=True)}
@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_store.apply_access(memo, is_vip=True)}
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}