Merge stash WIP onto BMI A/B: join-group, live config, channel tracking.

Keep Douyin homeVariant BMI router intact while restoring admin join-group controls, TLS-safe config fetch, and ntfy channel labels.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-10-03 15:42:09 +08:00
parent 0e85d71386
commit 534400f554
69 changed files with 2998 additions and 370 deletions

View File

@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Deploy join-group admin UI + API to 82.157.112.245 (admin.nomadro.cn / nomadmini-api)."""
from __future__ import annotations
import io
import re
import tarfile
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1] # apps/admin
REPO = ROOT.parents[1] # nomadro
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf jg-unpack && mkdir jg-unpack
tar -xzf jg-release.tar.gz -C jg-unpack
# --- admin SPA ---
if [ -d jg-unpack/admin-dist ]; then
sudo rsync -a --delete jg-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_dist_synced
fi
# --- API files ---
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then
API_ROOT=/opt/nomadmini/backend
fi
echo API_ROOT=$API_ROOT
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
sudo mkdir -p "$B/routers" "$B/services"
sudo cp jg-unpack/backend/routers/join_group_admin.py "$B/routers/"
sudo cp jg-unpack/backend/services/join_group_config.py "$B/services/"
# patch main.py to include join_group_admin (idempotent)
MAIN="$B/main.py"
sudo python3 <<PY
from pathlib import Path
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
if "join_group_admin" not in t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track",
)
if t2 == t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, pay, track\n",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track\n",
)
t = t2
if "join_group_admin" not in t:
raise SystemExit("failed to patch import in main.py")
changed = True
if "include_router(join_group_admin.router)" not in t:
needle = "app.include_router(douyin_admin.router)"
if needle not in t:
raise SystemExit("douyin_admin include missing")
t = t.replace(
needle,
needle + "\napp.include_router(join_group_admin.router)",
1,
)
changed = True
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
# additive flags on portal remote-config (never wipe platforms/modules)
CFG=/var/www/nomadro.cn/data/remote-config.json
if [ -f "$CFG" ]; then
sudo python3 <<'PY'
import json
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
cfg = json.loads(p.read_text(encoding="utf-8"))
flags = cfg.setdefault("flags", {})
copy = cfg.setdefault("copy", {})
changed = False
defaults = {
"joinGroupWechat": True,
"joinGroupDouyin": False,
"socialFollowAuto": False,
}
for k, v in defaults.items():
if k not in flags:
flags[k] = v
changed = True
copy_defs = {
"wechatOaName": "异度世界",
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
"joinGroupDouyinQr": "",
}
for k, v in copy_defs.items():
if k not in copy:
copy[k] = v
changed = True
if changed:
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("remote-config flags seeded (additive)")
else:
print("remote-config flags already present")
print("flags=", {k: flags.get(k) for k in list(defaults)})
PY
fi
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
echo "--- smoke ---"
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
# login + join-group get
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" || true)
echo "token_len=${#TOK}"
if [ -n "$TOK" ]; then
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/join-group | python3 -c "import sys,json; d=json.load(sys.stdin); print('join-group', d.get('ok'), d.get('flags'))"
fi
curl -sk https://nomadro.cn/api/config | python3 -c "import sys,json; f=json.load(sys.stdin).get('config',{}).get('flags',{}); print('portal flags', {k:f.get(k) for k in ('joinGroupWechat','joinGroupDouyin','socialFollowAuto')})"
rm -rf jg-unpack jg-release.tar.gz
echo DONE
"""
def main() -> int:
dist = ROOT / "dist"
if not (dist / "index.html").exists():
print("missing apps/admin/dist — run pnpm build first")
return 1
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
router_src = (EBOOK / "routers" / "join_group_admin.py").read_text(encoding="utf-8")
svc_src = (EBOOK / "services" / "join_group_config.py").read_text(encoding="utf-8")
for name, text in (
("backend/routers/join_group_admin.py", to_app_pkg(router_src)),
("backend/services/join_group_config.py", to_app_pkg(svc_src)),
):
data = text.encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
payload = buf.getvalue()
print(f"pack {len(payload)/1024:.1f} KB", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/jg-release.tar.gz", "wb") as rf:
rf.write(payload)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command(REMOTE_SH, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
print(f"[exit {code}]", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Deploy public /api/config on dyapi/api (valid TLS) for Douyin 真机."""
from __future__ import annotations
import io
import tarfile
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf pc-unpack && mkdir pc-unpack
tar -xzf pc-release.tar.gz -C pc-unpack
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then
API_ROOT=/opt/nomadmini/backend
fi
echo API_ROOT=$API_ROOT
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
sudo mkdir -p "$B/routers"
sudo cp pc-unpack/backend/routers/public_config.py "$B/routers/"
MAIN="$B/main.py"
sudo python3 <<PY
from pathlib import Path
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
if "public_config" not in t:
for old in (
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track\n",
"from app.routers import admin, auth, books, douyin_admin, pay, track",
):
if old.strip() in t.replace("\r",""):
pass
if "join_group_admin" in t and "public_config" not in t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track",
)
if t2 == t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, pay, public_config, track",
)
t = t2
changed = True
if "public_config" not in t:
raise SystemExit("failed to patch import")
if "include_router(public_config.router)" not in t:
for needle in (
"app.include_router(join_group_admin.router)",
"app.include_router(douyin_admin.router)",
"app.include_router(admin.router)",
):
if needle in t:
t = t.replace(needle, needle + "\napp.include_router(public_config.router)", 1)
changed = True
break
else:
raise SystemExit("no include needle")
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
echo "--- smoke ---"
for u in \
https://dyapi.nomadro.cn/api/config \
https://api.nomadro.cn/api/config \
https://dyapi.nomadro.cn/api/config/meta \
https://api.nomadro.cn/api/config/meta
do
code=$(curl -s -o /tmp/pcbody.json -w '%{http_code}' -m 15 "$u" || echo ERR)
echo "$code $u"
python3 -c "import json; d=json.load(open('/tmp/pcbody.json')); c=d.get('config',d); f=(c.get('flags') or {}) if isinstance(c,dict) else {}; print(' ver', c.get('version') if isinstance(c,dict) else d.get('version'), 'wx', f.get('joinGroupWechat'), 'dy', f.get('joinGroupDouyin'))" 2>/dev/null || head -c 120 /tmp/pcbody.json; echo
done
rm -rf pc-unpack pc-release.tar.gz
"""
def main() -> None:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
src = (EBOOK / "routers" / "public_config.py").read_text(encoding="utf-8")
data = to_app_pkg(src).encode("utf-8")
info = tarfile.TarInfo(name="backend/routers/public_config.py")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
payload = buf.getvalue()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30)
sftp = c.open_sftp()
with sftp.file("/tmp/pc-release.tar.gz", "wb") as f:
f.write(payload)
with sftp.file("/tmp/pc-deploy.sh", "w") as f:
f.write(REMOTE_SH)
sftp.close()
print("uploaded, running remote…")
_, stdout, stderr = c.exec_command("bash /tmp/pc-deploy.sh", timeout=120)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
print(out)
if err.strip():
print("STDERR:", err)
c.close()
print("done", time.strftime("%H:%M:%S"))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Deploy track analytics + ntfy channel labels to nomadmini-api."""
from __future__ import annotations
import io
import tarfile
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
FILES = [
"routers/admin.py",
"services/track.py",
"services/store.py",
]
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf ta-unpack && mkdir ta-unpack
tar -xzf ta-release.tar.gz -C ta-unpack
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then
API_ROOT=/opt/nomadmini/backend
fi
echo API_ROOT=$API_ROOT
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
sudo mkdir -p "$B/routers" "$B/services"
sudo cp ta-unpack/backend/routers/admin.py "$B/routers/"
sudo cp ta-unpack/backend/services/track.py "$B/services/"
sudo cp ta-unpack/backend/services/store.py "$B/services/"
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
echo "--- smoke ---"
curl -s -X POST http://127.0.0.1:8010/api/track \
-H 'Content-Type: application/json' \
-d '{"events":[{"name":"page_view","page":"pages/index/index","label":"deploy-test","props":{"channel":"tt"}}],"client":"tt"}'
echo
curl -s -X POST http://127.0.0.1:8010/api/track \
-H 'Content-Type: application/json' \
-d '{"events":[{"name":"join_group_show","label":"公众号","props":{"popup":"wechat","channel":"weapp"}}],"client":"weapp"}'
echo
rm -rf ta-unpack ta-release.tar.gz
"""
def main() -> None:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel in FILES:
src = (EBOOK / rel).read_text(encoding="utf-8")
data = to_app_pkg(src).encode("utf-8")
info = tarfile.TarInfo(name=f"backend/{rel}")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
payload = buf.getvalue()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30)
sftp = c.open_sftp()
with sftp.file("/tmp/ta-release.tar.gz", "wb") as f:
f.write(payload)
with sftp.file("/tmp/ta-deploy.sh", "w") as f:
f.write(REMOTE_SH)
sftp.close()
print("uploaded, running remote…")
_, stdout, stderr = c.exec_command("bash /tmp/ta-deploy.sh", timeout=120)
print(stdout.read().decode("utf-8", errors="replace"))
err = stderr.read().decode("utf-8", errors="replace")
if err.strip():
print("STDERR:", err)
c.close()
print("done", time.strftime("%H:%M:%S"))
if __name__ == "__main__":
main()

View File

@ -15,6 +15,7 @@ import DouyinOverview from './pages/douyin/DouyinOverview'
import DouyinModules from './pages/douyin/DouyinModules'
import DouyinBook from './pages/douyin/DouyinBook'
import DouyinDocs from './pages/douyin/DouyinDocs'
import JoinGroupAdmin from './pages/JoinGroupAdmin'
function Private({ children }: { children: React.ReactNode }) {
if (!getToken()) return <Navigate to="/login" replace />
@ -32,8 +33,8 @@ function LegacyBookRedirect() {
/**
* https://admin.nomadro.cn
* - /wechat/* 微信电子书后台(原业务)
* - /douyin/* 抖音定制面板(入口开关 + Markdown,非微信复刻)
* - /wechat/* 微信电子书后台
* - /douyin/* 抖音定制面板(含加群引导)
* 门户 nomadro.cn/admin 是另一套系统
*/
export default function App() {
@ -50,6 +51,8 @@ export default function App() {
}
/>
<Route path="/join-group" element={<Navigate to="/douyin/join-group" replace />} />
<Route
path="/wechat"
element={
@ -64,6 +67,7 @@ export default function App() {
<Route path="users" element={<Users />} />
<Route path="events" element={<Events />} />
<Route path="checklist" element={<Checklist />} />
<Route path="join-group" element={<Navigate to="/douyin/join-group" replace />} />
</Route>
<Route
@ -77,6 +81,7 @@ export default function App() {
<Route index element={<DouyinOverview />} />
<Route path="modules" element={<DouyinModules />} />
<Route path="book" element={<DouyinBook />} />
<Route path="join-group" element={<JoinGroupAdmin />} />
<Route path="docs" element={<DouyinDocs />} />
</Route>

View File

@ -31,21 +31,30 @@ const FILTERS = [
'wx_push',
'error',
'app_launch',
'join_group_open',
'join_group_show',
'join_group_dismiss',
'join_group_qr_preview',
]
const CLIENTS = ['', 'tt', 'weapp', 'h5', 'miniapp', 'api', 'wx_push']
export default function Events() {
const [events, setEvents] = useState<TrackEvent[]>([])
const [filter, setFilter] = useState('')
const [clientFilter, setClientFilter] = useState('')
const [loading, setLoading] = useState(false)
const load = useCallback(() => {
setLoading(true)
const q = filter ? `?limit=200&name=${encodeURIComponent(filter)}` : '?limit=200'
api<TrackEvent[]>(`/api/admin/track-events${q}`)
const qs = new URLSearchParams({ limit: '200' })
if (filter) qs.set('name', filter)
if (clientFilter) qs.set('client', clientFilter)
api<TrackEvent[]>(`/api/admin/track-events?${qs}`)
.then(setEvents)
.catch(console.error)
.finally(() => setLoading(false))
}, [filter])
}, [filter, clientFilter])
useEffect(() => {
load()
@ -63,7 +72,7 @@ export default function Events() {
</button>
</header>
<div className="panel" style={{ marginBottom: 16 }}>
<div className="panel" style={{ marginBottom: 16, display: 'flex', flexWrap: 'wrap', gap: 16 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<span>筛选事件</span>
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
@ -74,6 +83,16 @@ export default function Events() {
))}
</select>
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<span>渠道</span>
<select value={clientFilter} onChange={(e) => setClientFilter(e.target.value)}>
{CLIENTS.map((c) => (
<option key={c || 'all'} value={c}>
{c === 'tt' ? '抖音' : c === 'weapp' ? '微信' : c === 'h5' ? 'H5' : c || '全部'}
</option>
))}
</select>
</label>
</div>
<div className="panel table-wrap">

View File

@ -0,0 +1,237 @@
import { useCallback, useEffect, useState } from 'react'
import { api } from '../api'
type JoinCfg = {
ok?: boolean
flags: {
joinGroupWechat: boolean
joinGroupDouyin: boolean
socialFollowAuto: boolean
}
copy: {
joinGroupDouyinHint: string
joinGroupDouyinQr: string
wechatOaName: string
}
updatedAt?: string
}
/**
* 加群引导 — 挂在抖音控制台内。
* 微信开 → 弹公众号;抖音开 → 弹抖音群。「稍后再说」= 关弹窗。
*/
export default function JoinGroupAdmin() {
const [cfg, setCfg] = useState<JoinCfg | null>(null)
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const [busy, setBusy] = useState(false)
const load = useCallback(async () => {
setErr('')
try {
const data = await api<JoinCfg>('/api/admin/join-group')
setCfg(data)
} catch (e) {
setErr(e instanceof Error ? e.message : String(e))
}
}, [])
useEffect(() => {
void load()
}, [load])
async function save() {
if (!cfg) return
setBusy(true)
setMsg('')
setErr('')
try {
const data = await api<JoinCfg>('/api/admin/join-group', {
method: 'PUT',
body: JSON.stringify({
flags: cfg.flags,
copy: cfg.copy,
}),
})
setCfg(data)
setMsg(`已保存 · ${data.updatedAt || 'OK'}`)
} catch (e) {
setErr(e instanceof Error ? e.message : String(e))
} finally {
setBusy(false)
}
}
if (!cfg && !err) return <div className="dy-skeleton">加载加群引导…</div>
return (
<div>
<header className="dy-head">
<div className="dy-head-copy">
<div className="dy-eyebrow">Join Group</div>
<h1>加群引导</h1>
<p>
用户点「加群」时按开关出弹窗。用户端没有开关,只改内容。「稍后再说」= 关闭。
</p>
</div>
<div className="dy-actions">
<button type="button" className="dy-btn" disabled={busy || !cfg} onClick={save}>
{busy ? '保存中…' : '保存'}
</button>
</div>
</header>
{err ? <p className="dy-err dy-toast">{err}</p> : null}
{msg ? <p className="dy-ok dy-toast">{msg}</p> : null}
{cfg ? (
<>
<section className="dy-panel">
<h2>渠道开关</h2>
<div className="dy-mod-list">
<div className={`dy-mod${cfg.flags.joinGroupWechat ? ' is-on' : ''}`}>
<div className="dy-mod-meta">
<div className="dy-mod-ico">💬</div>
<div className="dy-mod-text">
<strong>
微信公众号
<span className={`dy-mod-badge ${cfg.flags.joinGroupWechat ? 'on' : 'off'}`}>
{cfg.flags.joinGroupWechat ? '开' : '关'}
</span>
</strong>
<span>开 → 加群弹窗引导关注公众号</span>
</div>
</div>
<label className="dy-switch">
<input
type="checkbox"
checked={cfg.flags.joinGroupWechat}
onChange={(e) =>
setCfg({
...cfg,
flags: { ...cfg.flags, joinGroupWechat: e.target.checked },
})
}
/>
<span className="dy-switch-track">
<span className="dy-switch-thumb" />
</span>
</label>
</div>
<div className={`dy-mod${cfg.flags.joinGroupDouyin ? ' is-on' : ''}`}>
<div className="dy-mod-meta">
<div className="dy-mod-ico">🎵</div>
<div className="dy-mod-text">
<strong>
抖音群
<span className={`dy-mod-badge ${cfg.flags.joinGroupDouyin ? 'on' : 'off'}`}>
{cfg.flags.joinGroupDouyin ? '开' : '关'}
</span>
</strong>
<span>开 → 加群弹窗引导进抖音群</span>
</div>
</div>
<label className="dy-switch">
<input
type="checkbox"
checked={cfg.flags.joinGroupDouyin}
onChange={(e) =>
setCfg({
...cfg,
flags: { ...cfg.flags, joinGroupDouyin: e.target.checked },
})
}
/>
<span className="dy-switch-track">
<span className="dy-switch-thumb" />
</span>
</label>
</div>
<div className={`dy-mod${cfg.flags.socialFollowAuto ? ' is-on' : ''}`}>
<div className="dy-mod-meta">
<div className="dy-mod-ico">⏱</div>
<div className="dy-mod-text">
<strong>
自动弹出
<span className={`dy-mod-badge ${cfg.flags.socialFollowAuto ? 'on' : 'off'}`}>
{cfg.flags.socialFollowAuto ? '开' : '关'}
</span>
</strong>
<span>门户首页延迟自动弹(默认关)</span>
</div>
</div>
<label className="dy-switch">
<input
type="checkbox"
checked={cfg.flags.socialFollowAuto}
onChange={(e) =>
setCfg({
...cfg,
flags: { ...cfg.flags, socialFollowAuto: e.target.checked },
})
}
/>
<span className="dy-switch-track">
<span className="dy-switch-thumb" />
</span>
</label>
</div>
</div>
</section>
<section className="dy-panel">
<h2>文案 / 素材</h2>
<div className="dy-grid2" style={{ gap: 14 }}>
<label className="dy-label">
公众号名称
<input
className="dy-input"
value={cfg.copy.wechatOaName}
onChange={(e) =>
setCfg({ ...cfg, copy: { ...cfg.copy, wechatOaName: e.target.value } })
}
/>
</label>
<label className="dy-label">
抖音群提示文案
<input
className="dy-input"
value={cfg.copy.joinGroupDouyinHint}
onChange={(e) =>
setCfg({
...cfg,
copy: { ...cfg.copy, joinGroupDouyinHint: e.target.value },
})
}
/>
</label>
<label className="dy-label" style={{ gridColumn: '1 / -1' }}>
抖音群二维码 URL(可选)
<input
className="dy-input"
value={cfg.copy.joinGroupDouyinQr}
placeholder="https://… 或留空仅显示文案"
onChange={(e) =>
setCfg({
...cfg,
copy: { ...cfg.copy, joinGroupDouyinQr: e.target.value },
})
}
/>
</label>
</div>
</section>
<div className="dy-savebar">
<span className="dy-muted">保存后真机联网即时生效(无需发版)</span>
<button type="button" className="dy-btn" disabled={busy} onClick={save}>
{busy ? '保存中…' : '保存配置'}
</button>
</div>
</>
) : null}
</div>
)
}

View File

@ -2,6 +2,7 @@ import { useNavigate } from 'react-router-dom'
/**
* admin.nomadro.cn 登录后中间页(非 nomadro.cn/admin)。
* 只两扇门:微信 / 抖音。加群引导在抖音控制台内。
*/
export default function PlatformSelect() {
const nav = useNavigate()
@ -15,24 +16,27 @@ export default function PlatformSelect() {
<div>
<h1>选择管理端</h1>
<p>
<code>admin.nomadro.cn</code> · 微信运营后台 / 抖音定制面板相互隔离
<code>admin.nomadro.cn</code> · 微信与抖音数据隔离
<br />
<span style={{ opacity: 0.75 }}>门户统一后台:nomadro.cn/admin(另一套)</span>
<span className="platform-brand-note">门户统一后台:nomadro.cn/admin</span>
</p>
</div>
</div>
<div className="platform-grid">
<div className="platform-grid platform-grid--duo">
<button
type="button"
className="platform-card platform-card--wechat"
onClick={() => nav('/wechat')}
>
<span className="platform-emoji" aria-hidden>
💬
<span className="platform-card-top">
<span className="platform-ico platform-ico--wechat" aria-hidden>
💬
</span>
<span className="platform-badge">WeChat</span>
</span>
<strong>微信小程序</strong>
<span>读者 · 订单 · 试读% · 书籍(原虚拟支付业务)</span>
<span className="platform-desc">读者 · 订单 · 试读% · 书籍 · 埋点</span>
<span className="platform-cta">进入微信后台 →</span>
</button>
@ -41,11 +45,14 @@ export default function PlatformSelect() {
className="platform-card platform-card--douyin"
onClick={() => nav('/douyin')}
>
<span className="platform-emoji" aria-hidden>
🎵
<span className="platform-card-top">
<span className="platform-ico platform-ico--douyin" aria-hidden>
抖
</span>
<span className="platform-badge platform-badge--dy">Douyin</span>
</span>
<strong>抖音小程序</strong>
<span>入口开关 · 小册 Markdown · 抖音验收(定制面板,非微信复刻)</span>
<span className="platform-desc">入口开关 · 小册 · 加群引导 · 验收</span>
<span className="platform-cta">进入抖音控制台 →</span>
</button>
</div>

View File

@ -6,10 +6,11 @@ const NAV = [
{ to: '/douyin', end: true, ico: '◈', label: '总览' },
{ to: '/douyin/modules', end: false, ico: '⏻', label: '入口开关' },
{ to: '/douyin/book', end: false, ico: '✎', label: '小册 Markdown' },
{ to: '/douyin/join-group', end: false, ico: '👥', label: '加群引导' },
{ to: '/douyin/docs', end: false, ico: '✓', label: '开发与验收' },
] as const
/** 抖音定制壳 — 不复用微信概览/读者/订单 */
/** 抖音定制壳 — 加群引导属于本端 */
export default function DouyinLayout() {
const nav = useNavigate()
return (
@ -18,7 +19,7 @@ export default function DouyinLayout() {
<div className="dy-logo">
<span className="dy-mark">抖</span>
<div>
<div className="dy-title">Douyin 控制台</div>
<div className="dy-title">抖音控制台</div>
<div className="dy-sub">tt995defe · 运营面板</div>
</div>
</div>
@ -40,7 +41,7 @@ export default function DouyinLayout() {
</nav>
<div className="dy-side-foot">
<p className="dy-hint">只改 platforms.tt:首页 A/B、入口与小册正文。无道具、无虚拟支付。</p>
<p className="dy-hint">只改 platforms.tt:首页 A/B、入口、小册与加群。无道具、无虚拟支付。</p>
<button type="button" className="dy-ghost" onClick={() => nav('/')}>
← 切换平台
</button>

View File

@ -121,11 +121,15 @@ export default function DouyinOverview() {
<div className="dy-quick">
<Link to="/douyin/modules">
<strong>⏻ 入口开关</strong>
<span>导航 / 小册 / 社群 一键显隐,带手机预览</span>
<span>导航 / 小册 / 社群 显隐,带手机预览</span>
</Link>
<Link to="/douyin/join-group">
<strong>👥 加群引导</strong>
<span>公众号 / 抖音群弹窗开关与文案</span>
</Link>
<Link to="/douyin/book">
<strong>✎ 小册 Markdown</strong>
<span>远程改 7 章正文,抖音端下次拉取生效</span>
<span>远程改正文,真机下次拉取生效</span>
</Link>
<Link to="/douyin/docs">
<strong>✓ 开发验收</strong>

View File

@ -11,26 +11,25 @@
--dy-text: #f4f6fb;
--dy-muted: #8b93a8;
--dy-faint: #5c6478;
--dy-pink: #fe2c55;
--dy-cyan: #25f4ee;
--dy-ok: #3dffb5;
--dy-warn: #ffb020;
--dy-danger: #ff6b7a;
--dy-radius: 18px;
--dy-pink: #ff4d6d;
--dy-cyan: #2dd4bf;
--dy-ok: #34d399;
--dy-warn: #fbbf24;
--dy-danger: #f87171;
--dy-radius: 16px;
--dy-radius-sm: 12px;
--dy-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);
--dy-font: 'Sora', 'Syne', system-ui, sans-serif;
--dy-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
--dy-font: 'Sora', system-ui, sans-serif;
--dy-body: 'IBM Plex Sans', system-ui, sans-serif;
--dy-mono: 'IBM Plex Mono', ui-monospace, monospace;
--dy-side-w: 268px;
--dy-side-w: 250px;
min-height: 100vh;
display: grid;
grid-template-columns: var(--dy-side-w) 1fr;
background:
radial-gradient(900px 520px at -5% -10%, rgba(254, 44, 85, 0.16), transparent 55%),
radial-gradient(720px 480px at 105% 0%, rgba(37, 244, 238, 0.1), transparent 50%),
radial-gradient(500px 320px at 50% 100%, rgba(254, 44, 85, 0.05), transparent 60%),
radial-gradient(820px 480px at -8% -8%, rgba(254, 44, 85, 0.1), transparent 55%),
radial-gradient(640px 420px at 108% 0%, rgba(45, 212, 191, 0.07), transparent 50%),
var(--dy-bg);
color: var(--dy-text);
font-family: var(--dy-body);
@ -61,17 +60,17 @@
padding: 4px 6px 8px;
}
.dy-mark {
width: 44px;
height: 44px;
border-radius: 14px;
width: 42px;
height: 42px;
border-radius: 12px;
display: grid;
place-items: center;
background: linear-gradient(145deg, #fe2c55 0%, #ff4d6d 45%, #25f4ee 140%);
background: linear-gradient(145deg, #fe2c55 0%, #ff6b81 70%, #2dd4bf 160%);
color: #fff;
font-family: var(--dy-font);
font-weight: 800;
font-size: 18px;
box-shadow: 0 8px 24px rgba(254, 44, 85, 0.35);
font-size: 17px;
box-shadow: 0 6px 18px rgba(254, 44, 85, 0.28);
position: relative;
overflow: hidden;
}
@ -162,9 +161,9 @@
color: var(--dy-text);
}
.dy-nav a.active {
background: linear-gradient(90deg, rgba(254, 44, 85, 0.18), rgba(37, 244, 238, 0.08));
background: rgba(254, 44, 85, 0.12);
color: var(--dy-text);
box-shadow: inset 0 0 0 1px rgba(254, 44, 85, 0.28);
box-shadow: inset 0 0 0 1px rgba(254, 44, 85, 0.22);
}
.dy-nav a.active .dy-nav-ico {
background: rgba(254, 44, 85, 0.25);
@ -428,7 +427,7 @@
box-shadow: 0 2px 6px rgba(0,0,0,0.35);
}
.dy-switch input:checked + .dy-switch-track {
background: linear-gradient(90deg, #fe2c55, #25f4ee);
background: #fe2c55;
border-color: transparent;
}
.dy-switch input:checked + .dy-switch-track .dy-switch-thumb {
@ -554,23 +553,22 @@
/* —— 按钮 —— */
.dy-btn {
border: none;
border-radius: 14px;
border-radius: 12px;
padding: 12px 18px;
font-family: var(--dy-font);
font-weight: 700;
font-size: 14px;
cursor: pointer;
background: linear-gradient(120deg, #fe2c55, #ff4d6d 55%, #25f4ee);
background-size: 160% 100%;
background: #fe2c55;
color: #fff;
box-shadow: 0 10px 28px rgba(254, 44, 85, 0.28);
transition: transform 0.15s, box-shadow 0.15s, background-position 0.3s;
box-shadow: 0 8px 22px rgba(254, 44, 85, 0.28);
transition: transform 0.15s, box-shadow 0.15s, filter 0.15s;
min-height: 44px;
}
.dy-btn:hover:not(:disabled) {
transform: translateY(-1px);
background-position: 100% 0;
box-shadow: 0 14px 32px rgba(254, 44, 85, 0.38);
filter: brightness(1.06);
box-shadow: 0 12px 28px rgba(254, 44, 85, 0.36);
}
.dy-btn:disabled { opacity: 0.55; cursor: wait; }
.dy-btn-ghost {
@ -791,7 +789,7 @@
.dy-quick {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.dy-quick a {

View File

@ -251,12 +251,13 @@ th, td { text-align: left; padding: 10px 8px; border-bottom: 1px solid var(--lin
inset: 0;
pointer-events: none;
background:
radial-gradient(700px 420px at 20% 10%, rgba(94, 196, 120, 0.2), transparent 55%),
radial-gradient(600px 380px at 85% 20%, rgba(88, 166, 255, 0.12), transparent 50%);
radial-gradient(700px 420px at 18% 8%, rgba(94, 196, 120, 0.18), transparent 55%),
radial-gradient(640px 400px at 88% 12%, rgba(254, 44, 85, 0.1), transparent 52%),
radial-gradient(480px 320px at 50% 100%, rgba(37, 244, 238, 0.06), transparent 55%);
}
.platform-inner {
position: relative;
width: min(760px, 100%);
width: min(720px, 100%);
}
.platform-brand {
display: flex;
@ -273,59 +274,112 @@ th, td { text-align: left; padding: 10px 8px; border-bottom: 1px solid var(--lin
margin: 0;
color: var(--muted);
font-size: 14px;
line-height: 1.5;
}
.platform-brand-note {
opacity: 0.7;
font-size: 13px;
}
.platform-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.platform-grid--duo {
grid-template-columns: 1fr 1fr;
}
.platform-card {
text-align: left;
border: 1px solid var(--line);
border-radius: 18px;
padding: 22px 20px;
background: rgba(21, 32, 25, 0.88);
border-radius: 20px;
padding: 22px 20px 20px;
background: rgba(21, 32, 25, 0.9);
color: var(--text);
cursor: pointer;
display: flex;
flex-direction: column;
gap: 8px;
transition: transform 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
min-height: 200px;
transition: transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;
}
.platform-card:hover {
transform: translateY(-2px);
border-color: rgba(94, 196, 120, 0.45);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.28);
transform: translateY(-3px);
}
.platform-card-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
}
.platform-ico {
width: 48px;
height: 48px;
border-radius: 14px;
display: grid;
place-items: center;
font-size: 22px;
line-height: 1;
}
.platform-ico--wechat {
background: rgba(94, 196, 120, 0.15);
box-shadow: inset 0 0 0 1px rgba(94, 196, 120, 0.25);
}
.platform-ico--douyin {
background: linear-gradient(145deg, rgba(254, 44, 85, 0.9), rgba(37, 244, 238, 0.55));
color: #fff;
font-weight: 800;
font-size: 18px;
font-family: var(--font-display);
box-shadow: 0 8px 20px rgba(254, 44, 85, 0.28);
}
.platform-badge {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
padding: 4px 9px;
border-radius: 999px;
color: var(--accent);
background: rgba(94, 196, 120, 0.12);
border: 1px solid rgba(94, 196, 120, 0.28);
}
.platform-badge--dy {
color: #ff7a93;
background: rgba(254, 44, 85, 0.1);
border-color: rgba(254, 44, 85, 0.28);
}
.platform-card--wechat:hover {
border-color: rgba(94, 196, 120, 0.5);
box-shadow: 0 14px 36px rgba(0, 0, 0, 0.3);
}
.platform-card--douyin {
background: rgba(18, 12, 18, 0.92);
border-color: rgba(254, 44, 85, 0.22);
background:
linear-gradient(160deg, rgba(22, 14, 20, 0.96), rgba(12, 12, 16, 0.96));
border-color: rgba(255, 255, 255, 0.08);
}
.platform-card--douyin:hover {
border-color: rgba(254, 44, 85, 0.55);
box-shadow: 0 14px 36px rgba(254, 44, 85, 0.18);
}
.platform-emoji {
font-size: 28px;
line-height: 1;
border-color: rgba(254, 44, 85, 0.45);
box-shadow: 0 16px 40px rgba(254, 44, 85, 0.16);
}
.platform-card strong {
font-family: var(--font-display);
font-size: 20px;
letter-spacing: -0.02em;
}
.platform-card > span:nth-of-type(2) {
.platform-desc {
color: var(--muted);
font-size: 13px;
line-height: 1.45;
line-height: 1.5;
flex: 1;
}
.platform-cta {
margin-top: 10px;
margin-top: 8px;
color: var(--accent);
font-weight: 700;
font-size: 14px;
}
.platform-card--douyin .platform-cta {
color: #fe2c55;
color: #ff7a93;
}
@media (max-width: 960px) {

View File

@ -11,7 +11,7 @@ from fastapi.staticfiles import StaticFiles
from ebook_svc.config import settings
from ebook_svc.jobs import reconcile_pending_orders
from ebook_svc.routers import admin, auth, books, douyin_admin, pay, track
from ebook_svc.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track
scheduler = AsyncIOScheduler()
@ -47,6 +47,10 @@ for _api_prefix in ("/api", "/api/ebook"):
app.include_router(admin.router)
# 抖音定制面板(与微信读者/订单隔离)
app.include_router(douyin_admin.router)
# 加群引导开关(微信公众号 / 抖音群)
app.include_router(join_group_admin.router)
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
app.include_router(public_config.router)
@app.get("/health")

View File

@ -39,10 +39,11 @@ async def admin_stats(_: str = Depends(require_admin)):
async def admin_track_events(
limit: int = 100,
name: str = "",
client: str = "",
_: str = Depends(require_admin),
):
lim = max(1, min(limit, 500))
return store.list_track_events(limit=lim, name=name)
return store.list_track_events(limit=lim, name=name, client=client)
@router.get("/product-offers")

View File

@ -0,0 +1,45 @@
"""加群引导开关 API — 供 admin.nomadro.cn;用户端无感知。"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from ebook_svc.core.security import require_admin
from ebook_svc.services.join_group_config import (
read_join_group_config,
write_join_group_config,
)
router = APIRouter(prefix="/api/admin/join-group", tags=["join-group-admin"])
class JoinFlags(BaseModel):
joinGroupWechat: bool | None = None
joinGroupDouyin: bool | None = None
socialFollowAuto: bool | None = None
class JoinCopy(BaseModel):
joinGroupDouyinHint: str | None = None
joinGroupDouyinQr: str | None = None
wechatOaName: str | None = None
class JoinGroupBody(BaseModel):
flags: JoinFlags | None = None
copy: JoinCopy | None = None
@router.get("")
async def get_join_group(_: str = Depends(require_admin)) -> dict[str, Any]:
return {"ok": True, **read_join_group_config()}
@router.put("")
async def put_join_group(body: JoinGroupBody, _: str = Depends(require_admin)) -> dict[str, Any]:
flags_patch = body.flags.model_dump(exclude_none=True) if body.flags else None
copy_patch = body.copy.model_dump(exclude_none=True) if body.copy else None
saved = write_join_group_config(flags_patch=flags_patch, copy_patch=copy_patch)
return {"ok": True, **saved}

View File

@ -0,0 +1,73 @@
"""公开远程配置 — 供抖音真机拉配置(合法域名 + 有效证书)。
门户 nomadro.cn 证书与主机名不匹配,真机会 TLS 失败;
开发者工具不校验证书所以看起来正常。
走 dyapi.nomadro.cn / api.nomadro.cn(已在 request 合法域名且证书 OK)。
"""
from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from ebook_svc.services.tt_platform_config import resolve_config_file
router = APIRouter(tags=["public-config"])
def _read_full_config() -> dict[str, Any]:
path = resolve_config_file()
if not path.is_file():
return {
"version": 1,
"updatedAt": "",
"modules": {},
"flags": {},
"copy": {},
"platforms": {},
}
try:
raw = json.loads(path.read_text(encoding="utf-8"))
return raw if isinstance(raw, dict) else {}
except Exception:
return {
"version": 1,
"updatedAt": "",
"modules": {},
"flags": {},
"copy": {},
"platforms": {},
}
@router.get("/api/config")
@router.get("/api/ebook/config")
async def public_remote_config() -> JSONResponse:
"""对齐门户 GET /api/config:{ ok, source, config }。"""
config = _read_full_config()
return JSONResponse(
content={"ok": True, "source": "file", "config": config},
headers={
"Cache-Control": "no-store, no-cache, must-revalidate",
"Access-Control-Allow-Origin": "*",
},
)
@router.get("/api/config/meta")
@router.get("/api/ebook/config/meta")
async def public_remote_config_meta() -> JSONResponse:
config = _read_full_config()
return JSONResponse(
content={
"ok": True,
"version": int(config.get("version") or 0),
"updatedAt": str(config.get("updatedAt") or ""),
},
headers={
"Cache-Control": "no-store, no-cache, must-revalidate",
"Access-Control-Allow-Origin": "*",
},
)

View File

@ -0,0 +1,107 @@
"""加群引导远程开关 — 只改 flags,不碰 modules / platforms.tt / 订单数据。"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from ebook_svc.services.tt_platform_config import resolve_config_file
# 加群相关 flag 白名单(其它 flag 只读透传,不在此写入)
JOIN_FLAG_KEYS = (
"joinGroupWechat",
"joinGroupDouyin",
"socialFollowAuto",
)
DEFAULT_JOIN_FLAGS = {
"joinGroupWechat": True,
"joinGroupDouyin": False,
"socialFollowAuto": False,
}
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 read_join_group_config() -> dict[str, Any]:
raw = _read_raw()
flags = dict(raw.get("flags") or {})
out_flags = {k: bool(flags.get(k, DEFAULT_JOIN_FLAGS[k])) for k in JOIN_FLAG_KEYS}
copy = raw.get("copy") or {}
return {
"flags": out_flags,
"copy": {
"joinGroupDouyinHint": str(
copy.get("joinGroupDouyinHint")
or "打开抖音搜群「数字游民」或扫码进群"
),
"joinGroupDouyinQr": str(copy.get("joinGroupDouyinQr") or ""),
"wechatOaName": str(copy.get("wechatOaName") or "异度世界"),
},
"updatedAt": raw.get("updatedAt"),
"version": raw.get("version"),
"configPath": str(resolve_config_file()),
}
def write_join_group_config(
*,
flags_patch: dict[str, Any] | None = None,
copy_patch: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""增量写 flags / 文案;保留 modules、platforms、其它 flags。"""
import json
path = resolve_config_file()
path.parent.mkdir(parents=True, exist_ok=True)
existing = _read_raw()
out = dict(existing) if existing else {"version": 2, "modules": {}, "flags": {}, "copy": {}}
flags = dict(out.get("flags") or {})
# 补齐默认,避免旧文件缺键
for k, v in DEFAULT_JOIN_FLAGS.items():
if k not in flags:
flags[k] = v
if flags_patch:
for k, v in flags_patch.items():
if k not in JOIN_FLAG_KEYS:
continue
if isinstance(v, bool):
flags[k] = v
out["flags"] = flags
copy = dict(out.get("copy") or {})
if copy_patch:
for k in ("joinGroupDouyinHint", "joinGroupDouyinQr", "wechatOaName"):
if k in copy_patch and copy_patch[k] is not None:
copy[k] = str(copy_patch[k])
out["copy"] = copy
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
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return read_join_group_config()

View File

@ -521,24 +521,30 @@ class Store:
"track_events": tracks,
}
def list_track_events(self, limit: int = 100, name: str = "") -> list[dict[str, Any]]:
def list_track_events(
self,
limit: int = 100,
name: str = "",
client: str = "",
) -> list[dict[str, Any]]:
with self.conn() as c:
clauses: list[str] = []
params: list[Any] = []
if name.strip():
rows = c.execute(
"""
SELECT id, name, page, label, props_json, openid, client, ts, created_at
FROM track_events WHERE name=? ORDER BY ts DESC LIMIT ?
""",
(name.strip(), limit),
).fetchall()
else:
rows = c.execute(
"""
SELECT id, name, page, label, props_json, openid, client, ts, created_at
FROM track_events ORDER BY ts DESC LIMIT ?
""",
(limit,),
).fetchall()
clauses.append("name=?")
params.append(name.strip())
if client.strip():
clauses.append("client=?")
params.append(client.strip())
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
params.append(limit)
rows = c.execute(
f"""
SELECT id, name, page, label, props_json, openid, client, ts, created_at
FROM track_events{where} ORDER BY ts DESC LIMIT ?
""",
tuple(params),
).fetchall()
out = []
for r in rows:
item = dict(r)

View File

@ -1,4 +1,4 @@
"""埋点:入库(轻量)+ 按级别推 ntfy。"""
"""埋点:入库(轻量)+ 按级别推 ntfy(含渠道识别)。"""
from __future__ import annotations
import logging
@ -34,6 +34,10 @@ NTFY_ALWAYS = {
"wx_push",
"error",
"config_change",
"join_group_open",
"join_group_show",
"join_group_dismiss",
"join_group_qr_preview",
}
PRIORITY = {
@ -53,6 +57,10 @@ PRIORITY = {
"page_view": 2,
"btn_click": 2,
"app_launch": 3,
"join_group_open": 3,
"join_group_show": 4,
"join_group_dismiss": 2,
"join_group_qr_preview": 3,
}
TAGS = {
@ -78,6 +86,25 @@ TAGS = {
"access_updated": "arrows_counterclockwise",
"wx_push": "incoming_envelope",
"config_change": "gear,loudspeaker",
"join_group_open": "wave",
"join_group_show": "busts_in_silhouette",
"join_group_dismiss": "no_entry",
"join_group_qr_preview": "frame_with_picture",
}
CLIENT_LABEL = {
"tt": "抖音",
"weapp": "微信",
"h5": "H5",
"miniapp": "小程序",
"api": "API",
"wx_push": "微信推送",
}
CLIENT_NTFY_TAGS = {
"tt": "tiktok",
"weapp": "wechat",
"h5": "globe_with_meridians",
}
@ -88,7 +115,13 @@ def _short_openid(openid: str | None) -> str:
return f"…{o[-8:]}" if len(o) > 8 else o
def _title(name: str) -> str:
def _channel_label(client: str | None) -> str:
c = (client or "miniapp").strip()
return CLIENT_LABEL.get(c, c)
def _title(name: str, *, client: str | None = None) -> str:
ch = _channel_label(client)
mapping = {
"app_launch": "打开小程序",
"page_view": "进入页面",
@ -112,8 +145,13 @@ def _title(name: str) -> str:
"wx_push": "微信推送",
"error": "前端异常",
"config_change": "抖音配置变更",
"join_group_open": "加群弹窗",
"join_group_show": "加群展示",
"join_group_dismiss": "加群关闭",
"join_group_qr_preview": "加群二维码",
}
return mapping.get(name, f"埋点 {name}")
base = mapping.get(name, f"埋点 {name}")
return f"[{ch}] {base}"
def format_event_message(ev: dict[str, Any], *, openid: str | None, client: str | None) -> str:
@ -125,8 +163,19 @@ def format_event_message(ev: dict[str, Any], *, openid: str | None, client: str
props = ev.get("props") or {}
if isinstance(props, dict) and props:
bits = []
for k, v in list(props.items())[:6]:
bits.append(f"{k}={v}")
for k, v in list(props.items())[:8]:
if v is None or v == "":
continue
if k == "popup" and v == "douyin":
bits.append("弹窗=抖音群")
elif k == "popup" and v == "wechat":
bits.append("弹窗=公众号")
elif k == "offline" and v:
bits.append("离线兜底")
elif k == "channel":
bits.append(f"渠道={CLIENT_LABEL.get(str(v), v)}")
else:
bits.append(f"{k}={v}")
if bits:
parts.append(" · ".join(bits))
if client:
@ -143,6 +192,8 @@ async def ingest_events(
now = time.time()
saved = 0
notified = 0
client_key = (client or "miniapp").strip()
for raw in events:
name = str(raw.get("name") or "").strip()
if not name:
@ -154,7 +205,7 @@ async def ingest_events(
"props": raw.get("props") if isinstance(raw.get("props"), dict) else {},
"ts": float(raw.get("ts") or now),
"openid": openid or "",
"client": client or "miniapp",
"client": client_key,
}
try:
store.add_track_event(ev)
@ -163,19 +214,32 @@ async def ingest_events(
logger.exception("track save failed")
if name in NTFY_ALWAYS:
ntfy_title = _title(name)
ntfy_title = _title(name, client=client_key)
if name == "wx_push" and ev.get("label"):
ntfy_title = str(ev["label"])[:80]
ntfy_title = f"[{_channel_label(client_key)}] {ev['label']}"[:80]
elif name == "pay_deliver" and ev.get("label"):
ntfy_title = f"支付发货 · {ev['label']}"[:80]
ntfy_title = f"[{_channel_label(client_key)}] 支付发货 · {ev['label']}"[:80]
elif name == "join_group_show":
props = ev.get("props") or {}
popup = props.get("popup") if isinstance(props, dict) else None
if popup == "douyin":
ntfy_title = f"[{_channel_label(client_key)}] 加群 · 抖音群"
elif popup == "wechat":
ntfy_title = f"[{_channel_label(client_key)}] 加群 · 公众号"
tags = TAGS.get(name, "bar_chart")
channel_tag = CLIENT_NTFY_TAGS.get(client_key)
if channel_tag:
tags = f"{channel_tag},{tags}"
props = ev.get("props") or {}
if name == "wx_push" and isinstance(props, dict) and props.get("tags"):
tags = str(props["tags"])
elif name == "pay_deliver" and isinstance(props, dict) and not props.get("delivered"):
tags = "moneybag"
ok = await ntfy_svc.notify(
format_event_message(ev, openid=openid, client=client),
format_event_message(ev, openid=openid, client=client_key),
title=ntfy_title,
tags=tags,
priority=PRIORITY.get(name, 3),

View File

@ -1,28 +1,46 @@
import { useEffect } from 'react'
import type { PropsWithChildren } from 'react'
import { useLaunch } from '@tarojs/taro'
import { loadRemoteConfig } from './services/remoteConfig'
import { useDidHide, useDidShow, useLaunch } from '@tarojs/taro'
import { flush, trackAppLaunch } from './utils/track'
import {
loadRemoteConfig,
softRefreshRemoteConfig,
startRemoteConfigLiveSync,
} from './services/remoteConfig'
import { startH5RemLock } from './utils/h5RemLock'
import { applyH5Theme, getStoredH5Theme } from './utils/h5Theme'
// Taro multi-end: theme.h5.ts -> community.scss; theme.ts -> h5-theme.scss
import './styles/theme'
import './styles/ebook.scss'
import './app.scss'
function App({ children }: PropsWithChildren) {
useLaunch(() => {
trackAppLaunch()
void loadRemoteConfig(true)
startRemoteConfigLiveSync()
if (process.env.TARO_ENV === 'h5') {
applyH5Theme(getStoredH5Theme())
}
})
useDidShow(() => {
softRefreshRemoteConfig()
})
useDidHide(() => {
void flush()
})
useEffect(() => {
const stopRem = startH5RemLock()
const stopLive = startRemoteConfigLiveSync()
if (process.env.TARO_ENV === 'h5') {
applyH5Theme(getStoredH5Theme())
}
return stopRem
return () => {
stopRem()
stopLive()
}
}, [])
return children

View File

@ -1,5 +1,6 @@
import type { CSSProperties, ReactNode } from 'react'
import { View, Text } from '@tarojs/components'
import { trackClick } from '../utils/track'
const isH5 = process.env.TARO_ENV === 'h5'
@ -13,6 +14,8 @@ type BoxProps = {
'aria-hidden'?: boolean
'aria-label'?: string
'data-theme'?: string
/** 设了则点击时自动 btn_click 埋点 */
trackLabel?: string
}
/** H5 uses native div (taro-view-core defaults to inline and breaks grid/absolute). */
@ -26,14 +29,24 @@ export function H5Box({
'aria-hidden': ariaHidden,
'aria-label': ariaLabel,
'data-theme': dataTheme,
trackLabel,
}: BoxProps) {
const handleClick = onClick
? () => {
if (trackLabel) trackClick(trackLabel)
onClick()
}
: trackLabel
? () => trackClick(trackLabel)
: undefined
if (isH5) {
return (
<div
id={id}
className={className}
style={style}
onClick={onClick}
onClick={handleClick}
aria-hidden={ariaHidden}
aria-label={ariaLabel}
data-theme={dataTheme}
@ -48,7 +61,7 @@ export function H5Box({
id={id}
className={className}
style={style}
onClick={onClick}
onClick={handleClick}
data-theme={dataTheme}
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
>

View File

@ -4,12 +4,13 @@ import {
getCachedRemoteConfig,
isModuleEnabled,
loadRemoteConfig,
subscribeRemoteConfig,
} from '@/services/remoteConfig'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
type ModuleKey = keyof NomadroRemoteConfig['modules']
/** 小程序页级模块闸门:对齐门户 ModuleGate(首屏放行,无技术文案) */
/** 小程序页级模块闸门:订阅远程配置实时变更 */
export function MiniModuleGate({
moduleKey,
children,
@ -20,11 +21,13 @@ export function MiniModuleGate({
const [enabled, setEnabled] = useState(true)
useEffect(() => {
const cached = getCachedRemoteConfig()
setEnabled(isModuleEnabled(cached, moduleKey))
loadRemoteConfig().then((r) => {
setEnabled(isModuleEnabled(r.config, moduleKey))
})
const apply = (cfg: NomadroRemoteConfig) => {
setEnabled(isModuleEnabled(cfg, moduleKey))
}
apply(getCachedRemoteConfig())
const unsub = subscribeRemoteConfig((r) => apply(r.config))
void loadRemoteConfig(true)
return unsub
}, [moduleKey])
if (!enabled) {

View File

@ -140,3 +140,69 @@
border-radius: 12px;
background: rgba(255, 255, 255, 0.04);
}
.woa-loader {
position: relative;
z-index: 1;
width: 56px;
height: 56px;
flex-shrink: 0;
}
.woa-loader-ring {
position: absolute;
inset: 0;
border-radius: 50%;
border: 2px solid transparent;
box-sizing: border-box;
}
.woa-loader-ring--a {
border-top-color: #4ecdc4;
border-right-color: rgba(78, 205, 196, 0.25);
animation: woa-spin 0.9s linear infinite;
}
.woa-loader-ring--b {
inset: 8px;
border-bottom-color: #ff6b6b;
border-left-color: rgba(255, 107, 107, 0.2);
animation: woa-spin-rev 1.25s linear infinite;
}
.woa-loader-core {
position: absolute;
left: 50%;
top: 50%;
width: 10px;
height: 10px;
margin: -5px 0 0 -5px;
border-radius: 50%;
background: radial-gradient(circle, #4ecdc4 0%, rgba(78, 205, 196, 0.2) 70%, transparent 100%);
box-shadow: 0 0 12px rgba(78, 205, 196, 0.7);
animation: woa-pulse 1.2s ease-in-out infinite;
}
@keyframes woa-spin {
to {
transform: rotate(360deg);
}
}
@keyframes woa-spin-rev {
to {
transform: rotate(-360deg);
}
}
@keyframes woa-pulse {
0%,
100% {
opacity: 0.55;
transform: scale(0.85);
}
50% {
opacity: 1;
transform: scale(1.15);
}
}

View File

@ -1,17 +1,52 @@
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Image, OfficialAccount } from '@tarojs/components'
import qrImg from '../assets/wechat-oa-qr.png'
import { loadRemoteConfig } from '../services/remoteConfig'
import { trackJoinGroup } from '../utils/track'
import './WechatOaModal.scss'
/** 公众号:异度世界(二维码固化于 assets/wechat-oa-qr.png) */
/** 公众号默认名(可被远程 copy.wechatOaName 覆盖) */
export const WECHAT_OA_NAME = '异度世界'
export const WECHAT_OA_KEYWORD = '加群'
const QR_SRC = qrImg as string
const isWeapp = process.env.TARO_ENV === 'weapp'
const isTt = process.env.TARO_ENV === 'tt'
/** 对齐门户:关注公众号二维码 → 私信加群 */
type Channel = 'wechat' | 'douyin' | 'none'
type ModalCopy = {
wechatName: string
douyinHint: string
douyinQr: string
}
function flagOn(v: unknown): boolean {
return v === true || v === 1 || v === 'true'
}
/**
* 仅在「联网拿到后台配置」时用:严格跟 flags。
* 双开时:抖音端优先抖音,其它端优先微信。
*/
function resolveChannelOnline(flags: {
joinGroupWechat?: unknown
joinGroupDouyin?: unknown
}): Channel {
const wx = flagOn(flags.joinGroupWechat)
const dy = flagOn(flags.joinGroupDouyin)
if (wx && !dy) return 'wechat'
if (dy && !wx) return 'douyin'
if (wx && dy) return isTt ? 'douyin' : 'wechat'
return 'none'
}
/**
* 加群弹窗:
* - 拉取失败 / 离线 → 默认抖音群
* - 联网成功 → 永远跟后台 flags 实时显示
*/
export function WechatOaModal({
open,
onClose,
@ -19,34 +54,114 @@ export function WechatOaModal({
open: boolean
onClose: () => void
}) {
const onCloseRef = useRef(onClose)
onCloseRef.current = onClose
const [oaOk, setOaOk] = useState(true)
const [channel, setChannel] = useState<Channel | null>(null)
const [copy, setCopy] = useState<ModalCopy>({
wechatName: WECHAT_OA_NAME,
douyinHint: '打开抖音搜群「数字游民」或扫码进群',
douyinQr: '',
})
useEffect(() => {
if (!open) {
setChannel(null)
return
}
let cancelled = false
setChannel(null)
trackJoinGroup('open')
void (async () => {
try {
const result = await loadRemoteConfig(true)
if (cancelled) return
const cfg = result.config
const offline = result.fromOffline
setCopy({
wechatName: String(cfg.copy?.wechatOaName || WECHAT_OA_NAME),
douyinHint: String(
cfg.copy?.joinGroupDouyinHint ||
'打开抖音搜群「数字游民」或扫码进群',
),
douyinQr: String(cfg.copy?.joinGroupDouyinQr || ''),
})
const ch = offline ? 'douyin' : resolveChannelOnline(cfg.flags || {})
if (ch === 'none') {
Taro.showToast({ title: '加群暂未开放', icon: 'none' })
onCloseRef.current()
return
}
trackJoinGroup('show', { popup: ch, offline })
setChannel(ch)
} catch {
if (cancelled) return
trackJoinGroup('show', { popup: 'douyin', offline: true })
setChannel('douyin')
}
})()
return () => {
cancelled = true
}
}, [open])
if (!open) return null
const previewQr = () => {
if (!isWeapp) return
// image 内嵌二维码不能长按识别;previewImage 支持长按识别公众号
// https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.previewImage.html
void Taro.previewImage({ urls: [QR_SRC], current: QR_SRC })
if (channel === null) {
return (
<View className='woa-root' catchMove>
<View className='woa-backdrop' onClick={() => onCloseRef.current()} />
<View className='woa-loader' aria-hidden>
<View className='woa-loader-ring woa-loader-ring--a' />
<View className='woa-loader-ring woa-loader-ring--b' />
<View className='woa-loader-core' />
</View>
</View>
)
}
if (channel === 'none') return null
const isDouyin = channel === 'douyin'
const closeModal = () => {
trackJoinGroup('dismiss', { popup: isDouyin ? 'douyin' : 'wechat', label: '稍后再说' })
onCloseRef.current()
}
const previewQr = (src: string) => {
if (!isWeapp && !isTt) return
trackJoinGroup('qr_preview', { popup: isDouyin ? 'douyin' : 'wechat' })
void Taro.previewImage({ urls: [src], current: src })
}
return (
<View className='woa-root' catchMove>
<View className='woa-backdrop' onClick={onClose} />
<View className='woa-backdrop' onClick={closeModal} />
<View className='woa-card' onClick={(e) => e.stopPropagation()}>
<View className='woa-close' onClick={onClose}>
<View className='woa-close' onClick={closeModal}>
<Text>✕</Text>
</View>
<Text className='woa-eyebrow'>保持连接</Text>
<Text className='woa-title'>
关注 <Text className='woa-accent'>{WECHAT_OA_NAME}</Text>
{isDouyin ? (
<>
加入 <Text className='woa-accent'>抖音群</Text>
</>
) : (
<>
关注 <Text className='woa-accent'>{copy.wechatName}</Text>
</>
)}
</Text>
<Text className='woa-lead'>
获取出海导航、游民社群与会员更新。
{isDouyin
? copy.douyinHint
: '获取出海导航、游民社群与会员更新。'}
</Text>
{/* 需小程序后台「设置 → 关注公众号」关联同主体公众号;仅特定场景展示 */}
{isWeapp && oaOk ? (
{!isDouyin && isWeapp && oaOk ? (
<View className='woa-official'>
<OfficialAccount
onLoad={() => setOaOk(true)}
@ -56,23 +171,45 @@ export function WechatOaModal({
) : null}
<View className='woa-qr-wrap'>
<Image
className='woa-qr'
src={QR_SRC}
mode='aspectFit'
showMenuByLongpress
onClick={previewQr}
/>
<Text className='woa-qr-hint'>
{isWeapp
? '点按二维码预览,长按识别关注'
: `搜索公众号「${WECHAT_OA_NAME}」`}
</Text>
<Text className='woa-qr-kw'>
关注后私信关键词「{WECHAT_OA_KEYWORD}」
</Text>
{isDouyin ? (
copy.douyinQr ? (
<Image
className='woa-qr'
src={copy.douyinQr}
mode='aspectFit'
showMenuByLongpress
onClick={() => previewQr(copy.douyinQr)}
/>
) : (
<Text className='woa-qr-hint' style={{ padding: '24px 8px' }}>
{copy.douyinHint}
</Text>
)
) : (
<Image
className='woa-qr'
src={QR_SRC}
mode='aspectFit'
showMenuByLongpress
onClick={() => previewQr(QR_SRC)}
/>
)}
{!isDouyin ? (
<>
<Text className='woa-qr-hint'>
{isWeapp
? '点按二维码预览,长按识别关注'
: `搜索公众号「${copy.wechatName}」`}
</Text>
<Text className='woa-qr-kw'>
关注后私信关键词「{WECHAT_OA_KEYWORD}」
</Text>
</>
) : copy.douyinQr ? (
<Text className='woa-qr-hint'>长按识别进群</Text>
) : null}
</View>
<View className='woa-later' onClick={onClose}>
<View className='woa-later' onClick={closeModal}>
<Text>稍后再说</Text>
</View>
</View>

View File

@ -22,6 +22,9 @@ export type NomadroRemoteConfig = {
flags: {
payEnabled: boolean
socialFollow: boolean
socialFollowAuto?: boolean
joinGroupWechat?: boolean
joinGroupDouyin?: boolean
offlineBadge: boolean
}
copy: {
@ -31,6 +34,9 @@ export type NomadroRemoteConfig = {
vipPriceFen: number
vipProductId: string
vipCta: string
wechatOaName?: string
joinGroupDouyinHint?: string
joinGroupDouyinQr?: string
}
}
@ -50,15 +56,21 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
flags: {
payEnabled: true,
socialFollow: true,
socialFollowAuto: false,
joinGroupWechat: true,
joinGroupDouyin: false,
offlineBadge: false,
},
copy: {
homeBrand: 'nomadro',
homeTagline: '',
homeLead: '',
vipPriceFen: 8800,
vipPriceFen: 29800,
vipProductId: 'vip_membership',
vipCta: '立即加入',
wechatOaName: '异度世界',
joinGroupDouyinHint: '打开抖音搜群「数字游民」或扫码进群',
joinGroupDouyinQr: '',
},
}

View File

@ -0,0 +1,9 @@
import { useDidShow } from '@tarojs/taro'
import { trackPage } from '../utils/track'
/** 页面 show 时自动 page_view(去重由 trackPage 处理) */
export function usePageTrack(page: string, label?: string) {
useDidShow(() => {
trackPage(page, label)
})
}

View File

@ -13,6 +13,8 @@ import { MiniModuleGate } from '@/components/MiniModuleGate'
import { useNomadroTheme } from '@/utils/h5Theme'
import { usePageShare, markPageShare } from '@/utils/pageShare'
import { getSafeAreaMetrics } from '@/utils/safeArea'
import { usePageTrack } from '@/hooks/usePageTrack'
import { trackTap } from '@/utils/track'
import './index.scss'
const isH5 = process.env.TARO_ENV === 'h5'
@ -75,6 +77,7 @@ const SOCIAL_MESH_SVG = `<svg class="social-mesh-svg" viewBox="0 0 400 400" fill
</svg>`
function HomePageInner() {
usePageTrack('pages/community/index', '旅居社群')
const theme = useNomadroTheme()
const [tw, setTw] = useState('')
const [joinOpen, setJoinOpen] = useState(false)
@ -209,7 +212,7 @@ function HomePageInner() {
<H5Box className="hero-bottom">
<H5Box className="hero-actions">
<Button className="btn btn-primary" onClick={() => setJoinOpen(true)}>
<Button className="btn btn-primary" onClick={trackTap('加群', () => setJoinOpen(true))}>
👥 加群
</Button>
</H5Box>

View File

@ -14,6 +14,7 @@ import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme'
import { goPage } from '@/utils/nav'
import { usePageShare, markPageShare } from '@/utils/pageShare'
import { getSafeAreaMetrics } from '@/utils/safeArea'
import { usePageTrack } from '@/hooks/usePageTrack'
import './index.scss'
type PortalId = 'nav' | 'book' | 'community' | 'vip' | 'game'
@ -158,6 +159,7 @@ function Txt({ className, children }: { className?: string; children?: ReactNode
}
function IndexPage() {
usePageTrack('pages/index/index', '首页')
usePageShare({ title: 'nomadro · 随处工作,自由生活', path: '/pages/index/index' })
const [config, setConfig] = useState<NomadroRemoteConfig | null>(null)

View File

@ -184,7 +184,7 @@ function VipLanding() {
}, [])
const payOk = cfg.flags.payEnabled !== false
const priceFen = cfg.copy.vipPriceFen || 8800
const priceFen = cfg.copy.vipPriceFen || 29800
const productId = cfg.copy.vipProductId || 'vip_membership'
const cta = cfg.copy.vipCta || '立即加入'
const brand = cfg.copy.homeBrand || 'nomadro'

View File

@ -8,6 +8,8 @@ import {
const STORAGE_KEY = 'nomadro_remote_config_v1'
const CACHE_TTL_MS = 1000 * 60 * 30
/** 小程序无 EventSource:meta 轮询间隔(近实时) */
const META_POLL_MS = 8000
type LoadResult = {
config: NomadroRemoteConfig
@ -15,7 +17,25 @@ type LoadResult = {
source: 'network' | 'storage' | 'bundle'
}
type Listener = (result: LoadResult) => void
let memory: LoadResult | null = null
const listeners = new Set<Listener>()
let liveStarted = false
let metaTimer: ReturnType<typeof setInterval> | null = null
let knownVersion = 0
function emit(result: LoadResult) {
memory = result
knownVersion = Number(result.config.version) || knownVersion
listeners.forEach((fn) => {
try {
fn(result)
} catch {
/* ignore */
}
})
}
function readStorage(): NomadroRemoteConfig | null {
try {
@ -38,9 +58,12 @@ function writeStorage(config: NomadroRemoteConfig) {
}
}
function metaUrls(): string[] {
if (APP_TARGET === 'h5') return ['/api/config/meta']
return [`${WEB_BASE}/api/config/meta`]
}
async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
// H5:只打同源 /api(devServer 代理),绝不直连线上以免 CORS 红屏
// 小程序:直连门户 / 电子书 API
const urls =
APP_TARGET === 'h5'
? ['/api/config']
@ -60,7 +83,26 @@ async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
return mergeRemoteConfig(res.data as NomadroRemoteConfig)
}
} catch {
/* try next — 失败走包内 DEFAULT */
/* try next */
}
}
return null
}
async function fetchMeta(): Promise<{ version: number; updatedAt: string } | null> {
for (const url of metaUrls()) {
try {
const res = await Taro.request({ url, method: 'GET', timeout: 5000 })
if (res.statusCode >= 400) continue
const body = res.data as { version?: number; updatedAt?: string }
if (body?.version != null) {
return {
version: Number(body.version) || 0,
updatedAt: String(body.updatedAt || ''),
}
}
} catch {
/* try next */
}
}
return null
@ -68,7 +110,7 @@ async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
/**
* 兜底顺序:内存 → 网络 → Storage → 包内 DEFAULT
* 纯前端 / 小红书:网络失败仍可用 bundle
* force=true:跳过内存,强制打 API(加群弹窗 / 前台唤醒)
*/
export async function loadRemoteConfig(force = false): Promise<LoadResult> {
if (!force && memory) return memory
@ -79,28 +121,43 @@ export async function loadRemoteConfig(force = false): Promise<LoadResult> {
const remote = await fetchRemote()
if (remote) {
writeStorage(remote)
memory = { config: remote, fromOffline: false, source: 'network' }
return memory
const result: LoadResult = {
config: remote,
fromOffline: false,
source: 'network',
}
emit(result)
return result
}
} catch {
/* fall through */
}
if (cached) {
memory = { config: cached, fromOffline: true, source: 'storage' }
return memory
const result: LoadResult = {
config: cached,
fromOffline: true,
source: 'storage',
}
emit(result)
return result
}
memory = {
const result: LoadResult = {
config: mergeRemoteConfig(DEFAULT_REMOTE_CONFIG),
fromOffline: true,
source: 'bundle',
}
return memory
emit(result)
return result
}
export function getCachedRemoteConfig(): NomadroRemoteConfig {
return memory?.config || readStorage() || mergeRemoteConfig(DEFAULT_REMOTE_CONFIG)
return (
memory?.config ||
readStorage() ||
mergeRemoteConfig(DEFAULT_REMOTE_CONFIG)
)
}
export function isModuleEnabled(
@ -109,3 +166,88 @@ export function isModuleEnabled(
): boolean {
return Boolean(config.modules[key]?.enabled)
}
/** 订阅配置变更(模块闸门 / 页面热刷新) */
export function subscribeRemoteConfig(listener: Listener): () => void {
listeners.add(listener)
if (memory) listener(memory)
return () => listeners.delete(listener)
}
async function softCheckMeta() {
const meta = await fetchMeta()
if (!meta) return
if (knownVersion && meta.version === knownVersion) return
await loadRemoteConfig(true)
}
/**
* 启动实时同步:
* - H5:EventSource → /api/config/stream
* - 小程序:meta 轮询 + onShow(无 SSE)
*/
export function startRemoteConfigLiveSync(): () => void {
if (liveStarted) return () => {}
liveStarted = true
knownVersion = Number(getCachedRemoteConfig().version) || 0
let es: EventSource | null = null
let stopped = false
const stop = () => {
stopped = true
liveStarted = false
if (metaTimer) {
clearInterval(metaTimer)
metaTimer = null
}
es?.close()
es = null
}
if (APP_TARGET === 'h5' && typeof EventSource !== 'undefined') {
try {
es = new EventSource('/api/config/stream')
es.addEventListener('config', (ev) => {
try {
const data = JSON.parse(String((ev as MessageEvent).data || '{}')) as {
version?: number
}
const v = Number(data.version) || 0
if (v && v !== knownVersion) void loadRemoteConfig(true)
} catch {
void loadRemoteConfig(true)
}
})
es.onerror = () => {
/* 断线后靠 meta 轮询兜底 */
}
} catch {
/* fall through to poll */
}
}
metaTimer = setInterval(() => {
if (!stopped) void softCheckMeta()
}, META_POLL_MS)
// 前台可见 / 小程序 onShow 由 app 层再调 softRefreshRemoteConfig
if (APP_TARGET === 'h5' && typeof document !== 'undefined') {
const onVis = () => {
if (document.visibilityState === 'visible') void softCheckMeta()
}
document.addEventListener('visibilitychange', onVis)
const prevStop = stop
return () => {
document.removeEventListener('visibilitychange', onVis)
prevStop()
}
}
return stop
}
/** 前台唤醒:强制检查后台 version */
export function softRefreshRemoteConfig(): void {
void softCheckMeta()
}

View File

@ -1,4 +1,5 @@
import Taro from '@tarojs/taro'
import { trackClick } from './track'
const isH5 = process.env.TARO_ENV === 'h5'
@ -16,6 +17,7 @@ export function goPage(url: string): void {
const path = normalizePath(url)
const qs = url.includes('?') ? url.slice(url.indexOf('?')) : ''
const full = `${path}${qs}`
trackClick('页面跳转', { to: full })
if (isH5 && path.includes('/pages/index')) {
Taro.redirectTo({ url: full }).catch(() => Taro.navigateTo({ url: full }))
return

View File

@ -1,7 +1,8 @@
import Taro from '@tarojs/taro'
import { API_BASE, STORAGE_OPENID, STORAGE_TOKEN } from './config'
import { API_BASE, APP_TARGET, STORAGE_OPENID, STORAGE_TOKEN } from './config'
type TrackProps = Record<string, string | number | boolean | null | undefined>
export type TrackChannel = 'tt' | 'weapp' | 'h5'
export type TrackProps = Record<string, string | number | boolean | null | undefined>
type TrackItem = {
name: string
@ -14,6 +15,30 @@ type TrackItem = {
const queue: TrackItem[] = []
let flushTimer: ReturnType<typeof setTimeout> | null = null
let flushing = false
let lastPageView = { key: '', at: 0 }
/** 上报 client:抖音 tt / 微信 weapp / H5 h5 */
export function getTrackClient(): TrackChannel {
const env = process.env.TARO_ENV
if (env === 'tt') return 'tt'
if (env === 'h5') return 'h5'
if (APP_TARGET === 'tt') return 'tt'
if (APP_TARGET === 'h5') return 'h5'
return 'weapp'
}
export function getTrackChannelLabel(client?: string): string {
switch (client || getTrackClient()) {
case 'tt':
return '抖音'
case 'weapp':
return '微信'
case 'h5':
return 'H5'
default:
return client || '未知'
}
}
function currentPage(): string {
try {
@ -25,7 +50,22 @@ function currentPage(): string {
}
}
function scheduleFlush() {
function withChannelProps(props?: TrackProps): TrackProps {
return {
channel: getTrackClient(),
...props,
}
}
function scheduleFlush(immediate = false) {
if (immediate) {
if (flushTimer) {
clearTimeout(flushTimer)
flushTimer = null
}
void flush()
return
}
if (flushTimer) return
flushTimer = setTimeout(() => {
flushTimer = null
@ -46,7 +86,7 @@ export async function flush(): Promise<void> {
data: {
events: batch,
openid: openid || undefined,
client: 'miniapp',
client: getTrackClient(),
},
timeout: 5000,
header: {
@ -55,7 +95,6 @@ export async function flush(): Promise<void> {
},
})
} catch {
// 失败塞回队列头部,避免丢关键事件
queue.unshift(...batch)
} finally {
flushing = false
@ -66,33 +105,70 @@ export async function flush(): Promise<void> {
/** 通用埋点:静默上报,失败不打扰用户 */
export function track(
name: string,
opts?: { page?: string; label?: string; props?: TrackProps },
opts?: { page?: string; label?: string; props?: TrackProps; immediate?: boolean },
): void {
queue.push({
name,
page: opts?.page || currentPage(),
label: opts?.label,
props: opts?.props,
props: withChannelProps(opts?.props),
ts: Date.now() / 1000,
})
if (queue.length >= 8) {
void flush()
if (opts?.immediate || queue.length >= 8) {
scheduleFlush(true)
} else {
scheduleFlush()
}
}
export function trackPage(page: string, label?: string, props?: TrackProps) {
track('page_view', { page, label: label || page, props })
const key = `${page}|${label || page}`
const now = Date.now()
if (lastPageView.key === key && now - lastPageView.at < 1500) return
lastPageView = { key, at: now }
track('page_view', { page, label: label || page, props, immediate: true })
}
export function trackClick(label: string, props?: TrackProps) {
track('btn_click', { label, props })
track('btn_click', { label, props, immediate: true })
}
/** onClick 包装:先埋点再执行 */
export function trackTap<T extends (...args: never[]) => void>(
label: string,
handler?: T,
props?: TrackProps,
): (...args: Parameters<T>) => void {
return (...args: Parameters<T>) => {
trackClick(label, props)
handler?.(...args)
}
}
export function trackPay(
stage: 'start' | 'success' | 'cancel' | 'fail' | 'pending',
props?: TrackProps,
) {
track(`pay_${stage}`, { label: stage, props })
track(`pay_${stage}`, { label: stage, props, immediate: true })
}
export function trackJoinGroup(
stage: 'open' | 'show' | 'dismiss' | 'qr_preview',
opts?: { popup?: 'wechat' | 'douyin'; offline?: boolean; label?: string },
) {
track(`join_group_${stage}`, {
label: opts?.label || stage,
props: {
popup: opts?.popup,
offline: opts?.offline,
},
})
}
export function trackAppLaunch() {
track('app_launch', {
label: getTrackChannelLabel(),
props: { channel: getTrackClient() },
immediate: true,
})
}

View File

@ -62,7 +62,7 @@ pnpm build # 生产构建 + copy-static + validate:size
| 运行时 | `FORCE_OFFLINE_BOOK`,不拉线上旧目录 |
| 阅读 | **连续竖滑**:首屏渐进挂载章节(避免一次解析 41 章卡死);目录跳章 `ensureMountedThrough`;全书挂完才出「全书读完」 |
| 滚动 | 目录跳转只用短回钉;用户滑离即停 `pageScrollTo`;跳章锁定期勿增章(否则会抖回封面) |
| 过审 | 默认 BMI 首页(健康管理类目);后台 `homeVariant=hub` 切回门户;门户默认隐藏「出海导航」;小册正文不嵌公众号二维码;加群弹窗优先抖音群 |
| 过审 | 默认 BMI 首页(健康管理类目);后台 `homeVariant=hub` 切回门户;门户默认隐藏「出海导航」;小册正文不嵌公众号二维码;加群由 `joinGroupWechat`/`joinGroupDouyin` 开关决定;「稍后再说」仅关闭弹窗 |
## 包体积(官方)

View File

@ -1,10 +1,14 @@
import { useEffect } from 'react'
import type { PropsWithChildren } from 'react'
import { useLaunch } from '@tarojs/taro'
import { loadRemoteConfig } from './services/remoteConfig'
import { useDidHide, useDidShow, useLaunch } from '@tarojs/taro'
import { flush, trackAppLaunch } from './utils/track'
import {
loadRemoteConfig,
softRefreshRemoteConfig,
startRemoteConfigLiveSync,
} from './services/remoteConfig'
import { startH5RemLock } from './utils/h5RemLock'
import { applyH5Theme, getStoredH5Theme } from './utils/h5Theme'
import { track } from './utils/track'
// Taro multi-end: theme.h5.ts -> community.scss; theme.ts -> h5-theme.scss
import './styles/theme'
import './styles/ebook.scss'
@ -12,19 +16,31 @@ import './app.scss'
function App({ children }: PropsWithChildren) {
useLaunch(() => {
trackAppLaunch()
void loadRemoteConfig(true)
track('app_launch', { page: 'app', label: '打开抖音小程序', immediate: true })
if (process.env.TARO_ENV === 'h5') {
applyH5Theme(getStoredH5Theme())
}
})
useDidShow(() => {
softRefreshRemoteConfig()
})
useDidHide(() => {
void flush()
})
useEffect(() => {
const stopRem = startH5RemLock()
const stopLive = startRemoteConfigLiveSync()
if (process.env.TARO_ENV === 'h5') {
applyH5Theme(getStoredH5Theme())
}
return stopRem
return () => {
stopRem()
stopLive()
}
}, [])
return children

View File

@ -1,5 +1,6 @@
import type { CSSProperties, ReactNode } from 'react'
import { View, Text } from '@tarojs/components'
import { trackClick } from '../utils/track'
const isH5 = process.env.TARO_ENV === 'h5'
@ -13,6 +14,8 @@ type BoxProps = {
'aria-hidden'?: boolean
'aria-label'?: string
'data-theme'?: string
/** 设了则点击时自动 btn_click 埋点 */
trackLabel?: string
}
/** H5 uses native div (taro-view-core defaults to inline and breaks grid/absolute). */
@ -26,14 +29,24 @@ export function H5Box({
'aria-hidden': ariaHidden,
'aria-label': ariaLabel,
'data-theme': dataTheme,
trackLabel,
}: BoxProps) {
const handleClick = onClick
? () => {
if (trackLabel) trackClick(trackLabel)
onClick()
}
: trackLabel
? () => trackClick(trackLabel)
: undefined
if (isH5) {
return (
<div
id={id}
className={className}
style={style}
onClick={onClick}
onClick={handleClick}
aria-hidden={ariaHidden}
aria-label={ariaLabel}
data-theme={dataTheme}
@ -48,7 +61,7 @@ export function H5Box({
id={id}
className={className}
style={style}
onClick={onClick}
onClick={handleClick}
data-theme={dataTheme}
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
>

View File

@ -4,12 +4,13 @@ import {
getCachedRemoteConfig,
isModuleEnabled,
loadRemoteConfig,
subscribeRemoteConfig,
} from '@/services/remoteConfig'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
type ModuleKey = keyof NomadroRemoteConfig['modules']
/** 小程序页级模块闸门:对齐门户 ModuleGate(首屏放行,无技术文案) */
/** 小程序页级模块闸门:订阅远程配置实时变更 */
export function MiniModuleGate({
moduleKey,
children,
@ -20,11 +21,13 @@ export function MiniModuleGate({
const [enabled, setEnabled] = useState(true)
useEffect(() => {
const cached = getCachedRemoteConfig()
setEnabled(isModuleEnabled(cached, moduleKey))
loadRemoteConfig().then((r) => {
setEnabled(isModuleEnabled(r.config, moduleKey))
})
const apply = (cfg: NomadroRemoteConfig) => {
setEnabled(isModuleEnabled(cfg, moduleKey))
}
apply(getCachedRemoteConfig())
const unsub = subscribeRemoteConfig((r) => apply(r.config))
void loadRemoteConfig(true)
return unsub
}, [moduleKey])
if (!enabled) {

View File

@ -123,3 +123,69 @@
font-size: 28rpx;
color: #94a3b8;
}
.woa-loader {
position: relative;
z-index: 1;
width: 112rpx;
height: 112rpx;
flex-shrink: 0;
}
.woa-loader-ring {
position: absolute;
inset: 0;
border-radius: 50%;
border: 4rpx solid transparent;
box-sizing: border-box;
}
.woa-loader-ring--a {
border-top-color: #4ecdc4;
border-right-color: rgba(78, 205, 196, 0.25);
animation: woa-spin 0.9s linear infinite;
}
.woa-loader-ring--b {
inset: 16rpx;
border-bottom-color: #ff6b6b;
border-left-color: rgba(255, 107, 107, 0.2);
animation: woa-spin-rev 1.25s linear infinite;
}
.woa-loader-core {
position: absolute;
left: 50%;
top: 50%;
width: 20rpx;
height: 20rpx;
margin: -10rpx 0 0 -10rpx;
border-radius: 50%;
background: radial-gradient(circle, #4ecdc4 0%, rgba(78, 205, 196, 0.2) 70%, transparent 100%);
box-shadow: 0 0 24rpx rgba(78, 205, 196, 0.7);
animation: woa-pulse 1.2s ease-in-out infinite;
}
@keyframes woa-spin {
to {
transform: rotate(360deg);
}
}
@keyframes woa-spin-rev {
to {
transform: rotate(-360deg);
}
}
@keyframes woa-pulse {
0%,
100% {
opacity: 0.55;
transform: scale(0.85);
}
50% {
opacity: 1;
transform: scale(1.15);
}
}

View File

@ -1,18 +1,56 @@
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import ttGroupQr from '../assets/tt-group-qr.png'
import wechatOaQr from '../assets/wechat-oa-qr.png'
import { loadRemoteConfig } from '../services/remoteConfig'
import { trackJoinGroup } from '../utils/track'
import './WechatOaModal.scss'
/** 公众号:异度世界 */
/** 公众号:异度世界(可被远程 copy.wechatOaName 覆盖) */
export const WECHAT_OA_NAME = '异度世界'
export const WECHAT_OA_KEYWORD = '加群'
const TT_QR = ttGroupQr as string
const OA_QR = wechatOaQr as string
const IS_TT = process.env.TARO_ENV === 'tt'
/** 默认抖音群;点「稍后再说」切换为公众号关注引导 */
type Channel = 'wechat' | 'douyin' | 'none'
type ModalCopy = {
wechatName: string
douyinHint: string
douyinQr: string
}
/**
* 严格按后台开关(联网成功时):
* - 只开微信 → 公众号
* - 只开抖音 → 抖音群
* - 都开 → 抖音端优先抖音
* - 都关 → none
*
* 失败/离线由调用方直接默认 douyin,不走此函数。
*/
function resolveChannelOnline(flags: {
joinGroupWechat?: unknown
joinGroupDouyin?: unknown
}): Channel {
const on = (v: unknown) => v === true || v === 1 || v === 'true'
const wx = on(flags.joinGroupWechat)
const dy = on(flags.joinGroupDouyin)
if (wx && !dy) return 'wechat'
if (dy && !wx) return 'douyin'
if (wx && dy) return IS_TT ? 'douyin' : 'wechat'
return 'none'
}
/**
* 加群弹窗:
* - 拉取失败 / 离线 → 默认抖音群
* - 联网成功 → 永远跟后台 flags 实时显示
* 「稍后再说」= 仅关闭
*/
export function WechatOaModal({
open,
onClose,
@ -20,50 +58,116 @@ export function WechatOaModal({
open: boolean
onClose: () => void
}) {
const [showOa, setShowOa] = useState(false)
const onCloseRef = useRef(onClose)
onCloseRef.current = onClose
const [channel, setChannel] = useState<Channel | null>(null)
const [copy, setCopy] = useState<ModalCopy>({
wechatName: WECHAT_OA_NAME,
douyinHint: '打开抖音搜群「数字游民」或扫码进群',
douyinQr: '',
})
useEffect(() => {
if (!open) setShowOa(false)
if (!open) {
setChannel(null)
return
}
let cancelled = false
setChannel(null)
trackJoinGroup('open')
void (async () => {
try {
const result = await loadRemoteConfig(true)
if (cancelled) return
const cfg = result.config
const offline = result.fromOffline
setCopy({
wechatName: String(cfg.copy?.wechatOaName || WECHAT_OA_NAME),
douyinHint: String(
cfg.copy?.joinGroupDouyinHint ||
'打开抖音搜群「数字游民」或扫码进群',
),
douyinQr: String(cfg.copy?.joinGroupDouyinQr || ''),
})
// 失败 / 离线:默认抖音;联网:严格跟后台
const ch = offline ? 'douyin' : resolveChannelOnline(cfg.flags || {})
if (ch === 'none') {
Taro.showToast({ title: '加群暂未开放', icon: 'none' })
onCloseRef.current()
return
}
trackJoinGroup('show', { popup: ch, offline })
setChannel(ch)
} catch {
if (cancelled) return
trackJoinGroup('show', { popup: 'douyin', offline: true })
setChannel('douyin')
}
})()
return () => {
cancelled = true
}
}, [open])
if (!open) return null
const qrSrc = showOa ? OA_QR : TT_QR
const previewQr = () => {
void Taro.previewImage({ urls: [qrSrc], current: qrSrc })
if (channel === null) {
return (
<View className='woa-root' catchMove>
<View className='woa-backdrop' onClick={() => onCloseRef.current()} />
<View className='woa-loader' aria-hidden>
<View className='woa-loader-ring woa-loader-ring--a' />
<View className='woa-loader-ring woa-loader-ring--b' />
<View className='woa-loader-core' />
</View>
</View>
)
}
const onLater = () => {
if (!showOa) {
setShowOa(true)
return
}
onClose()
if (channel === 'none') return null
const isDouyin = channel === 'douyin'
const qrSrc = isDouyin ? copy.douyinQr || TT_QR : OA_QR
const closeModal = () => {
trackJoinGroup('dismiss', { popup: isDouyin ? 'douyin' : 'wechat', label: '稍后再说' })
onCloseRef.current()
}
const previewQr = () => {
trackJoinGroup('qr_preview', { popup: isDouyin ? 'douyin' : 'wechat' })
void Taro.previewImage({ urls: [qrSrc], current: qrSrc })
}
return (
<View className='woa-root' catchMove>
<View className='woa-backdrop' onClick={onClose} />
<View className='woa-backdrop' onClick={closeModal} />
<View className='woa-card' onClick={(e) => e.stopPropagation()}>
<View className='woa-close' onClick={onClose}>
<View className='woa-close' onClick={closeModal}>
<Text>✕</Text>
</View>
<Text className='woa-eyebrow'>{showOa ? '保持连接' : '社群'}</Text>
{showOa ? (
<Text className='woa-title'>
关注 <Text className='woa-accent'>{WECHAT_OA_NAME}</Text>
</Text>
) : (
<Text className='woa-title'>
加入 <Text className='woa-accent'>抖音群</Text>
</Text>
)}
<Text className='woa-eyebrow'>{isDouyin ? '社群' : '保持连接'}</Text>
<Text className='woa-title'>
{isDouyin ? (
<>
加入 <Text className='woa-accent'>抖音群</Text>
</>
) : (
<>
关注 <Text className='woa-accent'>{copy.wechatName}</Text>
</>
)}
</Text>
<Text className='woa-lead'>
{showOa
? '获取出海导航、游民社群与会员更新。'
: '扫码进群,获取游民社群与活动更新。'}
{isDouyin
? copy.douyinHint
: '获取出海导航、游民社群与会员更新。'}
</Text>
<View className='woa-qr-wrap'>
@ -73,19 +177,19 @@ export function WechatOaModal({
mode='aspectFit'
onClick={previewQr}
/>
{showOa ? (
{isDouyin ? (
<Text className='woa-qr-hint'>抖音扫一扫 · 加入社群</Text>
) : (
<>
<Text className='woa-qr-hint'>搜索公众号「{WECHAT_OA_NAME}」</Text>
<Text className='woa-qr-hint'>搜索公众号「{copy.wechatName}」</Text>
<Text className='woa-qr-kw'>
关注后私信关键词「{WECHAT_OA_KEYWORD}」
</Text>
</>
) : (
<Text className='woa-qr-hint'>抖音扫一扫 · 加入社群</Text>
)}
</View>
<View className='woa-later' onClick={onLater}>
<View className='woa-later' onClick={closeModal}>
<Text>稍后再说</Text>
</View>
</View>

View File

@ -57,6 +57,11 @@ export type NomadroRemoteConfig = {
flags: {
payEnabled: boolean
socialFollow: boolean
socialFollowAuto?: boolean
/** 加群 → 微信公众号(后台开关) */
joinGroupWechat?: boolean
/** 加群 → 抖音群(后台开关) */
joinGroupDouyin?: boolean
offlineBadge: boolean
}
copy: {
@ -66,6 +71,9 @@ export type NomadroRemoteConfig = {
vipPriceFen: number
vipProductId: string
vipCta: string
wechatOaName?: string
joinGroupDouyinHint?: string
joinGroupDouyinQr?: string
}
platforms?: {
tt?: TtPlatformConfig
@ -100,16 +108,16 @@ export const DEFAULT_TT_PLATFORM: TtPlatformConfig = {
note: '抖音默认隐藏,后台可开',
},
book: {
enabled: true,
enabled: false,
title: '数字游民小册',
tabLabel: '小册',
note: '默认开启 · 正文可远程改',
note: '默认关闭 · 以后台入口开关为准',
},
community: {
enabled: false,
enabled: true,
title: '旅居社群',
tabLabel: '社群',
note: '抖音默认隐藏,后台可开',
note: '抖音默认入口 · 后台可关',
},
},
bookContent: DEFAULT_TT_BOOK_CONTENT,
@ -121,8 +129,8 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
modules: {
home: { enabled: true, title: '首页', tabLabel: '首页' },
nav: { enabled: false, title: '出海导航', tabLabel: '导航', note: 'tt: use platforms.tt' },
book: { enabled: true, title: '数字游民小册', tabLabel: '小册' },
community: { enabled: false, title: '旅居社群', tabLabel: '社群', note: 'tt: use platforms.tt' },
book: { enabled: false, title: '数字游民小册', tabLabel: '小册', note: 'tt: use platforms.tt' },
community: { enabled: true, title: '旅居社群', tabLabel: '社群', note: 'tt: use platforms.tt' },
destinations: { enabled: true, title: '目的地' },
meetups: { enabled: true, title: '活动' },
vip: { enabled: true, title: '会员中心' },
@ -130,6 +138,9 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
flags: {
payEnabled: false,
socialFollow: true,
socialFollowAuto: false,
joinGroupWechat: false,
joinGroupDouyin: true,
offlineBadge: false,
},
copy: {
@ -139,6 +150,9 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
vipPriceFen: 0,
vipProductId: 'vip_membership',
vipCta: '本端免费开放',
wechatOaName: '异度世界',
joinGroupDouyinHint: '打开抖音搜群「数字游民」或扫码进群',
joinGroupDouyinQr: '',
},
platforms: {
tt: JSON.parse(JSON.stringify(DEFAULT_TT_PLATFORM)) as TtPlatformConfig,

View File

@ -0,0 +1,9 @@
import { useDidShow } from '@tarojs/taro'
import { trackPage } from '../utils/track'
/** 页面 show 时自动 page_view(去重由 trackPage 处理) */
export function usePageTrack(page: string, label?: string) {
useDidShow(() => {
trackPage(page, label)
})
}

View File

@ -1,5 +1,5 @@
/**
* 社区首页收敛:仅顶栏 + Hero;「加群」→ 公众号二维码。
* 社区首页收敛:仅顶栏 + Hero;「加群」→ 按后台 flags 弹抖音群/公众号。
* Hero 视觉:社交星座网(区别于门户首页地球)。对齐 Next `/community`。
*/
import { View, Button } from '@tarojs/components'
@ -16,6 +16,8 @@ import {
} from '@/services/remoteConfig'
import { useNomadroTheme } from '@/utils/h5Theme'
import { getSafeAreaMetrics } from '@/utils/safeArea'
import { usePageTrack } from '@/hooks/usePageTrack'
import { trackTap } from '@/utils/track'
import './index.scss'
const isH5 = process.env.TARO_ENV === 'h5'
@ -78,6 +80,7 @@ const SOCIAL_MESH_SVG = `<svg class="social-mesh-svg" viewBox="0 0 400 400" fill
</svg>`
function HomePageInner() {
usePageTrack('pages/community/index', '旅居社群')
const theme = useNomadroTheme()
const [tw, setTw] = useState('')
const [joinOpen, setJoinOpen] = useState(false)
@ -222,7 +225,7 @@ function HomePageInner() {
<H5Box className="hero-bottom">
{socialFollow ? (
<H5Box className="hero-actions">
<Button className="btn btn-primary" onClick={() => setJoinOpen(true)}>
<Button className="btn btn-primary" onClick={trackTap('加群', () => setJoinOpen(true))}>
👥 加群
</Button>
</H5Box>

View File

@ -4,12 +4,14 @@ import { useState } from 'react'
import { BrandNav, SiteFooter } from '../../components/Chrome'
import { fetchDestination, type Destination } from '../../services/api'
import './index.scss'
import { usePageTrack } from '../../hooks/usePageTrack'
function hueBg(hue = 170) {
return `linear-gradient(160deg, hsl(${hue}, 42%, 24%), hsl(${hue}, 30%, 10%))`
}
export default function DestinationPage() {
usePageTrack('pages/destination/index', '目的地详情')
const router = useRouter()
const [d, setD] = useState<Destination | null>(null)
const [err, setErr] = useState('')

View File

@ -5,8 +5,10 @@ import { BrandNav, SiteFooter } from '../../components/Chrome'
import { DestinationsSection } from '../../components/DestinationsSection'
import { fetchDestinations, type Destination } from '../../services/api'
import './index.scss'
import { usePageTrack } from '../../hooks/usePageTrack'
export default function DestinationsPage() {
usePageTrack('pages/destinations/index', '目的地列表')
const [list, setList] = useState<Destination[]>([])
const [err, setErr] = useState('')
const [loading, setLoading] = useState(true)

View File

@ -2,20 +2,20 @@
* 抖音启动页:默认 BMI(过审);homeVariant=hub 时跳正式门户
* 每次 onShow 强制拉配置,后台切换首页可近实时生效
*/
import { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { useEffect, useState } from \'react\'
import Taro, { useDidShow } from \'@tarojs/taro\'
import {
getCachedRemoteConfig,
loadRemoteConfig,
} from '@/services/remoteConfig'
} from \'@/services/remoteConfig\'
import {
resolveTtHomeVariantFromConfig,
type NomadroRemoteConfig,
} from '@/data/remoteConfig.defaults'
import { useNomadroTheme } from '@/utils/h5Theme'
import BmiHome from './BmiHome'
} from \'@/data/remoteConfig.defaults\'
import { useNomadroTheme } from \'@/utils/h5Theme\'
import BmiHome from \'./BmiHome\'
const HUB_PATH = '/pages/hub/index'
const HUB_PATH = \'/pages/hub/index\'
export default function IndexPage() {
const [config, setConfig] = useState<NomadroRemoteConfig>(() => getCachedRemoteConfig())
@ -25,7 +25,7 @@ export default function IndexPage() {
async function syncVariant(force = false) {
const r = await loadRemoteConfig(force)
setConfig(r.config)
if (resolveTtHomeVariantFromConfig(r.config) === 'hub') {
if (resolveTtHomeVariantFromConfig(r.config) === \'hub\') {
Taro.reLaunch({ url: HUB_PATH })
return false
}
@ -38,7 +38,7 @@ export default function IndexPage() {
syncVariant(true).then((ok) => {
if (cancelled || !ok) return
})
if (resolveTtHomeVariantFromConfig(getCachedRemoteConfig()) !== 'hub') {
if (resolveTtHomeVariantFromConfig(getCachedRemoteConfig()) !== \'hub\') {
setReady(true)
}
return () => {

View File

@ -4,8 +4,10 @@ import { useMemo, useState } from 'react'
import { BrandNav, SiteFooter } from '../../components/Chrome'
import { fetchMeetups, type Meetup } from '../../services/api'
import './index.scss'
import { usePageTrack } from '../../hooks/usePageTrack'
export default function MeetupsPage() {
usePageTrack('pages/meetups/index', '活动')
const [list, setList] = useState<Meetup[]>([])
const [mode, setMode] = useState<'all' | 'online' | 'offline' | 'hybrid'>('all')
const [fromLocal, setFromLocal] = useState(false)

View File

@ -15,8 +15,10 @@ import {
type ProfileStats,
} from '../../services/api'
import './index.scss'
import { usePageTrack } from '../../hooks/usePageTrack'
export default function MinePage() {
usePageTrack('pages/mine/index', '我的')
const [user, setUser] = useState<AuthUser | null>(null)
const [stats, setStats] = useState<ProfileStats | null>(null)
const [favs, setFavs] = useState<Destination[]>([])

View File

@ -9,6 +9,7 @@ import { MiniModuleGate } from '@/components/MiniModuleGate'
import { NavLinkSheet, type SheetLink } from '@/components/NavLinkSheet'
import { H5Box, H5Txt } from '@/components/H5Box'
import config from '@/data/links.json'
import { usePageTrack } from '../../hooks/usePageTrack'
import {
copyFailToast,
ttSetClipboardData,
@ -78,6 +79,7 @@ const CLOSE_SVG = `<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
</svg>`
function NavPageInner() {
usePageTrack('pages/nav/index', '出海导航')
const theme = useNomadroTheme()
const [activeId, setActiveId] = useState(visibleCategories[0]?.id ?? '')
const [drawerOpen, setDrawerOpen] = useState(false)

View File

@ -12,6 +12,7 @@ import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import { useNomadroTheme } from '@/utils/h5Theme'
import { goHome } from '@/utils/nav'
import { getSafeAreaMetrics } from '@/utils/safeArea'
import { usePageTrack } from '@/hooks/usePageTrack'
import './index.scss'
const isH5 = process.env.TARO_ENV === 'h5'
@ -148,6 +149,7 @@ export default function VipPage() {
}
function VipLanding() {
usePageTrack('pages/vip/index', '会员中心')
const theme = useNomadroTheme()
const [busy, setBusy] = useState(false)
const [cfg, setCfg] = useState<NomadroRemoteConfig>(getCachedRemoteConfig())
@ -181,7 +183,7 @@ function VipLanding() {
/** 抖音无支付:全免费,不展示锁/不拉支付 */
const payOk = cfg.flags.payEnabled !== false
const freeMode = !payOk
const priceFen = freeMode ? 0 : cfg.copy.vipPriceFen || 8800
const priceFen = freeMode ? 0 : cfg.copy.vipPriceFen || 29800
const productId = cfg.copy.vipProductId || 'vip_membership'
const cta = freeMode ? '本端免费开放' : cfg.copy.vipCta || '立即加入'
const brand = cfg.copy.homeBrand || 'nomadro'

View File

@ -1,5 +1,5 @@
import Taro from '@tarojs/taro'
import { API_BASE, APP_TARGET, WEB_BASE } from '../utils/config'
import { API_BASE, APP_TARGET, TT_CONFIG_BASES, WEB_BASE } from '../utils/config'
import {
DEFAULT_REMOTE_CONFIG,
mergeRemoteConfig,
@ -8,9 +8,11 @@ import {
type TtBookContent,
} from '../data/remoteConfig.defaults'
const STORAGE_KEY = 'nomadro_remote_config_v1'
/** v2:作废旧缓存里「小册默认开」的脏数据 */
const STORAGE_KEY = 'nomadro_remote_config_v2'
const CACHE_TTL_MS = 1000 * 60 * 30
/** 抖音小程序无支付:强制免费 */
/** 抖音无 EventSource:meta 近实时轮询 */
const META_POLL_MS = 8000
const TT_FORCE_FREE = process.env.TARO_ENV === 'tt'
type LoadResult = {
@ -19,33 +21,52 @@ type LoadResult = {
source: 'network' | 'storage' | 'bundle'
}
let memory: LoadResult | null = null
type Listener = (result: LoadResult) => void
let memory: LoadResult | null = null
const listeners = new Set<Listener>()
let liveStarted = false
let metaTimer: ReturnType<typeof setInterval> | null = null
let knownVersion = 0
/** 抖音:仅强制免费;模块显隐交给 platforms.tt(后台可控) */
function applyTtFreePolicy(config: NomadroRemoteConfig): NomadroRemoteConfig {
if (!TT_FORCE_FREE) return config
const tt = config.platforms?.tt
const tt = config.platforms?.tt || DEFAULT_REMOTE_CONFIG.platforms!.tt!
return {
...config,
// 顶层 modules 与 platforms.tt 对齐,方便旧闸门读 modules
modules: {
...config.modules,
nav: tt?.modules.nav || config.modules.nav,
book: tt?.modules.book || config.modules.book,
community: tt?.modules.community || config.modules.community,
// 必须用 ??:enabled:false 的对象也是 truthy,|| 没问题,但缺字段时不能 silently 用门户顶层
nav: tt.modules.nav ?? config.modules.nav,
book: tt.modules.book ?? config.modules.book,
community: tt.modules.community ?? config.modules.community,
},
flags: { ...config.flags, payEnabled: false },
copy: {
...config.copy,
vipPriceFen: 0,
vipCta: config.copy.vipCta?.includes('免费') ? config.copy.vipCta : '本端免费开放',
vipCta: config.copy.vipCta?.includes('免费')
? config.copy.vipCta
: '本端免费开放',
},
platforms: {
tt: tt || DEFAULT_REMOTE_CONFIG.platforms!.tt!,
tt,
},
}
}
function emit(result: LoadResult) {
memory = result
knownVersion = Number(result.config.version) || knownVersion
listeners.forEach((fn) => {
try {
fn(result)
} catch {
/* ignore */
}
})
}
function readStorage(): NomadroRemoteConfig | null {
try {
const raw = Taro.getStorageSync(STORAGE_KEY)
@ -67,13 +88,20 @@ function writeStorage(config: NomadroRemoteConfig) {
}
}
function withCacheBust(url: string): string {
const sep = url.includes('?') ? '&' : '?'
return `${url}${sep}_=${Date.now()}`
}
async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
// 生产可用:api.nomadro.cn/api/config(含 platforms.tt.homeVariant)
// nomadro.cn/api/config 证书/域名常失败;/v1/config 现网 404
// 真机走白名单域名 + 有效证书(含 platforms.tt.homeVariant)。
// nomadro.cn 证书 SAN 不匹配会 TLS 失败;优先 api / dyapi。
const urls =
APP_TARGET === 'h5'
? ['/api/config']
: [
...TT_CONFIG_BASES.map((b) => `${b}/api/config`),
...TT_CONFIG_BASES.map((b) => `${b}/api/ebook/config`),
`${API_BASE}/api/config`,
`${API_BASE}/v1/config`,
`${WEB_BASE}/api/config`,
@ -82,9 +110,10 @@ async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
for (const url of urls) {
try {
const res = await Taro.request({
url,
url: withCacheBust(url),
method: 'GET',
timeout: 6000,
timeout: 8000,
header: { 'Cache-Control': 'no-cache' },
})
if (res.statusCode >= 400) continue
const body = res.data as { config?: Partial<NomadroRemoteConfig> }
@ -99,12 +128,43 @@ async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
return null
}
/**
* 兜底顺序:内存 → 网络 → Storage → 包内 DEFAULT
*/
async function fetchMeta(): Promise<{ version: number; updatedAt: string } | null> {
const urls =
APP_TARGET === 'h5'
? ['/api/config/meta']
: [
...TT_CONFIG_BASES.map((b) => `${b}/api/config/meta`),
...TT_CONFIG_BASES.map((b) => `${b}/api/ebook/config/meta`),
`${WEB_BASE}/api/config/meta`,
]
for (const url of urls) {
try {
const res = await Taro.request({
url: withCacheBust(url),
method: 'GET',
timeout: 5000,
header: { 'Cache-Control': 'no-cache' },
})
if (res.statusCode >= 400) continue
const body = res.data as { version?: number; updatedAt?: string }
if (body?.version != null) {
return {
version: Number(body.version) || 0,
updatedAt: String(body.updatedAt || ''),
}
}
} catch {
/* try next */
}
}
return null
}
export async function loadRemoteConfig(force = false): Promise<LoadResult> {
if (!force && memory) return memory
// force 也读缓存:网络失败时仍用上次成功同步的后台 flags(加群/入口)
const cached = readStorage()
try {
@ -112,24 +172,35 @@ export async function loadRemoteConfig(force = false): Promise<LoadResult> {
if (remote) {
const config = applyTtFreePolicy(remote)
writeStorage(config)
memory = { config, fromOffline: false, source: 'network' }
return memory
const result: LoadResult = {
config,
fromOffline: false,
source: 'network',
}
emit(result)
return result
}
} catch {
/* fall through */
}
if (cached) {
memory = { config: applyTtFreePolicy(cached), fromOffline: true, source: 'storage' }
return memory
const result: LoadResult = {
config: applyTtFreePolicy(cached),
fromOffline: true,
source: 'storage',
}
emit(result)
return result
}
memory = {
const result: LoadResult = {
config: applyTtFreePolicy(mergeRemoteConfig(DEFAULT_REMOTE_CONFIG)),
fromOffline: true,
source: 'bundle',
}
return memory
emit(result)
return result
}
export function getCachedRemoteConfig(): NomadroRemoteConfig {
@ -150,6 +221,12 @@ export function isModuleEnabled(
config: NomadroRemoteConfig,
key: keyof NomadroRemoteConfig['modules'],
): boolean {
// 抖音入口:只认 platforms.tt,绝不回退到门户顶层 modules(线上顶层全是 true)
if (TT_FORCE_FREE && (key === 'nav' || key === 'book' || key === 'community')) {
const tt = config.platforms?.tt?.modules?.[key]
if (tt && typeof tt.enabled === 'boolean') return tt.enabled
return false
}
if (key === 'nav' || key === 'book' || key === 'community') {
const tt = config.platforms?.tt?.modules?.[key]
if (tt && typeof tt.enabled === 'boolean') return tt.enabled
@ -157,7 +234,45 @@ export function isModuleEnabled(
return Boolean(config.modules[key]?.enabled)
}
/** 当前生效的抖音小册正文(远程优先,包内 7 章兜底) */
export function getTtBookContent(config?: NomadroRemoteConfig): TtBookContent {
return resolveTtBookContent(config || getCachedRemoteConfig())
}
export function subscribeRemoteConfig(listener: Listener): () => void {
listeners.add(listener)
if (memory) listener(memory)
return () => listeners.delete(listener)
}
async function softCheckMeta() {
const meta = await fetchMeta()
if (!meta) {
await loadRemoteConfig(true)
return
}
if (knownVersion && meta.version === knownVersion) return
await loadRemoteConfig(true)
}
/** 抖音:meta 轮询 + 前台唤醒(无 EventSource) */
export function startRemoteConfigLiveSync(): () => void {
if (liveStarted) return () => {}
liveStarted = true
knownVersion = Number(getCachedRemoteConfig().version) || 0
metaTimer = setInterval(() => {
void softCheckMeta()
}, META_POLL_MS)
return () => {
liveStarted = false
if (metaTimer) {
clearInterval(metaTimer)
metaTimer = null
}
}
}
export function softRefreshRemoteConfig(): void {
void softCheckMeta()
}

View File

@ -42,4 +42,12 @@ export const STORAGE_TOKEN = 'nomadro_token'
export const STORAGE_OPENID = 'nomadro_openid'
export const WEB_BASE = 'https://nomadro.cn'
/**
* 抖音 request 合法域名 + 有效 TLS(nomadro.cn 证书主机名不匹配,真机必挂)
* 开发者工具不校验证书所以看似正常。
*/
export const TT_CONFIG_BASES = [
'https://api.nomadro.cn',
'https://dyapi.nomadro.cn',
] as const
export const WX_APPID = 'wxa55815dd741a540d'

View File

@ -1,4 +1,5 @@
import Taro from '@tarojs/taro'
import { trackClick } from './track'
/**
* 抖音无 tabBar:一律 navigate / redirect / reLaunch。
@ -8,6 +9,7 @@ export function goPage(url: string): void {
const path = raw.startsWith('/') ? raw : `/${raw}`
const qs = url.includes('?') ? url.slice(url.indexOf('?')) : ''
const full = `${path}${qs}`
trackClick('页面跳转', { to: full })
if (path.includes('/pages/index')) {
Taro.reLaunch({ url: full }).catch(() =>

View File

@ -1,7 +1,8 @@
import Taro from '@tarojs/taro'
import { API_BASE, STORAGE_OPENID, STORAGE_TOKEN } from './config'
import { API_BASE, APP_TARGET, STORAGE_OPENID, STORAGE_TOKEN } from './config'
type TrackProps = Record<string, string | number | boolean | null | undefined>
export type TrackChannel = 'tt' | 'weapp' | 'h5'
export type TrackProps = Record<string, string | number | boolean | null | undefined>
type TrackItem = {
name: string
@ -14,9 +15,30 @@ type TrackItem = {
const queue: TrackItem[] = []
let flushTimer: ReturnType<typeof setTimeout> | null = null
let flushing = false
let lastPageView = { key: '', at: 0 }
/** 抖音端标识,便于后台埋点筛选 */
const CLIENT = 'tt'
/** 上报 client:抖音 tt / 微信 weapp / H5 h5 */
export function getTrackClient(): TrackChannel {
const env = process.env.TARO_ENV
if (env === 'tt') return 'tt'
if (env === 'h5') return 'h5'
if (APP_TARGET === 'tt') return 'tt'
if (APP_TARGET === 'h5') return 'h5'
return 'weapp'
}
export function getTrackChannelLabel(client?: string): string {
switch (client || getTrackClient()) {
case 'tt':
return '抖音'
case 'weapp':
return '微信'
case 'h5':
return 'H5'
default:
return client || '未知'
}
}
function currentPage(): string {
try {
@ -28,6 +50,13 @@ function currentPage(): string {
}
}
function withChannelProps(props?: TrackProps): TrackProps {
return {
channel: getTrackClient(),
...props,
}
}
function scheduleFlush(immediate = false) {
if (immediate) {
if (flushTimer) {
@ -57,7 +86,7 @@ export async function flush(): Promise<void> {
data: {
events: batch,
openid: openid || undefined,
client: CLIENT,
client: getTrackClient(),
},
timeout: 5000,
header: {
@ -82,7 +111,7 @@ export function track(
name,
page: opts?.page || currentPage(),
label: opts?.label,
props: opts?.props,
props: withChannelProps(opts?.props),
ts: Date.now() / 1000,
})
if (opts?.immediate || queue.length >= 8) {
@ -93,6 +122,10 @@ export function track(
}
export function trackPage(page: string, label?: string, props?: TrackProps) {
const key = `${page}|${label || page}`
const now = Date.now()
if (lastPageView.key === key && now - lastPageView.at < 1500) return
lastPageView = { key, at: now }
track('page_view', { page, label: label || page, props, immediate: true })
}
@ -100,9 +133,42 @@ export function trackClick(label: string, props?: TrackProps) {
track('btn_click', { label, props, immediate: true })
}
/** onClick 包装:先埋点再执行 */
export function trackTap<T extends (...args: never[]) => void>(
label: string,
handler?: T,
props?: TrackProps,
): (...args: Parameters<T>) => void {
return (...args: Parameters<T>) => {
trackClick(label, props)
handler?.(...args)
}
}
export function trackPay(
stage: 'start' | 'success' | 'cancel' | 'fail' | 'pending',
props?: TrackProps,
) {
track(`pay_${stage}`, { label: stage, props, immediate: true })
}
export function trackJoinGroup(
stage: 'open' | 'show' | 'dismiss' | 'qr_preview',
opts?: { popup?: 'wechat' | 'douyin'; offline?: boolean; label?: string },
) {
track(`join_group_${stage}`, {
label: opts?.label || stage,
props: {
popup: opts?.popup,
offline: opts?.offline,
},
})
}
export function trackAppLaunch() {
track('app_launch', {
label: getTrackChannelLabel(),
props: { channel: getTrackClient() },
immediate: true,
})
}

View File

@ -833,7 +833,7 @@
'<button type="button" class="vip-btnPrimary vip-btnLarge vip-ctaBtnPrimary" id="vip-cta">🔒 ' +
escapeHtml(vip.cta || "立即加入") +
" · " +
escapeHtml(vip.priceLabel || "¥88") +
escapeHtml(vip.priceLabel || "¥298") +
'</button><button type="button" class="vip-ctaBtnSecondary" id="vip-login">已有账号</button></div>' +
'<p class="vip-ctaHint">开通请用微信小程序或 nomadro.cn/vip</p></div></div></div>';

View File

@ -5,7 +5,7 @@ var PORTAL_DATA = {
"homeTagline": "随处工作 · 自由生活",
"homeLead": "导航 · 小册 · 社群 · VIP · 离线可用",
"vipCta": "立即加入",
"vipPriceFen": 8800,
"vipPriceFen": 29800,
"modules": {
"nav": {
"enabled": true,
@ -967,8 +967,8 @@ var PORTAL_DATA = {
"titleRest": "持续更新 · 抱团出海",
"lead": "一次付费,解锁电子书、视频教程、私密社群、即时问答,每周更新",
"cta": "立即加入",
"priceFen": 8800,
"priceLabel": "¥88",
"priceFen": 29800,
"priceLabel": "¥298",
"portalUrl": "https://nomadro.cn/vip",
"stats": [
{

View File

@ -1,5 +1,5 @@
{
"version": 2,
"version": 3,
"updatedAt": "2026-03-30T12:00:00.000Z",
"modules": {
"home": {
@ -39,6 +39,8 @@
"payEnabled": true,
"socialFollow": true,
"socialFollowAuto": false,
"joinGroupWechat": false,
"joinGroupDouyin": true,
"offlineBadge": false
},
"copy": {
@ -47,7 +49,10 @@
"homeLead": "",
"vipPriceFen": 29800,
"vipProductId": "vip_membership",
"vipCta": "立即加入"
"vipCta": "立即加入",
"wechatOaName": "异度世界",
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
"joinGroupDouyinQr": ""
},
"platforms": {
"tt": {
@ -60,16 +65,16 @@
"note": "抖音默认隐藏,后台可开"
},
"book": {
"enabled": true,
"enabled": false,
"title": "数字游民小册",
"tabLabel": "小册",
"note": "默认开启 · 正文可远程改"
"note": "默认关闭 · 以后台入口开关为准"
},
"community": {
"enabled": false,
"enabled": true,
"title": "旅居社群",
"tabLabel": "社群",
"note": "抖音默认隐藏,后台可开"
"note": "抖音默认入口 · 后台可关"
}
},
"bookContent": {
@ -140,4 +145,4 @@
}
}
}
}
}

View File

@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Hotfix join-group frontend logic on 82.157.112.245 (source sync + portal rebuild)."""
from __future__ import annotations
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REPO = Path(__file__).resolve().parents[2]
FILES = [
(
REPO / "src/components/social-follow.tsx",
"/var/www/nomadro.cn/src/components/social-follow.tsx",
),
(
REPO / "apps/miniprogram/h5/src/components/WechatOaModal.tsx",
"/var/www/nomadro.cn/apps/miniprogram/h5/src/components/WechatOaModal.tsx",
),
(
REPO / "apps/miniprogram/h5/src/data/remoteConfig.defaults.ts",
"/var/www/nomadro.cn/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts",
),
(
REPO / "apps/miniprogram/tt/src/components/WechatOaModal.tsx",
"/var/www/nomadro.cn/apps/miniprogram/tt/src/components/WechatOaModal.tsx",
),
(
REPO / "apps/miniprogram/tt/src/data/remoteConfig.defaults.ts",
"/var/www/nomadro.cn/apps/miniprogram/tt/src/data/remoteConfig.defaults.ts",
),
(
REPO / "src/lib/remote-config.ts",
"/var/www/nomadro.cn/src/lib/remote-config.ts",
),
(
REPO / "data/remote-config.json",
"/var/www/nomadro.cn/data/remote-config.json.seed-check",
),
]
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 900) -> int:
print(f"$ {cmd[:200]}", flush=True)
_, stdout, _ = c.exec_command(cmd, timeout=timeout, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
return code
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
t = c.get_transport()
if t:
t.set_keepalive(15)
sftp = c.open_sftp()
for local, remote in FILES:
if not local.is_file():
print("missing", local)
return 1
# seed-check: don't overwrite live remote-config; only upload sources
if remote.endswith(".seed-check"):
print("skip live remote-config overwrite:", remote)
continue
print(f"upload {local.name} -> {remote}", flush=True)
# ensure parent exists & writable via temp then sudo mv
tmp = f"/tmp/jgfix_{local.name}"
with sftp.file(tmp, "wb") as rf:
rf.write(local.read_bytes())
run(c, f"sudo cp {tmp} {remote} && sudo chown ubuntu:ubuntu {remote} && rm -f {tmp}", 60)
sftp.close()
# Additive flags only (never wipe)
run(
c,
r"""
sudo python3 <<'PY'
import json
from pathlib import Path
p = Path('/var/www/nomadro.cn/data/remote-config.json')
cfg = json.loads(p.read_text(encoding='utf-8'))
flags = cfg.setdefault('flags', {})
copy = cfg.setdefault('copy', {})
changed = False
for k, v in {
'joinGroupWechat': True,
'joinGroupDouyin': False,
'socialFollowAuto': False,
}.items():
if k not in flags:
flags[k] = v
changed = True
for k, v in {
'wechatOaName': '异度世界',
'joinGroupDouyinHint': '打开抖音搜群「数字游民」或扫码进群',
'joinGroupDouyinQr': '',
}.items():
if k not in copy:
copy[k] = v
changed = True
if changed:
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print('seeded flags')
else:
print('flags ok')
print('flags', {k: flags.get(k) for k in ('joinGroupWechat','joinGroupDouyin','socialFollowAuto','socialFollow')})
PY
""",
60,
)
# Verify TT modal no longer switches on later
run(
c,
r"""
grep -n 'onLater\|setShowOa\|joinGroupWechat\|稍后再说' \
/var/www/nomadro.cn/apps/miniprogram/tt/src/components/WechatOaModal.tsx \
/var/www/nomadro.cn/src/components/social-follow.tsx | head -40
""",
30,
)
# Rebuild portal (source-based production)
code = run(
c,
r"""
set -euo pipefail
cd /var/www/nomadro.cn
# preserve remote-config across build side effects
cp -a data/remote-config.json /tmp/remote-config.pre-jg.json
export NODE_OPTIONS=--max-old-space-size=4096
/usr/local/bin/pnpm build
cp -a /tmp/remote-config.pre-jg.json data/remote-config.json
sudo systemctl restart nomadro.service
sleep 4
systemctl is-active nomadro.service
curl -sk -o /dev/null -w 'portal %{http_code}\n' https://nomadro.cn/
curl -sk https://nomadro.cn/api/config | python3 -c "import sys,json; f=json.load(sys.stdin).get('config',{}).get('flags',{}); print('flags', {k:f.get(k) for k in ('joinGroupWechat','joinGroupDouyin','socialFollowAuto')})"
grep -n 'joinGroupWechat\|稍后再说\|DISMISS_KEY\|setShowOa' src/components/social-follow.tsx | head -20
echo DONE
""",
1200,
)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Sync TT miniprogram dist+src join-group fix to production box (for IDE publish backup)."""
from __future__ import annotations
import io
import sys
import tarfile
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
TT = Path(__file__).resolve().parents[2] / "apps" / "miniprogram" / "tt"
REMOTE_DIR = "/var/www/nomadro.cn/apps/miniprogram/tt"
def main() -> int:
if not (TT / "dist" / "app.json").exists():
print("missing tt/dist — run pnpm build:tt first")
return 1
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel in (
"dist",
"src/components/WechatOaModal.tsx",
"src/data/remoteConfig.defaults.ts",
"README.md",
"project.tt.json",
):
p = TT / rel
if p.is_dir():
for f in p.rglob("*"):
if f.is_file():
tar.add(f, arcname=f.relative_to(TT).as_posix())
elif p.is_file():
tar.add(p, arcname=rel.replace("\\", "/"))
payload = buf.getvalue()
print(f"pack {len(payload)/1024/1024:.1f} MB", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
banner_timeout=120,
allow_agent=False,
look_for_keys=False,
)
t = c.get_transport()
if t:
t.set_keepalive(10)
sftp = c.open_sftp()
with sftp.file("/tmp/tt-jg.tar.gz", "wb") as rf:
rf.write(payload)
sftp.close()
print("uploaded", flush=True)
cmd = rf"""
set -euo pipefail
cd /tmp
rm -rf tt-jg-unpack && mkdir tt-jg-unpack
tar -xzf tt-jg.tar.gz -C tt-jg-unpack
sudo mkdir -p {REMOTE_DIR}
# sync dist replace
if [ -d tt-jg-unpack/dist ]; then
sudo rsync -a --delete tt-jg-unpack/dist/ {REMOTE_DIR}/dist/
fi
# sync source fixes
sudo mkdir -p {REMOTE_DIR}/src/components {REMOTE_DIR}/src/data
sudo cp -a tt-jg-unpack/src/components/WechatOaModal.tsx {REMOTE_DIR}/src/components/
sudo cp -a tt-jg-unpack/src/data/remoteConfig.defaults.ts {REMOTE_DIR}/src/data/
sudo cp -a tt-jg-unpack/README.md {REMOTE_DIR}/ 2>/dev/null || true
sudo cp -a tt-jg-unpack/project.tt.json {REMOTE_DIR}/ 2>/dev/null || true
sudo chown -R ubuntu:ubuntu {REMOTE_DIR}
# verify bundle has new logic / no old switch
echo '--- verify ---'
grep -c setShowOa {REMOTE_DIR}/dist/pages/community/index.js || echo setShowOa=0
grep -c joinGroupWechat {REMOTE_DIR}/dist/pages/community/index.js || echo join=0
grep -c joinGroupWechat {REMOTE_DIR}/src/components/WechatOaModal.tsx
# portal smoke
curl -sk -o /dev/null -w 'portal %{{http_code}}\n' https://nomadro.cn/
curl -sk https://nomadro.cn/api/config | python3 -c "import sys,json; f=json.load(sys.stdin).get('config',{{}}).get('flags',{{}}); print('flags', {{k:f.get(k) for k in ('joinGroupWechat','joinGroupDouyin','socialFollowAuto')}})"
rm -rf tt-jg-unpack tt-jg.tar.gz
echo DONE
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
sys.stdout.write(chunk.encode("ascii", "replace").decode("ascii"))
sys.stdout.flush()
time.sleep(0.05)
while stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
sys.stdout.write(chunk.encode("ascii", "replace").decode("ascii"))
sys.stdout.flush()
code = stdout.channel.recv_exit_status()
c.close()
print(f"\n[exit {code}]", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -143,10 +143,20 @@ export default function AdminConfigPage() {
label: "关注引导总开关",
hint: "关闭后不自动弹出「关注公众号 / X」弹窗(含稍后再说)",
},
{
key: "joinGroupWechat" as const,
label: "加群 → 微信公众号",
hint: "后台开关;用户点「加群」时引导关注公众号(用户端无 switch)",
},
{
key: "joinGroupDouyin" as const,
label: "加群 → 抖音群",
hint: "后台开关;用户点「加群」时引导进抖音群(用户端无 switch)",
},
{
key: "socialFollowAuto" as const,
label: "自动弹出关注公众号(稍后再说)",
hint: "开启后首页延迟约 4.5s 弹出;需同时打开「关注引导总开关」。默认关闭。",
label: "自动弹出关注引导",
hint: "开启后首页延迟弹出;「稍后再说」= 永久关闭。默认关。",
},
{
key: "offlineBadge" as const,

View File

@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import {
ensureConfigFileWatcher,
refreshConfigMeta,
} from "~/lib/remote-config-live";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/** 轻量版本探针:小程序轮询 / 前端比对 */
export async function GET() {
ensureConfigFileWatcher();
const meta = await refreshConfigMeta();
return NextResponse.json({
ok: true,
version: meta.version,
updatedAt: meta.updatedAt,
});
}

View File

@ -0,0 +1,74 @@
import {
ensureConfigFileWatcher,
onConfigChange,
refreshConfigMeta,
} from "~/lib/remote-config-live";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* SSE:后台改 remote-config → 立刻推 version/updatedAt。
* 门户 / H5 EventSource 订阅;小程序无 EventSource 时改轮询 /api/config/meta。
*/
export async function GET() {
ensureConfigFileWatcher();
const encoder = new TextEncoder();
let closed = false;
let unsub = () => {};
let heartbeat: ReturnType<typeof setInterval> | null = null;
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const send = (event: string, data: unknown) => {
if (closed) return;
try {
controller.enqueue(
encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
);
} catch {
closed = true;
}
};
try {
const meta = await refreshConfigMeta();
send("config", meta);
} catch {
send("config", { version: 1, updatedAt: "" });
}
unsub = onConfigChange((payload) => {
send("config", {
version: payload.version,
updatedAt: payload.updatedAt,
source: payload.source,
});
});
heartbeat = setInterval(() => {
if (closed) return;
try {
controller.enqueue(encoder.encode(`: ping\n\n`));
} catch {
closed = true;
}
}, 15000);
},
cancel() {
closed = true;
unsub();
if (heartbeat) clearInterval(heartbeat);
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
}

View File

@ -12,7 +12,7 @@ import { queryXorPayOrderStatus } from "@vip/app/lib/xorpayStatus";
import { queryZPayOrderStatus } from "@vip/app/lib/zpayStatus";
const getDefaultTotalFee = () =>
getPaymentConfig().defaultAmount ?? Number(process.env.PAYMENT_DEFAULT_AMOUNT) ?? 18800;
getPaymentConfig().defaultAmount ?? Number(process.env.PAYMENT_DEFAULT_AMOUNT) ?? 29800;
function parsePayPriceToCents(payPrice: unknown): number | null {
if (payPrice == null) return null;

View File

@ -320,7 +320,7 @@ export async function triggerPay(
(getStorage("wechatUserId") || "").trim() ||
(getStorage("userid") || "").trim();
const isPayTestMode = getStorage(VIP_PAY_TEST_MODE_KEY) === "1";
const totalFee = isPayTestMode ? 100 : getPaymentConfig().defaultAmount ?? 8800;
const totalFee = isPayTestMode ? 100 : getPaymentConfig().defaultAmount ?? 29800;
const profile = getDisplayProfile();
const shouldShowLaunchOverlay =
device !== "wechat" && !!(profile.avatar || "").trim();

View File

@ -5,29 +5,31 @@ import { isChinaUser } from "is-china-user";
import { useLocale } from "~/components/locale-provider";
import styles from "./social-follow.module.css";
const DISMISS_KEY = "nomadro-social-dismiss";
const DISMISS_MS = 1000 * 60 * 60 * 24 * 7; // 7 days
const SHOW_DELAY_MS = 4500;
const X_URL = "https://x.com/nomadro";
/** Public WeChat OA QR — replace asset when brand QR updates */
export const WECHAT_OA_QR = "/wechat-oa-qr.png";
type Mode = "x" | "wechat";
type Mode = "x" | "wechat" | "douyin";
function shouldShow(): boolean {
try {
const raw = localStorage.getItem(DISMISS_KEY);
if (!raw) return true;
const ts = Number(raw);
if (!Number.isFinite(ts)) return true;
return Date.now() - ts > DISMISS_MS;
} catch {
return true;
}
}
type JoinMeta = {
wechatName: string;
douyinHint: string;
douyinQr: string;
joinWechat: boolean;
joinDouyin: boolean;
};
/** 受控:加群 / 关注公众号二维码弹窗 */
const DEFAULT_META: JoinMeta = {
wechatName: "nomadro",
douyinHint: "打开抖音搜群「数字游民」或扫码进群",
douyinQr: "",
joinWechat: true,
joinDouyin: false,
};
/** 受控:加群弹窗(内容由后台 joinGroup* 开关决定;用户无感知 switch) */
export function WechatOaModal({
open,
onClose,
@ -35,8 +37,45 @@ export function WechatOaModal({
open: boolean;
onClose: () => void;
}) {
const [meta, setMeta] = useState<JoinMeta>(DEFAULT_META);
const [channel, setChannel] = useState<"wechat" | "douyin">("wechat");
useEffect(() => {
if (!open) return;
let cancelled = false;
void (async () => {
try {
const res = await fetch("/api/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
const flags = data?.config?.flags || {};
const copy = data?.config?.copy || {};
const m: JoinMeta = {
wechatName: String(copy.wechatOaName || "异度世界"),
douyinHint: String(
copy.joinGroupDouyinHint || DEFAULT_META.douyinHint,
),
douyinQr: String(copy.joinGroupDouyinQr || ""),
joinWechat: flags.joinGroupWechat !== false,
joinDouyin: flags.joinGroupDouyin === true,
};
if (cancelled) return;
setMeta(m);
if (m.joinWechat) setChannel("wechat");
else if (m.joinDouyin) setChannel("douyin");
else onClose();
} catch {
/* keep defaults */
}
})();
return () => {
cancelled = true;
};
}, [open, onClose]);
if (!open) return null;
const isDouyin = channel === "douyin";
return (
<div className={styles.root} role="dialog" aria-modal="true" aria-labelledby="wechat-oa-title">
<button type="button" className={styles.backdrop} aria-label="关闭" onClick={onClose} />
@ -47,27 +86,52 @@ export function WechatOaModal({
</button>
<p className={styles.eyebrow}>保持连接</p>
<h2 id="wechat-oa-title" className={styles.title}>
关注 <span className={styles.accent}>公众号</span>
{isDouyin ? (
<>
加入 <span className={styles.accent}>抖音群</span>
</>
) : (
<>
关注 <span className={styles.accent}>公众号</span>
</>
)}
</h2>
<p className={styles.lead}>获取出海导航、游民社群与会员更新,扫码即达。</p>
<p className={styles.lead}>
{isDouyin
? meta.douyinHint
: "获取出海导航、游民社群与会员更新,扫码即达。"}
</p>
<div className={styles.qrWrap}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className={styles.qr}
src={WECHAT_OA_QR}
alt="微信公众号二维码"
width={180}
height={180}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
const fallback = e.currentTarget.nextElementSibling;
if (fallback instanceof HTMLElement) fallback.hidden = false;
}}
/>
<div className={styles.qrFallback} hidden>
<span aria-hidden>📱</span>
<p>请搜索公众号「nomadro」</p>
</div>
{isDouyin && !meta.douyinQr ? (
<div className={styles.qrFallback}>
<span aria-hidden>🎵</span>
<p>{meta.douyinHint}</p>
</div>
) : (
<>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className={styles.qr}
src={isDouyin ? meta.douyinQr : WECHAT_OA_QR}
alt={isDouyin ? "抖音群二维码" : "微信公众号二维码"}
width={180}
height={180}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
const fallback = e.currentTarget.nextElementSibling;
if (fallback instanceof HTMLElement) fallback.hidden = false;
}}
/>
<div className={styles.qrFallback} hidden>
<span aria-hidden>{isDouyin ? "🎵" : "📱"}</span>
<p>
{isDouyin
? meta.douyinHint
: `请搜索公众号「${meta.wechatName}」`}
</p>
</div>
</>
)}
</div>
<button type="button" className={styles.later} onClick={onClose}>
稍后再说
@ -79,21 +143,20 @@ export function WechatOaModal({
/**
* 自动引导弹窗(默认关闭;远程 flags.socialFollowAuto === true 才延迟弹出)
* 社区「加群」请用 WechatOaModal
* 「稍后再说」= 仅关闭弹窗(不切换通道、不写永久 dismiss)
*/
export function SocialFollowPrompt() {
const { locale, ready } = useLocale();
const [open, setOpen] = useState(false);
const [mode, setMode] = useState<Mode>("wechat");
const [meta, setMeta] = useState<JoinMeta>(DEFAULT_META);
useEffect(() => {
if (!ready) return;
if (!shouldShow()) return;
let cancelled = false;
let timer = 0;
const china = Boolean(isChinaUser()) || locale === "zh";
setMode(china ? "wechat" : "x");
void (async () => {
let allow = false;
@ -101,9 +164,25 @@ export function SocialFollowPrompt() {
const res = await fetch("/api/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
const flags = data?.config?.flags;
// 双开关:总开关关 → 永不弹;自动弹须显式 true(默认 false,现网不变)
const copy = data?.config?.copy || {};
allow =
flags?.socialFollow !== false && flags?.socialFollowAuto === true;
if (!cancelled) {
const m: JoinMeta = {
wechatName: String(copy.wechatOaName || "异度世界"),
douyinHint: String(
copy.joinGroupDouyinHint || DEFAULT_META.douyinHint,
),
douyinQr: String(copy.joinGroupDouyinQr || ""),
joinWechat: flags?.joinGroupWechat !== false,
joinDouyin: flags?.joinGroupDouyin === true,
};
setMeta(m);
if (!china) setMode("x");
else if (m.joinWechat) setMode("wechat");
else if (m.joinDouyin) setMode("douyin");
else setMode("wechat");
}
} catch {
allow = false;
}
@ -119,16 +198,12 @@ export function SocialFollowPrompt() {
const dismiss = useCallback(() => {
setOpen(false);
try {
localStorage.setItem(DISMISS_KEY, String(Date.now()));
} catch {
/* ignore */
}
}, []);
if (!open) return null;
const isZh = mode === "wechat";
const isZh = mode === "wechat" || mode === "douyin";
const isDouyin = mode === "douyin";
return (
<div className={styles.root} role="dialog" aria-modal="true" aria-labelledby="social-follow-title">
@ -140,41 +215,60 @@ export function SocialFollowPrompt() {
</button>
<p className={styles.eyebrow}>{isZh ? "保持连接" : "Stay in the loop"}</p>
<h2 id="social-follow-title" className={styles.title}>
{isZh ? (
{!isZh ? (
<>
关注 <span className={styles.accent}>公众号</span>
Follow us on <span className={styles.accent}>X</span>
</>
) : isDouyin ? (
<>
加入 <span className={styles.accent}>抖音群</span>
</>
) : (
<>
Follow us on <span className={styles.accent}>X</span>
关注 <span className={styles.accent}>公众号</span>
</>
)}
</h2>
<p className={styles.lead}>
{isZh
? "获取出海导航、游民社群与会员更新,扫码即达。"
: "Nomad nav, community drops, and VIP updates — one follow away."}
{!isZh
? "Nomad nav, community drops, and VIP updates — one follow away."
: isDouyin
? meta.douyinHint
: "获取出海导航、游民社群与会员更新,扫码即达。"}
</p>
{isZh ? (
<div className={styles.qrWrap}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className={styles.qr}
src={WECHAT_OA_QR}
alt="微信公众号二维码"
width={180}
height={180}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
const fallback = e.currentTarget.nextElementSibling;
if (fallback instanceof HTMLElement) fallback.hidden = false;
}}
/>
<div className={styles.qrFallback} hidden>
<span aria-hidden>📱</span>
<p>请搜索公众号「nomadro」</p>
</div>
{isDouyin && !meta.douyinQr ? (
<div className={styles.qrFallback}>
<span aria-hidden>🎵</span>
<p>{meta.douyinHint}</p>
</div>
) : (
<>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className={styles.qr}
src={isDouyin ? meta.douyinQr : WECHAT_OA_QR}
alt={isDouyin ? "抖音群二维码" : "微信公众号二维码"}
width={180}
height={180}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
const fallback = e.currentTarget.nextElementSibling;
if (fallback instanceof HTMLElement) fallback.hidden = false;
}}
/>
<div className={styles.qrFallback} hidden>
<span aria-hidden>{isDouyin ? "🎵" : "📱"}</span>
<p>
{isDouyin
? meta.douyinHint
: `请搜索公众号「${meta.wechatName}」`}
</p>
</div>
</>
)}
</div>
) : (
<a

View File

@ -0,0 +1,93 @@
/**
* 远程配置实时总线:本地写入 + 文件变更(FastAPI 后台同文件写入)→ SSE 推送。
*/
import { EventEmitter } from "node:events";
import { watch, type FSWatcher } from "node:fs";
import path from "node:path";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
export type ConfigMeta = {
version: number;
updatedAt: string;
};
type ChangePayload = ConfigMeta & { source: "write" | "watch" | "poll" };
const bus = new EventEmitter();
bus.setMaxListeners(200);
const FILE = path.join(process.cwd(), "data", "remote-config.json");
let watcher: FSWatcher | null = null;
let lastMeta: ConfigMeta | null = null;
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
let started = false;
function sameMeta(a: ConfigMeta | null, b: ConfigMeta): boolean {
return Boolean(
a && a.version === b.version && a.updatedAt === b.updatedAt,
);
}
export function getLastConfigMeta(): ConfigMeta | null {
return lastMeta;
}
export async function refreshConfigMeta(): Promise<ConfigMeta> {
const cfg = await readRemoteConfigFile();
return {
version: Number(cfg.version) || 1,
updatedAt: String(cfg.updatedAt || ""),
};
}
export function notifyConfigChanged(
meta: ConfigMeta,
source: ChangePayload["source"] = "write",
): void {
if (sameMeta(lastMeta, meta)) return;
lastMeta = meta;
bus.emit("change", { ...meta, source } satisfies ChangePayload);
}
export function onConfigChange(
listener: (payload: ChangePayload) => void,
): () => void {
bus.on("change", listener);
return () => bus.off("change", listener);
}
async function emitFromDisk(source: ChangePayload["source"]) {
try {
const meta = await refreshConfigMeta();
notifyConfigChanged(meta, source);
} catch {
/* ignore */
}
}
/** 单例:监听 remote-config.json(覆盖门户 PUT + FastAPI 加群/抖音写同一文件) */
export function ensureConfigFileWatcher(): void {
if (started || typeof window !== "undefined") return;
started = true;
void emitFromDisk("poll");
try {
watcher = watch(FILE, { persistent: false }, () => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
void emitFromDisk("watch");
}, 200);
});
watcher.on("error", () => {
/* 文件暂不存在时忽略 */
});
} catch {
/* watch 不可用时靠 SSE 内轮询 */
}
// 兜底轮询(跨进程 / 某些 FS 不触发 watch,例如 FastAPI 另进程写入)
setInterval(() => {
void emitFromDisk("poll");
}, 4000);
}

View File

@ -53,6 +53,8 @@ function assertSafeConfig(cfg: NomadroRemoteConfig): void {
"payEnabled",
"socialFollow",
"socialFollowAuto",
"joinGroupWechat",
"joinGroupDouyin",
"offlineBadge",
] as const) {
if (typeof cfg.flags[k] !== "boolean") {
@ -80,14 +82,25 @@ export async function writeRemoteConfigFile(
tt: next.platforms?.tt ?? current.platforms?.tt,
},
};
// 每次写入递增 version,前端靠 meta 轮询发现变更并热刷新(无需重编译)
const nextVersion = Math.max(1, Number(current.version) || 1) + 1;
const merged = mergeRemoteConfig({
...withPlatforms,
updatedAt: new Date().toISOString(),
version: Math.max(1, Number(withPlatforms.version) || 1),
version: nextVersion,
});
assertSafeConfig(merged);
await fs.mkdir(path.dirname(FILE), { recursive: true });
await backupCurrentConfig();
await fs.writeFile(FILE, JSON.stringify(merged, null, 2), "utf8");
try {
const { notifyConfigChanged } = await import("~/lib/remote-config-live");
notifyConfigChanged(
{ version: merged.version, updatedAt: merged.updatedAt },
"write",
);
} catch {
/* ignore */
}
return merged;
}

View File

@ -69,6 +69,10 @@ export type NomadroRemoteConfig = {
* 须 socialFollow !== false 且本项为 true 才弹出;默认 false,不影响现网行为。
*/
socialFollowAuto: boolean;
/** 加群 → 微信公众号(后台开关,用户无感知) */
joinGroupWechat: boolean;
/** 加群 → 抖音群(后台开关,用户无感知) */
joinGroupDouyin: boolean;
offlineBadge: boolean;
};
copy: {
@ -78,6 +82,9 @@ export type NomadroRemoteConfig = {
vipPriceFen: number;
vipProductId: string;
vipCta: string;
wechatOaName?: string;
joinGroupDouyinHint?: string;
joinGroupDouyinQr?: string;
};
/** 分端配置;仅抖音等使用。门户 / 微信仍只读顶层 modules,互不影响 */
platforms?: {
@ -159,6 +166,8 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
payEnabled: true,
socialFollow: true,
socialFollowAuto: false,
joinGroupWechat: true,
joinGroupDouyin: false,
offlineBadge: false,
},
copy: {
@ -168,6 +177,9 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
vipPriceFen: 29800,
vipProductId: "vip_membership",
vipCta: "立即加入",
wechatOaName: "异度世界",
joinGroupDouyinHint: "打开抖音搜群「数字游民」或扫码进群",
joinGroupDouyinQr: "",
},
platforms: {
tt: structuredClone(DEFAULT_TT_PLATFORM),
@ -281,6 +293,8 @@ export function mergeRemoteConfig(
payEnabled: asBool(pf.payEnabled, base.flags.payEnabled),
socialFollow: asBool(pf.socialFollow, base.flags.socialFollow),
socialFollowAuto: asBool(pf.socialFollowAuto, base.flags.socialFollowAuto),
joinGroupWechat: asBool(pf.joinGroupWechat, base.flags.joinGroupWechat),
joinGroupDouyin: asBool(pf.joinGroupDouyin, base.flags.joinGroupDouyin),
offlineBadge: asBool(pf.offlineBadge, base.flags.offlineBadge),
},
copy: { ...base.copy, ...(partial.copy || {}) },

View File

@ -39,7 +39,6 @@ function writeCache(config: NomadroRemoteConfig) {
}
function initialState(): Result {
// SSR / 首屏:包内默认即 ready,避免整页挡「加载配置」
return {
config: DEFAULT_REMOTE_CONFIG,
fromOffline: true,
@ -47,33 +46,57 @@ function initialState(): Result {
};
}
/** 门户远程配置:首屏默认可开 → 网络刷新 → localStorage 兜底 */
async function fetchFullConfig(): Promise<NomadroRemoteConfig | null> {
try {
const res = await fetch("/api/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
if (res.ok && data?.config) return mergeRemoteConfig(data.config);
} catch {
/* ignore */
}
return null;
}
/**
* 门户远程配置:
* - 首屏默认 / 缓存兜底
* - SSE `/api/config/stream` 实时推送 version 变更 → 全量拉取
* - visibility / focus 兜底强制检查
*/
export function useRemoteConfig(): Result {
const [state, setState] = useState<Result>(initialState);
useEffect(() => {
let cancelled = false;
let knownVersion = Number(state.config.version) || 0;
let es: EventSource | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
const apply = (config: NomadroRemoteConfig, fromOffline: boolean) => {
if (cancelled) return;
knownVersion = Number(config.version) || knownVersion;
writeCache(config);
setState({ config, fromOffline, ready: true });
};
const pull = async () => {
const config = await fetchFullConfig();
if (!config || cancelled) return;
if (Number(config.version) === knownVersion && knownVersion > 0) return;
apply(config, false);
};
const cached = readCache();
if (cached) {
knownVersion = Number(cached.version) || 0;
setState({ config: cached, fromOffline: true, ready: true });
}
(async () => {
try {
const res = await fetch("/api/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
if (cancelled) return;
if (res.ok && data?.config) {
const config = mergeRemoteConfig(data.config);
writeCache(config);
setState({ config, fromOffline: false, ready: true });
return;
}
} catch {
/* fallthrough */
}
void (async () => {
const config = await fetchFullConfig();
if (cancelled) return;
if (!cached) {
if (config) apply(config, false);
else if (!cached) {
setState({
config: DEFAULT_REMOTE_CONFIG,
fromOffline: true,
@ -82,9 +105,48 @@ export function useRemoteConfig(): Result {
}
})();
const connectSse = () => {
if (cancelled || typeof EventSource === "undefined") return;
try {
es?.close();
es = new EventSource("/api/config/stream");
es.addEventListener("config", (ev) => {
try {
const data = JSON.parse(String((ev as MessageEvent).data || "{}")) as {
version?: number;
};
const v = Number(data.version) || 0;
if (v && v !== knownVersion) void pull();
} catch {
void pull();
}
});
es.onerror = () => {
es?.close();
es = null;
if (cancelled) return;
reconnectTimer = setTimeout(connectSse, 5000);
};
} catch {
/* SSE 不可用时靠 visibility 兜底 */
}
};
connectSse();
const onVisible = () => {
if (document.visibilityState === "visible") void pull();
};
window.addEventListener("focus", onVisible);
document.addEventListener("visibilitychange", onVisible);
return () => {
cancelled = true;
es?.close();
if (reconnectTimer) clearTimeout(reconnectTimer);
window.removeEventListener("focus", onVisible);
document.removeEventListener("visibilitychange", onVisible);
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount once
}, []);
return state;

View File

@ -12,7 +12,7 @@ import { queryXorPayOrderStatus } from "@vip/app/lib/xorpayStatus";
import { queryZPayOrderStatus } from "@vip/app/lib/zpayStatus";
const getDefaultTotalFee = () =>
getPaymentConfig().defaultAmount ?? Number(process.env.PAYMENT_DEFAULT_AMOUNT) ?? 18800;
getPaymentConfig().defaultAmount ?? Number(process.env.PAYMENT_DEFAULT_AMOUNT) ?? 29800;
function parsePayPriceToCents(payPrice: unknown): number | null {
if (payPrice == null) return null;

View File

@ -332,7 +332,7 @@ export async function triggerPay(
? 100
: remote.vipPriceFen && remote.vipPriceFen > 0
? remote.vipPriceFen
: getPaymentConfig().defaultAmount ?? 8800;
: getPaymentConfig().defaultAmount ?? 29800;
const profile = getDisplayProfile();
const shouldShowLaunchOverlay =
device !== "wechat" && !!(profile.avatar || "").trim();

View File

@ -16,7 +16,7 @@ export interface PaymentConfig {
apiUrl: string;
provider: "zpay" | "xorpay";
zpaySubmitUrl: string;
/** 默认金额(分),88元=8800分 */
/** 默认金额(分),298元=29800分 */
defaultAmount?: number;
/** nomadvip 专用接口路径 */
nomadvipPayPath: string;
@ -106,8 +106,8 @@ export function getPaymentConfig(): PaymentConfig {
provider: (process.env.PAYMENT_PROVIDER as "zpay" | "xorpay") || "zpay",
zpaySubmitUrl:
process.env.ZPAY_SUBMIT_URL || "https://zpayz.cn/submit.php",
/** 支付价格 599 元=59900 分 */
defaultAmount: Number(process.env.PAYMENT_DEFAULT_AMOUNT) || 59900,
/** 支付价格 298 元=29800 分 */
defaultAmount: Number(process.env.PAYMENT_DEFAULT_AMOUNT) || 29800,
nomadvipPayPath: "/nomadvip/payh5",
};
}