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>
895 lines
33 KiB
Python
895 lines
33 KiB
Python
"""VIP 知识社群(知识星球风格):标题 / 精华 / 收藏 / Markdown / 图 / 标签。"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
import sqlite3
|
||
import time
|
||
import uuid
|
||
from contextlib import contextmanager
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from ebook_svc.config import settings
|
||
|
||
TAG_RE = re.compile(r"#([\w\u4e00-\u9fff\-]{1,32})")
|
||
TITLE_RE = re.compile(r"^#{1,3}\s+(.+)$", re.M)
|
||
|
||
DEFAULT_SETTINGS: dict[str, Any] = {
|
||
"enabled": True,
|
||
"canPost": False,
|
||
"canComment": True,
|
||
"canLike": True,
|
||
"canFavorite": True,
|
||
"canUpload": True,
|
||
"adminOnlyPost": True,
|
||
# requireVip=False → 全员视为 VIP(关闭付费墙)
|
||
"requireVip": True,
|
||
# 未付费可浏览列表 + 试读帖;关闭则 feed/detail 也需 VIP
|
||
"allowTrialBrowse": True,
|
||
# 后台发帖默认试读
|
||
"defaultTrial": True,
|
||
# 未付费是否可读试读帖下的评论(默认否,防讨论区泄露)
|
||
"trialComments": False,
|
||
"maxContentLen": 20000,
|
||
"maxImages": 9,
|
||
"planetName": "Nomadro 知识社群",
|
||
"planetDesc": "博主分享实战干货,会员阅读互动",
|
||
"notice": "置顶与精华优先 · 支持 Markdown / 图片 / #话题 · 未付费可试读",
|
||
}
|
||
|
||
SEED_MEMOS = [
|
||
{
|
||
"title": "欢迎加入知识社群",
|
||
"content": (
|
||
"## 欢迎加入知识社群\n\n"
|
||
"这里是 VIP 专属内容区(对标知识星球的阅读体验)。\n\n"
|
||
"- 博主发帖分享干货\n"
|
||
"- 支持 **Markdown**、图片、`#话题`\n"
|
||
"- 会员可点赞、评论、收藏\n\n"
|
||
"> 友善交流,禁止广告刷屏。\n\n"
|
||
"#欢迎 #VIP"
|
||
),
|
||
"nickname": "Nomadro",
|
||
"openid": "__system__",
|
||
"pinned": 1,
|
||
"featured": 1,
|
||
"visibility": "trial",
|
||
"resources": [],
|
||
},
|
||
{
|
||
"title": "如何高效读帖",
|
||
"content": (
|
||
"## 如何高效读帖\n\n"
|
||
"1. 用顶部 **精华 / 最新** 筛选\n"
|
||
"2. 点 `#话题` 看同主题系列\n"
|
||
"3. 详情页可收藏,方便回看\n\n"
|
||
"有问题直接在帖下评论。\n\n"
|
||
"#使用指南"
|
||
),
|
||
"nickname": "Nomadro",
|
||
"openid": "__system__",
|
||
"pinned": 0,
|
||
"featured": 1,
|
||
"visibility": "trial",
|
||
"resources": [],
|
||
},
|
||
]
|
||
|
||
|
||
def extract_tags(content: str) -> list[str]:
|
||
found: list[str] = []
|
||
for m in TAG_RE.finditer(content or ""):
|
||
t = m.group(1).strip()
|
||
if t and t not in found:
|
||
found.append(t)
|
||
return found[:20]
|
||
|
||
|
||
def extract_title(content: str, explicit: str = "") -> str:
|
||
t = (explicit or "").strip()
|
||
if t:
|
||
return t[:120]
|
||
m = TITLE_RE.search(content or "")
|
||
if m:
|
||
return m.group(1).strip()[:120]
|
||
plain = re.sub(r"[#>*`_\-\[\]\(\)]+", " ", content or "")
|
||
plain = re.sub(r"\s+", " ", plain).strip()
|
||
return (plain[:40] + ("…" if len(plain) > 40 else "")) if plain else "未命名"
|
||
|
||
|
||
def extract_excerpt(content: str, limit: int = 96) -> str:
|
||
lines = []
|
||
for line in (content or "").splitlines():
|
||
s = line.strip()
|
||
if not s or s.startswith("#"):
|
||
continue
|
||
if s.startswith(">"):
|
||
s = s.lstrip("> ").strip()
|
||
s = re.sub(r"[*_`]", "", s)
|
||
if s:
|
||
lines.append(s)
|
||
plain = " ".join(lines) if lines else re.sub(r"\s+", " ", content or "").strip()
|
||
plain = re.sub(r"#([\w\u4e00-\u9fff\-]+)", "", plain).strip()
|
||
if len(plain) <= limit:
|
||
return plain
|
||
return plain[: limit - 1] + "…"
|
||
|
||
|
||
class MemoStore:
|
||
def __init__(self, path: str):
|
||
self.path = Path(path)
|
||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||
self._init_db()
|
||
|
||
@contextmanager
|
||
def conn(self):
|
||
from ebook_svc.core.sqlite_util import connect as sqlite_connect
|
||
|
||
c = sqlite_connect(self.path)
|
||
try:
|
||
yield c
|
||
c.commit()
|
||
finally:
|
||
c.close()
|
||
|
||
def _migrate(self, c: sqlite3.Connection) -> None:
|
||
cols = {r[1] for r in c.execute("PRAGMA table_info(memos)").fetchall()}
|
||
if not cols:
|
||
return
|
||
alters = [
|
||
("resources_json", "TEXT DEFAULT '[]'"),
|
||
("tags_json", "TEXT DEFAULT '[]'"),
|
||
("visibility", "TEXT DEFAULT 'vip'"),
|
||
("title", "TEXT DEFAULT ''"),
|
||
("featured", "INTEGER DEFAULT 0"),
|
||
("favorite_count", "INTEGER DEFAULT 0"),
|
||
]
|
||
for name, decl in alters:
|
||
if name not in cols:
|
||
c.execute(f"ALTER TABLE memos ADD COLUMN {name} {decl}")
|
||
c.executescript(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS memo_favorites (
|
||
memo_id TEXT NOT NULL,
|
||
openid TEXT NOT NULL,
|
||
created_at REAL,
|
||
PRIMARY KEY (memo_id, openid)
|
||
);
|
||
"""
|
||
)
|
||
# backfill titles
|
||
rows = c.execute(
|
||
"SELECT id, content, title FROM memos WHERE IFNULL(title,'')='' "
|
||
).fetchall()
|
||
for r in rows:
|
||
title = extract_title(r["content"] or "")
|
||
if title:
|
||
c.execute("UPDATE memos SET title=? WHERE id=?", (title, r["id"]))
|
||
|
||
def _init_db(self):
|
||
with self.conn() as c:
|
||
c.executescript(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS memo_settings (
|
||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||
json TEXT NOT NULL,
|
||
updated_at REAL
|
||
);
|
||
CREATE TABLE IF NOT EXISTS memos (
|
||
id TEXT PRIMARY KEY,
|
||
openid TEXT NOT NULL,
|
||
nickname TEXT,
|
||
title TEXT DEFAULT '',
|
||
content TEXT NOT NULL,
|
||
resources_json TEXT DEFAULT '[]',
|
||
tags_json TEXT DEFAULT '[]',
|
||
visibility TEXT DEFAULT 'vip',
|
||
pinned INTEGER DEFAULT 0,
|
||
featured INTEGER DEFAULT 0,
|
||
status TEXT DEFAULT 'active',
|
||
like_count INTEGER DEFAULT 0,
|
||
comment_count INTEGER DEFAULT 0,
|
||
favorite_count INTEGER DEFAULT 0,
|
||
created_at REAL,
|
||
updated_at REAL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_memos_created
|
||
ON memos(pinned DESC, featured DESC, created_at DESC);
|
||
CREATE TABLE IF NOT EXISTS memo_comments (
|
||
id TEXT PRIMARY KEY,
|
||
memo_id TEXT NOT NULL,
|
||
openid TEXT NOT NULL,
|
||
nickname TEXT,
|
||
content TEXT NOT NULL,
|
||
status TEXT DEFAULT 'active',
|
||
created_at REAL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_memo_comments_memo
|
||
ON memo_comments(memo_id, created_at ASC);
|
||
CREATE TABLE IF NOT EXISTS memo_likes (
|
||
memo_id TEXT NOT NULL,
|
||
openid TEXT NOT NULL,
|
||
created_at REAL,
|
||
PRIMARY KEY (memo_id, openid)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS memo_favorites (
|
||
memo_id TEXT NOT NULL,
|
||
openid TEXT NOT NULL,
|
||
created_at REAL,
|
||
PRIMARY KEY (memo_id, openid)
|
||
);
|
||
"""
|
||
)
|
||
self._migrate(c)
|
||
row = c.execute("SELECT id FROM memo_settings WHERE id=1").fetchone()
|
||
if not row:
|
||
c.execute(
|
||
"INSERT INTO memo_settings(id, json, updated_at) VALUES (1, ?, ?)",
|
||
(json.dumps(DEFAULT_SETTINGS, ensure_ascii=False), time.time()),
|
||
)
|
||
else:
|
||
try:
|
||
cur = json.loads(
|
||
c.execute("SELECT json FROM memo_settings WHERE id=1").fetchone()["json"]
|
||
)
|
||
if isinstance(cur, dict):
|
||
merged = dict(DEFAULT_SETTINGS)
|
||
merged.update(cur)
|
||
c.execute(
|
||
"UPDATE memo_settings SET json=? WHERE id=1",
|
||
(json.dumps(merged, ensure_ascii=False),),
|
||
)
|
||
except Exception:
|
||
pass
|
||
n = c.execute("SELECT COUNT(*) AS n FROM memos").fetchone()["n"]
|
||
if n == 0:
|
||
now = time.time()
|
||
for i, m in enumerate(SEED_MEMOS):
|
||
mid = f"mseed{i+1}"
|
||
tags = extract_tags(m["content"])
|
||
vis = str(m.get("visibility") or "trial")
|
||
if vis not in {"trial", "public", "free", "vip"}:
|
||
vis = "trial"
|
||
c.execute(
|
||
"""
|
||
INSERT INTO memos(
|
||
id,openid,nickname,title,content,resources_json,tags_json,visibility,
|
||
pinned,featured,status,like_count,comment_count,favorite_count,
|
||
created_at,updated_at
|
||
) VALUES (?,?,?,?,?,?,?,?,?,?,'active',0,0,0,?,?)
|
||
""",
|
||
(
|
||
mid,
|
||
m["openid"],
|
||
m["nickname"],
|
||
m.get("title") or extract_title(m["content"]),
|
||
m["content"],
|
||
json.dumps(m.get("resources") or [], ensure_ascii=False),
|
||
json.dumps(tags, ensure_ascii=False),
|
||
vis,
|
||
m["pinned"],
|
||
m.get("featured") or 0,
|
||
now - (len(SEED_MEMOS) - i) * 120,
|
||
now,
|
||
),
|
||
)
|
||
else:
|
||
# 系统欢迎帖默认开放试读(已有库一次性抬升)
|
||
c.execute(
|
||
"UPDATE memos SET visibility='trial' "
|
||
"WHERE id IN ('mseed1','mseed2') AND IFNULL(visibility,'vip')='vip'"
|
||
)
|
||
rows = c.execute(
|
||
"SELECT id, content, tags_json FROM memos WHERE IFNULL(tags_json,'') IN ('','[]')"
|
||
).fetchall()
|
||
for r in rows:
|
||
tags = extract_tags(r["content"] or "")
|
||
if tags:
|
||
c.execute(
|
||
"UPDATE memos SET tags_json=? WHERE id=?",
|
||
(json.dumps(tags, ensure_ascii=False), r["id"]),
|
||
)
|
||
|
||
def get_settings(self) -> dict[str, Any]:
|
||
with self.conn() as c:
|
||
row = c.execute("SELECT json FROM memo_settings WHERE id=1").fetchone()
|
||
base = dict(DEFAULT_SETTINGS)
|
||
if not row:
|
||
return base
|
||
try:
|
||
raw = json.loads(row["json"] or "{}")
|
||
if isinstance(raw, dict):
|
||
base.update(raw)
|
||
except Exception:
|
||
pass
|
||
return base
|
||
|
||
def content_revision(self) -> int:
|
||
s = self.get_settings()
|
||
try:
|
||
return int(s.get("_contentRevision") or 0)
|
||
except Exception:
|
||
return 0
|
||
|
||
def bump_content_revision(self) -> int:
|
||
"""后台隐藏/发帖/改配置后递增,前端轮询此值做近实时同步。"""
|
||
cur = self.get_settings()
|
||
rev = int(time.time() * 1000)
|
||
cur["_contentRevision"] = rev
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memo_settings SET json=?, updated_at=? WHERE id=1",
|
||
(json.dumps(cur, ensure_ascii=False), time.time()),
|
||
)
|
||
return rev
|
||
|
||
def save_settings(self, patch: dict[str, Any]) -> dict[str, Any]:
|
||
cur = self.get_settings()
|
||
for k, v in patch.items():
|
||
if k in DEFAULT_SETTINGS and v is not None:
|
||
cur[k] = v
|
||
cur["_contentRevision"] = int(time.time() * 1000)
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memo_settings SET json=?, updated_at=? WHERE id=1",
|
||
(json.dumps(cur, ensure_ascii=False), time.time()),
|
||
)
|
||
return cur
|
||
|
||
def _parse_json_list(self, raw: Any) -> list[Any]:
|
||
try:
|
||
v = json.loads(raw or "[]")
|
||
return v if isinstance(v, list) else []
|
||
except Exception:
|
||
return []
|
||
|
||
def _memo_row(
|
||
self,
|
||
row: sqlite3.Row,
|
||
*,
|
||
openid: str = "",
|
||
with_flags: bool = False,
|
||
) -> dict[str, Any]:
|
||
keys = set(row.keys())
|
||
resources = self._parse_json_list(row["resources_json"] if "resources_json" in keys else "[]")
|
||
tags = self._parse_json_list(row["tags_json"] if "tags_json" in keys else "[]")
|
||
content = row["content"] or ""
|
||
title = (row["title"] if "title" in keys else "") or extract_title(content)
|
||
cover = ""
|
||
for r in resources:
|
||
if isinstance(r, dict) and str(r.get("type") or "image") == "image" and r.get("url"):
|
||
cover = str(r["url"])
|
||
break
|
||
visibility = (row["visibility"] if "visibility" in keys else None) or "vip"
|
||
is_trial = visibility in {"trial", "public", "free"}
|
||
item = {
|
||
"id": row["id"],
|
||
"openid": row["openid"],
|
||
"nickname": row["nickname"] or "博主",
|
||
"title": title,
|
||
"excerpt": extract_excerpt(content),
|
||
"content": content,
|
||
"resources": resources,
|
||
"cover": cover,
|
||
"tags": tags,
|
||
"visibility": visibility,
|
||
"trial": is_trial,
|
||
"locked": False,
|
||
"pinned": bool(row["pinned"]),
|
||
"featured": bool(row["featured"] if "featured" in keys else 0),
|
||
"status": row["status"],
|
||
"likeCount": int(row["like_count"] or 0),
|
||
"commentCount": int(row["comment_count"] or 0),
|
||
"favoriteCount": int(
|
||
(row["favorite_count"] if "favorite_count" in keys else 0) or 0
|
||
),
|
||
"createdAt": row["created_at"],
|
||
"updatedAt": row["updated_at"],
|
||
"isMine": bool(openid and row["openid"] == openid),
|
||
"liked": False,
|
||
"favorited": False,
|
||
}
|
||
if with_flags and openid:
|
||
item["liked"] = self.has_liked(row["id"], openid)
|
||
item["favorited"] = self.has_favorited(row["id"], openid)
|
||
return item
|
||
|
||
@staticmethod
|
||
def apply_access(memo: dict[str, Any], *, is_vip: bool) -> dict[str, Any]:
|
||
"""未付费:试读贴全文;非试读仅摘要 + locked。"""
|
||
out = dict(memo)
|
||
is_trial = bool(out.get("trial")) or str(out.get("visibility") or "") in {
|
||
"trial",
|
||
"public",
|
||
"free",
|
||
}
|
||
out["trial"] = is_trial
|
||
locked = not is_vip and not is_trial
|
||
out["locked"] = locked
|
||
if locked:
|
||
out["content"] = ""
|
||
out["resources"] = []
|
||
return out
|
||
|
||
def has_liked(self, memo_id: str, openid: str) -> bool:
|
||
with self.conn() as c:
|
||
return bool(
|
||
c.execute(
|
||
"SELECT 1 FROM memo_likes WHERE memo_id=? AND openid=?",
|
||
(memo_id, openid),
|
||
).fetchone()
|
||
)
|
||
|
||
def has_favorited(self, memo_id: str, openid: str) -> bool:
|
||
with self.conn() as c:
|
||
return bool(
|
||
c.execute(
|
||
"SELECT 1 FROM memo_favorites WHERE memo_id=? AND openid=?",
|
||
(memo_id, openid),
|
||
).fetchone()
|
||
)
|
||
|
||
def list_memos(
|
||
self,
|
||
*,
|
||
openid: str = "",
|
||
limit: int = 50,
|
||
offset: int = 0,
|
||
include_hidden: bool = False,
|
||
q: str = "",
|
||
tag: str = "",
|
||
featured: bool | None = None,
|
||
favorited_by: str = "",
|
||
visibility: str = "",
|
||
# 未付费搜索不扫会员帖正文,避免关键词泄露
|
||
safe_search: bool = False,
|
||
) -> list[dict[str, Any]]:
|
||
with self.conn() as c:
|
||
clauses: list[str] = []
|
||
params: list[Any] = []
|
||
if not include_hidden:
|
||
clauses.append("status='active'")
|
||
if q.strip():
|
||
like = f"%{q.strip()}%"
|
||
if safe_search:
|
||
clauses.append(
|
||
"("
|
||
"title LIKE ? OR tags_json LIKE ? OR "
|
||
"(IFNULL(visibility,'vip') IN ('trial','public','free') AND content LIKE ?)"
|
||
")"
|
||
)
|
||
params.extend([like, like, like])
|
||
else:
|
||
clauses.append("(title LIKE ? OR content LIKE ? OR tags_json LIKE ?)")
|
||
params.extend([like, like, like])
|
||
if tag.strip():
|
||
clauses.append("tags_json LIKE ?")
|
||
params.append(f'%"{tag.strip()}"%')
|
||
if featured is True:
|
||
clauses.append("featured=1")
|
||
vis = (visibility or "").strip().lower()
|
||
if vis == "trial":
|
||
clauses.append("IFNULL(visibility,'vip') IN ('trial','public','free')")
|
||
elif vis == "vip":
|
||
clauses.append("IFNULL(visibility,'vip') NOT IN ('trial','public','free')")
|
||
if favorited_by:
|
||
clauses.append(
|
||
"id IN (SELECT memo_id FROM memo_favorites WHERE openid=?)"
|
||
)
|
||
params.append(favorited_by)
|
||
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||
params.extend([limit, offset])
|
||
rows = c.execute(
|
||
f"""
|
||
SELECT * FROM memos{where}
|
||
ORDER BY pinned DESC, featured DESC, created_at DESC
|
||
LIMIT ? OFFSET ?
|
||
""",
|
||
tuple(params),
|
||
).fetchall()
|
||
return [self._memo_row(r, openid=openid, with_flags=True) for r in rows]
|
||
|
||
def list_tags(self, limit: int = 40) -> list[dict[str, Any]]:
|
||
counts: dict[str, int] = {}
|
||
with self.conn() as c:
|
||
rows = c.execute(
|
||
"SELECT tags_json FROM memos WHERE status='active'"
|
||
).fetchall()
|
||
for r in rows:
|
||
for t in self._parse_json_list(r["tags_json"]):
|
||
if isinstance(t, str) and t:
|
||
counts[t] = counts.get(t, 0) + 1
|
||
ordered = sorted(counts.items(), key=lambda x: (-x[1], x[0]))[:limit]
|
||
return [{"name": k, "count": v} for k, v in ordered]
|
||
|
||
def get_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> dict[str, Any] | None:
|
||
with self.conn() as c:
|
||
row = c.execute("SELECT * FROM memos WHERE id=?", (memo_id,)).fetchone()
|
||
if not row:
|
||
return None
|
||
if not admin and row["status"] != "active":
|
||
return None
|
||
return self._memo_row(row, openid=openid, with_flags=True)
|
||
|
||
def create_memo(
|
||
self,
|
||
*,
|
||
openid: str,
|
||
content: str,
|
||
nickname: str = "",
|
||
title: str = "",
|
||
pinned: bool = False,
|
||
featured: bool = False,
|
||
visibility: str = "vip",
|
||
resources: list[dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
content = (content or "").strip()
|
||
resources = resources or []
|
||
if not content and not resources:
|
||
raise ValueError("内容或图片至少一项")
|
||
s = self.get_settings()
|
||
max_len = int(s.get("maxContentLen") or 20000)
|
||
max_images = int(s.get("maxImages") or 9)
|
||
if len(content) > max_len:
|
||
raise ValueError(f"内容超过 {max_len} 字")
|
||
if len(resources) > max_images:
|
||
raise ValueError(f"最多 {max_images} 张图")
|
||
clean_res: list[dict[str, Any]] = []
|
||
for r in resources:
|
||
url = str((r or {}).get("url") or "").strip()
|
||
if not url:
|
||
continue
|
||
clean_res.append(
|
||
{"type": str((r or {}).get("type") or "image"), "url": url}
|
||
)
|
||
tags = extract_tags(content)
|
||
title_f = extract_title(content, title)
|
||
vis = (visibility or "vip").strip().lower()
|
||
if vis not in {"vip", "trial", "public", "free"}:
|
||
vis = "vip"
|
||
mid = f"m{uuid.uuid4().hex[:16]}"
|
||
now = time.time()
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"""
|
||
INSERT INTO memos(
|
||
id,openid,nickname,title,content,resources_json,tags_json,visibility,
|
||
pinned,featured,status,like_count,comment_count,favorite_count,
|
||
created_at,updated_at
|
||
) VALUES (?,?,?,?,?,?,?,?,?,?,'active',0,0,0,?,?)
|
||
""",
|
||
(
|
||
mid,
|
||
openid,
|
||
nickname or "博主",
|
||
title_f,
|
||
content,
|
||
json.dumps(clean_res, ensure_ascii=False),
|
||
json.dumps(tags, ensure_ascii=False),
|
||
vis,
|
||
1 if pinned else 0,
|
||
1 if featured else 0,
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
memo = self.get_memo(mid, openid=openid) # type: ignore
|
||
self.bump_content_revision()
|
||
return memo
|
||
|
||
def update_memo(
|
||
self,
|
||
memo_id: str,
|
||
*,
|
||
content: str | None = None,
|
||
title: str | None = None,
|
||
nickname: str | None = None,
|
||
visibility: str | None = None,
|
||
resources: list[dict[str, Any]] | None = None,
|
||
) -> dict[str, Any] | None:
|
||
memo = self.get_memo(memo_id, admin=True)
|
||
if not memo:
|
||
return None
|
||
if str(memo.get("status") or "") == "deleted":
|
||
raise ValueError("已删除的帖子不能编辑")
|
||
s = self.get_settings()
|
||
max_len = int(s.get("maxContentLen") or 20000)
|
||
max_images = int(s.get("maxImages") or 9)
|
||
new_content = memo.get("content") or ""
|
||
if content is not None:
|
||
new_content = (content or "").strip()
|
||
if len(new_content) > max_len:
|
||
raise ValueError(f"内容超过 {max_len} 字")
|
||
new_title = memo.get("title") or ""
|
||
if title is not None:
|
||
new_title = extract_title(new_content, title)
|
||
new_nick = memo.get("nickname") or "博主"
|
||
if nickname is not None:
|
||
new_nick = (nickname or "博主").strip()[:32] or "博主"
|
||
vis = memo.get("visibility") or "vip"
|
||
if visibility is not None:
|
||
vis = (visibility or "vip").strip().lower()
|
||
if vis not in {"vip", "trial", "public", "free"}:
|
||
vis = "vip"
|
||
clean_res = memo.get("resources") or []
|
||
if resources is not None:
|
||
clean_res = []
|
||
for r in resources:
|
||
url = str((r or {}).get("url") or "").strip()
|
||
if not url:
|
||
continue
|
||
clean_res.append({"type": str((r or {}).get("type") or "image"), "url": url})
|
||
if len(clean_res) > max_images:
|
||
raise ValueError(f"最多 {max_images} 张图")
|
||
if not new_content and not clean_res:
|
||
raise ValueError("内容或图片至少一项")
|
||
tags = extract_tags(new_content)
|
||
now = time.time()
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"""
|
||
UPDATE memos SET nickname=?, title=?, content=?, resources_json=?, tags_json=?,
|
||
visibility=?, updated_at=?
|
||
WHERE id=?
|
||
""",
|
||
(
|
||
new_nick,
|
||
new_title,
|
||
new_content,
|
||
json.dumps(clean_res, ensure_ascii=False),
|
||
json.dumps(tags, ensure_ascii=False),
|
||
vis,
|
||
now,
|
||
memo_id,
|
||
),
|
||
)
|
||
self.bump_content_revision()
|
||
return self.get_memo(memo_id, admin=True)
|
||
|
||
def delete_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
||
memo = self.get_memo(memo_id, openid=openid, admin=True)
|
||
if not memo:
|
||
return False
|
||
if not admin and memo["openid"] != openid:
|
||
raise ValueError("无权删除")
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memos SET status='deleted', updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
self.bump_content_revision()
|
||
return True
|
||
|
||
def hide_memo(self, memo_id: str) -> dict[str, Any] | None:
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memos SET status='hidden', updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
self.bump_content_revision()
|
||
return self.get_memo(memo_id, admin=True)
|
||
|
||
def unhide_memo(self, memo_id: str) -> dict[str, Any] | None:
|
||
"""已隐藏 → 恢复公开显示(已删除不可恢复)。"""
|
||
memo = self.get_memo(memo_id, admin=True)
|
||
if not memo:
|
||
return None
|
||
if str(memo.get("status") or "") == "deleted":
|
||
raise ValueError("已删除的帖子不能恢复,请重新发布")
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memos SET status='active', updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
self.bump_content_revision()
|
||
return self.get_memo(memo_id, admin=True)
|
||
|
||
def set_pin(self, memo_id: str, pinned: bool) -> dict[str, Any] | None:
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memos SET pinned=?, updated_at=? WHERE id=?",
|
||
(1 if pinned else 0, time.time(), memo_id),
|
||
)
|
||
self.bump_content_revision()
|
||
return self.get_memo(memo_id, admin=True)
|
||
|
||
def set_featured(self, memo_id: str, featured: bool) -> dict[str, Any] | None:
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memos SET featured=?, updated_at=? WHERE id=?",
|
||
(1 if featured else 0, time.time(), memo_id),
|
||
)
|
||
self.bump_content_revision()
|
||
return self.get_memo(memo_id, admin=True)
|
||
|
||
def set_visibility(self, memo_id: str, visibility: str) -> dict[str, Any] | None:
|
||
vis = (visibility or "vip").strip().lower()
|
||
if vis not in {"vip", "trial", "public", "free"}:
|
||
raise ValueError("visibility 仅支持 vip / trial")
|
||
if vis in {"public", "free"}:
|
||
vis = "trial"
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"UPDATE memos SET visibility=?, updated_at=? WHERE id=?",
|
||
(vis, time.time(), memo_id),
|
||
)
|
||
self.bump_content_revision()
|
||
return self.get_memo(memo_id, admin=True)
|
||
|
||
def toggle_like(self, memo_id: str, openid: str) -> dict[str, Any]:
|
||
memo = self.get_memo(memo_id, openid=openid)
|
||
if not memo:
|
||
raise ValueError("帖子不存在")
|
||
with self.conn() as c:
|
||
existed = c.execute(
|
||
"SELECT 1 FROM memo_likes WHERE memo_id=? AND openid=?",
|
||
(memo_id, openid),
|
||
).fetchone()
|
||
if existed:
|
||
c.execute(
|
||
"DELETE FROM memo_likes WHERE memo_id=? AND openid=?",
|
||
(memo_id, openid),
|
||
)
|
||
c.execute(
|
||
"UPDATE memos SET like_count=CASE WHEN like_count>0 THEN like_count-1 ELSE 0 END, updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
liked = False
|
||
else:
|
||
c.execute(
|
||
"INSERT INTO memo_likes(memo_id, openid, created_at) VALUES (?,?,?)",
|
||
(memo_id, openid, time.time()),
|
||
)
|
||
c.execute(
|
||
"UPDATE memos SET like_count=like_count+1, updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
liked = True
|
||
out = self.get_memo(memo_id, openid=openid)
|
||
if out:
|
||
out["liked"] = liked
|
||
return out # type: ignore
|
||
|
||
def toggle_favorite(self, memo_id: str, openid: str) -> dict[str, Any]:
|
||
memo = self.get_memo(memo_id, openid=openid)
|
||
if not memo:
|
||
raise ValueError("帖子不存在")
|
||
with self.conn() as c:
|
||
existed = c.execute(
|
||
"SELECT 1 FROM memo_favorites WHERE memo_id=? AND openid=?",
|
||
(memo_id, openid),
|
||
).fetchone()
|
||
if existed:
|
||
c.execute(
|
||
"DELETE FROM memo_favorites WHERE memo_id=? AND openid=?",
|
||
(memo_id, openid),
|
||
)
|
||
c.execute(
|
||
"UPDATE memos SET favorite_count=CASE WHEN favorite_count>0 THEN favorite_count-1 ELSE 0 END, updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
favorited = False
|
||
else:
|
||
c.execute(
|
||
"INSERT INTO memo_favorites(memo_id, openid, created_at) VALUES (?,?,?)",
|
||
(memo_id, openid, time.time()),
|
||
)
|
||
c.execute(
|
||
"UPDATE memos SET favorite_count=favorite_count+1, updated_at=? WHERE id=?",
|
||
(time.time(), memo_id),
|
||
)
|
||
favorited = True
|
||
out = self.get_memo(memo_id, openid=openid)
|
||
if out:
|
||
out["favorited"] = favorited
|
||
return out # type: ignore
|
||
|
||
def list_comments(self, memo_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
|
||
with self.conn() as c:
|
||
rows = c.execute(
|
||
"""
|
||
SELECT * FROM memo_comments
|
||
WHERE memo_id=? AND status='active'
|
||
ORDER BY created_at ASC LIMIT ?
|
||
""",
|
||
(memo_id, limit),
|
||
).fetchall()
|
||
return [
|
||
{
|
||
"id": r["id"],
|
||
"memoId": r["memo_id"],
|
||
"openid": r["openid"],
|
||
"nickname": r["nickname"] or "会员",
|
||
"content": r["content"],
|
||
"createdAt": r["created_at"],
|
||
}
|
||
for r in rows
|
||
]
|
||
|
||
def add_comment(
|
||
self,
|
||
memo_id: str,
|
||
*,
|
||
openid: str,
|
||
content: str,
|
||
nickname: str = "",
|
||
) -> dict[str, Any]:
|
||
content = (content or "").strip()
|
||
if not content:
|
||
raise ValueError("评论不能为空")
|
||
memo = self.get_memo(memo_id, openid=openid)
|
||
if not memo:
|
||
raise ValueError("帖子不存在")
|
||
cid = f"c{uuid.uuid4().hex[:14]}"
|
||
now = time.time()
|
||
with self.conn() as c:
|
||
c.execute(
|
||
"""
|
||
INSERT INTO memo_comments(id,memo_id,openid,nickname,content,status,created_at)
|
||
VALUES (?,?,?,?,?,'active',?)
|
||
""",
|
||
(cid, memo_id, openid, nickname or "会员", content, now),
|
||
)
|
||
c.execute(
|
||
"UPDATE memos SET comment_count=comment_count+1, updated_at=? WHERE id=?",
|
||
(now, memo_id),
|
||
)
|
||
return {
|
||
"id": cid,
|
||
"memoId": memo_id,
|
||
"openid": openid,
|
||
"nickname": nickname or "会员",
|
||
"content": content,
|
||
"createdAt": now,
|
||
}
|
||
|
||
def delete_comment(self, comment_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
||
with self.conn() as c:
|
||
row = c.execute("SELECT * FROM memo_comments WHERE id=?", (comment_id,)).fetchone()
|
||
if not row:
|
||
return False
|
||
if not admin and row["openid"] != openid:
|
||
raise ValueError("无权删除")
|
||
c.execute(
|
||
"UPDATE memo_comments SET status='deleted' WHERE id=?",
|
||
(comment_id,),
|
||
)
|
||
c.execute(
|
||
"""
|
||
UPDATE memos SET comment_count=CASE WHEN comment_count>0 THEN comment_count-1 ELSE 0 END, updated_at=?
|
||
WHERE id=?
|
||
""",
|
||
(time.time(), row["memo_id"]),
|
||
)
|
||
return True
|
||
|
||
def stats(self) -> dict[str, Any]:
|
||
with self.conn() as c:
|
||
memos = c.execute(
|
||
"SELECT COUNT(*) AS n FROM memos WHERE status='active'"
|
||
).fetchone()["n"]
|
||
trial = c.execute(
|
||
"SELECT COUNT(*) AS n FROM memos WHERE status='active' "
|
||
"AND IFNULL(visibility,'vip') IN ('trial','public','free')"
|
||
).fetchone()["n"]
|
||
comments = c.execute(
|
||
"SELECT COUNT(*) AS n FROM memo_comments WHERE status='active'"
|
||
).fetchone()["n"]
|
||
likes = c.execute("SELECT COUNT(*) AS n FROM memo_likes").fetchone()["n"]
|
||
favorites = c.execute("SELECT COUNT(*) AS n FROM memo_favorites").fetchone()["n"]
|
||
featured = c.execute(
|
||
"SELECT COUNT(*) AS n FROM memos WHERE status='active' AND featured=1"
|
||
).fetchone()["n"]
|
||
return {
|
||
"memos": memos,
|
||
"trial": trial,
|
||
"comments": comments,
|
||
"likes": likes,
|
||
"favorites": favorites,
|
||
"featured": featured,
|
||
}
|
||
|
||
|
||
memo_store = MemoStore(settings.sqlite_path)
|