nomadro/apps/api/services/ebook_svc/services/social_ops.py
Eric 9b7ffb24dc Ship social-first admin console, soft trials, and safer join gates.
Rebuild admin.nomadro.com around community ops, add configurable free peeks instead of nav locks, humanize user copy, and harden UGC/liveness admin APIs with backup/self-test scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 23:47:04 +08:00

352 lines
11 KiB
Python
Raw 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.

"""游民社区运营开关 — pages / sections / features / buttons / copy。
只深合并 remote-config 的 copy.social* 与 copy.socialFlags;
不碰 orders、PocketBase、platforms.tt、socialCatalogs 内容数组(除非显式传入)。
"""
from __future__ import annotations
from copy import deepcopy
from datetime import datetime, timezone
from typing import Any
from ebook_svc.services.tt_platform_config import resolve_config_file
PAGE_KEYS = (
"index",
"chat",
"date",
"people",
"peopleProfile",
"roster",
"meetup",
"meetupLive",
"team",
)
SECTION_KEYS = (
"people",
"date",
"meetup",
"cities",
"team",
"ways",
"promo",
"invite",
)
FEATURE_KEYS = (
"joinPay",
"cafeReviews",
"creationSheet",
"chatRealtime",
"livePusher",
"dateSwipe",
"rosterEdit",
"teamApply",
"dock",
"homeEntry",
"avatarFaceCheck",
)
BUTTON_KEYS = (
"heroJoin",
"heroChat",
"heroDate",
"heroStory",
"wayGroup",
"wayDate",
"wayMeetup",
"wayCafe",
"wayTeam",
"dockHome",
"dockChat",
"dockDate",
"dockPeople",
"dockRoster",
)
COPY_KEYS = (
"socialEyebrow",
"socialHeroLine1",
"socialHeroAccent",
"socialHeroLead",
"socialJoinCta",
"socialInviteTitle",
"socialInviteLead",
"socialOnlineTitle",
"socialOfflineTitle",
"socialTeamTitle",
"socialWayGroup",
"socialWayChat",
"socialWayDate",
"socialWayCafe",
"socialWayTeam",
"socialPromoUrl",
)
PAGE_META = {
"index": ("社区首页", "pages/social/index"),
"chat": ("游民大厅", "pages/social/chat"),
"date": ("认识一下", "pages/social/date"),
"people": ("想见的人", "pages/social/people"),
"peopleProfile": ("成员详情", "pages/social/people/profile"),
"roster": ("我的介绍", "pages/social/roster"),
"meetup": ("视频场次", "pages/social/meetup"),
"meetupLive": ("语音视频厅", "pages/social/meetup-live"),
"team": ("找搭子/共创", "pages/social/team"),
}
SECTION_META = {
"people": "首页 · 成员目录",
"date": "首页 · 认识一下",
"meetup": "首页 · 语音视频",
"cities": "首页 · 同城见面",
"team": "首页 · 团队共创",
"ways": "首页 · 连接方式卡片",
"promo": "首页 · 宣传片/故事",
"invite": "首页 · 底部邀请",
}
FEATURE_META = {
"joinPay": "加群虚拟支付底栏",
"cafeReviews": "咖啡馆评价",
"creationSheet": "共创/视频详情抽屉",
"chatRealtime": "大厅实时消息",
"livePusher": "原生推流预览",
"dateSwipe": "认识一下滑卡",
"rosterEdit": "编辑我的介绍",
"teamApply": "共创报名表单",
"dock": "底部 SocialDock",
"homeEntry": "小程序首页「游民社区」入口",
"avatarFaceCheck": "头像上传人脸检测(关=可任意图;开=强制正脸)",
}
BUTTON_META = {
"heroJoin": "首屏主 CTA(加群)",
"heroChat": "首屏 · 群组聊天",
"heroDate": "首屏 · 认识一下",
"heroStory": "首屏 · 社区故事",
"wayGroup": "方式卡 · 群聊",
"wayDate": "方式卡 · 认识",
"wayMeetup": "方式卡 · 视频",
"wayCafe": "方式卡 · 同城",
"wayTeam": "方式卡 · 共创",
"dockHome": "Dock · 首页",
"dockChat": "Dock · 聊天",
"dockDate": "Dock · 认识",
"dockPeople": "Dock · 看看谁",
"dockRoster": "Dock · 我",
}
DEFAULT_COPY = {
"socialEyebrow": "自由生活,同频相遇",
"socialHeroLine1": "世界很大,",
"socialHeroAccent": "同类",
"socialHeroLead": "换一座城市,不必重新孤独。\n从一句你好、一杯咖啡开始,找到一起生活、\n一起探索、一起做点什么的人。",
"socialJoinCta": "找到我的同频",
"socialInviteTitle": "下一站,和同类一起。",
"socialInviteLead": "无论你正在出发,还是已经在路上,这里都有一个属于你的位置。",
"socialOnlineTitle": "随时,聊得来",
"socialOfflineTitle": "同城,见一面",
"socialTeamTitle": "一起,做点事",
"socialWayGroup": "群组聊天",
"socialWayChat": "开视频聊聊",
"socialWayDate": "认识一下",
"socialWayCafe": "找个地方见面",
"socialWayTeam": "找搭子 · 共创",
"socialPromoUrl": "",
}
def _all_true(keys: tuple[str, ...]) -> dict[str, bool]:
return {k: True for k in keys}
def _read_raw() -> dict[str, Any]:
path = resolve_config_file()
if not path.is_file():
return {}
try:
import json
raw = json.loads(path.read_text(encoding="utf-8"))
return raw if isinstance(raw, dict) else {}
except Exception:
return {}
def _write_raw(out: dict[str, Any]) -> None:
import json
path = resolve_config_file()
path.parent.mkdir(parents=True, exist_ok=True)
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
try:
out["version"] = int(out.get("version") or 1) + 1
except Exception:
out["version"] = 2
if path.is_file():
bak = path.with_suffix(path.suffix + f".bak-social-{out['updatedAt'].replace(':', '-')}")
try:
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
except Exception:
pass
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
try:
from ebook_svc.services.config_live import notify_config_written
notify_config_written(out)
except Exception:
pass
def _bool_map(raw: Any, keys: tuple[str, ...], default: bool = True) -> dict[str, bool]:
src = raw if isinstance(raw, dict) else {}
out: dict[str, bool] = {}
for k in keys:
if k in src:
out[k] = bool(src[k])
else:
out[k] = default
return out
def _norm_flags(raw: Any) -> dict[str, dict[str, bool]]:
src = raw if isinstance(raw, dict) else {}
features = _bool_map(src.get("features"), FEATURE_KEYS, True)
# Test-phase default: face check OFF unless explicitly enabled
feat_src = src.get("features") if isinstance(src.get("features"), dict) else {}
if "avatarFaceCheck" not in feat_src:
features["avatarFaceCheck"] = False
return {
"pages": _bool_map(src.get("pages"), PAGE_KEYS, True),
"sections": _bool_map(src.get("sections"), SECTION_KEYS, True),
"features": features,
"buttons": _bool_map(src.get("buttons"), BUTTON_KEYS, True),
}
def _hidden_from_sections(sections: dict[str, bool]) -> list[str]:
return [k for k, on in sections.items() if not on]
def _sections_from_hidden(hidden: Any, base: dict[str, bool]) -> dict[str, bool]:
out = dict(base)
if not isinstance(hidden, list):
return out
for item in hidden:
if isinstance(item, str) and item in out:
out[item] = False
return out
def read_social_ops() -> dict[str, Any]:
raw = _read_raw()
modules = raw.get("modules") if isinstance(raw.get("modules"), dict) else {}
social_mod = modules.get("social") if isinstance(modules.get("social"), dict) else {}
copy_raw = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
flags = _norm_flags(copy_raw.get("socialFlags"))
# 兼容旧 socialHiddenSections
flags["sections"] = _sections_from_hidden(
copy_raw.get("socialHiddenSections"), flags["sections"]
)
top_flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
if "socialAvatarFaceCheck" in top_flags:
flags["features"]["avatarFaceCheck"] = bool(top_flags.get("socialAvatarFaceCheck"))
copy_out: dict[str, str] = {}
for k in COPY_KEYS:
v = copy_raw.get(k)
copy_out[k] = str(v).strip() if isinstance(v, str) else str(DEFAULT_COPY.get(k) or "")
pages_meta = copy_raw.get("socialPages") if isinstance(copy_raw.get("socialPages"), dict) else {}
return {
"ok": True,
"moduleEnabled": social_mod.get("enabled", True) is not False,
"moduleTitle": str(social_mod.get("title") or "游民社区"),
"flags": flags,
"copy": copy_out,
"pageCopy": pages_meta,
"meta": {
"pages": PAGE_META,
"sections": SECTION_META,
"features": FEATURE_META,
"buttons": BUTTON_META,
"copyKeys": {k: k for k in COPY_KEYS},
},
"version": raw.get("version"),
"updatedAt": raw.get("updatedAt"),
"configPath": str(resolve_config_file()),
}
def write_social_ops(patch: dict[str, Any]) -> dict[str, Any]:
raw = _read_raw()
out: dict[str, Any] = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
modules = dict(out.get("modules") or {})
copy = dict(out.get("copy") or {})
flags = _norm_flags(copy.get("socialFlags"))
flags["sections"] = _sections_from_hidden(copy.get("socialHiddenSections"), flags["sections"])
if "moduleEnabled" in patch:
prev = modules.get("social") if isinstance(modules.get("social"), dict) else {}
modules["social"] = {
**{
"enabled": True,
"title": "游民社区",
"tabLabel": "社区",
"note": "Taro 原生 pages/social",
},
**prev,
"enabled": bool(patch["moduleEnabled"]),
}
if isinstance(patch.get("flags"), dict):
fp = patch["flags"]
for group in ("pages", "sections", "features", "buttons"):
if isinstance(fp.get(group), dict):
keys = {
"pages": PAGE_KEYS,
"sections": SECTION_KEYS,
"features": FEATURE_KEYS,
"buttons": BUTTON_KEYS,
}[group]
for k, v in fp[group].items():
if k in keys:
flags[group][k] = bool(v)
if isinstance(patch.get("copy"), dict):
for k, v in patch["copy"].items():
if k in COPY_KEYS and v is not None:
copy[k] = str(v)
if isinstance(patch.get("pageCopy"), dict):
pages = copy.get("socialPages") if isinstance(copy.get("socialPages"), dict) else {}
pages = dict(pages)
for pid, val in patch["pageCopy"].items():
if not isinstance(pid, str) or not pid:
continue
if val is None:
pages.pop(pid, None)
continue
if not isinstance(val, dict):
continue
cur = dict(pages.get(pid) or {}) if isinstance(pages.get(pid), dict) else {}
for field in ("eyebrow", "title", "accent", "description"):
if field in val and val[field] is not None:
cur[field] = str(val[field]).strip()
pages[pid] = cur
copy["socialPages"] = pages
copy["socialFlags"] = flags
copy["socialHiddenSections"] = _hidden_from_sections(flags["sections"])
# Mirror to top-level flags for portal SSE clients + social_svc upload gate
top_flags = dict(out.get("flags") or {}) if isinstance(out.get("flags"), dict) else {}
top_flags["socialAvatarFaceCheck"] = bool(flags["features"].get("avatarFaceCheck"))
out["flags"] = top_flags
out["modules"] = modules
out["copy"] = copy
_write_raw(out)
return read_social_ops()