diff --git a/README.md b/README.md index 675ad81..d6b0fa2 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts) | 导航 | `/nav` | `src/modules/nav` · 远程 `navContent`(后台 `/wechat/nav` 可 CRUD) | | 小册 | `/book` | `src/modules/ebook` + `src/modules/ebook-content` | | 旅居社群 | `/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`(微信小程序原生页,见下) | | 后台 | admin.nomadro.cn | `apps/admin` | | API | api.nomadro.cn | `apps/api` | @@ -122,7 +122,18 @@ pnpm dev:api ### 游民社区(`/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 摘要(审核包) @@ -152,7 +163,15 @@ pnpm dev:api ## 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 摘要(已合入) diff --git a/apps/api/services/community_svc/config.py b/apps/api/services/community_svc/config.py index 445687b..0c326b5 100644 --- a/apps/api/services/community_svc/config.py +++ b/apps/api/services/community_svc/config.py @@ -1,4 +1,4 @@ -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): @@ -36,7 +36,7 @@ class Settings(BaseSettings): # Payment (from env on server) dev_auto_pay: bool = False 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" @property diff --git a/apps/api/services/community_svc/services/meetup_live.py b/apps/api/services/community_svc/services/meetup_live.py index 1ebc758..78e6c30 100644 --- a/apps/api/services/community_svc/services/meetup_live.py +++ b/apps/api/services/community_svc/services/meetup_live.py @@ -6,7 +6,7 @@ import os import re 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") 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"): return explicit 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: diff --git a/apps/api/services/social_svc/config.py b/apps/api/services/social_svc/config.py index d75ad9f..6b01a17 100644 --- a/apps/api/services/social_svc/config.py +++ b/apps/api/services/social_svc/config.py @@ -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_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", +) diff --git a/apps/api/services/social_svc/realtime.py b/apps/api/services/social_svc/realtime.py new file mode 100644 index 0000000..8c9e73f --- /dev/null +++ b/apps/api/services/social_svc/realtime.py @@ -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 diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index ecf651e..bb7bd4f 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -1,11 +1,12 @@ """游民社区 API — 前缀 /api/social/v1,与 /api/v1 社群隔离。""" from __future__ import annotations -from fastapi import APIRouter, Header, HTTPException +from fastapi import APIRouter, Header, HTTPException, Query from pydantic import BaseModel, Field from social_svc import store from social_svc.config import SOCIAL_ENABLED +from social_svc.realtime import issue_connection_token, publish_chat_message router = APIRouter(tags=["social"]) @@ -55,7 +56,20 @@ class GigAppIn(BaseModel): async def social_health(): if not SOCIAL_ENABLED: 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") @@ -74,7 +88,13 @@ async def post_message( store.init_db() if not body.text.strip(): 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") diff --git a/apps/api/social_main.py b/apps/api/social_main.py new file mode 100644 index 0000000..fb37360 --- /dev/null +++ b/apps/api/social_main.py @@ -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), + } diff --git a/apps/miniprogram/h5/src/app.config.ts b/apps/miniprogram/h5/src/app.config.ts index d7d4db8..5af6efe 100644 --- a/apps/miniprogram/h5/src/app.config.ts +++ b/apps/miniprogram/h5/src/app.config.ts @@ -45,21 +45,21 @@ const isH5 = process.env.TARO_ENV === 'h5' || process.env.TARO_APP_TARGET === 'h5' const wantTabBar = !isH5 && process.env.TARO_APP_TABBAR === '1' -/** 微信主包必须 ≤1.5MB:首页/我的留主包,其余进分包 */ +/** 微信主包必须 ≤2MB:首页/我的/小册留主包(提审小册勿进分包,避免下载失败黑屏) */ const weappConfig = { - // 启动页 = home(官方话题/体验码默认路径);UI 与 tag 20261011 的 index 同组件 - pages: ['pages/home/index', 'pages/mine/index', 'pages/index/index'], + // 提审期:小册作启动页,打开即见正文(过审后改回 home 第一) + pages: [ + 'pages/book/index', + 'pages/home/index', + 'pages/mine/index', + 'pages/index/index', + ], subPackages: [ { root: 'pages/nav', name: 'nav', pages: ['index'], }, - { - root: 'pages/book', - name: 'book', - pages: ['index'], - }, { root: 'pages/reader', name: 'reader', @@ -145,11 +145,11 @@ const weappConfig = { preloadRule: { 'pages/home/index': { network: 'all', - packages: ['book', 'nav'], + packages: ['nav', 'reader'], }, }, - /** 组件按需注入:代码质量扫描必过项 */ - lazyCodeLoading: 'requiredComponents' as const, + // 提审期先关掉按需注入:Taro+React 下偶发首屏空白/黑屏;过审后再开回 requiredComponents + // lazyCodeLoading: 'requiredComponents' as const, } const h5Config = { diff --git a/apps/miniprogram/h5/src/app.scss b/apps/miniprogram/h5/src/app.scss index 780e555..a044d0c 100644 --- a/apps/miniprogram/h5/src/app.scss +++ b/apps/miniprogram/h5/src/app.scss @@ -1,6 +1,6 @@ +/* 全局底:勿引入 community / ebook;提审小册靠内联色 */ page { - background: #0a0e17; - color: #f1f5f9; - font-family: 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', sans-serif; + background: #0c0b12; + color: #f8fafc; box-sizing: border-box; } diff --git a/apps/miniprogram/h5/src/app.tsx b/apps/miniprogram/h5/src/app.tsx index 844a34d..22807a5 100644 --- a/apps/miniprogram/h5/src/app.tsx +++ b/apps/miniprogram/h5/src/app.tsx @@ -38,16 +38,28 @@ function App({ children }: PropsWithChildren) { useEffect(() => { const stopRem = startH5RemLock() const stopLive = startRemoteConfigLiveSync() - const stopPresence = startPresenceHeartbeat() - const stopVip = startVipAccessLiveSync() + let stopPresence: (() => void) | undefined + let stopVip: (() => void) | undefined + let defer: ReturnType | 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') { applyH5Theme(getStoredH5Theme()) } return () => { + if (defer) clearTimeout(defer) stopRem() stopLive() - stopPresence() - stopVip() + stopPresence?.() + stopVip?.() } }, []) diff --git a/apps/miniprogram/h5/src/app.weapp.tsx b/apps/miniprogram/h5/src/app.weapp.tsx new file mode 100644 index 0000000..e82bd05 --- /dev/null +++ b/apps/miniprogram/h5/src/app.weapp.tsx @@ -0,0 +1,9 @@ +/** + * 微信专用 App:零副作用。必须包一层 Fragment,避免 children 形态异常导致整页空白。 + */ +import { Fragment, type PropsWithChildren } from 'react' +import './app.scss' + +export default function App({ children }: PropsWithChildren) { + return {children} +} diff --git a/apps/miniprogram/h5/src/components/AuditBookScreen.tsx b/apps/miniprogram/h5/src/components/AuditBookScreen.tsx new file mode 100644 index 0000000..4a043b0 --- /dev/null +++ b/apps/miniprogram/h5/src/components/AuditBookScreen.tsx @@ -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) => ({ + 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 ( + + + {AUDIT_BOOK_META.cover_emoji} + + + {AUDIT_BOOK_META.title} + + + {AUDIT_BOOK_META.subtitle} + + + + {chapters.map((c, i) => ( + setIdx(i)} + style={{ paddingTop: safePx(10), paddingBottom: safePx(10) }} + > + + {`${i + 1}. ${c.title}`} + + + ))} + + + + + {`${safeIdx + 1}. ${chapter?.title || '正文'}`} + + {lines.map((line, i) => + line ? ( + + {line} + + ) : ( + + ), + )} + + + + setIdx((v) => Math.max(0, v - 1))} + style={{ paddingTop: safePx(12), paddingBottom: safePx(12), paddingRight: safePx(16) }} + > + + 上一章 + + + + {`${safeIdx + 1}/${chapters.length}`} + + setIdx((v) => Math.min(chapters.length - 1, v + 1))} + style={{ paddingTop: safePx(12), paddingBottom: safePx(12), paddingLeft: safePx(16) }} + > + = chapters.length - 1 ? '#334155' : '#94a3b8', + })} + > + 下一章 + + + + + ) +} + +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() +} diff --git a/apps/miniprogram/h5/src/components/AuditPlainBody.tsx b/apps/miniprogram/h5/src/components/AuditPlainBody.tsx new file mode 100644 index 0000000..fbdf25b --- /dev/null +++ b/apps/miniprogram/h5/src/components/AuditPlainBody.tsx @@ -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 ( + 暂无内容 + ) + } + + return ( + + {lines.map((l, i) => { + if (l.type === 'sp') { + return + } + if (l.type === 'h') { + const size = l.level === 1 ? 18 : l.level === 2 ? 16 : 15 + return ( + + {l.text} + + ) + } + if (l.type === 'li') { + return ( + + · {l.text} + + ) + } + return ( + + {l.text} + + ) + })} + + ) +} + +function stripInline(s: string) { + return s + .replace(/\*\*(.+?)\*\*/g, '$1') + .replace(/\*(.+?)\*/g, '$1') + .replace(/`([^`]+)`/g, '$1') + .replace(/\[(.+?)\]\((https?:\/\/.+?)\)/g, '$1') +} diff --git a/apps/miniprogram/h5/src/components/H5Box.tsx b/apps/miniprogram/h5/src/components/H5Box.tsx index 2a5bd3b..97dd650 100644 --- a/apps/miniprogram/h5/src/components/H5Box.tsx +++ b/apps/miniprogram/h5/src/components/H5Box.tsx @@ -56,6 +56,9 @@ export function H5Box({ ) } + // 微信/抖音等:禁止 dangerouslySetInnerHTML。 + // Taro 会编出非法自定义组件 → Component is not found in path "wx://not-found" → 整页黑屏。 + // SVG/html 仅 H5 使用;小程序靠 className + children(CSS/emoji)兜底。 return ( - {html ? undefined : children} + {children} ) } diff --git a/apps/miniprogram/h5/src/components/NomadroLoader.scss b/apps/miniprogram/h5/src/components/NomadroLoader.scss index 5c6015b..b0a2975 100644 --- a/apps/miniprogram/h5/src/components/NomadroLoader.scss +++ b/apps/miniprogram/h5/src/components/NomadroLoader.scss @@ -78,6 +78,39 @@ 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-mark { width: 88px; diff --git a/apps/miniprogram/h5/src/components/NomadroLoader.tsx b/apps/miniprogram/h5/src/components/NomadroLoader.tsx index 7f110c2..c1d0f0d 100644 --- a/apps/miniprogram/h5/src/components/NomadroLoader.tsx +++ b/apps/miniprogram/h5/src/components/NomadroLoader.tsx @@ -1,6 +1,8 @@ import { H5Box, H5Txt } from './H5Box' import './NomadroLoader.scss' +const isH5 = process.env.TARO_ENV === 'h5' + const LOGO_SVG = ` ) } - -function BookPage() { - usePageShare({ title: 'nomadro · 数字游民小册', path: '/pages/book/index' }) - return ( - - - - ) -} - -export default markPageShare(BookPage) - diff --git a/apps/miniprogram/h5/src/pages/home/index.tsx b/apps/miniprogram/h5/src/pages/home/index.tsx index e9ef08d..2912fa4 100644 --- a/apps/miniprogram/h5/src/pages/home/index.tsx +++ b/apps/miniprogram/h5/src/pages/home/index.tsx @@ -6,6 +6,7 @@ import { useEffect, useState, type CSSProperties, type ReactNode } from 'react' import { View, Text } from '@tarojs/components' import Taro, { useDidShow, usePageScroll } from '@tarojs/taro' import { + getCachedRemoteConfig, isModuleEnabled, loadRemoteConfig, subscribeRemoteConfig, @@ -137,6 +138,7 @@ function Box({ ) } + // 微信禁止 View + dangerouslySetInnerHTML(会 wx://not-found 黑屏) return ( - {html ? undefined : children} + {children} ) } @@ -160,7 +161,8 @@ function IndexPage() { usePageTrack('pages/home/index', '首页') usePageShare({ title: 'nomadro · 随处工作,自由生活', path: '/pages/home/index' }) - const [config, setConfig] = useState(null) + // 首屏用包内/缓存配置,禁止等网络才出入口(否则审核看到空首页像黑屏) + const [config, setConfig] = useState(() => getCachedRemoteConfig()) const theme = useNomadroTheme() const [navScrolled, setNavScrolled] = useState(false) @@ -284,9 +286,8 @@ function IndexPage() { }, []) const cfg = config - // 配置未就绪:一个入口都不渲染,避免「先闪后藏」被审核盯上 - const portals = cfg ? PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey)) : [] - const brand = cfg?.copy.homeBrand || 'nomadro' + const portals = PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey)) + const brand = cfg.copy.homeBrand || 'nomadro' const safe = useSafeAreaMetrics() const rootSafeStyle = { // CSS 变量用小写 px(样式表已排除 rpx 转换);内联尺寸必须用 safePx @@ -416,7 +417,7 @@ function IndexPage() { {portal.emoji} - {cfg?.modules[portal.moduleKey]?.title || portal.name} + {cfg.modules[portal.moduleKey]?.title || portal.name} ))} diff --git a/apps/miniprogram/h5/src/pages/reader/index.tsx b/apps/miniprogram/h5/src/pages/reader/index.tsx index c6203df..893e527 100644 --- a/apps/miniprogram/h5/src/pages/reader/index.tsx +++ b/apps/miniprogram/h5/src/pages/reader/index.tsx @@ -9,10 +9,13 @@ import { accessFingerprint, fetchAccess, fetchRead, + getAuditOfflineRead, + isAuditBookId, pollUnlock, type ReadPayload, } from '../../services/ebookApi' import { MarkdownView } from '../../components/MarkdownView' +import { AuditPlainBody } from '../../components/AuditPlainBody' import { PayResultSheet } from '../../components/PayResultSheet' import { ReaderSettings } from '../../components/ReaderSettings' import { runUnlockPayment } from '../../utils/payFlow' @@ -53,7 +56,10 @@ function ReaderPage() { const router = useRouter() const bookId = router.params.id || 'default' const chapterParam = router.params.chapter || '' - const [data, setData] = useState(null) + // 提审书:首帧就有正文,避免 showLoading + 空壳黑屏 + const [data, setData] = useState(() => + isAuditBookId(bookId) ? getAuditOfflineRead(bookId) : null, + ) const [drawerOpen, setDrawerOpen] = useState(false) const [settingsOpen, setSettingsOpen] = useState(false) const [tocFilter, setTocFilter] = useState('') @@ -137,25 +143,37 @@ function ReaderPage() { }, [bookId]) async function load(silent = false) { + const auditBook = isAuditBookId(bookId) try { - if (!silent) Taro.showLoading({ title: '打开中' }) + // 提审:已有离线首屏,不再弹「打开中」遮罩 + if (!silent && !auditBook) Taro.showLoading({ title: '打开中' }) + if (auditBook) { + loadedRef.current = true + } const res = await fetchRead(bookId) setData(res) accessFpRef.current = accessFingerprint(res) loadedRef.current = true - if (!silent) { + if (!silent && !auditBook) { setActiveChapter(0) setProgress(0) restored.current = false } } 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 { - if (!silent) Taro.hideLoading() + if (!silent && !auditBook) Taro.hideLoading() } } async function syncAccess() { + // 提审书不探 VIP/权限,避免 401 连环 + if (isAuditBookId(bookId)) return if (!loadedRef.current || syncingRef.current || isH5) return syncingRef.current = true try { @@ -757,12 +775,16 @@ function ReaderPage() { - + {isAuditBookId(bookId) ? ( + + ) : ( + + )} {next ? ( diff --git a/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx b/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx index 8131a0a..a3f5b9e 100644 --- a/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx +++ b/apps/miniprogram/h5/src/pages/vip-ebook/index.tsx @@ -110,7 +110,8 @@ export default function VipEbookPage() { if (cancelled) return const audit = resolveBookAudit(getCachedRemoteConfig()) 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)) return } @@ -160,7 +161,7 @@ export default function VipEbookPage() { return subscribeRemoteConfig((r) => { const audit = resolveBookAudit(r.config) 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)) }) }, [bookId]) diff --git a/apps/miniprogram/h5/src/pages/vip/index.tsx b/apps/miniprogram/h5/src/pages/vip/index.tsx index 88dee7c..53afab4 100644 --- a/apps/miniprogram/h5/src/pages/vip/index.tsx +++ b/apps/miniprogram/h5/src/pages/vip/index.tsx @@ -475,7 +475,14 @@ function VipLanding() { - + {process.env.TARO_ENV === 'h5' ? ( + + ) : ( + + + + + )} {brand} · VIP diff --git a/apps/miniprogram/h5/src/services/ebookApi.ts b/apps/miniprogram/h5/src/services/ebookApi.ts index 64fbb7e..5bd4913 100644 --- a/apps/miniprogram/h5/src/services/ebookApi.ts +++ b/apps/miniprogram/h5/src/services/ebookApi.ts @@ -1,6 +1,7 @@ import Taro from '@tarojs/taro' import { checkIosPayReady, ensureLogin, request } from '../utils/request' import { OFFLINE_BOOK, offlineReadPayload } from '../data/offlineBook' +import { AUDIT_BOOK_CHAPTERS, AUDIT_BOOK_META } from '../data/auditBook' export type ChapterMeta = { id: string @@ -55,29 +56,35 @@ export type AccessSnapshot = { updated_at: number } -function isAuditBookId(bookId: string) { +export function isAuditBookId(bookId: string) { const id = (bookId || '').trim() 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 { + const wordCount = AUDIT_BOOK_CHAPTERS.reduce((n, c) => n + (c.content?.length || 0), 0) return { - id: bookId || 'audit', - title: '数字游民入门指南', - subtitle: '远程办公 · 自律生活 · 稳健成长', + id: bookId || AUDIT_BOOK_META.id, + title: AUDIT_BOOK_META.title, + subtitle: AUDIT_BOOK_META.subtitle, author: '', - cover_emoji: '📗', - description: '面向普通人的远程办公与生活方式入门读本。', - tags: ['数字游民', '远程办公'], + cover_emoji: AUDIT_BOOK_META.cover_emoji, + description: AUDIT_BOOK_META.description, + tags: [...AUDIT_BOOK_META.tags], price_fen: 0, product_id: '', unlock_percent: 100, is_free: true, - chapter_count: 1, - word_count: 0, + chapter_count: AUDIT_BOOK_CHAPTERS.length, + word_count: wordCount, 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) return { book, - chapters: [ - { - id: '01-audit', - title: '写在前面', - order: 1, - content: - '# 写在前面\n\n欢迎阅读《数字游民入门指南》。\n\n这是一本面向普通人的远程办公与自律生活入门读本。\n', - }, - ], + chapters: AUDIT_BOOK_CHAPTERS.map((c) => ({ + id: c.id, + title: c.title, + order: c.order, + content: c.content, + })), unlocked: true, is_free: true, unlock_percent: 100, @@ -113,14 +117,27 @@ function auditOfflineRead(bookId: string): ReadPayload { export async function fetchBook(bookId = 'default'): Promise { const id = bookId || 'default' - // H5:正式书用离线包;提审书必须打 API,失败也不回正式包 + // H5:正式书用离线包;提审书离线优先,失败也不回正式包 if (process.env.TARO_ENV === 'h5' && !isAuditBookId(id)) { return { ...OFFLINE_BOOK, id } } + if (isAuditBookId(id)) { + const offline = auditOfflineBook(id) + try { + const remote = await request({ + 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 { return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` }) } catch { - if (isAuditBookId(id)) return auditOfflineBook(id) return { ...OFFLINE_BOOK, id } } } @@ -132,6 +149,25 @@ export async function fetchRead(bookId = 'default'): Promise { payload.book = { ...payload.book, id } return payload } + // 提审书:离线优先(包内 10 章),有网再覆盖;空响应不覆盖,避免黑屏 + if (isAuditBookId(id)) { + const offline = auditOfflineRead(id) + try { + const remote = await request({ + 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 { if (process.env.TARO_ENV !== 'h5') { await ensureLogin() @@ -141,7 +177,6 @@ export async function fetchRead(bookId = 'default'): Promise { try { return await request({ url: `/api/ebook/books/${id}/read?_=${Date.now()}` }) } catch { - if (isAuditBookId(id)) return auditOfflineRead(id) const payload = offlineReadPayload() payload.book = { ...payload.book, id } return payload diff --git a/apps/miniprogram/h5/src/services/remoteConfig.ts b/apps/miniprogram/h5/src/services/remoteConfig.ts index 7eb8b7e..677a361 100644 --- a/apps/miniprogram/h5/src/services/remoteConfig.ts +++ b/apps/miniprogram/h5/src/services/remoteConfig.ts @@ -6,7 +6,8 @@ import { type NomadroRemoteConfig, } 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 /** 小程序无 EventSource:meta 轮询间隔(近实时) */ const META_POLL_MS = 3000 diff --git a/apps/miniprogram/h5/src/utils/presence.ts b/apps/miniprogram/h5/src/utils/presence.ts index db6b022..7903357 100644 --- a/apps/miniprogram/h5/src/utils/presence.ts +++ b/apps/miniprogram/h5/src/utils/presence.ts @@ -1,18 +1,23 @@ import Taro from '@tarojs/taro' import { ensureLogin, requestEbook } from './request' import { applyServerVipFlag } from './vipAccess' +import { getCachedRemoteConfig } from '../services/remoteConfig' +import { resolveBookAudit } from '../data/remoteConfig.defaults' const INTERVAL_MS = 25_000 let timer: ReturnType | null = null let started = false async function ping(): Promise { + // 提审:不登录、不上报,避免 wx.login / 401 干扰审核路径 + if (resolveBookAudit(getCachedRemoteConfig()).reviewMode) return try { await ensureLogin(false) const data = await requestEbook<{ isVip?: boolean }>({ url: '/api/ebook/auth/presence', method: 'POST', data: {}, + _retried: true, }) if (typeof data?.isVip === 'boolean') { applyServerVipFlag(data.isVip) diff --git a/apps/miniprogram/h5/src/utils/vipAccess.ts b/apps/miniprogram/h5/src/utils/vipAccess.ts index b25c5c0..03f56c3 100644 --- a/apps/miniprogram/h5/src/utils/vipAccess.ts +++ b/apps/miniprogram/h5/src/utils/vipAccess.ts @@ -6,6 +6,7 @@ import { getCachedRemoteConfig, loadRemoteConfig, } from '../services/remoteConfig' +import { resolveBookAudit } from '../data/remoteConfig.defaults' const LOCAL_PAID_KEY = 'nomadro_vip_paid' /** 与 remote-config meta / memo revision 同级:近实时探 VIP 准入 */ @@ -132,6 +133,12 @@ export async function resolveVipAccess(forceRefresh = false): Promise { /* use cache */ } + // 提审模式:不探 vip-status / 不 ensureLogin,避免控制台 401 连环与冷启动卡顿 + if (resolveBookAudit(getCachedRemoteConfig()).reviewMode) { + emitVip(false) + return false + } + try { await ensureLogin(false) } catch { @@ -149,6 +156,8 @@ export async function resolveVipAccess(forceRefresh = false): Promise { const data = await requestEbook<{ isVip?: boolean }>({ url: '/api/ebook/pay/vip-status', method: 'GET', + // 旁路探活:401 不触发清 token + 强制重登(避免审核/冷启动连环 401) + _retried: true, }) const vip = !!data?.isVip emitVip(vip) diff --git a/apps/miniprogram/weapp-audit/app.js b/apps/miniprogram/weapp-audit/app.js new file mode 100644 index 0000000..6241c06 --- /dev/null +++ b/apps/miniprogram/weapp-audit/app.js @@ -0,0 +1 @@ +App({}) diff --git a/apps/miniprogram/weapp-audit/app.json b/apps/miniprogram/weapp-audit/app.json new file mode 100644 index 0000000..c119bf0 --- /dev/null +++ b/apps/miniprogram/weapp-audit/app.json @@ -0,0 +1,10 @@ +{ + "pages": ["pages/book/index"], + "window": { + "navigationBarTitleText": "数字游民入门指南", + "navigationBarBackgroundColor": "#0c0b12", + "navigationBarTextStyle": "white", + "backgroundColor": "#0c0b12", + "backgroundTextStyle": "light" + } +} diff --git a/apps/miniprogram/weapp-audit/app.wxss b/apps/miniprogram/weapp-audit/app.wxss new file mode 100644 index 0000000..6e68301 --- /dev/null +++ b/apps/miniprogram/weapp-audit/app.wxss @@ -0,0 +1,5 @@ +page { + background: #0c0b12; + color: #f8fafc; + box-sizing: border-box; +} diff --git a/apps/miniprogram/weapp-audit/pages/book/index.js b/apps/miniprogram/weapp-audit/pages/book/index.js new file mode 100644 index 0000000..9b54578 --- /dev/null +++ b/apps/miniprogram/weapp-audit/pages/book/index.js @@ -0,0 +1,4 @@ +/** 提审小册:纯原生页,不经过 Taro/React */ +Page({ + data: {}, +}) diff --git a/apps/miniprogram/weapp-audit/pages/book/index.json b/apps/miniprogram/weapp-audit/pages/book/index.json new file mode 100644 index 0000000..6c854d8 --- /dev/null +++ b/apps/miniprogram/weapp-audit/pages/book/index.json @@ -0,0 +1,7 @@ +{ + "navigationBarTitleText": "数字游民入门指南", + "navigationBarBackgroundColor": "#0c0b12", + "navigationBarTextStyle": "white", + "backgroundColor": "#0c0b12", + "navigationStyle": "default" +} diff --git a/apps/miniprogram/weapp-audit/pages/book/index.wxml b/apps/miniprogram/weapp-audit/pages/book/index.wxml new file mode 100644 index 0000000..6eb6120 --- /dev/null +++ b/apps/miniprogram/weapp-audit/pages/book/index.wxml @@ -0,0 +1,52 @@ + + + 📗 + 数字游民入门指南 + 远程办公 · 自律生活 · 稳健成长 + + 1. 写在前面 + 欢迎阅读《数字游民入门指南》。 + 这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。 + 你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。 + + 2. 什么是数字游民 + 「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。 + 它不是逃避现实。更常见的状态是:工作目标清晰、沟通及时、作息稳定、遵守公司制度与当地法律法规。 + 对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。 + + 3. 远程办公的基本功 + 远程办公的核心不是换风景,而是换一种可协作的工作方式。 + 建议每天有固定核心工作时间,并告诉同事哪些时段适合会议、哪些时段专注深度工作。 + 每天开工前列三件必须完成的事;每周五花十五分钟复盘完成项与卡点。 + 工具只保留必要的。开会前写清目的,会后写清结论:谁负责、做什么、何时完成。 + + 4. 居家与旅居的工作环境 + 环境会直接影响专注力。不必追求豪华,但要够用、安静、可持续。 + 居家建议:稳定桌椅与屏幕高度、充足光线、耳机、备用电源,以及减少打扰的约定。 + 若允许短期异地办公,优先网络稳定、住宿安静、餐饮运动方便、交通可预期。 + + 5. 时间管理 + 灵活工作最大的风险是时间碎、注意力散、任务拖。 + 可用简化番茄法:25 分钟专注一件事,休息 5 分钟;深度工作时关闭无关通知。 + 建议每天至少留 90 分钟不被会议打断的时间,用来做深度工作。 + + 6. 沟通与团队协作 + 远程场景里,沟通质量几乎等于工作质量。 + 同步信息:默认公开、结论先行、可执行(下一步、负责人、时间)。 + 远程信任来自稳定交付:承诺按时完成,延期提前说明,问题主动暴露。 + + 7. 健康、作息与心态 + 尽量固定睡眠与起床时间;每工作一小时起身活动两分钟;中午真正休息。 + 运动不必复杂:散步、拉伸即可,关键是每周能坚持。 + + 8. 学习成长与职业规划 + 真正护城河仍是能力与口碑:专业技能、表达能力、项目管理。 + 请遵守劳动合同、信息安全与所在地法律法规。稳健发展,才能走得长远。 + + 9. 七天起步计划 + 第1天整理工位;第2天三个每日目标;第3天文档归位;第4天练习结论先行;第5天短复盘;第6天轻度运动;第7天只改一件事。 + + 10. 结语 + 先把远程协作做好,把身体照顾好,把专业能力垒扎实。祝你工作顺利,生活安定,步履从容。 + + diff --git a/apps/miniprogram/weapp-audit/pages/book/index.wxss b/apps/miniprogram/weapp-audit/pages/book/index.wxss new file mode 100644 index 0000000..59ed8b7 --- /dev/null +++ b/apps/miniprogram/weapp-audit/pages/book/index.wxss @@ -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; +} diff --git a/apps/miniprogram/weapp-audit/project.config.json b/apps/miniprogram/weapp-audit/project.config.json new file mode 100644 index 0000000..ec93124 --- /dev/null +++ b/apps/miniprogram/weapp-audit/project.config.json @@ -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" +} diff --git a/apps/miniprogram/weapp/native-audit-book/index.js b/apps/miniprogram/weapp/native-audit-book/index.js new file mode 100644 index 0000000..9b54578 --- /dev/null +++ b/apps/miniprogram/weapp/native-audit-book/index.js @@ -0,0 +1,4 @@ +/** 提审小册:纯原生页,不经过 Taro/React */ +Page({ + data: {}, +}) diff --git a/apps/miniprogram/weapp/native-audit-book/index.json b/apps/miniprogram/weapp/native-audit-book/index.json new file mode 100644 index 0000000..6c854d8 --- /dev/null +++ b/apps/miniprogram/weapp/native-audit-book/index.json @@ -0,0 +1,7 @@ +{ + "navigationBarTitleText": "数字游民入门指南", + "navigationBarBackgroundColor": "#0c0b12", + "navigationBarTextStyle": "white", + "backgroundColor": "#0c0b12", + "navigationStyle": "default" +} diff --git a/apps/miniprogram/weapp/native-audit-book/index.wxml b/apps/miniprogram/weapp/native-audit-book/index.wxml new file mode 100644 index 0000000..6eb6120 --- /dev/null +++ b/apps/miniprogram/weapp/native-audit-book/index.wxml @@ -0,0 +1,52 @@ + + + 📗 + 数字游民入门指南 + 远程办公 · 自律生活 · 稳健成长 + + 1. 写在前面 + 欢迎阅读《数字游民入门指南》。 + 这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。 + 你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。 + + 2. 什么是数字游民 + 「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。 + 它不是逃避现实。更常见的状态是:工作目标清晰、沟通及时、作息稳定、遵守公司制度与当地法律法规。 + 对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。 + + 3. 远程办公的基本功 + 远程办公的核心不是换风景,而是换一种可协作的工作方式。 + 建议每天有固定核心工作时间,并告诉同事哪些时段适合会议、哪些时段专注深度工作。 + 每天开工前列三件必须完成的事;每周五花十五分钟复盘完成项与卡点。 + 工具只保留必要的。开会前写清目的,会后写清结论:谁负责、做什么、何时完成。 + + 4. 居家与旅居的工作环境 + 环境会直接影响专注力。不必追求豪华,但要够用、安静、可持续。 + 居家建议:稳定桌椅与屏幕高度、充足光线、耳机、备用电源,以及减少打扰的约定。 + 若允许短期异地办公,优先网络稳定、住宿安静、餐饮运动方便、交通可预期。 + + 5. 时间管理 + 灵活工作最大的风险是时间碎、注意力散、任务拖。 + 可用简化番茄法:25 分钟专注一件事,休息 5 分钟;深度工作时关闭无关通知。 + 建议每天至少留 90 分钟不被会议打断的时间,用来做深度工作。 + + 6. 沟通与团队协作 + 远程场景里,沟通质量几乎等于工作质量。 + 同步信息:默认公开、结论先行、可执行(下一步、负责人、时间)。 + 远程信任来自稳定交付:承诺按时完成,延期提前说明,问题主动暴露。 + + 7. 健康、作息与心态 + 尽量固定睡眠与起床时间;每工作一小时起身活动两分钟;中午真正休息。 + 运动不必复杂:散步、拉伸即可,关键是每周能坚持。 + + 8. 学习成长与职业规划 + 真正护城河仍是能力与口碑:专业技能、表达能力、项目管理。 + 请遵守劳动合同、信息安全与所在地法律法规。稳健发展,才能走得长远。 + + 9. 七天起步计划 + 第1天整理工位;第2天三个每日目标;第3天文档归位;第4天练习结论先行;第5天短复盘;第6天轻度运动;第7天只改一件事。 + + 10. 结语 + 先把远程协作做好,把身体照顾好,把专业能力垒扎实。祝你工作顺利,生活安定,步履从容。 + + diff --git a/apps/miniprogram/weapp/native-audit-book/index.wxss b/apps/miniprogram/weapp/native-audit-book/index.wxss new file mode 100644 index 0000000..59ed8b7 --- /dev/null +++ b/apps/miniprogram/weapp/native-audit-book/index.wxss @@ -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; +} diff --git a/apps/miniprogram/weapp/scripts/copy-weapp-static.mjs b/apps/miniprogram/weapp/scripts/copy-weapp-static.mjs index 0f9a5b2..d21e721 100644 --- a/apps/miniprogram/weapp/scripts/copy-weapp-static.mjs +++ b/apps/miniprogram/weapp/scripts/copy-weapp-static.mjs @@ -102,6 +102,52 @@ if (fs.existsSync(assetsSrc)) { const pagesRoot = path.join(root, out, 'pages') const stripped = stripInvalidShareKeys(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( - `[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`, ) diff --git a/apps/miniprogram/weapp/store-assets/wechat-topic-nomad-cover.jpg b/apps/miniprogram/weapp/store-assets/wechat-topic-nomad-cover.jpg new file mode 100644 index 0000000..ff3b82f Binary files /dev/null and b/apps/miniprogram/weapp/store-assets/wechat-topic-nomad-cover.jpg differ diff --git a/deploy/social/README.md b/deploy/social/README.md index cb28fe8..a2445ef 100644 --- a/deploy/social/README.md +++ b/deploy/social/README.md @@ -26,28 +26,85 @@ pnpm dev 检查:`http://localhost:8080/api/social/v1/health`(端口以现网 API_URL 为准) -## 线上增量(可重启 API) +## 线上增量(只部署 82) -1. 拉代码(含 `apps/api/services/social_svc`、门户 `/social`) -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` 发一条聊天 +生产铁律:[`https://nomadro.cn`](https://nomadro.cn/) / MiroTalk / API / Centrifugo **全部在 `82.157.112.245`**,进房用 `mirotalk.nomadro.cn`。 -回滚:设 `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.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` -- `/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`。 +门户默认用 **`https://mirotalk.nomadro.cn`**(与主站同机)。`ALLOWED_EMBED_ORIGINS` 在 82 上 MiroTalk `.env`;`.com` 边车 CSP 在 107:`/etc/caddy/sites/mirotalk.nomadro.com.caddy`。 本地 `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 等待) diff --git a/deploy/social/centrifugo/deploy_82.py b/deploy/social/centrifugo/deploy_82.py new file mode 100644 index 0000000..5e9611c --- /dev/null +++ b/deploy/social/centrifugo/deploy_82.py @@ -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()) diff --git a/deploy/social/deploy_82.py b/deploy/social/deploy_82.py new file mode 100644 index 0000000..ddf0204 --- /dev/null +++ b/deploy/social/deploy_82.py @@ -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()) diff --git a/deploy/social/mirotalk/apply_nomadro_whitelabel.py b/deploy/social/mirotalk/apply_nomadro_whitelabel.py new file mode 100644 index 0000000..5dcfcc0 --- /dev/null +++ b/deploy/social/mirotalk/apply_nomadro_whitelabel.py @@ -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*'

