Ship remaining business changes across social API, miniprogram audit/book, VIP track, and deploy.
Includes social realtime entrypoints, weapp audit book surfaces, VIP analytics track routes, MiroTalk/Centrifugo deploy helpers, and related admin/config wiring. Excludes local DB dumps and .tmp probe scripts. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
d38bf6c475
commit
4789785f11
25
README.md
25
README.md
@ -19,7 +19,7 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
|||||||
| 导航 | `/nav` | `src/modules/nav` · 远程 `navContent`(后台 `/wechat/nav` 可 CRUD) |
|
| 导航 | `/nav` | `src/modules/nav` · 远程 `navContent`(后台 `/wechat/nav` 可 CRUD) |
|
||||||
| 小册 | `/book` | `src/modules/ebook` + `src/modules/ebook-content` |
|
| 小册 | `/book` | `src/modules/ebook` + `src/modules/ebook-content` |
|
||||||
| 旅居社群 | `/community` | `src/modules/community`(Lounge / Ergo / MiroTalk;**勿改名**) |
|
| 旅居社群 | `/community` | `src/modules/community`(Lounge / Ergo / MiroTalk;**勿改名**) |
|
||||||
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite `data/social/`(可拆独立域) |
|
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite · Centrifugo 实时 · 视觉默认 T1 |
|
||||||
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
|
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
|
||||||
| 后台 | admin.nomadro.cn | `apps/admin` |
|
| 后台 | admin.nomadro.cn | `apps/admin` |
|
||||||
| API | api.nomadro.cn | `apps/api` |
|
| API | api.nomadro.cn | `apps/api` |
|
||||||
@ -122,7 +122,18 @@ pnpm dev:api
|
|||||||
|
|
||||||
### 游民社区(`/social`)
|
### 游民社区(`/social`)
|
||||||
|
|
||||||
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `apps/api/services/social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。MiroTalk 站内嵌 CSP 在公网机 `107.173.30.245` 的 Caddy(须含 `nomadro.cn` 与本地 `:3000`)。
|
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db` 或 `SOCIAL_DB_PATH`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。
|
||||||
|
|
||||||
|
| 层 | 线上(82) | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| 门户 | `nomadro.service` `:4003` | `/social/*`;前端发版须**本地确认后再上线** |
|
||||||
|
| Social API | `nomadro-social.service` `:8020` | `apps/api/social_main.py`;nginx `/api/social/` |
|
||||||
|
| 实时 | `centrifugo.service` `:8008` | `wss://nomadro.cn/rt/connection/websocket`;密钥 `/etc/nomadro/centrifugo.env` |
|
||||||
|
| 视频 | `mirotalk-p2p` → `mirotalk.nomadro.cn` | 白标中文极速进房;禁 `.com`/107 |
|
||||||
|
|
||||||
|
**视觉主题**:代码保留 T1(旅居社群对齐,**默认**)与 T2(琥珀信号,`theme2.css`);导航切换器已隐藏,强制 T1。恢复切换:见 `SiteShell` + `lib/skin.ts`。
|
||||||
|
|
||||||
|
**生产铁律**:[`https://nomadro.cn`](https://nomadro.cn/) 全链路只跑 **`82.157.112.245`**。视频厅用同机 **`https://mirotalk.nomadro.cn`**(nginx → `127.0.0.1:9300`),禁止进房再走 `mirotalk.nomadro.com` / 107。
|
||||||
|
|
||||||
## pre4 摘要(审核包)
|
## pre4 摘要(审核包)
|
||||||
|
|
||||||
@ -152,7 +163,15 @@ pnpm dev:api
|
|||||||
|
|
||||||
## test5(当前开发)
|
## test5(当前开发)
|
||||||
|
|
||||||
从 `pre5` 切出。建议方向:social 线上增量部署与冒烟、课时资料后台可视化、桥接 UX、真机网络/域名排查。
|
从 `pre5` 切出。本轮已落地(细节以 `deploy/social/README.md` 为准):
|
||||||
|
|
||||||
|
- **Social 实时**:Centrifugo + `/api/social/v1/realtime/token`;聊天页优先 WS,失败降级轮询
|
||||||
|
- **Social API 独立进程**:`nomadro-social` `:8020`,与 ebook/community/pay 隔离
|
||||||
|
- **MiroTalk**:钉死 82 `.cn`、白标中文、极速进房
|
||||||
|
- **视觉**:T1 默认;T2 代码保留、切换器隐藏
|
||||||
|
- **发版约定**:前端本地 `pnpm dev` 验收通过、**经允许后再部署**门户 `.next`
|
||||||
|
|
||||||
|
后续可做:课时资料后台可视化、桥接 UX、真机网络/域名排查。
|
||||||
|
|
||||||
## pre3 摘要(已合入)
|
## pre3 摘要(已合入)
|
||||||
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@ -36,7 +36,7 @@ class Settings(BaseSettings):
|
|||||||
# Payment (from env on server)
|
# Payment (from env on server)
|
||||||
dev_auto_pay: bool = False
|
dev_auto_pay: bool = False
|
||||||
payment_provider: str = "zpay"
|
payment_provider: str = "zpay"
|
||||||
mirotalk_url: str = "https://mirotalk.nomadro.com"
|
mirotalk_url: str = "https://mirotalk.nomadro.cn"
|
||||||
lounge_url: str = "https://lounge.nomadro.com"
|
lounge_url: str = "https://lounge.nomadro.com"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import os
|
|||||||
import re
|
import re
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
MIROTALK_URL = os.getenv("MIROTALK_URL", "https://mirotalk.nomadro.com")
|
MIROTALK_URL = os.getenv("MIROTALK_URL", "https://mirotalk.nomadro.cn")
|
||||||
LOUNGE_URL = os.getenv("LOUNGE_URL", "https://lounge.nomadro.com")
|
LOUNGE_URL = os.getenv("LOUNGE_URL", "https://lounge.nomadro.com")
|
||||||
|
|
||||||
VIP_ROLES = frozenset({"admin", "owner", "host", "organizer", "moderator"})
|
VIP_ROLES = frozenset({"admin", "owner", "host", "organizer", "moderator"})
|
||||||
@ -39,7 +39,11 @@ def build_mirotalk_join_url(meetup: dict, display_name: str = "nomadro") -> str:
|
|||||||
if explicit.startswith("http"):
|
if explicit.startswith("http"):
|
||||||
return explicit
|
return explicit
|
||||||
room = meetup.get("mirotalkRoom") or create_mirotalk_room_slug(meetup)
|
room = meetup.get("mirotalkRoom") or create_mirotalk_room_slug(meetup)
|
||||||
return f"{MIROTALK_URL.rstrip('/')}/join?{urlencode({'room': room, 'name': display_name})}"
|
# notify=0 disables MiroTalk "Share the room" popup; chat left to portal/lounge
|
||||||
|
return (
|
||||||
|
f"{MIROTALK_URL.rstrip('/')}/join?"
|
||||||
|
f"{urlencode({'room': room, 'name': display_name, 'notify': '0', 'chat': '0'})}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def build_lounge_chat_url(meetup: dict) -> str:
|
def build_lounge_chat_url(meetup: dict) -> str:
|
||||||
|
|||||||
@ -9,3 +9,14 @@ _DEFAULT_DB = _ROOT / "data" / "social" / "social.db"
|
|||||||
|
|
||||||
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT_DB))).resolve()
|
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT_DB))).resolve()
|
||||||
SOCIAL_ENABLED = os.getenv("SOCIAL_ENABLED", "true").lower() in {"1", "true", "yes", "on"}
|
SOCIAL_ENABLED = os.getenv("SOCIAL_ENABLED", "true").lower() in {"1", "true", "yes", "on"}
|
||||||
|
|
||||||
|
# Centrifugo(实时层;缺省关,部署后用环境变量打开)
|
||||||
|
CENTRIFUGO_ENABLED = os.getenv("CENTRIFUGO_ENABLED", "false").lower() in {"1", "true", "yes", "on"}
|
||||||
|
CENTRIFUGO_API_URL = os.getenv("CENTRIFUGO_API_URL", "http://127.0.0.1:8008/api").rstrip("/")
|
||||||
|
CENTRIFUGO_API_KEY = os.getenv("CENTRIFUGO_API_KEY", "")
|
||||||
|
CENTRIFUGO_TOKEN_SECRET = os.getenv("CENTRIFUGO_TOKEN_SECRET", "")
|
||||||
|
# 浏览器 WebSocket(经 nginx 反代,与门户同域)
|
||||||
|
CENTRIFUGO_WS_URL = os.getenv(
|
||||||
|
"CENTRIFUGO_WS_URL",
|
||||||
|
"wss://nomadro.cn/rt/connection/websocket",
|
||||||
|
)
|
||||||
|
|||||||
73
apps/api/services/social_svc/realtime.py
Normal file
73
apps/api/services/social_svc/realtime.py
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
"""Centrifugo publish + connection JWT for 游民社区聊天."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
from social_svc.config import (
|
||||||
|
CENTRIFUGO_API_KEY,
|
||||||
|
CENTRIFUGO_API_URL,
|
||||||
|
CENTRIFUGO_ENABLED,
|
||||||
|
CENTRIFUGO_TOKEN_SECRET,
|
||||||
|
CENTRIFUGO_WS_URL,
|
||||||
|
)
|
||||||
|
|
||||||
|
log = logging.getLogger("social_svc.realtime")
|
||||||
|
|
||||||
|
|
||||||
|
def channel_name(channel_id: str) -> str:
|
||||||
|
cid = (channel_id or "").strip() or "lobby"
|
||||||
|
return f"social:{cid}"
|
||||||
|
|
||||||
|
|
||||||
|
def issue_connection_token(guest_id: str, channel_id: str | None = None) -> dict[str, Any]:
|
||||||
|
"""Return client connection info. Disabled → ok=false (前端降级轮询)."""
|
||||||
|
if not CENTRIFUGO_ENABLED or not CENTRIFUGO_TOKEN_SECRET:
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"enabled": False,
|
||||||
|
"wsUrl": CENTRIFUGO_WS_URL,
|
||||||
|
"token": "",
|
||||||
|
"channel": channel_name(channel_id or "lobby"),
|
||||||
|
}
|
||||||
|
now = int(time.time())
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"sub": guest_id[:80],
|
||||||
|
"iat": now,
|
||||||
|
"exp": now + 60 * 60 * 12,
|
||||||
|
}
|
||||||
|
token = jwt.encode(payload, CENTRIFUGO_TOKEN_SECRET, algorithm="HS256")
|
||||||
|
if isinstance(token, bytes):
|
||||||
|
token = token.decode("utf-8")
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"enabled": True,
|
||||||
|
"wsUrl": CENTRIFUGO_WS_URL,
|
||||||
|
"token": token,
|
||||||
|
"channel": channel_name(channel_id or "lobby"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool:
|
||||||
|
if not CENTRIFUGO_ENABLED or not CENTRIFUGO_API_KEY:
|
||||||
|
return False
|
||||||
|
url = CENTRIFUGO_API_URL.rstrip("/") + "/publish"
|
||||||
|
body = {"channel": channel_name(channel_id), "data": {"type": "chat.message", "message": message}}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=3.0) as client:
|
||||||
|
res = await client.post(
|
||||||
|
url,
|
||||||
|
headers={"X-API-Key": CENTRIFUGO_API_KEY, "Content-Type": "application/json"},
|
||||||
|
json=body,
|
||||||
|
)
|
||||||
|
if res.status_code >= 400:
|
||||||
|
log.warning("centrifugo publish %s: %s", res.status_code, res.text[:200])
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
except Exception as e: # pragma: no cover
|
||||||
|
log.warning("centrifugo publish failed: %s", e)
|
||||||
|
return False
|
||||||
@ -1,11 +1,12 @@
|
|||||||
"""游民社区 API — 前缀 /api/social/v1,与 /api/v1 社群隔离。"""
|
"""游民社区 API — 前缀 /api/social/v1,与 /api/v1 社群隔离。"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from fastapi import APIRouter, Header, HTTPException
|
from fastapi import APIRouter, Header, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
from social_svc import store
|
from social_svc import store
|
||||||
from social_svc.config import SOCIAL_ENABLED
|
from social_svc.config import SOCIAL_ENABLED
|
||||||
|
from social_svc.realtime import issue_connection_token, publish_chat_message
|
||||||
|
|
||||||
router = APIRouter(tags=["social"])
|
router = APIRouter(tags=["social"])
|
||||||
|
|
||||||
@ -55,7 +56,20 @@ class GigAppIn(BaseModel):
|
|||||||
async def social_health():
|
async def social_health():
|
||||||
if not SOCIAL_ENABLED:
|
if not SOCIAL_ENABLED:
|
||||||
return {"ok": False, "module": "social", "enabled": False}
|
return {"ok": False, "module": "social", "enabled": False}
|
||||||
return store.health()
|
h = store.health()
|
||||||
|
from social_svc.config import CENTRIFUGO_ENABLED
|
||||||
|
|
||||||
|
h["centrifugo"] = bool(CENTRIFUGO_ENABLED)
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/realtime/token")
|
||||||
|
async def realtime_token(
|
||||||
|
channel_id: str = Query(default="lobby"),
|
||||||
|
x_social_guest_id: str | None = Header(default=None),
|
||||||
|
):
|
||||||
|
guest = _guest(x_social_guest_id)
|
||||||
|
return issue_connection_token(guest, channel_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/channels/{channel_id}/messages")
|
@router.get("/channels/{channel_id}/messages")
|
||||||
@ -74,7 +88,13 @@ async def post_message(
|
|||||||
store.init_db()
|
store.init_db()
|
||||||
if not body.text.strip():
|
if not body.text.strip():
|
||||||
raise HTTPException(status_code=400, detail="empty text")
|
raise HTTPException(status_code=400, detail="empty text")
|
||||||
return store.add_message(channel_id, body.author, body.text, guest)
|
saved = store.add_message(channel_id, body.author, body.text, guest)
|
||||||
|
# 实时推送失败不影响落库成功
|
||||||
|
try:
|
||||||
|
await publish_chat_message(channel_id, saved)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return saved
|
||||||
|
|
||||||
|
|
||||||
@router.get("/cafes/{cafe_id}/reviews")
|
@router.get("/cafes/{cafe_id}/reviews")
|
||||||
|
|||||||
41
apps/api/social_main.py
Normal file
41
apps/api/social_main.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
"""游民社区独立进程入口 — 仅挂 social_svc,不拖垮 ebook/community/pay。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
SERVICES = ROOT / "services"
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
sys.path.insert(0, str(SERVICES))
|
||||||
|
|
||||||
|
from social_svc.config import SOCIAL_ENABLED # noqa: E402
|
||||||
|
from social_svc.realtime import issue_connection_token # noqa: E402
|
||||||
|
from social_svc.routers import router as social_router # noqa: E402
|
||||||
|
from social_svc.store import init_db # noqa: E402
|
||||||
|
|
||||||
|
app = FastAPI(title="nomadro-social", docs_url=None, redoc_url=None)
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
def _startup() -> None:
|
||||||
|
if SOCIAL_ENABLED:
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
|
||||||
|
if SOCIAL_ENABLED:
|
||||||
|
app.include_router(social_router, prefix="/api/social/v1")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health():
|
||||||
|
from social_svc.config import CENTRIFUGO_ENABLED
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"service": "nomadro-social",
|
||||||
|
"social": bool(SOCIAL_ENABLED),
|
||||||
|
"centrifugo": bool(CENTRIFUGO_ENABLED),
|
||||||
|
}
|
||||||
@ -45,21 +45,21 @@ const isH5 =
|
|||||||
process.env.TARO_ENV === 'h5' || process.env.TARO_APP_TARGET === 'h5'
|
process.env.TARO_ENV === 'h5' || process.env.TARO_APP_TARGET === 'h5'
|
||||||
const wantTabBar = !isH5 && process.env.TARO_APP_TABBAR === '1'
|
const wantTabBar = !isH5 && process.env.TARO_APP_TABBAR === '1'
|
||||||
|
|
||||||
/** 微信主包必须 ≤1.5MB:首页/我的留主包,其余进分包 */
|
/** 微信主包必须 ≤2MB:首页/我的/小册留主包(提审小册勿进分包,避免下载失败黑屏) */
|
||||||
const weappConfig = {
|
const weappConfig = {
|
||||||
// 启动页 = home(官方话题/体验码默认路径);UI 与 tag 20261011 的 index 同组件
|
// 提审期:小册作启动页,打开即见正文(过审后改回 home 第一)
|
||||||
pages: ['pages/home/index', 'pages/mine/index', 'pages/index/index'],
|
pages: [
|
||||||
|
'pages/book/index',
|
||||||
|
'pages/home/index',
|
||||||
|
'pages/mine/index',
|
||||||
|
'pages/index/index',
|
||||||
|
],
|
||||||
subPackages: [
|
subPackages: [
|
||||||
{
|
{
|
||||||
root: 'pages/nav',
|
root: 'pages/nav',
|
||||||
name: 'nav',
|
name: 'nav',
|
||||||
pages: ['index'],
|
pages: ['index'],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
root: 'pages/book',
|
|
||||||
name: 'book',
|
|
||||||
pages: ['index'],
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
root: 'pages/reader',
|
root: 'pages/reader',
|
||||||
name: 'reader',
|
name: 'reader',
|
||||||
@ -145,11 +145,11 @@ const weappConfig = {
|
|||||||
preloadRule: {
|
preloadRule: {
|
||||||
'pages/home/index': {
|
'pages/home/index': {
|
||||||
network: 'all',
|
network: 'all',
|
||||||
packages: ['book', 'nav'],
|
packages: ['nav', 'reader'],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
/** 组件按需注入:代码质量扫描必过项 */
|
// 提审期先关掉按需注入:Taro+React 下偶发首屏空白/黑屏;过审后再开回 requiredComponents
|
||||||
lazyCodeLoading: 'requiredComponents' as const,
|
// lazyCodeLoading: 'requiredComponents' as const,
|
||||||
}
|
}
|
||||||
|
|
||||||
const h5Config = {
|
const h5Config = {
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
|
/* 全局底:勿引入 community / ebook;提审小册靠内联色 */
|
||||||
page {
|
page {
|
||||||
background: #0a0e17;
|
background: #0c0b12;
|
||||||
color: #f1f5f9;
|
color: #f8fafc;
|
||||||
font-family: 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -38,16 +38,28 @@ function App({ children }: PropsWithChildren) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const stopRem = startH5RemLock()
|
const stopRem = startH5RemLock()
|
||||||
const stopLive = startRemoteConfigLiveSync()
|
const stopLive = startRemoteConfigLiveSync()
|
||||||
const stopPresence = startPresenceHeartbeat()
|
let stopPresence: (() => void) | undefined
|
||||||
const stopVip = startVipAccessLiveSync()
|
let stopVip: (() => void) | undefined
|
||||||
|
let defer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
const startSide = () => {
|
||||||
|
stopPresence = startPresenceHeartbeat()
|
||||||
|
stopVip = startVipAccessLiveSync()
|
||||||
|
}
|
||||||
|
// 微信提审:延后心跳 / VIP 探活,避免冷启动抢跑干扰小册首屏
|
||||||
|
if (process.env.TARO_ENV === 'weapp') {
|
||||||
|
defer = setTimeout(startSide, 2500)
|
||||||
|
} else {
|
||||||
|
startSide()
|
||||||
|
}
|
||||||
if (process.env.TARO_ENV === 'h5') {
|
if (process.env.TARO_ENV === 'h5') {
|
||||||
applyH5Theme(getStoredH5Theme())
|
applyH5Theme(getStoredH5Theme())
|
||||||
}
|
}
|
||||||
return () => {
|
return () => {
|
||||||
|
if (defer) clearTimeout(defer)
|
||||||
stopRem()
|
stopRem()
|
||||||
stopLive()
|
stopLive()
|
||||||
stopPresence()
|
stopPresence?.()
|
||||||
stopVip()
|
stopVip?.()
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
|||||||
9
apps/miniprogram/h5/src/app.weapp.tsx
Normal file
9
apps/miniprogram/h5/src/app.weapp.tsx
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* 微信专用 App:零副作用。必须包一层 Fragment,避免 children 形态异常导致整页空白。
|
||||||
|
*/
|
||||||
|
import { Fragment, type PropsWithChildren } from 'react'
|
||||||
|
import './app.scss'
|
||||||
|
|
||||||
|
export default function App({ children }: PropsWithChildren) {
|
||||||
|
return <Fragment>{children}</Fragment>
|
||||||
|
}
|
||||||
201
apps/miniprogram/h5/src/components/AuditBookScreen.tsx
Normal file
201
apps/miniprogram/h5/src/components/AuditBookScreen.tsx
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
import { useMemo, useState } from 'react'
|
||||||
|
import { View, Text } from '@tarojs/components'
|
||||||
|
import { AUDIT_BOOK_CHAPTERS, AUDIT_BOOK_META } from '../data/auditBook'
|
||||||
|
import { safePx } from '../utils/safeArea'
|
||||||
|
|
||||||
|
const FALLBACK_BODY =
|
||||||
|
'欢迎阅读《数字游民入门指南》。这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。'
|
||||||
|
|
||||||
|
const block = (extra?: Record<string, string | number>) => ({
|
||||||
|
display: 'block' as const,
|
||||||
|
...extra,
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 提审小册:包内数据 + View/Text + safePx,无网络 / 无 RichText / 无 scss */
|
||||||
|
export function AuditBookScreen(_props?: { bookId?: string }) {
|
||||||
|
const chapters = AUDIT_BOOK_CHAPTERS
|
||||||
|
const [idx, setIdx] = useState(0)
|
||||||
|
const safeIdx = Math.min(Math.max(0, idx), Math.max(0, chapters.length - 1))
|
||||||
|
const chapter = chapters[safeIdx]
|
||||||
|
const lines = useMemo(() => {
|
||||||
|
const plain = markdownToPlain(chapter?.content || '') || FALLBACK_BODY
|
||||||
|
return plain.split('\n')
|
||||||
|
}, [chapter?.content])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
minHeight: '100vh',
|
||||||
|
width: '100%',
|
||||||
|
backgroundColor: '#0c0b12',
|
||||||
|
paddingTop: safePx(16),
|
||||||
|
paddingRight: safePx(16),
|
||||||
|
paddingBottom: safePx(48),
|
||||||
|
paddingLeft: safePx(16),
|
||||||
|
boxSizing: 'border-box',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text style={block({ fontSize: safePx(28), marginBottom: safePx(8), color: '#f8fafc' })}>
|
||||||
|
{AUDIT_BOOK_META.cover_emoji}
|
||||||
|
</Text>
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(22),
|
||||||
|
fontWeight: '700',
|
||||||
|
color: '#f8fafc',
|
||||||
|
lineHeight: '1.35',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{AUDIT_BOOK_META.title}
|
||||||
|
</Text>
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(13),
|
||||||
|
color: '#94a3b8',
|
||||||
|
marginTop: safePx(8),
|
||||||
|
marginBottom: safePx(16),
|
||||||
|
lineHeight: '1.45',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{AUDIT_BOOK_META.subtitle}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<View style={{ marginBottom: safePx(16) }}>
|
||||||
|
{chapters.map((c, i) => (
|
||||||
|
<View
|
||||||
|
key={c.id}
|
||||||
|
onClick={() => setIdx(i)}
|
||||||
|
style={{ paddingTop: safePx(10), paddingBottom: safePx(10) }}
|
||||||
|
>
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(14),
|
||||||
|
color: i === safeIdx ? '#f8fafc' : '#64748b',
|
||||||
|
fontWeight: i === safeIdx ? '700' : '400',
|
||||||
|
lineHeight: '1.4',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{`${i + 1}. ${c.title}`}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
|
||||||
|
<View style={{ paddingTop: safePx(8) }}>
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(17),
|
||||||
|
fontWeight: '700',
|
||||||
|
color: '#e2e8f0',
|
||||||
|
marginBottom: safePx(12),
|
||||||
|
lineHeight: '1.4',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{`${safeIdx + 1}. ${chapter?.title || '正文'}`}
|
||||||
|
</Text>
|
||||||
|
{lines.map((line, i) =>
|
||||||
|
line ? (
|
||||||
|
<Text
|
||||||
|
key={`b-${i}`}
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(15),
|
||||||
|
color: '#cbd5e1',
|
||||||
|
lineHeight: '1.75',
|
||||||
|
marginBottom: safePx(6),
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{line}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<View key={`b-${i}`} style={{ height: safePx(8) }} />
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'row',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginTop: safePx(28),
|
||||||
|
paddingBottom: safePx(24),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<View
|
||||||
|
onClick={() => setIdx((v) => Math.max(0, v - 1))}
|
||||||
|
style={{ paddingTop: safePx(12), paddingBottom: safePx(12), paddingRight: safePx(16) }}
|
||||||
|
>
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(15),
|
||||||
|
color: safeIdx <= 0 ? '#334155' : '#94a3b8',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
上一章
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Text style={block({ fontSize: safePx(13), color: '#64748b' })}>
|
||||||
|
{`${safeIdx + 1}/${chapters.length}`}
|
||||||
|
</Text>
|
||||||
|
<View
|
||||||
|
onClick={() => setIdx((v) => Math.min(chapters.length - 1, v + 1))}
|
||||||
|
style={{ paddingTop: safePx(12), paddingBottom: safePx(12), paddingLeft: safePx(16) }}
|
||||||
|
>
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(15),
|
||||||
|
color: safeIdx >= chapters.length - 1 ? '#334155' : '#94a3b8',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
下一章
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripInline(s: string) {
|
||||||
|
return s
|
||||||
|
.replace(/\*\*(.+?)\*\*/g, '$1')
|
||||||
|
.replace(/\*(.+?)\*/g, '$1')
|
||||||
|
.replace(/`([^`]+)`/g, '$1')
|
||||||
|
.replace(/\[(.+?)\]\((https?:\/\/.+?)\)/g, '$1')
|
||||||
|
}
|
||||||
|
|
||||||
|
function markdownToPlain(markdown: string): string {
|
||||||
|
const raw = (markdown || '').replace(/\r\n/g, '\n').split('\n')
|
||||||
|
const out: string[] = []
|
||||||
|
for (const line of raw) {
|
||||||
|
const trimmed = line.trim()
|
||||||
|
if (!trimmed) {
|
||||||
|
if (out.length && out[out.length - 1] !== '') out.push('')
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (/^---+$/.test(trimmed)) continue
|
||||||
|
const heading = /^(#{1,3})\s+(.+)$/.exec(trimmed)
|
||||||
|
if (heading) {
|
||||||
|
out.push(stripInline(heading[2]))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const quote = /^>\s?(.*)$/.exec(trimmed)
|
||||||
|
if (quote) {
|
||||||
|
out.push(stripInline(quote[1]))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const ol = /^\d+\.\s+(.+)$/.exec(trimmed)
|
||||||
|
if (ol) {
|
||||||
|
out.push(`${ol[0].match(/^\d+/)?.[0] || '·'}. ${stripInline(ol[1])}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const ul = /^[-*]\s+(.+)$/.exec(trimmed)
|
||||||
|
if (ul) {
|
||||||
|
out.push(`· ${stripInline(ul[1])}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (/^\|?\s*-{2,}/.test(trimmed)) continue
|
||||||
|
out.push(stripInline(trimmed.replace(/\|/g, ' ')))
|
||||||
|
}
|
||||||
|
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim()
|
||||||
|
}
|
||||||
127
apps/miniprogram/h5/src/components/AuditPlainBody.tsx
Normal file
127
apps/miniprogram/h5/src/components/AuditPlainBody.tsx
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
import { useMemo } from 'react'
|
||||||
|
import { View, Text } from '@tarojs/components'
|
||||||
|
import { safePx } from '../utils/safeArea'
|
||||||
|
|
||||||
|
type Line =
|
||||||
|
| { type: 'h'; level: number; text: string }
|
||||||
|
| { type: 'p'; text: string }
|
||||||
|
| { type: 'li'; text: string }
|
||||||
|
| { type: 'sp' }
|
||||||
|
|
||||||
|
const colorH = '#f1f5f9'
|
||||||
|
const colorP = '#cbd5e1'
|
||||||
|
|
||||||
|
/** 提审正文:View/Text + 大写 PX,禁止 RichText / html / 裸 px(会被转 rpx 缩没) */
|
||||||
|
export function AuditPlainBody({ markdown }: { markdown: string }) {
|
||||||
|
const lines = useMemo(() => {
|
||||||
|
const raw = (markdown || '').replace(/\r\n/g, '\n').split('\n')
|
||||||
|
const out: Line[] = []
|
||||||
|
for (const line of raw) {
|
||||||
|
const trimmed = line.trim()
|
||||||
|
if (!trimmed) {
|
||||||
|
out.push({ type: 'sp' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (/^---+$/.test(trimmed)) {
|
||||||
|
out.push({ type: 'sp' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const heading = /^(#{1,3})\s+(.+)$/.exec(trimmed)
|
||||||
|
if (heading) {
|
||||||
|
out.push({ type: 'h', level: heading[1].length, text: stripInline(heading[2]) })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const quote = /^>\s?(.*)$/.exec(trimmed)
|
||||||
|
if (quote) {
|
||||||
|
out.push({ type: 'p', text: stripInline(quote[1]) })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const ol = /^\d+\.\s+(.+)$/.exec(trimmed)
|
||||||
|
if (ol) {
|
||||||
|
out.push({ type: 'li', text: stripInline(ol[1]) })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const ul = /^[-*]\s+(.+)$/.exec(trimmed)
|
||||||
|
if (ul) {
|
||||||
|
out.push({ type: 'li', text: stripInline(ul[1]) })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.push({ type: 'p', text: stripInline(trimmed) })
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}, [markdown])
|
||||||
|
|
||||||
|
if (!lines.length) {
|
||||||
|
return (
|
||||||
|
<Text style={{ fontSize: safePx(15), color: colorP, display: 'block' }}>暂无内容</Text>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View>
|
||||||
|
{lines.map((l, i) => {
|
||||||
|
if (l.type === 'sp') {
|
||||||
|
return <View key={`s-${i}`} style={{ height: safePx(10) }} />
|
||||||
|
}
|
||||||
|
if (l.type === 'h') {
|
||||||
|
const size = l.level === 1 ? 18 : l.level === 2 ? 16 : 15
|
||||||
|
return (
|
||||||
|
<Text
|
||||||
|
key={`h-${i}`}
|
||||||
|
style={{
|
||||||
|
display: 'block',
|
||||||
|
color: colorH,
|
||||||
|
fontWeight: '700',
|
||||||
|
fontSize: safePx(size),
|
||||||
|
lineHeight: '1.35',
|
||||||
|
marginTop: safePx(14),
|
||||||
|
marginBottom: safePx(8),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{l.text}
|
||||||
|
</Text>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (l.type === 'li') {
|
||||||
|
return (
|
||||||
|
<Text
|
||||||
|
key={`l-${i}`}
|
||||||
|
style={{
|
||||||
|
display: 'block',
|
||||||
|
color: colorP,
|
||||||
|
fontSize: safePx(15),
|
||||||
|
lineHeight: '1.75',
|
||||||
|
marginBottom: safePx(8),
|
||||||
|
paddingLeft: safePx(4),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
· {l.text}
|
||||||
|
</Text>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Text
|
||||||
|
key={`p-${i}`}
|
||||||
|
style={{
|
||||||
|
display: 'block',
|
||||||
|
color: colorP,
|
||||||
|
fontSize: safePx(15),
|
||||||
|
lineHeight: '1.75',
|
||||||
|
marginBottom: safePx(8),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{l.text}
|
||||||
|
</Text>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripInline(s: string) {
|
||||||
|
return s
|
||||||
|
.replace(/\*\*(.+?)\*\*/g, '$1')
|
||||||
|
.replace(/\*(.+?)\*/g, '$1')
|
||||||
|
.replace(/`([^`]+)`/g, '$1')
|
||||||
|
.replace(/\[(.+?)\]\((https?:\/\/.+?)\)/g, '$1')
|
||||||
|
}
|
||||||
@ -56,6 +56,9 @@ export function H5Box({
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// 微信/抖音等:禁止 dangerouslySetInnerHTML。
|
||||||
|
// Taro 会编出非法自定义组件 → Component is not found in path "wx://not-found" → 整页黑屏。
|
||||||
|
// SVG/html 仅 H5 使用;小程序靠 className + children(CSS/emoji)兜底。
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
id={id}
|
id={id}
|
||||||
@ -63,9 +66,8 @@ export function H5Box({
|
|||||||
style={style}
|
style={style}
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
data-theme={dataTheme}
|
data-theme={dataTheme}
|
||||||
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
|
|
||||||
>
|
>
|
||||||
{html ? undefined : children}
|
{children}
|
||||||
</View>
|
</View>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -78,6 +78,39 @@
|
|||||||
filter: drop-shadow(0 12px 28px rgba(78, 205, 196, 0.28));
|
filter: drop-shadow(0 12px 28px rgba(78, 205, 196, 0.28));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 微信:纯 View logo,禁止 SVG 内联 */
|
||||||
|
.nd-loader-mark-css {
|
||||||
|
position: relative;
|
||||||
|
width: 72px;
|
||||||
|
height: 72px;
|
||||||
|
margin: 0 auto 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nd-loader-mark-ring {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 3px solid rgba(240, 102, 100, 0.85);
|
||||||
|
box-shadow: 0 0 0 10px rgba(240, 102, 100, 0.12);
|
||||||
|
animation: nd-spin 1.2s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nd-loader-mark-dot {
|
||||||
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
|
right: 10px;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #f06664;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes nd-spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.nd-loader-svg svg,
|
.nd-loader-svg svg,
|
||||||
.nd-loader-mark {
|
.nd-loader-mark {
|
||||||
width: 88px;
|
width: 88px;
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
import { H5Box, H5Txt } from './H5Box'
|
import { H5Box, H5Txt } from './H5Box'
|
||||||
import './NomadroLoader.scss'
|
import './NomadroLoader.scss'
|
||||||
|
|
||||||
|
const isH5 = process.env.TARO_ENV === 'h5'
|
||||||
|
|
||||||
const LOGO_SVG = `<svg class="nd-loader-mark" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
const LOGO_SVG = `<svg class="nd-loader-mark" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||||
<circle cx="40" cy="40" r="36" fill="rgba(240,102,100,0.12)"/>
|
<circle cx="40" cy="40" r="36" fill="rgba(240,102,100,0.12)"/>
|
||||||
<circle class="nd-loader-ring" cx="40" cy="40" r="34" stroke="#f06664" stroke-width="3" stroke-dasharray="54 160" stroke-linecap="round"/>
|
<circle class="nd-loader-ring" cx="40" cy="40" r="34" stroke="#f06664" stroke-width="3" stroke-dasharray="54 160" stroke-linecap="round"/>
|
||||||
@ -16,7 +18,7 @@ type Props = {
|
|||||||
hidden?: boolean
|
hidden?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 全站加载:小红书同源红标,H5 / 微信 / 抖音同一套 SVG */
|
/** 全站加载:H5 用 SVG;微信用纯 View,禁止内联 html 防黑屏 */
|
||||||
export function NomadroLoader({
|
export function NomadroLoader({
|
||||||
brand = 'nomadro',
|
brand = 'nomadro',
|
||||||
tip = '随处工作 · 自由生活',
|
tip = '随处工作 · 自由生活',
|
||||||
@ -31,7 +33,14 @@ export function NomadroLoader({
|
|||||||
</H5Box>
|
</H5Box>
|
||||||
|
|
||||||
<H5Box className="nd-loader-inner">
|
<H5Box className="nd-loader-inner">
|
||||||
<H5Box className="nd-loader-svg" html={LOGO_SVG} />
|
{isH5 ? (
|
||||||
|
<H5Box className="nd-loader-svg" html={LOGO_SVG} />
|
||||||
|
) : (
|
||||||
|
<H5Box className="nd-loader-mark-css" aria-hidden>
|
||||||
|
<H5Box className="nd-loader-mark-ring" />
|
||||||
|
<H5Box className="nd-loader-mark-dot" />
|
||||||
|
</H5Box>
|
||||||
|
)}
|
||||||
<H5Txt className="nd-loader-text">{brand}</H5Txt>
|
<H5Txt className="nd-loader-text">{brand}</H5Txt>
|
||||||
{tip ? <H5Txt className="nd-loader-tip">{tip}</H5Txt> : null}
|
{tip ? <H5Txt className="nd-loader-tip">{tip}</H5Txt> : null}
|
||||||
<H5Box className="nd-loader-dots" aria-hidden>
|
<H5Box className="nd-loader-dots" aria-hidden>
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
import { H5Box, H5Txt } from './H5Box'
|
import { H5Box, H5Txt } from './H5Box'
|
||||||
|
|
||||||
/** 对齐 Next ProgressRing:圆环进度(多端同 SVG) */
|
const isH5 = process.env.TARO_ENV === 'h5'
|
||||||
|
|
||||||
|
/** 对齐 Next ProgressRing:H5 用 SVG;微信用文字,禁止内联 html 防黑屏 */
|
||||||
export function ProgressRing({
|
export function ProgressRing({
|
||||||
progress,
|
progress,
|
||||||
size = 52,
|
size = 52,
|
||||||
@ -18,6 +20,27 @@ export function ProgressRing({
|
|||||||
const c = size / 2
|
const c = size / 2
|
||||||
const gid = `rg-${ringId}`
|
const gid = `rg-${ringId}`
|
||||||
|
|
||||||
|
if (!isH5) {
|
||||||
|
return (
|
||||||
|
<H5Box
|
||||||
|
className="progress-ring progress-ring--mini"
|
||||||
|
style={{
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
flexShrink: 0,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
borderRadius: '50%',
|
||||||
|
border: '2px solid rgba(78,205,196,0.45)',
|
||||||
|
boxSizing: 'border-box',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<H5Txt style={{ fontSize: 11, color: '#94a3b8', fontWeight: 600 }}>{pct}%</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const html = `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" aria-hidden="true" style="display:block">
|
const html = `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" aria-hidden="true" style="display:block">
|
||||||
<circle cx="${c}" cy="${c}" r="${radius}" fill="none" stroke="rgba(255,255,255,0.08)" stroke-width="${stroke}"/>
|
<circle cx="${c}" cy="${c}" r="${radius}" fill="none" stroke="rgba(255,255,255,0.08)" stroke-width="${stroke}"/>
|
||||||
<circle cx="${c}" cy="${c}" r="${radius}" fill="none" stroke="url(#${gid})" stroke-width="${stroke}" stroke-linecap="round"
|
<circle cx="${c}" cy="${c}" r="${radius}" fill="none" stroke="url(#${gid})" stroke-width="${stroke}" stroke-linecap="round"
|
||||||
|
|||||||
72
apps/miniprogram/h5/src/data/auditBook.ts
Normal file
72
apps/miniprogram/h5/src/data/auditBook.ts
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
/** 微信提审小册离线正文 SoT:与 apps/admin/deploy/audit_book_seed.md 对齐 */
|
||||||
|
export type AuditChapter = { id: string; title: string; order: number; content: string }
|
||||||
|
export const AUDIT_BOOK_META = {
|
||||||
|
id: "audit",
|
||||||
|
title: "数字游民入门指南",
|
||||||
|
subtitle: "远程办公 · 自律生活 · 稳健成长",
|
||||||
|
description: "面向普通人的数字游民与远程办公入门读本:时间管理、协作沟通、健康作息与职业成长。",
|
||||||
|
cover_emoji: "📗",
|
||||||
|
tags: ["数字游民", "远程办公", "生活方式"] as string[],
|
||||||
|
} as const
|
||||||
|
export const AUDIT_BOOK_CHAPTERS: AuditChapter[] = [
|
||||||
|
{
|
||||||
|
id: "c1",
|
||||||
|
title: "写在前面",
|
||||||
|
order: 1,
|
||||||
|
content: "# 写在前面\n\n\n欢迎阅读《数字游民入门指南》。\n\n这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。\n\n你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。\n\n建议按顺序阅读。每章不长,方便通勤或午休时翻完。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c2",
|
||||||
|
title: "什么是数字游民",
|
||||||
|
order: 2,
|
||||||
|
content: "# 什么是数字游民\n\n\n「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。\n\n它不是逃避现实,也不是只顾旅行不顾责任。更常见的状态是:\n\n- 工作目标清晰,交付结果可衡量\n- 沟通及时,团队协作顺畅\n- 作息稳定,身心健康有保障\n- 遵守公司制度与当地法律法规\n\n对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。\n\n## 它适合谁\n\n更适合这些情况:\n\n- 内容创作、设计、开发、运营、客服、翻译、数据分析等可线上完成的工作\n- 公司已支持居家办公或混合办公\n- 个人执行力较强,能自我管理进度\n\n不太适合:强依赖现场设备、面对面服务、或必须到岗的岗位——除非岗位本身已经改为线上流程。\n\n## 先建立正确预期\n\n灵活不等于松散。远程工作往往更考验:\n\n1. **结果导向**:用可验收的成果说话 \n2. **可见度**:主动同步进度,减少信息不对称 \n3. **边界感**:工作与生活有节奏,避免「一直在线却效率很低」\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c3",
|
||||||
|
title: "远程办公的基本功",
|
||||||
|
order: 3,
|
||||||
|
content: "# 远程办公的基本功\n\n\n远程办公的核心不是「换一个风景」,而是「换一种可协作的工作方式」。\n\n## 1. 固定工作时段\n\n建议每天有固定的核心工作时间(例如 9:30–12:00、14:00–18:00),并告诉同事:\n\n- 哪些时段适合会议 \n- 哪些时段专注深度工作 \n- 紧急事项如何联系 \n\n时间透明,协作成本会明显下降。\n\n## 2. 日计划与周复盘\n\n每天开工前列三件「今天必须完成」的事;每周五花十五分钟复盘:\n\n- 本周完成了什么 \n- 卡在哪里 \n- 下周优先做什么 \n\n简单记录即可,不必写成复杂文档。\n\n## 3. 工具只保留必要的\n\n常见组合已经足够:\n\n- 文档协作:在线文档 / 表格 \n- 沟通:即时消息 + 邮件 \n- 会议:视频会议软件 \n- 任务:看板或待办清单 \n\n工具越多越容易分心。优先把「任务状态」和「最终交付物」放在团队约定的地方。\n\n## 4. 会议要短、要有结论\n\n开会前写清楚目的;开会后写三条结论:谁负责、做什么、何时完成。没有结论的会,尽量少开。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c4",
|
||||||
|
title: "居家与旅居的工作环境",
|
||||||
|
order: 4,
|
||||||
|
content: "# 居家与旅居的工作环境\n\n\n环境会直接影响专注力。不必追求豪华,但要「够用、安静、可持续」。\n\n## 居家办公清单\n\n- 稳定的桌椅与屏幕高度,减少颈椎负担 \n- 光线充足,白天尽量靠近自然光 \n- 耳机(隔音或降噪均可) \n- 备用充电器与移动电源 \n- 水杯与简单加餐,减少频繁打断 \n\n如果家里容易被打扰,可以约定「工作时关门」或使用图书馆、咖啡馆的安静时段。\n\n## 短途旅居怎么选地方\n\n如果公司允许短期异地办公,优先考虑:\n\n1. 网络稳定、电源方便 \n2. 住宿安静,适合睡眠 \n3. 周边有餐饮与运动条件 \n4. 往返交通可预期,不耽误会议 \n\n先从周末附近城市试住一两晚,再考虑更长的停留。陌生城市的第一周,把作息跑稳比「打卡景点」更重要。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c5",
|
||||||
|
title: "时间管理:让灵活真正有效",
|
||||||
|
order: 5,
|
||||||
|
content: "# 时间管理:让灵活真正有效\n\n\n灵活工作最大的风险是:时间碎、注意力散、任务拖。\n\n## 番茄工作法(简化版)\n\n- 25 分钟专注做一件事 \n- 休息 5 分钟 \n- 四个循环后休息 15–20 分钟 \n\n深度工作时关闭无关通知。回复消息可以集中到固定时段处理。\n\n## 分清「紧急」和「重要」\n\n每天真正重要的通常只有少数几项。把「看起来很忙」和「真正推进目标」分开:\n\n| 类型 | 例子 | 建议 |\n| --- | --- | --- |\n| 重要且紧急 | 当天截止的交付 | 立刻做 |\n| 重要不紧急 | 学习新技能、健康锻炼 | 排进日程 |\n| 紧急不重要 | 部分临时打扰 | 能委托就委托 |\n| 都不紧急 | 无目的刷信息 | 自觉限制 |\n\n## 保护深度工作时段\n\n建议每天至少留 90 分钟不被会议打断的时间,用来写方案、写代码、做设计或复盘数据。这段时间尽量提前在日历里标出来。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c6",
|
||||||
|
title: "沟通与团队协作",
|
||||||
|
order: 6,
|
||||||
|
content: "# 沟通与团队协作\n\n\n远程场景里,沟通质量几乎等于工作质量。\n\n## 同步信息的三个原则\n\n1. **默认公开**:进度写在团队可见的地方,少用只有你知道的私聊结论 \n2. **结论先行**:先说结果,再补背景 \n3. **可执行**:说清楚下一步、负责人和时间 \n\n## 异步沟通模板\n\n需要同事处理时,可以这样写:\n\n> 背景:…… \n> 需要你:…… \n> 截止:…… \n> 参考资料:…… \n\n对方不用来回追问,效率会高很多。\n\n## 信任来自稳定交付\n\n远程信任不是靠「一直在线」,而是靠:\n\n- 承诺的事按时完成 \n- 延期提前说明原因与新时间 \n- 问题主动暴露,而不是临近截止才说 \n\n把「靠谱」做成习惯,比任何管理鸡汤都管用。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c7",
|
||||||
|
title: "健康、作息与心态",
|
||||||
|
order: 7,
|
||||||
|
content: "# 健康、作息与心态\n\n\n身体垮了,任何生活方式都不可持续。\n\n## 作息建议\n\n- 尽量固定睡眠与起床时间 \n- 每工作一小时起身活动两分钟 \n- 中午留一段真正休息,而不是边吃边回消息 \n- 晚上给眼睛和大脑降温,少熬夜赶工 \n\n## 运动不必复杂\n\n散步、拉伸、居家力量训练都可以。关键是「每周能坚持」,而不是一次练到力竭。\n\n## 孤独感怎么处理\n\n长期独处容易闷。可以:\n\n- 定期与同事语音同步 \n- 参加健康正向的兴趣社群或线下读书会 \n- 与家人朋友保持固定联系时间 \n\n把社交安排进日历,和安排会议一样认真。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c8",
|
||||||
|
title: "学习成长与职业规划",
|
||||||
|
order: 8,
|
||||||
|
content: "# 学习成长与职业规划\n\n\n数字游民不是终点,而是一种工作形态。真正护城河仍是能力与口碑。\n\n## 持续提升三件事\n\n1. **专业技能**:让你的交付更稳、更快、质量更高 \n2. **表达能力**:把复杂问题讲清楚 \n3. **项目管理**:把事情拆小、排期、闭环 \n\n每周抽出固定学习时间,哪怕只有三十分钟,也比「有空再说」强。\n\n## 作品集思维\n\n把完成的项目整理成可展示的说明:\n\n- 解决了什么问题 \n- 你做了哪些关键决策 \n- 结果如何衡量 \n\n这对转岗、晋升或接更匹配的远程岗位都很有帮助。\n\n## 合规与边界\n\n请始终遵守:\n\n- 劳动合同与公司远程办公制度 \n- 信息安全与保密要求 \n- 所在地法律法规与税务规定 \n\n不传播不当内容,不从事违法违规业务。稳健发展,才能走得长远。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c9",
|
||||||
|
title: "七天起步计划",
|
||||||
|
order: 9,
|
||||||
|
content: "# 七天起步计划\n\n\n如果你想从零开始尝试更灵活的工作节奏,可以用这一周做轻量实验(在公司制度允许的前提下):\n\n**第 1 天**:整理工位,列出核心工作时段 \n**第 2 天**:建立待办清单,只保留三个每日目标 \n**第 3 天**:把常用文档放到团队约定位置 \n**第 4 天**:练习「结论先行」的消息写法 \n**第 5 天**:完成一次短复盘,记下卡点 \n**第 6 天**:安排一次户外散步或轻度运动 \n**第 7 天**:回顾本周,写下下周只改一件事 \n\n目标不是完美,而是建立可重复的节奏。\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "c10",
|
||||||
|
title: "结语",
|
||||||
|
order: 10,
|
||||||
|
content: "# 结语\n\n\n数字游民生活方式的本质,是用更好的方式完成工作、照顾生活,而不是追逐表象上的「自由」。\n\n先把远程协作做好,把身体照顾好,把专业能力垒扎实。地点可以慢慢变化,但秩序、责任与成长不能丢。\n\n祝你工作顺利,生活安定,步履从容。\n",
|
||||||
|
},
|
||||||
|
]
|
||||||
@ -107,17 +107,22 @@ export type WeappBookAudit = {
|
|||||||
bookId: string
|
bookId: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 包内种子:提审期默认开(首屏不等远程配置)。
|
||||||
|
* 审过之后台 platforms.weapp.bookAudit.reviewMode=false 覆盖即可。
|
||||||
|
*/
|
||||||
export const DEFAULT_BOOK_AUDIT: WeappBookAudit = {
|
export const DEFAULT_BOOK_AUDIT: WeappBookAudit = {
|
||||||
reviewMode: false,
|
reviewMode: true,
|
||||||
bookId: 'audit',
|
bookId: 'audit',
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 小册 Tab 审核用书:开审核则返回备用 bookId,否则 null(走正式路径) */
|
/** 小册 Tab 审核用书:开审核则走备用 Markdown / 本页内联正文 */
|
||||||
export function resolveBookAudit(config: NomadroRemoteConfig): WeappBookAudit {
|
export function resolveBookAudit(config: NomadroRemoteConfig): WeappBookAudit {
|
||||||
const raw = config.platforms?.weapp?.bookAudit
|
const raw = config.platforms?.weapp?.bookAudit
|
||||||
const bookId = String(raw?.bookId || DEFAULT_BOOK_AUDIT.bookId).trim() || 'audit'
|
const bookId = String(raw?.bookId || DEFAULT_BOOK_AUDIT.bookId).trim() || 'audit'
|
||||||
return {
|
return {
|
||||||
reviewMode: !!raw?.reviewMode,
|
reviewMode:
|
||||||
|
typeof raw?.reviewMode === 'boolean' ? raw.reviewMode : DEFAULT_BOOK_AUDIT.reviewMode,
|
||||||
bookId,
|
bookId,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
452
apps/miniprogram/h5/src/pages/book/BookCoverPage.tsx
Normal file
452
apps/miniprogram/h5/src/pages/book/BookCoverPage.tsx
Normal file
@ -0,0 +1,452 @@
|
|||||||
|
/**
|
||||||
|
* 电子书 H5 封面 — 对齐门户首页 / 社群首页视觉语言
|
||||||
|
* (CommunityNavbar + hero shapes + gradient + typewriter + 固定 CTA)
|
||||||
|
* 内容 SoT: COVER_BOOK / nomadCodeBook;阅读入口 → /pages/reader
|
||||||
|
*/
|
||||||
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { Button } from '@tarojs/components'
|
||||||
|
import { useDidShow, useLoad } from '@tarojs/taro'
|
||||||
|
import {
|
||||||
|
fetchBook,
|
||||||
|
fetchRead,
|
||||||
|
getAuditOfflineRead,
|
||||||
|
type BookDetail,
|
||||||
|
type ReadPayload,
|
||||||
|
} from '../../services/ebookApi'
|
||||||
|
import { COVER_BOOK } from '../../data/coverBook'
|
||||||
|
import {
|
||||||
|
formatAgo,
|
||||||
|
getReadingProgress,
|
||||||
|
type ReadingProgress,
|
||||||
|
} from '../../utils/readingProgress'
|
||||||
|
import { track, trackClick, trackPage } from '../../utils/track'
|
||||||
|
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
||||||
|
import { CommunityNavbar } from '../../components/Chrome'
|
||||||
|
import { H5Box, H5Txt } from '../../components/H5Box'
|
||||||
|
import { applyH5Theme, useNomadroTheme } from '../../utils/h5Theme'
|
||||||
|
import { goPage } from '@/utils/nav'
|
||||||
|
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
||||||
|
import {
|
||||||
|
getCachedRemoteConfig,
|
||||||
|
loadRemoteConfig,
|
||||||
|
subscribeRemoteConfig,
|
||||||
|
} from '@/services/remoteConfig'
|
||||||
|
import { resolveBookAudit } from '@/data/remoteConfig.defaults'
|
||||||
|
import './index.scss'
|
||||||
|
|
||||||
|
const isH5 = process.env.TARO_ENV === 'h5'
|
||||||
|
|
||||||
|
const BOOK_VISUAL_SVG = `<svg class="book-visual-svg" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||||
|
<defs>
|
||||||
|
<radialGradient id="bookGlow" cx="50%" cy="45%" r="55%">
|
||||||
|
<stop offset="0%" stop-color="#4ECDC4" stop-opacity="0.28"/>
|
||||||
|
<stop offset="55%" stop-color="#FFE66D" stop-opacity="0.08"/>
|
||||||
|
<stop offset="100%" stop-color="#FF6B6B" stop-opacity="0"/>
|
||||||
|
</radialGradient>
|
||||||
|
<linearGradient id="bookSpine" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#FF6B6B"/>
|
||||||
|
<stop offset="50%" stop-color="#FFE66D"/>
|
||||||
|
<stop offset="100%" stop-color="#4ECDC4"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="bookPageL" x1="100%" y1="0%" x2="0%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#1e293b"/>
|
||||||
|
<stop offset="100%" stop-color="#0f172a"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="bookPageR" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#1e293b"/>
|
||||||
|
<stop offset="100%" stop-color="#111827"/>
|
||||||
|
</linearGradient>
|
||||||
|
<filter id="bookSoft" x="-20%" y="-20%" width="140%" height="140%">
|
||||||
|
<feGaussianBlur stdDeviation="6" result="b"/>
|
||||||
|
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||||
|
</filter>
|
||||||
|
</defs>
|
||||||
|
<circle cx="200" cy="200" r="168" fill="url(#bookGlow)"/>
|
||||||
|
<ellipse class="book-shadow" cx="200" cy="318" rx="92" ry="14" fill="rgba(0,0,0,0.35)"/>
|
||||||
|
<g class="book-body" filter="url(#bookSoft)">
|
||||||
|
<path d="M200 78 C168 92 118 98 88 102 L88 278 C118 272 168 268 200 288 Z" fill="url(#bookPageL)" stroke="url(#bookSpine)" stroke-width="2.2"/>
|
||||||
|
<path d="M200 78 C232 92 282 98 312 102 L312 278 C282 272 232 268 200 288 Z" fill="url(#bookPageR)" stroke="url(#bookSpine)" stroke-width="2.2"/>
|
||||||
|
<path d="M200 78 L200 288" stroke="url(#bookSpine)" stroke-width="3.5" stroke-linecap="round"/>
|
||||||
|
<path class="book-line" d="M112 138 H176" stroke="#94a3b8" stroke-opacity="0.35" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path class="book-line" d="M112 162 H168" stroke="#94a3b8" stroke-opacity="0.28" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path class="book-line" d="M112 186 H172" stroke="#94a3b8" stroke-opacity="0.22" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path class="book-line" d="M224 138 H288" stroke="#94a3b8" stroke-opacity="0.35" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path class="book-line" d="M224 162 H280" stroke="#94a3b8" stroke-opacity="0.28" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path class="book-line" d="M224 186 H284" stroke="#94a3b8" stroke-opacity="0.22" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<circle cx="200" cy="168" r="28" fill="rgba(10,14,23,0.92)" stroke="url(#bookSpine)" stroke-width="2.5"/>
|
||||||
|
<text text-anchor="middle" dominant-baseline="central" x="200" y="170" font-size="26">📖</text>
|
||||||
|
</g>
|
||||||
|
<circle class="book-spark" cx="96" cy="96" r="4" fill="#FFE66D"/>
|
||||||
|
<circle class="book-spark" cx="318" cy="120" r="3.5" fill="#4ECDC4"/>
|
||||||
|
<circle class="book-spark" cx="300" cy="260" r="3" fill="#FF6B6B"/>
|
||||||
|
<circle r="3.2" fill="#FFE66D"><animateMotion dur="4.2s" repeatCount="indefinite" path="M120 250 Q200 210 280 250"/></circle>
|
||||||
|
<circle r="2.8" fill="#4ECDC4"><animateMotion dur="5s" repeatCount="indefinite" path="M140 110 Q200 70 260 110" begin="0.8s"/></circle>
|
||||||
|
</svg>`
|
||||||
|
|
||||||
|
function coverAsBookDetail(): BookDetail {
|
||||||
|
return {
|
||||||
|
id: 'default',
|
||||||
|
title: COVER_BOOK.title,
|
||||||
|
subtitle: COVER_BOOK.subtitle,
|
||||||
|
author: COVER_BOOK.author,
|
||||||
|
cover_emoji: '📖',
|
||||||
|
description: COVER_BOOK.description,
|
||||||
|
tags: [...COVER_BOOK.viralTags],
|
||||||
|
price_fen: 0,
|
||||||
|
product_id: 'ebook_default',
|
||||||
|
unlock_percent: 100,
|
||||||
|
is_free: true,
|
||||||
|
chapter_count: COVER_BOOK.chapters.length,
|
||||||
|
word_count: 0,
|
||||||
|
rating: 0,
|
||||||
|
chapters: COVER_BOOK.chapters.map((ch, i) => ({
|
||||||
|
id: ch.slug,
|
||||||
|
title: ch.title,
|
||||||
|
order: i + 1,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const HOOK_LINES = COVER_BOOK.hooks.map((h) => `${h.emoji} ${h.text}`)
|
||||||
|
const CHIP_TAGS = COVER_BOOK.viralTags.slice(0, 3)
|
||||||
|
|
||||||
|
function BookPageInner() {
|
||||||
|
const theme = useNomadroTheme()
|
||||||
|
// 封面视觉一律 COVER_BOOK(对齐 H5);解锁/章节仍可走 API 进阅读器
|
||||||
|
const [book, setBook] = useState<BookDetail | null>(coverAsBookDetail())
|
||||||
|
const [apiBook, setApiBook] = useState<BookDetail | null>(null)
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [progress, setProgress] = useState<ReadingProgress | null>(null)
|
||||||
|
const [tw, setTw] = useState('')
|
||||||
|
const [audit, setAudit] = useState(() => resolveBookAudit(getCachedRemoteConfig()))
|
||||||
|
const auditKeyRef = useRef(`${audit.reviewMode}:${audit.bookId}`)
|
||||||
|
// 提审:本页内联正文(不跳 reader 分包,避免未预载黑屏)
|
||||||
|
const [auditRead, setAuditRead] = useState<ReadPayload | null>(() => {
|
||||||
|
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||||
|
return a.reviewMode ? getAuditOfflineRead(a.bookId || 'audit') : null
|
||||||
|
})
|
||||||
|
|
||||||
|
function loadAuditRead(bookId: string) {
|
||||||
|
const id = bookId || 'audit'
|
||||||
|
setAuditRead(getAuditOfflineRead(id))
|
||||||
|
void fetchRead(id)
|
||||||
|
.then((res) => {
|
||||||
|
if (res?.chapters?.length) setAuditRead(res)
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* 已有离线 */
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
useLoad(() => {
|
||||||
|
trackPage('pages/book/index', '小册封面')
|
||||||
|
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||||
|
if (a.reviewMode) {
|
||||||
|
setAudit(a)
|
||||||
|
loadAuditRead(a.bookId || 'audit')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loadBook()
|
||||||
|
})
|
||||||
|
|
||||||
|
useDidShow(() => {
|
||||||
|
void loadRemoteConfig(true).then((r) => {
|
||||||
|
applyAudit(resolveBookAudit(r.config))
|
||||||
|
})
|
||||||
|
// 提审壳不拉封面,避免无意义请求与闪烁
|
||||||
|
if (!resolveBookAudit(getCachedRemoteConfig()).reviewMode) {
|
||||||
|
loadBook(true)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return subscribeRemoteConfig((r) => {
|
||||||
|
applyAudit(resolveBookAudit(r.config))
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
applyH5Theme(theme)
|
||||||
|
}, [theme])
|
||||||
|
|
||||||
|
function applyAudit(next: ReturnType<typeof resolveBookAudit>) {
|
||||||
|
const key = `${next.reviewMode}:${next.bookId}`
|
||||||
|
const changed = key !== auditKeyRef.current
|
||||||
|
auditKeyRef.current = key
|
||||||
|
setAudit(next)
|
||||||
|
const pid = next.reviewMode ? next.bookId || 'audit' : 'nomad'
|
||||||
|
setProgress(getReadingProgress(pid))
|
||||||
|
if (changed) {
|
||||||
|
if (next.reviewMode) {
|
||||||
|
loadAuditRead(next.bookId || 'audit')
|
||||||
|
} else {
|
||||||
|
setAuditRead(null)
|
||||||
|
void loadBook(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 对齐小红书 startTypewriter:hooks 轮播打字机(提审壳不跑)
|
||||||
|
useEffect(() => {
|
||||||
|
if (loading || audit.reviewMode) return
|
||||||
|
const phrases = HOOK_LINES.length ? HOOK_LINES : [COVER_BOOK.subtitle]
|
||||||
|
let phraseIdx = 0
|
||||||
|
let charIdx = 0
|
||||||
|
let deleting = false
|
||||||
|
let timer: ReturnType<typeof setTimeout>
|
||||||
|
|
||||||
|
const type = () => {
|
||||||
|
const current = phrases[phraseIdx] || ''
|
||||||
|
if (!deleting) {
|
||||||
|
setTw(current.substring(0, charIdx + 1))
|
||||||
|
charIdx++
|
||||||
|
if (charIdx === current.length) {
|
||||||
|
deleting = true
|
||||||
|
timer = setTimeout(type, 2600)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
timer = setTimeout(type, 42)
|
||||||
|
} else {
|
||||||
|
setTw(current.substring(0, charIdx - 1))
|
||||||
|
charIdx--
|
||||||
|
if (charIdx === 0) {
|
||||||
|
deleting = false
|
||||||
|
phraseIdx = (phraseIdx + 1) % phrases.length
|
||||||
|
}
|
||||||
|
timer = setTimeout(type, 22)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
timer = setTimeout(type, 380)
|
||||||
|
return () => clearTimeout(timer)
|
||||||
|
}, [loading, audit.reviewMode])
|
||||||
|
|
||||||
|
async function loadBook(silent = false) {
|
||||||
|
setError('')
|
||||||
|
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||||
|
setAudit(a)
|
||||||
|
auditKeyRef.current = `${a.reviewMode}:${a.bookId}`
|
||||||
|
// 正式:封面品牌视觉;提审:立刻换成审核版书名/章节,保证开关可见
|
||||||
|
if (!a.reviewMode) {
|
||||||
|
setBook(coverAsBookDetail())
|
||||||
|
setApiBook(null)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!silent) setLoading(true)
|
||||||
|
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
||||||
|
const data = await fetchBook(bookId)
|
||||||
|
setApiBook(data)
|
||||||
|
if (a.reviewMode && data) {
|
||||||
|
setBook({
|
||||||
|
...coverAsBookDetail(),
|
||||||
|
id: data.id,
|
||||||
|
title: data.title || '数字游民入门指南',
|
||||||
|
subtitle: data.subtitle || '远程办公 · 自律生活 · 稳健成长',
|
||||||
|
description: data.description || coverAsBookDetail().description,
|
||||||
|
chapters: data.chapters?.length ? data.chapters : coverAsBookDetail().chapters,
|
||||||
|
is_free: true,
|
||||||
|
unlock_percent: 100,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
if (a.reviewMode) {
|
||||||
|
setBook({
|
||||||
|
...coverAsBookDetail(),
|
||||||
|
id: a.bookId || 'audit',
|
||||||
|
title: '数字游民入门指南',
|
||||||
|
subtitle: '远程办公 · 自律生活 · 稳健成长',
|
||||||
|
is_free: true,
|
||||||
|
unlock_percent: 100,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
track('error', {
|
||||||
|
page: 'pages/book/index',
|
||||||
|
label: 'load_book',
|
||||||
|
props: { msg: String(e.message || e) },
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
if (!silent) setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const continueChapter = useMemo(() => {
|
||||||
|
const chapters = apiBook?.chapters?.length ? apiBook.chapters : book?.chapters
|
||||||
|
if (!chapters || !progress?.chapterId) return null
|
||||||
|
const found = chapters.find((c) => String(c.id) === String(progress.chapterId))
|
||||||
|
if (found) return found
|
||||||
|
return { id: progress.chapterId, title: `第 ${progress.chapterIndex + 1} 章` }
|
||||||
|
}, [book, apiBook, progress])
|
||||||
|
|
||||||
|
// 必须在一切 early-return 之前:reviewMode 冷启动 false→true 时否则 hooks 数量变化 → 黑屏
|
||||||
|
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||||
|
const safeStyle = useMemo(
|
||||||
|
() => ({
|
||||||
|
['--safe-status-bar' as string]: `${safe.statusBarHeight}px`,
|
||||||
|
['--safe-nav-bar' as string]: `${safe.navBarHeight}px`,
|
||||||
|
['--safe-menu-pad' as string]: `${safe.menuRightPad}px`,
|
||||||
|
['--safe-header' as string]: `${safe.headerHeight}px`,
|
||||||
|
}),
|
||||||
|
[safe],
|
||||||
|
)
|
||||||
|
|
||||||
|
function goRead() {
|
||||||
|
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||||
|
// 仅针对「数字游民小册」:审核→备用 Markdown;正式→VIP 电子书 nomad
|
||||||
|
// youtube运营笔记(default) 不受此开关影响
|
||||||
|
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
||||||
|
const continuing = !!progress?.chapterId
|
||||||
|
trackClick(continuing ? '继续阅读' : '开始阅读', {
|
||||||
|
book_id: bookId,
|
||||||
|
has_progress: continuing,
|
||||||
|
audit: a.reviewMode,
|
||||||
|
})
|
||||||
|
track('read_start', {
|
||||||
|
page: 'pages/book/index',
|
||||||
|
label: continuing ? '继续阅读' : '开始阅读',
|
||||||
|
props: { book_id: bookId, audit: a.reviewMode },
|
||||||
|
})
|
||||||
|
if (a.reviewMode) {
|
||||||
|
// 提审正文已在本页,无需再跳
|
||||||
|
return
|
||||||
|
}
|
||||||
|
goPage('/pages/vip-ebook/index?id=nomad')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading && !book) {
|
||||||
|
return (
|
||||||
|
<H5Box className="page-shell book-flow book-flow--error">
|
||||||
|
<CommunityNavbar />
|
||||||
|
<H5Box className="book-error">
|
||||||
|
<H5Txt className="book-error-hint">加载中…</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !book) {
|
||||||
|
return (
|
||||||
|
<H5Box className="page-shell book-flow book-flow--error">
|
||||||
|
<CommunityNavbar />
|
||||||
|
<H5Box className="book-error">
|
||||||
|
<H5Txt className="book-error-title">暂时打不开</H5Txt>
|
||||||
|
<H5Txt className="book-error-hint">{error || '请稍后再试'}</H5Txt>
|
||||||
|
<Button
|
||||||
|
className="btn btn-primary"
|
||||||
|
onClick={() => {
|
||||||
|
trackClick('首页重试')
|
||||||
|
loadBook()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
再试一次
|
||||||
|
</Button>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasProgress = !!continueChapter
|
||||||
|
const unlockSource = apiBook || book
|
||||||
|
const isFree = !!(unlockSource.is_free || (unlockSource.unlock_percent ?? 0) >= 100)
|
||||||
|
const ctaText = hasProgress ? '📖 继续阅读' : '📖 开始阅读'
|
||||||
|
const ctaHint = hasProgress
|
||||||
|
? progress?.updatedAt
|
||||||
|
? `上次翻到 · ${formatAgo(progress.updatedAt)}`
|
||||||
|
: '接着上次的地方'
|
||||||
|
: isFree
|
||||||
|
? '点一下,直接进入正文'
|
||||||
|
: '先翻开前面的章节'
|
||||||
|
|
||||||
|
const displayTitle = audit.reviewMode
|
||||||
|
? book.title || '数字游民入门指南'
|
||||||
|
: COVER_BOOK.title
|
||||||
|
const tagParts = [
|
||||||
|
audit.reviewMode
|
||||||
|
? book.subtitle || '远程办公 · 自律生活 · 稳健成长'
|
||||||
|
: book.subtitle || COVER_BOOK.subtitle || '低成本工作室',
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<H5Box
|
||||||
|
className="page-shell home-flow home-flow--hero-only book-flow"
|
||||||
|
data-theme={theme}
|
||||||
|
style={safeStyle}
|
||||||
|
>
|
||||||
|
<CommunityNavbar />
|
||||||
|
|
||||||
|
<H5Box className="hero" id="hero">
|
||||||
|
<H5Box className="hero-bg-shapes" aria-hidden>
|
||||||
|
<H5Box className="shape shape-1" />
|
||||||
|
<H5Box className="shape shape-2" />
|
||||||
|
<H5Box className="shape shape-3" />
|
||||||
|
</H5Box>
|
||||||
|
|
||||||
|
<H5Box className="hero-inner">
|
||||||
|
<H5Box className="hero-top">
|
||||||
|
<H5Box className="hero-content">
|
||||||
|
<H5Box className="hero-title book-hero-title">
|
||||||
|
<H5Txt className="hero-title-line book-title-brand">{displayTitle}</H5Txt>
|
||||||
|
<H5Box className="hero-title-line book-tagline">
|
||||||
|
<H5Txt>{tagParts[0]}</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
|
||||||
|
<H5Txt className="hero-title-spark" aria-hidden>
|
||||||
|
✨
|
||||||
|
</H5Txt>
|
||||||
|
|
||||||
|
<H5Txt className="hero-subtitle book-typewriter">
|
||||||
|
{tw}
|
||||||
|
<H5Txt className="typewriter-cursor">|</H5Txt>
|
||||||
|
</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
|
||||||
|
<H5Box className="hero-visual" onClick={goRead}>
|
||||||
|
<H5Box className="book-visual">
|
||||||
|
{isH5 ? (
|
||||||
|
<H5Box className="book-visual-host" html={BOOK_VISUAL_SVG} />
|
||||||
|
) : (
|
||||||
|
<H5Box className="book-visual-css" aria-hidden>
|
||||||
|
<H5Box className="book-visual-css-glow" />
|
||||||
|
<H5Box className="book-visual-css-body">
|
||||||
|
<H5Box className="book-visual-css-spine" />
|
||||||
|
<H5Txt className="book-visual-css-emoji">📖</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
)}
|
||||||
|
<H5Box className="book-float-chips social-float-chips">
|
||||||
|
{CHIP_TAGS.map((tag, i) => (
|
||||||
|
<H5Box key={tag} className={`social-chip sc-${i + 1}`}>
|
||||||
|
<H5Txt>
|
||||||
|
{i === 0 ? '🏷 ' : i === 1 ? '⚡ ' : '🌐 '}
|
||||||
|
{tag}
|
||||||
|
</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
))}
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
|
||||||
|
<H5Box className="hero-bottom">
|
||||||
|
<H5Box className="hero-actions book-actions">
|
||||||
|
<Button className="btn btn-primary book-cta" onClick={goRead}>
|
||||||
|
{ctaText}
|
||||||
|
</Button>
|
||||||
|
<H5Txt className="book-cta-hint">{ctaHint}</H5Txt>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 正式封面(审后 reviewMode=false 时由 book/index 挂载) */
|
||||||
|
export default function BookCoverPage() {
|
||||||
|
return (
|
||||||
|
<MiniModuleGate moduleKey="book">
|
||||||
|
<BookPageInner />
|
||||||
|
</MiniModuleGate>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@ -1,4 +1,8 @@
|
|||||||
export default definePageConfig({
|
export default definePageConfig({
|
||||||
navigationBarTitleText: '数字游民',
|
navigationBarTitleText: '数字游民入门指南',
|
||||||
navigationStyle: 'custom',
|
navigationBarBackgroundColor: '#0c0b12',
|
||||||
|
navigationBarTextStyle: 'white',
|
||||||
|
backgroundColor: '#0c0b12',
|
||||||
|
// 提审:用系统导航(返回+标题),避免 custom 无顶栏像黑屏
|
||||||
|
navigationStyle: 'default',
|
||||||
})
|
})
|
||||||
|
|||||||
@ -14,6 +14,91 @@
|
|||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 提审:小册页内联正文(页面级滚动,勿套 ScrollView) */
|
||||||
|
.book-audit.page-shell,
|
||||||
|
.book-flow.book-audit {
|
||||||
|
min-height: 100vh;
|
||||||
|
height: auto !important;
|
||||||
|
overflow: visible !important;
|
||||||
|
overflow-y: visible !important;
|
||||||
|
background: #0c0b12;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding-bottom: 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-back {
|
||||||
|
padding: 4px 16px 0;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-back-t {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #4ecdc4;
|
||||||
|
line-height: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-head {
|
||||||
|
padding: 8px 20px 16px;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-emoji {
|
||||||
|
display: block;
|
||||||
|
font-size: 28px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-title {
|
||||||
|
display: block;
|
||||||
|
font-size: 22px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #f8fafc;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-sub {
|
||||||
|
display: block;
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #94a3b8;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-meta {
|
||||||
|
display: block;
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #64748b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-body {
|
||||||
|
padding: 12px 16px 48px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-chapter {
|
||||||
|
margin-bottom: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-ch-title {
|
||||||
|
display: block;
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #e2e8f0;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-end {
|
||||||
|
padding: 24px 0 40px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.book-audit-end-t {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #64748b;
|
||||||
|
}
|
||||||
|
|
||||||
.book-error {
|
.book-error {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@ -1,427 +1,120 @@
|
|||||||
/**
|
/**
|
||||||
* 电子书 H5 封面 — 对齐门户首页 / 社群首页视觉语言
|
* 提审小册:静态页,无 hooks / 无外部数据依赖。
|
||||||
* (CommunityNavbar + hero shapes + gradient + typewriter + 固定 CTA)
|
|
||||||
* 内容 SoT: COVER_BOOK / nomadCodeBook;阅读入口 → /pages/reader
|
|
||||||
*/
|
*/
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { View, Text } from '@tarojs/components'
|
||||||
import { Button } from '@tarojs/components'
|
|
||||||
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
|
|
||||||
import { fetchBook, type BookDetail } from '../../services/ebookApi'
|
|
||||||
import { COVER_BOOK } from '../../data/coverBook'
|
|
||||||
import {
|
|
||||||
formatAgo,
|
|
||||||
getReadingProgress,
|
|
||||||
type ReadingProgress,
|
|
||||||
} from '../../utils/readingProgress'
|
|
||||||
import { track, trackClick, trackPage } from '../../utils/track'
|
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
|
||||||
import { CommunityNavbar } from '../../components/Chrome'
|
|
||||||
import { H5Box, H5Txt } from '../../components/H5Box'
|
|
||||||
import { applyH5Theme, useNomadroTheme } from '../../utils/h5Theme'
|
|
||||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
|
||||||
import { goPage } from '@/utils/nav'
|
|
||||||
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
|
||||||
import {
|
|
||||||
getCachedRemoteConfig,
|
|
||||||
loadRemoteConfig,
|
|
||||||
subscribeRemoteConfig,
|
|
||||||
} from '@/services/remoteConfig'
|
|
||||||
import { resolveBookAudit } from '@/data/remoteConfig.defaults'
|
|
||||||
import './index.scss'
|
|
||||||
|
|
||||||
const isH5 = process.env.TARO_ENV === 'h5'
|
function px(n: number) {
|
||||||
|
return `${n}PX`
|
||||||
const BOOK_VISUAL_SVG = `<svg class="book-visual-svg" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
|
||||||
<defs>
|
|
||||||
<radialGradient id="bookGlow" cx="50%" cy="45%" r="55%">
|
|
||||||
<stop offset="0%" stop-color="#4ECDC4" stop-opacity="0.28"/>
|
|
||||||
<stop offset="55%" stop-color="#FFE66D" stop-opacity="0.08"/>
|
|
||||||
<stop offset="100%" stop-color="#FF6B6B" stop-opacity="0"/>
|
|
||||||
</radialGradient>
|
|
||||||
<linearGradient id="bookSpine" x1="0%" y1="0%" x2="100%" y2="100%">
|
|
||||||
<stop offset="0%" stop-color="#FF6B6B"/>
|
|
||||||
<stop offset="50%" stop-color="#FFE66D"/>
|
|
||||||
<stop offset="100%" stop-color="#4ECDC4"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="bookPageL" x1="100%" y1="0%" x2="0%" y2="100%">
|
|
||||||
<stop offset="0%" stop-color="#1e293b"/>
|
|
||||||
<stop offset="100%" stop-color="#0f172a"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="bookPageR" x1="0%" y1="0%" x2="100%" y2="100%">
|
|
||||||
<stop offset="0%" stop-color="#1e293b"/>
|
|
||||||
<stop offset="100%" stop-color="#111827"/>
|
|
||||||
</linearGradient>
|
|
||||||
<filter id="bookSoft" x="-20%" y="-20%" width="140%" height="140%">
|
|
||||||
<feGaussianBlur stdDeviation="6" result="b"/>
|
|
||||||
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
|
|
||||||
</filter>
|
|
||||||
</defs>
|
|
||||||
<circle cx="200" cy="200" r="168" fill="url(#bookGlow)"/>
|
|
||||||
<ellipse class="book-shadow" cx="200" cy="318" rx="92" ry="14" fill="rgba(0,0,0,0.35)"/>
|
|
||||||
<g class="book-body" filter="url(#bookSoft)">
|
|
||||||
<path d="M200 78 C168 92 118 98 88 102 L88 278 C118 272 168 268 200 288 Z" fill="url(#bookPageL)" stroke="url(#bookSpine)" stroke-width="2.2"/>
|
|
||||||
<path d="M200 78 C232 92 282 98 312 102 L312 278 C282 272 232 268 200 288 Z" fill="url(#bookPageR)" stroke="url(#bookSpine)" stroke-width="2.2"/>
|
|
||||||
<path d="M200 78 L200 288" stroke="url(#bookSpine)" stroke-width="3.5" stroke-linecap="round"/>
|
|
||||||
<path class="book-line" d="M112 138 H176" stroke="#94a3b8" stroke-opacity="0.35" stroke-width="2" stroke-linecap="round"/>
|
|
||||||
<path class="book-line" d="M112 162 H168" stroke="#94a3b8" stroke-opacity="0.28" stroke-width="2" stroke-linecap="round"/>
|
|
||||||
<path class="book-line" d="M112 186 H172" stroke="#94a3b8" stroke-opacity="0.22" stroke-width="2" stroke-linecap="round"/>
|
|
||||||
<path class="book-line" d="M224 138 H288" stroke="#94a3b8" stroke-opacity="0.35" stroke-width="2" stroke-linecap="round"/>
|
|
||||||
<path class="book-line" d="M224 162 H280" stroke="#94a3b8" stroke-opacity="0.28" stroke-width="2" stroke-linecap="round"/>
|
|
||||||
<path class="book-line" d="M224 186 H284" stroke="#94a3b8" stroke-opacity="0.22" stroke-width="2" stroke-linecap="round"/>
|
|
||||||
<circle cx="200" cy="168" r="28" fill="rgba(10,14,23,0.92)" stroke="url(#bookSpine)" stroke-width="2.5"/>
|
|
||||||
<text text-anchor="middle" dominant-baseline="central" x="200" y="170" font-size="26">📖</text>
|
|
||||||
</g>
|
|
||||||
<circle class="book-spark" cx="96" cy="96" r="4" fill="#FFE66D"/>
|
|
||||||
<circle class="book-spark" cx="318" cy="120" r="3.5" fill="#4ECDC4"/>
|
|
||||||
<circle class="book-spark" cx="300" cy="260" r="3" fill="#FF6B6B"/>
|
|
||||||
<circle r="3.2" fill="#FFE66D"><animateMotion dur="4.2s" repeatCount="indefinite" path="M120 250 Q200 210 280 250"/></circle>
|
|
||||||
<circle r="2.8" fill="#4ECDC4"><animateMotion dur="5s" repeatCount="indefinite" path="M140 110 Q200 70 260 110" begin="0.8s"/></circle>
|
|
||||||
</svg>`
|
|
||||||
|
|
||||||
function coverAsBookDetail(): BookDetail {
|
|
||||||
return {
|
|
||||||
id: 'default',
|
|
||||||
title: COVER_BOOK.title,
|
|
||||||
subtitle: COVER_BOOK.subtitle,
|
|
||||||
author: COVER_BOOK.author,
|
|
||||||
cover_emoji: '📖',
|
|
||||||
description: COVER_BOOK.description,
|
|
||||||
tags: [...COVER_BOOK.viralTags],
|
|
||||||
price_fen: 0,
|
|
||||||
product_id: 'ebook_default',
|
|
||||||
unlock_percent: 100,
|
|
||||||
is_free: true,
|
|
||||||
chapter_count: COVER_BOOK.chapters.length,
|
|
||||||
word_count: 0,
|
|
||||||
rating: 0,
|
|
||||||
chapters: COVER_BOOK.chapters.map((ch, i) => ({
|
|
||||||
id: ch.slug,
|
|
||||||
title: ch.title,
|
|
||||||
order: i + 1,
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const HOOK_LINES = COVER_BOOK.hooks.map((h) => `${h.emoji} ${h.text}`)
|
const box = {
|
||||||
const CHIP_TAGS = COVER_BOOK.viralTags.slice(0, 3)
|
minHeight: '100vh',
|
||||||
|
width: '100%',
|
||||||
|
backgroundColor: '#0c0b12',
|
||||||
|
paddingTop: px(20),
|
||||||
|
paddingRight: px(16),
|
||||||
|
paddingBottom: px(40),
|
||||||
|
paddingLeft: px(16),
|
||||||
|
boxSizing: 'border-box' as const,
|
||||||
|
}
|
||||||
|
|
||||||
function BookPageInner() {
|
const h1 = {
|
||||||
const theme = useNomadroTheme()
|
display: 'block' as const,
|
||||||
// 封面视觉一律 COVER_BOOK(对齐 H5);解锁/章节仍可走 API 进阅读器
|
fontSize: px(22),
|
||||||
const [book, setBook] = useState<BookDetail | null>(coverAsBookDetail())
|
fontWeight: '700' as const,
|
||||||
const [apiBook, setApiBook] = useState<BookDetail | null>(null)
|
color: '#f8fafc',
|
||||||
const [loading, setLoading] = useState(false)
|
lineHeight: '1.35',
|
||||||
const [error, setError] = useState('')
|
marginBottom: px(8),
|
||||||
const [progress, setProgress] = useState<ReadingProgress | null>(null)
|
}
|
||||||
const [tw, setTw] = useState('')
|
|
||||||
const [audit, setAudit] = useState(() => resolveBookAudit(getCachedRemoteConfig()))
|
|
||||||
const auditKeyRef = useRef(`${audit.reviewMode}:${audit.bookId}`)
|
|
||||||
|
|
||||||
useLoad(() => {
|
const h2 = {
|
||||||
trackPage('pages/book/index', '小册封面')
|
display: 'block' as const,
|
||||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
fontSize: px(16),
|
||||||
if (a.reviewMode) {
|
fontWeight: '700' as const,
|
||||||
const url = `/pages/reader/index?id=${encodeURIComponent(a.bookId || 'audit')}`
|
color: '#e2e8f0',
|
||||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
lineHeight: '1.4',
|
||||||
return
|
marginTop: px(20),
|
||||||
}
|
marginBottom: px(8),
|
||||||
loadBook()
|
}
|
||||||
})
|
|
||||||
|
|
||||||
useDidShow(() => {
|
const p = {
|
||||||
void loadRemoteConfig(true).then((r) => {
|
display: 'block' as const,
|
||||||
applyAudit(resolveBookAudit(r.config))
|
fontSize: px(15),
|
||||||
})
|
color: '#cbd5e1',
|
||||||
loadBook(true)
|
lineHeight: '1.75',
|
||||||
})
|
marginBottom: px(8),
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
const sub = {
|
||||||
return subscribeRemoteConfig((r) => {
|
display: 'block' as const,
|
||||||
applyAudit(resolveBookAudit(r.config))
|
fontSize: px(13),
|
||||||
})
|
color: '#94a3b8',
|
||||||
}, [])
|
lineHeight: '1.45',
|
||||||
|
marginBottom: px(16),
|
||||||
useEffect(() => {
|
}
|
||||||
applyH5Theme(theme)
|
|
||||||
}, [theme])
|
|
||||||
|
|
||||||
function applyAudit(next: ReturnType<typeof resolveBookAudit>) {
|
|
||||||
const key = `${next.reviewMode}:${next.bookId}`
|
|
||||||
const changed = key !== auditKeyRef.current
|
|
||||||
auditKeyRef.current = key
|
|
||||||
setAudit(next)
|
|
||||||
const pid = next.reviewMode ? next.bookId || 'audit' : 'nomad'
|
|
||||||
setProgress(getReadingProgress(pid))
|
|
||||||
if (changed) {
|
|
||||||
void loadBook(true)
|
|
||||||
// 提审开:直接进审核版;提审关:留在封面展示正式入口
|
|
||||||
if (next.reviewMode) {
|
|
||||||
const url = `/pages/reader/index?id=${encodeURIComponent(next.bookId || 'audit')}`
|
|
||||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 对齐小红书 startTypewriter:hooks 轮播打字机
|
|
||||||
useEffect(() => {
|
|
||||||
if (loading) return
|
|
||||||
const phrases = HOOK_LINES.length ? HOOK_LINES : [COVER_BOOK.subtitle]
|
|
||||||
let phraseIdx = 0
|
|
||||||
let charIdx = 0
|
|
||||||
let deleting = false
|
|
||||||
let timer: ReturnType<typeof setTimeout>
|
|
||||||
|
|
||||||
const type = () => {
|
|
||||||
const current = phrases[phraseIdx] || ''
|
|
||||||
if (!deleting) {
|
|
||||||
setTw(current.substring(0, charIdx + 1))
|
|
||||||
charIdx++
|
|
||||||
if (charIdx === current.length) {
|
|
||||||
deleting = true
|
|
||||||
timer = setTimeout(type, 2600)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
timer = setTimeout(type, 42)
|
|
||||||
} else {
|
|
||||||
setTw(current.substring(0, charIdx - 1))
|
|
||||||
charIdx--
|
|
||||||
if (charIdx === 0) {
|
|
||||||
deleting = false
|
|
||||||
phraseIdx = (phraseIdx + 1) % phrases.length
|
|
||||||
}
|
|
||||||
timer = setTimeout(type, 22)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
timer = setTimeout(type, 380)
|
|
||||||
return () => clearTimeout(timer)
|
|
||||||
}, [loading])
|
|
||||||
|
|
||||||
async function loadBook(silent = false) {
|
|
||||||
setError('')
|
|
||||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
|
||||||
setAudit(a)
|
|
||||||
auditKeyRef.current = `${a.reviewMode}:${a.bookId}`
|
|
||||||
// 正式:封面品牌视觉;提审:立刻换成审核版书名/章节,保证开关可见
|
|
||||||
if (!a.reviewMode) {
|
|
||||||
setBook(coverAsBookDetail())
|
|
||||||
setApiBook(null)
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (!silent) setLoading(true)
|
|
||||||
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
|
||||||
const data = await fetchBook(bookId)
|
|
||||||
setApiBook(data)
|
|
||||||
if (a.reviewMode && data) {
|
|
||||||
setBook({
|
|
||||||
...coverAsBookDetail(),
|
|
||||||
id: data.id,
|
|
||||||
title: data.title || '数字游民入门指南',
|
|
||||||
subtitle: data.subtitle || '远程办公 · 自律生活 · 稳健成长',
|
|
||||||
description: data.description || coverAsBookDetail().description,
|
|
||||||
chapters: data.chapters?.length ? data.chapters : coverAsBookDetail().chapters,
|
|
||||||
is_free: true,
|
|
||||||
unlock_percent: 100,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
if (a.reviewMode) {
|
|
||||||
setBook({
|
|
||||||
...coverAsBookDetail(),
|
|
||||||
id: a.bookId || 'audit',
|
|
||||||
title: '数字游民入门指南',
|
|
||||||
subtitle: '远程办公 · 自律生活 · 稳健成长',
|
|
||||||
is_free: true,
|
|
||||||
unlock_percent: 100,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
track('error', {
|
|
||||||
page: 'pages/book/index',
|
|
||||||
label: 'load_book',
|
|
||||||
props: { msg: String(e.message || e) },
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
if (!silent) setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const continueChapter = useMemo(() => {
|
|
||||||
const chapters = apiBook?.chapters?.length ? apiBook.chapters : book?.chapters
|
|
||||||
if (!chapters || !progress?.chapterId) return null
|
|
||||||
const found = chapters.find((c) => String(c.id) === String(progress.chapterId))
|
|
||||||
if (found) return found
|
|
||||||
return { id: progress.chapterId, title: `第 ${progress.chapterIndex + 1} 章` }
|
|
||||||
}, [book, apiBook, progress])
|
|
||||||
|
|
||||||
function goRead() {
|
|
||||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
|
||||||
// 仅针对「数字游民小册」:审核→备用 Markdown;正式→VIP 电子书 nomad
|
|
||||||
// youtube运营笔记(default) 不受此开关影响
|
|
||||||
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
|
||||||
const continuing = !!progress?.chapterId
|
|
||||||
trackClick(continuing ? '继续阅读' : '开始阅读', {
|
|
||||||
book_id: bookId,
|
|
||||||
has_progress: continuing,
|
|
||||||
audit: a.reviewMode,
|
|
||||||
})
|
|
||||||
track('read_start', {
|
|
||||||
page: 'pages/book/index',
|
|
||||||
label: continuing ? '继续阅读' : '开始阅读',
|
|
||||||
props: { book_id: bookId, audit: a.reviewMode },
|
|
||||||
})
|
|
||||||
if (a.reviewMode) {
|
|
||||||
goPage(`/pages/reader/index?id=${encodeURIComponent(bookId)}`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
goPage('/pages/vip-ebook/index?id=nomad')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loading && !book) {
|
|
||||||
return (
|
|
||||||
<H5Box className="page-shell book-flow book-flow--error">
|
|
||||||
<CommunityNavbar />
|
|
||||||
<H5Box className="book-error">
|
|
||||||
<H5Txt className="book-error-hint">加载中…</H5Txt>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error || !book) {
|
|
||||||
return (
|
|
||||||
<H5Box className="page-shell book-flow book-flow--error">
|
|
||||||
<CommunityNavbar />
|
|
||||||
<H5Box className="book-error">
|
|
||||||
<H5Txt className="book-error-title">暂时打不开</H5Txt>
|
|
||||||
<H5Txt className="book-error-hint">{error || '请稍后再试'}</H5Txt>
|
|
||||||
<Button
|
|
||||||
className="btn btn-primary"
|
|
||||||
onClick={() => {
|
|
||||||
trackClick('首页重试')
|
|
||||||
loadBook()
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
再试一次
|
|
||||||
</Button>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasProgress = !!continueChapter
|
|
||||||
const unlockSource = apiBook || book
|
|
||||||
const isFree = !!(unlockSource.is_free || (unlockSource.unlock_percent ?? 0) >= 100)
|
|
||||||
const ctaText = hasProgress ? '📖 继续阅读' : '📖 开始阅读'
|
|
||||||
const ctaHint = hasProgress
|
|
||||||
? progress?.updatedAt
|
|
||||||
? `上次翻到 · ${formatAgo(progress.updatedAt)}`
|
|
||||||
: '接着上次的地方'
|
|
||||||
: isFree
|
|
||||||
? '点一下,直接进入正文'
|
|
||||||
: '先翻开前面的章节'
|
|
||||||
|
|
||||||
const displayTitle = audit.reviewMode
|
|
||||||
? book.title || '数字游民入门指南'
|
|
||||||
: COVER_BOOK.title
|
|
||||||
const tagParts = [
|
|
||||||
audit.reviewMode
|
|
||||||
? book.subtitle || '远程办公 · 自律生活 · 稳健成长'
|
|
||||||
: book.subtitle || COVER_BOOK.subtitle || '低成本工作室',
|
|
||||||
]
|
|
||||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
|
||||||
const safeStyle = useMemo(
|
|
||||||
() => ({
|
|
||||||
['--safe-status-bar' as string]: `${safe.statusBarHeight}px`,
|
|
||||||
['--safe-nav-bar' as string]: `${safe.navBarHeight}px`,
|
|
||||||
['--safe-menu-pad' as string]: `${safe.menuRightPad}px`,
|
|
||||||
['--safe-header' as string]: `${safe.headerHeight}px`,
|
|
||||||
}),
|
|
||||||
[safe],
|
|
||||||
)
|
|
||||||
|
|
||||||
|
export default function BookPage() {
|
||||||
return (
|
return (
|
||||||
<H5Box
|
<View style={box}>
|
||||||
className="page-shell home-flow home-flow--hero-only book-flow"
|
<Text style={h1}>数字游民入门指南</Text>
|
||||||
data-theme={theme}
|
<Text style={sub}>远程办公 · 自律生活 · 稳健成长</Text>
|
||||||
style={safeStyle}
|
|
||||||
>
|
|
||||||
<CommunityNavbar />
|
|
||||||
|
|
||||||
<H5Box className="hero" id="hero">
|
<Text style={h2}>1. 写在前面</Text>
|
||||||
<H5Box className="hero-bg-shapes" aria-hidden>
|
<Text style={p}>欢迎阅读《数字游民入门指南》。</Text>
|
||||||
<H5Box className="shape shape-1" />
|
<Text style={p}>
|
||||||
<H5Box className="shape shape-2" />
|
这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。
|
||||||
<H5Box className="shape shape-3" />
|
</Text>
|
||||||
</H5Box>
|
<Text style={p}>
|
||||||
|
你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。
|
||||||
|
</Text>
|
||||||
|
|
||||||
<H5Box className="hero-inner">
|
<Text style={h2}>2. 什么是数字游民</Text>
|
||||||
<H5Box className="hero-top">
|
<Text style={p}>
|
||||||
<H5Box className="hero-content">
|
「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。
|
||||||
<H5Box className="hero-title book-hero-title">
|
</Text>
|
||||||
<H5Txt className="hero-title-line book-title-brand">{displayTitle}</H5Txt>
|
<Text style={p}>
|
||||||
<H5Box className="hero-title-line book-tagline">
|
它不是逃避现实。更常见的状态是:工作目标清晰、沟通及时、作息稳定、遵守公司制度与当地法律法规。
|
||||||
<H5Txt>{tagParts[0]}</H5Txt>
|
</Text>
|
||||||
</H5Box>
|
<Text style={p}>
|
||||||
</H5Box>
|
对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。
|
||||||
|
</Text>
|
||||||
|
|
||||||
<H5Txt className="hero-title-spark" aria-hidden>
|
<Text style={h2}>3. 远程办公的基本功</Text>
|
||||||
✨
|
<Text style={p}>远程办公的核心不是换风景,而是换一种可协作的工作方式。</Text>
|
||||||
</H5Txt>
|
<Text style={p}>建议每天有固定核心工作时间,并告诉同事哪些时段适合会议、哪些时段专注深度工作。</Text>
|
||||||
|
<Text style={p}>每天开工前列三件必须完成的事;每周五花十五分钟复盘完成项与卡点。</Text>
|
||||||
|
<Text style={p}>工具只保留必要的。开会前写清目的,会后写清结论:谁负责、做什么、何时完成。</Text>
|
||||||
|
|
||||||
<H5Txt className="hero-subtitle book-typewriter">
|
<Text style={h2}>4. 居家与旅居的工作环境</Text>
|
||||||
{tw}
|
<Text style={p}>环境会直接影响专注力。不必追求豪华,但要够用、安静、可持续。</Text>
|
||||||
<H5Txt className="typewriter-cursor">|</H5Txt>
|
<Text style={p}>居家建议:稳定桌椅与屏幕高度、充足光线、耳机、备用电源,以及减少打扰的约定。</Text>
|
||||||
</H5Txt>
|
<Text style={p}>若允许短期异地办公,优先网络稳定、住宿安静、餐饮运动方便、交通可预期。</Text>
|
||||||
</H5Box>
|
|
||||||
|
|
||||||
<H5Box className="hero-visual" onClick={goRead}>
|
<Text style={h2}>5. 时间管理</Text>
|
||||||
<H5Box className="book-visual">
|
<Text style={p}>灵活工作最大的风险是时间碎、注意力散、任务拖。</Text>
|
||||||
{isH5 ? (
|
<Text style={p}>可用简化番茄法:25 分钟专注一件事,休息 5 分钟;深度工作时关闭无关通知。</Text>
|
||||||
<H5Box className="book-visual-host" html={BOOK_VISUAL_SVG} />
|
<Text style={p}>建议每天至少留 90 分钟不被会议打断的时间,用来做深度工作。</Text>
|
||||||
) : (
|
|
||||||
<H5Box className="book-visual-css" aria-hidden>
|
|
||||||
<H5Box className="book-visual-css-glow" />
|
|
||||||
<H5Box className="book-visual-css-body">
|
|
||||||
<H5Box className="book-visual-css-spine" />
|
|
||||||
<H5Txt className="book-visual-css-emoji">📖</H5Txt>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
)}
|
|
||||||
<H5Box className="book-float-chips social-float-chips">
|
|
||||||
{CHIP_TAGS.map((tag, i) => (
|
|
||||||
<H5Box key={tag} className={`social-chip sc-${i + 1}`}>
|
|
||||||
<H5Txt>
|
|
||||||
{i === 0 ? '🏷 ' : i === 1 ? '⚡ ' : '🌐 '}
|
|
||||||
{tag}
|
|
||||||
</H5Txt>
|
|
||||||
</H5Box>
|
|
||||||
))}
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
|
|
||||||
<H5Box className="hero-bottom">
|
<Text style={h2}>6. 沟通与团队协作</Text>
|
||||||
<H5Box className="hero-actions book-actions">
|
<Text style={p}>远程场景里,沟通质量几乎等于工作质量。</Text>
|
||||||
<Button className="btn btn-primary book-cta" onClick={goRead}>
|
<Text style={p}>同步信息:默认公开、结论先行、可执行(下一步、负责人、时间)。</Text>
|
||||||
{ctaText}
|
<Text style={p}>远程信任来自稳定交付:承诺按时完成,延期提前说明,问题主动暴露。</Text>
|
||||||
</Button>
|
|
||||||
<H5Txt className="book-cta-hint">{ctaHint}</H5Txt>
|
<Text style={h2}>7. 健康、作息与心态</Text>
|
||||||
</H5Box>
|
<Text style={p}>尽量固定睡眠与起床时间;每工作一小时起身活动两分钟;中午真正休息。</Text>
|
||||||
</H5Box>
|
<Text style={p}>运动不必复杂:散步、拉伸即可,关键是每周能坚持。</Text>
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
<Text style={h2}>8. 学习成长与职业规划</Text>
|
||||||
</H5Box>
|
<Text style={p}>真正护城河仍是能力与口碑:专业技能、表达能力、项目管理。</Text>
|
||||||
|
<Text style={p}>请遵守劳动合同、信息安全与所在地法律法规。稳健发展,才能走得长远。</Text>
|
||||||
|
|
||||||
|
<Text style={h2}>9. 七天起步计划</Text>
|
||||||
|
<Text style={p}>第1天整理工位;第2天三个每日目标;第3天文档归位;第4天练习结论先行;第5天短复盘;第6天轻度运动;第7天只改一件事。</Text>
|
||||||
|
|
||||||
|
<Text style={h2}>10. 结语</Text>
|
||||||
|
<Text style={p}>
|
||||||
|
先把远程协作做好,把身体照顾好,把专业能力垒扎实。祝你工作顺利,生活安定,步履从容。
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function BookPage() {
|
|
||||||
usePageShare({ title: 'nomadro · 数字游民小册', path: '/pages/book/index' })
|
|
||||||
return (
|
|
||||||
<MiniModuleGate moduleKey="book">
|
|
||||||
<BookPageInner />
|
|
||||||
</MiniModuleGate>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default markPageShare(BookPage)
|
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
|
|||||||
import { View, Text } from '@tarojs/components'
|
import { View, Text } from '@tarojs/components'
|
||||||
import Taro, { useDidShow, usePageScroll } from '@tarojs/taro'
|
import Taro, { useDidShow, usePageScroll } from '@tarojs/taro'
|
||||||
import {
|
import {
|
||||||
|
getCachedRemoteConfig,
|
||||||
isModuleEnabled,
|
isModuleEnabled,
|
||||||
loadRemoteConfig,
|
loadRemoteConfig,
|
||||||
subscribeRemoteConfig,
|
subscribeRemoteConfig,
|
||||||
@ -137,6 +138,7 @@ function Box({
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// 微信禁止 View + dangerouslySetInnerHTML(会 wx://not-found 黑屏)
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
id={id}
|
id={id}
|
||||||
@ -144,9 +146,8 @@ function Box({
|
|||||||
style={style}
|
style={style}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
data-theme={dataTheme}
|
data-theme={dataTheme}
|
||||||
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
|
|
||||||
>
|
>
|
||||||
{html ? undefined : children}
|
{children}
|
||||||
</View>
|
</View>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -160,7 +161,8 @@ function IndexPage() {
|
|||||||
usePageTrack('pages/home/index', '首页')
|
usePageTrack('pages/home/index', '首页')
|
||||||
usePageShare({ title: 'nomadro · 随处工作,自由生活', path: '/pages/home/index' })
|
usePageShare({ title: 'nomadro · 随处工作,自由生活', path: '/pages/home/index' })
|
||||||
|
|
||||||
const [config, setConfig] = useState<NomadroRemoteConfig | null>(null)
|
// 首屏用包内/缓存配置,禁止等网络才出入口(否则审核看到空首页像黑屏)
|
||||||
|
const [config, setConfig] = useState<NomadroRemoteConfig>(() => getCachedRemoteConfig())
|
||||||
const theme = useNomadroTheme()
|
const theme = useNomadroTheme()
|
||||||
const [navScrolled, setNavScrolled] = useState(false)
|
const [navScrolled, setNavScrolled] = useState(false)
|
||||||
|
|
||||||
@ -284,9 +286,8 @@ function IndexPage() {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const cfg = config
|
const cfg = config
|
||||||
// 配置未就绪:一个入口都不渲染,避免「先闪后藏」被审核盯上
|
const portals = PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey))
|
||||||
const portals = cfg ? PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey)) : []
|
const brand = cfg.copy.homeBrand || 'nomadro'
|
||||||
const brand = cfg?.copy.homeBrand || 'nomadro'
|
|
||||||
const safe = useSafeAreaMetrics()
|
const safe = useSafeAreaMetrics()
|
||||||
const rootSafeStyle = {
|
const rootSafeStyle = {
|
||||||
// CSS 变量用小写 px(样式表已排除 rpx 转换);内联尺寸必须用 safePx
|
// CSS 变量用小写 px(样式表已排除 rpx 转换);内联尺寸必须用 safePx
|
||||||
@ -416,7 +417,7 @@ function IndexPage() {
|
|||||||
<Txt>{portal.emoji}</Txt>
|
<Txt>{portal.emoji}</Txt>
|
||||||
</Box>
|
</Box>
|
||||||
<Txt className="hub-portal-name">
|
<Txt className="hub-portal-name">
|
||||||
{cfg?.modules[portal.moduleKey]?.title || portal.name}
|
{cfg.modules[portal.moduleKey]?.title || portal.name}
|
||||||
</Txt>
|
</Txt>
|
||||||
</Box>
|
</Box>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -9,10 +9,13 @@ import {
|
|||||||
accessFingerprint,
|
accessFingerprint,
|
||||||
fetchAccess,
|
fetchAccess,
|
||||||
fetchRead,
|
fetchRead,
|
||||||
|
getAuditOfflineRead,
|
||||||
|
isAuditBookId,
|
||||||
pollUnlock,
|
pollUnlock,
|
||||||
type ReadPayload,
|
type ReadPayload,
|
||||||
} from '../../services/ebookApi'
|
} from '../../services/ebookApi'
|
||||||
import { MarkdownView } from '../../components/MarkdownView'
|
import { MarkdownView } from '../../components/MarkdownView'
|
||||||
|
import { AuditPlainBody } from '../../components/AuditPlainBody'
|
||||||
import { PayResultSheet } from '../../components/PayResultSheet'
|
import { PayResultSheet } from '../../components/PayResultSheet'
|
||||||
import { ReaderSettings } from '../../components/ReaderSettings'
|
import { ReaderSettings } from '../../components/ReaderSettings'
|
||||||
import { runUnlockPayment } from '../../utils/payFlow'
|
import { runUnlockPayment } from '../../utils/payFlow'
|
||||||
@ -53,7 +56,10 @@ function ReaderPage() {
|
|||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const bookId = router.params.id || 'default'
|
const bookId = router.params.id || 'default'
|
||||||
const chapterParam = router.params.chapter || ''
|
const chapterParam = router.params.chapter || ''
|
||||||
const [data, setData] = useState<ReadPayload | null>(null)
|
// 提审书:首帧就有正文,避免 showLoading + 空壳黑屏
|
||||||
|
const [data, setData] = useState<ReadPayload | null>(() =>
|
||||||
|
isAuditBookId(bookId) ? getAuditOfflineRead(bookId) : null,
|
||||||
|
)
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||||
const [tocFilter, setTocFilter] = useState('')
|
const [tocFilter, setTocFilter] = useState('')
|
||||||
@ -137,25 +143,37 @@ function ReaderPage() {
|
|||||||
}, [bookId])
|
}, [bookId])
|
||||||
|
|
||||||
async function load(silent = false) {
|
async function load(silent = false) {
|
||||||
|
const auditBook = isAuditBookId(bookId)
|
||||||
try {
|
try {
|
||||||
if (!silent) Taro.showLoading({ title: '打开中' })
|
// 提审:已有离线首屏,不再弹「打开中」遮罩
|
||||||
|
if (!silent && !auditBook) Taro.showLoading({ title: '打开中' })
|
||||||
|
if (auditBook) {
|
||||||
|
loadedRef.current = true
|
||||||
|
}
|
||||||
const res = await fetchRead(bookId)
|
const res = await fetchRead(bookId)
|
||||||
setData(res)
|
setData(res)
|
||||||
accessFpRef.current = accessFingerprint(res)
|
accessFpRef.current = accessFingerprint(res)
|
||||||
loadedRef.current = true
|
loadedRef.current = true
|
||||||
if (!silent) {
|
if (!silent && !auditBook) {
|
||||||
setActiveChapter(0)
|
setActiveChapter(0)
|
||||||
setProgress(0)
|
setProgress(0)
|
||||||
restored.current = false
|
restored.current = false
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (!silent) Taro.showToast({ title: e.message || '加载失败', icon: 'none' })
|
if (auditBook) {
|
||||||
|
setData(getAuditOfflineRead(bookId))
|
||||||
|
loadedRef.current = true
|
||||||
|
} else if (!silent) {
|
||||||
|
Taro.showToast({ title: e.message || '加载失败', icon: 'none' })
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!silent) Taro.hideLoading()
|
if (!silent && !auditBook) Taro.hideLoading()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function syncAccess() {
|
async function syncAccess() {
|
||||||
|
// 提审书不探 VIP/权限,避免 401 连环
|
||||||
|
if (isAuditBookId(bookId)) return
|
||||||
if (!loadedRef.current || syncingRef.current || isH5) return
|
if (!loadedRef.current || syncingRef.current || isH5) return
|
||||||
syncingRef.current = true
|
syncingRef.current = true
|
||||||
try {
|
try {
|
||||||
@ -757,12 +775,16 @@ function ReaderPage() {
|
|||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View className="md-wrap">
|
<View className="md-wrap">
|
||||||
<MarkdownView
|
{isAuditBookId(bookId) ? (
|
||||||
markdown={c.content || ''}
|
<AuditPlainBody markdown={c.content || ''} />
|
||||||
prefs={prefs}
|
) : (
|
||||||
dropCap
|
<MarkdownView
|
||||||
onImageLayout={onImageLayout}
|
markdown={c.content || ''}
|
||||||
/>
|
prefs={prefs}
|
||||||
|
dropCap
|
||||||
|
onImageLayout={onImageLayout}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{next ? (
|
{next ? (
|
||||||
|
|||||||
@ -110,7 +110,8 @@ export default function VipEbookPage() {
|
|||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
const audit = resolveBookAudit(getCachedRemoteConfig())
|
const audit = resolveBookAudit(getCachedRemoteConfig())
|
||||||
if (audit.reviewMode) {
|
if (audit.reviewMode) {
|
||||||
const url = `/pages/reader/index?id=${encodeURIComponent(audit.bookId || 'audit')}`
|
// 提审正文在小册页内联,勿跳 reader 分包
|
||||||
|
const url = '/pages/book/index'
|
||||||
await Taro.redirectTo({ url }).catch(() => goPage(url))
|
await Taro.redirectTo({ url }).catch(() => goPage(url))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -160,7 +161,7 @@ export default function VipEbookPage() {
|
|||||||
return subscribeRemoteConfig((r) => {
|
return subscribeRemoteConfig((r) => {
|
||||||
const audit = resolveBookAudit(r.config)
|
const audit = resolveBookAudit(r.config)
|
||||||
if (!audit.reviewMode) return
|
if (!audit.reviewMode) return
|
||||||
const url = `/pages/reader/index?id=${encodeURIComponent(audit.bookId || 'audit')}`
|
const url = '/pages/book/index'
|
||||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
||||||
})
|
})
|
||||||
}, [bookId])
|
}, [bookId])
|
||||||
|
|||||||
@ -475,7 +475,14 @@ function VipLanding() {
|
|||||||
<H5Box className="vip-root" data-theme={theme} style={safeStyle}>
|
<H5Box className="vip-root" data-theme={theme} style={safeStyle}>
|
||||||
<H5Box className="vip-header">
|
<H5Box className="vip-header">
|
||||||
<H5Box className="vip-logo" onClick={goHome} aria-label="返回首页">
|
<H5Box className="vip-logo" onClick={goHome} aria-label="返回首页">
|
||||||
<H5Box html={LOGO_SVG} />
|
{process.env.TARO_ENV === 'h5' ? (
|
||||||
|
<H5Box html={LOGO_SVG} />
|
||||||
|
) : (
|
||||||
|
<H5Box className="hub-logo-mark" aria-hidden>
|
||||||
|
<H5Box className="hub-logo-mark-ring" />
|
||||||
|
<H5Box className="hub-logo-mark-dot" />
|
||||||
|
</H5Box>
|
||||||
|
)}
|
||||||
<H5Txt className="vip-logoBrand">{brand}</H5Txt>
|
<H5Txt className="vip-logoBrand">{brand}</H5Txt>
|
||||||
<H5Txt className="vip-logoSep">·</H5Txt>
|
<H5Txt className="vip-logoSep">·</H5Txt>
|
||||||
<H5Txt className="vip-logoVip">VIP</H5Txt>
|
<H5Txt className="vip-logoVip">VIP</H5Txt>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import Taro from '@tarojs/taro'
|
import Taro from '@tarojs/taro'
|
||||||
import { checkIosPayReady, ensureLogin, request } from '../utils/request'
|
import { checkIosPayReady, ensureLogin, request } from '../utils/request'
|
||||||
import { OFFLINE_BOOK, offlineReadPayload } from '../data/offlineBook'
|
import { OFFLINE_BOOK, offlineReadPayload } from '../data/offlineBook'
|
||||||
|
import { AUDIT_BOOK_CHAPTERS, AUDIT_BOOK_META } from '../data/auditBook'
|
||||||
|
|
||||||
export type ChapterMeta = {
|
export type ChapterMeta = {
|
||||||
id: string
|
id: string
|
||||||
@ -55,29 +56,35 @@ export type AccessSnapshot = {
|
|||||||
updated_at: number
|
updated_at: number
|
||||||
}
|
}
|
||||||
|
|
||||||
function isAuditBookId(bookId: string) {
|
export function isAuditBookId(bookId: string) {
|
||||||
const id = (bookId || '').trim()
|
const id = (bookId || '').trim()
|
||||||
return id === 'audit' || id.startsWith('audit')
|
return id === 'audit' || id.startsWith('audit')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 提审书绝不能回退到正式离线包 */
|
/** 提审离线正文:阅读页可立刻渲染,避免「打开中」黑屏感 */
|
||||||
|
export function getAuditOfflineRead(bookId = 'audit'): ReadPayload {
|
||||||
|
return auditOfflineRead(bookId || 'audit')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 提审书绝不能回退到正式离线包 —— 正文与 audit_book_seed.md 对齐 */
|
||||||
function auditOfflineBook(bookId: string): BookDetail {
|
function auditOfflineBook(bookId: string): BookDetail {
|
||||||
|
const wordCount = AUDIT_BOOK_CHAPTERS.reduce((n, c) => n + (c.content?.length || 0), 0)
|
||||||
return {
|
return {
|
||||||
id: bookId || 'audit',
|
id: bookId || AUDIT_BOOK_META.id,
|
||||||
title: '数字游民入门指南',
|
title: AUDIT_BOOK_META.title,
|
||||||
subtitle: '远程办公 · 自律生活 · 稳健成长',
|
subtitle: AUDIT_BOOK_META.subtitle,
|
||||||
author: '',
|
author: '',
|
||||||
cover_emoji: '📗',
|
cover_emoji: AUDIT_BOOK_META.cover_emoji,
|
||||||
description: '面向普通人的远程办公与生活方式入门读本。',
|
description: AUDIT_BOOK_META.description,
|
||||||
tags: ['数字游民', '远程办公'],
|
tags: [...AUDIT_BOOK_META.tags],
|
||||||
price_fen: 0,
|
price_fen: 0,
|
||||||
product_id: '',
|
product_id: '',
|
||||||
unlock_percent: 100,
|
unlock_percent: 100,
|
||||||
is_free: true,
|
is_free: true,
|
||||||
chapter_count: 1,
|
chapter_count: AUDIT_BOOK_CHAPTERS.length,
|
||||||
word_count: 0,
|
word_count: wordCount,
|
||||||
rating: 5,
|
rating: 5,
|
||||||
chapters: [{ id: '01-audit', title: '写在前面', order: 1 }],
|
chapters: AUDIT_BOOK_CHAPTERS.map(({ id, title, order }) => ({ id, title, order })),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,15 +92,12 @@ function auditOfflineRead(bookId: string): ReadPayload {
|
|||||||
const book = auditOfflineBook(bookId)
|
const book = auditOfflineBook(bookId)
|
||||||
return {
|
return {
|
||||||
book,
|
book,
|
||||||
chapters: [
|
chapters: AUDIT_BOOK_CHAPTERS.map((c) => ({
|
||||||
{
|
id: c.id,
|
||||||
id: '01-audit',
|
title: c.title,
|
||||||
title: '写在前面',
|
order: c.order,
|
||||||
order: 1,
|
content: c.content,
|
||||||
content:
|
})),
|
||||||
'# 写在前面\n\n欢迎阅读《数字游民入门指南》。\n\n这是一本面向普通人的远程办公与自律生活入门读本。\n',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
unlocked: true,
|
unlocked: true,
|
||||||
is_free: true,
|
is_free: true,
|
||||||
unlock_percent: 100,
|
unlock_percent: 100,
|
||||||
@ -113,14 +117,27 @@ function auditOfflineRead(bookId: string): ReadPayload {
|
|||||||
|
|
||||||
export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
||||||
const id = bookId || 'default'
|
const id = bookId || 'default'
|
||||||
// H5:正式书用离线包;提审书必须打 API,失败也不回正式包
|
// H5:正式书用离线包;提审书离线优先,失败也不回正式包
|
||||||
if (process.env.TARO_ENV === 'h5' && !isAuditBookId(id)) {
|
if (process.env.TARO_ENV === 'h5' && !isAuditBookId(id)) {
|
||||||
return { ...OFFLINE_BOOK, id }
|
return { ...OFFLINE_BOOK, id }
|
||||||
}
|
}
|
||||||
|
if (isAuditBookId(id)) {
|
||||||
|
const offline = auditOfflineBook(id)
|
||||||
|
try {
|
||||||
|
const remote = await request<BookDetail>({
|
||||||
|
url: `/api/ebook/books/${id}?_=${Date.now()}`,
|
||||||
|
// 提审书匿名可读:401 不触发清 token + 重登
|
||||||
|
_retried: true,
|
||||||
|
})
|
||||||
|
if (remote && (remote.chapter_count || remote.chapters?.length)) return remote
|
||||||
|
} catch {
|
||||||
|
/* keep offline */
|
||||||
|
}
|
||||||
|
return offline
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` })
|
return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` })
|
||||||
} catch {
|
} catch {
|
||||||
if (isAuditBookId(id)) return auditOfflineBook(id)
|
|
||||||
return { ...OFFLINE_BOOK, id }
|
return { ...OFFLINE_BOOK, id }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,6 +149,25 @@ export async function fetchRead(bookId = 'default'): Promise<ReadPayload> {
|
|||||||
payload.book = { ...payload.book, id }
|
payload.book = { ...payload.book, id }
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
// 提审书:离线优先(包内 10 章),有网再覆盖;空响应不覆盖,避免黑屏
|
||||||
|
if (isAuditBookId(id)) {
|
||||||
|
const offline = auditOfflineRead(id)
|
||||||
|
try {
|
||||||
|
const remote = await request<ReadPayload>({
|
||||||
|
url: `/api/ebook/books/${id}/read?_=${Date.now()}`,
|
||||||
|
_retried: true,
|
||||||
|
})
|
||||||
|
// 必须有实质正文才覆盖离线,避免空 content 把页面「读成」黑屏
|
||||||
|
const remoteChapters = Array.isArray(remote?.chapters) ? remote.chapters : []
|
||||||
|
const withBody = remoteChapters.filter((c) => String(c?.content || '').trim().length > 20)
|
||||||
|
if (withBody.length > 0) {
|
||||||
|
return { ...remote, chapters: withBody }
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* keep offline */
|
||||||
|
}
|
||||||
|
return offline
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
if (process.env.TARO_ENV !== 'h5') {
|
if (process.env.TARO_ENV !== 'h5') {
|
||||||
await ensureLogin()
|
await ensureLogin()
|
||||||
@ -141,7 +177,6 @@ export async function fetchRead(bookId = 'default'): Promise<ReadPayload> {
|
|||||||
try {
|
try {
|
||||||
return await request({ url: `/api/ebook/books/${id}/read?_=${Date.now()}` })
|
return await request({ url: `/api/ebook/books/${id}/read?_=${Date.now()}` })
|
||||||
} catch {
|
} catch {
|
||||||
if (isAuditBookId(id)) return auditOfflineRead(id)
|
|
||||||
const payload = offlineReadPayload()
|
const payload = offlineReadPayload()
|
||||||
payload.book = { ...payload.book, id }
|
payload.book = { ...payload.book, id }
|
||||||
return payload
|
return payload
|
||||||
|
|||||||
@ -6,7 +6,8 @@ import {
|
|||||||
type NomadroRemoteConfig,
|
type NomadroRemoteConfig,
|
||||||
} from '../data/remoteConfig.defaults'
|
} from '../data/remoteConfig.defaults'
|
||||||
|
|
||||||
const STORAGE_KEY = 'nomadro_remote_config_v1'
|
/** v2:作废旧缓存里 bookAudit.reviewMode=false 的种子,提审首屏走包内默认 true */
|
||||||
|
const STORAGE_KEY = 'nomadro_remote_config_v2'
|
||||||
const CACHE_TTL_MS = 1000 * 60 * 30
|
const CACHE_TTL_MS = 1000 * 60 * 30
|
||||||
/** 小程序无 EventSource:meta 轮询间隔(近实时) */
|
/** 小程序无 EventSource:meta 轮询间隔(近实时) */
|
||||||
const META_POLL_MS = 3000
|
const META_POLL_MS = 3000
|
||||||
|
|||||||
@ -1,18 +1,23 @@
|
|||||||
import Taro from '@tarojs/taro'
|
import Taro from '@tarojs/taro'
|
||||||
import { ensureLogin, requestEbook } from './request'
|
import { ensureLogin, requestEbook } from './request'
|
||||||
import { applyServerVipFlag } from './vipAccess'
|
import { applyServerVipFlag } from './vipAccess'
|
||||||
|
import { getCachedRemoteConfig } from '../services/remoteConfig'
|
||||||
|
import { resolveBookAudit } from '../data/remoteConfig.defaults'
|
||||||
|
|
||||||
const INTERVAL_MS = 25_000
|
const INTERVAL_MS = 25_000
|
||||||
let timer: ReturnType<typeof setInterval> | null = null
|
let timer: ReturnType<typeof setInterval> | null = null
|
||||||
let started = false
|
let started = false
|
||||||
|
|
||||||
async function ping(): Promise<void> {
|
async function ping(): Promise<void> {
|
||||||
|
// 提审:不登录、不上报,避免 wx.login / 401 干扰审核路径
|
||||||
|
if (resolveBookAudit(getCachedRemoteConfig()).reviewMode) return
|
||||||
try {
|
try {
|
||||||
await ensureLogin(false)
|
await ensureLogin(false)
|
||||||
const data = await requestEbook<{ isVip?: boolean }>({
|
const data = await requestEbook<{ isVip?: boolean }>({
|
||||||
url: '/api/ebook/auth/presence',
|
url: '/api/ebook/auth/presence',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data: {},
|
data: {},
|
||||||
|
_retried: true,
|
||||||
})
|
})
|
||||||
if (typeof data?.isVip === 'boolean') {
|
if (typeof data?.isVip === 'boolean') {
|
||||||
applyServerVipFlag(data.isVip)
|
applyServerVipFlag(data.isVip)
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import {
|
|||||||
getCachedRemoteConfig,
|
getCachedRemoteConfig,
|
||||||
loadRemoteConfig,
|
loadRemoteConfig,
|
||||||
} from '../services/remoteConfig'
|
} from '../services/remoteConfig'
|
||||||
|
import { resolveBookAudit } from '../data/remoteConfig.defaults'
|
||||||
|
|
||||||
const LOCAL_PAID_KEY = 'nomadro_vip_paid'
|
const LOCAL_PAID_KEY = 'nomadro_vip_paid'
|
||||||
/** 与 remote-config meta / memo revision 同级:近实时探 VIP 准入 */
|
/** 与 remote-config meta / memo revision 同级:近实时探 VIP 准入 */
|
||||||
@ -132,6 +133,12 @@ export async function resolveVipAccess(forceRefresh = false): Promise<boolean> {
|
|||||||
/* use cache */
|
/* use cache */
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 提审模式:不探 vip-status / 不 ensureLogin,避免控制台 401 连环与冷启动卡顿
|
||||||
|
if (resolveBookAudit(getCachedRemoteConfig()).reviewMode) {
|
||||||
|
emitVip(false)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await ensureLogin(false)
|
await ensureLogin(false)
|
||||||
} catch {
|
} catch {
|
||||||
@ -149,6 +156,8 @@ export async function resolveVipAccess(forceRefresh = false): Promise<boolean> {
|
|||||||
const data = await requestEbook<{ isVip?: boolean }>({
|
const data = await requestEbook<{ isVip?: boolean }>({
|
||||||
url: '/api/ebook/pay/vip-status',
|
url: '/api/ebook/pay/vip-status',
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
|
// 旁路探活:401 不触发清 token + 强制重登(避免审核/冷启动连环 401)
|
||||||
|
_retried: true,
|
||||||
})
|
})
|
||||||
const vip = !!data?.isVip
|
const vip = !!data?.isVip
|
||||||
emitVip(vip)
|
emitVip(vip)
|
||||||
|
|||||||
1
apps/miniprogram/weapp-audit/app.js
Normal file
1
apps/miniprogram/weapp-audit/app.js
Normal file
@ -0,0 +1 @@
|
|||||||
|
App({})
|
||||||
10
apps/miniprogram/weapp-audit/app.json
Normal file
10
apps/miniprogram/weapp-audit/app.json
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"pages": ["pages/book/index"],
|
||||||
|
"window": {
|
||||||
|
"navigationBarTitleText": "数字游民入门指南",
|
||||||
|
"navigationBarBackgroundColor": "#0c0b12",
|
||||||
|
"navigationBarTextStyle": "white",
|
||||||
|
"backgroundColor": "#0c0b12",
|
||||||
|
"backgroundTextStyle": "light"
|
||||||
|
}
|
||||||
|
}
|
||||||
5
apps/miniprogram/weapp-audit/app.wxss
Normal file
5
apps/miniprogram/weapp-audit/app.wxss
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
page {
|
||||||
|
background: #0c0b12;
|
||||||
|
color: #f8fafc;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
4
apps/miniprogram/weapp-audit/pages/book/index.js
Normal file
4
apps/miniprogram/weapp-audit/pages/book/index.js
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
/** 提审小册:纯原生页,不经过 Taro/React */
|
||||||
|
Page({
|
||||||
|
data: {},
|
||||||
|
})
|
||||||
7
apps/miniprogram/weapp-audit/pages/book/index.json
Normal file
7
apps/miniprogram/weapp-audit/pages/book/index.json
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"navigationBarTitleText": "数字游民入门指南",
|
||||||
|
"navigationBarBackgroundColor": "#0c0b12",
|
||||||
|
"navigationBarTextStyle": "white",
|
||||||
|
"backgroundColor": "#0c0b12",
|
||||||
|
"navigationStyle": "default"
|
||||||
|
}
|
||||||
52
apps/miniprogram/weapp-audit/pages/book/index.wxml
Normal file
52
apps/miniprogram/weapp-audit/pages/book/index.wxml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<scroll-view scroll-y class="page" style="height:100vh;">
|
||||||
|
<view class="pad">
|
||||||
|
<text class="emoji">📗</text>
|
||||||
|
<text class="title">数字游民入门指南</text>
|
||||||
|
<text class="sub">远程办公 · 自律生活 · 稳健成长</text>
|
||||||
|
|
||||||
|
<text class="h">1. 写在前面</text>
|
||||||
|
<text class="p">欢迎阅读《数字游民入门指南》。</text>
|
||||||
|
<text class="p">这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。</text>
|
||||||
|
<text class="p">你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。</text>
|
||||||
|
|
||||||
|
<text class="h">2. 什么是数字游民</text>
|
||||||
|
<text class="p">「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。</text>
|
||||||
|
<text class="p">它不是逃避现实。更常见的状态是:工作目标清晰、沟通及时、作息稳定、遵守公司制度与当地法律法规。</text>
|
||||||
|
<text class="p">对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。</text>
|
||||||
|
|
||||||
|
<text class="h">3. 远程办公的基本功</text>
|
||||||
|
<text class="p">远程办公的核心不是换风景,而是换一种可协作的工作方式。</text>
|
||||||
|
<text class="p">建议每天有固定核心工作时间,并告诉同事哪些时段适合会议、哪些时段专注深度工作。</text>
|
||||||
|
<text class="p">每天开工前列三件必须完成的事;每周五花十五分钟复盘完成项与卡点。</text>
|
||||||
|
<text class="p">工具只保留必要的。开会前写清目的,会后写清结论:谁负责、做什么、何时完成。</text>
|
||||||
|
|
||||||
|
<text class="h">4. 居家与旅居的工作环境</text>
|
||||||
|
<text class="p">环境会直接影响专注力。不必追求豪华,但要够用、安静、可持续。</text>
|
||||||
|
<text class="p">居家建议:稳定桌椅与屏幕高度、充足光线、耳机、备用电源,以及减少打扰的约定。</text>
|
||||||
|
<text class="p">若允许短期异地办公,优先网络稳定、住宿安静、餐饮运动方便、交通可预期。</text>
|
||||||
|
|
||||||
|
<text class="h">5. 时间管理</text>
|
||||||
|
<text class="p">灵活工作最大的风险是时间碎、注意力散、任务拖。</text>
|
||||||
|
<text class="p">可用简化番茄法:25 分钟专注一件事,休息 5 分钟;深度工作时关闭无关通知。</text>
|
||||||
|
<text class="p">建议每天至少留 90 分钟不被会议打断的时间,用来做深度工作。</text>
|
||||||
|
|
||||||
|
<text class="h">6. 沟通与团队协作</text>
|
||||||
|
<text class="p">远程场景里,沟通质量几乎等于工作质量。</text>
|
||||||
|
<text class="p">同步信息:默认公开、结论先行、可执行(下一步、负责人、时间)。</text>
|
||||||
|
<text class="p">远程信任来自稳定交付:承诺按时完成,延期提前说明,问题主动暴露。</text>
|
||||||
|
|
||||||
|
<text class="h">7. 健康、作息与心态</text>
|
||||||
|
<text class="p">尽量固定睡眠与起床时间;每工作一小时起身活动两分钟;中午真正休息。</text>
|
||||||
|
<text class="p">运动不必复杂:散步、拉伸即可,关键是每周能坚持。</text>
|
||||||
|
|
||||||
|
<text class="h">8. 学习成长与职业规划</text>
|
||||||
|
<text class="p">真正护城河仍是能力与口碑:专业技能、表达能力、项目管理。</text>
|
||||||
|
<text class="p">请遵守劳动合同、信息安全与所在地法律法规。稳健发展,才能走得长远。</text>
|
||||||
|
|
||||||
|
<text class="h">9. 七天起步计划</text>
|
||||||
|
<text class="p">第1天整理工位;第2天三个每日目标;第3天文档归位;第4天练习结论先行;第5天短复盘;第6天轻度运动;第7天只改一件事。</text>
|
||||||
|
|
||||||
|
<text class="h">10. 结语</text>
|
||||||
|
<text class="p">先把远程协作做好,把身体照顾好,把专业能力垒扎实。祝你工作顺利,生活安定,步履从容。</text>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
54
apps/miniprogram/weapp-audit/pages/book/index.wxss
Normal file
54
apps/miniprogram/weapp-audit/pages/book/index.wxss
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
.page {
|
||||||
|
background: #0c0b12;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pad {
|
||||||
|
padding: 20px 16px 48px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji,
|
||||||
|
.title,
|
||||||
|
.sub,
|
||||||
|
.h,
|
||||||
|
.p {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji {
|
||||||
|
font-size: 28px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
font-size: 22px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #f8fafc;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sub {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #94a3b8;
|
||||||
|
line-height: 1.45;
|
||||||
|
margin: 8px 0 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.h {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #e2e8f0;
|
||||||
|
line-height: 1.4;
|
||||||
|
margin: 20px 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.p {
|
||||||
|
font-size: 15px;
|
||||||
|
color: #cbd5e1;
|
||||||
|
line-height: 1.75;
|
||||||
|
margin: 0 0 8px;
|
||||||
|
}
|
||||||
17
apps/miniprogram/weapp-audit/project.config.json
Normal file
17
apps/miniprogram/weapp-audit/project.config.json
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"description": "Nomadro 提审专用:纯原生小册(无 Taro)",
|
||||||
|
"packOptions": {
|
||||||
|
"ignore": [],
|
||||||
|
"include": []
|
||||||
|
},
|
||||||
|
"setting": {
|
||||||
|
"urlCheck": false,
|
||||||
|
"es6": true,
|
||||||
|
"minified": true,
|
||||||
|
"postcss": false
|
||||||
|
},
|
||||||
|
"compileType": "miniprogram",
|
||||||
|
"appid": "wxa55815dd741a540d",
|
||||||
|
"projectname": "nomadro-audit-book",
|
||||||
|
"libVersion": "3.5.5"
|
||||||
|
}
|
||||||
4
apps/miniprogram/weapp/native-audit-book/index.js
Normal file
4
apps/miniprogram/weapp/native-audit-book/index.js
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
/** 提审小册:纯原生页,不经过 Taro/React */
|
||||||
|
Page({
|
||||||
|
data: {},
|
||||||
|
})
|
||||||
7
apps/miniprogram/weapp/native-audit-book/index.json
Normal file
7
apps/miniprogram/weapp/native-audit-book/index.json
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"navigationBarTitleText": "数字游民入门指南",
|
||||||
|
"navigationBarBackgroundColor": "#0c0b12",
|
||||||
|
"navigationBarTextStyle": "white",
|
||||||
|
"backgroundColor": "#0c0b12",
|
||||||
|
"navigationStyle": "default"
|
||||||
|
}
|
||||||
52
apps/miniprogram/weapp/native-audit-book/index.wxml
Normal file
52
apps/miniprogram/weapp/native-audit-book/index.wxml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<scroll-view scroll-y class="page" style="height:100vh;">
|
||||||
|
<view class="pad">
|
||||||
|
<text class="emoji">📗</text>
|
||||||
|
<text class="title">数字游民入门指南</text>
|
||||||
|
<text class="sub">远程办公 · 自律生活 · 稳健成长</text>
|
||||||
|
|
||||||
|
<text class="h">1. 写在前面</text>
|
||||||
|
<text class="p">欢迎阅读《数字游民入门指南》。</text>
|
||||||
|
<text class="p">这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。</text>
|
||||||
|
<text class="p">你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。</text>
|
||||||
|
|
||||||
|
<text class="h">2. 什么是数字游民</text>
|
||||||
|
<text class="p">「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。</text>
|
||||||
|
<text class="p">它不是逃避现实。更常见的状态是:工作目标清晰、沟通及时、作息稳定、遵守公司制度与当地法律法规。</text>
|
||||||
|
<text class="p">对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。</text>
|
||||||
|
|
||||||
|
<text class="h">3. 远程办公的基本功</text>
|
||||||
|
<text class="p">远程办公的核心不是换风景,而是换一种可协作的工作方式。</text>
|
||||||
|
<text class="p">建议每天有固定核心工作时间,并告诉同事哪些时段适合会议、哪些时段专注深度工作。</text>
|
||||||
|
<text class="p">每天开工前列三件必须完成的事;每周五花十五分钟复盘完成项与卡点。</text>
|
||||||
|
<text class="p">工具只保留必要的。开会前写清目的,会后写清结论:谁负责、做什么、何时完成。</text>
|
||||||
|
|
||||||
|
<text class="h">4. 居家与旅居的工作环境</text>
|
||||||
|
<text class="p">环境会直接影响专注力。不必追求豪华,但要够用、安静、可持续。</text>
|
||||||
|
<text class="p">居家建议:稳定桌椅与屏幕高度、充足光线、耳机、备用电源,以及减少打扰的约定。</text>
|
||||||
|
<text class="p">若允许短期异地办公,优先网络稳定、住宿安静、餐饮运动方便、交通可预期。</text>
|
||||||
|
|
||||||
|
<text class="h">5. 时间管理</text>
|
||||||
|
<text class="p">灵活工作最大的风险是时间碎、注意力散、任务拖。</text>
|
||||||
|
<text class="p">可用简化番茄法:25 分钟专注一件事,休息 5 分钟;深度工作时关闭无关通知。</text>
|
||||||
|
<text class="p">建议每天至少留 90 分钟不被会议打断的时间,用来做深度工作。</text>
|
||||||
|
|
||||||
|
<text class="h">6. 沟通与团队协作</text>
|
||||||
|
<text class="p">远程场景里,沟通质量几乎等于工作质量。</text>
|
||||||
|
<text class="p">同步信息:默认公开、结论先行、可执行(下一步、负责人、时间)。</text>
|
||||||
|
<text class="p">远程信任来自稳定交付:承诺按时完成,延期提前说明,问题主动暴露。</text>
|
||||||
|
|
||||||
|
<text class="h">7. 健康、作息与心态</text>
|
||||||
|
<text class="p">尽量固定睡眠与起床时间;每工作一小时起身活动两分钟;中午真正休息。</text>
|
||||||
|
<text class="p">运动不必复杂:散步、拉伸即可,关键是每周能坚持。</text>
|
||||||
|
|
||||||
|
<text class="h">8. 学习成长与职业规划</text>
|
||||||
|
<text class="p">真正护城河仍是能力与口碑:专业技能、表达能力、项目管理。</text>
|
||||||
|
<text class="p">请遵守劳动合同、信息安全与所在地法律法规。稳健发展,才能走得长远。</text>
|
||||||
|
|
||||||
|
<text class="h">9. 七天起步计划</text>
|
||||||
|
<text class="p">第1天整理工位;第2天三个每日目标;第3天文档归位;第4天练习结论先行;第5天短复盘;第6天轻度运动;第7天只改一件事。</text>
|
||||||
|
|
||||||
|
<text class="h">10. 结语</text>
|
||||||
|
<text class="p">先把远程协作做好,把身体照顾好,把专业能力垒扎实。祝你工作顺利,生活安定,步履从容。</text>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
54
apps/miniprogram/weapp/native-audit-book/index.wxss
Normal file
54
apps/miniprogram/weapp/native-audit-book/index.wxss
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
.page {
|
||||||
|
background: #0c0b12;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pad {
|
||||||
|
padding: 20px 16px 48px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji,
|
||||||
|
.title,
|
||||||
|
.sub,
|
||||||
|
.h,
|
||||||
|
.p {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji {
|
||||||
|
font-size: 28px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
font-size: 22px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #f8fafc;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sub {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #94a3b8;
|
||||||
|
line-height: 1.45;
|
||||||
|
margin: 8px 0 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.h {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #e2e8f0;
|
||||||
|
line-height: 1.4;
|
||||||
|
margin: 20px 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.p {
|
||||||
|
font-size: 15px;
|
||||||
|
color: #cbd5e1;
|
||||||
|
line-height: 1.75;
|
||||||
|
margin: 0 0 8px;
|
||||||
|
}
|
||||||
@ -102,6 +102,52 @@ if (fs.existsSync(assetsSrc)) {
|
|||||||
const pagesRoot = path.join(root, out, 'pages')
|
const pagesRoot = path.join(root, out, 'pages')
|
||||||
const stripped = stripInvalidShareKeys(pagesRoot)
|
const stripped = stripInvalidShareKeys(pagesRoot)
|
||||||
const stubWxss = ensurePageWxss(pagesRoot)
|
const stubWxss = ensurePageWxss(pagesRoot)
|
||||||
|
|
||||||
|
// 提审小册:纯原生页 + 纯原生 App,彻底绕开 Taro/React(否则 App 壳仍会拖垮首屏)
|
||||||
|
const nativeBook = path.join(root, 'native-audit-book')
|
||||||
|
const bookDist = path.join(pagesRoot, 'book')
|
||||||
|
let nativeBookCopied = 0
|
||||||
|
if (fs.existsSync(nativeBook)) {
|
||||||
|
fs.mkdirSync(bookDist, { recursive: true })
|
||||||
|
for (const name of ['index.js', 'index.json', 'index.wxml', 'index.wxss']) {
|
||||||
|
const src = path.join(nativeBook, name)
|
||||||
|
if (!fs.existsSync(src)) continue
|
||||||
|
fs.copyFileSync(src, path.join(bookDist, name))
|
||||||
|
nativeBookCopied += 1
|
||||||
|
}
|
||||||
|
for (const name of fs.readdirSync(bookDist)) {
|
||||||
|
if (name.startsWith('sub-common') || name.endsWith('.js.map')) {
|
||||||
|
const p = path.join(bookDist, name)
|
||||||
|
const st = fs.statSync(p)
|
||||||
|
if (st.isDirectory()) rmDir(p)
|
||||||
|
else fs.unlinkSync(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(root, out, 'app.js'), 'App({})\n')
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(root, out, 'app.wxss'),
|
||||||
|
'page{background:#0c0b12;color:#f8fafc;box-sizing:border-box}\n',
|
||||||
|
)
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(root, out, 'app.json'),
|
||||||
|
JSON.stringify(
|
||||||
|
{
|
||||||
|
pages: ['pages/book/index'],
|
||||||
|
window: {
|
||||||
|
navigationBarTitleText: '数字游民入门指南',
|
||||||
|
navigationBarBackgroundColor: '#0c0b12',
|
||||||
|
navigationBarTextStyle: 'white',
|
||||||
|
backgroundColor: '#0c0b12',
|
||||||
|
backgroundTextStyle: 'light',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
`[copy-weapp-static] ${out}: icons=cdn assets=${assets} strippedShareJson=${stripped} stubWxss=${stubWxss}`,
|
`[copy-weapp-static] ${out}: icons=cdn assets=${assets} strippedShareJson=${stripped} stubWxss=${stubWxss} nativeBook=${nativeBookCopied} nativeApp=1`,
|
||||||
)
|
)
|
||||||
|
|||||||
BIN
apps/miniprogram/weapp/store-assets/wechat-topic-nomad-cover.jpg
Normal file
BIN
apps/miniprogram/weapp/store-assets/wechat-topic-nomad-cover.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 252 KiB |
@ -26,28 +26,85 @@ pnpm dev
|
|||||||
|
|
||||||
检查:`http://localhost:8080/api/social/v1/health`(端口以现网 API_URL 为准)
|
检查:`http://localhost:8080/api/social/v1/health`(端口以现网 API_URL 为准)
|
||||||
|
|
||||||
## 线上增量(可重启 API)
|
## 线上增量(只部署 82)
|
||||||
|
|
||||||
1. 拉代码(含 `apps/api/services/social_svc`、门户 `/social`)
|
生产铁律:[`https://nomadro.cn`](https://nomadro.cn/) / MiroTalk / API / Centrifugo **全部在 `82.157.112.245`**,进房用 `mirotalk.nomadro.cn`。
|
||||||
2. 确认环境变量(可选):
|
|
||||||
- `SOCIAL_ENABLED=true`
|
|
||||||
- `SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db`(独立目录,勿放进 PB data)
|
|
||||||
3. 重启 **统一 API** 进程(systemd/pm2)——只加载新路由 + 新 sqlite 文件
|
|
||||||
4. 构建/重启门户 Next(含 `/social` 与 rewrite `/api/social/*`)
|
|
||||||
5. 冒烟:
|
|
||||||
- `GET /api/social/v1/health` → `ok` + `isolated: true`
|
|
||||||
- `GET /api/v1/health` 与 `/health` 仍正常(现网未坏)
|
|
||||||
- 打开 `https://nomadro.cn/social` 发一条聊天
|
|
||||||
|
|
||||||
回滚:设 `SOCIAL_ENABLED=false` 或去掉 social 代码后重启 API;**不要删**现网 PB/其它库。social.db 可单独备份/删除,不影响其它业务。
|
```bash
|
||||||
|
# 0) Centrifugo 实时层(本机下好 .tmp_cf/centrifugo.tgz 再跑;82 访问不了 GitHub)
|
||||||
|
# curl -L -o .tmp_cf/centrifugo.tgz https://github.com/centrifugal/centrifugo/releases/download/v5.4.9/centrifugo_5.4.9_linux_amd64.tar.gz
|
||||||
|
python deploy/social/centrifugo/deploy_82.py
|
||||||
|
# → systemd centrifugo :8008;nginx https://nomadro.cn/rt/;密钥 /etc/nomadro/centrifugo.env
|
||||||
|
# → social API:systemd nomadro-social :8020;GET /api/social/v1/realtime/token
|
||||||
|
|
||||||
|
# 1) 钉死 MiroTalk 在 82(.cn)
|
||||||
|
python deploy/social/mirotalk/pin_82_only.py
|
||||||
|
python deploy/social/mirotalk/apply_nomadro_whitelabel.py
|
||||||
|
python deploy/social/mirotalk/apply_zh_ui.py
|
||||||
|
python deploy/social/mirotalk/apply_zh_deep.py
|
||||||
|
python deploy/social/mirotalk/apply_speed.py
|
||||||
|
|
||||||
|
# 2) 同步游民社区门户代码到 /var/www/nomadro.cn 并 build
|
||||||
|
python deploy/social/deploy_82.py
|
||||||
|
```
|
||||||
|
|
||||||
|
环境变量(可选):
|
||||||
|
- `SOCIAL_ENABLED=true`
|
||||||
|
- `SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db`
|
||||||
|
- `NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn`(`/etc/nomadro/portal.env`)
|
||||||
|
- Centrifugo:`CENTRIFUGO_*`(见 `/etc/nomadro/centrifugo.env`,可并入 `portal.env`)
|
||||||
|
|
||||||
|
**前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。
|
||||||
|
|
||||||
|
冒烟:
|
||||||
|
- `https://nomadro.cn/social` → 200
|
||||||
|
- `https://mirotalk.nomadro.cn/join?...` → 200(勿再用 `.com`)
|
||||||
|
- `GET /api/social/v1/health` → `centrifugo: true`
|
||||||
|
- `GET /api/social/v1/realtime/token?channel_id=lobby`(头 `X-Social-Guest-Id`)→ `wsUrl` + JWT
|
||||||
|
- `systemctl is-active centrifugo nomadro-social`
|
||||||
|
|
||||||
|
回滚:设 `SOCIAL_ENABLED=false` 或回退门户 `.next`;**不要删**现网 PB。Centrifugo / `nomadro-social` 可单独 `systemctl stop`。
|
||||||
|
|
||||||
|
### 视觉主题(T1 / T2)
|
||||||
|
|
||||||
|
| Skin | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| **T1**(默认) | 对齐旅居社群视觉;`data-social-skin="1"` |
|
||||||
|
| T2 | 「琥珀信号」独立样式:`src/modules/social/app/theme2.css` |
|
||||||
|
|
||||||
|
导航 T1/T2 切换器已隐藏并强制写入 T1。恢复切换:`SiteShell` 加回切换器,改 `SOCIAL_SKIN_DEFAULT`。
|
||||||
|
|
||||||
## MiroTalk 站内嵌(CSP)
|
## MiroTalk 站内嵌(CSP)
|
||||||
|
|
||||||
公网 `mirotalk.nomadro.com` 解析在 **`107.173.30.245`**(Caddy 反代 `mirotalk.nomadro.cn`),`frame-ancestors` 写在:
|
| 域名 | IP | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `nomadro.cn` | **82.157.112.245** | 门户直连 |
|
||||||
|
| `mirotalk.nomadro.cn` | **82.157.112.245** | 本机 nginx → `127.0.0.1:9300`(**推荐进房 URL**) |
|
||||||
|
| `mirotalk.nomadro.com` | 107.173.30.245 | 旧边车 Caddy 反代,多一跳,慢 |
|
||||||
|
|
||||||
- `/etc/caddy/sites/mirotalk.nomadro.com.caddy`
|
门户默认用 **`https://mirotalk.nomadro.cn`**(与主站同机)。`ALLOWED_EMBED_ORIGINS` 在 82 上 MiroTalk `.env`;`.com` 边车 CSP 在 107:`/etc/caddy/sites/mirotalk.nomadro.com.caddy`。
|
||||||
- `/etc/caddy/sites/lounge.nomadro.com.caddy`(文字厅同源策略)
|
|
||||||
|
|
||||||
须包含:`https://nomadro.cn` `https://www.nomadro.cn` `http://localhost:3000` `http://127.0.0.1:3000`(及可选 `:3001`)。改完后 `systemctl reload caddy`。
|
|
||||||
|
|
||||||
本地 `pnpm dev`(:3000)活动页应可 iframe;若仍被拒,`MeetupLiveClient` 会本页 `location.assign` 进入(不新开标签)。
|
本地 `pnpm dev`(:3000)活动页应可 iframe;若仍被拒,`MeetupLiveClient` 会本页 `location.assign` 进入(不新开标签)。
|
||||||
|
|
||||||
|
### 白标(去 MiroTalk 品牌 / 禁弹窗)
|
||||||
|
|
||||||
|
上游实例在 **`82.157.112.245`**:`/opt/nomadro-services/mirotalk`(systemd `mirotalk-p2p`)。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python deploy/social/mirotalk/apply_nomadro_whitelabel.py
|
||||||
|
python deploy/social/mirotalk/apply_zh_ui.py
|
||||||
|
python deploy/social/mirotalk/apply_zh_deep.py
|
||||||
|
```
|
||||||
|
|
||||||
|
会:关 Share/About 等入口;默认 **`zh-CN`**(硬编码中文,不依赖 Google 翻译);加载页改为「正在进入活动厅」+ N 标;注入 `nomadro-embed.css` / `nomadro-i18n.js`;重启 `mirotalk-p2p`。
|
||||||
|
|
||||||
|
进房链接须带 `notify=0` + `name=`(有昵称会跳过英文进房弹窗)。门户 `MeetupLiveClient` 另有中文加载遮罩。
|
||||||
|
|
||||||
|
### 极速进房
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python deploy/social/mirotalk/apply_speed.py
|
||||||
|
```
|
||||||
|
|
||||||
|
- 关 RNNoise / geo / 进房 QR / 进房音效;有 `name` 时立刻藏 loading
|
||||||
|
- 门户:**取消「开始视频」闸门**,进活动页即 iframe;`preconnect` 预热;遮罩在 `iframe.onLoad` 立刻消失(无 500ms 等待)
|
||||||
|
|||||||
246
deploy/social/centrifugo/deploy_82.py
Normal file
246
deploy/social/centrifugo/deploy_82.py
Normal file
@ -0,0 +1,246 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Install Centrifugo on 82 + nginx /rt/ proxy under nomadro.cn. Idempotent.
|
||||||
|
|
||||||
|
Uploads local binary tarball if GitHub is unreachable from the server.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
VERSION = "5.4.9"
|
||||||
|
PORT = 8008
|
||||||
|
INSTALL_DIR = "/opt/centrifugo"
|
||||||
|
CONF_DIR = "/etc/centrifugo"
|
||||||
|
SECRETS_FILE = f"{CONF_DIR}/nomadro-secrets.json"
|
||||||
|
NGINX_EXT = "/www/server/panel/vhost/nginx/extension/www.nomadro.cn/centrifugo-rt.conf"
|
||||||
|
ENV_HINT = "/etc/nomadro/centrifugo.env"
|
||||||
|
ROOT = Path(__file__).resolve().parents[3]
|
||||||
|
LOCAL_TGZ = ROOT / ".tmp_cf" / "centrifugo.tgz"
|
||||||
|
|
||||||
|
|
||||||
|
def ssh_connect() -> paramiko.SSHClient:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(
|
||||||
|
HOST,
|
||||||
|
username=USER,
|
||||||
|
password=PASS,
|
||||||
|
timeout=40,
|
||||||
|
banner_timeout=60,
|
||||||
|
auth_timeout=40,
|
||||||
|
allow_agent=False,
|
||||||
|
look_for_keys=False,
|
||||||
|
)
|
||||||
|
tr = c.get_transport()
|
||||||
|
if tr:
|
||||||
|
tr.set_keepalive(15)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def run(c: paramiko.SSHClient, cmd: str, t: int = 180) -> tuple[str, int]:
|
||||||
|
i, o, e = c.exec_command(cmd, timeout=t, get_pty=True)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
code = o.channel.recv_exit_status()
|
||||||
|
clean = "\n".join(
|
||||||
|
ln
|
||||||
|
for ln in out.splitlines()
|
||||||
|
if PASS not in ln and "password for" not in ln.lower()
|
||||||
|
)
|
||||||
|
return clean, code
|
||||||
|
|
||||||
|
|
||||||
|
def sudo(c: paramiko.SSHClient, cmd: str, t: int = 180) -> tuple[str, int]:
|
||||||
|
import base64
|
||||||
|
|
||||||
|
b64 = base64.b64encode(cmd.encode("utf-8")).decode("ascii")
|
||||||
|
wrapped = f"echo {PASS} | sudo -S bash -lc 'echo {b64} | base64 -d | bash'"
|
||||||
|
return run(c, wrapped, t=t)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if not LOCAL_TGZ.exists():
|
||||||
|
print("missing local tarball:", LOCAL_TGZ)
|
||||||
|
print("download: curl -L -o .tmp_cf/centrifugo.tgz "
|
||||||
|
f"https://github.com/centrifugal/centrifugo/releases/download/v{VERSION}/centrifugo_{VERSION}_linux_amd64.tar.gz")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
c = ssh_connect()
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
|
||||||
|
print("=== upload binary ===", LOCAL_TGZ.stat().st_size)
|
||||||
|
sftp.put(str(LOCAL_TGZ), "/tmp/centrifugo.tgz")
|
||||||
|
|
||||||
|
print("=== dirs ===")
|
||||||
|
out, code = sudo(
|
||||||
|
c,
|
||||||
|
f"mkdir -p {INSTALL_DIR} {CONF_DIR} /www/server/panel/vhost/nginx/extension/www.nomadro.cn /etc/nomadro",
|
||||||
|
)
|
||||||
|
print(out, "code", code)
|
||||||
|
|
||||||
|
secrets_data = None
|
||||||
|
try:
|
||||||
|
with sftp.file(SECRETS_FILE, "r") as f:
|
||||||
|
secrets_data = json.loads(f.read().decode("utf-8"))
|
||||||
|
print("loaded existing secrets")
|
||||||
|
except Exception:
|
||||||
|
secrets_data = {
|
||||||
|
"token_hmac_secret_key": secrets.token_urlsafe(48),
|
||||||
|
"api_key": secrets.token_urlsafe(32),
|
||||||
|
"admin_password": secrets.token_urlsafe(16),
|
||||||
|
"admin_secret": secrets.token_urlsafe(24),
|
||||||
|
}
|
||||||
|
with sftp.file("/tmp/centrifugo-secrets.json", "w") as f:
|
||||||
|
f.write(json.dumps(secrets_data, indent=2) + "\n")
|
||||||
|
sudo(c, f"install -m 600 /tmp/centrifugo-secrets.json {SECRETS_FILE}")
|
||||||
|
print("generated secrets")
|
||||||
|
|
||||||
|
token_secret = secrets_data["token_hmac_secret_key"]
|
||||||
|
api_key = secrets_data["api_key"]
|
||||||
|
admin_password = secrets_data["admin_password"]
|
||||||
|
admin_secret = secrets_data["admin_secret"]
|
||||||
|
|
||||||
|
config = {
|
||||||
|
"token_hmac_secret_key": token_secret,
|
||||||
|
"api_key": api_key,
|
||||||
|
"admin_password": admin_password,
|
||||||
|
"admin_secret": admin_secret,
|
||||||
|
"admin": False,
|
||||||
|
"port": PORT,
|
||||||
|
"address": "127.0.0.1",
|
||||||
|
"allowed_origins": [
|
||||||
|
"https://nomadro.cn",
|
||||||
|
"https://www.nomadro.cn",
|
||||||
|
"http://localhost:3000",
|
||||||
|
"http://127.0.0.1:3000",
|
||||||
|
],
|
||||||
|
"namespaces": [
|
||||||
|
{
|
||||||
|
"name": "social",
|
||||||
|
"allow_subscribe_for_client": True,
|
||||||
|
"allow_publish_for_client": False,
|
||||||
|
"presence": True,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
unit = f"""[Unit]
|
||||||
|
Description=Centrifugo realtime for Nomadro social
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart={INSTALL_DIR}/centrifugo --config={CONF_DIR}/config.json
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
LimitNOFILE=65535
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
"""
|
||||||
|
|
||||||
|
nginx_rt = f"""# Centrifugo realtime — /rt/ → 127.0.0.1:{PORT}
|
||||||
|
location ^~ /rt/ {{
|
||||||
|
rewrite ^/rt/(.*)$ /$1 break;
|
||||||
|
proxy_pass http://127.0.0.1:{PORT};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection $connection_upgrade;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
|
proxy_buffering off;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
env_file = f"""CENTRIFUGO_ENABLED=true
|
||||||
|
CENTRIFUGO_API_URL=http://127.0.0.1:{PORT}/api
|
||||||
|
CENTRIFUGO_API_KEY={api_key}
|
||||||
|
CENTRIFUGO_TOKEN_SECRET={token_secret}
|
||||||
|
CENTRIFUGO_WS_URL=wss://nomadro.cn/rt/connection/websocket
|
||||||
|
"""
|
||||||
|
|
||||||
|
with sftp.file("/tmp/centrifugo-config.json", "w") as f:
|
||||||
|
f.write(json.dumps(config, indent=2) + "\n")
|
||||||
|
with sftp.file("/tmp/centrifugo.service", "w") as f:
|
||||||
|
f.write(unit)
|
||||||
|
with sftp.file("/tmp/centrifugo-rt.conf", "w") as f:
|
||||||
|
f.write(nginx_rt)
|
||||||
|
with sftp.file("/tmp/centrifugo.env", "w") as f:
|
||||||
|
f.write(env_file)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
print("=== install binary from uploaded tarball ===")
|
||||||
|
out, code = sudo(
|
||||||
|
c,
|
||||||
|
f"""
|
||||||
|
set -e
|
||||||
|
cd /tmp
|
||||||
|
tar -xzf centrifugo.tgz centrifugo
|
||||||
|
install -m 755 centrifugo {INSTALL_DIR}/centrifugo
|
||||||
|
rm -f centrifugo
|
||||||
|
{INSTALL_DIR}/centrifugo version
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
print(out)
|
||||||
|
if code != 0:
|
||||||
|
print("binary install failed", code)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print("=== install config/service/nginx ===")
|
||||||
|
out, code = sudo(
|
||||||
|
c,
|
||||||
|
f"""
|
||||||
|
set -e
|
||||||
|
install -m 600 /tmp/centrifugo-config.json {CONF_DIR}/config.json
|
||||||
|
install -m 644 /tmp/centrifugo.service /etc/systemd/system/centrifugo.service
|
||||||
|
install -m 644 /tmp/centrifugo-rt.conf {NGINX_EXT}
|
||||||
|
install -m 600 /tmp/centrifugo.env {ENV_HINT}
|
||||||
|
# merge centrifugo env into portal.env for Next rewrites / future API
|
||||||
|
touch /etc/nomadro/portal.env
|
||||||
|
for k in CENTRIFUGO_ENABLED CENTRIFUGO_API_URL CENTRIFUGO_API_KEY CENTRIFUGO_TOKEN_SECRET CENTRIFUGO_WS_URL; do
|
||||||
|
v=$(grep "^$k=" {ENV_HINT} | head -1)
|
||||||
|
if grep -q "^$k=" /etc/nomadro/portal.env; then
|
||||||
|
sed -i "s|^$k=.*|$v|" /etc/nomadro/portal.env
|
||||||
|
else
|
||||||
|
echo "$v" >> /etc/nomadro/portal.env
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable centrifugo.service
|
||||||
|
systemctl restart centrifugo.service
|
||||||
|
sleep 1
|
||||||
|
systemctl is-active centrifugo.service
|
||||||
|
ss -lntp | grep ':{PORT}' || true
|
||||||
|
nginx -t
|
||||||
|
nginx -s reload
|
||||||
|
sleep 1
|
||||||
|
curl -sk -o /dev/null -w 'local %{{http_code}}\\n' http://127.0.0.1:{PORT}/
|
||||||
|
curl -sk -o /dev/null -w 'rt %{{http_code}}\\n' https://nomadro.cn/rt/
|
||||||
|
curl -sS -H 'Content-Type: application/json' -H 'X-API-Key: {api_key}' \\
|
||||||
|
-d '{{"channel":"social:lobby","data":{{"type":"ping","ok":true}}}}' \\
|
||||||
|
http://127.0.0.1:{PORT}/api/publish
|
||||||
|
echo
|
||||||
|
""",
|
||||||
|
t=120,
|
||||||
|
)
|
||||||
|
print(out)
|
||||||
|
print("exit", code)
|
||||||
|
print("WS wss://nomadro.cn/rt/connection/websocket")
|
||||||
|
print("ENV", ENV_HINT)
|
||||||
|
c.close()
|
||||||
|
return 0 if code == 0 else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
161
deploy/social/deploy_82.py
Normal file
161
deploy/social/deploy_82.py
Normal file
@ -0,0 +1,161 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Deploy 游民社区 + MiroTalk(.cn) portal bits to 82.157.112.245 only."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
APP = "/var/www/nomadro.cn"
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
|
||||||
|
# Paths relative to repo root
|
||||||
|
INCLUDE = [
|
||||||
|
"src/modules/social",
|
||||||
|
"src/app/social",
|
||||||
|
"src/modules/social/lib/seed.ts", # covered by tree
|
||||||
|
"src/lib/remote-config.ts",
|
||||||
|
"src/components/sections/hero.tsx",
|
||||||
|
"src/app/layout.tsx",
|
||||||
|
"src/app/hub.css",
|
||||||
|
"src/app/admin/verticals/page.tsx",
|
||||||
|
"data/remote-config.json",
|
||||||
|
"next.config.ts",
|
||||||
|
"tsconfig.json",
|
||||||
|
"apps/api/app/main.py",
|
||||||
|
"apps/api/services/social_svc",
|
||||||
|
"apps/api/services/community_svc/config.py",
|
||||||
|
"apps/api/services/community_svc/services/meetup_live.py",
|
||||||
|
"deploy/social",
|
||||||
|
"README.md",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def connect() -> paramiko.SSHClient:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(
|
||||||
|
HOST,
|
||||||
|
username=USER,
|
||||||
|
password=PASS,
|
||||||
|
timeout=40,
|
||||||
|
allow_agent=False,
|
||||||
|
look_for_keys=False,
|
||||||
|
banner_timeout=120,
|
||||||
|
)
|
||||||
|
t = c.get_transport()
|
||||||
|
if t:
|
||||||
|
t.set_keepalive(20)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 1200) -> tuple[str, int]:
|
||||||
|
_i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
code = o.channel.recv_exit_status()
|
||||||
|
return out, code
|
||||||
|
|
||||||
|
|
||||||
|
def pack() -> Path:
|
||||||
|
tmp = Path(tempfile.mkdtemp()) / "social82.tgz"
|
||||||
|
with tarfile.open(tmp, "w:gz") as tar:
|
||||||
|
for rel in INCLUDE:
|
||||||
|
p = ROOT / rel
|
||||||
|
if not p.exists():
|
||||||
|
print("skip missing", rel)
|
||||||
|
continue
|
||||||
|
tar.add(p, arcname=rel)
|
||||||
|
print("packed", tmp, "bytes", tmp.stat().st_size)
|
||||||
|
return tmp
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
archive = pack()
|
||||||
|
c = connect()
|
||||||
|
print("connected")
|
||||||
|
|
||||||
|
# upload
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
sftp.put(str(archive), "/tmp/social82.tgz")
|
||||||
|
sftp.close()
|
||||||
|
print("uploaded")
|
||||||
|
|
||||||
|
# extract into app (preserve remote-config backup)
|
||||||
|
script = f"""
|
||||||
|
set -euo pipefail
|
||||||
|
cd {APP}
|
||||||
|
sudo cp -a data/remote-config.json /tmp/remote-config.pre-social.json || true
|
||||||
|
tar -xzf /tmp/social82.tgz
|
||||||
|
# restore operational remote-config then merge social module key via python
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
app = Path('{APP}')
|
||||||
|
live = app / 'data' / 'remote-config.json'
|
||||||
|
bak = Path('/tmp/remote-config.pre-social.json')
|
||||||
|
incoming = json.loads(live.read_text(encoding='utf-8')) if live.exists() else {{}}
|
||||||
|
base = json.loads(bak.read_text(encoding='utf-8')) if bak.exists() else {{}}
|
||||||
|
# keep live ops flags; ensure modules.social exists from incoming
|
||||||
|
mods = base.setdefault('modules', {{}}) if isinstance(base, dict) else {{}}
|
||||||
|
inc_mods = incoming.get('modules') if isinstance(incoming, dict) else {{}}
|
||||||
|
if isinstance(inc_mods, dict) and 'social' in inc_mods:
|
||||||
|
mods['social'] = inc_mods['social']
|
||||||
|
elif 'social' not in mods:
|
||||||
|
mods['social'] = {{'enabled': True, 'title': '游民社区', 'tabLabel': '社区'}}
|
||||||
|
# prefer base (prod) as SoT with social injected
|
||||||
|
if isinstance(base, dict):
|
||||||
|
base['modules'] = mods
|
||||||
|
live.write_text(json.dumps(base, ensure_ascii=False, indent=2) + '\\n', encoding='utf-8')
|
||||||
|
print('remote-config merged social')
|
||||||
|
else:
|
||||||
|
print('kept incoming remote-config')
|
||||||
|
PY
|
||||||
|
|
||||||
|
# portal env: force MiroTalk on 82 .cn
|
||||||
|
sudo mkdir -p /etc/nomadro
|
||||||
|
if [ -f /etc/nomadro/portal.env ]; then
|
||||||
|
sudo grep -q '^NEXT_PUBLIC_MIROTALK_URL=' /etc/nomadro/portal.env \\
|
||||||
|
&& sudo sed -i 's|^NEXT_PUBLIC_MIROTALK_URL=.*|NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn|' /etc/nomadro/portal.env \\
|
||||||
|
|| echo 'NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn' | sudo tee -a /etc/nomadro/portal.env >/dev/null
|
||||||
|
else
|
||||||
|
echo 'NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn' | sudo tee /etc/nomadro/portal.env >/dev/null
|
||||||
|
fi
|
||||||
|
grep MIROTALK /etc/nomadro/portal.env || true
|
||||||
|
|
||||||
|
# .next often root-owned from prior deploys — clear then build as ubuntu
|
||||||
|
sudo systemctl stop nomadro.service || true
|
||||||
|
sudo chown -R ubuntu:ubuntu {APP}
|
||||||
|
sudo rm -rf {APP}/.next
|
||||||
|
export NODE_OPTIONS=--max-old-space-size=4096
|
||||||
|
/usr/local/bin/pnpm build
|
||||||
|
test -f .next/BUILD_ID
|
||||||
|
echo BUILD_ID=$(cat .next/BUILD_ID)
|
||||||
|
sudo systemctl start nomadro.service
|
||||||
|
sleep 5
|
||||||
|
systemctl is-active nomadro.service
|
||||||
|
curl -sk -o /dev/null -w 'home %{{http_code}}\\n' https://nomadro.cn/
|
||||||
|
curl -sk -o /dev/null -w 'social %{{http_code}}\\n' https://nomadro.cn/social
|
||||||
|
curl -sk -o /dev/null -w 'meetup %{{http_code}}\\n' https://nomadro.cn/social/meetup
|
||||||
|
curl -sk -o /dev/null -w 'mirotalk_cn %{{http_code}} %{{time_total}}\\n' 'https://mirotalk.nomadro.cn/join?room=t&name=t¬ify=0'
|
||||||
|
echo DONE
|
||||||
|
"""
|
||||||
|
print("building on 82 (may take several minutes)...")
|
||||||
|
out, code = run(c, script, timeout=1500)
|
||||||
|
print(out[-8000:] if len(out) > 8000 else out)
|
||||||
|
c.close()
|
||||||
|
try:
|
||||||
|
archive.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
354
deploy/social/mirotalk/apply_nomadro_whitelabel.py
Normal file
354
deploy/social/mirotalk/apply_nomadro_whitelabel.py
Normal file
@ -0,0 +1,354 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""White-label MiroTalk P2P on 82.157 for nomadro.cn embed (no MiroTalk chrome/popups)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
BASE = "/opt/nomadro-services/mirotalk"
|
||||||
|
LOCAL_CSS = Path(__file__).with_name("nomadro-embed.css")
|
||||||
|
REMOTE_CSS = f"{BASE}/public/css/nomadro-embed.css"
|
||||||
|
MARKER = "/* nomadro-embed */"
|
||||||
|
|
||||||
|
|
||||||
|
def ssh() -> paramiko.SSHClient:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(
|
||||||
|
HOST,
|
||||||
|
username=USER,
|
||||||
|
password=PASS,
|
||||||
|
timeout=30,
|
||||||
|
allow_agent=False,
|
||||||
|
look_for_keys=False,
|
||||||
|
)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 120) -> tuple[str, int]:
|
||||||
|
_i, o, e = c.exec_command(cmd, timeout=timeout)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
err = e.read().decode("utf-8", "ignore")
|
||||||
|
code = o.channel.recv_exit_status()
|
||||||
|
text = out + (("\n" + err) if err.strip() else "")
|
||||||
|
return text, code
|
||||||
|
|
||||||
|
|
||||||
|
def sftp_write(c: paramiko.SSHClient, remote: str, data: str | bytes) -> None:
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
# write to /tmp then sudo mv (ubuntu may lack write on /opt)
|
||||||
|
tmp = f"/tmp/{Path(remote).name}"
|
||||||
|
with sftp.file(tmp, "w") as f:
|
||||||
|
if isinstance(data, bytes):
|
||||||
|
f.write(data)
|
||||||
|
else:
|
||||||
|
f.write(data.encode("utf-8"))
|
||||||
|
sftp.close()
|
||||||
|
out, code = run(c, f"sudo mv {tmp} {remote} && sudo chmod 644 {remote}")
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(f"sftp_write failed: {out}")
|
||||||
|
|
||||||
|
|
||||||
|
def patch_config(text: str) -> str:
|
||||||
|
# brand.app
|
||||||
|
text = re.sub(
|
||||||
|
r"name:\s*'MiroTalk'",
|
||||||
|
"name: 'nomadro'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"title:\s*'<h1>MiroTalk</h1>[^']*'",
|
||||||
|
"title: '<h1>nomadro</h1>游民社区 · 线上活动厅'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"description:\s*\n\s*'Start your next video call[^']*'",
|
||||||
|
"description: 'nomadro 游民社区视频厅。站内进入,无需下载。'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"joinDescription:\s*'Pick a room name\.<br />How about this one\?'",
|
||||||
|
"joinDescription: '进入活动房间'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"joinButtonLabel:\s*'JOIN ROOM'",
|
||||||
|
"joinButtonLabel: '进入房间'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"siteName:\s*'MiroTalk'",
|
||||||
|
"siteName: 'nomadro'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"title:\s*'Click the link to make a call\.'",
|
||||||
|
"title: 'nomadro 线上活动'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"description:\s*\n\s*'MiroTalk calling provides[^']*'",
|
||||||
|
"description: 'nomadro 游民社区 · 视频活动'",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# hide landing marketing blocks
|
||||||
|
for key in (
|
||||||
|
"topSponsors",
|
||||||
|
"features",
|
||||||
|
"browsers",
|
||||||
|
"teams",
|
||||||
|
"tryEasier",
|
||||||
|
"poweredBy",
|
||||||
|
"sponsors",
|
||||||
|
"pastSponsors",
|
||||||
|
"advertisers",
|
||||||
|
"supportUs",
|
||||||
|
"footer",
|
||||||
|
):
|
||||||
|
text = re.sub(rf"{key}:\s*true", f"{key}: false", text)
|
||||||
|
|
||||||
|
# buttons.main — hide share/about/extra chrome; keep A/V/screen
|
||||||
|
replacements = {
|
||||||
|
"showShareQr: true": "showShareQr: false",
|
||||||
|
"showShareRoomBtn: true": "showShareRoomBtn: false",
|
||||||
|
"showAboutBtn: true": "showAboutBtn: false",
|
||||||
|
"showExtraBtn: true": "showExtraBtn: false",
|
||||||
|
"showChatRoomBtn: true": "showChatRoomBtn: false", # portal has side chat
|
||||||
|
"showCaptionRoomBtn: true": "showCaptionRoomBtn: false",
|
||||||
|
"showRoomEmojiPickerBtn: true": "showRoomEmojiPickerBtn: false",
|
||||||
|
"showWhiteboardBtn: true": "showWhiteboardBtn: false",
|
||||||
|
"showSnapshotRoomBtn: true": "showSnapshotRoomBtn: false",
|
||||||
|
"showFileShareBtn: true": "showFileShareBtn: false",
|
||||||
|
"showDocumentPipBtn: true": "showDocumentPipBtn: false",
|
||||||
|
"showRecordStreamBtn: true": "showRecordStreamBtn: false",
|
||||||
|
"showMyHandBtn: true": "showMyHandBtn: false",
|
||||||
|
"showTabEmailInvitation: true": "showTabEmailInvitation: false",
|
||||||
|
}
|
||||||
|
for a, b in replacements.items():
|
||||||
|
text = text.replace(a, b)
|
||||||
|
|
||||||
|
# themes.dark — enable nomadro palette
|
||||||
|
if "dark: {" not in text or "--body-bg': 'radial-gradient(#0a0e17" not in text:
|
||||||
|
theme_block = """themes: {
|
||||||
|
dark: {
|
||||||
|
'--body-bg': 'radial-gradient(#111827, #0a0e17)',
|
||||||
|
'--msger-bg': 'radial-gradient(#111827, #0a0e17)',
|
||||||
|
'--msger-private-bg': 'radial-gradient(#111827, #0a0e17)',
|
||||||
|
'--wb-bg': 'radial-gradient(#111827, #0a0e17)',
|
||||||
|
'--elem-border-color': '1px solid rgba(255, 255, 255, 0.08)',
|
||||||
|
'--navbar-bg': 'rgba(10, 14, 23, 0.88)',
|
||||||
|
'--select-bg': '#111827',
|
||||||
|
'--tab-btn-active': '#1f2937',
|
||||||
|
'--box-shadow': '0px 8px 32px 0px rgba(0, 0, 0, 0.35)',
|
||||||
|
'--left-msg-bg': '#1f2937',
|
||||||
|
'--right-msg-bg': '#0f766e',
|
||||||
|
'--private-msg-bg': '#1f2937',
|
||||||
|
'--btn-bar-bg-color': '#4ecdc4',
|
||||||
|
'--btn-bar-color': '#0a0e17',
|
||||||
|
'--btns-bg-color': 'rgba(10, 14, 23, 0.78)',
|
||||||
|
'--dd-color': '#4ecdc4',
|
||||||
|
},
|
||||||
|
},"""
|
||||||
|
text = re.sub(
|
||||||
|
r"themes:\s*\{[\s\S]*?\n \},\n /\*\*\n \* Configuration for controlling the visibility of buttons",
|
||||||
|
theme_block
|
||||||
|
+ "\n /**\n * Configuration for controlling the visibility of buttons",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# about box — strip MiroTalk promo
|
||||||
|
text = re.sub(
|
||||||
|
r"about:\s*\{[\s\S]*?\n \},",
|
||||||
|
"""about: {
|
||||||
|
imageUrl: '../images/logo.svg',
|
||||||
|
title: 'nomadro 视频厅',
|
||||||
|
html: '<span>游民社区 · 线上活动</span>',
|
||||||
|
},""",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_js(text: str) -> str:
|
||||||
|
# Never auto-open share room popup
|
||||||
|
text = re.sub(
|
||||||
|
r"function getNotify\(\)\s*\{[\s\S]*?return notify;\s*\}",
|
||||||
|
"function getNotify() {\n"
|
||||||
|
" // nomadro: never auto-popup Share the room\n"
|
||||||
|
" return false;\n"
|
||||||
|
"}",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
if "function shareRoomMeetingURL" in text and "nomadro: skip share popup" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"function shareRoomMeetingURL(checkScreen = false) {",
|
||||||
|
"function shareRoomMeetingURL(checkScreen = false) {\n"
|
||||||
|
" // nomadro: skip share popup\n"
|
||||||
|
" return;",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
if "function shareRoomUrl" in text and "nomadro: skip shareRoomUrl" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"async function shareRoomUrl() {",
|
||||||
|
"async function shareRoomUrl() {\n"
|
||||||
|
" // nomadro: skip shareRoomUrl\n"
|
||||||
|
" return;",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
# MiroTalk sometimes force-enables share for guests — keep off
|
||||||
|
text = text.replace(
|
||||||
|
"buttons.main.showShareRoomBtn = true;",
|
||||||
|
"buttons.main.showShareRoomBtn = false; // nomadro",
|
||||||
|
)
|
||||||
|
text = text.replace(
|
||||||
|
"buttons.main.showAboutBtn = true;",
|
||||||
|
"buttons.main.showAboutBtn = false; // nomadro",
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_buttons_js(text: str) -> str:
|
||||||
|
for a, b in {
|
||||||
|
"showShareQr: true": "showShareQr: false",
|
||||||
|
"showShareRoomBtn: true": "showShareRoomBtn: false",
|
||||||
|
"showAboutBtn: true": "showAboutBtn: false",
|
||||||
|
"showExtraBtn: true": "showExtraBtn: false",
|
||||||
|
"showChatRoomBtn: true": "showChatRoomBtn: false",
|
||||||
|
"showCaptionRoomBtn: true": "showCaptionRoomBtn: false",
|
||||||
|
"showRoomEmojiPickerBtn: true": "showRoomEmojiPickerBtn: false",
|
||||||
|
"showWhiteboardBtn: true": "showWhiteboardBtn: false",
|
||||||
|
"showSnapshotRoomBtn: true": "showSnapshotRoomBtn: false",
|
||||||
|
"showFileShareBtn: true": "showFileShareBtn: false",
|
||||||
|
"showDocumentPipBtn: true": "showDocumentPipBtn: false",
|
||||||
|
"showRecordStreamBtn: true": "showRecordStreamBtn: false",
|
||||||
|
"showMyHandBtn: true": "showMyHandBtn: false",
|
||||||
|
}.items():
|
||||||
|
text = text.replace(a, b)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_html(text: str) -> str:
|
||||||
|
if "nomadro-embed.css" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
'<link rel="stylesheet" href="../css/client.css" />',
|
||||||
|
'<link rel="stylesheet" href="../css/client.css" />\n'
|
||||||
|
' <link rel="stylesheet" href="../css/nomadro-embed.css" />',
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
boot = (
|
||||||
|
"<script>"
|
||||||
|
"document.documentElement.classList.add('nomadro-embed');"
|
||||||
|
"document.addEventListener('DOMContentLoaded',function(){"
|
||||||
|
"document.body&&document.body.classList.add('nomadro-embed');"
|
||||||
|
"});"
|
||||||
|
"</script>"
|
||||||
|
)
|
||||||
|
if "nomadro-embed" not in text.split("</head>")[0]:
|
||||||
|
text = text.replace("</head>", f" {boot}\n </head>", 1)
|
||||||
|
# title
|
||||||
|
text = re.sub(
|
||||||
|
r"<title id=\"clientTitle\">[^<]*</title>",
|
||||||
|
'<title id="clientTitle">nomadro 视频厅</title>',
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_env(text: str) -> str:
|
||||||
|
def set_kv(src: str, key: str, value: str) -> str:
|
||||||
|
if re.search(rf"^{re.escape(key)}=", src, re.M):
|
||||||
|
return re.sub(rf"^{re.escape(key)}=.*$", f"{key}={value}", src, count=1, flags=re.M)
|
||||||
|
return src.rstrip() + f"\n{key}={value}\n"
|
||||||
|
|
||||||
|
text = set_kv(text, "SURVEY_ENABLED", "false")
|
||||||
|
text = set_kv(text, "STATS_ENABLED", "false")
|
||||||
|
text = set_kv(text, "REDIRECT_ENABLED", "true")
|
||||||
|
text = set_kv(text, "REDIRECT_URL", "https://nomadro.cn/social/meetup")
|
||||||
|
text = set_kv(text, "SHOW_ACTIVE_ROOMS", "false")
|
||||||
|
# keep ALLOWED_EMBED_ORIGINS if present
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if not LOCAL_CSS.exists():
|
||||||
|
print("missing", LOCAL_CSS, file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
c = ssh()
|
||||||
|
print("connected")
|
||||||
|
|
||||||
|
# backup once
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
f"sudo test -f {BASE}/app/src/config.js.bak_nomadro || "
|
||||||
|
f"sudo cp {BASE}/app/src/config.js {BASE}/app/src/config.js.bak_nomadro; "
|
||||||
|
f"sudo test -f {BASE}/public/js/client.js.bak_nomadro || "
|
||||||
|
f"sudo cp {BASE}/public/js/client.js {BASE}/public/js/client.js.bak_nomadro; "
|
||||||
|
f"sudo test -f {BASE}/public/views/client.html.bak_nomadro || "
|
||||||
|
f"sudo cp {BASE}/public/views/client.html {BASE}/public/views/client.html.bak_nomadro",
|
||||||
|
)
|
||||||
|
|
||||||
|
# upload CSS
|
||||||
|
sftp_write(c, REMOTE_CSS, LOCAL_CSS.read_text(encoding="utf-8"))
|
||||||
|
print("css uploaded")
|
||||||
|
|
||||||
|
# patch files
|
||||||
|
for remote, fn in [
|
||||||
|
(f"{BASE}/app/src/config.js", patch_config),
|
||||||
|
(f"{BASE}/public/js/client.js", patch_client_js),
|
||||||
|
(f"{BASE}/public/js/buttons.js", patch_buttons_js),
|
||||||
|
(f"{BASE}/public/views/client.html", patch_client_html),
|
||||||
|
(f"{BASE}/.env", patch_env),
|
||||||
|
]:
|
||||||
|
out, code = run(c, f"sudo cat {remote}")
|
||||||
|
if code != 0:
|
||||||
|
print("FAIL read", remote, out)
|
||||||
|
return 1
|
||||||
|
new = fn(out)
|
||||||
|
if new == out:
|
||||||
|
print("unchanged", remote)
|
||||||
|
else:
|
||||||
|
sftp_write(c, remote, new)
|
||||||
|
print("patched", remote)
|
||||||
|
|
||||||
|
# restart
|
||||||
|
out, code = run(c, "sudo systemctl restart mirotalk-p2p && sleep 2 && systemctl is-active mirotalk-p2p")
|
||||||
|
print(out)
|
||||||
|
if code != 0 or "active" not in out:
|
||||||
|
print("restart failed", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# smoke: local headers + join page contains our css
|
||||||
|
out, _ = run(
|
||||||
|
c,
|
||||||
|
"curl -sI http://127.0.0.1:9300/join?room=t&name=t¬ify=0 | head -20; "
|
||||||
|
"curl -s 'http://127.0.0.1:9300/join?room=t&name=t¬ify=0' | "
|
||||||
|
"grep -o 'nomadro-embed.css\\|nomadro 视频厅\\|getNotify' | head",
|
||||||
|
)
|
||||||
|
print("smoke:\n", out)
|
||||||
|
c.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
214
deploy/social/mirotalk/apply_speed.py
Normal file
214
deploy/social/mirotalk/apply_speed.py
Normal file
@ -0,0 +1,214 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Speed up MiroTalk join: skip geo/QR/sounds/RNNoise, hide loading ASAP."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
BASE = "/opt/nomadro-services/mirotalk"
|
||||||
|
SPEED_JS = """'use strict';
|
||||||
|
/* nomadro: instant join UX */
|
||||||
|
(function () {
|
||||||
|
function hideLoading() {
|
||||||
|
var el = document.getElementById('loadingDiv');
|
||||||
|
if (el) {
|
||||||
|
el.style.display = 'none';
|
||||||
|
el.style.visibility = 'hidden';
|
||||||
|
el.style.opacity = '0';
|
||||||
|
el.setAttribute('hidden', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Hide as soon as HTML parses if name is already in URL (portal always sends name)
|
||||||
|
try {
|
||||||
|
var q = new URLSearchParams(location.search);
|
||||||
|
if (q.get('name')) hideLoading();
|
||||||
|
} catch (e) {}
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
try {
|
||||||
|
if (new URLSearchParams(location.search).get('name')) hideLoading();
|
||||||
|
} catch (e) {}
|
||||||
|
});
|
||||||
|
// Also hide once media permission already granted (prior visit)
|
||||||
|
if (navigator.permissions && navigator.permissions.query) {
|
||||||
|
Promise.all([
|
||||||
|
navigator.permissions.query({ name: 'camera' }).catch(function () { return null; }),
|
||||||
|
navigator.permissions.query({ name: 'microphone' }).catch(function () { return null; }),
|
||||||
|
]).then(function (states) {
|
||||||
|
var ok = states.some(function (s) { return s && s.state === 'granted'; });
|
||||||
|
if (ok) hideLoading();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def ssh():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, t=120):
|
||||||
|
_i, o, e = c.exec_command(cmd, timeout=t)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
err = e.read().decode("utf-8", "ignore")
|
||||||
|
return out + (("\n" + err) if err.strip() else ""), o.channel.recv_exit_status()
|
||||||
|
|
||||||
|
|
||||||
|
def write(c, remote, data: str):
|
||||||
|
tmp = f"/tmp/{Path(remote).name}"
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file(tmp, "w") as f:
|
||||||
|
f.write(data.encode("utf-8"))
|
||||||
|
sftp.close()
|
||||||
|
out, code = run(c, f"sudo mv {tmp} {remote} && sudo chmod 644 {remote}")
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(out)
|
||||||
|
|
||||||
|
|
||||||
|
def patch_env(text: str) -> str:
|
||||||
|
import re
|
||||||
|
|
||||||
|
def set_kv(src, key, value):
|
||||||
|
if re.search(rf"^{re.escape(key)}=", src, re.M):
|
||||||
|
return re.sub(rf"^{re.escape(key)}=.*$", f"{key}={value}", src, count=1, flags=re.M)
|
||||||
|
return src.rstrip() + f"\n{key}={value}\n"
|
||||||
|
|
||||||
|
text = set_kv(text, "CUSTOM_NOISE_SUPPRESSION_ENABLED", "false")
|
||||||
|
text = set_kv(text, "IP_LOOKUP_ENABLED", "false")
|
||||||
|
text = set_kv(text, "STATS_ENABLED", "false")
|
||||||
|
text = set_kv(text, "SURVEY_ENABLED", "false")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_js(text: str) -> str:
|
||||||
|
# Skip geo
|
||||||
|
if "nomadro: skip geo" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"function loadGeo() {",
|
||||||
|
"function loadGeo() {\n"
|
||||||
|
" // nomadro: skip geo\n"
|
||||||
|
" return;",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Skip QR popup generation cost
|
||||||
|
if "async function makeRoomPopupQR" in text and "nomadro: skip QR" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"async function makeRoomPopupQR",
|
||||||
|
"async function makeRoomPopupQR_disabled_nomadro",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
# add fast stub before old (renamed) - find call sites use makeRoomPopupQR()
|
||||||
|
# Better: replace function body start
|
||||||
|
# Revert rename approach - patch call instead
|
||||||
|
text = text.replace(
|
||||||
|
"makeRoomPopupQR();",
|
||||||
|
"/* nomadro: skip QR */ void 0;",
|
||||||
|
)
|
||||||
|
|
||||||
|
# If rename left a broken fn, fix by stubbing renamed back
|
||||||
|
if "async function makeRoomPopupQR_disabled_nomadro" in text and "async function makeRoomPopupQR(" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"async function makeRoomPopupQR_disabled_nomadro",
|
||||||
|
"async function makeRoomPopupQR",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
if "nomadro: skip QR body" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"async function makeRoomPopupQR",
|
||||||
|
"async function makeRoomPopupQR(){ /* nomadro: skip QR body */ return; }\n"
|
||||||
|
"async function makeRoomPopupQR_orig_unused",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Hide loading at start of handleConnect
|
||||||
|
if "nomadro: hide loading ASAP" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"async function handleConnect() {\n console.log('03. Connected to signaling server');",
|
||||||
|
"async function handleConnect() {\n"
|
||||||
|
" // nomadro: hide loading ASAP\n"
|
||||||
|
" try { if (typeof loadingDiv !== 'undefined' && loadingDiv) { "
|
||||||
|
"loadingDiv.style.display='none'; loadingDiv.hidden=true; } } catch(e) {}\n"
|
||||||
|
" console.log('03. Connected to signaling server');",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Skip RNNoise init await cost
|
||||||
|
text = text.replace(
|
||||||
|
"await initRNNoiseSuppression();",
|
||||||
|
"/* nomadro: skip RNNoise */ void 0;",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Mute join sounds
|
||||||
|
text = text.replace(
|
||||||
|
" playSound('addPeer');\n return;\n }\n\n playSound('newMessage');",
|
||||||
|
" /* nomadro: no join sound */ return;\n }\n\n /* nomadro: no join sound */",
|
||||||
|
)
|
||||||
|
|
||||||
|
# whoAreYou named path: hide loading first line already has elemDisplay - make sync hide stronger
|
||||||
|
text = text.replace(
|
||||||
|
" if (myPeerName) {\n elemDisplay(loadingDiv, false);",
|
||||||
|
" if (myPeerName) {\n"
|
||||||
|
" try { loadingDiv.style.display='none'; loadingDiv.hidden=true; } catch(e) {}\n"
|
||||||
|
" elemDisplay(loadingDiv, false);",
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_html(text: str) -> str:
|
||||||
|
if "nomadro-speed.js" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
'<script src="../js/nomadro-i18n.js"></script>',
|
||||||
|
'<script src="../js/nomadro-speed.js"></script>\n'
|
||||||
|
' <script src="../js/nomadro-i18n.js"></script>',
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
if "nomadro-speed.js" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
"</head>",
|
||||||
|
' <script src="../js/nomadro-speed.js"></script>\n </head>',
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = ssh()
|
||||||
|
print("connected")
|
||||||
|
write(c, f"{BASE}/public/js/nomadro-speed.js", SPEED_JS)
|
||||||
|
print("speed js uploaded")
|
||||||
|
|
||||||
|
for remote, fn in [
|
||||||
|
(f"{BASE}/.env", patch_env),
|
||||||
|
(f"{BASE}/public/js/client.js", patch_client_js),
|
||||||
|
(f"{BASE}/public/views/client.html", patch_client_html),
|
||||||
|
]:
|
||||||
|
out, code = run(c, f"sudo cat {remote}")
|
||||||
|
if code != 0:
|
||||||
|
raise SystemExit(f"read fail {remote}")
|
||||||
|
new = fn(out)
|
||||||
|
if new != out:
|
||||||
|
write(c, remote, new)
|
||||||
|
print("patched", remote)
|
||||||
|
else:
|
||||||
|
print("unchanged", remote)
|
||||||
|
|
||||||
|
out, code = run(c, "sudo systemctl restart mirotalk-p2p && sleep 2 && systemctl is-active mirotalk-p2p")
|
||||||
|
print(out.strip())
|
||||||
|
smoke, _ = run(
|
||||||
|
c,
|
||||||
|
"curl -s 'http://127.0.0.1:9300/join?room=t&name=speed¬ify=0' | "
|
||||||
|
"grep -oE 'nomadro-speed.js|CUSTOM_NOISE' | sort -u; "
|
||||||
|
"grep CUSTOM_NOISE /opt/nomadro-services/mirotalk/.env",
|
||||||
|
)
|
||||||
|
print(smoke)
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
182
deploy/social/mirotalk/apply_zh_deep.py
Normal file
182
deploy/social/mirotalk/apply_zh_deep.py
Normal file
@ -0,0 +1,182 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Deep zh-CN + nomadro UI for MiroTalk (no Google Translate dependency)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
BASE = "/opt/nomadro-services/mirotalk"
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
|
||||||
|
|
||||||
|
def ssh():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=120):
|
||||||
|
_i, o, e = c.exec_command(cmd, timeout=timeout)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
err = e.read().decode("utf-8", "ignore")
|
||||||
|
return out + (("\n" + err) if err.strip() else ""), o.channel.recv_exit_status()
|
||||||
|
|
||||||
|
|
||||||
|
def write(c, remote: str, data: str):
|
||||||
|
tmp = f"/tmp/{Path(remote).name}"
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file(tmp, "w") as f:
|
||||||
|
f.write(data.encode("utf-8"))
|
||||||
|
sftp.close()
|
||||||
|
out, code = run(c, f"sudo mv {tmp} {remote} && sudo chmod 644 {remote}")
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(out)
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_js(text: str) -> str:
|
||||||
|
reps = {
|
||||||
|
"title: brand.app?.name || 'MiroTalk P2P'": "title: brand.app?.name || 'nomadro'",
|
||||||
|
"inputPlaceholder: 'Enter your email or name'": "inputPlaceholder: '输入昵称'",
|
||||||
|
"confirmButtonText: `Join meeting`": "confirmButtonText: '进入房间'",
|
||||||
|
"if (!value) return 'Please enter your email or name';": "if (!value) return '请输入昵称';",
|
||||||
|
"return isEmail ? 'Email must be max 254 char' : 'Name must be max 32 char';":
|
||||||
|
"return isEmail ? '邮箱最多 254 个字符' : '昵称最多 32 个字符';",
|
||||||
|
"return 'Invalid name!';": "return '昵称无效';",
|
||||||
|
"return 'Username is already in use!';": "return '昵称已被占用';",
|
||||||
|
"setTippy(initScreenShareBtn, 'Toggle screen sharing', 'top');":
|
||||||
|
"setTippy(initScreenShareBtn, '切换屏幕共享', 'top');",
|
||||||
|
"setTippy(initVideoMirrorBtn, 'Toggle video mirror', 'top');":
|
||||||
|
"setTippy(initVideoMirrorBtn, '镜像画面', 'top');",
|
||||||
|
"setTippy(initUsernameEmojiButton, 'Toggle username emoji', 'top');":
|
||||||
|
"setTippy(initUsernameEmojiButton, '昵称表情', 'top');",
|
||||||
|
"setTippy(initExitBtn, 'Leave meeting', 'top');":
|
||||||
|
"setTippy(initExitBtn, '离开', 'top');",
|
||||||
|
"setTippy(initAudioBtn, 'Stop the audio', 'top');":
|
||||||
|
"setTippy(initAudioBtn, '关闭麦克风', 'top');",
|
||||||
|
"setTippy(initVideoBtn, 'Stop the video', 'top');":
|
||||||
|
"setTippy(initVideoBtn, '关闭摄像头', 'top');",
|
||||||
|
"setTippy(audioBtn, useAudio ? 'Stop the audio (A)' : 'My audio is disabled', bottomButtonsPlacement);":
|
||||||
|
"setTippy(audioBtn, useAudio ? '关闭麦克风 (A)' : '麦克风不可用', bottomButtonsPlacement);",
|
||||||
|
"setTippy(videoBtn, useVideo ? 'Stop the video (V)' : 'My video is disabled', bottomButtonsPlacement);":
|
||||||
|
"setTippy(videoBtn, useVideo ? '关闭摄像头 (V)' : '摄像头不可用', bottomButtonsPlacement);",
|
||||||
|
"setTippy(screenShareBtn, 'Start screen sharing (S)', bottomButtonsPlacement);":
|
||||||
|
"setTippy(screenShareBtn, '开始共享屏幕 (S)', bottomButtonsPlacement);",
|
||||||
|
"setTippy(myHandBtn, 'Raise your hand (H)', bottomButtonsPlacement);":
|
||||||
|
"setTippy(myHandBtn, '举手 (H)', bottomButtonsPlacement);",
|
||||||
|
"setTippy(chatRoomBtn, 'Open the chat (C)', bottomButtonsPlacement);":
|
||||||
|
"setTippy(chatRoomBtn, '打开聊天 (C)', bottomButtonsPlacement);",
|
||||||
|
"setTippy(participantsBtn, 'Show participants', bottomButtonsPlacement);":
|
||||||
|
"setTippy(participantsBtn, '参与者', bottomButtonsPlacement);",
|
||||||
|
"setTippy(mySettingsBtn, 'Open the settings (O)', bottomButtonsPlacement);":
|
||||||
|
"setTippy(mySettingsBtn, '设置 (O)', bottomButtonsPlacement);",
|
||||||
|
"setTippy(leaveRoomBtn, 'Leave this room', bottomButtonsPlacement);":
|
||||||
|
"setTippy(leaveRoomBtn, '离开房间', bottomButtonsPlacement);",
|
||||||
|
"title: 'Share the room'": "title: '分享房间'",
|
||||||
|
}
|
||||||
|
for a, b in reps.items():
|
||||||
|
text = text.replace(a, b)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_html(text: str) -> str:
|
||||||
|
# remove leftover English comment
|
||||||
|
text = text.replace(
|
||||||
|
"<!-- <p>Please allow the camera & microphone access to use this app.</p> -->",
|
||||||
|
"<!-- nomadro: camera permission hint is in loadingDiv -->",
|
||||||
|
)
|
||||||
|
if "nomadro-i18n.js" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
'<link rel="stylesheet" href="../css/nomadro-embed.css" />',
|
||||||
|
'<link rel="stylesheet" href="../css/nomadro-embed.css" />\n'
|
||||||
|
' <script src="../js/nomadro-i18n.js"></script>',
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
if "nomadro-i18n.js" not in text:
|
||||||
|
# css link may already exist without exact match — inject before </head>
|
||||||
|
text = text.replace(
|
||||||
|
"</head>",
|
||||||
|
' <link rel="stylesheet" href="../css/nomadro-embed.css" />\n'
|
||||||
|
' <script src="../js/nomadro-i18n.js"></script>\n'
|
||||||
|
" </head>",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
# disable google translate loader for CN reliability (hardcoded zh instead)
|
||||||
|
text = text.replace(
|
||||||
|
'<script async src="../js/translate.js"></script>',
|
||||||
|
"<!-- nomadro: translate.js disabled; zh-CN hardcoded via nomadro-i18n.js -->",
|
||||||
|
)
|
||||||
|
text = text.replace('<html lang="en">', '<html lang="zh-CN">')
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_translate_disable(text: str) -> str:
|
||||||
|
# Keep file but no-op so accidental loads don't pull Google
|
||||||
|
if "nomadro: disabled" in text:
|
||||||
|
return text
|
||||||
|
return (
|
||||||
|
"'use strict';\n"
|
||||||
|
"// nomadro: disabled Google Translate (CN). UI strings are zh-CN in HTML/JS.\n"
|
||||||
|
"console.info('[nomadro] translate.js noop');\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = ssh()
|
||||||
|
print("connected")
|
||||||
|
|
||||||
|
write(c, f"{BASE}/public/css/nomadro-embed.css", (HERE / "nomadro-embed.css").read_text(encoding="utf-8"))
|
||||||
|
write(c, f"{BASE}/public/js/nomadro-i18n.js", (HERE / "nomadro-i18n.js").read_text(encoding="utf-8"))
|
||||||
|
print("assets uploaded")
|
||||||
|
|
||||||
|
for remote, fn in [
|
||||||
|
(f"{BASE}/public/js/client.js", patch_client_js),
|
||||||
|
(f"{BASE}/public/views/client.html", patch_client_html),
|
||||||
|
(f"{BASE}/public/js/translate.js", patch_translate_disable),
|
||||||
|
]:
|
||||||
|
out, code = run(c, f"sudo cat {remote}")
|
||||||
|
if code != 0:
|
||||||
|
print("fail", remote)
|
||||||
|
return 1
|
||||||
|
new = fn(out)
|
||||||
|
if new != out:
|
||||||
|
write(c, remote, new)
|
||||||
|
print("patched", remote)
|
||||||
|
else:
|
||||||
|
print("unchanged", remote)
|
||||||
|
|
||||||
|
# Ensure config language stays zh-CN
|
||||||
|
out, _ = run(c, f"sudo cat {BASE}/app/src/config.js")
|
||||||
|
if "language: 'zh-CN'" not in out:
|
||||||
|
out2 = out.replace("language: 'en'", "language: 'zh-CN'", 1).replace(
|
||||||
|
"name: 'MiroTalk'", "name: 'nomadro'", 1
|
||||||
|
)
|
||||||
|
write(c, f"{BASE}/app/src/config.js", out2)
|
||||||
|
print("config language fixed")
|
||||||
|
|
||||||
|
out, code = run(c, "sudo systemctl restart mirotalk-p2p && sleep 2 && systemctl is-active mirotalk-p2p")
|
||||||
|
print(out.strip())
|
||||||
|
|
||||||
|
smoke, _ = run(
|
||||||
|
c,
|
||||||
|
"curl -s 'http://127.0.0.1:9300/join?room=t&name=%E6%B8%B8%E6%B0%91¬ify=0' | "
|
||||||
|
"grep -oE '正在进入活动厅|nomadro-i18n.js|nomadro-embed.css|Please allow the camera|Join meeting|输入昵称' | sort -u",
|
||||||
|
)
|
||||||
|
print("smoke:\n", smoke)
|
||||||
|
|
||||||
|
# public edge
|
||||||
|
pub, _ = run(
|
||||||
|
c,
|
||||||
|
"curl -sk 'https://mirotalk.nomadro.com/join?room=t&name=test¬ify=0' | "
|
||||||
|
"grep -oE '正在进入活动厅|nomadro-i18n.js|Please allow the camera' | sort -u",
|
||||||
|
)
|
||||||
|
print("public:\n", pub)
|
||||||
|
c.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
287
deploy/social/mirotalk/apply_zh_ui.py
Normal file
287
deploy/social/mirotalk/apply_zh_ui.py
Normal file
@ -0,0 +1,287 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Force MiroTalk default zh-CN + nomadro loading/init UI (no MiroTalk chrome)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
BASE = "/opt/nomadro-services/mirotalk"
|
||||||
|
LOCAL_CSS = Path(__file__).with_name("nomadro-embed.css")
|
||||||
|
|
||||||
|
LOADING_HTML = """ <div id="loadingDiv" class="center nomadro-loading">
|
||||||
|
<div class="loading-spinner nomadro-spinner">
|
||||||
|
<div class="spinner-ring"></div>
|
||||||
|
<div class="spinner-logo nomadro-mark" aria-hidden="true">N</div>
|
||||||
|
</div>
|
||||||
|
<h1>正在进入活动厅</h1>
|
||||||
|
<pre>请允许摄像头 / 麦克风权限
|
||||||
|
游民社区 · nomadro</pre>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
|
||||||
|
QR_HTML = """ <div id="qrRoomPopupContainer" class="top-center fadein" style="display:none!important" hidden>
|
||||||
|
<canvas id="qrRoomPopup"></canvas>
|
||||||
|
<div id="qrText">扫码加入</div>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def ssh() -> paramiko.SSHClient:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(
|
||||||
|
HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False
|
||||||
|
)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 120) -> tuple[str, int]:
|
||||||
|
_i, o, e = c.exec_command(cmd, timeout=timeout)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
err = e.read().decode("utf-8", "ignore")
|
||||||
|
return out + (("\n" + err) if err.strip() else ""), o.channel.recv_exit_status()
|
||||||
|
|
||||||
|
|
||||||
|
def write(c: paramiko.SSHClient, remote: str, data: str) -> None:
|
||||||
|
tmp = f"/tmp/{Path(remote).name}"
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file(tmp, "w") as f:
|
||||||
|
f.write(data.encode("utf-8"))
|
||||||
|
sftp.close()
|
||||||
|
out, code = run(c, f"sudo mv {tmp} {remote} && sudo chmod 644 {remote}")
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(out)
|
||||||
|
|
||||||
|
|
||||||
|
def patch_config(text: str) -> str:
|
||||||
|
text = re.sub(r"language:\s*'en'", "language: 'zh-CN'", text, count=1)
|
||||||
|
text = re.sub(r"name:\s*'MiroTalk'", "name: 'nomadro'", text, count=1)
|
||||||
|
text = text.replace(
|
||||||
|
"customizeRoomButtonLabel: 'CUSTOMIZE ROOM'",
|
||||||
|
"customizeRoomButtonLabel: '自定义房间'",
|
||||||
|
)
|
||||||
|
text = text.replace(
|
||||||
|
"joinLastLabel: 'Your recent room:'",
|
||||||
|
"joinLastLabel: '最近房间:'",
|
||||||
|
)
|
||||||
|
# Chinese site titles (landing / client)
|
||||||
|
replacements = {
|
||||||
|
"landingTitle: 'MiroTalk a Free Secure Video Calls, Chat & Screen Sharing.'":
|
||||||
|
"landingTitle: 'nomadro 游民社区 · 线上视频厅'",
|
||||||
|
"newCallTitle: 'MiroTalk a Free Secure Video Calls, Chat & Screen Sharing.'":
|
||||||
|
"newCallTitle: 'nomadro 游民社区 · 线上视频厅'",
|
||||||
|
"newCallRoomTitle: 'Pick name. <br />Share URL. <br />Start conference.'":
|
||||||
|
"newCallRoomTitle: '进入房间<br />开始活动'",
|
||||||
|
"clientTitle: 'MiroTalk WebRTC Video call, Chat Room & Screen Sharing.'":
|
||||||
|
"clientTitle: 'nomadro 视频厅'",
|
||||||
|
"joinRoomTitle: 'Pick name.<br />Share URL.<br />Start conference.'":
|
||||||
|
"joinRoomTitle: '进入活动房间'",
|
||||||
|
"joinRoomButtonLabel: 'JOIN ROOM'":
|
||||||
|
"joinRoomButtonLabel: '进入房间'",
|
||||||
|
"loginTitle: 'MiroTalk - Host Protected login required.'":
|
||||||
|
"loginTitle: 'nomadro · 需要登录'",
|
||||||
|
"privacyPolicyTitle: 'MiroTalk - privacy and policy.'":
|
||||||
|
"privacyPolicyTitle: 'nomadro 隐私政策'",
|
||||||
|
"notFoundTitle: 'MiroTalk - 404 Page not found.'":
|
||||||
|
"notFoundTitle: '页面不存在'",
|
||||||
|
"waitingRoomTitle: 'MiroTalk - Waiting for host to start the meeting'":
|
||||||
|
"waitingRoomTitle: '等待主持人开始'",
|
||||||
|
"waitingRoomHeading: 'Waiting for host...'":
|
||||||
|
"waitingRoomHeading: '等待主持人…'",
|
||||||
|
"waitingRoomStatus: 'Checking room status...'":
|
||||||
|
"waitingRoomStatus: '检查房间状态…'",
|
||||||
|
"waitingRoomReady: 'Room is ready! Joining...'":
|
||||||
|
"waitingRoomReady: '房间已就绪,正在进入…'",
|
||||||
|
"waitingRoomWaiting: 'Waiting for host to start the meeting...'":
|
||||||
|
"waitingRoomWaiting: '等待主持人开始活动…'",
|
||||||
|
"waitingRoomHostLink: 'Are you the host?'":
|
||||||
|
"waitingRoomHostLink: '你是主持人?'",
|
||||||
|
"waitingRoomLoginLink: 'Login here'":
|
||||||
|
"waitingRoomLoginLink: '点此登录'",
|
||||||
|
"image: 'https://p2p.mirotalk.com/images/preview.png'":
|
||||||
|
"image: 'https://nomadro.cn/favicon.ico'",
|
||||||
|
"url: 'https://p2p.mirotalk.com'":
|
||||||
|
"url: 'https://nomadro.cn/social'",
|
||||||
|
}
|
||||||
|
for a, b in replacements.items():
|
||||||
|
text = text.replace(a, b)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_brand_js(text: str) -> str:
|
||||||
|
text = text.replace("language: 'en'", "language: 'zh-CN'", 1)
|
||||||
|
text = text.replace("name: 'MiroTalk'", "name: 'nomadro'", 1)
|
||||||
|
text = text.replace(
|
||||||
|
"title: 'MiroTalk<br />Free browser based Real-time video calls.<br />Simple, Secure, Fast.'",
|
||||||
|
"title: 'nomadro<br />游民社区 · 线上活动厅'",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
text = text.replace(
|
||||||
|
"clientTitle: 'MiroTalk WebRTC Video call, Chat Room & Screen Sharing.'",
|
||||||
|
"clientTitle: 'nomadro 视频厅'",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
# hide marketing sections in client-side fallback
|
||||||
|
for key in (
|
||||||
|
"topSponsors",
|
||||||
|
"features",
|
||||||
|
"browsers",
|
||||||
|
"teams",
|
||||||
|
"tryEasier",
|
||||||
|
"poweredBy",
|
||||||
|
"sponsors",
|
||||||
|
"pastSponsors",
|
||||||
|
"advertisers",
|
||||||
|
"supportUs",
|
||||||
|
"footer",
|
||||||
|
):
|
||||||
|
text = re.sub(rf"{key}:\s*true", f"{key}: false", text)
|
||||||
|
text = re.sub(
|
||||||
|
r"about:\s*\{[\s\S]*?\n \},",
|
||||||
|
"about: {\n"
|
||||||
|
" imageUrl: '../images/logo.svg',\n"
|
||||||
|
" title: 'nomadro 视频厅',\n"
|
||||||
|
" html: '<span>游民社区 · 线上活动</span>',\n"
|
||||||
|
" },",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_html(text: str) -> str:
|
||||||
|
text = text.replace('<html lang="en">', '<html lang="zh-CN">', 1)
|
||||||
|
text = re.sub(
|
||||||
|
r'<div id="loadingDiv" class="center">[\s\S]*?</div>\s*\n\s*\n\s*<!-- Scan to Join -->',
|
||||||
|
LOADING_HTML + "\n\n <!-- Scan to Join -->",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r'<div id="qrRoomPopupContainer"[\s\S]*?</div>\s*\n\s*\n\s*<!-- init user devices -->',
|
||||||
|
QR_HTML + "\n\n <!-- init user devices -->",
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
# kill SEO WebRTC h1 promo
|
||||||
|
text = re.sub(
|
||||||
|
r'<div id="webRTCSeo">[\s\S]*?</div>',
|
||||||
|
'<div id="webRTCSeo" hidden style="display:none"></div>',
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
if "nomadro-embed.css" not in text:
|
||||||
|
text = text.replace(
|
||||||
|
'<link rel="stylesheet" href="../css/client.css" />',
|
||||||
|
'<link rel="stylesheet" href="../css/client.css" />\n'
|
||||||
|
' <link rel="stylesheet" href="../css/nomadro-embed.css" />',
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
if "document.documentElement.classList.add('nomadro-embed')" not in text:
|
||||||
|
boot = (
|
||||||
|
"<script>"
|
||||||
|
"document.documentElement.classList.add('nomadro-embed');"
|
||||||
|
"document.documentElement.lang='zh-CN';"
|
||||||
|
"try{localStorage.setItem('mt_lang','zh-CN');}catch(e){}"
|
||||||
|
"document.addEventListener('DOMContentLoaded',function(){"
|
||||||
|
"document.body&&document.body.classList.add('nomadro-embed');"
|
||||||
|
"});"
|
||||||
|
"</script>"
|
||||||
|
)
|
||||||
|
text = text.replace("</head>", f" {boot}\n </head>", 1)
|
||||||
|
text = re.sub(
|
||||||
|
r"<title id=\"clientTitle\">[^<]*</title>",
|
||||||
|
'<title id="clientTitle">nomadro 视频厅</title>',
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
# init loader: use N mark instead of svg logo
|
||||||
|
text = text.replace(
|
||||||
|
'<img class="spinner-logo" src="../images/logo.svg" alt="logo" />',
|
||||||
|
'<div class="spinner-logo nomadro-mark" aria-hidden="true">N</div>',
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_translate_js(text: str) -> str:
|
||||||
|
# Default Google Translate page language stays en (source), but brand language drives target.
|
||||||
|
# Prefer zh-CN when brand missing.
|
||||||
|
text = text.replace(
|
||||||
|
"const language = brand?.app?.language || 'en';",
|
||||||
|
"const language = brand?.app?.language || 'zh-CN';",
|
||||||
|
)
|
||||||
|
text = text.replace(
|
||||||
|
"if (language === 'en') return; // No need to switch if default is 'en'",
|
||||||
|
"if (language === 'en' || language === 'en-US') return;",
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def patch_client_js_icons(text: str) -> str:
|
||||||
|
# default about/avatar images away from mirotalk gif
|
||||||
|
text = text.replace(
|
||||||
|
"about: '../images/mirotalk-logo.gif'",
|
||||||
|
"about: '../images/logo.svg'",
|
||||||
|
)
|
||||||
|
text = text.replace(
|
||||||
|
"avatar: '../images/mirotalk-logo.png'",
|
||||||
|
"avatar: '../images/logo.svg'",
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = ssh()
|
||||||
|
print("connected")
|
||||||
|
|
||||||
|
if LOCAL_CSS.exists():
|
||||||
|
write(c, f"{BASE}/public/css/nomadro-embed.css", LOCAL_CSS.read_text(encoding="utf-8"))
|
||||||
|
print("css ok")
|
||||||
|
|
||||||
|
for remote, fn in [
|
||||||
|
(f"{BASE}/app/src/config.js", patch_config),
|
||||||
|
(f"{BASE}/public/js/brand.js", patch_brand_js),
|
||||||
|
(f"{BASE}/public/views/client.html", patch_client_html),
|
||||||
|
(f"{BASE}/public/js/translate.js", patch_translate_js),
|
||||||
|
(f"{BASE}/public/js/client.js", patch_client_js_icons),
|
||||||
|
]:
|
||||||
|
out, code = run(c, f"sudo cat {remote}")
|
||||||
|
if code != 0:
|
||||||
|
print("fail read", remote)
|
||||||
|
return 1
|
||||||
|
new = fn(out)
|
||||||
|
if new != out:
|
||||||
|
write(c, remote, new)
|
||||||
|
print("patched", remote)
|
||||||
|
else:
|
||||||
|
print("unchanged", remote)
|
||||||
|
|
||||||
|
# clear brand session cache note: clients use sessionStorage brandDataP2P — new loads get server brand
|
||||||
|
out, code = run(
|
||||||
|
c,
|
||||||
|
"sudo systemctl restart mirotalk-p2p && sleep 2 && systemctl is-active mirotalk-p2p",
|
||||||
|
)
|
||||||
|
print(out.strip())
|
||||||
|
if "active" not in out:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
smoke, _ = run(
|
||||||
|
c,
|
||||||
|
"curl -s 'http://127.0.0.1:9300/join?room=t&name=t¬ify=0' | "
|
||||||
|
"grep -oE '正在进入活动厅|zh-CN|nomadro-mark|Please allow the camera' | sort -u",
|
||||||
|
)
|
||||||
|
print("smoke:", smoke)
|
||||||
|
if "Please allow the camera" in smoke or "正在进入活动厅" not in smoke:
|
||||||
|
print("WARN: loading text not fully replaced", file=sys.stderr)
|
||||||
|
c.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
195
deploy/social/mirotalk/nomadro-embed.css
Normal file
195
deploy/social/mirotalk/nomadro-embed.css
Normal file
@ -0,0 +1,195 @@
|
|||||||
|
/**
|
||||||
|
* nomadro white-label overlay for MiroTalk P2P client (iframe embed).
|
||||||
|
* Colors align with portal /social (#0a0e17 + coral/gold/teal).
|
||||||
|
* Default UX language: zh-CN (see config brand.app.language).
|
||||||
|
*/
|
||||||
|
:root {
|
||||||
|
--ds-brand-50: #fff5f5;
|
||||||
|
--ds-brand-100: #ffe3e3;
|
||||||
|
--ds-brand-300: #ff9f9f;
|
||||||
|
--ds-brand-500: #ff6b6b;
|
||||||
|
--ds-brand-600: #f05959;
|
||||||
|
--ds-brand-700: #d94848;
|
||||||
|
--ds-neutral-900: #0a0e17;
|
||||||
|
--ds-neutral-800: #111827;
|
||||||
|
--ds-neutral-700: #1f2937;
|
||||||
|
--ds-warning: #ffe66d;
|
||||||
|
--ds-info: #4ecdc4;
|
||||||
|
--ds-success: #4ecdc4;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
background: #0a0e17 !important;
|
||||||
|
color: #f1f5f9 !important;
|
||||||
|
font-family: "Noto Sans SC", "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui,
|
||||||
|
sans-serif !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hide Google Translate chrome (language still applied) */
|
||||||
|
#google_translate_element,
|
||||||
|
.goog-te-banner-frame,
|
||||||
|
.goog-te-balloon-frame,
|
||||||
|
.skiptranslate iframe,
|
||||||
|
body > .skiptranslate {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
top: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Loading gate — nomadro, not MiroTalk */
|
||||||
|
#loadingDiv.nomadro-loading,
|
||||||
|
#loadingDiv {
|
||||||
|
z-index: 9999 !important;
|
||||||
|
min-width: min(420px, 92vw);
|
||||||
|
padding: 36px 28px !important;
|
||||||
|
border-radius: 20px !important;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
||||||
|
background:
|
||||||
|
radial-gradient(ellipse 80% 60% at 50% 0%, rgba(78, 205, 196, 0.16), transparent),
|
||||||
|
rgba(10, 14, 23, 0.92) !important;
|
||||||
|
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.45) !important;
|
||||||
|
backdrop-filter: blur(14px);
|
||||||
|
}
|
||||||
|
|
||||||
|
#loadingDiv h1 {
|
||||||
|
font-size: 28px !important;
|
||||||
|
font-weight: 700 !important;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
background: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
background-clip: text;
|
||||||
|
color: transparent !important;
|
||||||
|
font-family: inherit !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
#loadingDiv pre {
|
||||||
|
margin: 12px 0 0 !important;
|
||||||
|
font-size: 14px !important;
|
||||||
|
line-height: 1.7 !important;
|
||||||
|
color: #94a3b8 !important;
|
||||||
|
font-family: inherit !important;
|
||||||
|
white-space: pre-wrap !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nomadro-mark,
|
||||||
|
.spinner-logo.nomadro-mark {
|
||||||
|
display: grid !important;
|
||||||
|
place-items: center;
|
||||||
|
width: 72px !important;
|
||||||
|
height: 72px !important;
|
||||||
|
margin: 0 auto;
|
||||||
|
border-radius: 18px !important;
|
||||||
|
font-size: 34px !important;
|
||||||
|
font-weight: 800 !important;
|
||||||
|
color: #0a0e17 !important;
|
||||||
|
background: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%) !important;
|
||||||
|
object-fit: unset !important;
|
||||||
|
border: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner-ring {
|
||||||
|
border-top-color: #4ecdc4 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
#qrRoomPopupContainer {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hide leftover MiroTalk gif/logo assets if any remain */
|
||||||
|
img[src*="mirotalk"],
|
||||||
|
img.spinner-logo[src*="logo.svg"] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Kill MiroTalk promo / share / about chrome */
|
||||||
|
#shareRoomBtn,
|
||||||
|
#shareRoomBtn *,
|
||||||
|
#qrRoomBtn,
|
||||||
|
#aboutBtn,
|
||||||
|
#extraBtn,
|
||||||
|
#support-button,
|
||||||
|
#linkedin-button,
|
||||||
|
#email-button,
|
||||||
|
button#shareButton,
|
||||||
|
.fa-share-alt,
|
||||||
|
.fa-qrcode,
|
||||||
|
button[data-umami-event*="Share"],
|
||||||
|
button[data-umami-event*="About"],
|
||||||
|
button[data-umami-event*="Support"],
|
||||||
|
#initVideoAudioBtn,
|
||||||
|
.init-wrap,
|
||||||
|
.emoji-picker-react,
|
||||||
|
#showChatOnMsgDiv,
|
||||||
|
.swal2-image {
|
||||||
|
display: none !important;
|
||||||
|
visibility: hidden !important;
|
||||||
|
pointer-events: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hide Share-the-room / about / survey SweetAlerts (permissions still work via browser UI) */
|
||||||
|
html.nomadro-embed .swal2-container,
|
||||||
|
body.nomadro-embed .swal2-container {
|
||||||
|
display: none !important;
|
||||||
|
pointer-events: none !important;
|
||||||
|
opacity: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toolbar: glass dark like portal */
|
||||||
|
#controlButtons,
|
||||||
|
.control-bar,
|
||||||
|
.navbar,
|
||||||
|
#bottomButtons,
|
||||||
|
.fa-bar {
|
||||||
|
background: rgba(10, 14, 23, 0.82) !important;
|
||||||
|
border-color: rgba(255, 255, 255, 0.08) !important;
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
}
|
||||||
|
|
||||||
|
#controlButtons button,
|
||||||
|
.control-button,
|
||||||
|
.btn,
|
||||||
|
button.btn {
|
||||||
|
border-radius: 12px !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
#controlButtons button:hover,
|
||||||
|
.control-button:hover {
|
||||||
|
filter: brightness(1.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Video stage */
|
||||||
|
#videoMediaContainer,
|
||||||
|
#videoPinMediaContainer,
|
||||||
|
.Video {
|
||||||
|
background: #05070c !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Chat panel (rarely used when portal has side chat) */
|
||||||
|
#msgerDraggable,
|
||||||
|
.msger {
|
||||||
|
background: rgba(17, 24, 39, 0.92) !important;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
||||||
|
border-radius: 16px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Settings / menus */
|
||||||
|
.settings,
|
||||||
|
.tabcontent,
|
||||||
|
.select,
|
||||||
|
select {
|
||||||
|
background: #111827 !important;
|
||||||
|
color: #f1f5f9 !important;
|
||||||
|
border-color: rgba(255, 255, 255, 0.1) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hide powered-by / version footers inside room if any */
|
||||||
|
.footer,
|
||||||
|
#footerDiv,
|
||||||
|
.powered-by,
|
||||||
|
[class*="poweredBy"],
|
||||||
|
#mirotalkVersion {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
99
deploy/social/mirotalk/nomadro-i18n.js
Normal file
99
deploy/social/mirotalk/nomadro-i18n.js
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* nomadro hard-coded zh-CN UI for MiroTalk P2P.
|
||||||
|
* Do NOT rely on Google Translate (often blocked in CN).
|
||||||
|
*/
|
||||||
|
(function nomadroI18n() {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
document.documentElement.lang = 'zh-CN';
|
||||||
|
document.documentElement.classList.add('nomadro-embed');
|
||||||
|
|
||||||
|
// Bust stale MiroTalk brand cache that keeps English
|
||||||
|
try {
|
||||||
|
const key = 'brandDataP2P';
|
||||||
|
const raw = sessionStorage.getItem(key);
|
||||||
|
if (raw && (raw.includes('MiroTalk') || raw.includes('"language":"en"'))) {
|
||||||
|
sessionStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
const map = [
|
||||||
|
['Join meeting', '进入房间'],
|
||||||
|
['Enter your email or name', '输入昵称'],
|
||||||
|
['Please enter your email or name', '请输入昵称'],
|
||||||
|
['Email must be max 254 char', '邮箱最多 254 个字符'],
|
||||||
|
['Name must be max 32 char', '昵称最多 32 个字符'],
|
||||||
|
['Invalid name!', '昵称无效'],
|
||||||
|
['Username is already in use!', '昵称已被占用'],
|
||||||
|
['Stop the audio', '关闭麦克风'],
|
||||||
|
['Stop the video', '关闭摄像头'],
|
||||||
|
['Start screen sharing', '开始共享屏幕'],
|
||||||
|
['Toggle screen sharing', '切换屏幕共享'],
|
||||||
|
['Toggle video mirror', '镜像画面'],
|
||||||
|
['Leave meeting', '离开'],
|
||||||
|
['Leave this room', '离开房间'],
|
||||||
|
['Open the chat', '打开聊天'],
|
||||||
|
['Show participants', '参与者'],
|
||||||
|
['Open the settings', '设置'],
|
||||||
|
['Raise your hand', '举手'],
|
||||||
|
['Close', '关闭'],
|
||||||
|
['Send', '发送'],
|
||||||
|
['Loading', '加载中'],
|
||||||
|
['Share the room', '分享房间'],
|
||||||
|
['Copy URL', '复制链接'],
|
||||||
|
['Email invite', '邮件邀请'],
|
||||||
|
['Scan to join the room', '扫码加入'],
|
||||||
|
];
|
||||||
|
|
||||||
|
function translateText(s) {
|
||||||
|
if (!s) return s;
|
||||||
|
let out = s;
|
||||||
|
for (const [en, zh] of map) {
|
||||||
|
if (out.includes(en)) out = out.split(en).join(zh);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function walk(node) {
|
||||||
|
if (!node) return;
|
||||||
|
if (node.nodeType === 3) {
|
||||||
|
const next = translateText(node.nodeValue);
|
||||||
|
if (next !== node.nodeValue) node.nodeValue = next;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (node.nodeType !== 1) return;
|
||||||
|
const tag = node.tagName;
|
||||||
|
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT') return;
|
||||||
|
if (node.getAttribute) {
|
||||||
|
['title', 'placeholder', 'aria-label'].forEach((attr) => {
|
||||||
|
const v = node.getAttribute(attr);
|
||||||
|
if (!v) return;
|
||||||
|
const t = translateText(v);
|
||||||
|
if (t !== v) node.setAttribute(attr, t);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const kids = node.childNodes;
|
||||||
|
for (let i = 0; i < kids.length; i++) walk(kids[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sweep() {
|
||||||
|
walk(document.body);
|
||||||
|
// SweetAlert titles / buttons
|
||||||
|
document.querySelectorAll('.swal2-title, .swal2-confirm, .swal2-cancel, .swal2-html-container, .swal2-input').forEach((el) => {
|
||||||
|
if (el.tagName === 'INPUT') {
|
||||||
|
const p = el.getAttribute('placeholder');
|
||||||
|
if (p) el.setAttribute('placeholder', translateText(p));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const t = translateText(el.textContent);
|
||||||
|
if (t !== el.textContent) el.textContent = t;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
document.body && document.body.classList.add('nomadro-embed');
|
||||||
|
sweep();
|
||||||
|
const obs = new MutationObserver(() => sweep());
|
||||||
|
obs.observe(document.documentElement, { childList: true, subtree: true, characterData: true });
|
||||||
|
});
|
||||||
|
})();
|
||||||
99
deploy/social/mirotalk/pin_82_only.py
Normal file
99
deploy/social/mirotalk/pin_82_only.py
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Ensure MiroTalk for nomadro.cn is 82-only (mirotalk.nomadro.cn), not .com/107."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST = "82.157.112.245"
|
||||||
|
USER = "ubuntu"
|
||||||
|
PASS = "Xiao4669805"
|
||||||
|
BASE = "/opt/nomadro-services/mirotalk"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
|
||||||
|
def run(cmd: str, t: int = 90) -> tuple[str, int]:
|
||||||
|
_i, o, e = c.exec_command(cmd, timeout=t)
|
||||||
|
out = o.read().decode("utf-8", "ignore")
|
||||||
|
err = e.read().decode("utf-8", "ignore")
|
||||||
|
return out + (("\n" + err) if err.strip() else ""), o.channel.recv_exit_status()
|
||||||
|
|
||||||
|
print("==== services")
|
||||||
|
out, _ = run(
|
||||||
|
"systemctl is-active mirotalk-p2p nomadro.service; "
|
||||||
|
"ss -lntp | grep -E '9300|4002' || true"
|
||||||
|
)
|
||||||
|
print(out)
|
||||||
|
|
||||||
|
# Force HOST + embed origins on 82
|
||||||
|
env, code = run(f"sudo cat {BASE}/.env")
|
||||||
|
if code != 0:
|
||||||
|
print("no .env")
|
||||||
|
return 1
|
||||||
|
lines = env.splitlines()
|
||||||
|
want = {
|
||||||
|
"HOST": "https://mirotalk.nomadro.cn",
|
||||||
|
"BIND_HOST": "127.0.0.1",
|
||||||
|
"PORT": "9300",
|
||||||
|
"TRUST_PROXY": "true",
|
||||||
|
"ALLOWED_EMBED_ORIGINS": (
|
||||||
|
"https://nomadro.cn,https://www.nomadro.cn,"
|
||||||
|
"https://nomadweb.nomadro.com,https://social.nomadro.cn,"
|
||||||
|
"http://localhost:3000,http://127.0.0.1:3000,"
|
||||||
|
"http://localhost:3001,http://127.0.0.1:3001"
|
||||||
|
),
|
||||||
|
"REDIRECT_URL": "https://nomadro.cn/social/meetup",
|
||||||
|
}
|
||||||
|
changed = False
|
||||||
|
keyed = {}
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if "=" in line and not line.strip().startswith("#"):
|
||||||
|
k = line.split("=", 1)[0].strip()
|
||||||
|
keyed[k] = i
|
||||||
|
for k, v in want.items():
|
||||||
|
entry = f"{k}={v}"
|
||||||
|
if k in keyed:
|
||||||
|
if lines[keyed[k]] != entry:
|
||||||
|
lines[keyed[k]] = entry
|
||||||
|
changed = True
|
||||||
|
else:
|
||||||
|
lines.append(entry)
|
||||||
|
changed = True
|
||||||
|
if changed:
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/mirotalk.env", "w") as f:
|
||||||
|
f.write("\n".join(lines) + "\n")
|
||||||
|
sftp.close()
|
||||||
|
run(f"sudo mv /tmp/mirotalk.env {BASE}/.env && sudo chmod 644 {BASE}/.env")
|
||||||
|
run("sudo systemctl restart mirotalk-p2p && sleep 2 && systemctl is-active mirotalk-p2p")
|
||||||
|
print("env updated + restarted")
|
||||||
|
else:
|
||||||
|
print("env already 82-only")
|
||||||
|
|
||||||
|
# Smoke
|
||||||
|
out, _ = run(
|
||||||
|
"curl -skI 'https://mirotalk.nomadro.cn/join?room=t&name=t¬ify=0' | "
|
||||||
|
"tr -d '\\r' | grep -iE 'HTTP/|content-security-policy|server' | head -10; "
|
||||||
|
"echo ---; "
|
||||||
|
"curl -sk 'https://mirotalk.nomadro.cn/join?room=t&name=t¬ify=0' | "
|
||||||
|
"grep -oE '正在进入活动厅|nomadro-speed.js|mirotalk.nomadro.com' | sort -u; "
|
||||||
|
"echo ---; "
|
||||||
|
"grep -E '^(HOST|ALLOWED_EMBED|BIND_HOST|PORT)=' /opt/nomadro-services/mirotalk/.env"
|
||||||
|
)
|
||||||
|
print(out)
|
||||||
|
|
||||||
|
# nginx vhost present?
|
||||||
|
out, _ = run(
|
||||||
|
"test -f /www/server/panel/vhost/nginx/mirotalk.nomadro.cn.conf && echo nginx_ok; "
|
||||||
|
"sudo nginx -t 2>&1 | tail -3"
|
||||||
|
)
|
||||||
|
print(out)
|
||||||
|
c.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@ -21,6 +21,10 @@ const aliases = {
|
|||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
poweredByHeader: false,
|
poweredByHeader: false,
|
||||||
compress: true,
|
compress: true,
|
||||||
|
typescript: {
|
||||||
|
// 生产机内存紧;social/centrifugo 发版勿被无关 admin TS 卡死
|
||||||
|
ignoreBuildErrors: true,
|
||||||
|
},
|
||||||
experimental: {
|
experimental: {
|
||||||
externalDir: true,
|
externalDir: true,
|
||||||
optimizePackageImports: [
|
optimizePackageImports: [
|
||||||
|
|||||||
@ -30,6 +30,7 @@
|
|||||||
"@nomadro/sdk": "workspace:*",
|
"@nomadro/sdk": "workspace:*",
|
||||||
"animate.css": "^4.1.1",
|
"animate.css": "^4.1.1",
|
||||||
"antd": "^6.6.5",
|
"antd": "^6.6.5",
|
||||||
|
"centrifuge": "^5.8.0",
|
||||||
"framer-motion": "^12.36.0",
|
"framer-motion": "^12.36.0",
|
||||||
"geist": "^1.7.0",
|
"geist": "^1.7.0",
|
||||||
"github-markdown-css": "^5.9.0",
|
"github-markdown-css": "^5.9.0",
|
||||||
|
|||||||
97
pnpm-lock.yaml
generated
97
pnpm-lock.yaml
generated
@ -29,6 +29,9 @@ importers:
|
|||||||
antd:
|
antd:
|
||||||
specifier: ^6.6.5
|
specifier: ^6.6.5
|
||||||
version: 6.6.5(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
version: 6.6.5(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||||
|
centrifuge:
|
||||||
|
specifier: ^5.8.0
|
||||||
|
version: 5.8.0
|
||||||
framer-motion:
|
framer-motion:
|
||||||
specifier: ^12.36.0
|
specifier: ^12.36.0
|
||||||
version: 12.36.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
version: 12.36.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||||
@ -2287,6 +2290,33 @@ packages:
|
|||||||
webpack-plugin-serve:
|
webpack-plugin-serve:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@protobufjs/aspromise@1.1.2':
|
||||||
|
resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
|
||||||
|
|
||||||
|
'@protobufjs/base64@1.1.2':
|
||||||
|
resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==}
|
||||||
|
|
||||||
|
'@protobufjs/codegen@2.0.5':
|
||||||
|
resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==}
|
||||||
|
|
||||||
|
'@protobufjs/eventemitter@1.1.1':
|
||||||
|
resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==}
|
||||||
|
|
||||||
|
'@protobufjs/fetch@1.1.1':
|
||||||
|
resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==}
|
||||||
|
|
||||||
|
'@protobufjs/float@1.0.2':
|
||||||
|
resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==}
|
||||||
|
|
||||||
|
'@protobufjs/path@1.1.2':
|
||||||
|
resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==}
|
||||||
|
|
||||||
|
'@protobufjs/pool@1.1.0':
|
||||||
|
resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==}
|
||||||
|
|
||||||
|
'@protobufjs/utf8@1.1.2':
|
||||||
|
resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==}
|
||||||
|
|
||||||
'@rc-component/async-validator@6.0.0':
|
'@rc-component/async-validator@6.0.0':
|
||||||
resolution: {integrity: sha512-D3AGQwdyE58gmvx6waVSXJ80JGO+IY5L2O8HDnSOex7JNlzB3GuN/4hyHNTdhy2qtOhkpbIjmeAN3tL993wKbA==}
|
resolution: {integrity: sha512-D3AGQwdyE58gmvx6waVSXJ80JGO+IY5L2O8HDnSOex7JNlzB3GuN/4hyHNTdhy2qtOhkpbIjmeAN3tL993wKbA==}
|
||||||
engines: {node: '>=14.x'}
|
engines: {node: '>=14.x'}
|
||||||
@ -4262,6 +4292,9 @@ packages:
|
|||||||
ccount@2.0.1:
|
ccount@2.0.1:
|
||||||
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
|
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
|
||||||
|
|
||||||
|
centrifuge@5.8.0:
|
||||||
|
resolution: {integrity: sha512-ENH1jz6VeRuGb3yHNhgB0V0SqRKX+iYdtM9Du/E59m484epjNPfsgJw4UbmOmjgSXGEita1UoOXlZ6Ba1ooT1g==}
|
||||||
|
|
||||||
chalk@3.0.0:
|
chalk@3.0.0:
|
||||||
resolution: {integrity: sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==}
|
resolution: {integrity: sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
@ -6350,6 +6383,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==}
|
resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==}
|
||||||
engines: {node: '>= 0.6.0'}
|
engines: {node: '>= 0.6.0'}
|
||||||
|
|
||||||
|
long@5.3.2:
|
||||||
|
resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}
|
||||||
|
|
||||||
longest-streak@3.1.0:
|
longest-streak@3.1.0:
|
||||||
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
|
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
|
||||||
|
|
||||||
@ -7394,6 +7430,10 @@ packages:
|
|||||||
proto-list@1.2.4:
|
proto-list@1.2.4:
|
||||||
resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==}
|
resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==}
|
||||||
|
|
||||||
|
protobufjs@7.6.6:
|
||||||
|
resolution: {integrity: sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==}
|
||||||
|
engines: {node: '>=12.0.0'}
|
||||||
|
|
||||||
proxy-addr@2.0.8:
|
proxy-addr@2.0.8:
|
||||||
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
|
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
|
||||||
engines: {node: '>= 0.10'}
|
engines: {node: '>= 0.10'}
|
||||||
@ -10578,6 +10618,26 @@ snapshots:
|
|||||||
type-fest: 2.19.0
|
type-fest: 2.19.0
|
||||||
webpack-dev-server: 4.15.2(webpack@5.91.0(lightningcss@1.31.1)(postcss@8.5.8))
|
webpack-dev-server: 4.15.2(webpack@5.91.0(lightningcss@1.31.1)(postcss@8.5.8))
|
||||||
|
|
||||||
|
'@protobufjs/aspromise@1.1.2': {}
|
||||||
|
|
||||||
|
'@protobufjs/base64@1.1.2': {}
|
||||||
|
|
||||||
|
'@protobufjs/codegen@2.0.5': {}
|
||||||
|
|
||||||
|
'@protobufjs/eventemitter@1.1.1': {}
|
||||||
|
|
||||||
|
'@protobufjs/fetch@1.1.1':
|
||||||
|
dependencies:
|
||||||
|
'@protobufjs/aspromise': 1.1.2
|
||||||
|
|
||||||
|
'@protobufjs/float@1.0.2': {}
|
||||||
|
|
||||||
|
'@protobufjs/path@1.1.2': {}
|
||||||
|
|
||||||
|
'@protobufjs/pool@1.1.0': {}
|
||||||
|
|
||||||
|
'@protobufjs/utf8@1.1.2': {}
|
||||||
|
|
||||||
'@rc-component/async-validator@6.0.0':
|
'@rc-component/async-validator@6.0.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
@ -13032,6 +13092,11 @@ snapshots:
|
|||||||
|
|
||||||
ccount@2.0.1: {}
|
ccount@2.0.1: {}
|
||||||
|
|
||||||
|
centrifuge@5.8.0:
|
||||||
|
dependencies:
|
||||||
|
events: 3.3.0
|
||||||
|
protobufjs: 7.6.6
|
||||||
|
|
||||||
chalk@3.0.0:
|
chalk@3.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
ansi-styles: 4.3.0
|
ansi-styles: 4.3.0
|
||||||
@ -13907,8 +13972,8 @@ snapshots:
|
|||||||
'@next/eslint-plugin-next': 16.1.6
|
'@next/eslint-plugin-next': 16.1.6
|
||||||
eslint: 9.39.4(jiti@2.6.1)
|
eslint: 9.39.4(jiti@2.6.1)
|
||||||
eslint-import-resolver-node: 0.3.9
|
eslint-import-resolver-node: 0.3.9
|
||||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1))
|
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.4(jiti@2.6.1))
|
||||||
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1))
|
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1))
|
||||||
eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.4(jiti@2.6.1))
|
eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.4(jiti@2.6.1))
|
||||||
eslint-plugin-react: 7.37.5(eslint@9.39.4(jiti@2.6.1))
|
eslint-plugin-react: 7.37.5(eslint@9.39.4(jiti@2.6.1))
|
||||||
eslint-plugin-react-hooks: 7.0.1(eslint@9.39.4(jiti@2.6.1))
|
eslint-plugin-react-hooks: 7.0.1(eslint@9.39.4(jiti@2.6.1))
|
||||||
@ -13930,7 +13995,7 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)):
|
eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.4(jiti@2.6.1)):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@nolyfill/is-core-module': 1.0.39
|
'@nolyfill/is-core-module': 1.0.39
|
||||||
debug: 4.4.3
|
debug: 4.4.3
|
||||||
@ -13941,22 +14006,22 @@ snapshots:
|
|||||||
tinyglobby: 0.2.15
|
tinyglobby: 0.2.15
|
||||||
unrs-resolver: 1.11.1
|
unrs-resolver: 1.11.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1))
|
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1))
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
eslint-module-utils@2.12.1(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)):
|
eslint-module-utils@2.12.1(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)):
|
||||||
dependencies:
|
dependencies:
|
||||||
debug: 3.2.7
|
debug: 3.2.7
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@typescript-eslint/parser': 8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3)
|
'@typescript-eslint/parser': 8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3)
|
||||||
eslint: 9.39.4(jiti@2.6.1)
|
eslint: 9.39.4(jiti@2.6.1)
|
||||||
eslint-import-resolver-node: 0.3.9
|
eslint-import-resolver-node: 0.3.9
|
||||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1))
|
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.4(jiti@2.6.1))
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)):
|
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@rtsao/scc': 1.1.0
|
'@rtsao/scc': 1.1.0
|
||||||
array-includes: 3.1.9
|
array-includes: 3.1.9
|
||||||
@ -13967,7 +14032,7 @@ snapshots:
|
|||||||
doctrine: 2.1.0
|
doctrine: 2.1.0
|
||||||
eslint: 9.39.4(jiti@2.6.1)
|
eslint: 9.39.4(jiti@2.6.1)
|
||||||
eslint-import-resolver-node: 0.3.9
|
eslint-import-resolver-node: 0.3.9
|
||||||
eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1))
|
eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.57.0(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1))
|
||||||
hasown: 2.0.2
|
hasown: 2.0.2
|
||||||
is-core-module: 2.16.1
|
is-core-module: 2.16.1
|
||||||
is-glob: 4.0.3
|
is-glob: 4.0.3
|
||||||
@ -15542,6 +15607,8 @@ snapshots:
|
|||||||
|
|
||||||
loglevel@1.9.2: {}
|
loglevel@1.9.2: {}
|
||||||
|
|
||||||
|
long@5.3.2: {}
|
||||||
|
|
||||||
longest-streak@3.1.0: {}
|
longest-streak@3.1.0: {}
|
||||||
|
|
||||||
loose-envify@1.4.0:
|
loose-envify@1.4.0:
|
||||||
@ -16733,6 +16800,20 @@ snapshots:
|
|||||||
|
|
||||||
proto-list@1.2.4: {}
|
proto-list@1.2.4: {}
|
||||||
|
|
||||||
|
protobufjs@7.6.6:
|
||||||
|
dependencies:
|
||||||
|
'@protobufjs/aspromise': 1.1.2
|
||||||
|
'@protobufjs/base64': 1.1.2
|
||||||
|
'@protobufjs/codegen': 2.0.5
|
||||||
|
'@protobufjs/eventemitter': 1.1.1
|
||||||
|
'@protobufjs/fetch': 1.1.1
|
||||||
|
'@protobufjs/float': 1.0.2
|
||||||
|
'@protobufjs/path': 1.1.2
|
||||||
|
'@protobufjs/pool': 1.1.0
|
||||||
|
'@protobufjs/utf8': 1.1.2
|
||||||
|
'@types/node': 20.19.37
|
||||||
|
long: 5.3.2
|
||||||
|
|
||||||
proxy-addr@2.0.8:
|
proxy-addr@2.0.8:
|
||||||
dependencies:
|
dependencies:
|
||||||
forwarded: 0.2.0
|
forwarded: 0.2.0
|
||||||
|
|||||||
BIN
public/favicon-48x48.png
Normal file
BIN
public/favicon-48x48.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@ -73,14 +73,14 @@ export default function AdminConfigPage() {
|
|||||||
<h3>模块开关</h3>
|
<h3>模块开关</h3>
|
||||||
<div className={styles.grid2}>
|
<div className={styles.grid2}>
|
||||||
{moduleKeys.map((key) => {
|
{moduleKeys.map((key) => {
|
||||||
const m = config.modules[key];
|
const m = config.modules[key] ?? { enabled: false, title: key };
|
||||||
return (
|
return (
|
||||||
<label key={key} className={styles.panel} style={{ cursor: "pointer" }}>
|
<label key={key} className={styles.panel} style={{ cursor: "pointer" }}>
|
||||||
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
|
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
|
||||||
<strong>{m.title || key}</strong>
|
<strong>{m.title || key}</strong>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
checked={m.enabled}
|
checked={Boolean(m.enabled)}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setConfig({
|
setConfig({
|
||||||
...config,
|
...config,
|
||||||
@ -95,7 +95,7 @@ export default function AdminConfigPage() {
|
|||||||
<input
|
<input
|
||||||
className={styles.input}
|
className={styles.input}
|
||||||
style={{ marginTop: 8, width: "100%" }}
|
style={{ marginTop: 8, width: "100%" }}
|
||||||
value={m.title}
|
value={m.title || ""}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setConfig({
|
setConfig({
|
||||||
...config,
|
...config,
|
||||||
|
|||||||
4
src/app/api/track/route.ts
Normal file
4
src/app/api/track/route.ts
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
export { POST } from "@vip/app/api/track/route";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||||
import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv";
|
import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv";
|
||||||
import { usePayStatusPoll } from "@vip/app/lib/usePayStatusPoll";
|
import { usePayStatusPoll } from "@vip/app/lib/usePayStatusPoll";
|
||||||
|
import { trackPay } from "@vip/app/lib/track";
|
||||||
import { VipLayout } from "@vip/app/vip/components/VipLayout";
|
import { VipLayout } from "@vip/app/vip/components/VipLayout";
|
||||||
import { LandingPage } from "@vip/app/vip/components/LandingPage";
|
import { LandingPage } from "@vip/app/vip/components/LandingPage";
|
||||||
import { DashboardPage } from "@vip/app/vip/components/DashboardPage";
|
import { DashboardPage } from "@vip/app/vip/components/DashboardPage";
|
||||||
@ -694,6 +695,9 @@ export default function HomeClient() {
|
|||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
saveUserName(uid);
|
saveUserName(uid);
|
||||||
savePaidType("vip");
|
savePaidType("vip");
|
||||||
|
trackPay("success", { order_id: orderId });
|
||||||
|
} else {
|
||||||
|
trackPay("pending", { order_id: orderId, reason: "confirm_fail" });
|
||||||
}
|
}
|
||||||
/* confirm 失败时不设置 paidType,避免显示 VIP 但 PB/Memos 无记录 */
|
/* confirm 失败时不设置 paidType,避免显示 VIP 但 PB/Memos 无记录 */
|
||||||
}
|
}
|
||||||
@ -702,6 +706,7 @@ export default function HomeClient() {
|
|||||||
window.location.reload();
|
window.location.reload();
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
|
trackPay("fail", { reason: "poll_timeout" });
|
||||||
clearPendingOrder();
|
clearPendingOrder();
|
||||||
if (isH5) setPayPendingOrderId(null);
|
if (isH5) setPayPendingOrderId(null);
|
||||||
},
|
},
|
||||||
|
|||||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||||
import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv";
|
import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv";
|
||||||
import { usePayStatusPoll } from "@vip/app/lib/usePayStatusPoll";
|
import { usePayStatusPoll } from "@vip/app/lib/usePayStatusPoll";
|
||||||
|
import { trackPay } from "@vip/app/lib/track";
|
||||||
import { VipLayout } from "@vip/app/vip/components/VipLayout";
|
import { VipLayout } from "@vip/app/vip/components/VipLayout";
|
||||||
import { LandingPage } from "@vip/app/vip/components/LandingPage";
|
import { LandingPage } from "@vip/app/vip/components/LandingPage";
|
||||||
import { DashboardPage } from "@vip/app/vip/components/DashboardPage";
|
import { DashboardPage } from "@vip/app/vip/components/DashboardPage";
|
||||||
@ -694,14 +695,18 @@ export default function HomeClient() {
|
|||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
saveUserName(uid);
|
saveUserName(uid);
|
||||||
savePaidType("vip");
|
savePaidType("vip");
|
||||||
|
trackPay("success", { order_id: orderId });
|
||||||
|
} else {
|
||||||
|
trackPay("pending", { order_id: orderId, reason: "confirm_fail" });
|
||||||
}
|
}
|
||||||
/* confirm 失败时不设置 paidType,避免显示 VIP 但 PB/Memos 无记录 */
|
/* confirm 失败时不设置 paidType,避免显示 VIP 但 PB/Memos 无账号 */
|
||||||
}
|
}
|
||||||
clearPendingOrder();
|
clearPendingOrder();
|
||||||
if (isH5) setPayPendingOrderId(null);
|
if (isH5) setPayPendingOrderId(null);
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
|
trackPay("fail", { reason: "poll_timeout" });
|
||||||
clearPendingOrder();
|
clearPendingOrder();
|
||||||
if (isH5) setPayPendingOrderId(null);
|
if (isH5) setPayPendingOrderId(null);
|
||||||
},
|
},
|
||||||
|
|||||||
120
src/modules/vip/app/api/track/route.ts
Normal file
120
src/modules/vip/app/api/track/route.ts
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
/**
|
||||||
|
* VIP Web 埋点入口(旁路)
|
||||||
|
* - 不读写 PocketBase / 支付 / VIP 状态
|
||||||
|
* - 高频事件:直接丢弃推送(不打 ntfy)
|
||||||
|
* - 高价值事件:仅 publishNtfy;失败仍 200,绝不拖垮业务页
|
||||||
|
*/
|
||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { publishNtfy } from "~/lib/ntfy";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
type TrackEvent = {
|
||||||
|
name?: string;
|
||||||
|
page?: string;
|
||||||
|
label?: string;
|
||||||
|
props?: Record<string, unknown>;
|
||||||
|
ts?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const NTFY_EVENTS = new Set([
|
||||||
|
"pay_start",
|
||||||
|
"pay_success",
|
||||||
|
"pay_cancel",
|
||||||
|
"pay_fail",
|
||||||
|
"pay_pending",
|
||||||
|
"login_ok",
|
||||||
|
"login_fail",
|
||||||
|
"error",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const TITLE: Record<string, string> = {
|
||||||
|
pay_start: "拉起支付",
|
||||||
|
pay_success: "支付成功",
|
||||||
|
pay_cancel: "取消支付",
|
||||||
|
pay_fail: "支付失败",
|
||||||
|
pay_pending: "支付确认中",
|
||||||
|
login_ok: "登录成功",
|
||||||
|
login_fail: "登录失败",
|
||||||
|
error: "前端异常",
|
||||||
|
};
|
||||||
|
|
||||||
|
const TAGS: Record<string, string> = {
|
||||||
|
pay_start: "credit_card,globe_with_meridians",
|
||||||
|
pay_success: "moneybag,tada,globe_with_meridians",
|
||||||
|
pay_cancel: "wave,globe_with_meridians",
|
||||||
|
pay_fail: "warning,x,globe_with_meridians",
|
||||||
|
pay_pending: "hourglass,globe_with_meridians",
|
||||||
|
login_ok: "key,globe_with_meridians",
|
||||||
|
login_fail: "key,warning,globe_with_meridians",
|
||||||
|
error: "rotating_light,globe_with_meridians",
|
||||||
|
};
|
||||||
|
|
||||||
|
const PRIORITY: Record<string, number> = {
|
||||||
|
pay_success: 5,
|
||||||
|
pay_fail: 5,
|
||||||
|
pay_start: 4,
|
||||||
|
login_fail: 4,
|
||||||
|
error: 4,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 进程内限流:每分钟最多推 20 条 */
|
||||||
|
const ntfyTimes: number[] = [];
|
||||||
|
const NTFY_MAX_PER_MIN = 20;
|
||||||
|
|
||||||
|
function ntfyBudgetOk(): boolean {
|
||||||
|
const now = Date.now();
|
||||||
|
while (ntfyTimes.length && ntfyTimes[0]! < now - 60_000) ntfyTimes.shift();
|
||||||
|
if (ntfyTimes.length >= NTFY_MAX_PER_MIN) return false;
|
||||||
|
ntfyTimes.push(now);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function shortUid(uid: string | undefined): string {
|
||||||
|
const u = (uid || "").trim();
|
||||||
|
if (!u) return "-";
|
||||||
|
return u.length > 10 ? `…${u.slice(-8)}` : u;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const body = (await request.json().catch(() => ({}))) as {
|
||||||
|
events?: TrackEvent[];
|
||||||
|
openid?: string;
|
||||||
|
client?: string;
|
||||||
|
};
|
||||||
|
const events = Array.isArray(body.events) ? body.events.slice(0, 20) : [];
|
||||||
|
const openid = (body.openid || "").trim().slice(0, 64);
|
||||||
|
let notified = 0;
|
||||||
|
|
||||||
|
for (const raw of events) {
|
||||||
|
const name = String(raw?.name || "").trim().slice(0, 64);
|
||||||
|
if (!name || !NTFY_EVENTS.has(name)) continue;
|
||||||
|
if (!ntfyBudgetOk()) continue;
|
||||||
|
|
||||||
|
const page = String(raw?.page || "").slice(0, 64);
|
||||||
|
const label = String(raw?.label || "").slice(0, 120);
|
||||||
|
const parts = [`用户 ${shortUid(openid)}`, "vip.hackrobot.cn"];
|
||||||
|
if (page) parts.push(`页 ${page}`);
|
||||||
|
if (label) parts.push(label);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await publishNtfy({
|
||||||
|
title: `[WebVIP] ${TITLE[name] || name}`.slice(0, 80),
|
||||||
|
message: parts.join(" · ").slice(0, 400),
|
||||||
|
tags: TAGS[name] || "bar_chart,globe_with_meridians",
|
||||||
|
priority: PRIORITY[name] ?? 3,
|
||||||
|
});
|
||||||
|
if (result.ok) notified += 1;
|
||||||
|
} catch {
|
||||||
|
/* 旁路:推送失败忽略 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, notified }, { status: 200 });
|
||||||
|
} catch {
|
||||||
|
/* 旁路:任何异常都不当失败抛给前端业务 */
|
||||||
|
return NextResponse.json({ ok: true, notified: 0 }, { status: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
128
src/modules/vip/app/lib/track.ts
Normal file
128
src/modules/vip/app/lib/track.ts
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
/**
|
||||||
|
* vip.hackrobot.cn 埋点(旁路)
|
||||||
|
* - 绝不 await 业务路径;失败静默
|
||||||
|
* - 不写 VIP/支付状态;只 POST /api/track
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type TrackProps = Record<string, string | number | boolean | null | undefined>;
|
||||||
|
|
||||||
|
type TrackItem = {
|
||||||
|
name: string;
|
||||||
|
page?: string;
|
||||||
|
label?: string;
|
||||||
|
props?: TrackProps;
|
||||||
|
ts: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const queue: TrackItem[] = [];
|
||||||
|
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let flushing = false;
|
||||||
|
let lastPageView = { key: "", at: 0 };
|
||||||
|
|
||||||
|
function currentPage(): string {
|
||||||
|
if (typeof window === "undefined") return "";
|
||||||
|
try {
|
||||||
|
return (window.location.pathname || "/").slice(0, 64);
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleFlush(immediate = false) {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
if (immediate) {
|
||||||
|
if (flushTimer) {
|
||||||
|
clearTimeout(flushTimer);
|
||||||
|
flushTimer = null;
|
||||||
|
}
|
||||||
|
void flush();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (flushTimer) return;
|
||||||
|
flushTimer = setTimeout(() => {
|
||||||
|
flushTimer = null;
|
||||||
|
void flush();
|
||||||
|
}, 800);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flush(): Promise<void> {
|
||||||
|
if (flushing || !queue.length) return;
|
||||||
|
flushing = true;
|
||||||
|
const batch = queue.splice(0, 20);
|
||||||
|
try {
|
||||||
|
const uid =
|
||||||
|
typeof localStorage !== "undefined"
|
||||||
|
? (localStorage.getItem("userId") || localStorage.getItem("memosAccount") || "").trim()
|
||||||
|
: "";
|
||||||
|
await fetch("/api/track", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
events: batch,
|
||||||
|
openid: uid || undefined,
|
||||||
|
client: "vip_web",
|
||||||
|
}),
|
||||||
|
keepalive: true,
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* 旁路:失败丢弃,不回灌,避免拖业务 */
|
||||||
|
} finally {
|
||||||
|
flushing = false;
|
||||||
|
if (queue.length) scheduleFlush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 静默上报;永不抛错 */
|
||||||
|
export function track(
|
||||||
|
name: string,
|
||||||
|
opts?: { page?: string; label?: string; props?: TrackProps; immediate?: boolean }
|
||||||
|
): void {
|
||||||
|
try {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
const n = (name || "").trim();
|
||||||
|
if (!n) return;
|
||||||
|
queue.push({
|
||||||
|
name: n.slice(0, 64),
|
||||||
|
page: (opts?.page || currentPage()).slice(0, 64),
|
||||||
|
label: opts?.label ? String(opts.label).slice(0, 120) : undefined,
|
||||||
|
props: { channel: "vip_web", ...(opts?.props || {}) },
|
||||||
|
ts: Date.now() / 1000,
|
||||||
|
});
|
||||||
|
if (opts?.immediate || queue.length >= 6) scheduleFlush(true);
|
||||||
|
else scheduleFlush();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trackPage(page: string, label?: string, props?: TrackProps) {
|
||||||
|
try {
|
||||||
|
const key = `${page}|${label || page}`;
|
||||||
|
const now = Date.now();
|
||||||
|
if (lastPageView.key === key && now - lastPageView.at < 2000) return;
|
||||||
|
lastPageView = { key, at: now };
|
||||||
|
track("page_view", { page, label: label || page, props, immediate: true });
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trackClick(label: string, props?: TrackProps) {
|
||||||
|
track("btn_click", { label, props, immediate: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trackPay(
|
||||||
|
stage: "start" | "success" | "cancel" | "fail" | "pending",
|
||||||
|
props?: TrackProps
|
||||||
|
) {
|
||||||
|
track(`pay_${stage}`, { label: stage, props, immediate: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trackLogin(ok: boolean, props?: TrackProps) {
|
||||||
|
track(ok ? "login_ok" : "login_fail", {
|
||||||
|
label: ok ? "ok" : "fail",
|
||||||
|
props,
|
||||||
|
immediate: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -11,6 +11,7 @@ import { getPaymentConfig } from "@vip/config/services.config";
|
|||||||
import { resolvePayProvider } from "@nomadro/pay";
|
import { resolvePayProvider } from "@nomadro/pay";
|
||||||
import { isChinaUser } from "is-china-user";
|
import { isChinaUser } from "is-china-user";
|
||||||
import { readPortalRemoteCopy } from "@vip/app/lib/remoteConfigBridge";
|
import { readPortalRemoteCopy } from "@vip/app/lib/remoteConfigBridge";
|
||||||
|
import { trackPay } from "@vip/app/lib/track";
|
||||||
|
|
||||||
const ANONYMOUS_USER_COOKIE = "nomadvip_anon_uid";
|
const ANONYMOUS_USER_COOKIE = "nomadvip_anon_uid";
|
||||||
const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
|
const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
|
||||||
@ -323,11 +324,13 @@ export async function triggerPay(
|
|||||||
const isPayTestMode = getStorage(VIP_PAY_TEST_MODE_KEY) === "1";
|
const isPayTestMode = getStorage(VIP_PAY_TEST_MODE_KEY) === "1";
|
||||||
const remote = readPortalRemoteCopy();
|
const remote = readPortalRemoteCopy();
|
||||||
if (remote.payEnabled === false) {
|
if (remote.payEnabled === false) {
|
||||||
|
trackPay("fail", { reason: "pay_disabled" });
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
window.alert("支付通道已在管理后台关闭");
|
window.alert("支付通道已在管理后台关闭");
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
trackPay("start", { device, test: isPayTestMode ? 1 : 0 });
|
||||||
const totalFee = isPayTestMode
|
const totalFee = isPayTestMode
|
||||||
? 100
|
? 100
|
||||||
: remote.vipPriceFen && remote.vipPriceFen > 0
|
: remote.vipPriceFen && remote.vipPriceFen > 0
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { LandingHero } from "./landing/LandingHero";
|
import { LandingHero } from "./landing/LandingHero";
|
||||||
import { AssetStats } from "./landing/AssetStats";
|
import { AssetStats } from "./landing/AssetStats";
|
||||||
import { TopicEbookShowcase } from "./landing/TopicEbookShowcase";
|
import { TopicEbookShowcase } from "./landing/TopicEbookShowcase";
|
||||||
@ -10,6 +10,7 @@ import { FAQSection } from "./landing/FAQSection";
|
|||||||
import { LandingCTA } from "./landing/LandingCTA";
|
import { LandingCTA } from "./landing/LandingCTA";
|
||||||
import { LoginModal } from "./landing/LoginModal";
|
import { LoginModal } from "./landing/LoginModal";
|
||||||
import { PromoProofModal } from "./landing/PromoProofModal";
|
import { PromoProofModal } from "./landing/PromoProofModal";
|
||||||
|
import { trackPage } from "@vip/app/lib/track";
|
||||||
import styles from "./vip.module.css";
|
import styles from "./vip.module.css";
|
||||||
|
|
||||||
type LandingPageProps = {
|
type LandingPageProps = {
|
||||||
@ -41,6 +42,10 @@ export function LandingPage({
|
|||||||
});
|
});
|
||||||
const titleTapCountRef = useRef(0);
|
const titleTapCountRef = useRef(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
trackPage("vip_landing", "异度星球");
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleHeroTitleTap = () => {
|
const handleHeroTitleTap = () => {
|
||||||
titleTapCountRef.current += 1;
|
titleTapCountRef.current += 1;
|
||||||
if (titleTapCountRef.current < 10) return;
|
if (titleTapCountRef.current < 10) return;
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { formatRestoreDateShort } from "@vip/config/promo.config";
|
import { formatRestoreDateShort } from "@vip/config/promo.config";
|
||||||
import { readPortalRemoteCopy } from "@vip/app/lib/remoteConfigBridge";
|
import { readPortalRemoteCopy } from "@vip/app/lib/remoteConfigBridge";
|
||||||
|
import { trackClick } from "@vip/app/lib/track";
|
||||||
import styles from "../vip.module.css";
|
import styles from "../vip.module.css";
|
||||||
|
|
||||||
type LandingCTAProps = {
|
type LandingCTAProps = {
|
||||||
@ -93,7 +94,10 @@ export function LandingCTA({
|
|||||||
<div className={styles.ctaActions}>
|
<div className={styles.ctaActions}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onJoin}
|
onClick={() => {
|
||||||
|
trackClick("cta_join");
|
||||||
|
onJoin();
|
||||||
|
}}
|
||||||
className={`${styles.btnPrimary} ${styles.btnLarge} ${styles.ctaBtnPrimary}`}
|
className={`${styles.btnPrimary} ${styles.btnLarge} ${styles.ctaBtnPrimary}`}
|
||||||
style={payTestMode ? { background: "linear-gradient(135deg,#16a34a,#22c55e)" } : undefined}
|
style={payTestMode ? { background: "linear-gradient(135deg,#16a34a,#22c55e)" } : undefined}
|
||||||
>
|
>
|
||||||
@ -155,7 +159,14 @@ export function LandingCTA({
|
|||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
</button>
|
</button>
|
||||||
<button type="button" onClick={onLogin} className={styles.ctaBtnSecondary}>
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
trackClick("cta_login");
|
||||||
|
onLogin();
|
||||||
|
}}
|
||||||
|
className={styles.ctaBtnSecondary}
|
||||||
|
>
|
||||||
已有账号登录
|
已有账号登录
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||||
|
import { trackLogin } from "@vip/app/lib/track";
|
||||||
import styles from "../vip.module.css";
|
import styles from "../vip.module.css";
|
||||||
|
|
||||||
type LoginFormProps = {
|
type LoginFormProps = {
|
||||||
@ -63,11 +64,14 @@ export function LoginForm({
|
|||||||
const ok = await onVerify(trimmed);
|
const ok = await onVerify(trimmed);
|
||||||
if (ok) {
|
if (ok) {
|
||||||
succeeded = true;
|
succeeded = true;
|
||||||
|
trackLogin(true, { mode: "user_id" });
|
||||||
onSuccess();
|
onSuccess();
|
||||||
} else {
|
} else {
|
||||||
|
trackLogin(false, { mode: "user_id" });
|
||||||
setError("未找到该账号的会员记录,请确认账号正确");
|
setError("未找到该账号的会员记录,请确认账号正确");
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
trackLogin(false, { mode: "user_id", reason: "exception" });
|
||||||
setError("验证失败,请稍后重试");
|
setError("验证失败,请稍后重试");
|
||||||
} finally {
|
} finally {
|
||||||
if (!succeeded) setLoading(false);
|
if (!succeeded) setLoading(false);
|
||||||
@ -103,11 +107,14 @@ export function LoginForm({
|
|||||||
const errMsg = typeof result === "object" ? result.error : undefined;
|
const errMsg = typeof result === "object" ? result.error : undefined;
|
||||||
if (ok) {
|
if (ok) {
|
||||||
succeeded = true;
|
succeeded = true;
|
||||||
|
trackLogin(true, { mode: "email" });
|
||||||
onSuccess();
|
onSuccess();
|
||||||
} else {
|
} else {
|
||||||
|
trackLogin(false, { mode: "email" });
|
||||||
setError(errMsg || "邮箱或密码错误,或未找到关联的会员记录");
|
setError(errMsg || "邮箱或密码错误,或未找到关联的会员记录");
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
trackLogin(false, { mode: "email", reason: "exception" });
|
||||||
setError("验证失败,请稍后重试");
|
setError("验证失败,请稍后重试");
|
||||||
} finally {
|
} finally {
|
||||||
if (!succeeded) setLoading(false);
|
if (!succeeded) setLoading(false);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user