nomadro/apps/ebook/dymini/backend/app/domains/books/read_policy.py
eric d93a355fd5 Migrate navmini/ebook/nomadweb into apps/ as same-origin portal subpaths.
Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:30:34 -05:00

110 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""试读截断策略:按全书正文字符数百分比裁剪。 unlock_percent>=100 视为免费全书。"""
from __future__ import annotations
import re
from .products import is_book_free, match_offer, unlock_button_text
_INCOMPLETE_IMG = re.compile(r"<img\b[^>]*$", re.IGNORECASE | re.DOTALL)
_INCOMPLETE_MD_IMG = re.compile(r"!\[[^\]]*\]\([^)]*$")
_INCOMPLETE_HTML = re.compile(r"<[A-Za-z][^>]*$")
def is_free_unlock(percent: int | None) -> bool:
return int(percent or 0) >= 100
def safe_cut_text(content: str, limit: int) -> str:
"""按字数裁剪,避免切在 HTML/Markdown 图片标签中间。"""
if limit <= 0:
return ""
cut = content if len(content) <= limit else content[:limit]
cut = cut.rstrip()
if len(content) > limit:
for sep in ("\n\n", "\n", "。", "!", "?", ".", "!", "?"):
idx = cut.rfind(sep)
if idx >= max(40, limit // 3):
cut = cut[: idx + len(sep)].rstrip()
break
# 无论是否整段装下,末尾半截标签都清掉(防预算刚好卡在 <img 中间)
cut = _INCOMPLETE_IMG.sub("", cut)
cut = _INCOMPLETE_MD_IMG.sub("", cut)
cut = _INCOMPLETE_HTML.sub("", cut)
return cut.rstrip()
def truncate_by_percent(chapters: list[dict], percent: int) -> list[dict]:
if is_free_unlock(percent):
return [{**ch, "content": ch.get("content") or ""} for ch in chapters]
ratio = max(1, min(99, int(percent))) / 100.0
total = sum(len(ch.get("content") or "") for ch in chapters) or 1
budget = max(120, int(total * ratio))
used = 0
out: list[dict] = []
for ch in chapters:
content = ch.get("content") or ""
if used >= budget:
out.append({**ch, "content": ""})
continue
remain = budget - used
if len(content) <= remain:
out.append({**ch, "content": content})
used += len(content)
else:
cut = safe_cut_text(content, remain)
out.append({**ch, "content": cut})
used = budget
return out
def public_book(book: dict) -> dict:
chapters = [
{"id": c["id"], "title": c["title"], "order": c["order"]}
for c in book.get("chapters") or []
]
free = is_book_free(book)
offer = match_offer(book)
price_fen = 0 if free else int(book.get("price_fen") or 0)
return {
"id": book["id"],
"title": book["title"],
"subtitle": book["subtitle"],
"author": book["author"],
"cover_emoji": book["cover_emoji"],
"description": book["description"],
"tags": book["tags"],
"price_fen": price_fen,
"product_id": "" if free else book["product_id"],
"unlock_percent": book["unlock_percent"],
"is_free": free,
"offer_key": offer.get("key"),
"offer_name": offer.get("name") or offer.get("label"),
"price_label": "" if free or price_fen <= 0 else f"¥{price_fen / 100:.0f}",
"unlock_btn_text": unlock_button_text(book),
"updated_at": book.get("updated_at"),
"chapter_count": book["chapter_count"],
"word_count": book["word_count"],
"rating": book["rating"],
"chapters": chapters,
}
def access_snapshot(book: dict, *, openid: str, unlocked: bool) -> dict:
"""轻量权限快照,供小程序轮询,无需清缓存。"""
free = is_book_free(book)
offer = match_offer(book)
return {
"book_id": book["id"],
"unlocked": bool(unlocked or free),
"is_free": free,
"unlock_percent": int(book.get("unlock_percent") or 0),
"product_id": "" if free else str(book.get("product_id") or ""),
"price_fen": 0 if free else int(book.get("price_fen") or 0),
"offer_key": offer.get("key"),
"updated_at": book.get("updated_at") or 0,
"openid": openid,
}