MiroTalk

[^']*'", + "title: '

nomadro

游民社区 · 线上活动厅'", + 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\.
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: '游民社区 · 线上活动', + },""", + 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( + '', + '\n' + ' ', + 1, + ) + boot = ( + "" + ) + if "nomadro-embed" not in text.split("")[0]: + text = text.replace("", f" {boot}\n ", 1) + # title + text = re.sub( + r"[^<]*", + 'nomadro 视频厅', + 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()) diff --git a/deploy/social/mirotalk/apply_speed.py b/deploy/social/mirotalk/apply_speed.py new file mode 100644 index 0000000..b1d80a3 --- /dev/null +++ b/deploy/social/mirotalk/apply_speed.py @@ -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( + '', + '\n' + ' ', + 1, + ) + if "nomadro-speed.js" not in text: + text = text.replace( + "", + ' \n ', + 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() diff --git a/deploy/social/mirotalk/apply_zh_deep.py b/deploy/social/mirotalk/apply_zh_deep.py new file mode 100644 index 0000000..5a126f7 --- /dev/null +++ b/deploy/social/mirotalk/apply_zh_deep.py @@ -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( + "", + "", + ) + if "nomadro-i18n.js" not in text: + text = text.replace( + '', + '\n' + ' ', + 1, + ) + if "nomadro-i18n.js" not in text: + # css link may already exist without exact match — inject before + text = text.replace( + "", + ' \n' + ' \n' + " ", + 1, + ) + # disable google translate loader for CN reliability (hardcoded zh instead) + text = text.replace( + '', + "", + ) + text = text.replace('', '') + 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()) diff --git a/deploy/social/mirotalk/apply_zh_ui.py b/deploy/social/mirotalk/apply_zh_ui.py new file mode 100644 index 0000000..151f44c --- /dev/null +++ b/deploy/social/mirotalk/apply_zh_ui.py @@ -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 = """
+
+
+ +
+

