Gate /social/work behind join/login/profile; harden Work UX and LanguageSwitcher SSR; deploy portal, admin, and work API. Co-authored-by: Cursor <cursoragent@cursor.com>
476 lines
18 KiB
Python
476 lines
18 KiB
Python
"""微信小程序「开关」— modules / flags / copy / VIP 区块 / 小册审核模式。
|
||
|
||
写入 remote-config.json;不碰 platforms.tt、订单与 PocketBase。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import tempfile
|
||
from copy import deepcopy
|
||
from datetime import datetime, timezone
|
||
from typing import Any
|
||
|
||
from ebook_svc.services.store import store
|
||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||
from ebook_svc.services.vip_content import (
|
||
apply_vip_content_patch,
|
||
read_vip_content_from_raw,
|
||
)
|
||
|
||
DEFAULT_BOOK_AUDIT: dict[str, Any] = {
|
||
"reviewMode": False,
|
||
"bookId": "audit",
|
||
}
|
||
|
||
MODULE_KEYS = (
|
||
"home",
|
||
"nav",
|
||
"book",
|
||
"community",
|
||
"social",
|
||
"socialBlog",
|
||
"vip",
|
||
"destinations",
|
||
"meetups",
|
||
)
|
||
|
||
DEFAULT_MODULES: dict[str, dict[str, Any]] = {
|
||
"home": {"enabled": True, "title": "首页", "tabLabel": "首页"},
|
||
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
|
||
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
|
||
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
|
||
# 对齐线上 remote-config:游民社区 / pages/social/index;缺省开启,写入只改 enabled
|
||
"social": {
|
||
"enabled": True,
|
||
"title": "游民社区",
|
||
"tabLabel": "社区",
|
||
"note": "Taro 原生 pages/social · 开关不碰业务库",
|
||
},
|
||
"socialBlog": {
|
||
"enabled": True,
|
||
"title": "Nomad Blog",
|
||
"tabLabel": "Blog",
|
||
"note": "/social/blog · EN long-form · AdSense",
|
||
},
|
||
"vip": {"enabled": False, "title": "会员中心"},
|
||
"destinations": {"enabled": True, "title": "目的地"},
|
||
"meetups": {"enabled": True, "title": "活动"},
|
||
"game": {"enabled": False, "title": "数字游民", "note": "冻结隐藏 · 勿开入口"},
|
||
}
|
||
|
||
VIP_ENTRY_BOOLS = (
|
||
"showStats",
|
||
"showTopics",
|
||
"showVideos",
|
||
"showEbooks",
|
||
"showCompare",
|
||
"showFaq",
|
||
"showCta",
|
||
"reviewMode",
|
||
)
|
||
|
||
|
||
DEFAULT_SOCIAL_TRIAL: dict[str, Any] = {
|
||
"enabled": True,
|
||
"chatMessages": 1,
|
||
"dateViews": 5,
|
||
"coffeeBookings": 0,
|
||
"mapOpens": 3,
|
||
}
|
||
|
||
|
||
def _social_trial(raw: Any) -> dict[str, Any]:
|
||
base = dict(DEFAULT_SOCIAL_TRIAL)
|
||
if not isinstance(raw, dict):
|
||
return base
|
||
if "enabled" in raw:
|
||
base["enabled"] = bool(raw["enabled"])
|
||
for k in ("chatMessages", "dateViews", "coffeeBookings", "mapOpens"):
|
||
if k in raw and raw[k] is not None:
|
||
try:
|
||
base[k] = max(0, int(raw[k]))
|
||
except (TypeError, ValueError):
|
||
pass
|
||
return base
|
||
|
||
|
||
DEFAULT_SOCIAL_LIVE: dict[str, Any] = {
|
||
"presenceEnabled": True,
|
||
"presenceStrip": True,
|
||
"presenceCityScope": True,
|
||
"discoveryAutoRefresh": True,
|
||
"discoveryRefreshSec": 45,
|
||
"configHotReloadToast": True,
|
||
"offlineFallbackShell": True,
|
||
"hideNoFaceAvatar": True,
|
||
"livenessGate": True,
|
||
"trackLiveEvents": True,
|
||
"chatPresencePill": True,
|
||
"mapLivePins": True,
|
||
"joinPriceLive": True,
|
||
"onlineCountBadge": True,
|
||
"softStatusSync": True,
|
||
"configVersionChip": False,
|
||
"trialLive": True,
|
||
"presenceHeartbeatSec": 25,
|
||
}
|
||
|
||
|
||
def _social_live(raw: Any) -> dict[str, Any]:
|
||
base = dict(DEFAULT_SOCIAL_LIVE)
|
||
if not isinstance(raw, dict):
|
||
return base
|
||
for k, default in DEFAULT_SOCIAL_LIVE.items():
|
||
if k not in raw or raw[k] is None:
|
||
continue
|
||
if isinstance(default, bool):
|
||
base[k] = bool(raw[k])
|
||
elif isinstance(default, int):
|
||
try:
|
||
n = int(raw[k])
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if k.endswith("Sec"):
|
||
lo, hi = (15, 300) if k == "discoveryRefreshSec" else (10, 120)
|
||
base[k] = max(lo, min(hi, n))
|
||
else:
|
||
base[k] = max(0, n)
|
||
return base
|
||
|
||
|
||
def _vip_price_fen(raw: Any, fallback: int = 10) -> int:
|
||
try:
|
||
return max(0, int(raw))
|
||
except Exception:
|
||
return max(0, int(fallback))
|
||
|
||
|
||
def _read_raw() -> dict[str, Any]:
|
||
path = resolve_config_file()
|
||
if not path.is_file():
|
||
return {}
|
||
try:
|
||
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:
|
||
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-{out['updatedAt'].replace(':', '-')}")
|
||
try:
|
||
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
|
||
except Exception:
|
||
pass
|
||
temporary = None
|
||
try:
|
||
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
|
||
prefix=path.name + '.', suffix='.tmp', delete=False) as handle:
|
||
temporary = handle.name
|
||
handle.write(json.dumps(out, ensure_ascii=False, indent=2) + '\n')
|
||
handle.flush()
|
||
os.fsync(handle.fileno())
|
||
if path.exists():
|
||
os.chmod(temporary, path.stat().st_mode & 0o777)
|
||
if hasattr(os, 'chown'):
|
||
info = path.stat()
|
||
os.chown(temporary, info.st_uid, info.st_gid)
|
||
os.replace(temporary, path)
|
||
finally:
|
||
if temporary and os.path.exists(temporary):
|
||
os.unlink(temporary)
|
||
try:
|
||
from ebook_svc.services.config_live import notify_config_written
|
||
|
||
notify_config_written(out)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _norm_mod(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
|
||
m = raw if isinstance(raw, dict) else {}
|
||
out = deepcopy(fallback)
|
||
if "enabled" in m:
|
||
out["enabled"] = bool(m["enabled"])
|
||
if m.get("title"):
|
||
out["title"] = str(m["title"]).strip() or out["title"]
|
||
if "tabLabel" in m and m["tabLabel"] is not None:
|
||
out["tabLabel"] = str(m["tabLabel"]).strip()
|
||
if "note" in m and m["note"] is not None:
|
||
out["note"] = str(m["note"]).strip()
|
||
return out
|
||
|
||
|
||
def read_book_audit(raw: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
data = raw if raw is not None else _read_raw()
|
||
platforms = data.get("platforms") if isinstance(data.get("platforms"), dict) else {}
|
||
weapp = platforms.get("weapp") if isinstance(platforms.get("weapp"), dict) else {}
|
||
ba = weapp.get("bookAudit") if isinstance(weapp.get("bookAudit"), dict) else {}
|
||
book_id = str(ba.get("bookId") or DEFAULT_BOOK_AUDIT["bookId"]).strip() or "audit"
|
||
return {
|
||
"reviewMode": bool(ba.get("reviewMode")),
|
||
"bookId": book_id,
|
||
}
|
||
|
||
|
||
def read_weapp_switches() -> dict[str, Any]:
|
||
raw = _read_raw()
|
||
modules_raw = raw.get("modules") if isinstance(raw.get("modules"), dict) else {}
|
||
flags_raw = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
|
||
copy_raw = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
|
||
|
||
modules: dict[str, Any] = {}
|
||
for key in MODULE_KEYS:
|
||
modules[key] = _norm_mod(modules_raw.get(key), DEFAULT_MODULES[key])
|
||
# game 只读展示(强制关)
|
||
modules["game"] = {
|
||
**DEFAULT_MODULES["game"],
|
||
"enabled": False,
|
||
}
|
||
|
||
vip_content = read_vip_content_from_raw(raw)
|
||
vip_entries = {k: bool(vip_content.get(k)) for k in VIP_ENTRY_BOOLS}
|
||
|
||
return {
|
||
"ok": True,
|
||
"modules": modules,
|
||
"flags": {
|
||
"payEnabled": flags_raw.get("payEnabled", True) is not False,
|
||
"socialFollow": flags_raw.get("socialFollow", True) is not False,
|
||
"offlineBadge": bool(flags_raw.get("offlineBadge")),
|
||
"joinGroupAction": (
|
||
"vip" if flags_raw.get("joinGroupAction") == "vip" else "popup"
|
||
),
|
||
"memoTrialBrowse": flags_raw.get("memoTrialBrowse", True) is not False,
|
||
"joinGroupWechat": flags_raw.get("joinGroupWechat", True) is not False,
|
||
# AdSense: default off until publisher approval
|
||
"adsenseEnabled": bool(flags_raw.get("adsenseEnabled")),
|
||
"adsenseClientId": str(flags_raw.get("adsenseClientId") or ""),
|
||
"adsensePublisherId": str(flags_raw.get("adsensePublisherId") or ""),
|
||
"adsenseSlotBlogMid": str(flags_raw.get("adsenseSlotBlogMid") or ""),
|
||
"adsenseSlotBlogEnd": str(flags_raw.get("adsenseSlotBlogEnd") or ""),
|
||
"gaEnabled": flags_raw.get("gaEnabled", True) is not False,
|
||
"gaMeasurementId": str(flags_raw.get("gaMeasurementId") or ""),
|
||
"googleAdsId": str(flags_raw.get("googleAdsId") or ""),
|
||
"googleAdsConversionLabel": str(
|
||
flags_raw.get("googleAdsConversionLabel") or ""
|
||
),
|
||
"googleSiteVerification": str(
|
||
flags_raw.get("googleSiteVerification") or ""
|
||
),
|
||
"socialAvatarFaceCheck": bool(flags_raw.get("socialAvatarFaceCheck")),
|
||
"socialTrialEnabled": flags_raw.get("socialTrialEnabled", True) is not False,
|
||
"socialLive": _social_live(flags_raw.get("socialLive")),
|
||
},
|
||
"copy": {
|
||
"homeBrand": str(copy_raw.get("homeBrand") or "nomadro"),
|
||
"homeTagline": str(copy_raw.get("homeTagline") or ""),
|
||
"homeLead": str(copy_raw.get("homeLead") or ""),
|
||
"vipCta": str(copy_raw.get("vipCta") or "立即加入"),
|
||
"vipPriceFen": _vip_price_fen(copy_raw.get("vipPriceFen")),
|
||
"vipProductId": str(copy_raw.get("vipProductId") or "tiktok"),
|
||
"wechatOaName": str(copy_raw.get("wechatOaName") or "异度世界"),
|
||
"memoUnlockCta": str(copy_raw.get("memoUnlockCta") or "解锁 VIP 读全文"),
|
||
"xHandle": str(copy_raw.get("xHandle") or ""),
|
||
"socialTrial": _social_trial(copy_raw.get("socialTrial")),
|
||
},
|
||
"vipEntries": vip_entries,
|
||
"vipHero": {
|
||
"heroEyebrow": str(vip_content.get("heroEyebrow") or ""),
|
||
"heroTitleAccent": str(vip_content.get("heroTitleAccent") or ""),
|
||
"heroTitleRest": str(vip_content.get("heroTitleRest") or ""),
|
||
"heroLead": str(vip_content.get("heroLead") or ""),
|
||
},
|
||
"bookAudit": read_book_audit(raw),
|
||
"version": raw.get("version"),
|
||
"updatedAt": raw.get("updatedAt"),
|
||
"configPath": str(resolve_config_file()),
|
||
}
|
||
|
||
|
||
def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]:
|
||
raw = _read_raw()
|
||
out: dict[str, Any] = (
|
||
dict(raw) if raw else {"version": 2, "modules": {}, "flags": {}, "copy": {}}
|
||
)
|
||
modules = dict(out.get("modules") or {})
|
||
flags = dict(out.get("flags") or {})
|
||
copy = dict(out.get("copy") or {})
|
||
|
||
if isinstance(patch.get("modules"), dict):
|
||
for key, val in patch["modules"].items():
|
||
if key == "game":
|
||
modules["game"] = {**DEFAULT_MODULES["game"], "enabled": False}
|
||
continue
|
||
if key not in MODULE_KEYS:
|
||
continue
|
||
if not isinstance(val, dict):
|
||
continue
|
||
base = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
|
||
modules[key] = _norm_mod(val, base)
|
||
|
||
# 防止补丁写入后兄弟模块丢失 / 首页入口被清空:始终补齐 MODULE_KEYS
|
||
for key in MODULE_KEYS:
|
||
modules[key] = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
|
||
modules["game"] = {**DEFAULT_MODULES["game"], "enabled": False}
|
||
|
||
if isinstance(patch.get("flags"), dict):
|
||
fp = patch["flags"]
|
||
if "payEnabled" in fp:
|
||
flags["payEnabled"] = bool(fp["payEnabled"])
|
||
if "socialFollow" in fp:
|
||
flags["socialFollow"] = bool(fp["socialFollow"])
|
||
if "offlineBadge" in fp:
|
||
flags["offlineBadge"] = bool(fp["offlineBadge"])
|
||
if "memoTrialBrowse" in fp:
|
||
flags["memoTrialBrowse"] = bool(fp["memoTrialBrowse"])
|
||
if "joinGroupWechat" in fp:
|
||
flags["joinGroupWechat"] = bool(fp["joinGroupWechat"])
|
||
if "joinGroupAction" in fp:
|
||
flags["joinGroupAction"] = (
|
||
"vip" if fp["joinGroupAction"] == "vip" else "popup"
|
||
)
|
||
if "adsenseEnabled" in fp:
|
||
flags["adsenseEnabled"] = bool(fp["adsenseEnabled"])
|
||
if "gaEnabled" in fp:
|
||
flags["gaEnabled"] = bool(fp["gaEnabled"])
|
||
if "socialAvatarFaceCheck" in fp:
|
||
flags["socialAvatarFaceCheck"] = bool(fp["socialAvatarFaceCheck"])
|
||
if "socialTrialEnabled" in fp:
|
||
flags["socialTrialEnabled"] = bool(fp["socialTrialEnabled"])
|
||
if "socialLive" in fp and fp["socialLive"] is not None:
|
||
prev = flags.get("socialLive") if isinstance(flags.get("socialLive"), dict) else {}
|
||
incoming = fp["socialLive"] if isinstance(fp["socialLive"], dict) else {}
|
||
flags["socialLive"] = _social_live({**prev, **incoming})
|
||
for ak in (
|
||
"adsenseClientId",
|
||
"adsensePublisherId",
|
||
"adsenseSlotBlogMid",
|
||
"adsenseSlotBlogEnd",
|
||
"gaMeasurementId",
|
||
"googleAdsId",
|
||
"googleAdsConversionLabel",
|
||
"googleSiteVerification",
|
||
):
|
||
if ak in fp and fp[ak] is not None:
|
||
flags[ak] = str(fp[ak]).strip()
|
||
# 规范化 ID 大小写 + AdSense publisher 自动补全
|
||
if flags.get("gaMeasurementId"):
|
||
flags["gaMeasurementId"] = str(flags["gaMeasurementId"]).upper()
|
||
if flags.get("googleAdsId"):
|
||
flags["googleAdsId"] = str(flags["googleAdsId"]).upper()
|
||
client = str(flags.get("adsenseClientId") or "").lower()
|
||
if client:
|
||
flags["adsenseClientId"] = client
|
||
if client.startswith("ca-pub-") and not str(flags.get("adsensePublisherId") or ""):
|
||
flags["adsensePublisherId"] = client[3:]
|
||
elif flags.get("adsensePublisherId"):
|
||
flags["adsensePublisherId"] = str(flags["adsensePublisherId"]).lower()
|
||
|
||
if isinstance(patch.get("copy"), dict):
|
||
cp = patch["copy"]
|
||
for k in (
|
||
"homeBrand",
|
||
"homeTagline",
|
||
"homeLead",
|
||
"vipCta",
|
||
"vipProductId",
|
||
"wechatOaName",
|
||
"memoUnlockCta",
|
||
"xHandle",
|
||
):
|
||
if k in cp and cp[k] is not None:
|
||
copy[k] = str(cp[k]).strip()
|
||
if "socialTrial" in cp and cp["socialTrial"] is not None:
|
||
prev = copy.get("socialTrial") if isinstance(copy.get("socialTrial"), dict) else {}
|
||
merged = {**DEFAULT_SOCIAL_TRIAL, **prev}
|
||
if isinstance(cp["socialTrial"], dict):
|
||
st = cp["socialTrial"]
|
||
if "enabled" in st:
|
||
merged["enabled"] = bool(st["enabled"])
|
||
for k in ("chatMessages", "dateViews", "coffeeBookings", "mapOpens"):
|
||
if k in st and st[k] is not None:
|
||
try:
|
||
merged[k] = max(0, int(st[k]))
|
||
except (TypeError, ValueError):
|
||
pass
|
||
copy["socialTrial"] = merged
|
||
# Keep flag in sync when copy carries enabled
|
||
if "enabled" in merged:
|
||
flags["socialTrialEnabled"] = bool(merged["enabled"])
|
||
if "vipPriceFen" in cp and cp["vipPriceFen"] is not None:
|
||
copy["vipPriceFen"] = _vip_price_fen(cp["vipPriceFen"])
|
||
# 同步受众轨 CTA,避免 lane 文案卡在旧价
|
||
fen = int(copy["vipPriceFen"])
|
||
yuan = fen / 100.0
|
||
price_txt = (
|
||
"免费"
|
||
if fen <= 0
|
||
else (f"¥{int(yuan)}" if fen % 100 == 0 else f"¥{yuan:.2f}")
|
||
)
|
||
cn_cta = "免费加入" if fen <= 0 else f"立即加入 · {price_txt}"
|
||
intl_cta = "Join free" if fen <= 0 else f"Join VIP · {price_txt.replace('¥', '$')}"
|
||
audience = dict(out.get("audience") or {})
|
||
for lane_key, cta in (("cn", cn_cta), ("intl", intl_cta)):
|
||
lane = dict(audience.get(lane_key) or {})
|
||
lane["vipCta"] = cta
|
||
audience[lane_key] = lane
|
||
if "defaultLane" not in audience:
|
||
audience["defaultLane"] = "intl"
|
||
out["audience"] = audience
|
||
|
||
out["modules"] = modules
|
||
out["flags"] = flags
|
||
out["copy"] = copy
|
||
|
||
# VIP 入口区块 + hero 文案 → platforms.weapp.vipContent
|
||
vip_patch: dict[str, Any] = {}
|
||
if isinstance(patch.get("vipEntries"), dict):
|
||
for k in VIP_ENTRY_BOOLS:
|
||
if k in patch["vipEntries"]:
|
||
vip_patch[k] = bool(patch["vipEntries"][k])
|
||
if isinstance(patch.get("vipHero"), dict):
|
||
for k in ("heroEyebrow", "heroTitleAccent", "heroTitleRest", "heroLead"):
|
||
if k in patch["vipHero"] and patch["vipHero"][k] is not None:
|
||
vip_patch[k] = str(patch["vipHero"][k]).strip()
|
||
if vip_patch:
|
||
out = apply_vip_content_patch(out, vip_patch)
|
||
|
||
# 小册审核模式 → platforms.weapp.bookAudit(不碰 tt)
|
||
if isinstance(patch.get("bookAudit"), dict):
|
||
platforms = dict(out.get("platforms") or {})
|
||
weapp = dict(platforms.get("weapp") or {})
|
||
prev = weapp.get("bookAudit") if isinstance(weapp.get("bookAudit"), dict) else {}
|
||
ba = {**DEFAULT_BOOK_AUDIT, **prev}
|
||
bp = patch["bookAudit"]
|
||
if "reviewMode" in bp:
|
||
ba["reviewMode"] = bool(bp["reviewMode"])
|
||
if "bookId" in bp and bp["bookId"] is not None:
|
||
bid = str(bp["bookId"]).strip() or "audit"
|
||
ba["bookId"] = bid[:64]
|
||
weapp["bookAudit"] = ba
|
||
platforms["weapp"] = weapp
|
||
out["platforms"] = platforms
|
||
# 确保审核书存在(免费全文,与 default 隔离)
|
||
try:
|
||
store.ensure_book(
|
||
str(ba["bookId"]),
|
||
title="数字游民·提审版",
|
||
subtitle="仅给微信审核员看 · 与正式会员书无关",
|
||
free=True,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
_write_raw(out)
|
||
return read_weapp_switches()
|