"""试读截断策略:按全书正文字符数百分比裁剪。 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"]*$", 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 # 无论是否整段装下,末尾半截标签都清掉(防预算刚好卡在 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, }