Harden weapp/API P0 paths: VIP auth, ebook login, WAL limits, game stub.
Drop Three from weapp game, mount VIP library on unified API, and auto-enable local debug without manual .env. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
85211f2ff2
commit
017008dd7c
12
README.md
12
README.md
@ -119,9 +119,15 @@ pnpm dev:api
|
||||
|
||||
## pre4 摘要
|
||||
|
||||
- 微信启动页改为 **`pages/home/index`**(话题/体验码同路径);`pages/index` 兼容跳转
|
||||
- 首页样式源码在 `h5/src/pages/home`,`home/index.scss` 进 weapp `pxExclude`(真 px)
|
||||
- 本轮标记:**`20261011b`**(在 `20261011` 审核包之上仅改启动路径)
|
||||
- 微信启动页 **`pages/home/index`**(话题/体验码同路径);`pages/index` 兼容 `reLaunch` → home
|
||||
- 本轮标记:**`20261011b`**(视觉对齐 `20261011`)
|
||||
- **P0/P1 加固**
|
||||
- 统一 API 挂载 VIP library / weapp switches;VIP 正文需鉴权(目录可匿名)
|
||||
- Mine 统一 ebook 登录(`ensureLogin` / `clearLogin`)
|
||||
- weapp game:`index.weapp.tsx` stub + `IgnorePlugin(three)`,无 Three.js 包体
|
||||
- SQLite WAL + busy_timeout;login / pay / track 限流
|
||||
- CORS 白名单;本地自动 `.env`(`run.py`)与非生产默认 `DEBUG`/devtools;生产设 `NOMADRO_ENV=production`
|
||||
- 社区 API 默认 `https://api.nomadro.cn/api/v1`;`WechatOaModal` 进 `pxExclude`
|
||||
|
||||
## pre3 摘要(已合入)
|
||||
|
||||
|
||||
2
apps/api/.env.example
Normal file
2
apps/api/.env.example
Normal file
@ -0,0 +1,2 @@
|
||||
DEBUG=true
|
||||
WX_ALLOW_DEVTOOLS_LOGIN=true
|
||||
@ -22,6 +22,7 @@ if str(SERVICES) not in sys.path:
|
||||
sys.path.insert(0, str(SERVICES))
|
||||
|
||||
from ebook_svc.jobs import reconcile_pending_orders # noqa: E402
|
||||
from ebook_svc.config import settings as ebook_settings # noqa: E402
|
||||
from ebook_svc.routers import ( # noqa: E402
|
||||
admin,
|
||||
auth,
|
||||
@ -37,6 +38,9 @@ from ebook_svc.routers import ( # noqa: E402
|
||||
shop_admin,
|
||||
track,
|
||||
vip_admin,
|
||||
vip_library_admin,
|
||||
vip_library_public,
|
||||
weapp_switches_admin,
|
||||
)
|
||||
from community_svc.routers import ( # noqa: E402
|
||||
api as community_api,
|
||||
@ -94,9 +98,10 @@ app = FastAPI(
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
_cors = [o.strip() for o in str(ebook_settings.cors_origins or "").split(",") if o.strip()]
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_origins=_cors or ["https://admin.nomadro.cn", "https://nomadro.cn"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
@ -114,6 +119,9 @@ app.include_router(admin.router)
|
||||
app.include_router(douyin_admin.router)
|
||||
app.include_router(join_group_admin.router)
|
||||
app.include_router(vip_admin.router)
|
||||
app.include_router(vip_library_admin.router)
|
||||
app.include_router(vip_library_public.router)
|
||||
app.include_router(weapp_switches_admin.router)
|
||||
app.include_router(shop_admin.router)
|
||||
app.include_router(memo_admin.router)
|
||||
app.include_router(nav_admin.router)
|
||||
|
||||
@ -11,9 +11,26 @@ SERVICES = ROOT / "services"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(SERVICES))
|
||||
|
||||
_LOCAL_ENV = """# 本地开发自动生成 — 勿提交
|
||||
DEBUG=true
|
||||
WX_ALLOW_DEVTOOLS_LOGIN=true
|
||||
"""
|
||||
|
||||
|
||||
def _ensure_local_env() -> None:
|
||||
"""缺 .env 时自动写入本地调试开关,避免手动配。"""
|
||||
if os.getenv("NOMADRO_ENV", "").lower() in {"prod", "production"}:
|
||||
return
|
||||
env_path = ROOT / ".env"
|
||||
if env_path.exists():
|
||||
return
|
||||
env_path.write_text(_LOCAL_ENV, encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
_ensure_local_env()
|
||||
host = os.getenv("HOST", "127.0.0.1")
|
||||
port = int(os.getenv("PORT", "8080"))
|
||||
uvicorn.run("app.main:app", host=host, port=port, reload=os.getenv("RELOAD") == "1")
|
||||
|
||||
@ -1,16 +1,27 @@
|
||||
import os
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
def _local_dev_default() -> bool:
|
||||
"""非生产机默认开本地调试;生产设 NOMADRO_ENV=production。"""
|
||||
return os.getenv("NOMADRO_ENV", "").lower() not in {"prod", "production"}
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
app_name: str = "nomadmini-api"
|
||||
debug: bool = True
|
||||
# 本地默认开;生产用 NOMADRO_ENV=production 或 DEBUG=false
|
||||
debug: bool = _local_dev_default()
|
||||
api_host: str = "0.0.0.0"
|
||||
api_port: int = 8000
|
||||
public_api_base: str = "https://api.nomadro.cn"
|
||||
admin_origin: str = "https://admin.nomadro.cn"
|
||||
cors_origins: str = "https://admin.nomadro.cn,http://localhost:5173,http://127.0.0.1:5173"
|
||||
cors_origins: str = (
|
||||
"https://admin.nomadro.cn,https://nomadro.cn,https://www.nomadro.cn,"
|
||||
"http://localhost:5173,http://127.0.0.1:5173,http://localhost:3000,http://127.0.0.1:3000"
|
||||
)
|
||||
|
||||
# WeChat
|
||||
wx_appid: str = "wxa55815dd741a540d"
|
||||
@ -42,7 +53,8 @@ class Settings(BaseSettings):
|
||||
|
||||
wx_push_token: str = "hackrobot"
|
||||
wx_push_encoding_aes_key: str = "ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI"
|
||||
wx_allow_devtools_login: bool = True
|
||||
# 本地默认开;生产 NOMADRO_ENV=production 时默认关
|
||||
wx_allow_devtools_login: bool = _local_dev_default()
|
||||
|
||||
# ntfy(自建 https://ntfy.nomadro.cn)
|
||||
ntfy_enabled: bool = True
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
"""核心横切能力:依赖注入、鉴权。"""
|
||||
"""核心横切能力:鉴权 / SQLite / 限流。
|
||||
|
||||
from .deps import get_current_openid
|
||||
from .security import create_admin_token, require_admin
|
||||
|
||||
__all__ = ["get_current_openid", "create_admin_token", "require_admin"]
|
||||
注意:勿在此包级 import deps(会与 store 形成循环导入)。
|
||||
按需:`from ebook_svc.core.deps import get_current_openid`
|
||||
"""
|
||||
|
||||
35
apps/api/services/ebook_svc/core/rate_limit.py
Normal file
35
apps/api/services/ebook_svc/core/rate_limit.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""简易内存限流(单进程)。按 IP + 桶名滑动窗口。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from threading import Lock
|
||||
from typing import Deque
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
_lock = Lock()
|
||||
_buckets: dict[str, Deque[float]] = defaultdict(deque)
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str:
|
||||
forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()[:64]
|
||||
if request.client and request.client.host:
|
||||
return request.client.host
|
||||
return "unknown"
|
||||
|
||||
|
||||
def rate_limit(request: Request, *, bucket: str, limit: int, window_sec: float) -> None:
|
||||
"""超出限制抛 429。"""
|
||||
key = f"{bucket}:{_client_ip(request)}"
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
q = _buckets[key]
|
||||
cutoff = now - window_sec
|
||||
while q and q[0] < cutoff:
|
||||
q.popleft()
|
||||
if len(q) >= limit:
|
||||
raise HTTPException(429, "请求过于频繁,请稍后再试")
|
||||
q.append(now)
|
||||
19
apps/api/services/ebook_svc/core/sqlite_util.py
Normal file
19
apps/api/services/ebook_svc/core/sqlite_util.py
Normal file
@ -0,0 +1,19 @@
|
||||
"""SQLite 连接约定:WAL + busy_timeout,减轻并发写锁。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
|
||||
p = Path(path)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
c = sqlite3.connect(str(p), timeout=timeout)
|
||||
c.row_factory = sqlite3.Row
|
||||
try:
|
||||
c.execute("PRAGMA journal_mode=WAL")
|
||||
c.execute(f"PRAGMA busy_timeout={int(timeout * 1000)}")
|
||||
c.execute("PRAGMA synchronous=NORMAL")
|
||||
except sqlite3.Error:
|
||||
pass
|
||||
return c
|
||||
@ -2,9 +2,10 @@ from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.core.rate_limit import rate_limit
|
||||
from ebook_svc.schemas.auth import LoginBody
|
||||
from ebook_svc.services.pocketbase import pb
|
||||
from ebook_svc.services.store import store
|
||||
@ -17,9 +18,11 @@ __all__ = ["router", "get_current_openid", "LoginBody"]
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(body: LoginBody):
|
||||
async def login(body: LoginBody, request: Request):
|
||||
from ebook_svc.services.track import ingest_events
|
||||
|
||||
rate_limit(request, bucket="auth.login", limit=30, window_sec=60.0)
|
||||
|
||||
try:
|
||||
data = await code2session(body.code)
|
||||
except Exception as e:
|
||||
|
||||
@ -10,6 +10,7 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.core.rate_limit import rate_limit
|
||||
from ebook_svc.domains.books import is_book_free
|
||||
from ebook_svc.domains.books.products import PRODUCT_OFFERS
|
||||
from ebook_svc.schemas.pay import DevConfirmBody, OrderBody, StatusBody
|
||||
@ -154,8 +155,11 @@ async def _track_vip_order(openid: str, payload: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
@router.post("/vip-order")
|
||||
async def create_vip_pay_order(openid: str = Depends(get_current_openid)):
|
||||
async def create_vip_pay_order(
|
||||
request: Request, openid: str = Depends(get_current_openid)
|
||||
):
|
||||
"""VIP 会员虚拟支付下单 — 读 remote-config 道具,不查 books。"""
|
||||
rate_limit(request, bucket="pay.order", limit=20, window_sec=60.0)
|
||||
payload = _build_vip_order_payload(openid)
|
||||
await _track_vip_order(openid, payload)
|
||||
return payload
|
||||
@ -181,9 +185,11 @@ def _require_shop_vip(openid: str) -> None:
|
||||
@router.post("/shop-order")
|
||||
async def create_shop_pay_order(
|
||||
body: ShopOrderBody,
|
||||
request: Request,
|
||||
openid: str = Depends(get_current_openid),
|
||||
):
|
||||
"""电商虚拟支付下单:虚拟发卡 / 实体待发货。"""
|
||||
rate_limit(request, bucket="pay.order", limit=20, window_sec=60.0)
|
||||
_require_shop_vip(openid)
|
||||
product = shop_store.get_product(body.productId)
|
||||
if not product:
|
||||
@ -275,7 +281,10 @@ async def create_shop_pay_order(
|
||||
|
||||
|
||||
@router.post("/order")
|
||||
async def create_pay_order(body: OrderBody, openid: str = Depends(get_current_openid)):
|
||||
async def create_pay_order(
|
||||
body: OrderBody, request: Request, openid: str = Depends(get_current_openid)
|
||||
):
|
||||
rate_limit(request, bucket="pay.order", limit=20, window_sec=60.0)
|
||||
book = store.get_book(body.book_id)
|
||||
if not book:
|
||||
# 兼容旧 VIP 客户端:把 product_id 误当成 book_id 传来 → 走会员单
|
||||
@ -464,13 +473,11 @@ async def pay_notify(request: Request):
|
||||
pass
|
||||
|
||||
delivered = False
|
||||
# 仅对已登记 pending 订单发货;禁止无单号/未知单号直接 grant_unlock
|
||||
if out_trade_no and store.get_order(str(out_trade_no)):
|
||||
delivered = store.mark_delivered(
|
||||
str(out_trade_no), wx_order_id=str(wx_order_id), raw_notify=text
|
||||
)
|
||||
elif openid:
|
||||
store.grant_unlock(str(openid), book_id, source="pay")
|
||||
delivered = True
|
||||
|
||||
try:
|
||||
from ebook_svc.services.track import ingest_events
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Header
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Header, Request
|
||||
|
||||
from ebook_svc.core.rate_limit import rate_limit
|
||||
from ebook_svc.schemas.track import TrackBatchBody
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.track import ingest_events
|
||||
@ -14,9 +16,11 @@ router = APIRouter(prefix="/track", tags=["track"])
|
||||
@router.post("/")
|
||||
async def track_batch(
|
||||
body: TrackBatchBody,
|
||||
request: Request,
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
):
|
||||
"""小程序埋点上报。可匿名;若带 Bearer 则绑定 openid。"""
|
||||
rate_limit(request, bucket="track", limit=120, window_sec=60.0)
|
||||
openid = (body.openid or "").strip() or None
|
||||
if authorization and authorization.startswith("Bearer "):
|
||||
token = authorization.removeprefix("Bearer ").strip()
|
||||
|
||||
@ -1,21 +1,52 @@
|
||||
"""公开 VIP 正式内容 — 小程序拉电子书/课程(合法域名 API)。"""
|
||||
"""公开 VIP 正式内容 — 目录可匿名;正文需 VIP(免费方案除外)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ebook_svc.core.deps import get_optional_openid
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.vip_config import read_vip_config
|
||||
from ebook_svc.services.vip_library import get_course, get_ebook, get_lesson, library_meta, read_library
|
||||
|
||||
router = APIRouter(tags=["vip-library-public"])
|
||||
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
|
||||
_NO_STORE = {
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
}
|
||||
|
||||
|
||||
def _is_vip(openid: str) -> bool:
|
||||
cfg = read_vip_config()
|
||||
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
|
||||
return True
|
||||
if not openid:
|
||||
return False
|
||||
return store.is_unlocked(openid, VIP_BOOK_ID)
|
||||
|
||||
|
||||
def _strip_ebook(book: dict[str, Any]) -> dict[str, Any]:
|
||||
"""未解锁:只返回元信息,去掉章节正文。"""
|
||||
out = {k: v for k, v in book.items() if k != "chapters"}
|
||||
chapters = book.get("chapters")
|
||||
if isinstance(chapters, list):
|
||||
out["chapters"] = [
|
||||
{
|
||||
"id": c.get("id"),
|
||||
"title": c.get("title"),
|
||||
"locked": True,
|
||||
}
|
||||
for c in chapters
|
||||
if isinstance(c, dict)
|
||||
]
|
||||
out["locked"] = True
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/api/vip/library/meta")
|
||||
@router.get("/api/ebook/vip/library/meta")
|
||||
async def public_library_meta() -> JSONResponse:
|
||||
@ -24,14 +55,33 @@ async def public_library_meta() -> JSONResponse:
|
||||
|
||||
@router.get("/api/vip/library")
|
||||
@router.get("/api/ebook/vip/library")
|
||||
async def public_library() -> JSONResponse:
|
||||
async def public_library(openid: str = Depends(get_optional_openid)) -> JSONResponse:
|
||||
lib = read_library()
|
||||
return JSONResponse(content={"ok": True, **lib}, headers=_NO_STORE)
|
||||
if _is_vip(openid):
|
||||
return JSONResponse(content={"ok": True, **lib}, headers=_NO_STORE)
|
||||
# 未 VIP:课程大纲可看,电子书正文与课时 markdown 剥离
|
||||
ebooks = lib.get("ebooks") if isinstance(lib.get("ebooks"), dict) else {}
|
||||
stripped_books = {
|
||||
k: _strip_ebook(v) if isinstance(v, dict) else v for k, v in ebooks.items()
|
||||
}
|
||||
return JSONResponse(
|
||||
content={
|
||||
"ok": True,
|
||||
"version": lib.get("version"),
|
||||
"ebooks": stripped_books,
|
||||
"course": lib.get("course") or get_course(),
|
||||
"lessons": {},
|
||||
"locked": True,
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/vip/ebooks/{book_id}")
|
||||
@router.get("/api/ebook/vip/ebooks/{book_id}")
|
||||
async def public_ebook(book_id: str) -> JSONResponse:
|
||||
async def public_ebook(
|
||||
book_id: str, openid: str = Depends(get_optional_openid)
|
||||
) -> JSONResponse:
|
||||
book = get_ebook(book_id)
|
||||
if not book:
|
||||
return JSONResponse(
|
||||
@ -39,6 +89,11 @@ async def public_ebook(book_id: str) -> JSONResponse:
|
||||
status_code=404,
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
if not _is_vip(openid):
|
||||
return JSONResponse(
|
||||
content={"ok": True, "ebook": _strip_ebook(book), "locked": True},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
return JSONResponse(content={"ok": True, "ebook": book}, headers=_NO_STORE)
|
||||
|
||||
|
||||
@ -50,10 +105,11 @@ async def public_course() -> JSONResponse:
|
||||
|
||||
@router.get("/api/vip/lessons/{lesson_key}")
|
||||
@router.get("/api/ebook/vip/lessons/{lesson_key}")
|
||||
async def public_lesson(lesson_key: str) -> JSONResponse:
|
||||
async def public_lesson(
|
||||
lesson_key: str, openid: str = Depends(get_optional_openid)
|
||||
) -> JSONResponse:
|
||||
lesson = get_lesson(lesson_key)
|
||||
course = get_course()
|
||||
# also resolve lesson meta from course modules
|
||||
meta: dict[str, Any] | None = None
|
||||
for m in course.get("modules") or []:
|
||||
if not isinstance(m, dict):
|
||||
@ -68,6 +124,17 @@ async def public_lesson(lesson_key: str) -> JSONResponse:
|
||||
status_code=404,
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
if not _is_vip(openid):
|
||||
return JSONResponse(
|
||||
content={
|
||||
"ok": True,
|
||||
"key": lesson_key,
|
||||
"lesson": {},
|
||||
"meta": meta,
|
||||
"locked": True,
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
return JSONResponse(
|
||||
content={
|
||||
"ok": True,
|
||||
|
||||
@ -124,8 +124,9 @@ class MemoStore:
|
||||
|
||||
@contextmanager
|
||||
def conn(self):
|
||||
c = sqlite3.connect(self.path)
|
||||
c.row_factory = sqlite3.Row
|
||||
from ebook_svc.core.sqlite_util import connect as sqlite_connect
|
||||
|
||||
c = sqlite_connect(self.path)
|
||||
try:
|
||||
yield c
|
||||
c.commit()
|
||||
|
||||
@ -85,8 +85,9 @@ class ShopStore:
|
||||
|
||||
@contextmanager
|
||||
def conn(self):
|
||||
c = sqlite3.connect(self.path)
|
||||
c.row_factory = sqlite3.Row
|
||||
from ebook_svc.core.sqlite_util import connect as sqlite_connect
|
||||
|
||||
c = sqlite_connect(self.path)
|
||||
try:
|
||||
yield c
|
||||
c.commit()
|
||||
|
||||
@ -116,8 +116,9 @@ class Store:
|
||||
|
||||
@contextmanager
|
||||
def conn(self):
|
||||
c = sqlite3.connect(self.path)
|
||||
c.row_factory = sqlite3.Row
|
||||
from ebook_svc.core.sqlite_util import connect as sqlite_connect
|
||||
|
||||
c = sqlite_connect(self.path)
|
||||
try:
|
||||
yield c
|
||||
c.commit()
|
||||
|
||||
@ -13,7 +13,7 @@ const h5ViteProxy = {
|
||||
rewrite: (p: string) => p.replace(/^\/ebook-api/, ''),
|
||||
},
|
||||
'/community-api': {
|
||||
target: process.env.TARO_H5_COMMUNITY_PROXY || 'https://nomadweb.nomadro.com',
|
||||
target: process.env.TARO_H5_COMMUNITY_PROXY || 'https://api.nomadro.cn',
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
rewrite: (p: string) => p.replace(/^\/community-api/, '/api/v1'),
|
||||
@ -42,7 +42,7 @@ export default defineConfig(async (merge) => {
|
||||
defineConstants: {
|
||||
TARO_APP_API: JSON.stringify(defaultApi),
|
||||
TARO_APP_COMMUNITY_API: JSON.stringify(
|
||||
process.env.TARO_APP_COMMUNITY_API || 'https://nomadweb.nomadro.com/api/v1',
|
||||
process.env.TARO_APP_COMMUNITY_API || 'https://api.nomadro.cn/api/v1',
|
||||
),
|
||||
TARO_APP_GATEWAY: JSON.stringify(
|
||||
process.env.TARO_APP_GATEWAY || process.env.TARO_APP_API || defaultApi,
|
||||
|
||||
@ -131,6 +131,7 @@ const weappConfig = {
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
// weapp 用 index.weapp.tsx stub(无 Three.js);H5 仍用完整 index.tsx
|
||||
root: 'pages/game',
|
||||
name: 'game',
|
||||
pages: ['index'],
|
||||
|
||||
25
apps/miniprogram/h5/src/modules/game/nomad3d.weapp.ts
Normal file
25
apps/miniprogram/h5/src/modules/game/nomad3d.weapp.ts
Normal file
@ -0,0 +1,25 @@
|
||||
/** weapp:不打包 three,占位实现 */
|
||||
export type GameHud = {
|
||||
day: number
|
||||
cash: number
|
||||
energy: number
|
||||
mood: number
|
||||
location: string
|
||||
}
|
||||
|
||||
export type Nomad3DHandle = {
|
||||
destroy: () => void
|
||||
restart: () => void
|
||||
setInput: (v: { x?: number; z?: number; interact?: boolean }) => void
|
||||
}
|
||||
|
||||
export function createNomad3D(
|
||||
_canvas: unknown,
|
||||
_opts?: { onHud?: (h: GameHud) => void; onToast?: (m: string) => void },
|
||||
): Nomad3DHandle {
|
||||
return {
|
||||
destroy() {},
|
||||
restart() {},
|
||||
setInput() {},
|
||||
}
|
||||
}
|
||||
9
apps/miniprogram/h5/src/pages/game/index.weapp.scss
Normal file
9
apps/miniprogram/h5/src/pages/game/index.weapp.scss
Normal file
@ -0,0 +1,9 @@
|
||||
.game-stub {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #0c0c0f;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
}
|
||||
20
apps/miniprogram/h5/src/pages/game/index.weapp.tsx
Normal file
20
apps/miniprogram/h5/src/pages/game/index.weapp.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
/**
|
||||
* weapp 冷冻 stub:不引入 Three.js,避免 ~2MB;入口默认关闭。
|
||||
* H5 仍用同目录 index.tsx 完整游戏。
|
||||
*/
|
||||
import { View, Text } from '@tarojs/components'
|
||||
import Taro, { useLoad } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import './index.weapp.scss'
|
||||
|
||||
export default function GameStubPage() {
|
||||
useLoad(() => {
|
||||
Taro.showToast({ title: '游戏仅 H5 可用', icon: 'none', duration: 1500 })
|
||||
setTimeout(() => goPage('/pages/home/index'), 400)
|
||||
})
|
||||
return (
|
||||
<View className="game-stub">
|
||||
<Text>游戏入口已关闭</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@ -3,37 +3,56 @@ import Taro from '@tarojs/taro'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { BrandNav, SiteFooter } from '../../components/Chrome'
|
||||
import { DestCard } from '../../components/DestCard'
|
||||
import { STORAGE_TOKEN } from '../../utils/config'
|
||||
import { STORAGE_OPENID, STORAGE_TOKEN } from '../../utils/config'
|
||||
import { clearLogin, ensureLogin, requestEbook } from '../../utils/request'
|
||||
import {
|
||||
fetchFavoriteDetails,
|
||||
fetchMe,
|
||||
fetchProfileStats,
|
||||
loginWechat,
|
||||
type AuthUser,
|
||||
type Destination,
|
||||
type ProfileStats,
|
||||
} from '../../services/api'
|
||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||
import './index.scss'
|
||||
|
||||
type MineUser = {
|
||||
id: string
|
||||
name: string
|
||||
email: string
|
||||
avatar: string
|
||||
isVip?: boolean
|
||||
}
|
||||
|
||||
function MinePage() {
|
||||
usePageShare({ title: 'nomadro · 我的', path: '/pages/mine/index' })
|
||||
const [user, setUser] = useState<AuthUser | null>(null)
|
||||
const [user, setUser] = useState<MineUser | null>(null)
|
||||
const [stats, setStats] = useState<ProfileStats | null>(null)
|
||||
const [favs, setFavs] = useState<Destination[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function refresh() {
|
||||
const t = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
if (!t) {
|
||||
const token = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
const openid = Taro.getStorageSync(STORAGE_OPENID)
|
||||
if (!token || !openid) {
|
||||
setUser(null)
|
||||
setStats(null)
|
||||
setFavs([])
|
||||
return
|
||||
}
|
||||
try {
|
||||
const me = await fetchMe()
|
||||
setUser(me)
|
||||
// 主会话:ebook Bearer(与支付 / VIP 一致)
|
||||
const presence = await requestEbook<{
|
||||
ok?: boolean
|
||||
openid?: string
|
||||
isVip?: boolean
|
||||
}>({ url: '/api/ebook/auth/presence', method: 'POST' })
|
||||
setUser({
|
||||
id: String(presence.openid || openid),
|
||||
name: 'Nomadro 用户',
|
||||
email: '',
|
||||
avatar: '🟢',
|
||||
isVip: Boolean(presence.isVip),
|
||||
})
|
||||
// 社群收藏为增强项,失败不踢主登录
|
||||
const [s, f] = await Promise.all([
|
||||
fetchProfileStats().catch(() => null),
|
||||
fetchFavoriteDetails().catch(() => [] as Destination[]),
|
||||
@ -41,35 +60,29 @@ function MinePage() {
|
||||
setStats(s)
|
||||
setFavs(f)
|
||||
} catch {
|
||||
Taro.removeStorageSync(STORAGE_TOKEN)
|
||||
clearLogin()
|
||||
setUser(null)
|
||||
setStats(null)
|
||||
setFavs([])
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { refresh() }, [])
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [])
|
||||
|
||||
async function onWechatLogin() {
|
||||
if (loading) return
|
||||
setLoading(true)
|
||||
try {
|
||||
const { ensureLogin } = await import('../../utils/request')
|
||||
try {
|
||||
const { code } = await Taro.login()
|
||||
if (!code) throw new Error('获取登录码失败')
|
||||
const res = await loginWechat(code)
|
||||
Taro.setStorageSync(STORAGE_TOKEN, res.token)
|
||||
setUser(res.user)
|
||||
} catch {
|
||||
await ensureLogin(true)
|
||||
setUser({
|
||||
id: 'wx',
|
||||
email: '',
|
||||
name: 'Nomadro 用户',
|
||||
avatar: '🟢',
|
||||
})
|
||||
}
|
||||
// 统一走 ebook /api/ebook/auth/login,勿再写社区 token
|
||||
const session = await ensureLogin(true)
|
||||
setUser({
|
||||
id: session.openid,
|
||||
name: 'Nomadro 用户',
|
||||
email: '',
|
||||
avatar: '🟢',
|
||||
})
|
||||
await refresh().catch(() => undefined)
|
||||
Taro.showToast({ title: '登录成功', icon: 'success' })
|
||||
} catch (e) {
|
||||
@ -81,74 +94,86 @@ function MinePage() {
|
||||
}
|
||||
|
||||
function onLogout() {
|
||||
Taro.removeStorageSync(STORAGE_TOKEN)
|
||||
clearLogin()
|
||||
setUser(null)
|
||||
setStats(null)
|
||||
setFavs([])
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView scrollY className='page-shell' showScrollbar={false}>
|
||||
<BrandNav chip='我的' />
|
||||
<View className='container' style={{ paddingBottom: '48px' }}>
|
||||
<Text className='section-tag'>👤 MINE</Text>
|
||||
<Text className='section-h2'>我的</Text>
|
||||
<ScrollView scrollY className="page-shell" showScrollbar={false}>
|
||||
<BrandNav chip="我的" />
|
||||
<View className="container" style={{ paddingBottom: '48px' }}>
|
||||
<Text className="section-tag">👤 MINE</Text>
|
||||
<Text className="section-h2">我的</Text>
|
||||
|
||||
{!user ? (
|
||||
<View className='profile-header'>
|
||||
<View className='profile-avatar'><Text>🧑💻</Text></View>
|
||||
<Text className='profile-name'>未登录</Text>
|
||||
<Text className='profile-email'>微信一键登录,同步收藏与等级</Text>
|
||||
<Button className='btn btn-primary' loading={loading} onClick={onWechatLogin}>
|
||||
<View className="profile-header">
|
||||
<View className="profile-avatar">
|
||||
<Text>🧑💻</Text>
|
||||
</View>
|
||||
<Text className="profile-name">未登录</Text>
|
||||
<Text className="profile-email">微信一键登录,同步会员与收藏</Text>
|
||||
<Button className="btn btn-primary" loading={loading} onClick={onWechatLogin}>
|
||||
微信登录
|
||||
</Button>
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
<View className='profile-header'>
|
||||
<View className='profile-avatar'><Text>{user.avatar || '🟢'}</Text></View>
|
||||
<Text className='profile-name'>{user.name}</Text>
|
||||
<Text className='profile-email'>{user.email}</Text>
|
||||
{stats ? <Text className='profile-level'>{stats.nomad_level}</Text> : null}
|
||||
<Button className='btn btn-ghost' onClick={onLogout}>退出登录</Button>
|
||||
<View className="profile-header">
|
||||
<View className="profile-avatar">
|
||||
<Text>{user.avatar || '🟢'}</Text>
|
||||
</View>
|
||||
<Text className="profile-name">{user.name}</Text>
|
||||
<Text className="profile-email">
|
||||
{user.isVip ? '👑 VIP 会员' : '普通用户 · 可开通 VIP'}
|
||||
</Text>
|
||||
{stats ? <Text className="profile-level">{stats.nomad_level}</Text> : null}
|
||||
<Button className="btn btn-ghost" onClick={onLogout}>
|
||||
退出登录
|
||||
</Button>
|
||||
</View>
|
||||
|
||||
{stats ? (
|
||||
<View className='profile-stats'>
|
||||
<View className='profile-stat'>
|
||||
<View className="profile-stats">
|
||||
<View className="profile-stat">
|
||||
<Text>❤️</Text>
|
||||
<Text className='profile-stat-n'>{stats.favorites_count}</Text>
|
||||
<Text className='profile-stat-l'>收藏</Text>
|
||||
<Text className="profile-stat-n">{stats.favorites_count}</Text>
|
||||
<Text className="profile-stat-l">收藏</Text>
|
||||
</View>
|
||||
<View className='profile-stat'>
|
||||
<View className="profile-stat">
|
||||
<Text>🗺️</Text>
|
||||
<Text className='profile-stat-n'>{stats.destinations_explored}</Text>
|
||||
<Text className='profile-stat-l'>探索</Text>
|
||||
<Text className="profile-stat-n">{stats.destinations_explored}</Text>
|
||||
<Text className="profile-stat-l">探索</Text>
|
||||
</View>
|
||||
<View className='profile-stat'>
|
||||
<View className="profile-stat">
|
||||
<Text>🏅</Text>
|
||||
<Text className='profile-stat-n'>{stats.member_since}</Text>
|
||||
<Text className='profile-stat-l'>加入</Text>
|
||||
<Text className="profile-stat-n">{stats.member_since}</Text>
|
||||
<Text className="profile-stat-l">加入</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Text className='section-h2' style={{ fontSize: '32px', marginBottom: '16px' }}>❤️ 收藏的城市</Text>
|
||||
{favs.length ? favs.map((d) => <DestCard key={d.slug} d={d} favorited />) : (
|
||||
<Text className='dest-empty'>还没有收藏 · 去目的地逛逛</Text>
|
||||
<Text className="section-h2" style={{ fontSize: '32px', marginBottom: '16px' }}>
|
||||
❤️ 收藏的城市
|
||||
</Text>
|
||||
{favs.length ? (
|
||||
favs.map((d) => <DestCard key={d.slug} d={d} favorited />)
|
||||
) : (
|
||||
<Text className="dest-empty">还没有收藏 · 去目的地逛逛</Text>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button
|
||||
className='btn btn-primary'
|
||||
className="btn btn-primary"
|
||||
style={{ marginTop: '16px', width: '100%' }}
|
||||
onClick={() => Taro.navigateTo({ url: '/pages/vip/index' })}
|
||||
>
|
||||
👑 开通 VIP
|
||||
</Button>
|
||||
<Button
|
||||
className='btn btn-ghost'
|
||||
className="btn btn-ghost"
|
||||
style={{ marginTop: '24px', width: '100%' }}
|
||||
onClick={() => Taro.setClipboardData({ data: 'https://nomadro.cn' })}
|
||||
>
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
* 网络失败 → 包内 vipEbooks / vipCourse / vipLessonContent 兜底
|
||||
*/
|
||||
import Taro from '@tarojs/taro'
|
||||
import { API_BASE, APP_TARGET, WEB_BASE } from '../utils/config'
|
||||
import { API_BASE, APP_TARGET, STORAGE_TOKEN, WEB_BASE } from '../utils/config'
|
||||
import {
|
||||
VIP_EBOOKS,
|
||||
type VipEbookId,
|
||||
@ -68,9 +68,14 @@ function writeCache(data: LibraryPayload) {
|
||||
}
|
||||
|
||||
async function fetchJson(path: string): Promise<LibraryPayload | null> {
|
||||
const token = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
const header: Record<string, string> = {
|
||||
'Cache-Control': 'no-cache',
|
||||
}
|
||||
if (token) header.Authorization = `Bearer ${token}`
|
||||
for (const url of urls(path)) {
|
||||
try {
|
||||
const res = await Taro.request({ url, method: 'GET', timeout: 8000 })
|
||||
const res = await Taro.request({ url, method: 'GET', timeout: 8000, header })
|
||||
if (res.statusCode >= 400) continue
|
||||
const body = res.data as LibraryPayload
|
||||
if (body && (body.ebooks || body.course || body.ok)) return body
|
||||
|
||||
@ -26,7 +26,7 @@ export const COMMUNITY_API_BASE = isH5
|
||||
? '/community-api'
|
||||
: typeof TARO_APP_COMMUNITY_API !== 'undefined' && TARO_APP_COMMUNITY_API
|
||||
? String(TARO_APP_COMMUNITY_API).replace(/\/$/, '')
|
||||
: 'https://nomadweb.nomadro.com/api/v1'
|
||||
: 'https://api.nomadro.cn/api/v1'
|
||||
|
||||
/**
|
||||
* 统一网关(VIP 等,默认与电子书同域或 apps/api)
|
||||
|
||||
@ -24,7 +24,8 @@ const pxExclude = (file: string) =>
|
||||
/[\\/]pages[\\/]nav[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]book[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]community[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip[\\/]index\.scss/.test(file)
|
||||
/[\\/]pages[\\/]vip[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]components[\\/]WechatOaModal\.scss/.test(file)
|
||||
|
||||
export default defineConfig(async (merge) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
|
||||
@ -28,6 +28,7 @@ pnpm --dir apps/miniprogram/weapp build:weapp # 或根目录 pnpm build:weapp
|
||||
| 组件按需注入 | `lazyCodeLoading: "requiredComponents"` |
|
||||
| 图片合计 ≤200K | 导航图标不进包,运行时 `https://nomadro.cn/icons/*.webp`(后台 download/图片域名放行 `nomadro.cn`) |
|
||||
| 安全区 | `utils/safeArea.ts` → `safePx()` 大写 `PX`,避免内联被转 rpx |
|
||||
| game 冷冻 | weapp 用 `index.weapp.tsx` stub(无 Three.js);H5 完整游戏 |
|
||||
|
||||
`scripts/copy-weapp-static.mjs`:清历史 `icons/`,只同步必要 `assets`(如公众号二维码)。
|
||||
|
||||
|
||||
@ -38,7 +38,8 @@ const pxExclude = (file: string) =>
|
||||
/[\\/]pages[\\/]vip-store-orders[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-memo[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-memo-detail[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]components[\\/]DebugFab\.scss/.test(file)
|
||||
/[\\/]components[\\/]DebugFab\.scss/.test(file) ||
|
||||
/[\\/]components[\\/]WechatOaModal\.scss/.test(file)
|
||||
|
||||
export default defineConfig(async (merge) => {
|
||||
const baseConfig: UserConfigExport = {
|
||||
@ -57,7 +58,7 @@ export default defineConfig(async (merge) => {
|
||||
defineConstants: {
|
||||
TARO_APP_API: JSON.stringify(defaultApi),
|
||||
TARO_APP_COMMUNITY_API: JSON.stringify(
|
||||
process.env.TARO_APP_COMMUNITY_API || 'https://nomadweb.nomadro.com/api/v1',
|
||||
process.env.TARO_APP_COMMUNITY_API || 'https://api.nomadro.cn/api/v1',
|
||||
),
|
||||
TARO_APP_GATEWAY: JSON.stringify(
|
||||
process.env.TARO_APP_GATEWAY || process.env.TARO_APP_API || defaultApi,
|
||||
@ -85,11 +86,24 @@ export default defineConfig(async (merge) => {
|
||||
},
|
||||
modifyWebpackChain(chain) {
|
||||
const weappNm = path.resolve(__dirname, '..', 'node_modules')
|
||||
const webpack = require('webpack')
|
||||
chain.resolve.modules.prepend(weappNm)
|
||||
chain.resolve.alias.set(
|
||||
'@tarojs/plugin-platform-weapp',
|
||||
path.join(weappNm, '@tarojs/plugin-platform-weapp'),
|
||||
)
|
||||
// game:weapp 用无 three 的 stub,避免 ~2MB
|
||||
chain.resolve.alias.set(
|
||||
path.join(h5Src, 'modules/game/nomad3d'),
|
||||
path.join(h5Src, 'modules/game/nomad3d.weapp.ts'),
|
||||
)
|
||||
chain.resolve.alias.set(
|
||||
'@/modules/game/nomad3d',
|
||||
path.join(h5Src, 'modules/game/nomad3d.weapp.ts'),
|
||||
)
|
||||
chain.plugin('ignore-three').use(webpack.IgnorePlugin, [
|
||||
{ resourceRegExp: /^three$/ },
|
||||
])
|
||||
// 导航图标不进包:运行时用 https://nomadro.cn/icons(代码质量:图片合计≤200K)
|
||||
// watch 完成后补缺失页面 wxss(home/index 样式进 common 时 Taro 不落文件)
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
|
||||
Loading…
Reference in New Issue
Block a user