package com.shitoucuo.postpad
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.TimeUnit
/**
* 站点 RssUnion 插件的只读接口(与 obsidian-rss-union 同一条链路)。
*
* 插件本身不抓 RSS,条目由站点抓好后存在服务端;App 只通过
* {site}/action/rssunion?do=obsidianXxx&code=ruo_xxx 读取。
* 所有响应外层是 { success:true, ... },失败时 success=false + message。
*/
object RssApi {
private val client: OkHttpClient = Http.newWith(20, 60, 60, TimeUnit.SECONDS)
class ApiException(message: String) : Exception(message)
/** 带浏览器特征的 UA:站点 WAF 会拦截 okhttp 默认标识 */
const val UA_BROWSER =
"Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36"
data class Item(
val id: Long,
val title: String,
val link: String,
val excerpt: String,
val siteTitle: String,
val categoryName: String,
val pubDate: String,
val tags: List,
)
data class Category(val id: Long, val name: String, val feedCount: Int)
data class ItemsResult(
val items: List,
val page: Int,
val pages: Int,
val total: Int,
)
/** 连通检查:ping 接口回报版本、用户与订阅站点数 */
suspend fun check(prefs: Prefs): String = withContext(Dispatchers.IO) {
val json = get(prefs, "obsidianPing")
val version = json.optString("apiVersion")
val siteCount = json.optInt("siteCount", -1)
val name = json.optJSONObject("user")?.optString("name").orEmpty()
buildString {
append("连接正常")
if (name.isNotEmpty()) append(",用户 $name")
if (siteCount >= 0) append(",订阅 $siteCount 个站点")
if (version.isNotEmpty()) append("(接口 v$version)")
}
}
/** 订阅范围内的分类树 */
suspend fun categories(prefs: Prefs): List = withContext(Dispatchers.IO) {
val json = get(prefs, "obsidianTree")
val array = json.optJSONArray("tree") ?: JSONArray()
val out = ArrayList(array.length())
for (i in 0 until array.length()) {
val obj = array.optJSONObject(i) ?: continue
val id = obj.optLong("id", 0L)
val name = obj.optString("name")
if (id > 0 && name.isNotEmpty()) {
out.add(Category(id, name, obj.optInt("feedCount", 0)))
}
}
out.sortedByDescending { it.feedCount }
}
/**
* 分页条目。keyword 走服务端匹配;catId / urlId 为 0 表示不过滤。
*
* pageSize 默认用设置里的每页条数;未读统计会显式传 100,把这件只读的活
* 压缩成尽量少的请求(逐个用 20 条去扫,条目多时就是几十次往返)。
*/
suspend fun items(
prefs: Prefs,
page: Int,
keyword: String = "",
catId: Long = 0L,
urlId: Long = 0L,
pageSize: Int = prefs.rssPageSize,
): ItemsResult = withContext(Dispatchers.IO) {
val params = mutableMapOf(
"page" to page.toString(),
"page_size" to pageSize.coerceIn(1, 100).toString(),
)
if (keyword.isNotBlank()) params["keyword"] = keyword.trim()
if (catId > 0) params["cat_id"] = catId.toString()
if (urlId > 0) params["url_id"] = urlId.toString()
val json = get(prefs, "obsidianItems", params)
val array = json.optJSONArray("items") ?: JSONArray()
val out = ArrayList(array.length())
for (i in 0 until array.length()) {
val obj = array.optJSONObject(i) ?: continue
out.add(
Item(
id = obj.optLong("id", 0L),
title = obj.optString("title").ifBlank { "无标题" },
link = obj.optString("link"),
excerpt = cleanExcerpt(obj.optString("excerpt")),
siteTitle = obj.optString("siteTitle"),
categoryName = obj.optString("categoryName"),
pubDate = obj.optString("pubDate").ifBlank { obj.optString("srcPubDate") },
tags = stringList(obj.opt("tags")),
)
)
}
ItemsResult(
items = out,
page = json.optInt("page", page),
pages = json.optInt("pages", 1),
total = json.optInt("total", out.size),
)
}
// ==================== 未读统计(底部菜单角标) ====================
/**
* 未读数缓存。
*
* 「未读 RSS 总数」只能靠把条目 id 全部过一遍才算得准(本地只记已读集合,
* 不知道服务端现在还有哪些条目)。全量扫描要若干次请求,所以结果在内存里
* 复用 [UNREAD_TTL_MS],切页、返回首页都不会反复联网;下拉刷新时传
* force = true 重新统计。
*/
@Volatile
private var unreadCacheAt = 0L
@Volatile
private var unreadCacheValue = -1
private val unreadLock = Any()
/** 扫描页数上限:服务端 pages 异常时不要无限请求(100 条/页,足够覆盖上万条) */
private const val MAX_SCAN_PAGES = 30
private const val UNREAD_TTL_MS = 10 * 60_000L
/**
* 全部 RSS 条目中未读的数量。
*
* 已读集合来自本地(点开即写),条目集合来自服务端,两者相减就是精确值——
* 不像列表里那样只统计已加载的前几十条,翻页不影响这个数字。
*/
suspend fun unreadCount(prefs: Prefs, force: Boolean = false): Int =
withContext(Dispatchers.IO) {
if (!prefs.rssReady) return@withContext 0
if (!force) {
val cached = synchronized(unreadLock) { unreadCacheValue }
if (cached >= 0 && System.currentTimeMillis() - unreadCacheAt < UNREAD_TTL_MS) {
return@withContext cached
}
}
var page = 1
var pages = 1
var unread = 0
while (page <= pages && page <= MAX_SCAN_PAGES) {
val result = items(prefs, page, pageSize = 100)
pages = result.pages
result.items.forEach { item ->
val id = item.id.toString()
// 本地删除过的条目不再计入未读,否则删掉后角标数字还挂着。
// 键与首页一致,都带 "rss:" 前缀(文章的 cid 可能与之同号)
if (!prefs.isRssHidden("rss:$id") && !prefs.isRssRead(id)) unread++
}
page++
}
synchronized(unreadLock) {
unreadCacheValue = unread
unreadCacheAt = System.currentTimeMillis()
}
unread
}
/**
* 本地刚标记了若干条已读 / 未读,把缓存值同步挪一下。
*
* 不这样做的话,角标会先按界面变化减一,下次切页又读回缓存里的旧值跳回去。
* 传 0 之外的值都不必重新扫描;真正准确的数字由下一次强制统计给。
*/
fun adjustUnread(delta: Int) {
if (delta == 0) return
synchronized(unreadLock) {
if (unreadCacheValue >= 0) {
unreadCacheValue = (unreadCacheValue + delta).coerceAtLeast(0)
}
}
}
/**
* 抓取原文并转成简易 Markdown,同时带回作者。
*
* 阅读页只留「标题 / 作者 / 正文」:标题由顶栏显示,作者提到顶栏的 meta 行,
* 正文里的标题重复行、日期、分类、标签、目录、版权、评论、点赞等一律清掉。
* 抓取链路是「挑正文容器 → 整块剔除噪音 → 转 Markdown → 按行兜底」。
*/
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 author = extractAuthor(html)
val main = selectMainContent(html)
val markdown = pruneNoiseLines(htmlToMarkdown(flexPhotoTokens(pruneNoiseBlocks(main))))
Article(markdown, author)
}
/** 原文正文与作者 */
data class Article(val markdown: String, val author: String = "")
/**
* 作者提取:优先结构化数据(meta / JSON-LD),再退到 class="author" 之类。
*
* 阅读页把它放进顶栏的 meta 行,正文里那条「作者:xxx」就不再重复显示。
*/
private fun extractAuthor(html: String): String {
val head = html.take(200_000)
val patterns = listOf(
Regex("]+name=[\"']author[\"'][^>]+content=[\"']([^\"']{1,60})[\"']", RegexOption.IGNORE_CASE),
Regex("]+content=[\"']([^\"']{1,60})[\"'][^>]+name=[\"']author[\"']", RegexOption.IGNORE_CASE),
Regex("]+property=[\"']article:author[\"'][^>]+content=[\"']([^\"']{1,60})[\"']", RegexOption.IGNORE_CASE),
Regex("\"author\"\\s*:\\s*\\{[^{}]*?\"name\"\\s*:\\s*\"([^\"]{1,60})\"", RegexOption.IGNORE_CASE),
Regex("\"author\"\\s*:\\s*\"([^\"]{1,60})\"", RegexOption.IGNORE_CASE),
Regex(
"]+(?:rel=[\"']author[\"']|class=[\"'][^\"']*author[^\"']*[\"'])[^>]*>([\\s\\S]{1,120}?)",
RegexOption.IGNORE_CASE,
),
Regex(
"]+class=[\"'][^\"']*(?:author-name|author)[^\"']*[\"'][^>]*>([\\s\\S]{1,80}?)",
RegexOption.IGNORE_CASE,
),
Regex("(?:作者|撰文|文)\\s*[::]\\s*([^\\s<,,。|·]{1,24})"),
)
for (re in patterns) {
val raw = re.find(head)?.groupValues?.get(1)?.let { stripTags(it) }?.trim().orEmpty()
val name = raw.replace(Regex("\\s+"), " ").trim().trimStart('@')
if (name.isEmpty() || name.length > 30) continue
if (name.startsWith("http", true) || name.contains("://")) continue
return name
}
return ""
}
/**
* 正文容器选择:先认主流主题的正文 class,其次挑文本最长的 article / main。
*
* 直接取第一个 `` 是不行的:不少主题把「评论列表」也写成 ``,
* 或者在 header 里放一条摘要式 article;取「最长」能稳定命中真正的正文。
* 选中正文容器后,页头、页脚、侧栏、目录、标签云、评论、版权在结构上就已经不在里面了。
*/
private fun selectMainContent(html: String): String {
val s = html
.replace(Regex("", RegexOption.IGNORE_CASE), " ")
.replace(Regex("", RegexOption.IGNORE_CASE), "")
s = s.replace(Regex("
| ", RegexOption.IGNORE_CASE), "\u0002> ")
"\u0001> " + inner.trim() + "\u0001"
}
// 懒加载图片:先取 data-* 里的地址
s = s.replace(
Regex("]*?(?:data-src|data-original|data-actualsrc|data-lazy-src)=[\"']([^\"']+)[\"'][^>]*?>", RegexOption.IGNORE_CASE),
) { m -> "" }
// 行内顺序很关键:先把 a / img 落成 markdown,再处理 strong / em,
// 否则 strong 内部的 stripTags 会把刚转好的链接啃成纯文字
s = s.replace(Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE)) { m ->
val t = unescape(stripTags(m.groupValues[1]))
if (t.isBlank()) "" else "`$t`"
}
s = s.replace(Regex("]*href=[\"']([^\"']+)[\"'][^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE)) { m ->
val text = unescape(stripTags(m.groupValues[2])).trim()
if (text.isEmpty()) "" else "[$text](${m.groupValues[1].trim()})"
}
s = s.replace(Regex("]*src=[\"']([^\"']+)[\"'][^>]*?>", RegexOption.IGNORE_CASE)) { m ->
val alt = unescape(attrValue(m.value, "alt")).replace(Regex("\\s+"), " ").trim()
"\u0001\u0001"
}
s = s.replace(Regex("<(strong|b)\\b[^>]*>([\\s\\S]*?)\\1>", RegexOption.IGNORE_CASE)) { m ->
val t = unescape(stripTags(m.groupValues[2])).trim()
if (t.isEmpty()) "" else "**$t**"
}
s = s.replace(Regex("<(em|i)\\b[^>]*>([\\s\\S]*?)\\1>", RegexOption.IGNORE_CASE)) { m ->
val t = unescape(stripTags(m.groupValues[2])).trim()
if (t.isEmpty()) "" else "*$t*"
}
for (level in 1..6) {
s = s.replace(
Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE),
) { m -> "\u0001${"#".repeat(level)} ${unescape(stripTags(m.groupValues[1])).trim()}\u0001" }
}
// 表格整块转成 markdown 表:留到最后处理只会被打散成一行行文字
val tables = mutableListOf()
s = Regex("
]*>([\\s\\S]*?)
", RegexOption.IGNORE_CASE).replace(s) { m ->
val md = tableToMarkdown(m.groupValues[1])
if (md.isBlank()) "" else {
tables.add(md)
"\u0001\u0000T${tables.size - 1}\u0000\u0001"
}
}
// 有序列表整块编号,否则只能统一成无序项
s = Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE).replace(s) { m ->
var i = 0
val body = Regex("