v3.38:阅读页更多菜单、作者主页与标签浏览、AI 摘要卡片

This commit is contained in:
XIGE
2026-11-27 09:01:56 +08:00
parent 4a21ac8df6
commit 1e6108e690
13 changed files with 1196 additions and 97 deletions

View File

@@ -37,6 +37,12 @@
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".ArticleListActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".MailDetailActivity"
android:configChanges="orientation|screenSize|keyboardHidden"

View File

@@ -11,7 +11,7 @@ import org.json.JSONObject
import java.util.concurrent.TimeUnit
/**
* 润色 / 完善用的 AI 调用。
* 润色 / 完善 / 摘要用的 AI 调用。
*
* 走的是 AIAssist 插件同一家的对话接口(DeepSeek / 智谱),请求体就是标准的
* OpenAI 兼容格式:{model, messages[], stream:false}。
@@ -30,6 +30,9 @@ object AiApi {
/** 单次提交的字数上限:再长模型容易把结尾截掉,不如按住提示用户分段 */
const val MAX_INPUT = 12000
/** 摘要只需要看懂主旨,正文太长反而拖慢并抬高费用,取开头这么多字足够 */
private const val BRIEF_INPUT = 4500
private val JSON = "application/json; charset=utf-8".toMediaType()
/** AI 生成慢,读超时给足;发布与上传用的是另外的 client */
@@ -54,6 +57,20 @@ object AiApi {
"必须完整保留 Markdown 语法与图片 ![说明](地址) 的写法、地址和位置,图片一行都不能丢。" +
"保留第一人称与作者语气。只输出完整正文,不要任何解释、前言或后缀。"
/** 阅读页摘要:一段话概括 + 几个标签,一次性生成 */
private const val BRIEF_PROMPT =
"你是中文内容编辑,为文章写摘要并打标签。要求:\n" +
"1. summary:2 到 4 句、80 到 140 个字,客观概括文章讲了什么、核心观点或结论。" +
"直接陈述内容,不要用「本文」「这篇文章」开头,不要评价好坏,不要编造原文没有的信息。" +
"纯文本,不要 Markdown 标记。\n" +
"2. tags:3 到 5 个主题标签,每个 2 到 6 个字,体现文章的领域和主题;" +
"不要空泛词(文章、其他、综合、杂谈),不要带 # 号,不要重复。\n" +
"只输出一个 JSON 对象,格式:{\"summary\":\"……\",\"tags\":[\"……\",\"……\"]}," +
"不要代码块标记,不要任何解释。"
/** 摘要 + 标签 */
data class Brief(val summary: String, val tags: List<String>)
/**
* 执行一次改写。
*
@@ -62,86 +79,152 @@ object AiApi {
* @return 改写后的全文
*/
suspend fun run(prefs: Prefs, text: String, mode: String): String =
withContext(Dispatchers.IO) {
val key = prefs.aiKey
if (key.isEmpty()) {
throw ApiException("还没填 AI Key,先到设置里填一下")
}
chat(
prefs = prefs,
system = if (mode == MODE_POLISH) POLISH_PROMPT else EXPAND_PROMPT,
user = text,
// 校对要稳定,扩写允许一点发挥
temperature = if (mode == MODE_POLISH) 0.2 else 0.7,
maxTokens = 8192,
)
val provider = prefs.aiProvider
val endpoint: String
val defaultModel: String
when (provider) {
PROVIDER_ZHIPU -> {
endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
defaultModel = "glm-4-flash"
}
else -> {
endpoint = "https://api.deepseek.com/chat/completions"
defaultModel = "deepseek-chat"
}
}
val model = prefs.aiModel.ifEmpty { defaultModel }
/**
* 生成阅读页的 AI 摘要与标签。
*
* 调用方负责兜底:没配 Key、超时、模型返回垃圾都不能影响正文阅读,
* 所以这里只抛异常,由界面决定「静默不显示」还是提示。
*/
suspend fun brief(prefs: Prefs, title: String, body: String): Brief {
val plain = body
// 阅读页会把图片换成 %%IMG%% / %%FLEXP%% token,摘要里不需要地址
.replace(Regex("%%(?:IMG|FLEXP)%%[\\s\\S]*?%%/(?:IMG|FLEXP)%%"), " ")
.replace(Regex("!\\[[^\\]]*\\]\\([^)]*\\)"), "")
.replace(Regex("<[^>]*>"), " ")
.replace(Regex("\\s+"), " ")
.trim()
if (plain.length < 120) throw ApiException("正文太短,不需要摘要")
val input = buildString {
if (title.isNotBlank()) append("标题:").append(title.trim()).append('\n')
append("正文:").append(plain.take(BRIEF_INPUT))
}
val raw = chat(prefs, BRIEF_PROMPT, input, temperature = 0.3, maxTokens = 800)
return parseBrief(raw)
}
val messages = JSONArray().apply {
put(JSONObject().apply {
put("role", "system")
put("content", if (mode == MODE_POLISH) POLISH_PROMPT else EXPAND_PROMPT)
})
put(JSONObject().apply {
put("role", "user")
put("content", text)
})
}
val payload = JSONObject().apply {
put("model", model)
put("messages", messages)
put("stream", false)
// 校对要稳定,扩写允许一点发挥
put("temperature", if (mode == MODE_POLISH) 0.2 else 0.7)
put("max_tokens", 8192)
}
val request = Request.Builder()
.url(endpoint)
.header("Authorization", "Bearer $key")
.header("Accept", "application/json")
.post(payload.toString().toRequestBody(JSON))
.build()
client.newCall(request).execute().use { response ->
val body = response.body?.string().orEmpty()
if (!response.isSuccessful) {
throw ApiException(friendlyMessage(response.code, body), response.code)
}
val json = try {
JSONObject(body)
} catch (e: Exception) {
throw ApiException("AI 返回的不是 JSON,稍后再试")
}
val content = json.optJSONArray("choices")
?.optJSONObject(0)
?.optJSONObject("message")
?.optString("content")
.orEmpty()
/** 解析模型返回的 JSON:模型偶尔爱套 ```json 围栏或加前言,这里只截第一个 { 到最后一个 } */
private fun parseBrief(raw: String): Brief {
val start = raw.indexOf('{')
val end = raw.lastIndexOf('}')
if (start < 0 || end <= start) throw ApiException("AI 没有按要求返回摘要")
val json = try {
JSONObject(raw.substring(start, end + 1))
} catch (e: Exception) {
throw ApiException("AI 返回的摘要格式不对,稍后再试")
}
val summary = json.optString("summary").trim()
if (summary.isEmpty()) throw ApiException("AI 没有返回摘要内容")
val tags = ArrayList<String>()
val array = json.optJSONArray("tags")
if (array != null) {
for (i in 0 until array.length()) {
val tag = array.optString(i)
.replace("#", "")
.replace(Regex("\\s+"), " ")
.trim()
if (content.isEmpty()) {
val finish = json.optJSONArray("choices")
?.optJSONObject(0)
?.optString("finish_reason")
.orEmpty()
throw ApiException(
if (finish == "length") "内容太长,AI 输出被截断了,试着分段处理"
else "AI 没有返回内容,稍后再试"
)
}
content
if (tag.isEmpty() || tag.length > 12) continue
if (tags.none { it.equals(tag, true) }) tags.add(tag)
if (tags.size >= 6) break
}
}
return Brief(summary, tags)
}
/** 统一的 chat/completions 调用:选服务商、拼消息、取 choices[0].message.content */
private suspend fun chat(
prefs: Prefs,
system: String,
user: String,
temperature: Double,
maxTokens: Int,
): String = withContext(Dispatchers.IO) {
val key = prefs.aiKey
if (key.isEmpty()) {
throw ApiException("还没填 AI Key,先到设置里填一下")
}
val provider = prefs.aiProvider
val endpoint: String
val defaultModel: String
when (provider) {
PROVIDER_ZHIPU -> {
endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
defaultModel = "glm-4-flash"
}
else -> {
endpoint = "https://api.deepseek.com/chat/completions"
defaultModel = "deepseek-chat"
}
}
val model = prefs.aiModel.ifEmpty { defaultModel }
val messages = JSONArray().apply {
put(JSONObject().apply {
put("role", "system")
put("content", system)
})
put(JSONObject().apply {
put("role", "user")
put("content", user)
})
}
val payload = JSONObject().apply {
put("model", model)
put("messages", messages)
put("stream", false)
put("temperature", temperature)
put("max_tokens", maxTokens)
}
val request = Request.Builder()
.url(endpoint)
.header("Authorization", "Bearer $key")
.header("Accept", "application/json")
.post(payload.toString().toRequestBody(JSON))
.build()
client.newCall(request).execute().use { response ->
val body = response.body?.string().orEmpty()
if (!response.isSuccessful) {
throw ApiException(friendlyMessage(response.code, body), response.code)
}
val json = try {
JSONObject(body)
} catch (e: Exception) {
throw ApiException("AI 返回的不是 JSON,稍后再试")
}
val content = json.optJSONArray("choices")
?.optJSONObject(0)
?.optJSONObject("message")
?.optString("content")
.orEmpty()
.trim()
if (content.isEmpty()) {
val finish = json.optJSONArray("choices")
?.optJSONObject(0)
?.optString("finish_reason")
.orEmpty()
throw ApiException(
if (finish == "length") "内容太长,AI 输出被截断了,试着分段处理"
else "AI 没有返回内容,稍后再试"
)
}
content
}
}
private fun friendlyMessage(code: Int, body: String): String {
val detail = try {

File diff suppressed because it is too large Load Diff

View File

@@ -59,6 +59,15 @@ data class FeedItem(
*/
val account: String = "",
val accountLabel: String = "",
/**
* RSS 条目自带的标签与来源站点信息。
*
* 列表本身不显示它们,但要透传给阅读页:条目标签是 AI 摘要失败时的兜底,
* urlId / siteUrl 供「作者主页」按站点过滤并打开网站首页。
*/
val tags: List<String> = emptyList(),
val urlId: Long = 0L,
val siteUrl: String = "",
)
class FeedAdapter(

View File

@@ -900,6 +900,9 @@ class HomeActivity : AppCompatActivity() {
link = item.link,
read = prefs.isRssRead(item.id.toString()),
content = item.excerpt,
tags = item.tags,
urlId = item.urlId,
siteUrl = item.siteUrl,
)
} to memoHasMore
}
@@ -1052,7 +1055,8 @@ class HomeActivity : AppCompatActivity() {
FeedItem(TAB_RSS, item.id.toString(), item.title,
item.siteTitle.ifBlank { item.categoryName },
parseDate(item.pubDate), item.excerpt, item.link,
prefs.isRssRead(item.id.toString()), item.excerpt)
prefs.isRssRead(item.id.toString()), item.excerpt,
tags = item.tags, urlId = item.urlId, siteUrl = item.siteUrl)
}
}
TAB_ARTICLE -> {
@@ -1136,7 +1140,8 @@ class HomeActivity : AppCompatActivity() {
if (markLocalRead(item)) RssApi.adjustUnread(-1)
ReaderActivity.open(
this, ReaderActivity.KIND_RSS, item.id, item.title,
item.source, item.date, item.content, item.link
item.source, item.date, item.content, item.link,
item.tags, item.urlId, item.siteUrl,
)
}
}

View File

@@ -475,6 +475,62 @@ class Prefs(context: Context) {
val aiReady: Boolean
get() = aiKey.isNotEmpty()
// ==================== AI 摘要缓存 ====================
/**
* 阅读页摘要 / 标签的本地缓存。
*
* 摘要对同一篇文章不会变,没必要每次点进来都花一次调用(还耗用户额度)。
* 存在单独一份 SharedPreferences 里:条目上限 [BRIEF_MAX],超出就按写入时间
* 淘汰最旧的一条,避免长期使用后文件无限膨胀。
*/
private val briefSp = appContext.getSharedPreferences("postpad_ai_brief", Context.MODE_PRIVATE)
private val briefLock = Any()
/** 读缓存;没有则返回 null(不是空对象,调用方据此决定要不要请求) */
fun getBrief(key: String): AiApi.Brief? {
if (key.isBlank()) return null
val obj = synchronized(briefLock) { briefRoot().optJSONObject(key) } ?: return null
val summary = obj.optString("s").trim()
if (summary.isEmpty()) return null
val tags = ArrayList<String>()
obj.optJSONArray("t")?.let { array ->
for (i in 0 until array.length()) {
val tag = array.optString(i).trim()
if (tag.isNotEmpty()) tags.add(tag)
}
}
return AiApi.Brief(summary, tags)
}
/** 写缓存,顺带裁掉超额的旧条目 */
fun putBrief(key: String, brief: AiApi.Brief) {
if (key.isBlank() || brief.summary.isBlank()) return
synchronized(briefLock) {
val root = briefRoot()
root.put(
key,
JSONObject().apply {
put("s", brief.summary)
put("t", JSONArray().also { a -> brief.tags.forEach { a.put(it) } })
put("at", System.currentTimeMillis())
},
)
if (root.length() > BRIEF_MAX) {
val keys = root.keys().asSequence()
.sortedBy { root.optJSONObject(it)?.optLong("at", 0L) ?: 0L }
.toList()
keys.take(root.length() - BRIEF_MAX).forEach { root.remove(it) }
}
briefSp.edit().putString(KEY_BRIEF_ITEMS, root.toString()).apply()
}
}
private fun briefRoot(): JSONObject = runCatching {
JSONObject(briefSp.getString(KEY_BRIEF_ITEMS, "").orEmpty())
}.getOrDefault(JSONObject())
/** RSS 已读状态单独存,避免和主配置混在一起 */
private val rssReadSp = appContext.getSharedPreferences("postpad_rss_read", Context.MODE_PRIVATE)
@@ -569,6 +625,10 @@ class Prefs(context: Context) {
private const val KEY_AI_PROVIDER = "ai_provider"
private const val KEY_AI_KEY = "ai_key"
private const val KEY_AI_MODEL = "ai_model"
/** AI 摘要缓存:全部条目存在这一个键下(一个 JSON 对象) */
private const val KEY_BRIEF_ITEMS = "brief_items"
/** 摘要缓存条数上限:一篇一条,200 篇足够日常回看,也不会让文件太大 */
private const val BRIEF_MAX = 200
private const val KEY_RSS_SITE = "rss_site"
private const val KEY_RSS_CODE = "rss_code"

File diff suppressed because it is too large Load Diff

View File

@@ -34,6 +34,9 @@ object RssApi {
val categoryName: String,
val pubDate: String,
val tags: List<String>,
/** 订阅站点 id 与站点首页:「作者主页」按它过滤该站文章,并作为「打开网站」的地址 */
val urlId: Long = 0L,
val siteUrl: String = "",
)
data class Category(val id: Long, val name: String, val feedCount: Int)
@@ -112,6 +115,8 @@ object RssApi {
categoryName = obj.optString("categoryName"),
pubDate = obj.optString("pubDate").ifBlank { obj.optString("srcPubDate") },
tags = stringList(obj.opt("tags")),
urlId = obj.optLong("urlId", 0L),
siteUrl = obj.optString("siteUrl"),
)
)
}

View File

@@ -0,0 +1,137 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
作者主页 / 标签浏览共用:顶部一张信息卡(网站名、收录数量),下面是文章列表。
两者数据结构完全一致(都是 RSS 条目),只是过滤条件不同,所以合成一个页面,
避免两份几乎一样的列表代码各自演化。
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
android:fitsSystemWindows="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingStart="14dp"
android:paddingEnd="14dp">
<ImageView
android:id="@+id/btnListBack"
android:layout_width="36dp"
android:layout_height="36dp"
android:contentDescription="@string/back"
android:padding="7dp"
android:src="@drawable/ic_back"
app:tint="@color/text_secondary" />
<TextView
android:id="@+id/tvListLabel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:text="@string/author_page"
android:textColor="@color/text"
android:textSize="15sp" />
<!-- 占位,让标题真正居中 -->
<Space
android:layout_width="36dp"
android:layout_height="36dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="12dp"
android:background="@drawable/bg_card"
android:orientation="vertical"
android:paddingStart="16dp"
android:paddingTop="14dp"
android:paddingEnd="16dp"
android:paddingBottom="14dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/tvSiteName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:maxLines="2"
android:textColor="@color/title"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/btnSiteOpen"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:layout_marginStart="10dp"
android:background="@drawable/bg_brand_soft"
android:gravity="center"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:text="@string/open_site"
android:textColor="@color/brand"
android:textSize="11.5sp"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="@+id/tvSiteMeta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="@color/text_tertiary"
android:textSize="12sp" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvArticles"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingTop="10dp"
android:paddingBottom="20dp"
android:scrollbars="none" />
<ProgressBar
android:id="@+id/listProgress"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:visibility="gone" />
<TextView
android:id="@+id/tvListEmpty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingStart="32dp"
android:paddingEnd="32dp"
android:textColor="@color/text_tertiary"
android:textSize="13sp"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>

View File

@@ -35,11 +35,13 @@
android:textSize="15sp" />
<TextView
android:id="@+id/btnOpenOriginal"
android:id="@+id/btnReaderMore"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:background="?android:attr/selectableItemBackground"
android:gravity="center"
android:text="@string/open_original"
android:minWidth="44dp"
android:text="@string/more"
android:textColor="@color/brand"
android:textSize="13sp" />
</LinearLayout>
@@ -75,6 +77,56 @@
android:textColor="@color/text_tertiary"
android:textSize="12sp" />
<!--
AI 摘要卡:正文之前。生成中、失败、只有标签三种状态都由代码控制,
没配 AI Key 且条目没有标签时整块 GONE,不占位。
-->
<LinearLayout
android:id="@+id/briefCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:background="@drawable/bg_card"
android:orientation="vertical"
android:paddingStart="14dp"
android:paddingTop="12dp"
android:paddingEnd="14dp"
android:paddingBottom="12dp"
android:visibility="gone">
<TextView
android:id="@+id/tvBriefTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ai_summary"
android:textColor="@color/brand"
android:textSize="11.5sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvBriefBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:textColor="@color/text_secondary"
android:textSize="13.5sp" />
<HorizontalScrollView
android:id="@+id/briefTagScroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="9dp"
android:scrollbars="none"
android:visibility="gone">
<LinearLayout
android:id="@+id/briefTags"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" />
</HorizontalScrollView>
</LinearLayout>
<!-- 正文容器:文字段与 FlexPhoto 横排图组动态插入 -->
<LinearLayout
android:id="@+id/bodyContainer"

View File

@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 作者主页 / 标签浏览的文章行:标题、来源与日期、摘要 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowRoot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="12dp"
android:background="@drawable/bg_card"
android:orientation="vertical"
android:paddingStart="14dp"
android:paddingTop="13dp"
android:paddingEnd="14dp"
android:paddingBottom="13dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/tvRowSource"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/brand"
android:textSize="11.5sp" />
<TextView
android:id="@+id/tvRowDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textColor="@color/text_tertiary"
android:textSize="11sp" />
</LinearLayout>
<TextView
android:id="@+id/tvRowTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:ellipsize="end"
android:maxLines="2"
android:textColor="@color/title"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvRowSummary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:maxLines="2"
android:textColor="@color/text_secondary"
android:textSize="12.5sp"
android:visibility="gone" />
</LinearLayout>

View File

@@ -196,4 +196,21 @@
<string name="image_preview_failed">图片加载失败,点击重试</string>
<string name="image_preview_close">关闭</string>
<string name="image_preview_close_glyph" translatable="false">✕</string>
<!-- 阅读页:更多菜单 / 作者主页 / 标签 / AI 摘要 -->
<string name="more">更多</string>
<string name="author_page">作者主页</string>
<string name="tag_page">标签浏览</string>
<string name="open_site">打开网站</string>
<string name="article_loading">正在读取…</string>
<string name="article_count">收录 %1$d 篇文章</string>
<string name="author_site_meta">%1$s</string>
<string name="author_meta_both">%1$s · 收录 %2$d 篇文章</string>
<string name="empty_author_articles">这个站点还没有收录文章</string>
<string name="empty_tag_articles">没有找到带「%1$s」标签的文章</string>
<string name="ai_summary">AI 摘要</string>
<string name="ai_summary_loading">AI 正在读这篇文章…</string>
<string name="ai_summary_failed">摘要没生成出来,点此重试</string>
<string name="ai_summary_failed_reason">%1$s\n点此重试</string>
<string name="article_tags">标签</string>
</resources>