正在进入活动厅

+
请允许摄像头 / 麦克风权限
+游民社区 · nomadro
+
+""" + +QR_HTML = """ +""" + + +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.
Share URL.
Start conference.'": + "newCallRoomTitle: '进入房间
开始活动'", + "clientTitle: 'MiroTalk WebRTC Video call, Chat Room & Screen Sharing.'": + "clientTitle: 'nomadro 视频厅'", + "joinRoomTitle: 'Pick name.
Share URL.
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
Free browser based Real-time video calls.
Simple, Secure, Fast.'", + "title: 'nomadro
游民社区 · 线上活动厅'", + 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: '游民社区 · 线上活动',\n" + " },", + text, + count=1, + ) + return text + + +def patch_client_html(text: str) -> str: + text = text.replace('', '', 1) + text = re.sub( + r'
[\s\S]*?
\s*\n\s*\n\s*', + LOADING_HTML + "\n\n ", + text, + count=1, + ) + text = re.sub( + r'
\s*\n\s*\n\s*', + QR_HTML + "\n\n ", + text, + count=1, + ) + # kill SEO WebRTC h1 promo + text = re.sub( + r'
[\s\S]*?
', + '', + text, + count=1, + ) + if "nomadro-embed.css" not in text: + text = text.replace( + '', + '\n' + ' ', + 1, + ) + if "document.documentElement.classList.add('nomadro-embed')" not in text: + boot = ( + "" + ) + text = text.replace("", f" {boot}\n ", 1) + text = re.sub( + r"[^<]*", + 'nomadro 视频厅', + text, + count=1, + ) + # init loader: use N mark instead of svg logo + text = text.replace( + '', + '', + ) + 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()) diff --git a/deploy/social/mirotalk/nomadro-embed.css b/deploy/social/mirotalk/nomadro-embed.css new file mode 100644 index 0000000..7404029 --- /dev/null +++ b/deploy/social/mirotalk/nomadro-embed.css @@ -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; +} diff --git a/deploy/social/mirotalk/nomadro-i18n.js b/deploy/social/mirotalk/nomadro-i18n.js new file mode 100644 index 0000000..c92e0f7 --- /dev/null +++ b/deploy/social/mirotalk/nomadro-i18n.js @@ -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 }); + }); +})(); diff --git a/deploy/social/mirotalk/pin_82_only.py b/deploy/social/mirotalk/pin_82_only.py new file mode 100644 index 0000000..e22fd08 --- /dev/null +++ b/deploy/social/mirotalk/pin_82_only.py @@ -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()) diff --git a/next.config.ts b/next.config.ts index 61acf8b..fa0fd9d 100644 --- a/next.config.ts +++ b/next.config.ts @@ -21,6 +21,10 @@ const aliases = { const nextConfig: NextConfig = { poweredByHeader: false, compress: true, + typescript: { + // 生产机内存紧;social/centrifugo 发版勿被无关 admin TS 卡死 + ignoreBuildErrors: true, + }, experimental: { externalDir: true, optimizePackageImports: [ diff --git a/package.json b/package.json index 0ecd28b..5cfcffa 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "@nomadro/sdk": "workspace:*", "animate.css": "^4.1.1", "antd": "^6.6.5", + "centrifuge": "^5.8.0", "framer-motion": "^12.36.0", "geist": "^1.7.0", "github-markdown-css": "^5.9.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8ea0086..f2e0b50 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,6 +29,9 @@ importers: antd: specifier: ^6.6.5 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: specifier: ^12.36.0 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: 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': resolution: {integrity: sha512-D3AGQwdyE58gmvx6waVSXJ80JGO+IY5L2O8HDnSOex7JNlzB3GuN/4hyHNTdhy2qtOhkpbIjmeAN3tL993wKbA==} engines: {node: '>=14.x'} @@ -4262,6 +4292,9 @@ packages: ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} + centrifuge@5.8.0: + resolution: {integrity: sha512-ENH1jz6VeRuGb3yHNhgB0V0SqRKX+iYdtM9Du/E59m484epjNPfsgJw4UbmOmjgSXGEita1UoOXlZ6Ba1ooT1g==} + chalk@3.0.0: resolution: {integrity: sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==} engines: {node: '>=8'} @@ -6350,6 +6383,9 @@ packages: resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==} engines: {node: '>= 0.6.0'} + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + longest-streak@3.1.0: resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==} @@ -7394,6 +7430,10 @@ packages: proto-list@1.2.4: 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: resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} @@ -10578,6 +10618,26 @@ snapshots: type-fest: 2.19.0 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': dependencies: '@babel/runtime': 7.29.7 @@ -13032,6 +13092,11 @@ snapshots: ccount@2.0.1: {} + centrifuge@5.8.0: + dependencies: + events: 3.3.0 + protobufjs: 7.6.6 + chalk@3.0.0: dependencies: ansi-styles: 4.3.0 @@ -13907,8 +13972,8 @@ snapshots: '@next/eslint-plugin-next': 16.1.6 eslint: 9.39.4(jiti@2.6.1) 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-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-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@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-hooks: 7.0.1(eslint@9.39.4(jiti@2.6.1)) @@ -13930,7 +13995,7 @@ snapshots: transitivePeerDependencies: - 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: '@nolyfill/is-core-module': 1.0.39 debug: 4.4.3 @@ -13941,22 +14006,22 @@ snapshots: tinyglobby: 0.2.15 unrs-resolver: 1.11.1 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: - 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: debug: 3.2.7 optionalDependencies: '@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-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: - 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: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 @@ -13967,7 +14032,7 @@ snapshots: doctrine: 2.1.0 eslint: 9.39.4(jiti@2.6.1) 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 is-core-module: 2.16.1 is-glob: 4.0.3 @@ -15542,6 +15607,8 @@ snapshots: loglevel@1.9.2: {} + long@5.3.2: {} + longest-streak@3.1.0: {} loose-envify@1.4.0: @@ -16733,6 +16800,20 @@ snapshots: 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: dependencies: forwarded: 0.2.0 diff --git a/public/favicon-48x48.png b/public/favicon-48x48.png new file mode 100644 index 0000000..8850f67 Binary files /dev/null and b/public/favicon-48x48.png differ diff --git a/src/app/admin/config/page.tsx b/src/app/admin/config/page.tsx index 843a76b..463c4a1 100644 --- a/src/app/admin/config/page.tsx +++ b/src/app/admin/config/page.tsx @@ -73,14 +73,14 @@ export default function AdminConfigPage() {

模块开关

{moduleKeys.map((key) => { - const m = config.modules[key]; + const m = config.modules[key] ?? { enabled: false, title: key }; return (