Isolate WeChat audit books as always-free from paid unlocks.
Keep review-mode content off nomad VIP/purchase state, document the rule in README, and add the 82 API push script. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
cee288b764
commit
60606e53a7
21
README.md
21
README.md
@ -10,6 +10,8 @@
|
||||
>
|
||||
> 反代、发版、鉴权、LIVE 注入、文档里写「管理后台」时必须带全称域名。规则见 \.cursor/rules/admin-hosts-never-confuse.mdc\。
|
||||
|
||||
2026-11-22:微信小册**提审态默认免费**,且与正式付费数据隔离 — `platforms.weapp.bookAudit.reviewMode` 开启时读独立 `audit*` 书(永远 `is_free` / 不可下单 / 不读正式 `unlocks`·`__vip__`);关闭后重新拉正式已购与 VIP,互不粘态。weapp App 挂远程配置 WS + 1s 轮询,后台开关约 1s 热更新。API 已推 `api.nomadro.cn`(`_push_audit_free_isolate.py`);体验包须本轮许可后再 `build:weapp` 上传。
|
||||
|
||||
2026-11-15:VIP 运营台实时能力 — dmin.hackrobot.cn LIVE 在线/弹窗通知(ops token ↔ /api/admin/live)、用户拉黑/曾拉黑 tag 与身份提示;**写死** dmin.hackrobot.cn 与 dmin.nomadro.cn 永远禁止混淆。资产 pps/admin/deploy/_vip_live_assets/ · API live_ops/ops_live。
|
||||
|
||||
|
||||
@ -232,10 +234,10 @@ pnpm dev:api
|
||||
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
|
||||
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
|
||||
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
||||
- 审核冻结分支:`pre4`(历史审核包);**本轮微信提审包:`test9` + tag `2026-11-02`**
|
||||
- 审核冻结分支:`pre4`(历史审核包);历史微信提审包:`test9` + tag `2026-11-02`
|
||||
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
|
||||
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
|
||||
- **当前开发 / 提审分支:`test9`**(tag `2026-11-02`)
|
||||
- **当前开发分支:`test14`**(微信小册提审隔离与热更新在此迭代;历史定版 tag 仍见 `test9`)
|
||||
|
||||
### 游民社区(`/social`)
|
||||
|
||||
@ -367,26 +369,29 @@ pnpm dev # http://localhost:3000/social/coffeechat
|
||||
| 分支 / Tag | `test9` · **`2026-11-02`** |
|
||||
| 启动页 | `pages/home/index`;门户入口 2×2;固定暗色(无主题切换) |
|
||||
| 远程配置 | `POST /api/config/pull`(避微信 GET 缓存)· `WS /api/config/ws` · SSE `/stream` · meta 兜底;后台 `/wechat/switches` |
|
||||
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 audit 正文(失联才包内兜底);关则正式 nomad |
|
||||
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` |
|
||||
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 **audit 正文(默认免费全文)**;关则正式 nomad |
|
||||
| 提审/正式隔离 | 提审不读正式已购·VIP·付费方案;正式不粘提审免费态;`audit*` 书禁下单 / 禁手动解锁 / 禁配付费档 |
|
||||
| 配置热更新 | weapp `app.weapp`:WS + 1s poll;封面/阅读页 1s 拉配置;后台开关约 1s 生效 |
|
||||
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` · VIP 库「微信提审」卡 |
|
||||
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
|
||||
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
|
||||
| 加入资料 | `/social/join`:支付 → profile 双栏名片 · 头像 `POST /upload` → SeaweedFS `s3.nomadro.com` |
|
||||
| 同域自研 | `/social/work` · `/social/notify` · `/notifications` · `/social/coffeechat`(禁 iframe) |
|
||||
|
||||
提审上传:
|
||||
提审上传(**须本轮明确许可**,见 `no-frontend-deploy-without-ok`):
|
||||
|
||||
```bash
|
||||
pnpm build:weapp
|
||||
# 微信开发者工具打开 apps/miniprogram/weapp(miniprogramRoot=dist/)→ 上传
|
||||
# 后台按需打开「数字游民」提审;socket 合法域名含 api.nomadro.cn
|
||||
# 微信开发者工具 / cli 上传 apps/miniprogram/weapp(miniprogramRoot=dist/)
|
||||
# 后台 VIP→电子书→数字游民打开「提审中」;socket 合法域名含 api.nomadro.cn
|
||||
# 后端隔离补丁:python apps/admin/deploy/_push_audit_free_isolate.py
|
||||
```
|
||||
|
||||
## pre3 摘要(已合入)
|
||||
|
||||
微信提审与包体:
|
||||
|
||||
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书,关则回正式 VIP 书;前端不展示「提审」文案
|
||||
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书(**默认免费**,与正式已购/VIP 隔离),关则回正式 VIP 书;前端不展示「提审」文案
|
||||
- **入口默认隐藏**:远程配置未就绪不渲染门户卡片 / 模块闸门,避免先闪后藏
|
||||
- **安全区**:自定义顶栏内联尺寸用大写 `PX` 跳过 Taro rpx;阅读页顶栏不再叠状态栏 padding
|
||||
- **代码质量**:`lazyCodeLoading` · 分包 + `optimizeMainPackage`(主包 ≪1.5MB)· 导航图标走 `https://nomadro.cn/icons`(包内图片合计 ≤200K)
|
||||
|
||||
108
apps/admin/deploy/_push_audit_free_isolate.py
Normal file
108
apps/admin/deploy/_push_audit_free_isolate.py
Normal file
@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Push audit-book free + pay isolation patches → 82 nomadmini-api (backend only)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
|
||||
FILES = [
|
||||
("apps/api/services/ebook_svc/domains/books/products.py", "domains/books/products.py"),
|
||||
("apps/api/services/ebook_svc/domains/books/__init__.py", "domains/books/__init__.py"),
|
||||
("apps/api/services/ebook_svc/routers/books.py", "routers/books.py"),
|
||||
("apps/api/services/ebook_svc/routers/pay.py", "routers/pay.py"),
|
||||
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
|
||||
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
|
||||
]
|
||||
|
||||
|
||||
def rewrite(text: str) -> str:
|
||||
return text.replace("ebook_svc.", "app.")
|
||||
|
||||
|
||||
def pack() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for rel, dest in FILES:
|
||||
src = REPO / rel
|
||||
text = rewrite(src.read_text(encoding="utf-8"))
|
||||
if "ebook_svc." in text:
|
||||
raise SystemExit(f"rewrite failed: {rel}")
|
||||
data = text.encode("utf-8")
|
||||
info = tarfile.TarInfo(name="api/" + dest)
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
print("pack", dest, flush=True)
|
||||
buf.seek(0)
|
||||
blob = buf.read()
|
||||
print("blob", len(blob), flush=True)
|
||||
return blob
|
||||
|
||||
|
||||
REMOTE_CMD = r"""
|
||||
set -e
|
||||
cd /tmp
|
||||
rm -rf audit-free-api && mkdir audit-free-api
|
||||
tar -xzf audit-free-api.tar.gz -C audit-free-api
|
||||
B=/opt/nomadmini/backend/app
|
||||
for f in domains/books/products.py domains/books/__init__.py routers/books.py routers/pay.py routers/admin.py services/store.py; do
|
||||
sudo cp -a "$B/$f" "$B/$f.bak-audit-free" 2>/dev/null || true
|
||||
sudo mkdir -p "$(dirname "$B/$f")"
|
||||
sudo cp "audit-free-api/api/$f" "$B/$f"
|
||||
echo copied $f
|
||||
done
|
||||
cd /opt/nomadmini/backend
|
||||
.venv/bin/python - <<'PY'
|
||||
from app.domains.books import is_audit_book_id, is_book_free
|
||||
assert is_audit_book_id('audit')
|
||||
assert is_audit_book_id('audit-v2')
|
||||
assert not is_audit_book_id('nomad')
|
||||
assert is_book_free({'id': 'audit', 'unlock_percent': 30})
|
||||
print('audit_free_ok')
|
||||
PY
|
||||
sudo systemctl restart nomadmini-api
|
||||
sleep 3
|
||||
systemctl is-active nomadmini-api
|
||||
curl -sk -o /dev/null -w 'health %{http_code}\n' https://api.nomadro.cn/health
|
||||
curl -sk 'https://api.nomadro.cn/api/ebook/books/audit' | python3 -c 'import sys,json; d=json.load(sys.stdin); print("audit", d.get("id"), "free", d.get("is_free"), "pct", d.get("unlock_percent"), "fen", d.get("price_fen"))'
|
||||
rm -rf /tmp/audit-free-api /tmp/audit-free-api.tar.gz
|
||||
"""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
blob = pack()
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(
|
||||
HOST,
|
||||
username=USER,
|
||||
password=PASS,
|
||||
timeout=60,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/audit-free-api.tar.gz", "wb") as rf:
|
||||
rf.write(blob)
|
||||
sftp.close()
|
||||
_, stdout, stderr = c.exec_command(REMOTE_CMD, timeout=180)
|
||||
out = stdout.read().decode("utf-8", "replace")
|
||||
err = stderr.read().decode("utf-8", "replace")
|
||||
print(out)
|
||||
if err.strip():
|
||||
print("STDERR", err)
|
||||
c.close()
|
||||
if "audit_free_ok" not in out:
|
||||
return 2
|
||||
if "active" not in out:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -432,7 +432,7 @@ export default function VipLibrary() {
|
||||
<div>
|
||||
<h2>微信提审</h2>
|
||||
<p>
|
||||
打开后,小程序「小册」只展示独立的审核版正文(不是下面这本正式会员书)。关了就恢复正式版。不影响云手机、youtube运营笔记。
|
||||
打开后,小程序「小册」只展示独立的审核版正文(默认免费全文,与正式会员书的已购/VIP/付费数据隔离)。关了就恢复正式版。不影响云手机、youtube运营笔记。
|
||||
</p>
|
||||
</div>
|
||||
<div className="vip-row" style={{ border: 'none', padding: 0, margin: 0 }}>
|
||||
@ -461,7 +461,7 @@ export default function VipLibrary() {
|
||||
去写审核版正文 →
|
||||
</Link>
|
||||
<span className="vip-hint" style={{ alignSelf: 'center' }}>
|
||||
审核版是单独一本,不会自动抄正式会员书
|
||||
审核版单独一本 · 永远免费 · 不共用正式付费解锁
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
@ -505,6 +505,7 @@ export default function VipLibrary() {
|
||||
</div>
|
||||
|
||||
{/* 每本独立试读/道具,与 youtube运营笔记(books/default) 同机制、互不影响 */}
|
||||
<div id="book-monetize" style={{ scrollMarginTop: 88 }}>
|
||||
<BookMonetizePanel
|
||||
bookId={bookId}
|
||||
bookLabel={bookLabel}
|
||||
@ -518,6 +519,7 @@ export default function VipLibrary() {
|
||||
}).catch(() => undefined)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="vip-layout">
|
||||
<aside className="vip-item-list" style={{ maxHeight: 520, overflow: 'auto' }}>
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
from .products import (
|
||||
PRODUCT_OFFERS,
|
||||
apply_offer_key,
|
||||
is_audit_book_id,
|
||||
is_book_free,
|
||||
match_offer,
|
||||
offer_public_list,
|
||||
@ -14,6 +15,7 @@ __all__ = [
|
||||
"PRODUCT_OFFERS",
|
||||
"access_snapshot",
|
||||
"apply_offer_key",
|
||||
"is_audit_book_id",
|
||||
"is_book_free",
|
||||
"is_free_unlock",
|
||||
"match_offer",
|
||||
|
||||
@ -133,9 +133,18 @@ _LEGACY_PRODUCT_IDS = {
|
||||
}
|
||||
|
||||
|
||||
def is_audit_book_id(book_id: str | None) -> bool:
|
||||
"""提审书 id:永远免费,且与正式付费 unlock / VIP 隔离。"""
|
||||
bid = (book_id or "").strip()
|
||||
return bid == "audit" or bid.startswith("audit")
|
||||
|
||||
|
||||
def is_book_free(book: dict[str, Any] | None) -> bool:
|
||||
if not book:
|
||||
return False
|
||||
# 提审书强制免费:禁止运营误配付费后与正式书共用解锁态
|
||||
if is_audit_book_id(str(book.get("id") or "")):
|
||||
return True
|
||||
return int(book.get("unlock_percent") or 0) >= 100
|
||||
|
||||
|
||||
|
||||
@ -7,7 +7,13 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.security import create_admin_token, require_admin
|
||||
from ebook_svc.domains.books import apply_offer_key, is_book_free, match_offer, offer_public_list
|
||||
from ebook_svc.domains.books import (
|
||||
apply_offer_key,
|
||||
is_audit_book_id,
|
||||
is_book_free,
|
||||
match_offer,
|
||||
offer_public_list,
|
||||
)
|
||||
from ebook_svc.schemas.admin import (
|
||||
AdminLoginBody,
|
||||
BookCreateBody,
|
||||
@ -161,6 +167,14 @@ async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
||||
async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(require_admin)):
|
||||
patch = body.model_dump(exclude_none=True)
|
||||
offer_key = patch.pop("offer_key", None)
|
||||
# 提审书永远免费,禁止改成付费方案以免与正式书数据串台
|
||||
if is_audit_book_id(book_id):
|
||||
if offer_key and offer_key != "free":
|
||||
raise HTTPException(400, "提审书默认免费,不可配置付费方案")
|
||||
patch["unlock_percent"] = 100
|
||||
patch["price_fen"] = 0
|
||||
patch["product_id"] = ""
|
||||
offer_key = "free"
|
||||
try:
|
||||
if offer_key:
|
||||
book = store.get_book(book_id)
|
||||
@ -179,7 +193,7 @@ async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(requ
|
||||
try:
|
||||
from ebook_svc.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
bump_books_offer_live(book_id, free=is_book_free(book))
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(book)
|
||||
@ -198,9 +212,13 @@ async def admin_apply_offer(
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
if is_audit_book_id(book_id) and body.offer_key != "free":
|
||||
raise HTTPException(400, "提审书默认免费,不可配置付费方案")
|
||||
try:
|
||||
keep = book.get("unlock_percent") if body.keep_preview_percent else None
|
||||
patch = apply_offer_key(body.offer_key, keep)
|
||||
if is_audit_book_id(book_id):
|
||||
patch = apply_offer_key("free", None)
|
||||
updated = store.update_book(book_id, patch)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
@ -211,7 +229,7 @@ async def admin_apply_offer(
|
||||
try:
|
||||
from ebook_svc.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
bump_books_offer_live(book_id, free=is_book_free(updated))
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(updated)
|
||||
@ -300,6 +318,8 @@ async def admin_order_status(
|
||||
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
|
||||
"""后台手动发货:小册 default / VIP __vip__ / 其它 book_id。"""
|
||||
book_id = (body.book_id or "").strip() or "default"
|
||||
if is_audit_book_id(book_id):
|
||||
raise HTTPException(400, "提审书默认免费,无需手动解锁")
|
||||
if book_id != VIP_BOOK_ID:
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
|
||||
@ -3,7 +3,14 @@ from __future__ import annotations
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
|
||||
from ebook_svc.core.deps import get_current_openid, get_optional_openid
|
||||
from ebook_svc.domains.books import access_snapshot, is_free_unlock, public_book, truncate_by_percent
|
||||
from ebook_svc.domains.books import (
|
||||
access_snapshot,
|
||||
is_audit_book_id,
|
||||
is_book_free,
|
||||
is_free_unlock,
|
||||
public_book,
|
||||
truncate_by_percent,
|
||||
)
|
||||
from ebook_svc.services.store import store
|
||||
|
||||
router = APIRouter(prefix="/books", tags=["books"])
|
||||
@ -19,6 +26,9 @@ def _no_store(resp: Response) -> None:
|
||||
|
||||
|
||||
def _book_unlocked(openid: str, book_id: str, *, free: bool) -> bool:
|
||||
# 提审书:只按免费放行,绝不读正式 unlocks / __vip__
|
||||
if is_audit_book_id(book_id):
|
||||
return True
|
||||
if free:
|
||||
return True
|
||||
if store.is_unlocked(openid, book_id):
|
||||
@ -28,6 +38,12 @@ def _book_unlocked(openid: str, book_id: str, *, free: bool) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _book_is_free(book: dict, book_id: str) -> bool:
|
||||
if is_audit_book_id(book_id):
|
||||
return True
|
||||
return is_book_free(book) or is_free_unlock(book.get("unlock_percent"))
|
||||
|
||||
|
||||
@router.get("/{book_id}")
|
||||
async def get_book(book_id: str, response: Response):
|
||||
_no_store(response)
|
||||
@ -48,7 +64,7 @@ async def book_access(
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
free = is_free_unlock(book.get("unlock_percent"))
|
||||
free = _book_is_free(book, book_id)
|
||||
unlocked = _book_unlocked(openid, book_id, free=free)
|
||||
return access_snapshot(book, openid=openid, unlocked=unlocked)
|
||||
|
||||
@ -63,7 +79,7 @@ async def read_book(
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
free = is_free_unlock(book.get("unlock_percent"))
|
||||
free = _book_is_free(book, book_id)
|
||||
# 付费书必须登录;免费/提审书可匿名全文
|
||||
if not free and not openid:
|
||||
raise HTTPException(401, "未登录")
|
||||
|
||||
@ -11,7 +11,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 import is_audit_book_id, is_book_free
|
||||
from ebook_svc.domains.books.products import PRODUCT_OFFERS
|
||||
from ebook_svc.schemas.pay import DevConfirmBody, OrderBody, StatusBody
|
||||
from ebook_svc.services.shop_store import shop_store
|
||||
@ -388,6 +388,8 @@ 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)
|
||||
if is_audit_book_id(body.book_id):
|
||||
raise HTTPException(400, "提审书默认免费,不可购买")
|
||||
book = store.get_book(body.book_id)
|
||||
if not book:
|
||||
# 兼容旧 VIP 客户端:把 product_id 误当成 book_id 传来 → 走会员单
|
||||
@ -421,14 +423,18 @@ async def create_pay_order(
|
||||
amount_fen=book["price_fen"],
|
||||
attach=attach,
|
||||
)
|
||||
pay_env = int(settings.wx_pay_env) if body.env is None else (1 if int(body.env) == 1 else 0)
|
||||
sign_data = build_sign_data(
|
||||
offer_id=settings.wx_offer_id,
|
||||
product_id=book["product_id"],
|
||||
goods_price=book["price_fen"],
|
||||
out_trade_no=out_trade_no,
|
||||
attach=attach,
|
||||
env=pay_env,
|
||||
)
|
||||
pay_sig = calc_pay_sig(
|
||||
"requestVirtualPayment", sign_data, active_wx_app_key(env=pay_env)
|
||||
)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, active_wx_app_key())
|
||||
signature = calc_signature(sign_data, user["session_key"])
|
||||
try:
|
||||
from ebook_svc.services.track import ingest_events
|
||||
@ -443,6 +449,7 @@ async def create_pay_order(
|
||||
"book_id": body.book_id,
|
||||
"out_trade_no": out_trade_no,
|
||||
"price_fen": book["price_fen"],
|
||||
"env": pay_env,
|
||||
},
|
||||
"ts": None,
|
||||
}
|
||||
@ -460,6 +467,7 @@ async def create_pay_order(
|
||||
"outTradeNo": out_trade_no,
|
||||
"productId": book["product_id"],
|
||||
"goodsPrice": book["price_fen"],
|
||||
"env": pay_env,
|
||||
"kind": "book",
|
||||
}
|
||||
|
||||
|
||||
@ -103,10 +103,54 @@ class Store:
|
||||
("vip_email", "ALTER TABLE users ADD COLUMN vip_email TEXT"),
|
||||
("web_user_id", "ALTER TABLE users ADD COLUMN web_user_id TEXT"),
|
||||
("vip_email_bound_at", "ALTER TABLE users ADD COLUMN vip_email_bound_at REAL"),
|
||||
# 公众号私信 userid(OA openid),与小程序 openid 分离
|
||||
("oa_userid", "ALTER TABLE users ADD COLUMN oa_userid TEXT"),
|
||||
("oa_bound_at", "ALTER TABLE users ADD COLUMN oa_bound_at REAL"),
|
||||
# 绑定发生在哪个微信小程序 AppID(openid 按 AppID 隔离;A/B 互不抢绑)
|
||||
("oa_mp_appid", "ALTER TABLE users ADD COLUMN oa_mp_appid TEXT"),
|
||||
]
|
||||
for name, sql in alters:
|
||||
if name not in cols:
|
||||
c.execute(sql)
|
||||
c.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS oa_profiles (
|
||||
userid TEXT PRIMARY KEY,
|
||||
nick TEXT,
|
||||
avatar TEXT,
|
||||
signature TEXT,
|
||||
gender_txt TEXT,
|
||||
region TEXT,
|
||||
follow_since TEXT,
|
||||
remark TEXT,
|
||||
matched_last_msg TEXT,
|
||||
channel_id TEXT,
|
||||
mp_openid TEXT,
|
||||
mp_appid TEXT,
|
||||
raw_json TEXT,
|
||||
created_at REAL,
|
||||
updated_at REAL
|
||||
)
|
||||
"""
|
||||
)
|
||||
oa_prof_cols = {r[1] for r in c.execute("PRAGMA table_info(oa_profiles)").fetchall()}
|
||||
if "mp_appid" not in oa_prof_cols:
|
||||
c.execute("ALTER TABLE oa_profiles ADD COLUMN mp_appid TEXT")
|
||||
c.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_oa_profiles_updated ON oa_profiles(updated_at DESC)"
|
||||
)
|
||||
c.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_users_oa_userid ON users(oa_userid)"
|
||||
)
|
||||
# 同一微信小程序 AppID 内:一个 OA userid 只能绑一个 mp openid
|
||||
c.execute(
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_oa_userid_appid_unique
|
||||
ON users(oa_userid, oa_mp_appid)
|
||||
WHERE oa_userid IS NOT NULL AND oa_userid != ''
|
||||
AND oa_mp_appid IS NOT NULL AND oa_mp_appid != ''
|
||||
"""
|
||||
)
|
||||
unlock_cols = {r[1] for r in c.execute("PRAGMA table_info(unlocks)").fetchall()}
|
||||
if "source" not in unlock_cols:
|
||||
c.execute("ALTER TABLE unlocks ADD COLUMN source TEXT")
|
||||
@ -293,6 +337,12 @@ class Store:
|
||||
raise ValueError("book_id required")
|
||||
existing = self.get_book(bid)
|
||||
if existing:
|
||||
# 提审书若被误配成付费,强制拉回免费,避免与正式书共用付费态
|
||||
if free and int(existing.get("unlock_percent") or 0) < 100:
|
||||
return self.update_book(
|
||||
bid,
|
||||
{"unlock_percent": 100, "price_fen": 0, "product_id": ""},
|
||||
)
|
||||
return existing
|
||||
now = time.time()
|
||||
chapters = [
|
||||
@ -485,6 +535,416 @@ class Store:
|
||||
)
|
||||
return self.get_user(openid)
|
||||
|
||||
def find_oa_binder(
|
||||
self,
|
||||
oa_userid: str,
|
||||
*,
|
||||
mp_appid: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""同一微信小程序 AppID 下,谁已绑定该公众号 userid。"""
|
||||
oa_userid = (oa_userid or "").strip()
|
||||
if not oa_userid:
|
||||
return None
|
||||
appid = (mp_appid or "").strip()
|
||||
with self.conn() as c:
|
||||
if appid:
|
||||
row = c.execute(
|
||||
"""
|
||||
SELECT openid, oa_userid, oa_mp_appid, oa_bound_at, nickname, avatar_url
|
||||
FROM users
|
||||
WHERE oa_userid=? AND oa_mp_appid=?
|
||||
LIMIT 1
|
||||
""",
|
||||
(oa_userid, appid),
|
||||
).fetchone()
|
||||
else:
|
||||
row = c.execute(
|
||||
"""
|
||||
SELECT openid, oa_userid, oa_mp_appid, oa_bound_at, nickname, avatar_url
|
||||
FROM users
|
||||
WHERE oa_userid=?
|
||||
LIMIT 1
|
||||
""",
|
||||
(oa_userid,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def bind_oa_userid(
|
||||
self,
|
||||
openid: str,
|
||||
oa_userid: str,
|
||||
*,
|
||||
nick: str | None = None,
|
||||
avatar: str | None = None,
|
||||
mp_appid: str | None = None,
|
||||
force: bool = True,
|
||||
) -> dict[str, Any] | None:
|
||||
"""把公众号 userid 强制绑到「当前微信小程序」的 openid。
|
||||
|
||||
排他范围:同一 mp_appid(小程序 A / B 的 openid 互不干扰)。
|
||||
该 AppID 下若 OA 已被其他 openid 占用 → 抛 ValueError('oa_bound_other')。
|
||||
"""
|
||||
openid = (openid or "").strip()
|
||||
oa_userid = (oa_userid or "").strip()
|
||||
appid = (mp_appid or "").strip()
|
||||
if not openid or not oa_userid:
|
||||
return None
|
||||
if not appid:
|
||||
raise ValueError("oa_mp_appid_required")
|
||||
|
||||
existing = self.find_oa_binder(oa_userid, mp_appid=appid)
|
||||
if existing and (existing.get("openid") or "").strip() != openid:
|
||||
raise ValueError("oa_bound_other")
|
||||
|
||||
me = self.get_user(openid) or {}
|
||||
my_oa = (me.get("oa_userid") or "").strip()
|
||||
my_app = (me.get("oa_mp_appid") or "").strip()
|
||||
|
||||
now = time.time()
|
||||
nick_s = (nick or "").strip()
|
||||
avatar_s = (avatar or "").strip()
|
||||
with self.conn() as c:
|
||||
# 档案侧二次校验(同 AppID)
|
||||
prow = c.execute(
|
||||
"SELECT mp_openid, mp_appid FROM oa_profiles WHERE userid=?",
|
||||
(oa_userid,),
|
||||
).fetchone()
|
||||
if prow:
|
||||
bound_mp = (prow["mp_openid"] or "").strip()
|
||||
bound_app = (prow["mp_appid"] or "").strip()
|
||||
if bound_mp and bound_mp != openid and (not bound_app or bound_app == appid):
|
||||
raise ValueError("oa_bound_other")
|
||||
|
||||
# 本人换绑到新 OA:释放旧 OA(仅本 AppID)
|
||||
if my_oa and my_oa != oa_userid and my_app == appid:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE oa_profiles
|
||||
SET mp_openid=NULL, mp_appid=NULL, updated_at=?
|
||||
WHERE userid=? AND IFNULL(mp_openid,'')=? AND IFNULL(mp_appid,'')=?
|
||||
""",
|
||||
(now, my_oa, openid, appid),
|
||||
)
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET oa_userid=?, oa_bound_at=CASE
|
||||
WHEN IFNULL(oa_userid,'')=? AND IFNULL(oa_mp_appid,'')=? THEN oa_bound_at
|
||||
ELSE ?
|
||||
END,
|
||||
oa_mp_appid=?,
|
||||
updated_at=?,
|
||||
nickname=COALESCE(NULLIF(?, ''), nickname),
|
||||
avatar_url=COALESCE(NULLIF(?, ''), avatar_url)
|
||||
WHERE openid=?
|
||||
""",
|
||||
(
|
||||
oa_userid,
|
||||
oa_userid,
|
||||
appid,
|
||||
now,
|
||||
appid,
|
||||
now,
|
||||
nick_s,
|
||||
avatar_s,
|
||||
openid,
|
||||
),
|
||||
)
|
||||
if prow:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE oa_profiles
|
||||
SET nick=COALESCE(NULLIF(?, ''), nick),
|
||||
avatar=COALESCE(NULLIF(?, ''), avatar),
|
||||
mp_openid=?,
|
||||
mp_appid=?,
|
||||
updated_at=?
|
||||
WHERE userid=?
|
||||
""",
|
||||
(nick_s, avatar_s, openid, appid, now, oa_userid),
|
||||
)
|
||||
else:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO oa_profiles(
|
||||
userid, nick, avatar, mp_openid, mp_appid, created_at, updated_at
|
||||
) VALUES(?,?,?,?,?,?,?)
|
||||
""",
|
||||
(oa_userid, nick_s, avatar_s, openid, appid, now, now),
|
||||
)
|
||||
_ = force
|
||||
return self.get_user(openid)
|
||||
|
||||
def get_oa_profile(self, userid: str) -> dict[str, Any] | None:
|
||||
userid = (userid or "").strip()
|
||||
if not userid:
|
||||
return None
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT * FROM oa_profiles WHERE userid=?", (userid,)
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def get_oa_profile_by_mp_openid(self, mp_openid: str) -> dict[str, Any] | None:
|
||||
mp = (mp_openid or "").strip()
|
||||
if not mp:
|
||||
return None
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT * FROM oa_profiles WHERE mp_openid=? ORDER BY updated_at DESC LIMIT 1",
|
||||
(mp,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def list_unlocks_for_openid(self, openid: str, *, limit: int = 12) -> list[dict[str, Any]]:
|
||||
oid = (openid or "").strip()
|
||||
if not oid:
|
||||
return []
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"""
|
||||
SELECT book_id, unlocked_at, source
|
||||
FROM unlocks WHERE openid=?
|
||||
ORDER BY unlocked_at DESC LIMIT ?
|
||||
""",
|
||||
(oid, max(1, min(int(limit), 40))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def upsert_oa_profile(self, payload: dict[str, Any], *, partial: bool = False) -> dict[str, Any]:
|
||||
userid = str(payload.get("userid") or payload.get("openid") or "").strip()
|
||||
if not userid:
|
||||
raise ValueError("userid required")
|
||||
now = time.time()
|
||||
|
||||
def pick(*keys: str, default: str = "") -> str:
|
||||
for k in keys:
|
||||
if k in payload and payload.get(k) is not None:
|
||||
return str(payload.get(k) or "").strip()
|
||||
return default
|
||||
|
||||
nick = pick("nick", "nickname")
|
||||
avatar = pick("avatar")
|
||||
signature = pick("signature")
|
||||
gender_txt = pick("gender_txt")
|
||||
region = pick("region")
|
||||
follow_since = pick("follow_since")
|
||||
remark = pick("remark")
|
||||
matched_last_msg = pick("matched_last_msg")
|
||||
channel_id = pick("channel_id")
|
||||
mp_openid = pick("mp_openid") or None
|
||||
mp_appid = pick("mp_appid") or None
|
||||
# VIP 同步默认不带 mp_openid:禁止顺带改写绑定
|
||||
touch_mp = ("mp_openid" in payload) or ("mp_appid" in payload)
|
||||
raw = payload.get("raw_json")
|
||||
if raw is None and isinstance(payload.get("raw_contact"), (dict, list)):
|
||||
raw = json.dumps(payload.get("raw_contact"), ensure_ascii=False)
|
||||
elif isinstance(raw, (dict, list)):
|
||||
raw = json.dumps(raw, ensure_ascii=False)
|
||||
raw_s = str(raw) if raw is not None else None
|
||||
|
||||
with self.conn() as c:
|
||||
exist = c.execute(
|
||||
"SELECT * FROM oa_profiles WHERE userid=?", (userid,)
|
||||
).fetchone()
|
||||
if exist:
|
||||
ex = dict(exist)
|
||||
|
||||
def merge(key: str, new_val: str) -> str:
|
||||
if partial and key not in payload and key != "nick" and key != "avatar":
|
||||
# nick/avatar 用别名键
|
||||
aliases = {"nick": ("nick", "nickname"), "avatar": ("avatar",)}
|
||||
if key in aliases and not any(a in payload for a in aliases[key]):
|
||||
return ex.get(key) or ""
|
||||
if partial and not new_val and key not in payload and key not in (
|
||||
"nick",
|
||||
"nickname",
|
||||
"avatar",
|
||||
):
|
||||
return ex.get(key) or ""
|
||||
return new_val if new_val or not partial else (ex.get(key) or "")
|
||||
|
||||
nick_v = nick or (ex.get("nick") or "")
|
||||
avatar_v = avatar or (ex.get("avatar") or "")
|
||||
next_mp = mp_openid if touch_mp else (ex.get("mp_openid") or None)
|
||||
next_app = mp_appid if ("mp_appid" in payload) else (ex.get("mp_appid") or None)
|
||||
if touch_mp and next_mp:
|
||||
# 同 AppID 下不得抢别人已绑的 OA
|
||||
rival = c.execute(
|
||||
"""
|
||||
SELECT openid FROM users
|
||||
WHERE oa_userid=? AND IFNULL(oa_mp_appid,'')=IFNULL(?, '')
|
||||
AND openid!=?
|
||||
LIMIT 1
|
||||
""",
|
||||
(userid, next_app or "", next_mp),
|
||||
).fetchone()
|
||||
if rival:
|
||||
raise ValueError("oa_bound_other")
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE oa_profiles SET
|
||||
nick=?, avatar=?, signature=?, gender_txt=?, region=?,
|
||||
follow_since=?, remark=?, matched_last_msg=?, channel_id=?,
|
||||
mp_openid=?,
|
||||
mp_appid=?,
|
||||
raw_json=COALESCE(?, raw_json),
|
||||
updated_at=?
|
||||
WHERE userid=?
|
||||
""",
|
||||
(
|
||||
nick_v,
|
||||
avatar_v,
|
||||
merge("signature", signature),
|
||||
merge("gender_txt", gender_txt),
|
||||
merge("region", region),
|
||||
merge("follow_since", follow_since),
|
||||
merge("remark", remark),
|
||||
merge("matched_last_msg", matched_last_msg),
|
||||
merge("channel_id", channel_id),
|
||||
next_mp,
|
||||
next_app,
|
||||
raw_s,
|
||||
now,
|
||||
userid,
|
||||
),
|
||||
)
|
||||
mp = next_mp if touch_mp else None
|
||||
app_for_user = next_app
|
||||
else:
|
||||
nick_v, avatar_v = nick, avatar
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO oa_profiles(
|
||||
userid, nick, avatar, signature, gender_txt, region,
|
||||
follow_since, remark, matched_last_msg, channel_id,
|
||||
mp_openid, mp_appid, raw_json, created_at, updated_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
userid,
|
||||
nick,
|
||||
avatar,
|
||||
signature,
|
||||
gender_txt,
|
||||
region,
|
||||
follow_since,
|
||||
remark,
|
||||
matched_last_msg,
|
||||
channel_id,
|
||||
mp_openid if touch_mp else None,
|
||||
mp_appid if touch_mp else None,
|
||||
raw_s,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
mp = mp_openid if touch_mp else None
|
||||
app_for_user = mp_appid if touch_mp else None
|
||||
if mp and touch_mp:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE users SET oa_userid=?, oa_bound_at=COALESCE(oa_bound_at, ?),
|
||||
oa_mp_appid=COALESCE(?, oa_mp_appid),
|
||||
nickname=COALESCE(NULLIF(?, ''), nickname),
|
||||
avatar_url=COALESCE(NULLIF(?, ''), avatar_url),
|
||||
updated_at=?
|
||||
WHERE openid=?
|
||||
""",
|
||||
(userid, now, app_for_user, nick_v, avatar_v, now, mp),
|
||||
)
|
||||
return self.get_oa_profile(userid) or {"userid": userid}
|
||||
|
||||
def delete_oa_profile(self, userid: str) -> bool:
|
||||
userid = (userid or "").strip()
|
||||
if not userid:
|
||||
return False
|
||||
with self.conn() as c:
|
||||
cur = c.execute("DELETE FROM oa_profiles WHERE userid=?", (userid,))
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE users SET oa_userid=NULL, oa_bound_at=NULL, oa_mp_appid=NULL, updated_at=?
|
||||
WHERE oa_userid=?
|
||||
""",
|
||||
(time.time(), userid),
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
|
||||
def list_oa_profiles(
|
||||
self,
|
||||
*,
|
||||
page: int = 1,
|
||||
limit: int = 50,
|
||||
q: str = "",
|
||||
) -> dict[str, Any]:
|
||||
page = max(1, int(page or 1))
|
||||
limit = max(1, min(int(limit or 50), 200))
|
||||
offset = (page - 1) * limit
|
||||
q = (q or "").strip()
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"SELECT * FROM oa_profiles ORDER BY updated_at DESC"
|
||||
).fetchall()
|
||||
bound = c.execute(
|
||||
"""
|
||||
SELECT openid, oa_userid, nickname, avatar_url, oa_bound_at, updated_at, status
|
||||
FROM users WHERE oa_userid IS NOT NULL AND oa_userid != ''
|
||||
"""
|
||||
).fetchall()
|
||||
by_id: dict[str, dict[str, Any]] = {}
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
by_id[item["userid"]] = item
|
||||
for b in bound:
|
||||
uid = (b["oa_userid"] or "").strip()
|
||||
if not uid:
|
||||
continue
|
||||
if uid in by_id:
|
||||
if not by_id[uid].get("mp_openid"):
|
||||
by_id[uid]["mp_openid"] = b["openid"]
|
||||
by_id[uid]["mp_status"] = b["status"] or "active"
|
||||
else:
|
||||
by_id[uid] = {
|
||||
"userid": uid,
|
||||
"nick": b["nickname"] or "",
|
||||
"avatar": b["avatar_url"] or "",
|
||||
"signature": "",
|
||||
"gender_txt": "",
|
||||
"region": "",
|
||||
"follow_since": "",
|
||||
"remark": "",
|
||||
"matched_last_msg": "",
|
||||
"channel_id": "",
|
||||
"mp_openid": b["openid"],
|
||||
"raw_json": None,
|
||||
"created_at": b["oa_bound_at"] or b["updated_at"],
|
||||
"updated_at": b["updated_at"],
|
||||
"from_users_only": True,
|
||||
"mp_status": b["status"] or "active",
|
||||
}
|
||||
users = list(by_id.values())
|
||||
if q:
|
||||
ql = q.lower()
|
||||
users = [
|
||||
u
|
||||
for u in users
|
||||
if ql in str(u.get("userid") or "").lower()
|
||||
or ql in str(u.get("nick") or "").lower()
|
||||
or ql in str(u.get("remark") or "").lower()
|
||||
or ql in str(u.get("mp_openid") or "").lower()
|
||||
]
|
||||
users.sort(key=lambda x: -(float(x.get("updated_at") or 0)))
|
||||
total_all = len(users)
|
||||
page_items = users[offset : offset + limit]
|
||||
return {
|
||||
"ok": True,
|
||||
"total": total_all,
|
||||
"page": page,
|
||||
"perPage": limit,
|
||||
"totalPages": max(1, (total_all + limit - 1) // limit) if total_all else 1,
|
||||
"users": page_items,
|
||||
}
|
||||
|
||||
def list_users(self, limit: int = 200, q: str = "") -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
if q.strip():
|
||||
@ -492,10 +952,11 @@ class Store:
|
||||
rows = c.execute(
|
||||
"""
|
||||
SELECT * FROM users
|
||||
WHERE openid LIKE ? OR IFNULL(nickname,'') LIKE ? OR IFNULL(notes,'') LIKE ?
|
||||
WHERE openid LIKE ? OR IFNULL(nickname,'') LIKE ?
|
||||
OR IFNULL(notes,'') LIKE ? OR IFNULL(oa_userid,'') LIKE ?
|
||||
ORDER BY updated_at DESC LIMIT ?
|
||||
""",
|
||||
(like, like, like, limit),
|
||||
(like, like, like, like, limit),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = c.execute(
|
||||
|
||||
@ -1,9 +1,60 @@
|
||||
/**
|
||||
* 微信专用 App:零副作用。必须包一层 Fragment,避免 children 形态异常导致整页空白。
|
||||
* 微信专用 App。
|
||||
* 必须挂远程配置热更新(WS + 1s 轮询),否则后台开关 / 提审切换前端不实时。
|
||||
* 仍避免塞 VIP/presence 等重副作用,防止冷启动白屏。
|
||||
*/
|
||||
import { Fragment, type PropsWithChildren } from 'react'
|
||||
import { Fragment, useEffect, type PropsWithChildren } from 'react'
|
||||
import Taro, { useLaunch } from '@tarojs/taro'
|
||||
import {
|
||||
loadRemoteConfig,
|
||||
startRemoteConfigLiveSync,
|
||||
} from './services/remoteConfig'
|
||||
import {
|
||||
captureOaUseridFromOptions,
|
||||
syncOaProfileBind,
|
||||
} from './utils/oaUserid'
|
||||
import './app.scss'
|
||||
|
||||
export default function App({ children }: PropsWithChildren) {
|
||||
useLaunch((options) => {
|
||||
const oa = captureOaUseridFromOptions(
|
||||
(options || {}) as unknown as Record<string, unknown>,
|
||||
)
|
||||
void loadRemoteConfig(true).catch(() => undefined)
|
||||
if (oa) {
|
||||
void syncOaProfileBind(true).catch(() => undefined)
|
||||
}
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
let stop: (() => void) | undefined
|
||||
// 略延后:先出首屏,再连 WS / 轮询
|
||||
const t = setTimeout(() => {
|
||||
stop = startRemoteConfigLiveSync()
|
||||
}, 320)
|
||||
return () => {
|
||||
clearTimeout(t)
|
||||
stop?.()
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const onShow = () => {
|
||||
void loadRemoteConfig(true).catch(() => undefined)
|
||||
}
|
||||
try {
|
||||
Taro.onAppShow(onShow)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return () => {
|
||||
try {
|
||||
Taro.offAppShow(onShow)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return <Fragment>{children}</Fragment>
|
||||
}
|
||||
|
||||
@ -140,11 +140,14 @@ function BookPageInner() {
|
||||
})
|
||||
}, [])
|
||||
|
||||
// 后台随时改小册方案:封面价/免费态约 2s 跟随
|
||||
// 后台随时改小册方案 / 提审开关:约 1s 拉配置,封面价与审核态跟随
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
void loadRemoteConfig(true)
|
||||
.then((r) => applyAudit(resolveBookAudit(r.config)))
|
||||
.catch(() => undefined)
|
||||
void loadBook(true)
|
||||
}, 2000)
|
||||
}, 1000)
|
||||
return () => clearInterval(timer)
|
||||
}, [])
|
||||
|
||||
@ -287,7 +290,7 @@ function BookPageInner() {
|
||||
if (loading && !book) {
|
||||
return (
|
||||
<H5Box className="page-shell book-flow book-flow--error">
|
||||
<CommunityNavbar />
|
||||
<CommunityNavbar showOa={false} />
|
||||
<H5Box className="book-error">
|
||||
<H5Txt className="book-error-hint">加载中…</H5Txt>
|
||||
</H5Box>
|
||||
@ -298,7 +301,7 @@ function BookPageInner() {
|
||||
if (error || !book) {
|
||||
return (
|
||||
<H5Box className="page-shell book-flow book-flow--error">
|
||||
<CommunityNavbar />
|
||||
<CommunityNavbar showOa={false} />
|
||||
<H5Box className="book-error">
|
||||
<H5Txt className="book-error-title">暂时打不开</H5Txt>
|
||||
<H5Txt className="book-error-hint">{error || '请稍后再试'}</H5Txt>
|
||||
@ -317,16 +320,12 @@ function BookPageInner() {
|
||||
}
|
||||
|
||||
const hasProgress = !!continueChapter
|
||||
const unlockSource = apiBook || book
|
||||
const isFree = !!(unlockSource.is_free || (unlockSource.unlock_percent ?? 0) >= 100)
|
||||
const ctaText = hasProgress ? '📖 继续阅读' : '📖 开始阅读'
|
||||
const ctaHint = hasProgress
|
||||
? progress?.updatedAt
|
||||
? `上次翻到 · ${formatAgo(progress.updatedAt)}`
|
||||
: '接着上次的地方'
|
||||
: isFree
|
||||
? '点一下,直接进入正文'
|
||||
: '先翻开前面的章节'
|
||||
: '点一下,直接进入正文'
|
||||
|
||||
const displayTitle = audit.reviewMode
|
||||
? book.title || '数字游民入门指南'
|
||||
@ -343,7 +342,7 @@ function BookPageInner() {
|
||||
data-theme={theme}
|
||||
style={safeStyle}
|
||||
>
|
||||
<CommunityNavbar />
|
||||
<CommunityNavbar showOa={false} />
|
||||
|
||||
<H5Box className="hero" id="hero">
|
||||
<H5Box className="hero-bg-shapes" aria-hidden>
|
||||
|
||||
@ -2,10 +2,10 @@
|
||||
* VIP 电子书 — 复刻 nomadvip EbookViewer 目录交互
|
||||
* 顶栏 ☰ 开目录(对齐小程序 reader),左侧抽屉可跳章节
|
||||
*/
|
||||
import { View, Text, ScrollView, Input, Button } from '@tarojs/components'
|
||||
import { View, Text, ScrollView, Button, Image } from '@tarojs/components'
|
||||
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { H5Box, H5Txt } from '../../components/H5Box'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { H5Box } from '../../components/H5Box'
|
||||
import { MarkdownView } from '../../components/MarkdownView'
|
||||
import {
|
||||
isYoutubeNotesBookId,
|
||||
@ -17,8 +17,7 @@ import { loadVipEbook } from '../../services/vipLibrary'
|
||||
import { goPage } from '../../utils/nav'
|
||||
import {
|
||||
goVipUnlock,
|
||||
hasVipContentAccessSync,
|
||||
resolveVipContentAccess,
|
||||
resolveVipAccess,
|
||||
subscribeVipAccess,
|
||||
} from '../../utils/vipAccess'
|
||||
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
||||
@ -30,6 +29,7 @@ import {
|
||||
} from '../../services/remoteConfig'
|
||||
import { resolveBookAudit } from '../../data/remoteConfig.defaults'
|
||||
import {
|
||||
accessFingerprint,
|
||||
fetchAccess,
|
||||
fetchAuditRead,
|
||||
fetchBook,
|
||||
@ -38,6 +38,9 @@ import {
|
||||
type BookDetail,
|
||||
} from '../../services/ebookApi'
|
||||
import { runUnlockPayment } from '../../utils/payFlow'
|
||||
import { mapPayError } from '../../utils/payFeedback'
|
||||
import { LockIcon } from '../../components/LockIcon'
|
||||
import { useOaPresence } from '@/hooks/useOaPresence'
|
||||
import './index.scss'
|
||||
|
||||
type BookPayMeta = {
|
||||
@ -52,41 +55,57 @@ type BookPayMeta = {
|
||||
|
||||
function metaFromBook(b: BookDetail | null | undefined, unlocked = false): BookPayMeta {
|
||||
if (!b) {
|
||||
// 失联 / 未拉到 books:fail-closed 试读,禁止默认全书免费
|
||||
return {
|
||||
is_free: unlocked,
|
||||
is_free: false,
|
||||
unlock_percent: unlocked ? 100 : 30,
|
||||
product_id: '',
|
||||
price_fen: 0,
|
||||
unlock_btn_text: unlocked ? '开始阅读' : '解锁全文',
|
||||
unlock_btn_text: unlocked ? '继续阅读' : '继续阅读',
|
||||
offer_name: '',
|
||||
unlocked,
|
||||
}
|
||||
}
|
||||
const unlock = Number(b.unlock_percent ?? 30)
|
||||
const free = !!(b.is_free || unlock >= 100 || !b.product_id)
|
||||
// 与后端 is_book_free 对齐:仅 unlock>=100 / 显式 is_free;缺 product_id 不视为免费
|
||||
const free = !!(b.is_free || unlock >= 100)
|
||||
const fen = free ? 0 : Number(b.price_fen || 0)
|
||||
return {
|
||||
is_free: free,
|
||||
unlock_percent: free ? 100 : Math.min(99, Math.max(1, unlock)),
|
||||
unlock_percent: free ? 100 : Math.min(99, Math.max(1, unlock || 30)),
|
||||
product_id: free ? '' : String(b.product_id || ''),
|
||||
price_fen: free ? 0 : Number(b.price_fen || 0),
|
||||
unlock_btn_text:
|
||||
b.unlock_btn_text ||
|
||||
(free ? '开始阅读' : `解锁全文 · ¥${Math.round(Number(b.price_fen || 0) / 100)}`),
|
||||
price_fen: fen,
|
||||
// 阅读壳 CTA 克制:不写「试读/解锁/付费」硬推;价在副文案
|
||||
unlock_btn_text: free ? '继续阅读' : '继续阅读',
|
||||
offer_name: b.offer_name || '',
|
||||
unlocked,
|
||||
}
|
||||
}
|
||||
|
||||
/** 提审态专用付费元数据:永远免费,且不带正式已购/道具字段 */
|
||||
function auditFreePayMeta(): BookPayMeta {
|
||||
return {
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
product_id: '',
|
||||
price_fen: 0,
|
||||
offer_name: '',
|
||||
unlock_btn_text: '继续阅读',
|
||||
unlocked: false,
|
||||
}
|
||||
}
|
||||
|
||||
function auditPayloadToPack(
|
||||
bookId: string,
|
||||
_bookId: string,
|
||||
payload: ReturnType<typeof getAuditOfflineRead>,
|
||||
): VipEbookPack {
|
||||
const chapters = payload.chapters || []
|
||||
const headers = chapters.map((c) => c.title)
|
||||
const sections = chapters.map((c) => c.content || '')
|
||||
const words = sections.reduce((n, s) => n + s.length, 0)
|
||||
// 阅读壳仍走 nomad 样式;正文来源是 audit,付费态由 auditLive 隔离,不复用 nomad unlock
|
||||
return {
|
||||
id: bookId === 'audit' ? 'nomad' : ((bookId as VipEbookPack['id']) || 'nomad'),
|
||||
id: 'nomad',
|
||||
title: payload.book?.title || '数字游民入门指南',
|
||||
free: true,
|
||||
estimatedMinutes: Math.max(5, Math.round(words / 400)),
|
||||
@ -107,6 +126,7 @@ type TocItem = { index: number; title: string }
|
||||
|
||||
export default function VipEbookPage() {
|
||||
const theme = useNomadroTheme()
|
||||
const oa = useOaPresence()
|
||||
const router = useRouter()
|
||||
const rawParam = router.params?.id
|
||||
const youtubeMisroute = isYoutubeNotesBookId(rawParam)
|
||||
@ -128,10 +148,10 @@ export default function VipEbookPage() {
|
||||
cover_emoji: '',
|
||||
description: '',
|
||||
tags: [],
|
||||
price_fen: 0,
|
||||
product_id: '',
|
||||
unlock_percent: 100,
|
||||
is_free: true,
|
||||
price_fen: 2900,
|
||||
product_id: 'nomad_lite',
|
||||
unlock_percent: 30,
|
||||
is_free: false,
|
||||
chapter_count: 0,
|
||||
word_count: 0,
|
||||
rating: 0,
|
||||
@ -139,18 +159,50 @@ export default function VipEbookPage() {
|
||||
}),
|
||||
)
|
||||
const [isVip, setIsVip] = useState(false)
|
||||
const [ready, setReady] = useState(false)
|
||||
/** 当前是否在展示提审正文:付费/VIP/已购一律不走正式书数据 */
|
||||
const [auditLive, setAuditLive] = useState(false)
|
||||
const [paying, setPaying] = useState(false)
|
||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||
const [tocFilter, setTocFilter] = useState('')
|
||||
const [scrollInto, setScrollInto] = useState('')
|
||||
const [scrollTop, setScrollTop] = useState(0)
|
||||
const [activeSec, setActiveSec] = useState(0)
|
||||
/** 目录跳转:从该章起渲染,scrollTop=0 瞬时到位(不量 DOM) */
|
||||
const [anchorIdx, setAnchorIdx] = useState(0)
|
||||
/** 渐进挂载 Markdown,避免首屏一次解析几十章卡死 */
|
||||
const [mountCount, setMountCount] = useState(2)
|
||||
/** 强制 ScrollView 重挂,避免同 scrollTop 不滚动 */
|
||||
const [scrollEpoch, setScrollEpoch] = useState(0)
|
||||
const [readProgress, setReadProgress] = useState(0)
|
||||
const [showBackTop, setShowBackTop] = useState(false)
|
||||
const scrollTick = useRef(0)
|
||||
const payFpRef = useRef('')
|
||||
const paySyncing = useRef(false)
|
||||
const auditLiveRef = useRef(false)
|
||||
|
||||
/** 本册全文:VIP / 本册已购 / 本册免费(与其它小册互不影响) */
|
||||
const fullAccess =
|
||||
payMeta.is_free || payMeta.unlocked || isVip || !!book.free
|
||||
function enterAuditMode(pack: VipEbookPack) {
|
||||
auditLiveRef.current = true
|
||||
setAuditLive(true)
|
||||
setBook(pack)
|
||||
setPayMeta(auditFreePayMeta())
|
||||
// 提审不借正式 VIP:只用 is_free,避免关提审后 VIP 粘住或反向污染
|
||||
setIsVip(false)
|
||||
payFpRef.current = 'audit|free'
|
||||
Taro.setNavigationBarTitle({ title: pack.title })
|
||||
}
|
||||
|
||||
async function leaveAuditMode() {
|
||||
auditLiveRef.current = false
|
||||
setAuditLive(false)
|
||||
payFpRef.current = ''
|
||||
const { book: next } = await loadVipEbook('nomad')
|
||||
setBook(next)
|
||||
Taro.setNavigationBarTitle({ title: next.title })
|
||||
const vip = await resolveVipAccess(true).catch(() => false)
|
||||
setIsVip(!!vip)
|
||||
await refreshPayMeta()
|
||||
}
|
||||
|
||||
/** 本册全文:提审=强制免费;正式= VIP / 已购 / books 免费。 */
|
||||
const fullAccess = auditLive || payMeta.is_free || payMeta.unlocked || isVip
|
||||
|
||||
const previewCount = useMemo(() => {
|
||||
const n = book.sections.length
|
||||
@ -158,113 +210,190 @@ export default function VipEbookPage() {
|
||||
return Math.max(1, Math.floor((n * payMeta.unlock_percent) / 100))
|
||||
}, [book.sections.length, fullAccess, payMeta.unlock_percent])
|
||||
|
||||
const visibleSections = useMemo(
|
||||
const readableSections = useMemo(
|
||||
() => (fullAccess ? book.sections : book.sections.slice(0, previewCount)),
|
||||
[book.sections, fullAccess, previewCount],
|
||||
)
|
||||
|
||||
async function refreshPayMeta(packFree?: boolean) {
|
||||
/** 仅挂载锚点起 mountCount 章,目录跳转不拖全书 DOM */
|
||||
const windowSections = useMemo(() => {
|
||||
if (readableSections.length <= 0) return [] as string[]
|
||||
const start = Math.min(anchorIdx, readableSections.length - 1)
|
||||
return readableSections.slice(start, start + mountCount)
|
||||
}, [readableSections, anchorIdx, mountCount])
|
||||
|
||||
const remainReadable = Math.max(0, readableSections.length - anchorIdx)
|
||||
|
||||
async function refreshPayMeta() {
|
||||
// 提审中禁止拉取正式书 access/unlock,避免污染提审全文或把正式已购粘进提审
|
||||
if (auditLiveRef.current) {
|
||||
const free = auditFreePayMeta()
|
||||
setPayMeta(free)
|
||||
payFpRef.current = 'audit|free'
|
||||
return free
|
||||
}
|
||||
try {
|
||||
const [detail, access] = await Promise.all([
|
||||
fetchBook(bookId).catch(() => null),
|
||||
fetchAccess(bookId).catch(() => null),
|
||||
])
|
||||
const unlocked = !!(access?.unlocked || access?.is_free)
|
||||
const next = metaFromBook(detail || undefined, unlocked)
|
||||
if (packFree) {
|
||||
// books 表决定是否免费;access.unlocked 在免费时也会是 true,不能当成「已购」粘住
|
||||
const bookFree = !!(
|
||||
detail?.is_free ||
|
||||
access?.is_free ||
|
||||
Number(detail?.unlock_percent ?? access?.unlock_percent ?? 0) >= 100
|
||||
)
|
||||
const purchased = !bookFree && !!(access?.unlocked)
|
||||
const next = metaFromBook(detail || undefined, purchased)
|
||||
if (bookFree) {
|
||||
next.is_free = true
|
||||
next.unlock_percent = 100
|
||||
next.unlocked = false
|
||||
next.product_id = ''
|
||||
next.price_fen = 0
|
||||
}
|
||||
setPayMeta(next)
|
||||
setPayMeta((prev) => {
|
||||
// 免费 → 收费:立刻收回已挂载全文窗口
|
||||
if ((prev.is_free || prev.unlocked) && !next.is_free && !next.unlocked && !isVip) {
|
||||
setAnchorIdx(0)
|
||||
setActiveSec(0)
|
||||
setMountCount(2)
|
||||
setScrollEpoch((n) => n + 1)
|
||||
setScrollTop(0)
|
||||
}
|
||||
return next
|
||||
})
|
||||
payFpRef.current = [
|
||||
next.is_free ? 1 : 0,
|
||||
next.unlocked ? 1 : 0,
|
||||
next.unlock_percent,
|
||||
next.product_id,
|
||||
next.price_fen,
|
||||
].join('|')
|
||||
return next
|
||||
} catch {
|
||||
return payMeta
|
||||
}
|
||||
}
|
||||
|
||||
const toc: TocItem[] = useMemo(() => {
|
||||
const titles =
|
||||
book.headers.length > 0
|
||||
? book.headers
|
||||
: book.sections.map((s, i) => {
|
||||
const m = s.match(/^#{1,2}\s+(.+)$/m)
|
||||
return m ? m[1].trim() : `章节 ${i + 1}`
|
||||
})
|
||||
// 目录项与 sections 对齐(跳转锚点)
|
||||
const n = Math.max(titles.length, book.sections.length)
|
||||
const items: TocItem[] = []
|
||||
for (let i = 0; i < n; i++) {
|
||||
items.push({
|
||||
index: Math.min(i, book.sections.length - 1),
|
||||
title: titles[i] || `章节 ${i + 1}`,
|
||||
})
|
||||
/** 与 reader 对齐:2s 轮询权限指纹,后台切免费/收费秒级生效 */
|
||||
async function syncPayAccess() {
|
||||
if (youtubeMisroute || paySyncing.current || auditLiveRef.current) return
|
||||
paySyncing.current = true
|
||||
try {
|
||||
const access = await fetchAccess(bookId).catch(() => null)
|
||||
const detail = await fetchBook(bookId).catch(() => null)
|
||||
const fp = access
|
||||
? accessFingerprint(access)
|
||||
: detail
|
||||
? [
|
||||
detail.is_free || Number(detail.unlock_percent || 0) >= 100 ? 1 : 0,
|
||||
0,
|
||||
detail.unlock_percent,
|
||||
detail.product_id || '',
|
||||
detail.price_fen ?? 0,
|
||||
].join('|')
|
||||
: ''
|
||||
if (!fp) return
|
||||
if (!payFpRef.current) {
|
||||
payFpRef.current = fp
|
||||
await refreshPayMeta()
|
||||
return
|
||||
}
|
||||
if (fp !== payFpRef.current) {
|
||||
payFpRef.current = fp
|
||||
await refreshPayMeta()
|
||||
}
|
||||
} finally {
|
||||
paySyncing.current = false
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
const toc: TocItem[] = useMemo(() => {
|
||||
// 一章一条,禁止 headers 多出行时多条目录塌到同一 index
|
||||
return book.sections.map((s, i) => {
|
||||
const fromHeader = book.headers[i]
|
||||
if (fromHeader) return { index: i, title: fromHeader }
|
||||
const m = s.match(/^#{1,2}\s+(.+)$/m)
|
||||
return { index: i, title: m ? m[1].trim() : `章节 ${i + 1}` }
|
||||
})
|
||||
}, [book])
|
||||
|
||||
const filteredToc = useMemo(() => {
|
||||
const q = tocFilter.trim().toLowerCase()
|
||||
if (!q) return toc
|
||||
return toc.filter((t) => t.title.toLowerCase().includes(q))
|
||||
}, [toc, tocFilter])
|
||||
// 目录/换书:重置为 2 章;首屏空闲只补到 4,再往后靠滚动
|
||||
useEffect(() => {
|
||||
setMountCount(2)
|
||||
}, [bookId, anchorIdx])
|
||||
|
||||
useEffect(() => {
|
||||
if (mountCount >= 4 || mountCount >= remainReadable) return
|
||||
const t = setTimeout(() => {
|
||||
setMountCount((c) => Math.min(c + 2, 4, remainReadable))
|
||||
}, 40)
|
||||
return () => clearTimeout(t)
|
||||
}, [mountCount, remainReadable])
|
||||
|
||||
useEffect(() => {
|
||||
if (youtubeMisroute) return
|
||||
let cancelled = false
|
||||
setScrollInto('')
|
||||
setScrollTop(0)
|
||||
setDrawerOpen(false)
|
||||
setTocFilter('')
|
||||
setActiveSec(0)
|
||||
setAnchorIdx(0)
|
||||
setMountCount(2)
|
||||
setScrollEpoch(0)
|
||||
setReadProgress(0)
|
||||
setReady(false)
|
||||
Taro.setNavigationBarTitle({ title: book.title })
|
||||
// 包内先读;网络全部后台,不挡首屏
|
||||
void (async () => {
|
||||
try {
|
||||
// 数字游民提审:同一 vip-ebook 壳 + 线上 audit 正文(失联才包内兜底)
|
||||
if (bookId === 'nomad') {
|
||||
try {
|
||||
await loadRemoteConfig(true)
|
||||
} catch {
|
||||
/* cache */
|
||||
}
|
||||
if (cancelled) return
|
||||
const audit = resolveBookAudit(getCachedRemoteConfig())
|
||||
if (audit.reviewMode) {
|
||||
const auditId = audit.bookId || 'audit'
|
||||
let pack: VipEbookPack
|
||||
if (!audit.reviewMode) {
|
||||
void loadRemoteConfig(false).catch(() => undefined)
|
||||
} else {
|
||||
try {
|
||||
const res = await fetchAuditRead(auditId)
|
||||
pack = auditPayloadToPack(auditId, res.payload)
|
||||
await loadRemoteConfig(true)
|
||||
} catch {
|
||||
pack = auditPayloadToPack(auditId, getAuditOfflineRead(auditId))
|
||||
/* cache */
|
||||
}
|
||||
if (cancelled) return
|
||||
setBook(pack)
|
||||
setPayMeta(metaFromBook(undefined, true))
|
||||
setIsVip(true)
|
||||
Taro.setNavigationBarTitle({ title: pack.title })
|
||||
return
|
||||
const nextAudit = resolveBookAudit(getCachedRemoteConfig())
|
||||
if (nextAudit.reviewMode) {
|
||||
const auditId = nextAudit.bookId || 'audit'
|
||||
let pack: VipEbookPack
|
||||
try {
|
||||
const res = await fetchAuditRead(auditId)
|
||||
pack = auditPayloadToPack(auditId, res.payload)
|
||||
} catch {
|
||||
pack = auditPayloadToPack(auditId, getAuditOfflineRead(auditId))
|
||||
}
|
||||
if (cancelled) return
|
||||
enterAuditMode(pack)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { book: next } = await loadVipEbook(bookId)
|
||||
if (cancelled) return
|
||||
setBook(next)
|
||||
Taro.setNavigationBarTitle({ title: next.title })
|
||||
const vip = await resolveVipContentAccess(true)
|
||||
if (cancelled) return
|
||||
setIsVip(vip)
|
||||
await refreshPayMeta(!!next.free)
|
||||
auditLiveRef.current = false
|
||||
setAuditLive(false)
|
||||
|
||||
void loadVipEbook(bookId)
|
||||
.then(({ book: next }) => {
|
||||
if (cancelled) return
|
||||
setBook(next)
|
||||
Taro.setNavigationBarTitle({ title: next.title })
|
||||
})
|
||||
.catch(() => undefined)
|
||||
|
||||
void resolveVipAccess(false)
|
||||
.then((vip) => {
|
||||
if (!cancelled && !auditLiveRef.current) setIsVip(vip)
|
||||
})
|
||||
.catch(() => undefined)
|
||||
|
||||
void refreshPayMeta()
|
||||
} catch {
|
||||
if (cancelled) return
|
||||
const fallback = VIP_EBOOKS[bookId] || VIP_EBOOKS.nomad
|
||||
setBook(fallback)
|
||||
setIsVip(false)
|
||||
await refreshPayMeta(!!fallback.free)
|
||||
Taro.setNavigationBarTitle({ title: fallback.title })
|
||||
} finally {
|
||||
if (!cancelled) setReady(true)
|
||||
/* keep seed book */
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
@ -272,63 +401,86 @@ export default function VipEbookPage() {
|
||||
}
|
||||
}, [bookId])
|
||||
|
||||
// 提审开关 + 本册付费方案 bump → 热刷新(只动当前 bookId)
|
||||
// 付费方案 bump:只刷 payMeta,禁止整页 setReady(false)(会黑屏)
|
||||
// 提审开关:仅 reviewMode 真变时才换正文
|
||||
useEffect(() => {
|
||||
let lastOfferRev = -1
|
||||
let lastAuditKey = ''
|
||||
return subscribeRemoteConfig((r) => {
|
||||
const rev = Number(r.config.copy?.booksOfferRev || 0)
|
||||
const bumped = String(r.config.copy?.booksOfferBookId || '')
|
||||
if (rev !== lastOfferRev) {
|
||||
lastOfferRev = rev
|
||||
if (!bumped || bumped === bookId) {
|
||||
void refreshPayMeta(!!book.free)
|
||||
// 提审中忽略正式书 offer bump,防止把付费方案刷进提审页
|
||||
if (!auditLiveRef.current && (!bumped || bumped === bookId)) {
|
||||
void refreshPayMeta()
|
||||
}
|
||||
}
|
||||
if (bookId !== 'nomad') return
|
||||
const audit = resolveBookAudit(r.config)
|
||||
setReady(false)
|
||||
const auditKey = `${audit.reviewMode ? 1 : 0}:${audit.bookId || ''}`
|
||||
if (auditKey === lastAuditKey) return
|
||||
lastAuditKey = auditKey
|
||||
void (async () => {
|
||||
try {
|
||||
if (audit.reviewMode) {
|
||||
const auditId = audit.bookId || 'audit'
|
||||
const res = await fetchAuditRead(auditId)
|
||||
const pack = auditPayloadToPack(auditId, res.payload)
|
||||
setBook(pack)
|
||||
setPayMeta(metaFromBook(undefined, true))
|
||||
Taro.setNavigationBarTitle({ title: pack.title })
|
||||
enterAuditMode(pack)
|
||||
} else {
|
||||
const { book: next } = await loadVipEbook('nomad')
|
||||
setBook(next)
|
||||
setIsVip(await resolveVipContentAccess(true))
|
||||
await refreshPayMeta(!!next.free)
|
||||
Taro.setNavigationBarTitle({ title: next.title })
|
||||
await leaveAuditMode()
|
||||
}
|
||||
} catch {
|
||||
/* keep */
|
||||
} finally {
|
||||
setReady(true)
|
||||
/* keep current page — never blank to black */
|
||||
}
|
||||
})()
|
||||
})
|
||||
}, [bookId, book.free])
|
||||
}, [bookId])
|
||||
|
||||
// 提审开关热更新兜底:页内 1s 拉配置(不依赖 App 层是否已挂 live sync)
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
void loadRemoteConfig(true).catch(() => undefined)
|
||||
}, 1000)
|
||||
return () => clearInterval(timer)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeVipAccess((vip) => {
|
||||
setIsVip(hasVipContentAccessSync(vip))
|
||||
// 提审态不吸收正式 VIP,避免关提审后粘住或审核员看到付费权益串台
|
||||
if (auditLiveRef.current) return
|
||||
setIsVip(!!vip)
|
||||
})
|
||||
}, [])
|
||||
|
||||
// 真机:2s 轮询 books/access,后台切免费↔收费不必靠 WS
|
||||
useEffect(() => {
|
||||
if (youtubeMisroute || auditLive) return
|
||||
if (process.env.TARO_ENV === 'h5') return
|
||||
const timer = setInterval(() => {
|
||||
void syncPayAccess()
|
||||
}, 2000)
|
||||
void syncPayAccess()
|
||||
return () => clearInterval(timer)
|
||||
}, [bookId, youtubeMisroute, auditLive])
|
||||
|
||||
useDidShow(() => {
|
||||
if (youtubeMisroute) return
|
||||
void refreshPayMeta(!!book.free)
|
||||
void resolveVipContentAccess(true).then(setIsVip)
|
||||
if (auditLiveRef.current) {
|
||||
setPayMeta(auditFreePayMeta())
|
||||
return
|
||||
}
|
||||
void refreshPayMeta()
|
||||
void syncPayAccess()
|
||||
void resolveVipAccess(false).then(setIsVip).catch(() => undefined)
|
||||
})
|
||||
|
||||
async function handleUnlockBook() {
|
||||
if (paying || fullAccess) return
|
||||
await refreshPayMeta(!!book.free)
|
||||
if (payMeta.is_free || payMeta.unlocked) return
|
||||
if (!payMeta.product_id || payMeta.price_fen <= 0) {
|
||||
if (paying || fullAccess || auditLiveRef.current) return
|
||||
const latest = await refreshPayMeta()
|
||||
if (latest.is_free || latest.unlocked) return
|
||||
if (!latest.product_id || latest.price_fen <= 0) {
|
||||
goVipUnlock()
|
||||
return
|
||||
}
|
||||
@ -340,7 +492,7 @@ export default function VipEbookPage() {
|
||||
try {
|
||||
if (await pollUnlock(bookId, outTradeNo)) {
|
||||
setPayMeta((m) => ({ ...m, unlocked: true }))
|
||||
Taro.showToast({ title: '已解锁本册', icon: 'success' })
|
||||
Taro.showToast({ title: '已打开全文', icon: 'success' })
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
@ -349,10 +501,20 @@ export default function VipEbookPage() {
|
||||
}
|
||||
Taro.showToast({ title: '支付确认中,请稍后下拉刷新', icon: 'none' })
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e)
|
||||
if (!/cancel|取消|-2/i.test(msg)) {
|
||||
Taro.showModal({ title: '支付未完成', content: msg, showCancel: false })
|
||||
}
|
||||
const fb = mapPayError(e)
|
||||
if (fb.kind === 'cancel') return
|
||||
Taro.showModal({
|
||||
title: fb.title,
|
||||
content: fb.desc,
|
||||
showCancel: !!fb.secondaryText,
|
||||
confirmText: fb.primaryText.slice(0, 4) || '确定',
|
||||
cancelText: (fb.secondaryText || '取消').slice(0, 4),
|
||||
success: (r) => {
|
||||
if (r.confirm && /再试|重新/.test(fb.primaryText)) {
|
||||
setTimeout(() => void handleUnlockBook(), 120)
|
||||
}
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
setPaying(false)
|
||||
}
|
||||
@ -361,11 +523,18 @@ export default function VipEbookPage() {
|
||||
function onScroll(e: {
|
||||
detail?: { scrollTop?: number; scrollHeight?: number }
|
||||
}) {
|
||||
const now = Date.now()
|
||||
if (now - scrollTick.current < 80) return
|
||||
scrollTick.current = now
|
||||
const top = Number(e.detail?.scrollTop || 0)
|
||||
const height = Number(e.detail?.scrollHeight || 1)
|
||||
const view = Math.max(1, height - 400)
|
||||
setReadProgress(Math.min(100, (top / view) * 100))
|
||||
setShowBackTop(top > 600)
|
||||
setShowBackTop(top > 400)
|
||||
// 接近底部再多挂载两章
|
||||
if (top > height * 0.55 && mountCount < remainReadable) {
|
||||
setMountCount((c) => Math.min(c + 2, remainReadable))
|
||||
}
|
||||
}
|
||||
|
||||
function openDrawer() {
|
||||
@ -376,16 +545,69 @@ export default function VipEbookPage() {
|
||||
setDrawerOpen(false)
|
||||
}
|
||||
|
||||
function bumpScroll(top = 0) {
|
||||
setScrollEpoch((n) => n + 1)
|
||||
setScrollTop(top)
|
||||
}
|
||||
|
||||
/** 量付费墙位置,滚到「试读末章末尾 + 付费区」 */
|
||||
function scrollPaywallIntoView() {
|
||||
setTimeout(() => {
|
||||
if (process.env.TARO_ENV === 'h5' && typeof document !== 'undefined') {
|
||||
const root = document.querySelector('.veb-scroll') as HTMLElement | null
|
||||
const el = document.getElementById('veb-paywall')
|
||||
if (root && el) {
|
||||
const next = Math.max(0, el.offsetTop - 24)
|
||||
setScrollTop(next + 0.01)
|
||||
requestAnimationFrame(() => setScrollTop(next))
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
const q = Taro.createSelectorQuery()
|
||||
q.select('.veb-scroll').boundingClientRect()
|
||||
q.select('#veb-paywall').boundingClientRect()
|
||||
q.select('.veb-scroll').scrollOffset()
|
||||
q.exec((res) => {
|
||||
const sv = res?.[0] as { top?: number } | undefined
|
||||
const target = res?.[1] as { top?: number } | undefined
|
||||
const offset = res?.[2] as { scrollTop?: number } | undefined
|
||||
if (
|
||||
!sv ||
|
||||
!target ||
|
||||
!offset ||
|
||||
typeof sv.top !== 'number' ||
|
||||
typeof target.top !== 'number'
|
||||
) {
|
||||
return
|
||||
}
|
||||
const next = Math.max(0, Number(offset.scrollTop || 0) + target.top - sv.top - 24)
|
||||
setScrollTop(next + 0.01)
|
||||
setTimeout(() => setScrollTop(next), 16)
|
||||
})
|
||||
}, 80)
|
||||
}
|
||||
|
||||
/** 目录跳转:切窗口到目标章 + 顶置,零等待量 DOM */
|
||||
function jumpTo(secIndex: number) {
|
||||
const maxIdx = fullAccess
|
||||
? book.sections.length - 1
|
||||
: Math.max(0, previewCount - 1)
|
||||
const maxIdx = Math.max(0, readableSections.length - 1)
|
||||
const idx = Math.max(0, Math.min(secIndex, maxIdx))
|
||||
setActiveSec(idx)
|
||||
setDrawerOpen(false)
|
||||
const id = `veb-sec-${idx}`
|
||||
setScrollInto('')
|
||||
setTimeout(() => setScrollInto(id), 120)
|
||||
setActiveSec(idx)
|
||||
setAnchorIdx(idx)
|
||||
setMountCount(2)
|
||||
bumpScroll(0)
|
||||
}
|
||||
|
||||
/** 锁定章:落到试读末章,下面接付费区(保留正文语境) */
|
||||
function jumpPaywall() {
|
||||
setDrawerOpen(false)
|
||||
const last = Math.max(0, readableSections.length - 1)
|
||||
setActiveSec(last)
|
||||
setAnchorIdx(last)
|
||||
setMountCount(1)
|
||||
bumpScroll(0)
|
||||
scrollPaywallIntoView()
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
@ -403,26 +625,21 @@ export default function VipEbookPage() {
|
||||
)
|
||||
}
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<H5Box className="veb" data-theme={theme}>
|
||||
<H5Txt className="veb-loading">加载中…</H5Txt>
|
||||
</H5Box>
|
||||
)
|
||||
}
|
||||
|
||||
const remainMin = Math.max(
|
||||
0,
|
||||
Math.ceil(book.estimatedMinutes * (1 - readProgress / 100)),
|
||||
)
|
||||
const drawerListH = `calc(100vh - ${safe.statusBarHeight + 200}px)`
|
||||
const needsPaywall = !fullAccess && visibleSections.length < book.sections.length
|
||||
const drawerListH = `calc(100vh - ${safe.statusBarHeight + 160}px)`
|
||||
const atReadableEnd =
|
||||
readableSections.length > 0 &&
|
||||
anchorIdx + Math.max(windowSections.length, 1) >= readableSections.length
|
||||
const needsPaywall =
|
||||
!fullAccess && readableSections.length < book.sections.length && atReadableEnd
|
||||
|
||||
return (
|
||||
<H5Box className="veb" data-theme={theme}>
|
||||
<View className="veb-progress" style={{ width: `${readProgress}%` }} />
|
||||
|
||||
{/* 顶栏:☰ 目录 | 标题(点也可开目录) | 右侧留胶囊位 */}
|
||||
<View className="veb-header" style={{ paddingTop: `${safe.statusBarHeight}px` }}>
|
||||
<View
|
||||
className="veb-header-inner"
|
||||
@ -434,10 +651,7 @@ export default function VipEbookPage() {
|
||||
<View className="veb-title-wrap" onClick={openDrawer}>
|
||||
<Text className="veb-title">{book.title}</Text>
|
||||
<Text className="veb-sub">
|
||||
{fullAccess
|
||||
? `${activeSec + 1}/${book.sections.length} · 约剩 ${remainMin} 分钟`
|
||||
: `试读 ${payMeta.unlock_percent}% · ${visibleSections.length}/${book.sections.length} 章`}
|
||||
{' · 点此开目录'}
|
||||
{`${activeSec + 1}/${book.sections.length} · 约剩 ${remainMin} 分钟`}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="veb-icon-btn" onClick={goBack} hoverClass="veb-icon-btn-hover">
|
||||
@ -447,47 +661,83 @@ export default function VipEbookPage() {
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
key={`veb-sv-${scrollEpoch}`}
|
||||
scrollY
|
||||
className="veb-scroll"
|
||||
style={{ height: `calc(100vh - ${safe.statusBarHeight + 52}px)` }}
|
||||
scrollIntoView={scrollInto}
|
||||
scrollWithAnimation
|
||||
enhanced
|
||||
showScrollbar
|
||||
scrollTop={scrollTop}
|
||||
scrollWithAnimation={false}
|
||||
showScrollbar={false}
|
||||
onScroll={onScroll}
|
||||
>
|
||||
<View className="veb-book">
|
||||
{visibleSections.map((sec, i) => (
|
||||
<View key={`sec-${i}`} id={`veb-sec-${i}`} className="veb-section">
|
||||
{windowSections.map((sec, i) => {
|
||||
const absIdx = anchorIdx + i
|
||||
return (
|
||||
<View
|
||||
key={`sec-${absIdx}`}
|
||||
id={`veb-sec-${absIdx}`}
|
||||
className="veb-section veb-book-sec"
|
||||
>
|
||||
<MarkdownView markdown={sec} prefs={EBOOK_PREFS} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
{needsPaywall ? (
|
||||
<View className="veb-paywall" id="veb-paywall">
|
||||
<Text className="veb-paywall-title">试读结束 · 解锁本册全文</Text>
|
||||
<View className="veb-paywall-breath">
|
||||
<Text className="veb-paywall-dots">· · ·</Text>
|
||||
</View>
|
||||
{oa.avatar || oa.nick ? (
|
||||
<View className="veb-paywall-who">
|
||||
{oa.avatar ? (
|
||||
<Image
|
||||
className="veb-paywall-avatar"
|
||||
src={oa.avatar}
|
||||
mode="aspectFill"
|
||||
/>
|
||||
) : (
|
||||
<View className="veb-paywall-avatar veb-paywall-avatar--fallback">
|
||||
<Text className="veb-paywall-avatar-txt">
|
||||
{(oa.nick || '游').slice(0, 1)}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
{oa.nick ? (
|
||||
<Text className="veb-paywall-who-name">{oa.nick}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
<Text className="veb-paywall-title">
|
||||
{oa.nick ? `${oa.nick},后面还有` : '后面还有'}
|
||||
</Text>
|
||||
<Text className="veb-paywall-sub">
|
||||
{payMeta.offer_name
|
||||
? `${payMeta.offer_name} · 仅解锁《${book.title}》,不影响其它小册`
|
||||
: `仅解锁《${book.title}》,与其它小册互不影响`}
|
||||
{oa.nick
|
||||
? `${oa.nick},读到这里了。想继续往后翻时,再打开完整章节。`
|
||||
: '读到这里了。想继续往后翻时,再打开完整章节。'}
|
||||
</Text>
|
||||
<Button
|
||||
className="veb-paywall-btn"
|
||||
loading={paying}
|
||||
onClick={() => void handleUnlockBook()}
|
||||
>
|
||||
{paying ? '拉起支付…' : payMeta.unlock_btn_text}
|
||||
{paying ? '请稍候…' : payMeta.unlock_btn_text}
|
||||
</Button>
|
||||
{payMeta.price_fen > 0 ? (
|
||||
<Text className="veb-paywall-price">
|
||||
{payMeta.offer_name
|
||||
? `${payMeta.offer_name} · ¥${Math.round(payMeta.price_fen / 100)}`
|
||||
: `¥${Math.round(payMeta.price_fen / 100)}`}
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="veb-paywall-vip" onClick={() => goVipUnlock()}>
|
||||
<Text>或开通 VIP 读全部会员书</Text>
|
||||
<Text>会员可阅读全部</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
) : atReadableEnd ? (
|
||||
<View className="veb-end">— 全书完 —</View>
|
||||
)}
|
||||
) : null}
|
||||
</ScrollView>
|
||||
|
||||
{/* 目录抽屉:mask 与 drawer 分离,避免点击穿透 */}
|
||||
{drawerOpen ? (
|
||||
<View className="veb-drawer-root">
|
||||
<View className="veb-mask" onClick={closeDrawer} />
|
||||
@ -497,82 +747,56 @@ export default function VipEbookPage() {
|
||||
catchMove
|
||||
>
|
||||
<View className="veb-drawer-hero">
|
||||
<Text className="veb-drawer-brand">CONTENTS</Text>
|
||||
<Text className="veb-drawer-title">章节目录</Text>
|
||||
<Text className="veb-drawer-book">《{book.title}》</Text>
|
||||
<View className="veb-drawer-meter">
|
||||
<View
|
||||
className="veb-drawer-meter-fill"
|
||||
style={{ width: `${readProgress}%` }}
|
||||
/>
|
||||
</View>
|
||||
<View className="veb-drawer-stats">
|
||||
<Text>进度 {Math.round(readProgress)}%</Text>
|
||||
<Text>
|
||||
{activeSec + 1}/{book.sections.length} 章
|
||||
{activeSec + 1}/{book.sections.length}
|
||||
</Text>
|
||||
</View>
|
||||
<Input
|
||||
className="veb-drawer-search"
|
||||
value={tocFilter}
|
||||
placeholder="筛选章节"
|
||||
placeholderClass="veb-drawer-search-ph"
|
||||
onInput={(e) => setTocFilter(e.detail.value)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
scrollY
|
||||
className="veb-drawer-list"
|
||||
style={{ height: drawerListH }}
|
||||
scrollWithAnimation
|
||||
enhanced
|
||||
showScrollbar
|
||||
showScrollbar={false}
|
||||
>
|
||||
{filteredToc.length === 0 ? (
|
||||
<View className="veb-drawer-empty">
|
||||
<Text>无匹配章节</Text>
|
||||
</View>
|
||||
) : (
|
||||
filteredToc.map((item, listIdx) => {
|
||||
const active = item.index === activeSec
|
||||
const locked = !fullAccess && item.index >= previewCount
|
||||
return (
|
||||
<View
|
||||
key={`toc-${listIdx}-${item.index}`}
|
||||
className={`veb-drawer-item${active ? ' is-active' : ''}${locked ? ' is-locked' : ''}`}
|
||||
onClick={() => {
|
||||
if (locked) {
|
||||
setDrawerOpen(false)
|
||||
setTimeout(() => setScrollInto('veb-paywall'), 80)
|
||||
return
|
||||
}
|
||||
jumpTo(item.index)
|
||||
}}
|
||||
>
|
||||
<Text className="veb-drawer-idx">
|
||||
{String(item.index + 1).padStart(2, '0')}
|
||||
</Text>
|
||||
<Text className="veb-drawer-name">{item.title}</Text>
|
||||
{locked ? <Text className="veb-drawer-lock">锁</Text> : null}
|
||||
</View>
|
||||
)
|
||||
})
|
||||
)}
|
||||
{toc.map((item) => {
|
||||
const active = item.index === activeSec
|
||||
const locked = !fullAccess && item.index >= previewCount
|
||||
return (
|
||||
<View
|
||||
key={`toc-${item.index}`}
|
||||
className={`veb-drawer-item${active ? ' is-active' : ''}${locked ? ' is-locked' : ''}`}
|
||||
hoverClass="veb-drawer-item-hover"
|
||||
onClick={() => {
|
||||
if (locked) {
|
||||
jumpPaywall()
|
||||
return
|
||||
}
|
||||
jumpTo(item.index)
|
||||
}}
|
||||
>
|
||||
<Text className="veb-drawer-idx">
|
||||
{String(item.index + 1).padStart(2, '0')}
|
||||
</Text>
|
||||
<Text className="veb-drawer-name">{item.title}</Text>
|
||||
{locked ? <LockIcon /> : null}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
</ScrollView>
|
||||
|
||||
<View className="veb-drawer-close" onClick={closeDrawer}>
|
||||
<Text>关闭目录</Text>
|
||||
<View className="veb-drawer-close" onClick={closeDrawer} hoverClass="veb-drawer-item-hover">
|
||||
<Text>关闭</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{showBackTop ? (
|
||||
<View
|
||||
className="veb-top"
|
||||
onClick={() => jumpTo(0)}
|
||||
>
|
||||
<View className="veb-top" onClick={() => jumpTo(0)}>
|
||||
<Text>↑</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@ -161,12 +161,35 @@ function auditOfflineRead(bookId: string): ReadPayload {
|
||||
}
|
||||
}
|
||||
|
||||
/** 离线正文可兜底;付费字段失联时 fail-closed(勿默认全书免费) */
|
||||
function offlinePayClosed(id: string): BookDetail {
|
||||
return {
|
||||
...OFFLINE_BOOK,
|
||||
id,
|
||||
is_free: false,
|
||||
unlock_percent: Math.min(99, Math.max(1, Number(OFFLINE_BOOK.unlock_percent) || 30)),
|
||||
// 保留包内 product 仅作占位;真正 SoT 必须来自线上 books
|
||||
price_fen: Number(OFFLINE_BOOK.price_fen) || 0,
|
||||
product_id: String(OFFLINE_BOOK.product_id || ''),
|
||||
}
|
||||
}
|
||||
|
||||
function forceAuditFreeBook(book: BookDetail, id: string): BookDetail {
|
||||
return {
|
||||
...book,
|
||||
id,
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
price_fen: 0,
|
||||
product_id: '',
|
||||
offer_key: 'free',
|
||||
offer_name: '免费全书',
|
||||
price_label: '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
||||
const id = bookId || 'default'
|
||||
// H5:正式书用离线包;提审书离线优先,失败也不回正式包
|
||||
if (process.env.TARO_ENV === 'h5' && !isAuditBookId(id)) {
|
||||
return { ...OFFLINE_BOOK, id }
|
||||
}
|
||||
if (isAuditBookId(id)) {
|
||||
try {
|
||||
const remote = await request<BookDetail>({
|
||||
@ -174,16 +197,33 @@ export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
||||
// 提审书匿名可读:401 不触发清 token + 重登
|
||||
_retried: true,
|
||||
})
|
||||
if (remote && (remote.chapter_count || remote.chapters?.length)) return remote
|
||||
if (remote && (remote.chapter_count || remote.chapters?.length)) {
|
||||
return forceAuditFreeBook(remote, id)
|
||||
}
|
||||
} catch {
|
||||
/* 失联才包内兜底 */
|
||||
}
|
||||
return auditOfflineBook(id)
|
||||
}
|
||||
// 付费 SoT 永远优先线上 books(含本地 H5);正文可另走离线包
|
||||
try {
|
||||
const remote = await request<BookDetail>({
|
||||
url: `/api/ebook/books/${id}?_=${Date.now()}`,
|
||||
_retried: true,
|
||||
})
|
||||
if (remote && (remote.id || remote.product_id || remote.unlock_percent != null)) {
|
||||
return remote
|
||||
}
|
||||
} catch {
|
||||
/* fallthrough */
|
||||
}
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
return offlinePayClosed(id)
|
||||
}
|
||||
try {
|
||||
return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` })
|
||||
} catch {
|
||||
return { ...OFFLINE_BOOK, id }
|
||||
return offlinePayClosed(id)
|
||||
}
|
||||
}
|
||||
|
||||
@ -216,33 +256,62 @@ export async function fetchRead(bookId = 'default'): Promise<ReadPayload> {
|
||||
}
|
||||
|
||||
export async function fetchAccess(bookId = 'default'): Promise<AccessSnapshot> {
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
const payload = offlineReadPayload()
|
||||
const id = bookId || 'default'
|
||||
// 提审书:本地硬编码免费快照,不读正式 unlocks / VIP
|
||||
if (isAuditBookId(id)) {
|
||||
return {
|
||||
book_id: bookId || 'default',
|
||||
unlocked: !!payload.unlocked,
|
||||
is_free: !!payload.is_free,
|
||||
unlock_percent: payload.unlock_percent,
|
||||
product_id: payload.book.product_id,
|
||||
price_fen: payload.book.price_fen,
|
||||
offer_key: payload.book.offer_key,
|
||||
updated_at: payload.updated_at || 0,
|
||||
book_id: id,
|
||||
unlocked: false,
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
product_id: '',
|
||||
price_fen: 0,
|
||||
offer_key: 'free',
|
||||
updated_at: Date.now(),
|
||||
}
|
||||
}
|
||||
try {
|
||||
await ensureLogin()
|
||||
return await request({ url: `/api/ebook/books/${bookId}/access?_=${Date.now()}` })
|
||||
} catch {
|
||||
const fromBook = async (): Promise<AccessSnapshot> => {
|
||||
const book = await fetchBook(id)
|
||||
const free = !!(book.is_free || (book.unlock_percent ?? 0) >= 100)
|
||||
return {
|
||||
book_id: bookId || 'default',
|
||||
book_id: id,
|
||||
unlocked: false,
|
||||
is_free: false,
|
||||
unlock_percent: OFFLINE_BOOK.unlock_percent,
|
||||
product_id: OFFLINE_BOOK.product_id,
|
||||
price_fen: OFFLINE_BOOK.price_fen,
|
||||
is_free: free,
|
||||
unlock_percent: free ? 100 : Math.min(99, Math.max(1, book.unlock_percent || 30)),
|
||||
product_id: free ? '' : String(book.product_id || ''),
|
||||
price_fen: free ? 0 : Number(book.price_fen || 0),
|
||||
offer_key: book.offer_key,
|
||||
updated_at: Date.now(),
|
||||
}
|
||||
}
|
||||
// 权限快照走线上;登录失败不堵页面(阅读壳先出正文)
|
||||
try {
|
||||
if (process.env.TARO_ENV !== 'h5') {
|
||||
try {
|
||||
await ensureLogin()
|
||||
} catch {
|
||||
return fromBook()
|
||||
}
|
||||
}
|
||||
return await request({
|
||||
url: `/api/ebook/books/${id}/access?_=${Date.now()}`,
|
||||
_retried: true,
|
||||
})
|
||||
} catch {
|
||||
try {
|
||||
return await fromBook()
|
||||
} catch {
|
||||
return {
|
||||
book_id: id,
|
||||
unlocked: false,
|
||||
is_free: false,
|
||||
unlock_percent: 30,
|
||||
product_id: '',
|
||||
price_fen: 0,
|
||||
updated_at: Date.now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function accessFingerprint(a: AccessSnapshot | ReadPayload | null | undefined): string {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user