From 4a21ac8df6cb95955b72e1a7e6b0a765828503a4 Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Fri, 27 Nov 2026 08:20:59 +0800 Subject: [PATCH] =?UTF-8?q?v3.37=EF=BC=9A=E6=9C=AA=E8=AF=BB=E7=BB=9F?= =?UTF-8?q?=E8=AE=A1=E4=B8=8E=E5=88=97=E8=A1=A8=E5=90=8C=E5=8F=A3=E5=BE=84?= =?UTF-8?q?=EF=BC=9BSPA=20=E7=AB=99=E7=82=B9=E6=94=B9=E4=BB=8E=E8=87=AA?= =?UTF-8?q?=E5=AE=B6=20RSS=20=E5=8F=96=E5=85=A8=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 7 + src/main/java/com/shitoucuo/postpad/RssApi.kt | 271 ++++++++++++++++-- 2 files changed, 250 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92a8923..1cd7ca5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # 变更记录 +## 2026-11-27 · v3.37(versionCode 58) + +- 修复信息角标与列表口径不一致(列表全读完、角标仍显示 3 条):未读统计改用与列表相同的每页条数。服务端 `getFeeds()` 是「按窗口取行 → 去重 → 切片分页」,`page_size` 一变窗口与切片边界全变,固定 100 条/页会扫到列表翻不到的条目;扫描上限同时改为按条数(1200)控制。 +- 新增 SPA 站点原文抓取:页面只有 `
` 等挂载点、正文由 JS 渲染时,自动回退到站点自家 `/feed/`,按文章 id 匹配 `content:encoded` 取全文(如 `zhongxiaojie.cn`);另以正文短于 80 字作为兜底触发条件。 +- feed 索引按站点缓存 10 分钟、最多翻 12 页,命中即返回;`content:encoded` 为 HTML 时走 HTML 转换,本身已是 Markdown 时按 Markdown 清理。 +- 实体还原补充数字实体(`–` 等十进制 / 十六进制),`&` 改为最后还原以避免二次转义。 + ## 2026-11-27 · v3.36(versionCode 57) - 修复信息角标(未读 RSS 数)虚高:服务端 `total / pages` 是跨站去重前口径、越界页会回落为最后一页返回同一批条目,统计改为按 id 去重,并在空页或页号被钳回时立即停止。 diff --git a/src/main/java/com/shitoucuo/postpad/RssApi.kt b/src/main/java/com/shitoucuo/postpad/RssApi.kt index 76b0a6e..5213bd3 100644 --- a/src/main/java/com/shitoucuo/postpad/RssApi.kt +++ b/src/main/java/com/shitoucuo/postpad/RssApi.kt @@ -141,8 +141,8 @@ object RssApi { private val unreadLock = Any() - /** 扫描页数上限:服务端 pages 异常时不要无限请求(100 条/页,足够覆盖上万条) */ - private const val MAX_SCAN_PAGES = 30 + /** 扫描上限按「条数」而不是「页数」:每页条数是用户可配的,按页数卡会算不准 */ + private const val MAX_SCAN_ITEMS = 1200 /** 统计结果复用窗口:本地已读变更会即时调整缓存值,这里只防抖动, * 不能设长——设成 10 分钟时,缓存里残留的旧数字会一直挂在角标上。 */ @@ -166,18 +166,24 @@ object RssApi { var page = 1 var pages = 1 var unread = 0 + var scanned = 0 + /* 每页条数必须与列表一致。服务端 getFeeds() 是「按窗口取行 → 去重 → 切片分页」, + page_size 不同,窗口大小(needRows*3+30)与切片边界都不同, + 同一批条目在两套分页里会落在不同页上——统计看得到、列表翻不到, + 就成了「文章全读完、角标还挂着 3 条」。同参扫描才能保证两边逐页对齐。 */ + val pageSize = prefs.rssPageSize /* 服务端的 total / pages 是「跨站去重前」的口径,比列表实际能翻到的条数略大 (见 RssUnion Front::getFeeds 的注释)。页码越界时它会把 page 回落成最后一页, - 于是同一批条目会被第二次、第三次返回——不去重就会把同一篇未读重复累加, - 用户把文章全读完、角标却还挂着数字,正是这么来的。 */ + 于是同一批条目会被第二次、第三次返回——不去重就会把同一篇未读重复累加。 */ val seenIds = HashSet() - while (page <= pages && page <= MAX_SCAN_PAGES) { - val result = items(prefs, page, pageSize = 100) + while (page <= pages && scanned < MAX_SCAN_ITEMS) { + val result = items(prefs, page, pageSize = pageSize) pages = result.pages // 空页:没有更多数据可扫 if (result.items.isEmpty()) break // 服务端把越界页钳回了别的页号(返回的 page 与请求不一致):已经到底,再翻就是重复 if (result.page != page) break + scanned += result.items.size result.items.forEach { item -> // 同一 id 只算一次,防止服务端重复返回时重复计数 if (!seenIds.add(item.id)) return@forEach @@ -219,22 +225,216 @@ object RssApi { */ suspend fun article(link: String): Article = withContext(Dispatchers.IO) { if (!link.startsWith("http", true)) return@withContext Article("") - val request = Request.Builder() - .url(link) - .header("User-Agent", "Mozilla/5.0 (Linux; Android) AppleWebKit/537.36 PostPad") - .header("Accept", "text/html,application/xhtml+xml") - .build() - val html = client.newCall(request).execute().use { response -> - if (!response.isSuccessful) throw ApiException("原文返回 HTTP ${response.code}") - val body = response.body?.string().orEmpty() - if (body.length > 1_500_000) body.substring(0, 1_500_000) else body + val html = fetchPage(link) + /* 纯前端渲染的站点(Vue / React 单页应用)HTML 里只有一个挂载点 + `
`,正文由 JS 在浏览器里拼出来,直接抓 HTML 永远是空壳。 + 这类站点通常仍开放 /feed/,而 content:encoded 里就是全文—— + 从自家 RSS 取是站点公开提供的渠道,不用碰它的接口签名。 */ + if (isSpaShell(html)) { + val full = feedFullText(link) + if (full.isNotBlank()) return@withContext Article(full) } val author = extractAuthor(html) val main = selectMainContent(html) val markdown = pruneNoiseLines(htmlToMarkdown(flexPhotoTokens(pruneNoiseBlocks(main)))) + // 正文短得不像文章(空壳站、或正文容器没被认出来):再试一次 feed 全文 + if (markdown.length < 80) { + val full = feedFullText(link) + if (full.isNotBlank()) return@withContext Article(full, author) + } Article(markdown, author) } + private fun fetchPage(url: String): String { + val request = Request.Builder() + .url(url) + .header("User-Agent", "Mozilla/5.0 (Linux; Android) AppleWebKit/537.36 PostPad") + .header("Accept", "text/html,application/xhtml+xml") + .build() + return client.newCall(request).execute().use { response -> + if (!response.isSuccessful) throw ApiException("原文返回 HTTP ${response.code}") + val body = response.body?.string().orEmpty() + if (body.length > 1_500_000) body.substring(0, 1_500_000) else body + } + } + + // ==================== SPA 站点:从站点自家 RSS 取全文 ==================== + + /** 单页应用的挂载点。`id="app"` 是最常见的一种,Nuxt / Next 分别用 __nuxt / __next */ + private val SPA_MOUNT = Regex( + "<(?:div|main|section|body)[^>]+id=[\"'](?:app|root|__nuxt|__next)[\"']", + RegexOption.IGNORE_CASE, + ) + + /** + * 判断是不是「只有壳、没有正文」的页面。 + * + * 有挂载点且去掉标签后几乎没字,就是空壳;另外正文短于 200 字也按空壳处理 + * (有些站点挂载点 id 不叫 app,但同样什么都不给)。 + */ + private fun isSpaShell(html: String): Boolean { + if (html.isBlank()) return true + val textLen = stripTags(html).trim().length + if (SPA_MOUNT.containsMatchIn(html) && textLen < 600) return true + return textLen < 200 + } + + /** feed 索引:同一站点一次点开只翻一次页,之后命中缓存 */ + private val feedIndex = object : LinkedHashMap>(4, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry>?): Boolean = + size > 4 + } + + private var feedIndexAt = 0L + + private data class FeedEntry(val link: String, val guid: String, val full: String, val author: String) + + /** feed 最多翻几页(每页通常 10 条):再老的文章就放弃,交给摘要兜底 */ + private const val FEED_MAX_PAGES = 12 + + private const val FEED_TTL_MS = 10 * 60_000L + + /** + * 从站点 feed 里找这篇的全文。 + * + * 定位顺序:先按文章 id 匹配 `link`(`/post/2485/`)或 `guid`(`?p=2485`), + * 再按规范化后的链接整体相等兜底。命中即返回,已拉到的条目留在缓存里, + * 下次点同一站点的另一篇直接从缓存找。 + */ + private fun feedFullText(link: String): String { + val origin = originOf(link) ?: return "" + val id = postIdOf(link) + synchronized(feedIndex) { + if (System.currentTimeMillis() - feedIndexAt < FEED_TTL_MS) { + feedIndex[origin]?.let { list -> + matchFeedEntry(list, id, link)?.let { return feedEntryToMarkdown(it.full) } + } + } + } + val collected = ArrayList() + for (p in 1..FEED_MAX_PAGES) { + val url = if (p == 1) "$origin/feed/" else "$origin/feed/?paged=$p" + val xml = runCatching { fetchFeed(url) }.getOrNull() ?: break + val page = parseFeedItems(xml) + if (page.isEmpty()) break + collected.addAll(page) + val hit = matchFeedEntry(page, id, link) + if (hit != null) { + synchronized(feedIndex) { + feedIndex[origin] = collected + feedIndexAt = System.currentTimeMillis() + } + return feedEntryToMarkdown(hit.full) + } + } + if (collected.isNotEmpty()) { + synchronized(feedIndex) { + feedIndex[origin] = collected + feedIndexAt = System.currentTimeMillis() + } + } + return "" + } + + private fun fetchFeed(url: String): String { + val request = Request.Builder() + .url(url) + .header("User-Agent", UA_BROWSER) + .header("Accept", "application/rss+xml,application/xml;q=0.9,text/xml;q=0.8,*/*;q=0.5") + .build() + return client.newCall(request).execute().use { response -> + if (!response.isSuccessful) throw ApiException("feed 返回 HTTP ${response.code}") + val body = response.body?.string().orEmpty() + // feed 整页几百 KB,取前 1.2MB 足够覆盖十几条全文 + if (body.length > 1_200_000) body.substring(0, 1_200_000) else body + } + } + + private fun matchFeedEntry(list: List, id: String, link: String): FeedEntry? { + for (e in list) { + if (id.isNotEmpty() && + (e.link.contains("/$id/") || e.link.endsWith("/$id") || e.guid.contains("p=$id")) + ) { + return e + } + } + return list.firstOrNull { sameUrl(it.link, link) } + } + + /** 去掉协议、`www.`、末尾斜杠与查询串后比较,避免 http/https、有无斜杠造成的不相等 */ + private fun sameUrl(a: String, b: String): Boolean = normalizeUrl(a) == normalizeUrl(b) + + private fun normalizeUrl(raw: String): String = raw.trim() + .substringBefore('#') + .removePrefix("https://").removePrefix("http://") + .removePrefix("www.") + .removeSuffix("/") + .lowercase() + + private fun originOf(link: String): String? = runCatching { + val u = java.net.URI(link) + if (u.host.isNullOrBlank()) null else "${u.scheme}://${u.host}" + }.getOrNull() + + /** 从 URL 里取文章 id:`/post/2485/`、`/archives/2485.html`、`?p=2485` 都认 */ + private fun postIdOf(link: String): String = + Regex("(?:/post/|/p/|/archives/|/article/)(\\d+)", RegexOption.IGNORE_CASE) + .find(link)?.groupValues?.get(1) + ?: Regex("[?&]p=(\\d+)").find(link)?.groupValues?.get(1) + ?: "" + + private fun parseFeedItems(xml: String): List { + if (!xml.contains("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE) + .findAll(xml) + .mapNotNull { m -> + val raw = m.groupValues[1] + val link = feedTag(raw, "link").ifBlank { + Regex("]+href=[\"']([^\"']+)[\"']", RegexOption.IGNORE_CASE) + .find(raw)?.groupValues?.get(1).orEmpty() + } + // content:encoded 是全文,description 多半只有摘要,两者都取不到就跳过 + val full = feedTag(raw, "content:encoded").ifBlank { feedTag(raw, "description") } + if (full.isBlank()) return@mapNotNull null + FeedEntry( + link = link.trim(), + guid = feedTag(raw, "guid"), + full = full, + author = feedTag(raw, "dc:creator").ifBlank { feedTag(raw, "author") }, + ) + } + .toList() + } + + private fun feedTag(xml: String, name: String): String { + val re = Regex( + "<${Regex.escape(name)}\\b[^>]*>([\\s\\S]*?)", + RegexOption.IGNORE_CASE, + ) + var v = re.find(xml)?.groupValues?.get(1)?.trim() ?: return "" + if (v.startsWith("")) v = v.removeSuffix("]]>") + return v.trim() + } + + /** + * feed 条目正文 → Markdown。 + * + * 有的站点在 content:encoded 里放渲染好的 HTML,有的直接放 Markdown 原文 + * (自己写的博客很常见)。标签多按 HTML 转,标签几乎没有就按 Markdown 清理, + * 否则 `#`、`|`、`**` 这些符号会被当成普通文字再转一遍。 + */ + private fun feedEntryToMarkdown(content: String): String { + val unescaped = unescape(content) + if (unescaped.isBlank()) return "" + val tagCount = Regex("<[a-zA-Z][^>]*>").findAll(unescaped).count() + return if (tagCount >= 5) { + pruneNoiseLines(htmlToMarkdown(flexPhotoTokens(pruneNoiseBlocks(unescaped)))) + } else { + pruneNoiseLines(tidyMarkdown(unescaped)) + } + } + /** 原文正文与作者 */ data class Article(val markdown: String, val author: String = "") @@ -825,19 +1025,34 @@ object RssApi { } /** 常见实体还原:正文里露出 & /   之类的原始写法很难看 */ - private fun unescape(s: String): String = s - .replace(" ", " ") - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - .replace(""", "\"") - .replace("'", "'") - .replace("'", "'") - .replace("—", "—") - .replace("–", "–") - .replace("“", "“") - .replace("”", "”") - .replace("…", "…") + private fun unescape(s: String): String { + var out = s + .replace(" ", " ") + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace("'", "'") + .replace("—", "—") + .replace("–", "–") + .replace("“", "“") + .replace("”", "”") + .replace("‘", "‘") + .replace("’", "’") + .replace("…", "…") + .replace("·", "·") + // 数字实体:feed 标题里常见 `–`(短破折号)、`“`(引号) + out = Regex("&#(\\d{1,7});").replace(out) { m -> + val cp = m.groupValues[1].toIntOrNull() + if (cp != null && cp in 1..0x10FFFF) String(Character.toChars(cp)) else m.value + } + out = Regex("&#[xX]([0-9a-fA-F]{1,6});").replace(out) { m -> + val cp = m.groupValues[1].toIntOrNull(16) + if (cp != null && cp in 1..0x10FFFF) String(Character.toChars(cp)) else m.value + } + // & 放最后:先换会把 `&lt;` 变成 `<` 后再被还原一次 + return out.replace("&", "&") + } private fun stripTags(s: String): String = s.replace(Regex("<[^>]*>"), "") }