diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cd7ca5..7b78154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # 变更记录 +## 2026-11-27 · v3.38(versionCode 59) + +- 阅读页右上角「查看原文」改为「更多」,点开是下拉菜单:查看原文、作者主页(没有原文链接时该项不出现)。 +- 新增作者主页 `ArticleListActivity`:显示网站名称、作者与收录文章数量,下面是该站文章列表,点任意一条进阅读页;顶部「打开网站」可直接跳浏览器。服务端条目没有 author 字段、接口也没有 author 参数,而个人博客通常一个站点对应一位作者,因此按 `url_id` 过滤。 +- 新增标签浏览:AI 摘要下方的标签可点击,按标签列出相关文章。AI 标签先用服务端关键词搜索匹配(命中标题 / 描述 / 站点名),结果太少时再全量扫一遍按条目自带 `tags` 补齐,两轮按 id 去重。 +- 阅读页正文前新增 AI 摘要卡片:调用已有 AI 接口(DeepSeek / 智谱)生成 2–4 句摘要与 3–5 个标签,JSON 输出带容错解析;摘要按条目缓存(`postpad_ai_brief`,上限 200 条按时间淘汰),失败时卡片退化为标签行、点文字可重试,正文短于 200 字或未配置 Key 时不发起请求。 +- `RssApi.Item` 增加 `urlId` / `siteUrl`,`FeedItem` 透传 `tags` / `urlId` / `siteUrl` 供阅读页使用。 + ## 2026-11-27 · v3.37(versionCode 58) - 修复信息角标与列表口径不一致(列表全读完、角标仍显示 3 条):未读统计改用与列表相同的每页条数。服务端 `getFeeds()` 是「按窗口取行 → 去重 → 切片分页」,`page_size` 一变窗口与切片边界全变,固定 100 条/页会扫到列表翻不到的条目;扫描上限同时改为按条数(1200)控制。 diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml index 5fe56ea..7a6b810 100644 --- a/src/main/AndroidManifest.xml +++ b/src/main/AndroidManifest.xml @@ -37,6 +37,12 @@ android:exported="false" android:screenOrientation="portrait" /> + + ) + /** * 执行一次改写。 * @@ -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() + 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 { diff --git a/src/main/java/com/shitoucuo/postpad/ArticleListActivity.kt b/src/main/java/com/shitoucuo/postpad/ArticleListActivity.kt new file mode 100644 index 0000000..39c9c8d --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/ArticleListActivity.kt @@ -0,0 +1,401 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.ProgressBar +import android.widget.TextView +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.text.SimpleDateFormat +import java.util.Locale + +/** + * 作者主页 / 标签浏览。 + * + * 两种入口是同一件事:按某个条件把 RSS 条目筛出来列一遍。 + * - 作者主页:服务端接口没有 author 参数,但条目带 urlId(订阅站点), + * 而这类"作者主页"几乎都是个人博客(一个站点一位作者),所以按站点过滤, + * 头部显示网站名称与收录数量; + * - 标签浏览:服务端同样没有 tag 参数,只有条目自带 tags 字段, + * 于是逐页拉取后在本地按标签过滤(最多扫几页,边扫边显示)。 + * + * 点任意一条进阅读页,和首页列表的行为一致。 + */ +class ArticleListActivity : AppCompatActivity() { + + companion object { + private const val EXTRA_MODE = "mode" + private const val EXTRA_NAME = "name" + private const val EXTRA_SITE = "site" + private const val EXTRA_SITE_URL = "site_url" + private const val EXTRA_URL_ID = "url_id" + + const val MODE_AUTHOR = "author" + const val MODE_TAG = "tag" + + /** 标签浏览的扫描上限:每页 100 条 × 5 页,够覆盖订阅里较新的内容 */ + private const val TAG_SCAN_PAGES = 5 + private const val TAG_PAGE_SIZE = 100 + + /** 作者主页:作者名 + 网站名 + 站点 id */ + fun openAuthor( + context: Context, + author: String, + siteTitle: String, + siteUrl: String, + urlId: Long, + ) { + context.startActivity( + Intent(context, ArticleListActivity::class.java).apply { + putExtra(EXTRA_MODE, MODE_AUTHOR) + putExtra(EXTRA_NAME, author) + putExtra(EXTRA_SITE, siteTitle) + putExtra(EXTRA_SITE_URL, siteUrl) + putExtra(EXTRA_URL_ID, urlId) + }, + ) + } + + /** 标签浏览 */ + fun openTag(context: Context, tag: String) { + context.startActivity( + Intent(context, ArticleListActivity::class.java).apply { + putExtra(EXTRA_MODE, MODE_TAG) + putExtra(EXTRA_NAME, tag) + }, + ) + } + } + + private lateinit var prefs: Prefs + private lateinit var adapter: RowAdapter + private lateinit var rv: RecyclerView + private lateinit var progress: ProgressBar + private lateinit var empty: TextView + private lateinit var tvSiteName: TextView + private lateinit var tvSiteMeta: TextView + private lateinit var btnSiteOpen: TextView + + private var mode = MODE_AUTHOR + private var name = "" + private var siteTitle = "" + private var siteUrl = "" + private var urlId = 0L + + /** 作者主页分页状态 */ + private var page = 0 + private var pages = 0 + private var loading = false + private var total = 0 + + override fun onCreate(savedInstanceState: Bundle?) { + prefs = Prefs(this) + val target = prefs.nightMode() + if (AppCompatDelegate.getDefaultNightMode() != target) { + AppCompatDelegate.setDefaultNightMode(target) + } + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_article_list) + + mode = intent.getStringExtra(EXTRA_MODE).orEmpty().ifBlank { MODE_AUTHOR } + name = intent.getStringExtra(EXTRA_NAME).orEmpty() + siteTitle = intent.getStringExtra(EXTRA_SITE).orEmpty() + siteUrl = intent.getStringExtra(EXTRA_SITE_URL).orEmpty() + urlId = intent.getLongExtra(EXTRA_URL_ID, 0L) + + rv = findViewById(R.id.rvArticles) + progress = findViewById(R.id.listProgress) + empty = findViewById(R.id.tvListEmpty) + tvSiteName = findViewById(R.id.tvSiteName) + tvSiteMeta = findViewById(R.id.tvSiteMeta) + btnSiteOpen = findViewById(R.id.btnSiteOpen) + findViewById(R.id.btnListBack).setOnClickListener { finish() } + + rv.layoutManager = LinearLayoutManager(this) + adapter = RowAdapter() + rv.adapter = adapter + rv.addOnScrollListener(object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + if (dy <= 0 || mode != MODE_AUTHOR || loading) return + val lm = recyclerView.layoutManager as? LinearLayoutManager ?: return + if (lm.findLastVisibleItemPosition() >= adapter.itemCount - 3) loadMore() + } + }) + + btnSiteOpen.setOnClickListener { + if (siteUrl.isBlank()) return@setOnClickListener + runCatching { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(siteUrl))) + }.onFailure { toast("打不开浏览器") } + } + + setupHeader() + if (mode == MODE_TAG) loadTag() else loadMore() + } + + private fun setupHeader() { + if (mode == MODE_TAG) { + findViewById(R.id.tvListLabel).text = getString(R.string.tag_page) + tvSiteName.text = "#$name" + tvSiteMeta.text = getString(R.string.article_loading) + btnSiteOpen.visibility = View.GONE + } else { + findViewById(R.id.tvListLabel).text = getString(R.string.author_page) + val title = if (name.isNotBlank()) name else siteTitle.ifBlank { getString(R.string.author_page) } + tvSiteName.text = title + tvSiteMeta.text = if (siteTitle.isNotBlank() && siteTitle != title) { + getString(R.string.author_site_meta, siteTitle) + } else { + getString(R.string.article_loading) + } + btnSiteOpen.visibility = if (siteUrl.isBlank()) View.GONE else View.VISIBLE + } + } + + // ==================== 作者主页:按站点分页 ==================== + + private fun loadMore() { + if (loading || mode != MODE_AUTHOR) return + if (page > 0 && page >= pages) return + loading = true + if (adapter.itemCount == 0) progress.visibility = View.VISIBLE + lifecycleScope.launch { + try { + val next = page + 1 + val result = withContext(Dispatchers.IO) { + RssApi.items( + prefs = prefs, + page = next, + // urlId 拿不到时(早期条目)退回按站点名搜索,至少不至于列出全站 + keyword = if (urlId <= 0 && siteTitle.isNotBlank()) siteTitle else "", + urlId = urlId, + ) + } + page = result.page + pages = result.pages + total = result.total + val rows = result.items + .filterNot { prefs.isRssHidden("rss:${it.id}") } + .map { it.toRow() } + adapter.append(rows) + renderCount() + refreshEmpty() + } catch (e: Exception) { + if (adapter.itemCount == 0) { + empty.text = "加载失败:${e.message ?: "未知错误"}" + empty.visibility = View.VISIBLE + } else { + toast("加载失败:${e.message ?: "未知错误"}") + } + } finally { + loading = false + progress.visibility = View.GONE + } + } + } + + private fun renderCount() { + if (mode != MODE_AUTHOR) return + val count = if (total > 0) total else adapter.itemCount + val site = siteTitle.ifBlank { name } + tvSiteMeta.text = if (name.isNotBlank() && site.isNotBlank() && site != name) { + getString(R.string.author_meta_both, site, count) + } else { + getString(R.string.article_count, count) + } + } + + // ==================== 标签浏览:关键词 + 条目标签 ==================== + + /** + * 标签有两类来源,匹配方式不同,所以分两轮: + * + * 1. AI 生成的标签是主题词(不是站点的 tag 字段),只能靠服务端关键词搜索—— + * keyword 命中标题 / 描述 / 网站名,正好覆盖"文章讲的就是这个主题"的情况; + * 2. 条目自带 tags 的,关键词未必出现(正文没提这个词但作者打了标签), + * 所以第一轮结果太少时再全量扫一遍、按 tags 过滤补齐。 + * + * 两轮都按 id 去重;边扫边显示,用户不用等全部扫完才有内容。 + */ + private fun loadTag() { + progress.visibility = View.VISIBLE + lifecycleScope.launch { + val seen = HashSet() + val rows = ArrayList() + + fun publish(hits: List) { + if (hits.isEmpty()) return + val fresh = hits.filter { !prefs.isRssHidden("rss:${it.id}") && seen.add(it.id) } + if (fresh.isEmpty()) return + val mapped = fresh.map { it.toRow() } + rows.addAll(mapped) + adapter.append(mapped) + tvSiteMeta.text = getString(R.string.article_count, rows.size) + } + + try { + // 第一轮:关键词搜索 + var pageNo = 1 + while (pageNo <= TAG_SCAN_PAGES) { + val result = withContext(Dispatchers.IO) { + RssApi.items(prefs, pageNo, keyword = name, pageSize = TAG_PAGE_SIZE) + } + if (result.items.isEmpty()) break + publish(result.items) + if (result.page != pageNo || pageNo >= result.pages) break + pageNo++ + } + // 第二轮:结果太少,按条目自带标签补扫 + if (rows.size < 8) { + pageNo = 1 + while (pageNo <= TAG_SCAN_PAGES) { + val result = withContext(Dispatchers.IO) { + RssApi.items(prefs, pageNo, pageSize = TAG_PAGE_SIZE) + } + if (result.items.isEmpty()) break + publish(result.items.filter { item -> item.tags.any { it.equals(name, true) } }) + if (result.page != pageNo || pageNo >= result.pages) break + pageNo++ + } + } + tvSiteMeta.text = getString(R.string.article_count, rows.size) + refreshEmpty() + } catch (e: Exception) { + if (adapter.itemCount == 0) { + empty.text = "加载失败:${e.message ?: "未知错误"}" + empty.visibility = View.VISIBLE + } else { + toast("扫描中断:${e.message ?: "未知错误"}") + } + } finally { + progress.visibility = View.GONE + } + } + } + + private fun refreshEmpty() { + if (adapter.itemCount > 0) { + empty.visibility = View.GONE + return + } + empty.text = if (mode == MODE_TAG) { + getString(R.string.empty_tag_articles, name) + } else { + getString(R.string.empty_author_articles) + } + empty.visibility = View.VISIBLE + } + + // ==================== 列表 ==================== + + private class Row( + val id: Long, + val title: String, + val link: String, + val source: String, + val date: Long, + val summary: String, + val excerpt: String, + ) + + private fun RssApi.Item.toRow() = Row( + id = id, + title = title, + link = link, + source = siteTitle.ifBlank { categoryName }, + date = parseDate(pubDate), + summary = excerpt, + excerpt = excerpt, + ) + + private inner class RowAdapter : RecyclerView.Adapter() { + private val items = ArrayList() + + fun append(rows: List) { + if (rows.isEmpty()) return + val start = items.size + items.addAll(rows) + notifyItemRangeInserted(start, rows.size) + } + + override fun getItemCount(): Int = items.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.item_article_row, parent, false) + return Holder(view) + } + + override fun onBindViewHolder(holder: Holder, position: Int) { + val row = items[position] + holder.source.text = row.source + holder.date.text = if (row.date > 0) formatDay(row.date) else "" + holder.title.text = row.title + holder.summary.text = row.summary + holder.summary.visibility = if (row.summary.isBlank()) View.GONE else View.VISIBLE + holder.root.setOnClickListener { + // 点开即已读,与首页列表一致 + prefs.setRssRead(row.id.toString(), true) + ReaderActivity.open( + this@ArticleListActivity, + ReaderActivity.KIND_RSS, + row.id.toString(), + row.title, + row.source, + row.date, + row.excerpt, + row.link, + ) + } + } + + inner class Holder(view: View) : RecyclerView.ViewHolder(view) { + val root: View = view.findViewById(R.id.rowRoot) + val source: TextView = view.findViewById(R.id.tvRowSource) + val date: TextView = view.findViewById(R.id.tvRowDate) + val title: TextView = view.findViewById(R.id.tvRowTitle) + val summary: TextView = view.findViewById(R.id.tvRowSummary) + } + } + + private val dateFormats = object : ThreadLocal>() { + override fun initialValue(): List = listOf( + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US), + SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US), + SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US), + SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US), + SimpleDateFormat("yyyy-MM-dd", Locale.US), + ) + } + + private fun parseDate(raw: String): Long { + if (raw.isBlank()) return 0L + for (format in dateFormats.get() ?: emptyList()) { + runCatching { + return format.parse(raw)?.time ?: 0L + } + } + return 0L + } + + private fun formatDay(ts: Long): String = + SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(java.util.Date(ts)) + + private fun toast(text: String) { + if (isFinishing || isDestroyed) return + Toast.makeText(this, text, Toast.LENGTH_SHORT).show() + } +} diff --git a/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt b/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt index 07005df..a0a5ec2 100644 --- a/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt +++ b/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt @@ -59,6 +59,15 @@ data class FeedItem( */ val account: String = "", val accountLabel: String = "", + /** + * RSS 条目自带的标签与来源站点信息。 + * + * 列表本身不显示它们,但要透传给阅读页:条目标签是 AI 摘要失败时的兜底, + * urlId / siteUrl 供「作者主页」按站点过滤并打开网站首页。 + */ + val tags: List = emptyList(), + val urlId: Long = 0L, + val siteUrl: String = "", ) class FeedAdapter( diff --git a/src/main/java/com/shitoucuo/postpad/HomeActivity.kt b/src/main/java/com/shitoucuo/postpad/HomeActivity.kt index ecf84e4..c5c5820 100644 --- a/src/main/java/com/shitoucuo/postpad/HomeActivity.kt +++ b/src/main/java/com/shitoucuo/postpad/HomeActivity.kt @@ -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, ) } } diff --git a/src/main/java/com/shitoucuo/postpad/Prefs.kt b/src/main/java/com/shitoucuo/postpad/Prefs.kt index db2e11b..4e89e61 100644 --- a/src/main/java/com/shitoucuo/postpad/Prefs.kt +++ b/src/main/java/com/shitoucuo/postpad/Prefs.kt @@ -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() + 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" diff --git a/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt b/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt index cb3fe23..15de322 100644 --- a/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt +++ b/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt @@ -11,11 +11,15 @@ import android.os.Bundle import android.app.Dialog import android.text.method.LinkMovementMethod import android.util.LruCache +import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.ViewOutlineProvider +import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.LinearLayout +import android.widget.ListView +import android.widget.PopupWindow import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast @@ -43,7 +47,12 @@ class ReaderActivity : AppCompatActivity() { private lateinit var tvMeta: TextView private lateinit var bodyContainer: LinearLayout private lateinit var progress: ProgressBar - private lateinit var btnOriginal: TextView + private lateinit var btnMore: TextView + private lateinit var briefCard: LinearLayout + private lateinit var tvBriefTitle: TextView + private lateinit var tvBriefBody: TextView + private lateinit var briefTagScroll: View + private lateinit var briefTags: LinearLayout private lateinit var markwon: Markwon private lateinit var imageClient: OkHttpClient @@ -54,6 +63,18 @@ class ReaderActivity : AppCompatActivity() { private var metaAuthor: String = "" private var metaDate: Long = 0L + /** 来源站点信息:作者主页按站点过滤,并用站点首页做「打开网站」 */ + private var siteUrl: String = "" + private var urlId: Long = 0L + + /** 条目自带的标签(服务端就有),AI 没给标签时用它兜底 */ + private var itemTags: List = emptyList() + + /** 摘要缓存键:同类内容 id 可能撞号,所以带 kind 前缀 */ + private var briefKey: String = "" + private var briefRequesting = false + private var briefBody: String = "" + companion object { private const val EXTRA_KIND = "kind" private const val EXTRA_ID = "id" @@ -62,6 +83,12 @@ class ReaderActivity : AppCompatActivity() { private const val EXTRA_DATE = "date" private const val EXTRA_CONTENT = "content" private const val EXTRA_LINK = "link" + private const val EXTRA_TAGS = "tags" + private const val EXTRA_URL_ID = "url_id" + private const val EXTRA_SITE_URL = "site_url" + + /** 正文短于这么多字就不必麻烦 AI 了 */ + private const val BRIEF_MIN_CHARS = 200 const val KIND_RSS = "rss" const val KIND_ARTICLE = "article" @@ -76,6 +103,9 @@ class ReaderActivity : AppCompatActivity() { date: Long, content: String, link: String, + tags: List = emptyList(), + urlId: Long = 0L, + siteUrl: String = "", ) { val intent = Intent(context, ReaderActivity::class.java).apply { putExtra(EXTRA_KIND, kind) @@ -85,6 +115,9 @@ class ReaderActivity : AppCompatActivity() { putExtra(EXTRA_DATE, date) putExtra(EXTRA_CONTENT, content) putExtra(EXTRA_LINK, link) + putStringArrayListExtra(EXTRA_TAGS, ArrayList(tags)) + putExtra(EXTRA_URL_ID, urlId) + putExtra(EXTRA_SITE_URL, siteUrl) } context.startActivity(intent) } @@ -103,7 +136,12 @@ class ReaderActivity : AppCompatActivity() { tvMeta = findViewById(R.id.tvReaderMeta) bodyContainer = findViewById(R.id.bodyContainer) progress = findViewById(R.id.readerProgress) - btnOriginal = findViewById(R.id.btnOpenOriginal) + btnMore = findViewById(R.id.btnReaderMore) + briefCard = findViewById(R.id.briefCard) + tvBriefTitle = findViewById(R.id.tvBriefTitle) + tvBriefBody = findViewById(R.id.tvBriefBody) + briefTagScroll = findViewById(R.id.briefTagScroll) + briefTags = findViewById(R.id.briefTags) imageClient = OkHttpClient.Builder() .connectTimeout(20, java.util.concurrent.TimeUnit.SECONDS) @@ -123,33 +161,29 @@ class ReaderActivity : AppCompatActivity() { val date = intent.getLongExtra(EXTRA_DATE, 0L) val preloaded = intent.getStringExtra(EXTRA_CONTENT).orEmpty() originalUrl = intent.getStringExtra(EXTRA_LINK).orEmpty() + itemTags = intent.getStringArrayListExtra(EXTRA_TAGS).orEmpty().filter { it.isNotBlank() } + urlId = intent.getLongExtra(EXTRA_URL_ID, 0L) + siteUrl = intent.getStringExtra(EXTRA_SITE_URL).orEmpty() + briefKey = if (id.isNotBlank()) "$kind:$id" else "$kind:${originalUrl.hashCode()}" tvTitle.text = title.ifBlank { getString(R.string.reader_untitled) } metaSource = source metaDate = date renderMeta() findViewById(R.id.btnReaderBack).setOnClickListener { finish() } - btnOriginal.setOnClickListener { - if (originalUrl.isBlank()) { - toast("这条内容没有原文链接") - return@setOnClickListener - } - runCatching { - startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(originalUrl))) - }.onFailure { toast("打不开浏览器") } - } + btnMore.setOnClickListener { showMoreMenu(it) } when (kind) { KIND_ARTICLE -> loadArticle(id, preloaded) KIND_RSS -> loadRss(preloaded) - else -> render(preloaded.ifBlank { "(empty)" }) + else -> renderWithBrief(preloaded.ifBlank { "(empty)" }) } } private fun loadArticle(cid: String, preloaded: String) { if (preloaded.isNotBlank()) { - render(preloaded) + renderWithBrief(preloaded) return } progress.visibility = TextView.VISIBLE @@ -160,7 +194,7 @@ class ReaderActivity : AppCompatActivity() { } originalUrl = detail.permalink.ifBlank { originalUrl } tvTitle.text = detail.title - render(detail.markdown.ifBlank { detail.text }) + renderWithBrief(detail.markdown.ifBlank { detail.text }) } catch (e: Exception) { render("读取文章失败:${e.message ?: "未知错误"}") } finally { @@ -171,7 +205,7 @@ class ReaderActivity : AppCompatActivity() { private fun loadRss(excerpt: String) { if (originalUrl.isBlank()) { - render(excerpt.ifBlank { "(这条内容没有正文)" }) + renderWithBrief(excerpt.ifBlank { "(这条内容没有正文)" }) return } progress.visibility = TextView.VISIBLE @@ -184,10 +218,10 @@ class ReaderActivity : AppCompatActivity() { renderMeta() } val body = stripLeadingNoise(article.markdown.ifBlank { excerpt }) - render(body.ifBlank { excerpt.ifBlank { "(原文里没有抓到正文)" } }) + renderWithBrief(body.ifBlank { excerpt.ifBlank { "(原文里没有抓到正文)" } }) } catch (e: Exception) { // 抓不到原文时用站端摘要兜底,至少能读个大概 - render(excerpt.ifNotBlank() ?: "抓取原文失败:${e.message ?: "未知错误"}") + renderWithBrief(excerpt.ifNotBlank() ?: "抓取原文失败:${e.message ?: "未知错误"}") } finally { progress.visibility = TextView.GONE } @@ -216,6 +250,225 @@ class ReaderActivity : AppCompatActivity() { tvMeta.visibility = if (text.isBlank()) View.GONE else View.VISIBLE } + // ==================== 顶栏「更多」菜单 ==================== + + /** + * 「更多」下拉:查看原文、作者主页。 + * + * 原来顶栏只有一个「查看原文」按钮,加作者主页后排不下两个入口, + * 于是收进这个菜单;没有原文链接时该项直接不出现,不留一个点了会报错的项。 + */ + private fun showMoreMenu(anchor: View) { + val entries = ArrayList() + val actions = ArrayList<() -> Unit>() + if (originalUrl.isNotBlank()) { + entries.add(getString(R.string.open_original)) + actions.add { openOriginal() } + } + entries.add(getString(R.string.author_page)) + actions.add { openAuthorPage() } + if (entries.isEmpty()) return + + val palette = Ui.popupPalette(this) + val listView = ListView(this).apply { + adapter = ArrayAdapter(this@ReaderActivity, R.layout.item_dropdown_center, entries) + dividerHeight = 0 + setPadding(0, dp(6), 0, dp(6)) + scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY + } + val popupW = Ui.menuWidth(this, entries, textSizeSp = 13f, extraDp = 52, minDp = 120, maxDp = 240) + val popupH = entries.size * dp(46) + dp(12) + val popup = PopupWindow(listView, popupW, popupH, true).apply { + isOutsideTouchable = true + setBackgroundDrawable(palette.background()) + elevation = dp(8).toFloat() + } + listView.setOnItemClickListener { _, _, position, _ -> + popup.dismiss() + actions.getOrNull(position)?.invoke() + } + // 按钮在右上角、下沿还有空间:贴着按钮下方展开,右边缘对齐 + val loc = IntArray(2) + val rootLoc = IntArray(2) + anchor.getLocationOnScreen(loc) + anchor.rootView.getLocationOnScreen(rootLoc) + val x = (loc[0] - rootLoc[0] + anchor.width - popupW) + .coerceIn(dp(8), (anchor.rootView.width - popupW - dp(8)).coerceAtLeast(dp(8))) + popup.showAtLocation( + anchor.rootView, + Gravity.TOP or Gravity.START, + x, + loc[1] - rootLoc[1] + anchor.height + dp(4), + ) + } + + private fun openOriginal() { + if (originalUrl.isBlank()) { + toast("这条内容没有原文链接") + return + } + runCatching { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(originalUrl))) + }.onFailure { toast("打不开浏览器") } + } + + /** + * 作者主页:按来源站点列出该作者(站点)的文章。 + * + * 服务端条目没有 author 字段、接口也没有 author 参数,而这类"作者主页"基本都是 + * 个人博客——一个站点就是一位作者,所以按站点 id 过滤,头部再标出网站名称与收录数量。 + * 作者名取不到时退回网站名,仍能进到站点文章列表。 + */ + private fun openAuthorPage() { + val site = siteName() + val author = metaAuthor.ifBlank { site } + if (author.isBlank()) { + toast("这条内容没有作者信息") + return + } + ArticleListActivity.openAuthor(this, author, site, siteUrl, urlId) + } + + /** 站点名:优先 RSS 条目带的 siteTitle,其次从原文地址里取域名 */ + private fun siteName(): String = metaSource.ifBlank { hostOf(originalUrl) } + + private fun hostOf(url: String): String = runCatching { + java.net.URI(url).host.orEmpty().removePrefix("www.") + }.getOrDefault("") + + // ==================== AI 摘要 + 标签 ==================== + + /** 先出正文,再补摘要:摘要是增强,不能挡住阅读 */ + private fun renderWithBrief(markdown: String) { + render(markdown) + setupBrief(markdown) + } + + private fun setupBrief(body: String) { + briefBody = body + // 没配 Key 就只显示条目自带标签,摘要位不占 + if (!prefs.aiReady || plainLength(body) < BRIEF_MIN_CHARS) { + showTagsOnly() + return + } + prefs.getBrief(briefKey)?.let { cached -> + showBrief(cached.summary, mergeTags(cached.tags)) + return + } + requestBrief() + } + + /** 摘要看重的是文字量,图片(含 %%IMG%% token)与标签不计入 */ + private fun plainLength(body: String): Int = body + .replace(Regex("%%(?:IMG|FLEXP)%%[\\s\\S]*?%%/(?:IMG|FLEXP)%%"), " ") + .replace(Regex("!\\[[^\\]]*\\]\\([^)]*\\)"), "") + .replace(Regex("<[^>]*>"), "") + .trim() + .length + + /** AI 给的标签优先,再并上条目自带的,去重后最多 8 个 */ + private fun mergeTags(aiTags: List): List { + val out = ArrayList() + (aiTags + itemTags).forEach { raw -> + val tag = raw.trim().removePrefix("#").trim() + if (tag.isEmpty() || tag.length > 14) return@forEach + if (out.none { it.equals(tag, true) }) out.add(tag) + } + return out.take(8) + } + + private fun requestBrief() { + if (briefRequesting) return + briefRequesting = true + briefCard.visibility = View.VISIBLE + tvBriefTitle.text = getString(R.string.ai_summary) + tvBriefBody.visibility = View.VISIBLE + tvBriefBody.setTextColor(ContextCompat.getColor(this, R.color.text_secondary)) + tvBriefBody.text = getString(R.string.ai_summary_loading) + tvBriefBody.setOnClickListener(null) + briefTagScroll.visibility = View.GONE + lifecycleScope.launch { + try { + val brief = withContext(Dispatchers.IO) { + AiApi.brief(prefs, tvTitle.text.toString(), briefBody) + } + if (isFinishing || isDestroyed) return@launch + prefs.putBrief(briefKey, brief) + showBrief(brief.summary, mergeTags(brief.tags)) + } catch (e: Exception) { + if (isFinishing || isDestroyed) return@launch + showBriefError(e.message.orEmpty()) + } finally { + briefRequesting = false + } + } + } + + private fun showBrief(summary: String, tags: List) { + briefCard.visibility = View.VISIBLE + tvBriefTitle.text = getString(R.string.ai_summary) + tvBriefBody.visibility = View.VISIBLE + tvBriefBody.setTextColor(ContextCompat.getColor(this, R.color.text_secondary)) + tvBriefBody.text = summary + tvBriefBody.setOnClickListener(null) + renderTags(tags) + } + + /** 失败时不留空白卡:有标签就只显示标签,点文字可重试 */ + private fun showBriefError(message: String) { + briefCard.visibility = View.VISIBLE + tvBriefTitle.text = getString(R.string.ai_summary) + tvBriefBody.visibility = View.VISIBLE + tvBriefBody.setTextColor(ContextCompat.getColor(this, R.color.brand)) + tvBriefBody.text = if (message.isBlank()) getString(R.string.ai_summary_failed) + else getString(R.string.ai_summary_failed_reason, message) + tvBriefBody.setOnClickListener { requestBrief() } + renderTags(mergeTags(emptyList())) + } + + private fun showTagsOnly() { + val tags = mergeTags(emptyList()) + if (tags.isEmpty()) { + briefCard.visibility = View.GONE + return + } + briefCard.visibility = View.VISIBLE + tvBriefTitle.text = getString(R.string.article_tags) + tvBriefBody.visibility = View.GONE + tvBriefBody.setOnClickListener(null) + renderTags(tags) + } + + /** 标签 chip 横排,点任意一个按该标签浏览 */ + private fun renderTags(tags: List) { + briefTags.removeAllViews() + if (tags.isEmpty()) { + briefTagScroll.visibility = View.GONE + return + } + briefTagScroll.visibility = View.VISIBLE + tags.forEach { tag -> + val chip = TextView(this).apply { + text = "#$tag" + textSize = 11.5f + setTextColor(ContextCompat.getColor(context, R.color.brand)) + background = ContextCompat.getDrawable(context, R.drawable.bg_brand_soft) + setPadding(dp(10), dp(4), dp(10), dp(5)) + isClickable = true + setOnClickListener { + ArticleListActivity.openTag(this@ReaderActivity, tag) + } + } + briefTags.addView( + chip, + LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ).apply { marginEnd = dp(8) }, + ) + } + } + /** * 正文开头的重复信息全部剥掉。 * diff --git a/src/main/java/com/shitoucuo/postpad/RssApi.kt b/src/main/java/com/shitoucuo/postpad/RssApi.kt index 5213bd3..6800f12 100644 --- a/src/main/java/com/shitoucuo/postpad/RssApi.kt +++ b/src/main/java/com/shitoucuo/postpad/RssApi.kt @@ -34,6 +34,9 @@ object RssApi { val categoryName: String, val pubDate: String, val tags: List, + /** 订阅站点 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"), ) ) } diff --git a/src/main/res/layout/activity_article_list.xml b/src/main/res/layout/activity_article_list.xml new file mode 100644 index 0000000..ae0401d --- /dev/null +++ b/src/main/res/layout/activity_article_list.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_reader.xml b/src/main/res/layout/activity_reader.xml index 74bba29..a45c388 100644 --- a/src/main/res/layout/activity_reader.xml +++ b/src/main/res/layout/activity_reader.xml @@ -35,11 +35,13 @@ android:textSize="15sp" /> @@ -75,6 +77,56 @@ android:textColor="@color/text_tertiary" android:textSize="12sp" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml index f2831f3..af085f9 100644 --- a/src/main/res/values/strings.xml +++ b/src/main/res/values/strings.xml @@ -196,4 +196,21 @@ 图片加载失败,点击重试 关闭 ✕ + + + 更多 + 作者主页 + 标签浏览 + 打开网站 + 正在读取… + 收录 %1$d 篇文章 + %1$s + %1$s · 收录 %2$d 篇文章 + 这个站点还没有收录文章 + 没有找到带「%1$s」标签的文章 + AI 摘要 + AI 正在读这篇文章… + 摘要没生成出来,点此重试 + %1$s\n点此重试 + 标签