411 lines
18 KiB
Kotlin
411 lines
18 KiB
Kotlin
|
|
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<String>,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
data class Category(val id: Long, val name: String, val feedCount: Int)
|
|||
|
|
|
|||
|
|
data class ItemsResult(
|
|||
|
|
val items: List<Item>,
|
|||
|
|
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<Category> = withContext(Dispatchers.IO) {
|
|||
|
|
val json = get(prefs, "obsidianTree")
|
|||
|
|
val array = json.optJSONArray("tree") ?: JSONArray()
|
|||
|
|
val out = ArrayList<Category>(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<String, String>(
|
|||
|
|
"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<Item>(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。
|
|||
|
|
* 站端只给摘要,正文需按 link 拉 HTML;这里做保守的标签转换,
|
|||
|
|
* 保留标题、段落、列表、链接与图片,丢掉脚本与样式。
|
|||
|
|
*/
|
|||
|
|
suspend fun article(link: String): String = withContext(Dispatchers.IO) {
|
|||
|
|
if (!link.startsWith("http", true)) return@withContext ""
|
|||
|
|
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
|
|||
|
|
}
|
|||
|
|
htmlToMarkdown(flexPhotoTokens(pruneNoiseBlocks(extractBody(html)))).let { pruneNoiseLines(it) }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* FlexPhoto(图片横排插件)服务端渲染出的 <div class="flexphoto"> 图组:
|
|||
|
|
* 转 markdown 会打散成竖排图片,这里先换成 token,
|
|||
|
|
* 阅读页遇到 token 再渲染成横排小图(点击放大)。
|
|||
|
|
*/
|
|||
|
|
private fun flexPhotoTokens(html: String): String {
|
|||
|
|
val divRe = Regex(
|
|||
|
|
"<div[^>]*class=\"[^\"]*flexphoto[^\"]*\"[^>]*>[\\s\\S]*?</div>",
|
|||
|
|
RegexOption.IGNORE_CASE,
|
|||
|
|
)
|
|||
|
|
val imgRe = Regex("<img\\b[^>]*>", RegexOption.IGNORE_CASE)
|
|||
|
|
val srcRe = Regex("\\b(?:data-src|src)\\s*=\\s*['\"]([^'\"]+)['\"]", RegexOption.IGNORE_CASE)
|
|||
|
|
return divRe.replace(html) { m ->
|
|||
|
|
val urls = imgRe.findAll(m.value).mapNotNull { img ->
|
|||
|
|
srcRe.find(img.value)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() }
|
|||
|
|
}.toList()
|
|||
|
|
if (urls.isEmpty()) m.value
|
|||
|
|
else "\n%%FLEXP%%\n" + urls.joinToString("\n") + "\n%%/FLEXP%%\n"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun endpoint(prefs: Prefs, action: String, params: Map<String, String>): String {
|
|||
|
|
val query = StringBuilder()
|
|||
|
|
.append("do=").append(action)
|
|||
|
|
.append("&code=").append(java.net.URLEncoder.encode(prefs.rssCode, "UTF-8"))
|
|||
|
|
params.forEach { (k, v) ->
|
|||
|
|
if (v.isNotEmpty()) query.append('&').append(k).append('=')
|
|||
|
|
.append(java.net.URLEncoder.encode(v, "UTF-8"))
|
|||
|
|
}
|
|||
|
|
return "${prefs.rssSite}/action/rssunion?$query"
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun get(prefs: Prefs, action: String, params: Map<String, String> = emptyMap()): JSONObject {
|
|||
|
|
if (!prefs.rssReady) throw ApiException("先填 RSS 站点地址和授权码")
|
|||
|
|
val request = Request.Builder()
|
|||
|
|
.url(endpoint(prefs, action, params))
|
|||
|
|
.header("Accept", "application/json")
|
|||
|
|
.header("User-Agent", UA_BROWSER)
|
|||
|
|
.build()
|
|||
|
|
val text = client.newCall(request).execute().use { response ->
|
|||
|
|
val body = response.body?.string().orEmpty()
|
|||
|
|
if (!response.isSuccessful) {
|
|||
|
|
throw ApiException("站点返回 HTTP ${response.code}:${brief(body)}")
|
|||
|
|
}
|
|||
|
|
body
|
|||
|
|
}
|
|||
|
|
val json = try {
|
|||
|
|
JSONObject(text.trim())
|
|||
|
|
} catch (e: Exception) {
|
|||
|
|
throw ApiException("站点返回的不是 JSON:${brief(text)}")
|
|||
|
|
}
|
|||
|
|
if (!json.optBoolean("success", false)) {
|
|||
|
|
throw ApiException(json.optString("message").ifBlank { "接口返回失败" })
|
|||
|
|
}
|
|||
|
|
return json
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun brief(text: String): String = text
|
|||
|
|
.replace(Regex("<[^>]*>"), " ")
|
|||
|
|
.replace(Regex("\\s+"), " ")
|
|||
|
|
.trim()
|
|||
|
|
.take(120)
|
|||
|
|
.ifEmpty { "空响应" }
|
|||
|
|
|
|||
|
|
/** tags 可能是字符串数组,也可能是 [{id,name,slug}] */
|
|||
|
|
private fun stringList(value: Any?): List<String> {
|
|||
|
|
val array = value as? JSONArray ?: return emptyList()
|
|||
|
|
val out = ArrayList<String>(array.length())
|
|||
|
|
for (i in 0 until array.length()) {
|
|||
|
|
val v = array.opt(i)
|
|||
|
|
val name = when (v) {
|
|||
|
|
is String -> v
|
|||
|
|
is JSONObject -> v.optString("name").ifBlank { v.optString("tag") }
|
|||
|
|
else -> ""
|
|||
|
|
}.trim().trimStart('#')
|
|||
|
|
if (name.isNotEmpty() && name !in out) out.add(name)
|
|||
|
|
}
|
|||
|
|
return out
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun cleanExcerpt(raw: String): String = raw
|
|||
|
|
.replace(Regex("<script[\\s\\S]*?</script>", RegexOption.IGNORE_CASE), " ")
|
|||
|
|
.replace(Regex("<style[\\s\\S]*?</style>", RegexOption.IGNORE_CASE), " ")
|
|||
|
|
.replace(Regex("<[^>]*>"), " ")
|
|||
|
|
.replace(Regex("\\s+"), " ")
|
|||
|
|
.trim()
|
|||
|
|
.take(300)
|
|||
|
|
|
|||
|
|
/** 优先取 article / main,退而求其次取 body */
|
|||
|
|
private fun extractBody(html: String): String {
|
|||
|
|
for (tag in listOf("article", "main")) {
|
|||
|
|
val regex = Regex("<$tag[^>]*>([\\s\\S]*?)</$tag>", RegexOption.IGNORE_CASE)
|
|||
|
|
val match = regex.find(html)
|
|||
|
|
if (match != null && match.groupValues[1].length > 200) return match.groupValues[1]
|
|||
|
|
}
|
|||
|
|
val body = Regex("<body[^>]*>([\\s\\S]*?)</body>", RegexOption.IGNORE_CASE).find(html)
|
|||
|
|
return body?.groupValues?.get(1) ?: html
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 阅读页只留正文:按 class / id 关键词整块剔除评论区、相关文章、
|
|||
|
|
* 上一篇下一篇、标签云、分享栏、打赏、版权、作者卡片等噪音区块。
|
|||
|
|
*/
|
|||
|
|
private fun pruneNoiseBlocks(html: String): String {
|
|||
|
|
val keys = listOf(
|
|||
|
|
"comment", "commentlist", "comments-list", "respond", "disqus",
|
|||
|
|
"related", "recommend", "adjacent", "post-nav", "postnav", "postnavigation",
|
|||
|
|
"prev-next", "pagination", "pager", "tag-list", "tagcloud", "post-tags",
|
|||
|
|
"entry-tags", "share", "social", "sidebar", "widget", "breadcrumb", "crumb",
|
|||
|
|
"reward", "donate", "copyright", "entry-footer", "post-footer",
|
|||
|
|
"article-meta", "post-meta", "entry-meta", "about-author", "author-card",
|
|||
|
|
"author-box", "subscribe", "newsletter", "table-of-contents", "toc-box",
|
|||
|
|
"read-more", "post-copyright", "article-tags",
|
|||
|
|
)
|
|||
|
|
var s = html
|
|||
|
|
for (key in keys) {
|
|||
|
|
// 容器 div/section/aside/footer,class 或 id 命中关键词就整块拿掉
|
|||
|
|
s = s.replace(
|
|||
|
|
Regex(
|
|||
|
|
"<(div|section|aside|footer|ul|ol|nav|form|figure)\\b[^>]*" +
|
|||
|
|
"(?:class|id)=\"[^\"]*$key[^\"]*\"[^>]*>[\\s\\S]*?</\\1>",
|
|||
|
|
RegexOption.IGNORE_CASE,
|
|||
|
|
),
|
|||
|
|
"",
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
return s
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** Markdown 层再按行兜底:标签行、上一篇下一篇、版权声明等残留直接过滤 */
|
|||
|
|
private fun pruneNoiseLines(markdown: String): String {
|
|||
|
|
val keys = listOf(
|
|||
|
|
"上一篇", "下一篇", "相关文章", "相关阅读", "相关推荐", "猜你喜欢", "延伸阅读",
|
|||
|
|
"本文链接", "原文链接", "转载请", "版权声明", "版权所有", "All rights reserved",
|
|||
|
|
"Copyright ©", "© 20", "发表评论", "写下你的评论", "暂无评论", "条评论",
|
|||
|
|
"标签:", "标签:", "Tags:", "Keywords:", "关键词:", "分类:", "分类:", "收录于",
|
|||
|
|
"打赏", "赞赏", "扫码", "扫一扫", "分享到", "订阅本站", "关注我们",
|
|||
|
|
"本文由", "作者主页", "阅读次数", "浏览次数", "最后更新", "编辑于",
|
|||
|
|
)
|
|||
|
|
val re = Regex("(?i)(${keys.joinToString("|")})")
|
|||
|
|
return markdown.lines()
|
|||
|
|
.filter { line ->
|
|||
|
|
val t = line.trim()
|
|||
|
|
// 只过滤短行(正文里整段提及"评论"的段落不受影响)
|
|||
|
|
!(t.length < 100 && re.containsMatchIn(t))
|
|||
|
|
}
|
|||
|
|
.joinToString("\n")
|
|||
|
|
.replace(Regex("[ \t]+\n"), "\n")
|
|||
|
|
.replace(Regex("\n{3,}"), "\n\n")
|
|||
|
|
.trim()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 轻量 HTML → Markdown,够阅读用,不追求完整 CommonMark */
|
|||
|
|
private fun htmlToMarkdown(raw: String): String {
|
|||
|
|
var s = raw
|
|||
|
|
s = s.replace(Regex("<script[\\s\\S]*?</script>", RegexOption.IGNORE_CASE), "")
|
|||
|
|
s = s.replace(Regex("<style[\\s\\S]*?</style>", RegexOption.IGNORE_CASE), "")
|
|||
|
|
s = s.replace(Regex("<nav[\\s\\S]*?</nav>", RegexOption.IGNORE_CASE), "")
|
|||
|
|
s = s.replace(Regex("<footer[\\s\\S]*?</footer>", RegexOption.IGNORE_CASE), "")
|
|||
|
|
// 懒加载图片:先取 data-* 里的地址
|
|||
|
|
s = s.replace(
|
|||
|
|
Regex("<img[^>]*?(?:data-src|data-original|data-actualsrc|data-lazy-src)=\"([^\"]+)\"[^>]*?>", RegexOption.IGNORE_CASE),
|
|||
|
|
) { m -> "<img src=\"${m.groupValues[1]}\">" }
|
|||
|
|
for (level in 1..6) {
|
|||
|
|
s = s.replace(
|
|||
|
|
Regex("<h$level[^>]*>([\\s\\S]*?)</h$level>", RegexOption.IGNORE_CASE),
|
|||
|
|
) { m -> "\n\n${"#".repeat(level)} ${stripTags(m.groupValues[1]).trim()}\n\n" }
|
|||
|
|
}
|
|||
|
|
s = s.replace(Regex("<strong[^>]*>([\\s\\S]*?)</strong>", RegexOption.IGNORE_CASE)) { m -> "**${stripTags(m.groupValues[1])}**" }
|
|||
|
|
s = s.replace(Regex("<b[^>]*>([\\s\\S]*?)</b>", RegexOption.IGNORE_CASE)) { m -> "**${stripTags(m.groupValues[1])}**" }
|
|||
|
|
s = s.replace(Regex("<em[^>]*>([\\s\\S]*?)</em>", RegexOption.IGNORE_CASE)) { m -> "*${stripTags(m.groupValues[1])}*" }
|
|||
|
|
s = s.replace(Regex("<a[^>]*href=\"([^\"]+)\"[^>]*>([\\s\\S]*?)</a>", RegexOption.IGNORE_CASE)) { m ->
|
|||
|
|
"[${stripTags(m.groupValues[2]).trim()}](${m.groupValues[1]})"
|
|||
|
|
}
|
|||
|
|
s = s.replace(Regex("<img[^>]*src=\"([^\"]+)\"[^>]*?>", RegexOption.IGNORE_CASE)) { m ->
|
|||
|
|
"\n\n\n\n"
|
|||
|
|
}
|
|||
|
|
s = s.replace(Regex("<li[^>]*>([\\s\\S]*?)</li>", RegexOption.IGNORE_CASE)) { m ->
|
|||
|
|
"\n- ${stripTags(m.groupValues[1]).trim()}"
|
|||
|
|
}
|
|||
|
|
s = s.replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n")
|
|||
|
|
s = s.replace(Regex("</(?:p|div|section|blockquote|ul|ol|pre|h[1-6])>", RegexOption.IGNORE_CASE), "\n\n")
|
|||
|
|
s = stripTags(s)
|
|||
|
|
s = s.replace(" ", " ").replace("&", "&")
|
|||
|
|
.replace("<", "<").replace(">", ">").replace(""", "\"")
|
|||
|
|
// 收拢空行
|
|||
|
|
return s.replace(Regex("\\n{3,}"), "\n\n").trim()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun stripTags(s: String): String = s.replace(Regex("<[^>]*>"), "")
|
|||
|
|
}
|