From d959ffed68fa0a025ce1253575b62e85bc174321 Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:04:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8F=92=E4=BB=B6=E6=BA=90?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=A0=87=E5=87=86?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 29 + CHANGELOG.md | 7 + CONTRIBUTING.md | 19 + LICENSE | 21 + README.md | 28 + src/main/AndroidManifest.xml | 61 + src/main/java/com/shitoucuo/postpad/AiApi.kt | 164 ++ .../java/com/shitoucuo/postpad/FeedAdapter.kt | 831 ++++++++++ .../com/shitoucuo/postpad/HomeActivity.kt | 1311 ++++++++++++++++ src/main/java/com/shitoucuo/postpad/Http.kt | 48 + .../java/com/shitoucuo/postpad/ImageCache.kt | 71 + .../shitoucuo/postpad/ImagePreviewActivity.kt | 425 +++++ .../java/com/shitoucuo/postpad/ImageUtils.kt | 97 ++ .../java/com/shitoucuo/postpad/MailApi.kt | 733 +++++++++ .../shitoucuo/postpad/MailDetailActivity.kt | 396 +++++ .../com/shitoucuo/postpad/MainActivity.kt | 1365 +++++++++++++++++ .../com/shitoucuo/postpad/MdThemePlugin.kt | 38 + .../java/com/shitoucuo/postpad/MemosApi.kt | 265 ++++ src/main/java/com/shitoucuo/postpad/Prefs.kt | 627 ++++++++ .../com/shitoucuo/postpad/ReaderActivity.kt | 634 ++++++++ src/main/java/com/shitoucuo/postpad/RssApi.kt | 410 +++++ .../com/shitoucuo/postpad/SettingsActivity.kt | 672 ++++++++ .../java/com/shitoucuo/postpad/TypechoApi.kt | 475 ++++++ src/main/java/com/shitoucuo/postpad/Ui.kt | 132 ++ .../shitoucuo/postpad/ZoomableImageView.kt | 158 ++ .../res/drawable-night/bg_icon_button.xml | 5 + src/main/res/drawable/bg_brand_soft.xml | 6 + src/main/res/drawable/bg_button_ghost.xml | 13 + src/main/res/drawable/bg_button_primary.xml | 13 + .../res/drawable/bg_button_primary_circle.xml | 13 + src/main/res/drawable/bg_card.xml | 9 + src/main/res/drawable/bg_chip_off.xml | 13 + src/main/res/drawable/bg_chip_on.xml | 6 + src/main/res/drawable/bg_dropdown_input.xml | 20 + src/main/res/drawable/bg_field.xml | 10 + src/main/res/drawable/bg_field_dropdown.xml | 18 + src/main/res/drawable/bg_icon_button.xml | 10 + src/main/res/drawable/bg_input.xml | 6 + src/main/res/drawable/bg_nav_badge.xml | 7 + src/main/res/drawable/bg_segment.xml | 6 + src/main/res/drawable/bg_segment_on.xml | 9 + src/main/res/drawable/bg_status.xml | 6 + src/main/res/drawable/bg_thumb_close.xml | 5 + src/main/res/drawable/ic_add.xml | 9 + src/main/res/drawable/ic_alert.xml | 10 + src/main/res/drawable/ic_article.xml | 9 + src/main/res/drawable/ic_back.xml | 13 + src/main/res/drawable/ic_check.xml | 10 + src/main/res/drawable/ic_check_circle_off.xml | 13 + src/main/res/drawable/ic_check_circle_on.xml | 16 + src/main/res/drawable/ic_chevron.xml | 13 + src/main/res/drawable/ic_disc.xml | 25 + src/main/res/drawable/ic_house.xml | 58 + src/main/res/drawable/ic_image.xml | 10 + .../res/drawable/ic_launcher_background.xml | 26 + src/main/res/drawable/ic_mark.xml | 6 + src/main/res/drawable/ic_memo.xml | 9 + src/main/res/drawable/ic_moon.xml | 11 + src/main/res/drawable/ic_plane.xml | 40 + src/main/res/drawable/ic_reply.xml | 9 + src/main/res/drawable/ic_send.xml | 10 + src/main/res/drawable/ic_settings.xml | 10 + src/main/res/drawable/ic_sun.xml | 11 + src/main/res/drawable/ic_trash.xml | 9 + src/main/res/layout/activity_home.xml | 410 +++++ src/main/res/layout/activity_mail_detail.xml | 134 ++ src/main/res/layout/activity_main.xml | 535 +++++++ src/main/res/layout/activity_reader.xml | 95 ++ src/main/res/layout/activity_settings.xml | 986 ++++++++++++ src/main/res/layout/item_dropdown_center.xml | 14 + src/main/res/layout/item_feed.xml | 98 ++ src/main/res/layout/item_spinner.xml | 9 + src/main/res/layout/item_spinner_dropdown.xml | 13 + .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 5 + src/main/res/mipmap-anydpi/ic_launcher.xml | 6 + .../res/mipmap-anydpi/ic_launcher_round.xml | 6 + src/main/res/values-night/colors.xml | 36 + src/main/res/values-night/themes.xml | 19 + src/main/res/values/colors.xml | 52 + src/main/res/values/strings.xml | 199 +++ src/main/res/values/themes.xml | 19 + 82 files changed, 12160 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/main/AndroidManifest.xml create mode 100644 src/main/java/com/shitoucuo/postpad/AiApi.kt create mode 100644 src/main/java/com/shitoucuo/postpad/FeedAdapter.kt create mode 100644 src/main/java/com/shitoucuo/postpad/HomeActivity.kt create mode 100644 src/main/java/com/shitoucuo/postpad/Http.kt create mode 100644 src/main/java/com/shitoucuo/postpad/ImageCache.kt create mode 100644 src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt create mode 100644 src/main/java/com/shitoucuo/postpad/ImageUtils.kt create mode 100644 src/main/java/com/shitoucuo/postpad/MailApi.kt create mode 100644 src/main/java/com/shitoucuo/postpad/MailDetailActivity.kt create mode 100644 src/main/java/com/shitoucuo/postpad/MainActivity.kt create mode 100644 src/main/java/com/shitoucuo/postpad/MdThemePlugin.kt create mode 100644 src/main/java/com/shitoucuo/postpad/MemosApi.kt create mode 100644 src/main/java/com/shitoucuo/postpad/Prefs.kt create mode 100644 src/main/java/com/shitoucuo/postpad/ReaderActivity.kt create mode 100644 src/main/java/com/shitoucuo/postpad/RssApi.kt create mode 100644 src/main/java/com/shitoucuo/postpad/SettingsActivity.kt create mode 100644 src/main/java/com/shitoucuo/postpad/TypechoApi.kt create mode 100644 src/main/java/com/shitoucuo/postpad/Ui.kt create mode 100644 src/main/java/com/shitoucuo/postpad/ZoomableImageView.kt create mode 100644 src/main/res/drawable-night/bg_icon_button.xml create mode 100644 src/main/res/drawable/bg_brand_soft.xml create mode 100644 src/main/res/drawable/bg_button_ghost.xml create mode 100644 src/main/res/drawable/bg_button_primary.xml create mode 100644 src/main/res/drawable/bg_button_primary_circle.xml create mode 100644 src/main/res/drawable/bg_card.xml create mode 100644 src/main/res/drawable/bg_chip_off.xml create mode 100644 src/main/res/drawable/bg_chip_on.xml create mode 100644 src/main/res/drawable/bg_dropdown_input.xml create mode 100644 src/main/res/drawable/bg_field.xml create mode 100644 src/main/res/drawable/bg_field_dropdown.xml create mode 100644 src/main/res/drawable/bg_icon_button.xml create mode 100644 src/main/res/drawable/bg_input.xml create mode 100644 src/main/res/drawable/bg_nav_badge.xml create mode 100644 src/main/res/drawable/bg_segment.xml create mode 100644 src/main/res/drawable/bg_segment_on.xml create mode 100644 src/main/res/drawable/bg_status.xml create mode 100644 src/main/res/drawable/bg_thumb_close.xml create mode 100644 src/main/res/drawable/ic_add.xml create mode 100644 src/main/res/drawable/ic_alert.xml create mode 100644 src/main/res/drawable/ic_article.xml create mode 100644 src/main/res/drawable/ic_back.xml create mode 100644 src/main/res/drawable/ic_check.xml create mode 100644 src/main/res/drawable/ic_check_circle_off.xml create mode 100644 src/main/res/drawable/ic_check_circle_on.xml create mode 100644 src/main/res/drawable/ic_chevron.xml create mode 100644 src/main/res/drawable/ic_disc.xml create mode 100644 src/main/res/drawable/ic_house.xml create mode 100644 src/main/res/drawable/ic_image.xml create mode 100644 src/main/res/drawable/ic_launcher_background.xml create mode 100644 src/main/res/drawable/ic_mark.xml create mode 100644 src/main/res/drawable/ic_memo.xml create mode 100644 src/main/res/drawable/ic_moon.xml create mode 100644 src/main/res/drawable/ic_plane.xml create mode 100644 src/main/res/drawable/ic_reply.xml create mode 100644 src/main/res/drawable/ic_send.xml create mode 100644 src/main/res/drawable/ic_settings.xml create mode 100644 src/main/res/drawable/ic_sun.xml create mode 100644 src/main/res/drawable/ic_trash.xml create mode 100644 src/main/res/layout/activity_home.xml create mode 100644 src/main/res/layout/activity_mail_detail.xml create mode 100644 src/main/res/layout/activity_main.xml create mode 100644 src/main/res/layout/activity_reader.xml create mode 100644 src/main/res/layout/activity_settings.xml create mode 100644 src/main/res/layout/item_dropdown_center.xml create mode 100644 src/main/res/layout/item_feed.xml create mode 100644 src/main/res/layout/item_spinner.xml create mode 100644 src/main/res/layout/item_spinner_dropdown.xml create mode 100644 src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 src/main/res/mipmap-anydpi/ic_launcher.xml create mode 100644 src/main/res/mipmap-anydpi/ic_launcher_round.xml create mode 100644 src/main/res/values-night/colors.xml create mode 100644 src/main/res/values-night/themes.xml create mode 100644 src/main/res/values/colors.xml create mode 100644 src/main/res/values/strings.xml create mode 100644 src/main/res/values/themes.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a90ef58 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 变更记录 + +## 2026-11-26 · 初始同步 + +- 同步插件源代码到新 Gitea 仓库。 +- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。 +- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..68e8c20 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 石头厝 / XIGE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c8fc532 --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +# PostPad(石头厝) + +> 仓库:`PostPad` · 类型:Android 应用 · 版本:`3.33` · 作者:石头厝 / XIGE + +自用安卓小工具:信息(RSS / 文章 / Memos)、发布(文章 / 微博)、邮件。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `src/` + +## 安装与使用 + +1. Android 源码位于 `app/src/`,按 Android 项目结构导入开发环境。 +2. 构建配置、签名密钥与依赖不在本仓库内,请按自有环境配置后构建安装。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5fe56ea --- /dev/null +++ b/src/main/AndroidManifest.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/shitoucuo/postpad/AiApi.kt b/src/main/java/com/shitoucuo/postpad/AiApi.kt new file mode 100644 index 0000000..b01708b --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/AiApi.kt @@ -0,0 +1,164 @@ +package com.shitoucuo.postpad + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject +import java.util.concurrent.TimeUnit + +/** + * 润色 / 完善用的 AI 调用。 + * + * 走的是 AIAssist 插件同一家的对话接口(DeepSeek / 智谱),请求体就是标准的 + * OpenAI 兼容格式:{model, messages[], stream:false}。 + * 之所以在本地直接调、不复用插件的 /aiassist-analyze: + * 那个端点按 cid 取已发布文章的正文,草稿在提交前还没有 cid,拿不到。 + * 这里填的 Key 与插件设置里的一致,模型也一样,效果等同插件的「润文」。 + */ +object AiApi { + + const val PROVIDER_DEEPSEEK = "deepseek" + const val PROVIDER_ZHIPU = "zhipu" + + const val MODE_POLISH = "polish" + const val MODE_EXPAND = "expand" + + /** 单次提交的字数上限:再长模型容易把结尾截掉,不如按住提示用户分段 */ + const val MAX_INPUT = 12000 + + private val JSON = "application/json; charset=utf-8".toMediaType() + + /** AI 生成慢,读超时给足;发布与上传用的是另外的 client */ + private val client: OkHttpClient = Http.newWith(20, 60, 300, TimeUnit.SECONDS) + + class ApiException(message: String, val code: Int = 0) : Exception(message) + + /** 「润色」只改错:错别字、病句、标点,别的一律不动 */ + private const val POLISH_PROMPT = + "你是中文文字编辑,只做校对。任务:修正错别字、错误用词、病句和标点,删掉重复的字词," + + "让句子读起来通顺。要求:不改变原意,不改写作者的表达风格,不增删内容,不加总结或点评," + + "不做文学加工。必须完整保留 Markdown 语法(标题 #、列表 -、引用 >、代码 ```、加粗 **、" + + "链接与图片 ![说明](地址))以及图片地址,原样不动。保留原有段落划分与顺序。" + + "只输出修改后的全文,不要任何解释、前言或后缀。" + + /** 「完善」在原意不变的前提下扩写补充 */ + private const val EXPAND_PROMPT = + "你是中文写作助手。任务:在保持原意、观点、立场和段落顺序不变的前提下,把文章补充完整。" + + "具体做法:把过于简略的地方展开,补上必要的细节、背景、原因与过渡句;" + + "把口语化的碎片句子整理成通顺的复句;段落之间缺衔接的补上衔接。" + + "篇幅控制在原文的 1.3 到 1.6 倍,不要注水,不要重复啰嗦,不要编造事实、数字和人名。" + + "必须完整保留 Markdown 语法与图片 ![说明](地址) 的写法、地址和位置,图片一行都不能丢。" + + "保留第一人称与作者语气。只输出完整正文,不要任何解释、前言或后缀。" + + /** + * 执行一次改写。 + * + * @param text 原文(调用方负责长度校验) + * @param mode [MODE_POLISH] 或 [MODE_EXPAND] + * @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,先到设置里填一下") + } + + 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", 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() + .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 { + val json = JSONObject(body) + json.optJSONObject("error")?.optString("message").orEmpty() + .ifBlank { json.optString("message") } + } catch (e: Exception) { + body.replace(Regex("<[^>]*>"), " ").replace(Regex("\\s+"), " ").trim().take(120) + } + + val prefix = when (code) { + 401 -> "AI Key 无效或已过期" + 402 -> "AI 账户余额不足" + 429 -> "请求太频繁,稍等一会儿再点" + 400 -> "请求被拒绝(模型名可能不对)" + else -> "HTTP $code" + } + return if (detail.isBlank()) prefix else "$prefix:$detail" + } +} diff --git a/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt b/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt new file mode 100644 index 0000000..07005df --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt @@ -0,0 +1,831 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.content.res.ColorStateList +import android.content.res.Configuration +import android.graphics.Rect +import android.text.Spanned +import android.text.method.LinkMovementMethod +import android.text.style.ImageSpan +import android.text.style.ReplacementSpan +import android.view.LayoutInflater +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView +import io.noties.markwon.AbstractMarkwonPlugin +import io.noties.markwon.Markwon +import io.noties.markwon.MarkwonConfiguration +import io.noties.markwon.image.AsyncDrawable +import io.noties.markwon.image.AsyncDrawableSpan +import io.noties.markwon.image.ImageSizeResolver +import io.noties.markwon.image.ImageSizeResolverDef +import io.noties.markwon.image.ImagesPlugin +import io.noties.markwon.image.network.OkHttpNetworkSchemeHandler +import okhttp3.OkHttpClient +import kotlin.math.abs +import kotlin.math.roundToInt + +/** 信息页统一列表项(RSS / 文章 / Memos / 邮件) */ +data class FeedItem( + val kind: String, + val id: String, + val title: String, + val source: String, + val date: Long, + val summary: String, + val link: String, + val read: Boolean, + val content: String = "", + val hasAttachment: Boolean = false, + /** + * Memos 的图片资源(resourceList 中 type 以 image/ 开头的 externalLink)。 + * + * Memos 上传的图片不写在正文里:无论网页端还是 App 上传,二进制都只挂在 + * memo 的 resourceList 上,content 只有文字。网页端会在正文下方渲染这组图, + * App 早期版本忽略了该字段,于是"手写的 Markdown 图片能显示、上传的图片看不到"。 + */ + val images: List = emptyList(), + /** + * 邮件所属账户(邮箱地址)与显示名。 + * + * 邮件页现在把**所有邮箱**合并成一条时间线,卡片必须让人看出这封属于哪个邮箱, + * 点开时也要按这个地址去找对应账户的配置(否则会拿错邮箱去连 IMAP, + * UID 对不上就提示"已删除",已读状态也会标到别的邮件上)。 + */ + val account: String = "", + val accountLabel: String = "", +) + +class FeedAdapter( + private val context: Context, + private val onOpen: (FeedItem) -> Unit, + private val onToggleRead: (FeedItem) -> Unit, + private val onImageClick: (String) -> Unit, +) : RecyclerView.Adapter() { + + /** Memos 卡片渲染 Markdown(含图片),列表共享一个 Markwon 实例与全局连接池 */ + private val markwon: Markwon by lazy { + Markwon.builder(themeCtx) + .usePlugin( + ImagesPlugin.create() + .addSchemeHandler(OkHttpNetworkSchemeHandler.create(imageClient)), + ) + // 多图横排:默认解析器把每张图都缩到画布宽度,多图必然各占一行。 + // 这里只改写「登记为网格图片」的宽度,正文手写的图片仍走默认逻辑。 + .usePlugin(GridImagePlugin(imageGridColumns, themeCtx.resources.displayMetrics.density)) + .usePlugin(MdThemePlugin(themeCtx)) + .build() + } + + /** + * 网格图片的目标列数:图片 URL → 该 memo 每行显示几张。 + * + * Markwon 的 ImageSizeResolver 只拿得到 AsyncDrawable(含 destination 与画布宽度), + * 拿不到"这是第几张、总共几张",而列数必须由渲染方决定(1 张全宽、2 张并排、 + * 3 张以上三列)。所以渲染前把 URL→列数 登记在这里,解析器按 URL 查表计算宽度。 + * 只在主线程读写;`size` 上限兜底见 memoMarkdown()。 + */ + private val imageGridColumns = java.util.concurrent.ConcurrentHashMap() + + /** + * 图片专用 OkHttp:由 [Http.imageClient] 提供单例(共享连接池 + 64MB 磁盘缓存)。 + * + * 大图预览页用同一份实例,避免两个 Cache 指向同一目录;同一 URL 在列表里 + * 已经下载过,点开大图直接命中缓存,不再重下一遍。 + */ + private val imageClient: OkHttpClient by lazy { Http.imageClient(context) } + + private val items = mutableListOf() + + // ==================== 批量选择 ==================== + + /** + * 是否处于「选择」模式。 + * + * 打开后每张卡片左侧出现勾选圈,点卡片由「打开内容」改为「勾选」; + * 右上栏的 全选 / 设为已读 / 删除 只在这个模式下可用。 + */ + var selectionMode: Boolean = false + private set + + /** 已选条目:key 为 `kind|id`(RSS 与邮件的 id 各自独立,必须带 kind 才不串) */ + private val selected = LinkedHashSet() + + /** 选中数量变化回调:首页据此刷新「已选 N 项」与按钮可用状态 */ + var onSelectionChanged: ((Int) -> Unit)? = null + + /** + * 当前页是否允许选择。 + * + * 只有信息(RSS)与邮件页有批量操作栏;其它页(文章 / 动态)不显示操作栏, + * 若不拦住,长按卡片会进入「点了只勾选、却没有任何按钮」的死胡同。 + */ + var selectionEnabled: Boolean = false + + private fun keyOf(item: FeedItem): String = item.kind + "|" + item.id + + fun enterSelection() { + if (selectionMode || !selectionEnabled) return + selectionMode = true + selected.clear() + notifyDataSetChanged() + onSelectionChanged?.invoke(0) + } + + fun exitSelection() { + if (!selectionMode) return + selectionMode = false + selected.clear() + notifyDataSetChanged() + onSelectionChanged?.invoke(0) + } + + fun selectedKeys(): Set = HashSet(selected) + + fun selectedCount(): Int = selected.size + + /** 当前显示的条目是否已全部选中(决定「全选 / 取消全选」按钮文案) */ + fun allSelected(): Boolean = + items.isNotEmpty() && items.all { selected.contains(keyOf(it)) } + + /** 全选 / 取消全选:只作用于当前显示(含筛选)的条目,不会选中看不见的行 */ + fun setSelectAll(all: Boolean) { + if (all) items.forEach { selected.add(keyOf(it)) } else selected.clear() + notifyDataSetChanged() + onSelectionChanged?.invoke(selected.size) + } + + /** 勾选 / 取消勾选单条:只刷新那一行,列表不跳动 */ + fun toggleSelection(item: FeedItem) { + val key = keyOf(item) + if (!selected.remove(key)) selected.add(key) + // 取消了最后一项=这次选择已经结束:收起选择栏、列表恢复「点开内容」, + // 不必再让用户去找「完成」按钮 + if (selected.isEmpty()) { + exitSelection() + return + } + val index = items.indexOfFirst { keyOf(it) == key } + if (index >= 0) notifyItemChanged(index) + onSelectionChanged?.invoke(selected.size) + } + + /** 数据整表替换后,把已不在列表里的选中项清掉,避免「删了还显示已选 3 项」 */ + private fun pruneSelection() { + if (!selectionMode || selected.isEmpty()) return + val alive = items.mapTo(HashSet(items.size)) { keyOf(it) } + if (selected.retainAll(alive)) onSelectionChanged?.invoke(selected.size) + } + + // ==================== 左滑激活选择 ==================== + + /** + * 左滑触发距离。 + * + * 比系统 touchSlop(约 8dp)大不少:手指落在卡片上轻微抖动、或想拖动列表时 + * 不会误进选择模式;真想选择时横向一划就过线。 + */ + private val swipeTrigger: Int = (40 * context.resources.displayMetrics.density).toInt() + + /** + * 左滑激活批量选择。 + * + * 语义与上一版的「左滑露出删除按钮」不同:左滑不再直接删东西(删除是破坏性操作, + * 一次滑动就删太容易误触,也和顶部的勾选/全选重复),而是把这张卡片当作 + * 「想整理这一条」的意图——进入选择模式并勾上它,随后由上面的操作栏统一处理。 + * + * 判定条件:横向位移超过 [swipeTrigger] **且** 横向明显大于纵向(1.5 倍), + * 否则把事件让给 RecyclerView 做纵向滚动,不影响上下滑列表。 + * 一旦触发就 requestDisallowInterceptTouchEvent,并把本次手势剩下的 UP 一并消费掉, + * 避免卡片被当成「被点了一下」而打开内容(选择模式下点卡片又会把它取消勾选)。 + */ + private fun attachSwipeSelect(holder: ViewHolder) { + val view = holder.root + var downX = 0f + var downY = 0f + var consumed = false + + view.setOnTouchListener { _, event -> + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downX = event.rawX + downY = event.rawY + consumed = false + } + + MotionEvent.ACTION_MOVE -> { + if (consumed) return@setOnTouchListener true + // 已经在选择模式里(点卡片即可勾选),或当前页不支持批量操作 + // (动态 / 文章页),都不接管手势,交回默认处理 + if (selectionMode || !selectionEnabled) return@setOnTouchListener false + val dx = event.rawX - downX + val dy = event.rawY - downY + if (dx < -swipeTrigger && abs(dx) > abs(dy) * 1.5f) { + val item = items.getOrNull(holder.bindingAdapterPosition) + ?: return@setOnTouchListener false + consumed = true + view.parent?.requestDisallowInterceptTouchEvent(true) + // 放到事件派发之后再做整表刷新:当前位置正在派发触摸事件, + // 立即 notifyDataSetChanged 会在派发中途改布局 + view.post { swipeSelect(item) } + return@setOnTouchListener true + } + } + + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + if (consumed) { + consumed = false + return@setOnTouchListener true + } + } + } + false + } + } + + /** + * 左滑落到「进入选择并勾上这一条」。 + * + * 选择栏平时不占位,只有这里(或长按)把它叫出来;已经在选择模式里时再左滑别的 + * 卡片只会追加勾选,不会清掉之前选的——批量删除通常要选好几条。 + */ + fun swipeSelect(item: FeedItem) { + if (!selectionEnabled) return + if (!selectionMode) { + selectionMode = true + selected.clear() + } + selected.add(keyOf(item)) + notifyDataSetChanged() + onSelectionChanged?.invoke(selected.size) + } + + private val prefs = Prefs(context) + + /** + * 卡片配色专用上下文:按偏好设置强制 uiMode 后再取资源。 + * + * 列表页停在后台时,其资源层配置可能被其它页面(邮件 WebView / DayNight 应用机制) + * 刷新,返回首页后直接取色会拿到浅色值——表现为"背景深色、卡片浅色"。 + * 这里以 prefs 里保存的深浅意图为唯一依据,深浅永远跟随设置, + * 不依赖运行期配置状态,从根上消除混色。 + */ + private fun themedContext(): Context { + val appCtx = context.applicationContext + val dark = when (prefs.darkMode) { + Prefs.MODE_DARK -> true + Prefs.MODE_LIGHT -> false + else -> (appCtx.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == + Configuration.UI_MODE_NIGHT_YES + } + val conf = Configuration(appCtx.resources.configuration) + conf.uiMode = (conf.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or + if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO + return appCtx.createConfigurationContext(conf) + } + + private var themeCtx: Context = themedContext() + + // ---- 主题配色:绑定时刻解析(而不是只在 inflate 时解析一次)---- + // 复用的卡片可能是在另一主题下创建的,绑定时逐项重设颜色, + // 保证整张列表永远是当前主题的配色,不会深浅混排。 + // 注意:这里只缓存颜色值(Int,无状态),Drawable 不能在这里缓存——见 themeVersion。 + private var cSource = ContextCompat.getColor(themeCtx, R.color.brand) + private var cDate = ContextCompat.getColor(themeCtx, R.color.text_tertiary) + private var cTitle = ContextCompat.getColor(themeCtx, R.color.title) + private var cSummary = ContextCompat.getColor(themeCtx, R.color.text_secondary) + + /** + * 主题版本号:卡片与「未读」徽标的背景,必须是**每个 View 各自一份**的 Drawable 实例。 + * + * 3.24 及更早版本在 Adapter 上缓存了一个 `cardBg` / `unreadBg` 实例给全部卡片共用, + * 这是「卡片高度比内容短、未读与长正文露在边框外」的根因: + * Drawable 的 bounds 是实例自身状态,而 View.drawBackground() 只在 + * mBackgroundSizeChanged 为 true(即 View 尺寸刚变过)时才重新 setBounds()。 + * 共用实例时,一张矮卡片绘制会把这份共享 bounds 改成自己的尺寸;高卡片随后重绘, + * 因为自身尺寸没变(标志为 false)就直接拿被改小的 bounds 去画背景, + * 于是边框只画到一半,内容与徽标露在外面。下拉刷新时每张卡片都重新 bind、 + * 重新 setBackground,标志全部置位,bounds 各归各位,所以一刷新就"好了"。 + * + * 修复方式是每个 View 持有独立实例;深浅色切换需要换配色, + * 用版本号让每个 View 在版本变化后重取一份,回收到池里的 View 下次绑定也会更新。 + */ + private var themeVersion = 0 + + /** 深浅色状态变化后调用:重取配色并整表重绑 */ + fun refreshTheme() { + themeCtx = themedContext() + themeVersion++ + cSource = ContextCompat.getColor(themeCtx, R.color.brand) + cDate = ContextCompat.getColor(themeCtx, R.color.text_tertiary) + cTitle = ContextCompat.getColor(themeCtx, R.color.title) + cSummary = ContextCompat.getColor(themeCtx, R.color.text_secondary) + notifyDataSetChanged() + } + + /** + * 邮件卡片是否显示所属邮箱名。 + * + * 邮件页默认是「全部邮箱」的合并时间线,卡片必须标出这封属于哪个邮箱; + * 但用顶部筛选只看某一个邮箱时,每张卡片都重复同一个名字既啰嗦又占位, + * 所以由首页按当前筛选状态切换这个开关。 + */ + var showMailAccount: Boolean = true + set(value) { + if (field == value) return + field = value + // 内容没变但显示规则变了,只能整表重绑 + if (items.isNotEmpty()) notifyDataSetChanged() + } + + fun submit(list: List) { + items.clear() + items.addAll(list) + notifyDataSetChanged() + pruneSelection() + } + + /** + * 用新数据刷新列表:能对齐就逐条差量更新,对不齐才整表重绑。 + * + * 从邮件详情 / 阅读页返回时会重新读一遍缓存,直接 notifyDataSetChanged 会把 + * 已经滚动到的位置弹回顶部;id 序列没变(只是已读状态、摘要变了)时逐条 + * 刷新,滚动位置与正在播放的图片都能保住。 + */ + fun update(list: List) { + val sameShape = items.size == list.size && items.indices.all { i -> + items[i].id == list[i].id && items[i].kind == list[i].kind + } + if (!sameShape) { + submit(list) + return + } + list.forEachIndexed { index, item -> + if (items[index] != item) { + items[index] = item + notifyItemChanged(index) + } + } + pruneSelection() + } + + /** 按 id 更新单条(点开即已读时用),找不到就忽略 */ + fun updateItem(item: FeedItem) { + val index = items.indexOfFirst { it.kind == item.kind && it.id == item.id } + if (index < 0) return + items[index] = item + notifyItemChanged(index) + } + + fun append(list: List) { + val from = items.size + items.addAll(list) + notifyItemRangeInserted(from, list.size) + } + + inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { + /** 卡片本体:整行都是它,左滑手势与点击都挂在上面 */ + val root: View = view.findViewById(R.id.itemRoot) + /** 选择模式下的勾选圈 */ + val check: ImageView = view.findViewById(R.id.itemCheck) + val source: TextView = view.findViewById(R.id.tvSource) + val date: TextView = view.findViewById(R.id.tvDate) + val title: TextView = view.findViewById(R.id.tvTitle) + val summary: TextView = view.findViewById(R.id.tvSummary) + val unread: TextView = view.findViewById(R.id.tvUnread) + + /** 该 View 私有背景当前对应的主题版本,-1 表示尚未设置 */ + var themeVersion: Int = -1 + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(parent.context).inflate(R.layout.item_feed, parent, false) + val holder = ViewHolder(view) + // 触摸监听只装一次:命中判断在抬手时读当前文本,回收复用不会串图 + attachImageTaps(holder.summary) + attachSwipeSelect(holder) + return holder + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = items[position] + // 每个 View 一份独立 Drawable:共用实例会让 bounds 互相覆盖(见 themeVersion 注释) + if (holder.themeVersion != themeVersion) { + holder.root.background = ContextCompat.getDrawable(themeCtx, R.drawable.bg_card) + holder.unread.background = ContextCompat.getDrawable(themeCtx, R.drawable.bg_brand_soft) + holder.themeVersion = themeVersion + } + // 每次绑定都按当前主题重设颜色,跨主题复用的卡片不会残留旧配色 + holder.source.setTextColor(cSource) + holder.date.setTextColor(cDate) + holder.title.setTextColor(cTitle) + holder.summary.setTextColor(cSummary) + holder.unread.setTextColor(cSource) + holder.date.text = formatDate(item.date) + + // Memos 卡片直接显示全文:不显示标题行,正文不限行数; + // 左侧原本的来源位换成完整时间(右侧相对时间隐藏) + val isMemo = item.kind == "memo" + if (isMemo) { + holder.source.text = buildString { + if (item.source == "置顶") append("置顶 · ") + append(formatFullDate(item.date)) + } + holder.date.text = "" + holder.title.visibility = View.GONE + holder.summary.maxLines = Int.MAX_VALUE + holder.summary.ellipsize = null + holder.summary.textSize = 14f + } else { + holder.source.text = buildString { + // 邮件卡片:邮箱名在前、发件人在后(合并时间线里「这是哪个邮箱」先要知道)。 + // 只筛单个邮箱时不重复标注邮箱名,见 showMailAccount。 + val showAccount = item.accountLabel.isNotBlank() && showMailAccount + if (showAccount) { + append(item.accountLabel) + if (item.source.isNotBlank()) append(" · ").append(item.source) + } else { + append(item.source) + } + if (item.hasAttachment) append(" · 有附件") + } + if (item.title.isBlank()) { + holder.title.visibility = View.GONE + } else { + holder.title.visibility = View.VISIBLE + holder.title.text = item.title + } + holder.summary.maxLines = 2 + holder.summary.ellipsize = android.text.TextUtils.TruncateAt.END + holder.summary.textSize = 12.5f + } + // Memos 卡片正文:正文 + resourceList 里的图片,渲染前拼成一份 Markdown + val memoBody = if (isMemo) memoMarkdown(item) else null + + val hasBody = + if (memoBody != null) memoBody.isNotBlank() else item.summary.isNotBlank() + if (!hasBody) { + holder.summary.visibility = View.GONE + } else { + holder.summary.visibility = View.VISIBLE + if (memoBody != null) { + // Memos 卡片支持 Markdown:粗体/斜体/列表/代码块/链接/图片 + holder.summary.movementMethod = LinkMovementMethod.getInstance() + markwon.setMarkdown(holder.summary, memoBody) + } else { + holder.summary.text = item.summary + } + } + holder.unread.visibility = if (item.read) View.GONE else View.VISIBLE + + // 选择模式:左侧出现勾选圈,勾中时填品牌色,未勾是灰色空心圆 + val checked = selectionMode && selected.contains(keyOf(item)) + holder.check.visibility = if (selectionMode) View.VISIBLE else View.GONE + if (selectionMode) { + holder.check.setImageResource( + if (checked) R.drawable.ic_check_circle_on else R.drawable.ic_check_circle_off + ) + holder.check.imageTintList = ColorStateList.valueOf(if (checked) cSource else cDate) + } + + holder.root.setOnClickListener { + if (selectionMode) toggleSelection(item) else onOpen(item) + } + // 长按与左滑等价:都直接进入选择模式并勾上这一条 + holder.root.setOnLongClickListener { + if (selectionMode || !selectionEnabled) return@setOnLongClickListener false + enterSelection() + toggleSelection(item) + true + } + holder.check.setOnClickListener { if (selectionMode) toggleSelection(item) } + holder.unread.setOnClickListener { onToggleRead(item) } + } + + /** + * Memos 卡片正文:把 resourceList 里的图片拼进 Markdown 一并渲染。 + * + * Memos 的图片有两种来源,网页端都会显示: + * 1. 正文里手写的 `![](url)`(网页编辑器插入的图片); + * 2. 只挂在 resourceList 上、正文没写的图片(App 上传的就是这一类)。 + * 这里按 resourceList 顺序把第 2 类追加到正文末尾,展示顺序与网页一致。 + * + * 布局与网页端对齐:单图全宽,两张并排,三张以上每行三张。实现方式是先把 + * 「一张图独占一段」的连续段落合并成**同一段落**(空格分隔),再让 + * [GridImageSizeResolver] 把每张的宽度压到画布宽度的 1/n——宽度之和不足一行, + * TextView 自然把它们排在同一行。 + * + * 正文图片与追加图片必须走同一套列数登记,否则会出现「一种横排、另一种竖排」, + * 点击行为也会跟着分叉(3.28 的 bug)。 + */ + private fun memoMarkdown(item: FeedItem): String { + // MyTrack 足迹地图短代码 {map-数字} APP 端无法渲染,直接隐藏 + val cleaned = item.summary.replace( + Regex("\\{map-\\d+\\}", RegexOption.IGNORE_CASE), "", + ) + // 正文里「每张图一段」的写法(网页编辑器、Obsidian 都这么写)合并成一段 + val text = mergeImageParagraphs(cleaned) + // 登记正文图片的列数,让它们和追加图片一样横排、一样能点 + registerGridColumns(text) + + if (item.images.isEmpty()) return text + + // 正文里已经手写引用过的图片不重复追加 + val extra = item.images.filter { it.isNotBlank() && !text.contains(it) } + if (extra.isEmpty()) return text + + // 少数部署版本只返回相对路径(/file/xxx),补成绝对地址,图片加载器才取得到 + val base = prefs.memosUrl.trimEnd('/') + val columns = columnsFor(extra.size) + // 登记表只为渲染服务,长期滚动会堆积已不再显示的历史 URL,超过阈值整体清一次; + // 清掉后下次绑定会重新登记,最差退化成一次全宽图片 + if (imageGridColumns.size > 256) imageGridColumns.clear() + + return buildString { + append(text.trimEnd()) + if (isNotEmpty()) append("\n\n") + extra.forEachIndexed { index, raw -> + val url = if (raw.startsWith("/")) base + raw else raw + imageGridColumns[url] = columns + append("![](").append(url).append(")") + // 同一段落内以空格分隔,图片才会横向排列;强制换行就会退回竖排 + if (index != extra.lastIndex) append(' ') + } + }.trimEnd() + } + + /** + * 把「一张图独占一段」的连续段落合并成一段(空格分隔)。 + * + * 网页端的图片网格不看段落:连续几张图并排显示。Markdown 里每张图各占一段时, + * 无论尺寸解析器怎么算宽度,TextView 也会按段落换行,结果只能是竖排。 + * 只有整段都是图片的段落参与合并,混着文字的段落原样保留。 + */ + private fun mergeImageParagraphs(text: String): String { + if (!text.contains("![")) return text + val blocks = text.split(PARAGRAPH_BREAK) + val out = ArrayList(blocks.size) + val run = ArrayList() + fun flush() { + if (run.isEmpty()) return + out.add(if (run.size == 1) run[0] else run.joinToString(" ")) + run.clear() + } + for (block in blocks) { + if (IMAGE_ONLY_BLOCK.matches(block.trim())) { + // 整段都是图片时,段内换行统一收成空格:Obsidian / 网页编辑器常用单个换行 + // 分隔图片,不收成空格的话仍会被渲染成换行,又退回竖排 + run.add(block.trim().replace(INLINE_BREAK, " ")) + } else { + flush() + out.add(block) + } + } + flush() + return out.joinToString("\n\n") + } + + /** 按段落登记图片的列数:只有「整段都是图片」的段落才按网格排 */ + private fun registerGridColumns(text: String) { + if (!text.contains("![")) return + if (imageGridColumns.size > 256) imageGridColumns.clear() + text.split(PARAGRAPH_BREAK).forEach { block -> + val trimmed = block.trim() + if (!IMAGE_ONLY_BLOCK.matches(trimmed)) return@forEach + val urls = IMAGE_URL.findAll(trimmed).map { it.groupValues[1] }.toList() + if (urls.size < 2) return@forEach + val columns = columnsFor(urls.size) + urls.forEach { imageGridColumns[it] = columns } + } + } + + /** 与网页端网格一致:单图全宽、两张并排、三张以上三列 */ + private fun columnsFor(count: Int): Int = when { + count <= 1 -> 1 + count == 2 -> 2 + else -> 3 + } + + override fun getItemCount(): Int = items.size + + /** 系统认定的滑动阈值:位移超过它就算滚动,不当作点击 */ + private val touchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop + + /** + * 图片点击:按「图片实际占用的矩形」命中,不依赖 ClickableSpan。 + * + * 3.28 的做法是给每个图片 span 同区间叠一个透明 ClickableSpan,靠 LinkMovementMethod + * 转发点击。实测只有「由 resourceList 追加的图片」能点,正文里手写的 `![](...)` + * 点了没反应——两者 span 类型相同,差异在 span 的标记与 offset 落点,靠猜不可靠。 + * + * 这里换成直接命中判断:抬手时把坐标换算成 Layout 里的行与横向位置,再拿所有 + * AsyncDrawableSpan 的实际绘制区间比对。不关心 span 标记、不关心 offset 落在图片 + * 左端还是右端,也不需要 ClickableSpan,正文图片与追加图片走同一条路。 + * + * 返回 false 让 TextView 照常处理:文字链接仍由 LinkMovementMethod 打开, + * 普通区域仍交给卡片与 RecyclerView(滑动不受影响,滑动时父容器会拦走事件, + * 子 View 收到的是 CANCEL,不会误触发)。 + */ + private fun attachImageTaps(tv: TextView) { + var downX = 0f + var downY = 0f + tv.setOnTouchListener { _, event -> + // 选择模式下点卡片是勾选,不要再弹大图(否则勾选时容易误触) + if (selectionMode) return@setOnTouchListener false + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downX = event.x + downY = event.y + } + + MotionEvent.ACTION_UP -> { + val dx = event.x - downX + val dy = event.y - downY + if (dx * dx + dy * dy <= (touchSlop * touchSlop).toFloat()) { + val hit = imageAt(tv, event.x, event.y) + if (hit != null) { + // 地址先归一化:正文里的图常带 <…>、&、相对路径、空格, + // 这些都是 OkHttp 直接拒绝的写法,预览页会误报"加载失败" + val target = ImageUrl.normalize(context, hit.url) + // 顺手把卡片里已经解码好的位图交给预览页做兜底 + ImageMemoryCache.put(target, hit.bitmap) + if (target != hit.url) ImageMemoryCache.put(hit.url, hit.bitmap) + onImageClick(target) + return@setOnTouchListener true + } + } + } + } + false + } + } + + /** 命中结果:图片地址 + 卡片里已经解码好的位图(可能为 null) */ + private class ImageHit(val url: String, val bitmap: android.graphics.Bitmap?) + + /** 返回 (x, y) 处的图片;没命中图片返回 null */ + private fun imageAt(tv: TextView, x: Float, y: Float): ImageHit? { + val layout = tv.layout ?: return null + val text = tv.text as? Spanned ?: return null + if (text.isEmpty()) return null + + // 与 LinkMovementMethod 相同的坐标换算:先减内边距,再加滚动量 + val px = x - tv.totalPaddingLeft + tv.scrollX + val py = y - tv.totalPaddingTop + tv.scrollY + if (px < 0f || py < 0f) return null + + val line = layout.getLineForVertical(py.toInt()) + if (py < layout.getLineTop(line) || py > layout.getLineBottom(line)) return null + + // 用 ReplacementSpan 取:Markwon 的图片是 AsyncDrawableSpan 子类, + // 但别的渲染路径(HTML/图组)可能给的是普通 ImageSpan,一并覆盖 + val spans = text.getSpans(0, text.length, ReplacementSpan::class.java) + if (spans.isEmpty()) return null + // 允许 4dp 误差:图片外框与行边界常有 1~2px 的取整偏差 + val tolerance = 4 * tv.resources.displayMetrics.density + + for (span in spans) { + val start = text.getSpanStart(span) + val end = text.getSpanEnd(span) + if (start < 0 || end <= start) continue + val first = layout.getLineForOffset(start) + // 用 end - 1 判断末行:图片正好结束在换行处时,end 会落到下一行 + val last = layout.getLineForOffset(end - 1) + if (line < first || line > last) continue + + val left = if (line == first) layout.getPrimaryHorizontal(start) else layout.getLineLeft(line) + val layoutRight = + if (line == last) layout.getPrimaryHorizontal(end) else layout.getLineRight(line) + // 图片刚下载完、TextView 还没来得及重新排版时,Layout 里记的还是占位符宽度 + // (很小),而图片已经按真实宽度画出来了。用绘制宽度把命中区补上, + // 避免这几十毫秒的空窗期点了没反应。 + val drawnWidth = runCatching { + (span as? AsyncDrawableSpan)?.drawable?.bounds?.width() ?: 0 + }.getOrDefault(0) + val right = if (drawnWidth > 0) maxOf(layoutRight, left + drawnWidth) else layoutRight + if (px < minOf(left, right) - tolerance) continue + if (px > maxOf(left, right) + tolerance) continue + + val url = when (span) { + is AsyncDrawableSpan -> runCatching { span.drawable.destination }.getOrNull() + is ImageSpan -> span.source + else -> null + } + if (!url.isNullOrBlank()) { + // Markwon 的 AsyncDrawable 持有已解码的 Drawable(getResult),取出来给预览页做兜底 + val bitmap = runCatching { + val d = (span as? AsyncDrawableSpan)?.drawable?.result + (d as? android.graphics.drawable.BitmapDrawable)?.bitmap + }.getOrNull() + return ImageHit(url, bitmap) + } + } + return null + } + + /** 格式化对象只建一次(绑定在主线程串行执行),滚动更省 CPU */ + private val shortFormat = java.text.SimpleDateFormat("MM-dd", java.util.Locale.getDefault()) + private val fullFormat = + java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()) + + private fun formatDate(ts: Long): String { + if (ts <= 0) return "" + val seconds = if (ts > 1_000_000_000_000L) ts / 1000 else ts + val diff = System.currentTimeMillis() / 1000 - seconds + return when { + diff < 60 -> "刚刚" + diff < 3600 -> "${diff / 60}分钟前" + diff < 86_400 -> "${diff / 3600}小时前" + diff < 7 * 86_400 -> "${diff / 86_400}天前" + else -> shortFormat.format(java.util.Date(seconds * 1000)) + } + } + + /** Memos 左侧使用的完整时间:yyyy-MM-dd HH:mm:ss */ + private fun formatFullDate(ts: Long): String { + if (ts <= 0) return "" + val seconds = if (ts > 1_000_000_000_000L) ts / 1000 else ts + return fullFormat.format(java.util.Date(seconds * 1000)) + } +} + +/** 段落分隔:一个空行(兼容 CRLF 与行尾空白) */ +private val PARAGRAPH_BREAK = Regex("\\r?\\n[ \\t]*\\r?\\n") + +/** 整段都是图片(一张或多张,图片之间以空白分隔),没有其他文字 */ +private val IMAGE_ONLY_BLOCK = Regex("^(?:!\\[[^\\]]*\\]\\([^)\\s]+\\)\\s*)+$") + +/** 从段落文本中取图片地址(第 1 组) */ +private val IMAGE_URL = Regex("!\\[[^\\]]*\\]\\(([^)\\s]+)\\)") + +/** 段内换行(不含空行),图片段落里统一收成空格 */ +private val INLINE_BREAK = Regex("[ \\t]*\\r?\\n[ \\t]*") + +/** 把网格尺寸解析器装进 Markwon 配置 */ +private class GridImagePlugin( + private val columns: Map, + private val density: Float, +) : AbstractMarkwonPlugin() { + + private val resolver = GridImageSizeResolver(columns, density) + + override fun configureConfiguration(builder: MarkwonConfiguration.Builder) { + builder.imageSizeResolver(resolver) + } +} + +/** + * 多图横排的尺寸解析器。 + * + * Markwon 4.6.2 的 [ImageSizeResolverDef] 会把每张图都缩到画布宽度,因此同一段落里的 + * 多张图片必然各占一行。这里对「已登记列数」的图片改成按列均分:目标宽度 = + * (画布宽 − 图片间距) / 列数,高度按原始宽高比推算。 + * + * 尺寸在这里返回后会成为 AsyncDrawable 的 bounds,`AsyncDrawableSpan.getSize()` 与绘制 + * 都直接采用它(已核实 4.6.2 的实现),所以宽度就是最终显示宽度。 + * + * 未登记列数的图片(正文手写的 `![]()`)、单图、以及画布宽度未知的情况一律交回默认解析器, + * 行为与改动前完全一致。 + */ +private class GridImageSizeResolver( + private val columns: Map, + private val density: Float, +) : ImageSizeResolver() { + + private val fallback = ImageSizeResolverDef() + + override fun resolveImageSize(drawable: AsyncDrawable): Rect { + val count = columns[drawable.destination] ?: return fallback.resolveImageSize(drawable) + if (count < 2) return fallback.resolveImageSize(drawable) + + // 图片尚未下载完时先按默认逻辑排版,加载完成会再次回调(setResult → initBounds) + val result = drawable.result ?: return fallback.resolveImageSize(drawable) + val imageW = result.intrinsicWidth + val imageH = result.intrinsicHeight + val canvas = drawable.lastKnownCanvasWidth + if (imageW <= 0 || imageH <= 0 || canvas <= 0) { + return fallback.resolveImageSize(drawable) + } + + // 间距 6dp:网页端网格的视觉间隔约 4~8dp。图片之间还会夹一个空格字符, + // 所以这里只按目标间隔预留,另一半由空格提供 + val gap = (6 * density).toInt().coerceAtLeast(1) + // 每格再收 2dp:像素取整、系统字体放大后空格变宽,都可能让总宽度刚好超过 + // 画布,最后一张被挤到下一行(又退回竖排) + val cell = (canvas - gap * (count - 1)).toFloat() / count - 2 * density + if (cell < 1f) return fallback.resolveImageSize(drawable) + + val height = cell * imageH / imageW + return Rect( + 0, + 0, + cell.roundToInt().coerceAtLeast(1), + height.roundToInt().coerceAtLeast(1), + ) + } +} diff --git a/src/main/java/com/shitoucuo/postpad/HomeActivity.kt b/src/main/java/com/shitoucuo/postpad/HomeActivity.kt new file mode 100644 index 0000000..edcd37f --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/HomeActivity.kt @@ -0,0 +1,1311 @@ +package com.shitoucuo.postpad + +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Rect +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.ArrayAdapter +import android.widget.EditText +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 +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.core.content.ContextCompat +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * 首页:底部三菜单(信息 / 发布 / 邮件)。 + * 信息页顶部切换 RSS(默认)/ 文章 / Memos,筛选放在顶部; + * 文章可按站点筛选,邮件可按邮箱切换; + * 发布按钮向上展开「发布文章 / 发布微博」二级菜单,复用原有 MainActivity。 + */ +class HomeActivity : AppCompatActivity() { + + private lateinit var prefs: Prefs + private lateinit var adapter: FeedAdapter + private lateinit var recyclerView: RecyclerView + private lateinit var swipeRefresh: SwipeRefreshLayout + private lateinit var tvEmpty: TextView + private lateinit var progress: ProgressBar + private lateinit var etFilter: EditText + private lateinit var btnFilter: TextView + private lateinit var btnSourcePick: TextView + + private lateinit var feedTabs: LinearLayout + private lateinit var filterRow: LinearLayout + private lateinit var selectionBar: LinearLayout + private lateinit var btnSelectDone: TextView + private lateinit var btnSelectAll: TextView + private lateinit var btnMarkRead: TextView + private lateinit var btnDeleteSelected: TextView + private lateinit var tvSelectedCount: TextView + private lateinit var tabRss: TextView + private lateinit var tabArticle: TextView + private lateinit var tabMemo: TextView + private lateinit var navInfo: TextView + private lateinit var navMail: TextView + private lateinit var badgeInfo: TextView + private lateinit var badgeMail: TextView + + /** rss / article / memo / mail */ + private var current = TAB_RSS + private var filterMode = FILTER_ALL + private var keyword = "" + + /** + * 邮件页按邮箱筛选:空串表示「全部邮箱」。 + * + * 邮件页默认把**所有账户**的邮件合成一条时间线(卡片上标出邮箱名), + * 顶部这个筛选只在需要专注某个邮箱时用;它是纯本地过滤,切换不重新联网。 + */ + private var mailFilter = "" + private var searchJob: Job? = null + private var loadJob: Job? = null + + private var rssPage = 1 + private var rssPages = 1 + private var articlePage = 1 + private var articlePages = 1 + private var memoToken = "" + private var memoHasMore = false + + private val allItems = mutableListOf() + + companion object { + const val TAB_RSS = "rss" + const val TAB_ARTICLE = "article" + const val TAB_MEMO = "memo" + const val TAB_MAIL = "mail" + + private const val FILTER_ALL = 0 + private const val FILTER_UNREAD = 1 + private const val FILTER_READ = 2 + } + + override fun onCreate(savedInstanceState: Bundle?) { + prefs = Prefs(this) + // 站点 / 邮箱都只存在 sites、mail_accounts 两个 JSON 数组里,没有更早的单条格式, + // 因此不需要「老配置物化」这一步。原写法 siteCount()==0 && typechoReady 恒为假 + // (siteUrl 本身就取自数组,数组为空必然空串),属于死代码,已删除。 + val target = prefs.nightMode() + if (AppCompatDelegate.getDefaultNightMode() != target) { + AppCompatDelegate.setDefaultNightMode(target) + } + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_home) + + bindViews() + setupList() + setupTabs() + setupFilter() + setupSelection() + setupNav() + setupTheme() + + load(refresh = true) + // 角标独立于列表加载:这里先在后台统计,结果到了再显示 + refreshBadges() + } + + // ==================== 初始化 ==================== + + private fun bindViews() { + recyclerView = findViewById(R.id.recyclerView) + swipeRefresh = findViewById(R.id.swipeRefresh) + tvEmpty = findViewById(R.id.tvEmpty) + progress = findViewById(R.id.progressBar) + etFilter = findViewById(R.id.etFilter) + btnFilter = findViewById(R.id.btnFilter) + btnSourcePick = findViewById(R.id.btnSourcePick) + feedTabs = findViewById(R.id.feedTabs) + filterRow = findViewById(R.id.filterRow) + selectionBar = findViewById(R.id.selectionBar) + btnSelectDone = findViewById(R.id.btnSelectDone) + btnSelectAll = findViewById(R.id.btnSelectAll) + btnMarkRead = findViewById(R.id.btnMarkRead) + btnDeleteSelected = findViewById(R.id.btnDeleteSelected) + tvSelectedCount = findViewById(R.id.tvSelectedCount) + tabRss = findViewById(R.id.tabRss) + tabArticle = findViewById(R.id.tabArticle) + tabMemo = findViewById(R.id.tabMemo) + navInfo = findViewById(R.id.navInfo) + navMail = findViewById(R.id.navMail) + badgeInfo = findViewById(R.id.badgeInfo) + badgeMail = findViewById(R.id.badgeMail) + } + + private fun setupList() { + adapter = FeedAdapter( + context = this, + onOpen = { openItem(it) }, + onToggleRead = { toggleRead(it) }, + onImageClick = { url -> startActivity(ImagePreviewActivity.intent(this, url)) }, + ) + adapter.onSelectionChanged = { count -> renderSelection(count) } + recyclerView.layoutManager = LinearLayoutManager(this) + recyclerView.adapter = adapter + // 列表尺寸不随内容变化,跳过多余的整表测量 + recyclerView.setHasFixedSize(true) + recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { + override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) { + if (dy <= 0) return + val manager = rv.layoutManager as? LinearLayoutManager ?: return + val last = manager.findLastVisibleItemPosition() + if (last >= adapter.itemCount - 3 && adapter.itemCount > 0) loadMore() + } + }) + + // 下拉刷新是用户明确要求「来最新的」:邮件页重算邮件角标,其它页强制重扫 RSS 未读 + swipeRefresh.setOnRefreshListener { + load(refresh = true) + if (current == TAB_MAIL) refreshMailBadge() else refreshBadges(rssForce = true) + } + } + + private fun setupTabs() { + tabRss.setOnClickListener { switchTab(TAB_RSS) } + tabArticle.setOnClickListener { switchTab(TAB_ARTICLE) } + tabMemo.setOnClickListener { switchTab(TAB_MEMO) } + updateTabStyle() + } + + private fun setupFilter() { + btnSourcePick.setOnClickListener { showSourcePickPopup() } + btnFilter.setOnClickListener { + filterMode = (filterMode + 1) % 3 + btnFilter.text = when (filterMode) { + FILTER_UNREAD -> getString(R.string.filter_unread) + FILTER_READ -> getString(R.string.filter_read) + else -> getString(R.string.filter_all) + } + applyFilter() + } + etFilter.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} + override fun afterTextChanged(s: Editable?) { + keyword = s?.toString().orEmpty().trim() + searchJob?.cancel() + searchJob = lifecycleScope.launch { + delay(350) + load(refresh = true) + } + } + }) + } + + // ==================== 批量选择 / 删除 ==================== + + private fun keyOf(item: FeedItem): String = item.kind + "|" + item.id + + private fun setupSelection() { + // 操作栏没有「选择」入口:左滑卡片即进入选择,这里只提供退出 + btnSelectDone.setOnClickListener { adapter.exitSelection() } + btnSelectAll.setOnClickListener { + if (!adapter.selectionMode) return@setOnClickListener + adapter.setSelectAll(!adapter.allSelected()) + } + btnMarkRead.setOnClickListener { markSelectedRead() } + btnDeleteSelected.setOnClickListener { confirmDeleteSelected() } + renderSelection(0) + } + + /** 只有「信息」与「邮件」支持批量选择与删除(文章/动态没有对应的服务端语义) */ + private fun selectionAvailable(): Boolean = current == TAB_RSS || current == TAB_MAIL + + /** + * 刷新批量操作栏。 + * + * 这根操作栏平时不占位:左滑(或长按)激活选择后 [FeedAdapter.selectionMode] 为 true, + * 它才出现在筛选行下面;退出选择(点「完成」、取消掉最后一项、切页、批量操作完成) + * 之后再次隐藏,界面回到平常的样子。 + */ + private fun renderSelection(count: Int) { + val on = adapter.selectionMode && selectionAvailable() + selectionBar.visibility = if (on) View.VISIBLE else View.GONE + if (!on) return + btnSelectAll.isEnabled = adapter.itemCount > 0 + btnSelectAll.alpha = if (btnSelectAll.isEnabled) 1f else 0.45f + btnSelectAll.text = getString( + if (adapter.allSelected()) R.string.select_none else R.string.select_all + ) + tvSelectedCount.text = if (count > 0) getString(R.string.selected_count, count) else "" + listOf(btnMarkRead, btnDeleteSelected).forEach { btn -> + btn.isEnabled = count > 0 + btn.alpha = if (btn.isEnabled) 1f else 0.45f + } + } + + /** 当前选中的条目(按 key 回 allItems 里取,拿到的都是完整字段) */ + private fun selectedItems(): List { + val keys = adapter.selectedKeys() + if (keys.isEmpty()) return emptyList() + return allItems.filter { keys.contains(keyOf(it)) } + } + + /** 批量设为已读:邮件走 IMAP 补标,RSS 只写本地已读集(站点接口只读) */ + private fun markSelectedRead() { + if (!adapter.selectionMode) return + val targets = selectedItems().filter { !it.read } + if (targets.isEmpty()) { + toast(getString(R.string.mark_read_none)) + return + } + + if (current == TAB_MAIL) { + val mails = targets.mapNotNull { item -> + val uid = item.id.substringAfterLast('|').toLongOrNull() ?: return@mapNotNull null + val account = prefs.mailAccount(item.account) ?: return@mapNotNull null + account to uid + } + targets.forEach { item -> + val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id } + if (index >= 0) allItems[index] = allItems[index].copy(read = true) + } + mailUnread = (mailUnread - targets.size).coerceAtLeast(0) + renderBadges() + adapter.exitSelection() + applyFilter() + toast(getString(R.string.mark_read_done)) + lifecycleScope.launch { + var failed = 0 + withContext(Dispatchers.IO) { + // 本地缓存先落盘,保证下次进入仍是已读 + targets.forEach { item -> + val uid = item.id.substringAfterLast('|').toLongOrNull() ?: return@forEach + val account = prefs.mailAccount(item.account) ?: return@forEach + MailApi.markSeenLocal(prefs, account, uid, true) + } + } + for ((account, uid) in mails) { + val ok = runCatching { + withContext(Dispatchers.IO) { + MailApi.setSeen(prefs, account, uid, "INBOX", true) + } + }.isSuccess + if (!ok) failed++ + } + refreshMailBadge() + if (failed > 0) toast("有 $failed 封邮件没同步到服务器,下次同步会校正") + } + return + } + + targets.forEach { prefs.setRssRead(it.id, true) } + targets.forEach { item -> + val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id } + if (index >= 0) allItems[index] = allItems[index].copy(read = true) + } + rssUnread = (rssUnread - targets.size).coerceAtLeast(0) + RssApi.adjustUnread(-targets.size) + renderBadges() + adapter.exitSelection() + applyFilter() + toast(getString(R.string.mark_read_done)) + } + + private fun confirmDeleteSelected() { + if (!adapter.selectionMode) return + val targets = selectedItems() + if (targets.isEmpty()) return + val isMail = current == TAB_MAIL + AlertDialog.Builder(this) + .setTitle(getString(R.string.delete_selected_title, targets.size)) + .setMessage( + getString( + if (isMail) R.string.delete_selected_msg else R.string.delete_selected_msg_local + ) + ) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.delete) { _, _ -> performDelete(targets) } + .show() + } + + /** 批量删除:邮件的服务端删除与其它类型的本地隐藏分开跑,互不影响 */ + private fun performDelete(targets: List) { + adapter.exitSelection() + val mails = targets.filter { it.kind == TAB_MAIL } + val locals = targets.filter { it.kind != TAB_MAIL } + if (locals.isNotEmpty()) hideLocally(locals) + if (mails.isNotEmpty()) deleteMails(mails) + } + + /** + * RSS / 文章删除=本地隐藏。 + * + * 站点只提供查询接口(obsidianItems 等),没有删除条目的入口, + * 所以记下 id 后在列表与未读统计里都跳过,观感与删除一致。 + * key 带类型前缀,避免 RSS 的 id 与文章 cid 数值相同而互相误伤。 + */ + private fun hideLocally(targets: List) { + prefs.hideRssIds(targets.map { "${it.kind}:${it.id}" }) + val keys = targets.map { keyOf(it) }.toSet() + val removedUnread = targets.count { !it.read } + allItems.removeAll { keys.contains(keyOf(it)) } + if (removedUnread > 0) { + rssUnread = (rssUnread - removedUnread).coerceAtLeast(0) + RssApi.adjustUnread(-removedUnread) + renderBadges() + } + applyFilter() + toast(getString(R.string.deleted_count, targets.size)) + } + + /** 邮件删除:先乐观移除,再逐封 IMAP 删除;失败的整表读回缓存 */ + private fun deleteMails(targets: List) { + val keys = targets.map { keyOf(it) }.toSet() + val removedUnread = targets.count { !it.read } + allItems.removeAll { keys.contains(keyOf(it)) } + if (removedUnread > 0) { + mailUnread = (mailUnread - removedUnread).coerceAtLeast(0) + renderBadges() + } + applyFilter() + lifecycleScope.launch { + var failed = 0 + var lastError: String? = null + for (item in targets) { + val uid = item.id.substringAfterLast('|').toLongOrNull() ?: continue + val account = prefs.mailAccount(item.account) ?: continue + val error = runCatching { + withContext(Dispatchers.IO) { MailApi.delete(prefs, account, uid, "INBOX") } + }.exceptionOrNull() + // GoneException 表示服务器上本来就没有,等同删除成功 + if (error != null && error !is MailApi.GoneException) { + failed++ + if (lastError == null) lastError = error.message + } + } + refreshMailBadge() + if (failed > 0) { + toast(getString(R.string.delete_failed, failed, lastError ?: "未知错误")) + refreshMailList() + } else { + toast(getString(R.string.deleted_count, targets.size)) + } + } + } + + private fun setupNav() { + // 点击区域是整格(文字 + 角标),所以监听挂在包住它们的容器上 + findViewById(R.id.navInfoHost).setOnClickListener { switchTab(TAB_RSS) } + findViewById(R.id.navMailHost).setOnClickListener { switchTab(TAB_MAIL) } + findViewById(R.id.navPublish).setOnClickListener { showPublishSheet() } + findViewById(R.id.btnSettingsHome).setOnClickListener { + startActivity(Intent(this, SettingsActivity::class.java)) + } + } + + // ==================== 未读角标 ==================== + + /** 未读 RSS 条数(全部条目,不只是当前列表里已加载的这些) */ + private var rssUnread = 0 + + /** 全部邮箱的未读邮件数 */ + private var mailUnread = 0 + + private var rssBadgeJob: Job? = null + private var mailBadgeJob: Job? = null + + /** 统计任务序号:后发起的任务才能写结果,避免慢的旧任务把新结果覆盖掉 */ + private var rssBadgeSeq = 0 + private var mailBadgeSeq = 0 + + /** + * 统计并刷新两个角标。 + * + * 信息角标 = 未读 RSS 条数:本地只存「已读集合」,条目集合必须向服务端要, + * 所以这里按 100 条/页把条目扫一遍再相减——只数已加载的前 20 条会明显偏小。 + * 邮件角标 = 所有账户缓存里的未读邮件数,数据本来就在本地,直接数即可。 + */ + private fun refreshBadges(rssForce: Boolean = false) { + refreshRssBadge(rssForce) + refreshMailBadge() + } + + private fun refreshRssBadge(force: Boolean) { + if (!prefs.rssReady) { + rssBadgeJob?.cancel() + rssBadgeSeq++ + rssUnread = 0 + renderBadges() + return + } + val seq = ++rssBadgeSeq + rssBadgeJob?.cancel() + rssBadgeJob = lifecycleScope.launch { + val count = try { + withContext(Dispatchers.IO) { RssApi.unreadCount(prefs, force) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // 统计失败就保留上次的数字,不要让角标忽有忽无 + return@launch + } + if (seq != rssBadgeSeq) return@launch + rssUnread = count + renderBadges() + } + } + + private fun refreshMailBadge() { + if (prefs.mailAccounts().none { it.email.isNotBlank() }) { + mailBadgeJob?.cancel() + mailBadgeSeq++ + mailUnread = 0 + renderBadges() + return + } + val seq = ++mailBadgeSeq + mailBadgeJob?.cancel() + mailBadgeJob = lifecycleScope.launch { + // 缓存是磁盘 JSON,解析放 IO 线程;这里每次都重算,避免本地增减与服务端修正后的真实值脱节 + val count = try { + withContext(Dispatchers.IO) { + MailApi.cachedAll(prefs).count { !it.item.seen } + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + return@launch + } + if (seq != mailBadgeSeq) return@launch + mailUnread = count + renderBadges() + } + } + + private fun renderBadges() { + bindBadge(badgeInfo, rssUnread) + bindBadge(badgeMail, mailUnread) + } + + /** 0 隐藏;三位数收成 99+,避免把菜单文字挤走 */ + private fun bindBadge(view: TextView, count: Int) { + if (count <= 0) { + view.visibility = View.GONE + return + } + view.text = if (count > 99) "99+" else count.toString() + view.visibility = View.VISIBLE + } + + private fun setupTheme() { + val btn = findViewById(R.id.btnThemeHome) + btn.setImageResource(if (isNight()) + R.drawable.ic_sun else R.drawable.ic_moon) + btn.setOnClickListener { + // 防抖:连续快速点击会让 recreate 排队,产生新旧窗口叠加、卡片深浅混乱 + val now = System.currentTimeMillis() + if (now - lastThemeClick < 1000) return@setOnClickListener + lastThemeClick = now + val night = isNight() + prefs.darkMode = if (night) Prefs.MODE_LIGHT else Prefs.MODE_DARK + AppCompatDelegate.setDefaultNightMode( + if (night) AppCompatDelegate.MODE_NIGHT_NO else AppCompatDelegate.MODE_NIGHT_YES + ) + } + } + + /** + * 当前是否为深色:以 Activity 实际生效的 configuration 为准。 + * 不能用 prefs.nightMode() == MODE_NIGHT_YES —— 用户没手动切过时它是 + * FOLLOW_SYSTEM,系统深色下会误判成浅色,弹窗就会与页面不一致。 + */ + private fun isNight(): Boolean = + (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == + Configuration.UI_MODE_NIGHT_YES + + private var lastThemeClick = 0L + + /** + * 发布二级菜单:底部「发布」按钮上方展开的圆角面板, + * 两行纯文字(发布文章 / 发布微博),不用系统弹窗。 + */ + private fun showPublishSheet() { + // 背景统一交给 PopupWindow,与站点/筛选弹窗走同一套深浅色逻辑; + // panel 只保留 6dp 内边距,与背景的 6dp inset 对齐,文字不会压到圆角上。 + // 配色一次性取齐:背景与文字必须来自同一份资源,否则深浅色切换后 + // 会出现「深色背景 + 浅色模式黑字」的黑底黑字。 + val palette = Ui.popupPalette(this) + val panel = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(6), dp(6), dp(6), dp(6)) + } + + val options = listOf( + getString(R.string.publish_article), + getString(R.string.publish_memo), + ) + + options.forEachIndexed { index, title -> + val row = TextView(this).apply { + text = title + textSize = 15f + setTextColor(palette.text) + // 文字水平居中,左右留对称内边距,菜单不再偏宽 + gravity = Gravity.CENTER + setPadding(dp(12), 0, dp(12), 0) + minimumHeight = dp(46) + isClickable = true + isFocusable = true + val attrs = obtainStyledAttributes(intArrayOf(android.R.attr.selectableItemBackground)) + background = attrs.getDrawable(0) + attrs.recycle() + + setOnClickListener { + sheetPopup?.dismiss() + val intent = Intent(this@HomeActivity, MainActivity::class.java).apply { + putExtra(MainActivity.EXTRA_TAB, if (index == 0) "publish" else "memo") + } + startActivity(intent) + } + } + panel.addView(row) + + if (index < options.lastIndex) { + panel.addView(View(this).apply { + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, dp(1), + ).apply { setMargins(dp(12), dp(4), dp(12), dp(4)) } + setBackgroundColor(palette.divider) + }) + } + } + + // 宽度只比最宽的菜单文字稍宽一点,不再固定偏宽。 + // extraDp 必须覆盖:背景 inset 6dp×2 + panel padding 6dp×2 + 行内边距 12dp×2 = 48, + // 再留 16dp 余量。之前正好取 48,文字可用宽度等于文字宽度,一点裕度都没有, + // 四字标题在部分字体/字号缩放下会贴边甚至换行。 + val popupW = Ui.menuWidth( + this, options, textSizeSp = 15f, extraDp = 64, minDp = 120, maxDp = 240, + ) + panel.measure( + View.MeasureSpec.makeMeasureSpec(popupW - dp(12), View.MeasureSpec.EXACTLY), + View.MeasureSpec.UNSPECIFIED, + ) + val popupH = panel.measuredHeight + val popup = PopupWindow(panel, popupW, popupH, true).apply { + isOutsideTouchable = true + setBackgroundDrawable(palette.background()) + elevation = dp(10).toFloat() + } + sheetPopup = popup + + // 贴着底部「发布」按钮的正上方居中展开,留 5dp 呼吸间距 + val anchor = findViewById(R.id.navPublish) + val loc = IntArray(2) + val rootLoc = IntArray(2) + anchor.getLocationOnScreen(loc) + anchor.rootView.getLocationOnScreen(rootLoc) + val rootW = anchor.rootView.width + val x = (loc[0] - rootLoc[0] + (anchor.width - popupW) / 2) + .coerceIn(dp(12), (rootW - popupW - dp(12)).coerceAtLeast(dp(12))) + val y = loc[1] - rootLoc[1] - popupH - dp(5) + popup.showAtLocation(anchor.rootView, Gravity.TOP or Gravity.START, x, y) + } + + private var sheetPopup: PopupWindow? = null + + // ==================== 切换与加载 ==================== + + private fun switchTab(tab: String) { + if (current == tab) return + current = tab + filterMode = FILTER_ALL + btnFilter.text = getString(R.string.filter_all) + etFilter.setText("") + keyword = "" + // 换页时退出选择模式,避免带着上一页的选中状态 + if (adapter.selectionMode) adapter.exitSelection() + updateTabStyle() + load(refresh = true) + } + + private fun updateTabStyle() { + val isMail = current == TAB_MAIL + feedTabs.visibility = if (isMail) View.GONE else View.VISIBLE + // 批量操作栏平时不占位,只在选择模式下出现;切走后必须退出选择模式, + // 否则回来时列表是「点一下只勾选」的状态,点卡片打不开内容 + val canSelect = selectionAvailable() + adapter.selectionEnabled = canSelect + if (!canSelect && adapter.selectionMode) adapter.exitSelection() + renderSelection(adapter.selectedCount()) + // 文章页按站点筛选、邮件页按邮箱切换;其它页隐藏 + when (current) { + TAB_ARTICLE -> { + btnSourcePick.visibility = View.VISIBLE + btnSourcePick.text = prefs.siteLabel(prefs.typechoCurrent) + } + TAB_MAIL -> { + // 被筛选的邮箱可能已在设置里删除,这里自动退回「全部邮箱」 + if (mailFilter.isNotBlank() && prefs.mailAccount(mailFilter) == null) { + mailFilter = "" + } + btnSourcePick.visibility = View.VISIBLE + btnSourcePick.text = mailFilterLabel() + } + else -> btnSourcePick.visibility = View.GONE + } + navInfo.setTextColor(if (isMail) colorSecondary() else colorBrand()) + navMail.setTextColor(if (isMail) colorBrand() else colorSecondary()) + + val activeTab = when (current) { + TAB_ARTICLE -> tabArticle + TAB_MEMO -> tabMemo + else -> tabRss + } + listOf(tabRss, tabArticle, tabMemo).forEach { tab -> + val on = tab === activeTab + tab.setBackgroundResource(if (on) R.drawable.bg_segment_on else 0) + tab.setTextColor(if (on) colorText() else colorSecondary()) + } + } + + /** 邮件页顶部按钮文案:未筛选时显示「全部邮箱」 */ + private fun mailFilterLabel(): String { + if (mailFilter.isBlank()) return getString(R.string.mail_all_accounts) + return prefs.mailAccount(mailFilter)?.label ?: getString(R.string.mail_all_accounts) + } + + /** + * 站点 / 邮箱切换弹窗:与分类下拉同款样式,向上展开,文字居中、左右对称。 + * 文章页切站点会重新加载;邮件页只是本地筛选(数据本来就是全账户合并的)。 + */ + private fun showSourcePickPopup() { + if (current == TAB_MAIL) { + val accounts = prefs.mailAccounts().filter { it.email.isNotBlank() } + if (accounts.isEmpty()) return + val labels = ArrayList(accounts.size + 1) + labels.add(getString(R.string.mail_all_accounts)) + accounts.forEach { labels.add(it.label) } + val checked = if (mailFilter.isBlank()) 0 else { + val index = accounts.indexOfFirst { it.email.equals(mailFilter, true) } + if (index < 0) 0 else index + 1 + } + showPickList(labels, checked) { position -> + mailFilter = if (position <= 0) "" else accounts[position - 1].email + updateTabStyle() + applyFilter() + } + return + } + + val count = prefs.siteCount() + if (count == 0) return + val labels = (0 until count).map { prefs.siteLabel(it) } + showPickList(labels, prefs.typechoCurrent) { position -> + prefs.typechoCurrent = position + updateTabStyle() + load(refresh = true) + } + } + + /** 通用「单选下拉」:labels + 当前选中项 + 选中回调 */ + private fun showPickList(labels: List, checked: Int, onPick: (Int) -> Unit) { + val palette = Ui.popupPalette(this) + val currentIdx = checked.coerceIn(0, (labels.size - 1).coerceAtLeast(0)) + + val listView = ListView(this).apply { + adapter = object : ArrayAdapter( + this@HomeActivity, R.layout.item_dropdown_center, labels, + ) { + override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { + val view = super.getView(position, convertView, parent) as TextView + // 与背景同一套色板:先前这里取的是页面资源、背景取自另一份资源, + // 深色切浅色后就成了「深底 + 黑字」,未选中项完全看不见。 + view.setTextColor(if (position == currentIdx) palette.brand else palette.text) + return view + } + } + dividerHeight = 0 + setPadding(0, dp6(), 0, dp6()) + scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY + } + val listH = (labels.size * dp(46) + dp(12)).coerceAtMost(dp(320)) + val popupH = listH + dp(12) + // 宽度只比最宽的站点 / 邮箱名稍宽,不再与筛选按钮等宽 + val popupW = Ui.menuWidth( + this, labels, textSizeSp = 15f, extraDp = 52, minDp = 110, maxDp = 320, + ) + val popup = PopupWindow(listView, popupW, popupH, true).apply { + isOutsideTouchable = true + setBackgroundDrawable(palette.background()) + elevation = dp(8).toFloat() + } + listView.setOnItemClickListener { _, _, position, _ -> + popup.dismiss() + onPick(position) + } + val loc = IntArray(2) + val rootLoc = IntArray(2) + btnSourcePick.getLocationOnScreen(loc) + btnSourcePick.rootView.getLocationOnScreen(rootLoc) + // 以筛选按钮为中心展开,弹出框别顶出屏幕两边 + val x = (loc[0] - rootLoc[0] + (btnSourcePick.width - popupW) / 2) + .coerceIn(dp(8), (btnSourcePick.rootView.width - popupW - dp(8)).coerceAtLeast(dp(8))) + popup.showAtLocation( + btnSourcePick.rootView, + Gravity.TOP or Gravity.START, + x, + loc[1] - rootLoc[1] - popupH - dp(6), + ) + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + private fun dp6(): Int = dp(6) + + private fun colorBrand(): Int = getColor(R.color.brand) + private fun colorSecondary(): Int = getColor(R.color.text_secondary) + private fun colorText(): Int = getColor(R.color.text) + + private fun emptyText(): String = when (current) { + // 邮件要分两种:真的没配置,还是配置好了但最近没邮件。 + // 原先不论哪种都说"先到设置里填邮箱",配置正确的人会被误导成配置丢了。 + TAB_MAIL -> { + val accounts = prefs.mailAccounts().filter { it.ready } + if (accounts.isEmpty()) { + getString(R.string.feed_empty_mail) + } else { + getString(R.string.feed_empty_mail_none, accounts.maxOf { it.days }) + } + } + TAB_ARTICLE -> if (prefs.typechoReady) getString(R.string.feed_empty) else getString(R.string.feed_empty_article) + TAB_MEMO -> if (prefs.memosReady) getString(R.string.feed_empty) else getString(R.string.feed_empty_memo) + else -> if (prefs.rssReady) getString(R.string.feed_empty) else getString(R.string.feed_empty_rss) + } + + private fun load(refresh: Boolean) { + loadJob?.cancel() + rssPage = 1 + articlePage = 1 + memoToken = "" + allItems.clear() + adapter.submit(emptyList()) + tvEmpty.visibility = View.GONE + + if (refresh) swipeRefresh.isRefreshing = true else progress.visibility = View.VISIBLE + + loadJob = lifecycleScope.launch { + try { + val result = withContext(Dispatchers.IO) { + when (current) { + TAB_ARTICLE -> loadArticles() + TAB_MEMO -> loadMemos() + TAB_MAIL -> loadMails() + else -> loadRss() + } + } + allItems.clear() + allItems.addAll(result.first) + applyFilter() + // 邮件:缓存先渲染,这里再补一次增量同步 + if (current == TAB_MAIL) syncMailInBackground() + } catch (e: CancellationException) { + // 切页 / 刷新会取消旧任务,取消不是错误:静默退出, + // 否则「StandaloneCoroutine was cancelled」会挂满屏幕 + throw e + } catch (e: Exception) { + tvEmpty.text = "加载失败:${e.message ?: "未知错误"}" + tvEmpty.visibility = View.VISIBLE + } finally { + swipeRefresh.isRefreshing = false + progress.visibility = View.GONE + } + } + } + + /** 邮件后台增量同步:逐个账户只拉比缓存里最新 UID 更新的邮件,全部跑完再刷新列表 */ + private var mailSyncJob: Job? = null + + private fun syncMailInBackground() { + if (mailSyncJob?.isActive == true) return + // 快照一次账户列表:同步过程可能持续几十秒,中途用户改设置也不影响本轮 + val accounts = prefs.mailAccounts().filter { it.ready } + if (accounts.isEmpty()) return + val hadCache = allItems.isNotEmpty() + mailSyncJob = lifecycleScope.launch { + var added = 0 + var firstError: String? = null + for (account in accounts) { + try { + added += withContext(Dispatchers.IO) { MailApi.sync(prefs, account) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // 单个邮箱失败不影响其它邮箱:记下第一条错误,全部跑完再决定是否提示 + if (firstError == null) firstError = "${account.label}:${e.message ?: "同步失败"}" + } + } + // 同步会用服务端的已读标记校正缓存,角标必须跟着重算(不论当前在哪个页) + refreshMailBadge() + if (current != TAB_MAIL) return@launch + // 300 封邮件的 JSON 解析放 IO 线程,避免主线程卡顿 + val items = withContext(Dispatchers.IO) { + mailsToFeedItems(MailApi.cachedAll(prefs)) + } + allItems.clear() + allItems.addAll(items) + applyFilter() + if (added > 0) { + toast("收到 $added 封新邮件") + } else if (firstError != null && !hadCache && allItems.isEmpty()) { + tvEmpty.text = "邮件同步失败:$firstError" + tvEmpty.visibility = View.VISIBLE + } + } + } + + private suspend fun loadRss(): Pair, Boolean> { + if (!prefs.rssReady) return emptyList() to false + val result = RssApi.items(prefs, 1, keyword) + rssPage = result.page + rssPages = result.pages + memoHasMore = result.page < result.pages + return result.items.filterNot { prefs.isRssHidden("$TAB_RSS:${it.id}") }.map { item -> + FeedItem( + kind = TAB_RSS, + id = item.id.toString(), + title = item.title, + source = item.siteTitle.ifBlank { item.categoryName }, + date = parseDate(item.pubDate), + summary = item.excerpt, + link = item.link, + read = prefs.isRssRead(item.id.toString()), + content = item.excerpt, + ) + } to memoHasMore + } + + /** + * 文章搜索是客户端过滤(Typecho 插件接口没有 search 参数), + * 首页与「加载更多」必须走同一套规则,否则搜索后翻页会混进不匹配的文章。 + */ + private fun List.matchKeyword(): List = + if (keyword.isBlank()) this + else filter { it.title.contains(keyword, true) || it.digest.contains(keyword, true) } + + private suspend fun loadArticles(): Pair, Boolean> { + if (!prefs.typechoReady) return emptyList() to false + val result = TypechoApi.posts(prefs, 1) + articlePage = result.page + articlePages = result.pages + return result.posts.matchKeyword().filterNot { prefs.isRssHidden("$TAB_ARTICLE:${it.cid}") } + .map { post -> + FeedItem( + kind = TAB_ARTICLE, + id = post.cid.toString(), + title = post.title, + source = "${prefs.siteLabel(prefs.typechoCurrent)} · ${post.comments} 条评论", + date = post.created, + summary = post.digest, + link = post.permalink, + read = true, + ) + } to (result.page < result.pages) + } + + private suspend fun loadMemos(): Pair, Boolean> { + if (!prefs.memosReady) return emptyList() to false + val result = MemosApi.list(prefs, 30) + memoToken = result.nextPageToken + memoHasMore = result.nextPageToken.isNotEmpty() + val list = if (keyword.isBlank()) result.memos else + result.memos.filter { it.content.contains(keyword, true) } + return list.map { memo -> + FeedItem( + kind = TAB_MEMO, + id = memo.id, + title = "", + source = if (memo.pinned) "置顶" else "", + date = memo.createdTs, + summary = memo.content, + link = "", + read = true, + content = memo.content, + images = memo.images, + ) + } to memoHasMore + } + + /** 缓存的邮件 → 列表项(带关键词过滤);全部账户合并,卡片带上所属邮箱 */ + private fun mailsToFeedItems(mails: List): List { + val list = mails.filter { entry -> + val mail = entry.item + keyword.isBlank() || mail.subject.contains(keyword, true) || + mail.from.contains(keyword, true) || mail.fromName.contains(keyword, true) + } + return list.map { entry -> + val mail = entry.item + FeedItem( + kind = TAB_MAIL, + // UID 只在单个账户内唯一,卡片标识必须带上邮箱,否则两个账户的同一 UID 会互相顶掉 + id = "${entry.account.email}|${mail.uid}", + title = mail.subject, + source = mail.fromName.ifBlank { mail.from }, + date = mail.date, + summary = mail.snippet, + link = "", + read = mail.seen, + hasAttachment = mail.hasAttachment, + account = entry.account.email, + accountLabel = entry.account.label, + ) + } + } + + private suspend fun loadMails(): Pair, Boolean> { + if (prefs.mailAccounts().none { it.ready }) return emptyList() to false + // 打开即渲染本地缓存(全部账户合并),增量同步放到 syncMailInBackground 里后台做。 + // 缓存是磁盘 JSON,解析必须在 IO 线程,否则首帧会明显掉帧。 + val items = withContext(Dispatchers.IO) { mailsToFeedItems(MailApi.cachedAll(prefs)) } + return items to false + } + + /** + * 从缓存重读邮件列表并差量刷新。 + * + * 从详情页返回时用它代替 load():后者会清空列表重新加载、列表弹回顶部, + * 而这里只是把缓存的最新状态(已读、摘要、被删的邮件)同步到界面。 + */ + private fun refreshMailList() { + lifecycleScope.launch { + val items = withContext(Dispatchers.IO) { mailsToFeedItems(MailApi.cachedAll(prefs)) } + allItems.clear() + allItems.addAll(items) + applyFilter() + } + } + + /** 正在加载更多:防止滚动时重复触发,同一时刻只允许一个请求 */ + private var loadingMore = false + + private fun loadMore() { + if (loadingMore) return + val job = loadJob + if (job?.isActive == true) return + if (current == TAB_MAIL) return + if (current == TAB_RSS && rssPage >= rssPages) return + if (current == TAB_ARTICLE && articlePage >= articlePages) return + if (current == TAB_MEMO && memoToken.isEmpty()) return + + loadingMore = true + lifecycleScope.launch { + var lastError: Exception? = null + // 站点偶发拦截(WAF / 限频)时静默重试一次,不给用户报错; + // 成功时静默追加,不再弹提示——否则退出 APP 后 Toast 还会留在桌面上 + try { + for (attempt in 1..2) { + try { + val more = withContext(Dispatchers.IO) { fetchMore() } + allItems.addAll(more) + if (filterMode == FILTER_ALL) adapter.append(more) else applyFilter() + return@launch + } catch (e: Exception) { + if (e is CancellationException) throw e + lastError = e + if (attempt == 1) delay(1200) + } + } + toast("加载更多失败:${friendlyError(lastError)}") + } finally { + loadingMore = false + } + } + } + + /** 拉下一页(loadMore 专用,失败可整体重试) */ + private suspend fun fetchMore(): List = withContext(Dispatchers.IO) { + when (current) { + TAB_RSS -> { + val result = RssApi.items(prefs, rssPage + 1, keyword) + rssPage = result.page + rssPages = result.pages + result.items.filterNot { prefs.isRssHidden("$TAB_RSS:${it.id}") }.map { item -> + 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) + } + } + TAB_ARTICLE -> { + val result = TypechoApi.posts(prefs, articlePage + 1) + articlePage = result.page + articlePages = result.pages + result.posts.matchKeyword().filterNot { prefs.isRssHidden("$TAB_ARTICLE:${it.cid}") } + .map { post -> + FeedItem(TAB_ARTICLE, post.cid.toString(), post.title, + prefs.siteLabel(prefs.typechoCurrent), post.created, + post.digest, post.permalink, true) + } + } + else -> { + val result = MemosApi.list(prefs, 30, memoToken) + memoToken = result.nextPageToken + result.memos.map { memo -> + FeedItem(TAB_MEMO, memo.id, "", "", memo.createdTs, + memo.content, "", true, memo.content, images = memo.images) + } + } + } + } + + /** WAF 拦截页 / HTML 响应转成人话,不再把整页文字甩给用户 */ + private fun friendlyError(e: Exception?): String { + val raw = e?.message ?: "未知错误" + return if (raw.contains("拦截") || raw.contains("<") || raw.contains("html", true) || + raw.contains("waf", true) || raw.contains("安全") + ) "站点防护拦截了请求,稍后再试" else raw + } + + private fun applyFilter() { + // 邮件页只在「全部邮箱」时给卡片标注邮箱名:筛了某个邮箱后每张都重复同一个名字 + adapter.showMailAccount = current != TAB_MAIL || mailFilter.isBlank() + + var list = when (filterMode) { + FILTER_UNREAD -> allItems.filter { !it.read } + FILTER_READ -> allItems.filter { it.read } + else -> allItems + } + // 邮件页还可按邮箱再筛一层(纯本地过滤,不动网络) + if (current == TAB_MAIL && mailFilter.isNotBlank()) { + list = list.filter { it.account.equals(mailFilter, true) } + } + // 差量刷新:只有已读状态变化时不会把列表弹回顶部 + adapter.update(list) + if (adapter.selectionMode) renderSelection(adapter.selectedCount()) + if (list.isEmpty()) { + tvEmpty.text = if (allItems.isEmpty()) emptyText() else "没有符合筛选条件的内容" + tvEmpty.visibility = View.VISIBLE + } else { + tvEmpty.visibility = View.GONE + } + } + + // ==================== 交互 ==================== + + private fun openItem(item: FeedItem) { + when (item.kind) { + // 卡片 id 形如 "邮箱|UID":必须带上账户,否则会拿当前账户去连服务端 + TAB_MAIL -> { + val uid = item.id.substringAfterLast('|').toLongOrNull() ?: 0L + // 点开即已读:列表与缓存先本地生效,服务端标记在后台补 + if (markLocalRead(item)) { + markMailSeenLocally(item, uid) + markMailSeenOnServer(item, uid) + } + MailDetailActivity.open(this, item.account, uid, "INBOX", item.title) + } + TAB_ARTICLE -> ReaderActivity.open( + this, ReaderActivity.KIND_ARTICLE, item.id, item.title, + item.source, item.date, "", item.link + ) + TAB_MEMO -> { + // 卡片已直接显示全文,不再进阅读内页 + } + else -> { + // 点开即已读:先写本地已读集,再原地刷新这一条(不重建列表,滚动位置不动) + prefs.setRssRead(item.id, true) + if (markLocalRead(item)) RssApi.adjustUnread(-1) + ReaderActivity.open( + this, ReaderActivity.KIND_RSS, item.id, item.title, + item.source, item.date, item.content, item.link + ) + } + } + } + + /** + * 把列表里的一条标为已读(纯内存 + 原地刷新),返回是否真的从「未读」变成了「已读」。 + * + * 不用 applyFilter():那会按筛选条件重建整张表,未读筛选下点开的条目会立刻消失、 + * 其它条目位置全变,返回首页时找不到刚才读的那条。这里只刷新那一行。 + */ + private fun markLocalRead(item: FeedItem): Boolean { + if (item.read) return false + val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id } + if (index < 0) return false + val updated = allItems[index].copy(read = true) + allItems[index] = updated + adapter.updateItem(updated) + when (item.kind) { + TAB_RSS -> if (rssUnread > 0) { + rssUnread-- + renderBadges() + } + TAB_MAIL -> if (mailUnread > 0) { + mailUnread-- + renderBadges() + } + } + return true + } + + /** 本地缓存先记成已读:列表、角标、下次进入都一致,不必等服务端往返 */ + private fun markMailSeenLocally(item: FeedItem, uid: Long) { + if (uid <= 0) return + val account = prefs.mailAccount(item.account) ?: return + lifecycleScope.launch(Dispatchers.IO) { + MailApi.markSeenLocal(prefs, account, uid, true) + } + } + + /** + * 服务端补标已读。 + * + * 刻意不因为失败而把界面改回未读:用户确实点开看过了, + * 回滚只会让列表和实际阅读行为对不上;缓存已按已读记录, + * 服务端状态会在下一次同步时以服务端为准校正(届时才可能回到未读)。 + */ + private fun markMailSeenOnServer(item: FeedItem, uid: Long) { + if (uid <= 0) return + val account = prefs.mailAccount(item.account) ?: return + lifecycleScope.launch { + val result = runCatching { + withContext(Dispatchers.IO) { + MailApi.setSeen(prefs, account, uid, "INBOX", true) + } + } + val error = result.exceptionOrNull() ?: return@launch + if (error is MailApi.GoneException) { + toast(error.message ?: "邮件已不存在") + load(refresh = true) + return@launch + } + toast("已标为已读,但同步到邮箱失败:${error.message ?: "未知错误"}") + } + } + + private fun toggleRead(item: FeedItem) { + // 列表持有的是不可变 FeedItem,改完必须替换 allItems 里那一条, + // 否则 applyFilter() 仍按旧状态过滤("标为未读"后不会消失) + val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id } + if (index < 0) return + val target = !item.read + + when (item.kind) { + TAB_RSS -> { + prefs.setRssRead(item.id, target) + allItems[index] = allItems[index].copy(read = target) + applyFilter() + // 角标同步挪一格,并与统计缓存对齐,切页回来不会跳 + val delta = if (target) -1 else 1 + rssUnread = (rssUnread + delta).coerceAtLeast(0) + RssApi.adjustUnread(delta) + renderBadges() + } + + TAB_MAIL -> { + val uid = item.id.substringAfterLast('|').toLongOrNull() ?: return + // 必须按卡片记录的邮箱去连:列表是所有账户合并的, + // 拿「当前账户」会把已读标到另一个邮箱里同 UID 的邮件上 + val account = prefs.mailAccount(item.account) + if (account == null) { + toast("这个邮箱的配置已被删除") + return + } + // 先本地生效,再后台同步到 IMAP,失败时回滚并提示 + allItems[index] = allItems[index].copy(read = target) + applyFilter() + mailUnread = (mailUnread + if (target) -1 else 1).coerceAtLeast(0) + renderBadges() + lifecycleScope.launch { + val result = runCatching { + withContext(Dispatchers.IO) { + MailApi.setSeen(prefs, account, uid, "INBOX", target) + } + } + val error = result.exceptionOrNull() + if (error == null) { + // 服务端已同步:以缓存里的真实状态重算角标 + refreshMailBadge() + return@launch + } + if (error is MailApi.GoneException) { + // 服务端已没有这封邮件:缓存已被清理,整表重读让它从列表消失 + toast(error.message ?: "邮件已不存在") + load(refresh = true) + refreshMailBadge() + return@launch + } + val current = allItems.indexOfFirst { + it.kind == TAB_MAIL && it.id == item.id + } + if (current >= 0) { + allItems[current] = allItems[current].copy(read = item.read) + applyFilter() + } + refreshMailBadge() + toast("同步到邮箱失败,已还原状态:${error.message ?: "未知错误"}") + } + } + + else -> toast("仅 RSS 与邮件支持切换已读状态") + } + } + + /** 日期解析格式按线程缓存,避免每条 RSS 都新建 SimpleDateFormat */ + private val dateFormats = object : ThreadLocal>() { + override fun initialValue(): List = listOf( + java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US), + java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.US), + java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", java.util.Locale.US), + java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US), + java.text.SimpleDateFormat("yyyy-MM-dd", java.util.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 + } + + /** 页面已退出时不再弹提示,避免 Toast 残留在桌面上 */ + private fun toast(text: String) { + if (isFinishing || isDestroyed) return + Toast.makeText(this, text, Toast.LENGTH_SHORT).show() + } + + override fun onResume() { + super.onResume() + val btn = findViewById(R.id.btnThemeHome) + btn.setImageResource(if (prefs.nightMode() == AppCompatDelegate.MODE_NIGHT_YES) + R.drawable.ic_sun else R.drawable.ic_moon) + // 从阅读页 / 邮件详情 / 设置页回来时整表按当前主题重刷: + // 绑定时逐项重设配色(FeedAdapter 内部完成),任何来源的卡片都不会深浅混排 + recyclerView.recycledViewPool.clear() + adapter.refreshTheme() + // 设置页可能改过站点 / 邮箱名称,刷新一次顶部来源标签 + updateTabStyle() + // 邮件详情里删了信、回填了摘要或已读过,回来按缓存差量刷新(不重建,滚动位置不动) + if (MailDetailActivity.consumeDataChanged() && current == TAB_MAIL) { + refreshMailList() + refreshMailBadge() + } + } +} diff --git a/src/main/java/com/shitoucuo/postpad/Http.kt b/src/main/java/com/shitoucuo/postpad/Http.kt new file mode 100644 index 0000000..b28635d --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/Http.kt @@ -0,0 +1,48 @@ +package com.shitoucuo.postpad + +import android.content.Context +import okhttp3.Cache +import okhttp3.OkHttpClient +import java.io.File +import java.util.concurrent.TimeUnit + +/** + * 全局共享的 OkHttpClient:连接池、线程池只保留一份。 + * 各 API 用 newWith() 微调超时,底层仍复用同一连接池,减少并发开销。 + */ +object Http { + + val client: OkHttpClient = OkHttpClient.Builder() + .connectTimeout(20, TimeUnit.SECONDS) + .writeTimeout(180, TimeUnit.SECONDS) + .readTimeout(120, TimeUnit.SECONDS) + .build() + + /** 在共享实例基础上调整超时;连接池与调度线程池与全局共用 */ + fun newWith(connect: Long, write: Long, read: Long, unit: TimeUnit): OkHttpClient = + client.newBuilder() + .connectTimeout(connect, unit) + .writeTimeout(write, unit) + .readTimeout(read, unit) + .build() + + @Volatile + private var cachedImageClient: OkHttpClient? = null + + /** + * 图片专用客户端:在共享连接池上加 64MB 磁盘缓存。 + * + * 图床/资源响应带 `Cache-Control: public, max-age=31536000`(一年)。没有磁盘缓存时, + * 列表每次复用卡片都会把几 MB 的原图重新下载一遍——滚动一趟就是几十 MB 流量。 + * + * 必须是**单例**:OkHttp 的 Cache 不允许两个实例指向同一目录(日志文件会互相踩), + * 而列表缩略图与大图预览用的是同一批 URL,共用一份缓存命中率也最高。 + */ + fun imageClient(context: Context): OkHttpClient = + cachedImageClient ?: synchronized(this) { + cachedImageClient ?: run { + val cache = Cache(File(context.cacheDir, "image-cache"), 64L * 1024 * 1024) + client.newBuilder().cache(cache).build().also { cachedImageClient = it } + } + } +} diff --git a/src/main/java/com/shitoucuo/postpad/ImageCache.kt b/src/main/java/com/shitoucuo/postpad/ImageCache.kt new file mode 100644 index 0000000..9284e0c --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/ImageCache.kt @@ -0,0 +1,71 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.graphics.Bitmap +import android.util.LruCache + +/** + * 列表与预览页共享的位图缓存。 + * + * 点开大图时,卡片里的那张图其实**已经解码在内存里**(Markwon 的 AsyncDrawable 持有它)。 + * 预览页先拿这张立即显示,再去请求原图;网络被拦、地址被改写、图床限流时, + * 至少不会只剩一行「加载失败」,用户点开的图一定能看到。 + * 上限 8MB,只存最近看过的几张,不会长期占内存。 + */ +object ImageMemoryCache { + + private val cache = object : LruCache(8 * 1024 * 1024) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount + } + + fun put(url: String, bitmap: Bitmap?) { + if (url.isBlank() || bitmap == null || bitmap.isRecycled) return + cache.put(url, bitmap) + } + + fun get(url: String): Bitmap? { + if (url.isBlank()) return null + val bitmap = cache.get(url) ?: return null + return if (bitmap.isRecycled) null else bitmap + } +} + +/** + * 图片地址归一化。 + * + * Markdown 正文里的图片地址由用户手写,形态比 resourceList 里的 externalLink 杂得多: + * 常见 `` 包裹、`&` 实体、协议相对 `//host/a.jpg`、Memos 的相对路径 + * `/file/xxx.jpg`、以及地址里带空格。这些写法 OkHttp 直接拒绝(抛 IllegalArgumentException), + * 表现为「点了图进去提示加载失败」,而列表里 Markwon 用的是另一套解析,所以图又能显示。 + * 统一在这里收敛成可直接请求的绝对地址。 + */ +object ImageUrl { + + fun normalize(context: Context, raw: String): String { + var s = raw.trim() + // CommonMark 允许 包一层,用于地址里带空格的情况 + if (s.length > 2 && s.startsWith("<") && s.endsWith(">")) { + s = s.substring(1, s.length - 1).trim() + } + // Markdown 正文里 & 常被转义成实体 + s = s.replace("&", "&") + + if (s.startsWith("data:", true)) return s + if (s.startsWith("//")) s = "https:$s" + + // Memos 自带资源的相对路径,按配置的站点补全 + if (s.startsWith("/")) { + val base = runCatching { Prefs(context).memosUrl }.getOrNull().orEmpty().trimEnd('/') + if (base.isNotEmpty()) s = base + s + } + if (s.startsWith("file://") || s.startsWith("content://")) return s + + if (!s.contains("://")) { + // 只可能是漏了协议;不像域名就原样返回,让上层给出明确错误 + if (!s.contains('.')) return s + s = "https://$s" + } + // OkHttp 会拒绝含空格的 URL;图片地址里的空格按 RFC 3986 编码即可 + return s.replace(" ", "%20") + } +} diff --git a/src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt b/src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt new file mode 100644 index 0000000..dc97391 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt @@ -0,0 +1,425 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Color +import android.graphics.Matrix +import android.graphics.RectF +import android.net.Uri +import android.os.Bundle +import android.util.TypedValue +import android.view.GestureDetector +import android.view.Gravity +import android.view.MotionEvent +import android.view.ScaleGestureDetector +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.ProgressBar +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okhttp3.Request + +/** + * 大图预览:黑底、双指缩放、放大后单指拖动、双击在「适应屏幕 / 2.5 倍」之间切换, + * 单击图片或点右上角 × 退出。 + * + * 界面用代码搭建:整页只有一张图和两个状态提示,写成布局文件反而多几个文件要维护。 + * + * 取图分三层,任何一层成功就显示,避免"点开只剩一行加载失败": + * 1. [ImageMemoryCache]:卡片上那张图已经解码在内存里,点开立即显示; + * 2. 原图下载:[Http.imageClient] 与列表共用 64MB 磁盘缓存,列表里下过的图直接命中; + * 3. 地址归一化 + 退一步的请求头(浏览器 UA + Referer):正文里手写的图片地址 + * 常带 `<…>`、`&`、相对路径、空格,或图床按 Referer 防盗链,直接请求会失败。 + */ +class ImagePreviewActivity : AppCompatActivity() { + + companion object { + private const val EXTRA_URL = "url" + + fun intent(context: Context, url: String): Intent = + Intent(context, ImagePreviewActivity::class.java).putExtra(EXTRA_URL, url) + } + + private lateinit var imageView: ZoomableImageView + private lateinit var progress: ProgressBar + private lateinit var errorView: TextView + + /** 原始地址(点卡片传过来的)与归一化后用于请求的地址 */ + private var rawUrl: String = "" + private var url: String = "" + + /** 当前正在显示的位图:用来判断原图是否比兜底图更清晰 */ + private var shown: Bitmap? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + rawUrl = intent.getStringExtra(EXTRA_URL).orEmpty().trim() + if (rawUrl.isBlank()) { + finish() + return + } + url = ImageUrl.normalize(this, rawUrl) + + // 看图页固定黑底,状态栏与导航栏一并压黑,避免白边割裂画面 + window.statusBarColor = Color.BLACK + window.navigationBarColor = Color.BLACK + + val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) } + + imageView = ZoomableImageView(this).apply { + layoutParams = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ) + onSingleTap = { finish() } + visibility = View.INVISIBLE + } + + progress = ProgressBar(this).apply { + layoutParams = FrameLayout.LayoutParams(dp(36), dp(36), Gravity.CENTER) + indeterminateDrawable?.setTint(Color.WHITE) + } + + errorView = TextView(this).apply { + setTextColor(Color.WHITE) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f) + gravity = Gravity.CENTER + setPadding(dp(24), dp(16), dp(24), dp(16)) + layoutParams = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + Gravity.CENTER, + ) + visibility = View.GONE + setOnClickListener { load() } + } + + val close = TextView(this).apply { + text = getString(R.string.image_preview_close_glyph) + contentDescription = getString(R.string.image_preview_close) + setTextColor(Color.WHITE) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f) + gravity = Gravity.CENTER + setPadding(dp(16), dp(10), dp(16), dp(10)) + layoutParams = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + Gravity.TOP or Gravity.END, + ).apply { + topMargin = dp(28) + rightMargin = dp(10) + } + setOnClickListener { finish() } + } + + root.addView(imageView) + root.addView(progress) + root.addView(errorView) + root.addView(close) + setContentView(root) + + load() + } + + private fun load() { + // 第一层:卡片里已经解码好的那张,先摆上去,用户点开立刻有画面 + val fallback = ImageMemoryCache.get(url) ?: ImageMemoryCache.get(rawUrl) + if (fallback != null) { + show(fallback) + progress.visibility = View.GONE + } else { + progress.visibility = View.VISIBLE + errorView.visibility = View.GONE + imageView.visibility = View.INVISIBLE + } + + lifecycleScope.launch { + val result = withContext(Dispatchers.IO) { runCatching { fetch(url) } } + if (isFinishing || isDestroyed) return@launch + progress.visibility = View.GONE + val bitmap = result.getOrNull() + if (bitmap != null) { + val current = shown + // 兜底图已经显示时,只在原图更清晰、且用户还没开始缩放的情况下替换, + // 否则会把正在看的位置与缩放比例重置掉 + val sharper = current == null || bitmap.byteCount > current.byteCount + if (current == null || (sharper && !imageView.transformed)) { + show(bitmap) + } + ImageMemoryCache.put(url, bitmap) + errorView.visibility = View.GONE + } else if (shown == null) { + val reason = result.exceptionOrNull()?.message.orEmpty() + errorView.text = if (reason.isBlank()) { + getString(R.string.image_preview_failed) + } else { + getString(R.string.image_preview_failed) + "\n" + reason + } + errorView.visibility = View.VISIBLE + } + } + } + + private fun show(bitmap: Bitmap) { + shown = bitmap + imageView.visibility = View.VISIBLE + imageView.setBitmap(bitmap) + } + + /** 下载并按目标尺寸采样解码,避免几千万像素的原图直接 OOM */ + private fun fetch(address: String): Bitmap { + val bytes = fetchBytes(address) + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) { + throw IllegalStateException("图片内容无法解析(可能被拦截或已失效)") + } + + val metrics = resources.displayMetrics + // 采样目标是屏幕长边:保证放大时仍有细节,同时把内存压在十几 MB 以内 + val target = maxOf(metrics.widthPixels, metrics.heightPixels) + val options = BitmapFactory.Options().apply { + inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, target) + inPreferredConfig = Bitmap.Config.ARGB_8888 + } + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) + ?: throw IllegalStateException("图片解码失败") + } + + /** + * 取原始字节。失败时抛出带原因的消息(直接显示给用户,便于对症下药): + * - `data:` / `content:` / `file:` 走本地解析; + * - http(s) 先按普通请求,失败再换浏览器 UA + Referer 重试一次(防盗链最常见的拦法)。 + */ + private fun fetchBytes(address: String): ByteArray { + if (address.startsWith("data:", true)) return dataUriBytes(address) + if (address.startsWith("content://") || address.startsWith("file://")) { + return contentResolver.openInputStream(Uri.parse(address))?.use { it.readBytes() } + ?: throw IllegalStateException("读不到本地图片") + } + + var reason = "图片地址无效:$address" + for (attempt in 0 until 2) { + val request = Request.Builder() + .url(address) + .header("Accept", "image/*,*/*;q=0.8") + .apply { + if (attempt == 0) { + header("User-Agent", "PostPad") + } else { + header("User-Agent", RssApi.UA_BROWSER) + refererOf(address)?.let { header("Referer", it) } + } + } + .build() + try { + Http.imageClient(this).newCall(request).execute().use { response -> + if (!response.isSuccessful) { + reason = "HTTP ${response.code}" + return@use + } + val type = response.header("Content-Type").orEmpty().lowercase() + if (type.startsWith("text/") || type.contains("html")) { + reason = "服务器返回的是网页($type)" + return@use + } + val body = response.body ?: run { + reason = "响应为空" + return@use + } + // inline use:这里是直接返回整个函数的字节 + return body.bytes() + } + } catch (e: Exception) { + reason = e.message ?: e.javaClass.simpleName + } + } + throw IllegalStateException(reason) + } + + /** data:image/png;base64,… 这类内联图片 */ + private fun dataUriBytes(uri: String): ByteArray { + val comma = uri.indexOf(',') + if (comma < 0) throw IllegalStateException("内联图片地址无效") + val meta = uri.substring(5, comma) + val payload = uri.substring(comma + 1) + return if (meta.contains("base64", true)) { + android.util.Base64.decode(payload, android.util.Base64.DEFAULT) + } else { + java.net.URLDecoder.decode(payload, "UTF-8").toByteArray() + } + } + + /** 防盗链常校验 Referer:取图片所在站点的根地址 */ + private fun refererOf(address: String): String? = runCatching { + val parsed = java.net.URL(address) + val host = parsed.host ?: return@runCatching null + "${parsed.protocol}://$host/" + }.getOrNull() + + private fun sampleSize(width: Int, height: Int, target: Int): Int { + var sample = 1 + while (width / (sample * 2) >= target && height / (sample * 2) >= target) { + sample *= 2 + } + return sample + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + /** + * 简易可缩放图片:只依赖 Matrix 与系统手势检测器,不引第三方手势库。 + * 缩放范围从「适应屏幕」到其 4 倍;放大后单指拖动,松手时把图拉回可视区域。 + */ + private class ZoomableImageView(context: Context) : + androidx.appcompat.widget.AppCompatImageView(context) { + + var onSingleTap: (() -> Unit)? = null + + private val transform = Matrix() + private var baseScale = 1f + private var currentScale = 1f + private var lastX = 0f + private var lastY = 0f + private var multiTouch = false + + /** 用户是否缩放/拖动过:用于决定原图到达时要不要替换画面 */ + var transformed = false + private set + + private val scaleDetector = ScaleGestureDetector( + context, + object : ScaleGestureDetector.SimpleOnScaleGestureListener() { + override fun onScale(detector: ScaleGestureDetector): Boolean { + applyScale(currentScale * detector.scaleFactor, detector.focusX, detector.focusY) + return true + } + }, + ) + + private val tapDetector = GestureDetector( + context, + object : GestureDetector.SimpleOnGestureListener() { + override fun onSingleTapConfirmed(e: MotionEvent): Boolean { + // 双指缩放结束后系统仍可能补一个单击,这里挡掉,避免缩放完直接被关掉 + if (!multiTouch) onSingleTap?.invoke() + return true + } + + override fun onDoubleTap(e: MotionEvent): Boolean { + val target = if (currentScale > baseScale * 1.5f) baseScale else baseScale * 2.5f + applyScale(target, e.x, e.y) + return true + } + }, + ) + + init { + scaleType = ScaleType.MATRIX + } + + fun setBitmap(bitmap: Bitmap) { + transformed = false + setImageBitmap(bitmap) + // 等一帧再算:此刻 width/height 可能还是 0 + post { fitToView() } + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + if (drawable != null) fitToView() + } + + /** 按控件尺寸等比缩放并居中,作为缩放下限 */ + private fun fitToView() { + val d = drawable ?: return + val viewW = width.toFloat() + val viewH = height.toFloat() + val imageW = d.intrinsicWidth.toFloat() + val imageH = d.intrinsicHeight.toFloat() + if (viewW <= 0f || viewH <= 0f || imageW <= 0f || imageH <= 0f) return + + val scale = minOf(viewW / imageW, viewH / imageH) + baseScale = scale + currentScale = scale + transform.reset() + transform.postScale(scale, scale) + transform.postTranslate((viewW - imageW * scale) / 2f, (viewH - imageH * scale) / 2f) + imageMatrix = transform + } + + private fun applyScale(target: Float, focusX: Float, focusY: Float) { + if (currentScale <= 0f) return + val clamped = target.coerceIn(baseScale, baseScale * 4f) + val factor = clamped / currentScale + if (factor == 1f) { + // 已经到边界:回弹到初始状态,避免反复缩放积累误差 + if (clamped <= baseScale) fitToView() + return + } + if (clamped != baseScale) transformed = true + currentScale = clamped + transform.postScale(factor, factor, focusX, focusY) + imageMatrix = transform + if (clamped <= baseScale) fitToView() + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + scaleDetector.onTouchEvent(event) + tapDetector.onTouchEvent(event) + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + multiTouch = false + lastX = event.x + lastY = event.y + } + + MotionEvent.ACTION_POINTER_DOWN -> { + multiTouch = true + transformed = true + } + + MotionEvent.ACTION_MOVE -> { + if (!scaleDetector.isInProgress && currentScale > baseScale) { + transform.postTranslate(event.x - lastX, event.y - lastY) + imageMatrix = transform + lastX = event.x + lastY = event.y + transformed = true + } + } + + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> settle() + } + return true + } + + /** 松手后把图片拉回可视范围,避免拖出屏幕后找不回来 */ + private fun settle() { + val d = drawable ?: return + val rect = RectF(0f, 0f, d.intrinsicWidth.toFloat(), d.intrinsicHeight.toFloat()) + transform.mapRect(rect) + val viewW = width.toFloat() + val viewH = height.toFloat() + var dx = 0f + var dy = 0f + if (rect.width() <= viewW) dx = (viewW - rect.width()) / 2f - rect.left + else if (rect.left > 0f) dx = -rect.left + else if (rect.right < viewW) dx = viewW - rect.right + if (rect.height() <= viewH) dy = (viewH - rect.height()) / 2f - rect.top + else if (rect.top > 0f) dy = -rect.top + else if (rect.bottom < viewH) dy = viewH - rect.bottom + if (dx != 0f || dy != 0f) { + transform.postTranslate(dx, dy) + imageMatrix = transform + } + } + } +} diff --git a/src/main/java/com/shitoucuo/postpad/ImageUtils.kt b/src/main/java/com/shitoucuo/postpad/ImageUtils.kt new file mode 100644 index 0000000..278acf4 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/ImageUtils.kt @@ -0,0 +1,97 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.net.Uri +import android.provider.OpenableColumns +import android.util.LruCache + +/** + * 相册取图的读取、缩略图与文件名处理。 + * 不引第三方图片库,自己按 inSampleSize 采样,避免大图 OOM。 + */ +object ImageUtils { + + data class PickedImage(val uri: Uri, val name: String, val mime: String) + + /** + * 缩略图按字节限额缓存(8MB)。 + * 原来每渲染一次配图条就要重新解码全部缩略图,删图时会重解 N-1 张; + * 有了缓存,同一张图在多次重建里只解一次。 + */ + private val thumbCache = object : LruCache(8 * 1024 * 1024) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount + } + + fun picked(context: Context, uri: Uri): PickedImage = + PickedImage(uri, displayName(context, uri), mimeOf(context, uri)) + + fun displayName(context: Context, uri: Uri): String { + var name = "" + try { + context.contentResolver + .query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) + ?.use { cursor -> + if (cursor.moveToFirst()) { + val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (index >= 0) name = cursor.getString(index) ?: "" + } + } + } catch (e: Exception) { + // 少数 provider 不给名字,下面用时间戳兜底 + } + if (name.isBlank()) { + name = "image-${System.currentTimeMillis()}.jpg" + } + return name.replace(Regex("[\"\\r\\n]"), "_") + } + + fun mimeOf(context: Context, uri: Uri): String = + context.contentResolver.getType(uri) ?: "image/jpeg" + + fun readBytes(context: Context, uri: Uri): ByteArray { + context.contentResolver.openInputStream(uri)?.use { stream -> + return stream.readBytes() + } + throw IllegalStateException("读取图片失败,可能已失去访问权限") + } + + fun loadThumbnail(context: Context, uri: Uri, maxSize: Int): Bitmap? { + val key = "$uri@$maxSize" + thumbCache.get(key)?.let { return it } + + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + try { + context.contentResolver.openInputStream(uri)?.use { + BitmapFactory.decodeStream(it, null, bounds) + } + } catch (e: Exception) { + return null + } + + val options = BitmapFactory.Options().apply { + inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, maxSize) + } + val bitmap = try { + context.contentResolver.openInputStream(uri)?.use { + BitmapFactory.decodeStream(it, null, options) + } + } catch (e: Exception) { + null + } + if (bitmap != null) thumbCache.put(key, bitmap) + return bitmap + } + + private fun sampleSize(width: Int, height: Int, maxSize: Int): Int { + if (width <= 0 || height <= 0 || maxSize <= 0) return 1 + var longest = maxOf(width, height) + var sample = 1 + while (longest / 2 >= maxSize) { + longest /= 2 + sample *= 2 + } + return sample + } +} diff --git a/src/main/java/com/shitoucuo/postpad/MailApi.kt b/src/main/java/com/shitoucuo/postpad/MailApi.kt new file mode 100644 index 0000000..a0f8f55 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/MailApi.kt @@ -0,0 +1,733 @@ +package com.shitoucuo.postpad + +import com.sun.mail.iap.Argument +import com.sun.mail.imap.IMAPFolder +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject +import java.util.Properties +import javax.mail.FetchProfile +import javax.mail.Flags +import javax.mail.Folder +import javax.mail.Message +import javax.mail.Session +import javax.mail.Store +import javax.mail.UIDFolder +import javax.mail.internet.InternetAddress +import javax.mail.internet.MimeMessage +import javax.mail.internet.MimeMultipart +import javax.mail.internet.MimeUtility + +/** + * 邮件直连 IMAP(与 obsidian-mail-desk 同一条链路,无服务端代理)。 + * + * **所有函数都接收账户快照 [Prefs.MailEntry],不在流程中途读 prefs 的当前账户。** + * 早期版本全程依赖 prefs.mailEmail / mailImapHost,用户切邮箱时正在跑的同步 + * 会在写缓存那一步读到新账户,把 A 的邮件写进 B 的缓存文件——表现为 + * 「列表里混进其它邮箱的邮件」「点开提示已删除」「已读状态错位」。快照消除这类竞态。 + * + * 列表走本地缓存(每个邮箱一份缓存文件): + * - 首次拉最近 N 天(最多 200 封); + * - 之后按 UID 增量,只向服务端要「比上次最大的 UID 更新」的邮件; + * - 每次同步顺带核对服务端的存留 UID 与已读标记,幽灵邮件会被清掉、 + * 已在其它端读过的邮件也会同步成已读; + * - 缓存记 UIDVALIDITY,邮箱被服务端重建时旧 UID 全部失效,整份缓存作废重拉。 + * + * 正文与附件在点开时才解析。 + * + * QQ / 163 邮箱要求客户端先发 IMAP ID 命令,否则登录成功但报 Unsafe Login, + * 这里在 connect 之后通过 IMAPFolder.doCommand 补发一次。 + */ +object MailApi { + + class ApiException(message: String) : Exception(message) + + /** 邮件在服务端已不存在(被其它端删除或已清理),缓存已同步移除 */ + class GoneException(message: String) : Exception(message) + + /** 列表项;snippet 在列表阶段可能为空,点开详情时回填 */ + data class MailItem( + val uid: Long, + val folder: String, + val subject: String, + val from: String, + val fromName: String, + val date: Long, + val snippet: String, + val seen: Boolean, + val hasAttachment: Boolean, + /** 所属邮箱地址,聚合列表里用于卡片标识与详情页路由 */ + val account: String = "", + ) + + data class Attachment(val name: String, val type: String, val size: Long) + + data class MailDetail( + val item: MailItem, + val body: String, + val html: String, + val attachments: List, + ) + + /** 聚合列表项:邮件 + 它所属的账户(卡片要显示邮箱名,详情要按账户连) */ + data class AccountMail(val account: Prefs.MailEntry, val item: MailItem) + + // ==================== 连接 ==================== + + private fun session(account: Prefs.MailEntry): Session { + val protocol = if (account.secure) "imaps" else "imap" + val props = Properties().apply { + put("mail.store.protocol", protocol) + put("mail.$protocol.host", account.host) + put("mail.$protocol.port", account.port.toString()) + put("mail.$protocol.ssl.enable", account.secure.toString()) + put("mail.$protocol.connectiontimeout", "20000") + put("mail.$protocol.timeout", "20000") + // 不把授权码写进日志 + put("mail.debug", "false") + } + return Session.getInstance(props) + } + + private fun connect(account: Prefs.MailEntry, version: String = ""): Store { + if (!account.ready) throw ApiException( + // 说清缺哪一项:笼统的"先填邮箱、授权码和 IMAP 主机"会让人以为整段配置都丢了 + when { + account.email.isBlank() -> "邮箱 ${account.label} 没填邮箱地址" + account.auth.isBlank() -> "邮箱 ${account.label} 没填 IMAP 授权码" + else -> "邮箱 ${account.label} 没填 IMAP 服务器" + } + ) + val protocol = if (account.secure) "imaps" else "imap" + val store = session(account).getStore(protocol) + try { + store.connect(account.host, account.port, account.email, account.auth) + } catch (e: Exception) { + val message = e.message.orEmpty() + if (message.contains("Unsafe Login", true) || + message.contains(" ID ", true) || + account.host.contains("qq.com", true) + ) { + // QQ 系邮箱:连接成功后需要补发 ID,这里先关闭再按带 ID 的流程重连 + runCatching { store.close() } + try { + val retry = session(account).getStore(protocol) + retry.connect(account.host, account.port, account.email, account.auth) + sendId(retry, version) + return retry + } catch (retryError: Exception) { + // 重连失败也要走 friendly(),否则会漏出 IMAP 原始英文报错 + throw ApiException(friendly(retryError)) + } + } + throw ApiException(friendly(e)) + } + sendId(store, version) + return store + } + + /** + * 补发 IMAP ID。126 / QQ 要求登录后、打开邮箱前发送,否则一直返回 Unsafe Login。 + * + * 用 IMAPFolder 公开的 doCommand 拿到底层协议,并用 writeAtom 原样发送 + * 括号参数(writeString 会被拆成裸字符串,服务端报 BAD Parse)。 + */ + private fun sendId(store: Store, version: String) { + runCatching { + val folder = store.getFolder("INBOX") as? IMAPFolder ?: return + val ver = version.ifBlank { "unknown" } + val fields = "(\"name\" \"PostPad\" \"version\" \"$ver\" \"vendor\" \"shitoucuo\")" + val arg = Argument().writeAtom(fields) + folder.doCommand { protocol -> + protocol.simpleCommand("ID", arg) + null + } + } + } + + private fun friendly(e: Exception): String = when { + e.message?.contains("Authentication failed", true) == true || + e.message?.contains("LOGIN failed", true) == true -> + "授权码错误,或邮箱未开启 IMAP 服务" + e.message?.contains("Connection refused", true) == true || + e.message?.contains("timed out", true) == true -> + "连不上 IMAP 服务器,检查主机、端口和网络" + e.message?.contains("Unsafe Login", true) == true -> + "邮箱要求客户端标识,仍被拒绝,尝试换 993 端口或关闭 SSL" + else -> e.message?.take(160).orEmpty().ifBlank { "邮箱连接失败" } + } + + // ==================== 连通检查 ==================== + + suspend fun check(prefs: Prefs, account: Prefs.MailEntry): String = + withContext(Dispatchers.IO) { + val store = connect(account, prefs.appVersion) + try { + val inbox = store.getFolder("INBOX") + if (!inbox.exists()) throw ApiException("邮箱里没有 INBOX 文件夹") + inbox.open(Folder.READ_ONLY) + val count = inbox.messageCount + "${account.label}:连接正常,收件箱 $count 封邮件" + } catch (e: ApiException) { + throw e + } catch (e: Exception) { + throw ApiException(friendly(e)) + } finally { + runCatching { store.close() } + } + } + + // ==================== 缓存 ==================== + + /** + * 账户的缓存文件,按邮箱地址散列命名。 + * + * 旧版的单文件缓存 `postpad_mail_cache.json` 不再"改名继承":那个文件属于 + * 升级前的单一账户,无法确定现在对应哪个邮箱,继承过去就会把别的邮箱的邮件 + * 显示在当前账户下(UID 又对不上,点开就是"已删除")。这里直接删除, + * 各账户首次打开时按 mailFetchDays 重新拉一遍。 + */ + private fun cacheFile(prefs: Prefs, account: Prefs.MailEntry): java.io.File { + val target = prefs.mailCacheFile(account.email) + val legacy = prefs.legacyMailCacheFile + if (legacy.exists()) runCatching { legacy.delete() } + return target + } + + private class CacheSnapshot( + val mails: List, + val lastUid: Long, + val uidValidity: Long, + ) + + /** 缓存读写的互斥锁:detail 与 markRead 都会「读-改-写」,并发会互相覆盖 */ + private val cacheLock = Any() + + private fun readCache(prefs: Prefs, account: Prefs.MailEntry): CacheSnapshot { + val file = cacheFile(prefs, account) + if (!file.exists()) return CacheSnapshot(emptyList(), 0L, 0L) + val root = runCatching { JSONObject(file.readText()) }.getOrNull() + ?: return CacheSnapshot(emptyList(), 0L, 0L) + val array = root.optJSONArray("mails") ?: JSONArray() + val out = ArrayList(array.length()) + for (i in 0 until array.length()) { + val obj = array.optJSONObject(i) ?: continue + out.add( + MailItem( + uid = obj.optLong("uid"), + folder = obj.optString("folder").ifBlank { "INBOX" }, + // 旧缓存里可能存着未解码的编码串与「名字 <地址>」格式,读的时候顺手纠正, + // 不必为了编码问题强制全量重同步一遍。 + subject = decodeHeader(obj.optString("subject")).ifBlank { "(无主题)" }, + from = plainAddress(obj.optString("from")), + fromName = decodeHeader(obj.optString("fromName")), + date = obj.optLong("date"), + snippet = obj.optString("snippet"), + seen = obj.optBoolean("seen"), + hasAttachment = obj.optBoolean("hasAttachment"), + account = account.email, + ) + ) + } + return CacheSnapshot( + out.sortedByDescending { it.date }, + root.optLong("lastUid"), + root.optLong("uidValidity"), + ) + } + + private fun writeCache( + prefs: Prefs, + account: Prefs.MailEntry, + items: List, + lastUid: Long, + uidValidity: Long, + ) { + val file = cacheFile(prefs, account) + val array = JSONArray() + items.forEach { item -> + array.put( + JSONObject().apply { + put("uid", item.uid) + put("folder", item.folder) + put("subject", item.subject) + put("from", item.from) + put("fromName", item.fromName) + put("date", item.date) + put("snippet", item.snippet) + put("seen", item.seen) + put("hasAttachment", item.hasAttachment) + } + ) + } + file.writeText( + JSONObject() + .put("mails", array) + .put("lastUid", lastUid) + .put("uidValidity", uidValidity) + .toString() + ) + } + + /** 「读-改-写」一次性完成,避免 detail / setSeen / delete 并发时互相覆盖 */ + private fun updateCache( + prefs: Prefs, + account: Prefs.MailEntry, + block: (LinkedHashMap, CacheSnapshot) -> Unit, + ) { + synchronized(cacheLock) { + val snapshot = readCache(prefs, account) + val merged = LinkedHashMap() + snapshot.mails.forEach { merged[it.uid] = it } + block(merged, snapshot) + writeCache( + prefs, + account, + merged.values.sortedByDescending { it.date }.take(300), + merged.keys.maxOrNull() ?: 0L, + snapshot.uidValidity, + ) + } + } + + /** 从本地缓存读取单个账户的列表(按时间倒序),断网可用 */ + fun cached(prefs: Prefs, account: Prefs.MailEntry): List = + readCache(prefs, account).mails + + /** + * 全部账户的缓存合并成一个列表(按时间倒序)。 + * + * 首页邮件页展示的是「所有邮箱」:不需要用户在顶部切来切去, + * 想知道某封属于哪个邮箱看卡片上的徽标即可。 + */ + fun cachedAll(prefs: Prefs): List { + val out = ArrayList() + prefs.mailAccounts().forEach { account -> + if (account.email.isBlank()) return@forEach + readCache(prefs, account).mails.forEach { out.add(AccountMail(account, it)) } + } + return out.sortedByDescending { it.item.date } + } + + /** + * 清掉指定账户的缓存,下次同步按新设置全量重拉。 + * + * 增量同步只取「比缓存里最新 UID 更新」的邮件,所以用户在设置里调大同步天数后, + * 不清缓存的话更早的邮件永远进不来,设置项等于无效。 + */ + fun resetCache(prefs: Prefs, account: Prefs.MailEntry) { + if (account.email.isBlank()) return + runCatching { cacheFile(prefs, account).delete() } + } + + /** 从缓存移除指定 UID(服务端已不存在时调用,保证列表不再出现幽灵邮件) */ + private fun removeFromCache(prefs: Prefs, account: Prefs.MailEntry, uid: Long) { + updateCache(prefs, account) { merged, _ -> merged.remove(uid) } + } + + // ==================== 列表与同步 ==================== + + /** 正在同步的账户(小写邮箱),防止同一账户被两个流程同时写缓存 */ + private val syncing = java.util.concurrent.ConcurrentHashMap.newKeySet() + + /** + * 增量同步一个账户的收件箱: + * - 缓存里有 lastUid 时只拉 UID 更大的新邮件,几封就几封,不再全量重取; + * - 首次同步取最近 200 封,并受该账户的 days 限制; + * - 顺带按服务端的 UID 存留与 FLAGS 校正缓存(清幽灵、同步已读)。 + * 返回本次新增的邮件数,方便界面提示。 + */ + suspend fun sync(prefs: Prefs, account: Prefs.MailEntry): Int = withContext(Dispatchers.IO) { + val key = account.email.trim().lowercase() + if (!account.ready) return@withContext 0 + // 同一账户已在同步:直接返回 0,避免两条连接对着同一份缓存互相覆盖 + if (!syncing.add(key)) return@withContext 0 + val store = try { + connect(account, prefs.appVersion) + } catch (e: Exception) { + syncing.remove(key) + throw e + } + try { + val folder = store.getFolder("INBOX") + folder.open(Folder.READ_ONLY) + val uidFolder = folder as UIDFolder + val uidValidity = runCatching { uidFolder.uidValidity }.getOrDefault(0L) + + var snapshot = readCache(prefs, account) + // UIDVALIDITY 变了说明服务端重建过邮箱:旧 UID 指向的已是别的邮件, + // 继续用缓存就会出现"打开是另一封""提示已删除",整份作废按首次同步重来 + if (uidValidity > 0 && snapshot.uidValidity > 0 && snapshot.uidValidity != uidValidity) { + snapshot = CacheSnapshot(emptyList(), 0L, uidValidity) + writeCache(prefs, account, emptyList(), 0L, uidValidity) + } + + // 与服务端核对存留 + 已读状态:其它端删除的邮件要清掉,其它端读过的要同步。 + // 只拉 UID 与 FLAGS,不拉内容,一次 FETCH 就能覆盖全部邮件。 + val serverFlags: Map? = runCatching { + val all = uidFolder.getMessagesByUID(1, UIDFolder.LASTUID) + if (all.isEmpty()) { + if (folder.messageCount == 0) emptyMap() else null + } else { + folder.fetch(all, FetchProfile().apply { + add(UIDFolder.FetchProfileItem.UID) + add(FetchProfile.Item.FLAGS) + }) + val out = HashMap(all.size) + for (m in all) { + val u = runCatching { uidFolder.getUID(m) }.getOrDefault(0L) + if (u > 0) { + out[u] = runCatching { + m.flags?.contains(Flags.Flag.SEEN) == true + }.getOrDefault(false) + } + } + out + } + }.getOrNull() + val kept = if (serverFlags != null) { + snapshot.mails.filter { it.uid in serverFlags } + .map { it.copy(seen = serverFlags[it.uid] ?: it.seen, account = account.email) } + } else { + snapshot.mails // 核对失败时不动缓存,宁可多显示也不误删 + } + + val messages = if (snapshot.lastUid > 0) { + // 增量:只取比已知最大 UID 新的邮件(LASTUID 是服务端最新一封) + uidFolder.getMessagesByUID(snapshot.lastUid + 1, UIDFolder.LASTUID) + } else { + val total = folder.messageCount + val limit = minOf(total, 200) + val start = total - limit + 1 + if (start > 1) folder.getMessages(start, total) else folder.getMessages() + } + + val profile = FetchProfile().apply { + add(FetchProfile.Item.ENVELOPE) + add(FetchProfile.Item.FLAGS) + add(UIDFolder.FetchProfileItem.UID) + add(FetchProfile.Item.CONTENT_INFO) + } + folder.fetch(messages, profile) + + val cutoff = System.currentTimeMillis() - account.days * 86_400_000L + val existingUids = snapshot.mails.map { it.uid }.toHashSet() + val fetched = ArrayList(messages.size) + var maxUid = snapshot.lastUid + var added = 0 + for (msg in messages) { + val uid = runCatching { uidFolder.getUID(msg) }.getOrDefault(0L) + if (uid <= 0) continue + if (uid <= snapshot.lastUid) continue // LASTUID 兜底返回旧邮件时跳过 + if (uid > maxUid) maxUid = uid + val sent = runCatching { msg.sentDate?.time ?: msg.receivedDate?.time ?: 0L } + .getOrDefault(0L) + // 首次同步只保留 days 内的;增量阶段全部收下 + if (snapshot.lastUid == 0L && sent > 0 && sent < cutoff) continue + val existed = uid in existingUids + if (!existed) added++ + fetched.add(toItem(msg, uid, "INBOX").copy(account = account.email)) + } + + val merged = LinkedHashMap() + kept.forEach { merged[it.uid] = it } + fetched.forEach { merged[it.uid] = it } + val all = merged.values.sortedByDescending { it.date } + synchronized(cacheLock) { + writeCache( + prefs, account, all.take(300), maxUid, + if (uidValidity > 0) uidValidity else snapshot.uidValidity, + ) + } + added + } catch (e: ApiException) { + throw e + } catch (e: Exception) { + throw ApiException(friendly(e)) + } finally { + syncing.remove(key) + runCatching { store.close() } + } + } + + /** 打开邮件:解析正文与附件,并把 120 字摘要写回缓存 */ + suspend fun detail(prefs: Prefs, account: Prefs.MailEntry, uid: Long, folderName: String): MailDetail = + withContext(Dispatchers.IO) { + val store = connect(account, prefs.appVersion) + try { + val folder = store.getFolder(folderName) + folder.open(Folder.READ_ONLY) + val uidFolder = folder as UIDFolder + val message = uidFolder.getMessageByUID(uid) + if (message == null) { + // 服务端已没有这封邮件(其它端删过 / 已清理):清掉缓存幽灵项并明确告知 + removeFromCache(prefs, account, uid) + throw GoneException("这封邮件可能已被删除,已从列表移除") + } + folder.fetch(arrayOf(message), FetchProfile().apply { + add(FetchProfile.Item.ENVELOPE) + add(FetchProfile.Item.CONTENT_INFO) + }) + + val parsed = parseContent(message) + val base = toItem(message, uid, folderName).copy(account = account.email) + val item = base.copy( + snippet = parsed.first.take(120).ifBlank { base.snippet }, + ) + // 回填摘要(不覆盖已读标记:是否已读由 markRead / setSeen 负责) + updateCache(prefs, account) { merged, _ -> + val seen = merged[uid]?.seen ?: item.seen + merged[uid] = item.copy(seen = seen) + } + + MailDetail(item, parsed.first, parsed.second, parsed.third) + } catch (e: ApiException) { + throw e + } catch (e: GoneException) { + // 已从缓存移除:调用方要按"已删除"处理(刷新列表),不能当普通错误 + throw e + } catch (e: Exception) { + throw ApiException(friendly(e)) + } finally { + runCatching { store.close() } + } + } + + /** 标记已读(IMAP \Seen) */ + suspend fun markRead(prefs: Prefs, account: Prefs.MailEntry, uid: Long, folderName: String) = + setSeen(prefs, account, uid, folderName, true) + + /** + * 只写本地缓存的已读状态,不连服务端。 + * + * 「点开即已读」要求列表、底部角标、下次进入看到的状态立刻一致,不能等一次 + * IMAP 往返(网络差时要好几秒,中途退出就白读了)。服务端的 \Seen 由 + * [setSeen] 随后补;万一补失败,本地仍按已读算,下一次同步再用服务端 FLAGS 校正。 + */ + fun markSeenLocal(prefs: Prefs, account: Prefs.MailEntry, uid: Long, seen: Boolean) { + if (account.email.isBlank() || uid <= 0) return + runCatching { + updateCache(prefs, account) { merged, _ -> + merged[uid]?.let { merged[uid] = it.copy(seen = seen) } + } + } + } + + /** 设置已读 / 未读,并同步本地缓存;列表的「标为未读」走这里 */ + suspend fun setSeen( + prefs: Prefs, + account: Prefs.MailEntry, + uid: Long, + folderName: String, + seen: Boolean, + ) = withContext(Dispatchers.IO) { + val store = connect(account, prefs.appVersion) + try { + val folder = store.getFolder(folderName) + folder.open(Folder.READ_WRITE) + val message = (folder as UIDFolder).getMessageByUID(uid) + if (message == null) { + removeFromCache(prefs, account, uid) + throw GoneException("这封邮件可能已被删除,已从列表移除") + } + message.setFlag(Flags.Flag.SEEN, seen) + updateCache(prefs, account) { merged, _ -> + merged[uid]?.let { merged[uid] = it.copy(seen = seen) } + } + } catch (e: ApiException) { + throw e + } catch (e: GoneException) { + throw e + } catch (e: Exception) { + throw ApiException(friendly(e)) + } finally { + runCatching { store.close() } + } + } + + /** 删除邮件:服务端标记删除并 expunge,同时从本地缓存移除 */ + suspend fun delete(prefs: Prefs, account: Prefs.MailEntry, uid: Long, folderName: String) = + withContext(Dispatchers.IO) { + val store = connect(account, prefs.appVersion) + try { + val folder = store.getFolder(folderName) + folder.open(Folder.READ_WRITE) + val message = (folder as UIDFolder).getMessageByUID(uid) + if (message == null) { + // 服务端已没有这封邮件:视为删除完成,清缓存让列表同步消失 + removeFromCache(prefs, account, uid) + throw GoneException("邮件在服务器上已不存在,已从列表移除") + } + message.setFlag(Flags.Flag.DELETED, true) + (folder as? IMAPFolder)?.expunge() + folder.close(false) + updateCache(prefs, account) { merged, _ -> merged.remove(uid) } + } catch (e: ApiException) { + throw e + } catch (e: GoneException) { + throw e + } catch (e: Exception) { + throw ApiException(friendly(e)) + } finally { + runCatching { store.close() } + } + } + + /** + * 用该账户的 SMTP 发信(回复用)。SMTP 主机由 IMAP 主机推导: + * imap.qq.com → smtp.qq.com,126 同理;465 端口 SSL。 + */ + suspend fun send(account: Prefs.MailEntry, to: String, subject: String, text: String) = + withContext(Dispatchers.IO) { + val smtpHost = account.host.replaceFirst("imap.", "smtp.", true) + val props = Properties().apply { + put("mail.smtp.host", smtpHost) + put("mail.smtp.port", "465") + put("mail.smtp.ssl.enable", "true") + put("mail.smtp.auth", "true") + put("mail.smtp.connectiontimeout", "20000") + put("mail.smtp.timeout", "30000") + } + try { + val session = Session.getInstance(props) + val message = MimeMessage(session).apply { + setFrom(javax.mail.internet.InternetAddress(account.email)) + setRecipients(Message.RecipientType.TO, to) + setSubject(subject, "UTF-8") + setText(text, "UTF-8") + } + val transport = session.getTransport("smtp") + try { + transport.connect(smtpHost, 465, account.email, account.auth) + transport.sendMessage(message, message.allRecipients) + } finally { + runCatching { transport.close() } + } + } catch (e: ApiException) { + throw e + } catch (e: Exception) { + throw ApiException("发送失败:" + friendly(e)) + } + } + + // ==================== 解析 ==================== + + private fun toItem(msg: Message, uid: Long, folder: String): MailItem { + val from = msg.from?.firstOrNull() + val addr = from as? InternetAddress + // from 只存纯地址:InternetAddress.toString() 会把显示名一起拼进来("张三" ), + // 详情页再套一层尖括号就成了「张三 <"张三" >」。 + val address = addr?.address?.trim().orEmpty() + .ifBlank { plainAddress(from?.toString().orEmpty()) } + // 显示名走 IMAP ENVELOPE 过来时是 RFC 2047 原文(=?utf-8?B?...?=),JavaMail 不会自动解, + // 不处理就直接把编码串显示在名字后面,即用户看到的"乱码"。 + val personal = decodeHeader(addr?.personal.orEmpty()) + val subject = decodeHeader(runCatching { msg.subject }.getOrNull().orEmpty()) + .ifBlank { "(无主题)" } + val date = runCatching { msg.sentDate?.time ?: msg.receivedDate?.time ?: 0L }.getOrDefault(0L) + val flags = runCatching { msg.flags }.getOrNull() + return MailItem( + uid = uid, + folder = folder, + subject = subject, + from = address, + fromName = personal.ifBlank { address.substringBefore('@') }, + date = date, + snippet = "", + seen = flags?.contains(Flags.Flag.SEEN) == true, + hasAttachment = hasAttachmentHeader(msg), + ) + } + + /** + * 解 RFC 2047 编码头:`=?UTF-8?B?5byg5LiJ?=`、`=?GBK?Q?...?=` 这类。 + * + * JavaMail 只在 MimeMessage.getSubject() 里自动解码,地址里的显示名 + * (InternetAddress.personal)保持原样,所以必须自己解一次。 + * 已经是正常文字的输入会原样返回,可以反复调用。 + */ + private fun decodeHeader(raw: String): String { + if (raw.isBlank()) return "" + // 先把折行(CRLF + 空格/Tab)展开,折在编码字中间时直接解码会失败 + val unfolded = raw.replace(Regex("[\\r\\n]+[ \\t]"), " ").trim() + return runCatching { MimeUtility.decodeText(unfolded) }.getOrDefault(unfolded) + } + + /** 从 "名字 " 里提出纯地址;缓存里存过旧格式,读的时候顺手归一 */ + private fun plainAddress(raw: String): String { + val s = raw.trim() + val lt = s.lastIndexOf('<') + if (lt >= 0) { + val end = s.indexOf('>', lt) + val inside = if (end > lt) s.substring(lt + 1, end) else s.substring(lt + 1) + if (inside.contains('@')) return inside.trim() + } + return s + } + + /** + * 只凭 BODYSTRUCTURE 判断有没有附件。 + * + * 旧实现访问 msg.content,JavaMail 为了拿到 MimeMultipart 会补拉 BODY[](整封正文), + * 首屏几百封邮件就等于把整个邮箱下载一遍——这是"第一次打开邮件页特别慢"的主因。 + * + * 也不能改用 msg.getHeader("Content-Type"):BODYSTRUCTURE 不含原始头部, + * 读 header 会让 JavaMail 逐封补拉 BODY.PEEK[HEADER],只是把整封换成了头部。 + * 这里只用 msg.contentType —— 它直接来自 BODYSTRUCTURE,不产生任何额外请求。 + * 代价是 multipart/mixed 的纯正文邮件会多显示一个附件图标,判断只会偏多不会漏。 + */ + private fun hasAttachmentHeader(msg: Message): Boolean = runCatching { + val topType = msg.contentType.orEmpty().lowercase() + if (!topType.startsWith("multipart/")) return@runCatching false + topType.startsWith("multipart/mixed") || topType.contains("name=") + }.getOrDefault(false) + + /** 返回 Triple(纯文本摘要, HTML 正文, 附件列表) */ + private fun parseContent(msg: Message): Triple> { + var plain = "" + var html = "" + val attachments = ArrayList() + fun walk(part: javax.mail.Part) { + if (part.isMimeType("text/plain")) { + if (plain.isEmpty()) plain = runCatching { part.content as? String }.getOrNull().orEmpty() + } else if (part.isMimeType("text/html")) { + if (html.isEmpty()) html = runCatching { part.content as? String }.getOrNull().orEmpty() + } else if (part.isMimeType("multipart/*")) { + val multipart = part.content as? MimeMultipart ?: return + for (i in 0 until multipart.count) walk(multipart.getBodyPart(i)) + } else if (part.isMimeType("message/rfc822")) { + walk(part.content as? javax.mail.Part ?: return) + } else { + val disposition = runCatching { part.disposition }.getOrNull().orEmpty() + val name = runCatching { part.fileName }.getOrNull() + ?: disposition.substringAfter("filename=", "").trim('"') + if (name.isNotEmpty() || disposition.contains("attachment", true)) { + attachments.add( + Attachment( + name = name.ifBlank { "附件 ${attachments.size + 1}" }, + type = runCatching { part.contentType }.getOrDefault("application/octet-stream"), + size = runCatching { part.size.toLong() }.getOrDefault(0L), + ) + ) + } + } + } + walk(msg) + if (plain.isBlank() && html.isNotBlank()) { + plain = htmlToText(html) + } + return Triple(plain.trim(), html, attachments) + } + + private fun htmlToText(html: String): String = html + .replace(Regex("", RegexOption.IGNORE_CASE), " ") + .replace(Regex("", RegexOption.IGNORE_CASE), " ") + .replace(Regex("", RegexOption.IGNORE_CASE), "\n") + .replace(Regex("", RegexOption.IGNORE_CASE), "\n") + .replace(Regex("<[^>]*>"), " ") + .replace(" ", " ").replace("&", "&") + .replace(Regex("[ \\t]{2,}"), " ") + .replace(Regex("\\n{3,}"), "\n\n") + .trim() +} diff --git a/src/main/java/com/shitoucuo/postpad/MailDetailActivity.kt b/src/main/java/com/shitoucuo/postpad/MailDetailActivity.kt new file mode 100644 index 0000000..ebda585 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/MailDetailActivity.kt @@ -0,0 +1,396 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.content.Intent +import android.content.res.Configuration +import android.os.Bundle +import android.view.ViewGroup +import android.webkit.WebSettings +import android.webkit.WebView +import android.widget.EditText +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.TextView +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * 邮件详情:主题、发件人、时间、正文与附件清单。 + * 顶栏支持回复(SMTP 直发,带引用)与删除(IMAP 删除 + 本地缓存移除)。 + */ +class MailDetailActivity : AppCompatActivity() { + + private lateinit var prefs: Prefs + private lateinit var tvSubject: TextView + private lateinit var tvMeta: TextView + private lateinit var tvBody: TextView + private lateinit var webViewMail: WebView + private lateinit var tvAttachments: TextView + private lateinit var progress: ProgressBar + + private var uid = 0L + private var folder = "INBOX" + + /** + * 这封邮件所属的账户快照。 + * + * 首页是所有邮箱合并的时间线,详情页必须用**卡片上那个邮箱**连服务端: + * 用当前账户去连,UID 对不上就提示「已删除」,已读也会标到别的邮箱的同 UID 邮件上。 + */ + private lateinit var account: Prefs.MailEntry + + /** 当前详情(回复时要发件人地址与正文引用) */ + private var detail: MailApi.MailDetail? = null + + companion object { + private const val EXTRA_UID = "uid" + private const val EXTRA_FOLDER = "folder" + private const val EXTRA_SUBJECT = "subject" + private const val EXTRA_ACCOUNT = "account" + + /** 邮件有变动(删除 / 已读)时置位,首页 onResume 里消费后刷新列表 */ + @Volatile + private var dataChanged = false + + fun consumeDataChanged(): Boolean { + val value = dataChanged + dataChanged = false + return value + } + + fun open(context: Context, account: String, uid: Long, folder: String, subject: String) { + context.startActivity( + Intent(context, MailDetailActivity::class.java).apply { + putExtra(EXTRA_ACCOUNT, account) + putExtra(EXTRA_UID, uid) + putExtra(EXTRA_FOLDER, folder) + putExtra(EXTRA_SUBJECT, subject) + } + ) + } + } + + 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_mail_detail) + + tvSubject = findViewById(R.id.tvMailSubject) + tvMeta = findViewById(R.id.tvMailMeta) + tvBody = findViewById(R.id.tvMailBody) + webViewMail = findViewById(R.id.webViewMail) + setupWebView() + tvAttachments = findViewById(R.id.tvMailAttachments) + progress = findViewById(R.id.mailProgress) + + uid = intent.getLongExtra(EXTRA_UID, 0L) + folder = intent.getStringExtra(EXTRA_FOLDER).orEmpty().ifBlank { "INBOX" } + tvSubject.text = intent.getStringExtra(EXTRA_SUBJECT).orEmpty().ifBlank { "(无主题)" } + + val accountEmail = intent.getStringExtra(EXTRA_ACCOUNT).orEmpty() + // 传了账户就必须用那个账户:找不到说明配置被删了,不能退回当前账户 + // (UID 在不同邮箱里互不相干,退回会打开另一封邮件) + val resolved = if (accountEmail.isBlank()) { + prefs.currentMailAccount + } else { + prefs.mailAccount(accountEmail) + } + if (resolved == null) { + Toast.makeText(this, "这个邮箱的配置已被删除", Toast.LENGTH_SHORT).show() + finish() + return + } + account = resolved + + findViewById(R.id.btnMailBack).setOnClickListener { finish() } + findViewById(R.id.btnMailReply).setOnClickListener { showReplyDialog() } + findViewById(R.id.btnMailDelete).setOnClickListener { confirmDelete() } + + progress.visibility = TextView.VISIBLE + lifecycleScope.launch { + try { + val loaded = withContext(Dispatchers.IO) { MailApi.detail(prefs, account, uid, folder) } + detail = loaded + tvSubject.text = loaded.item.subject + tvMeta.text = buildString { + append(getString(R.string.mail_from)).append(":") + val name = loaded.item.fromName.trim() + val addr = loaded.item.from.trim() + // 名称与地址相同时只显示一次(否则是 a@b.com ) + if (name.isNotBlank() && !name.equals(addr, ignoreCase = true)) { + append(name) + if (addr.isNotBlank()) append(" <").append(addr).append(">") + } else { + append(addr.ifBlank { name }) + } + append("\n").append(getString(R.string.mail_date)).append(":") + append(formatDate(loaded.item.date)) + } + val body = loaded.body.ifBlank { loaded.item.snippet } + if (loaded.html.isNotBlank()) { + // HTML 邮件:按邮件自带排版渲染(表格 / 图片 / 内嵌样式都不丢) + showHtmlMail(loaded.html) + } else { + tvBody.visibility = TextView.VISIBLE + webViewMail.visibility = TextView.GONE + tvBody.text = body.ifBlank { getString(R.string.mail_no_content) } + } + if (loaded.attachments.isEmpty()) { + tvAttachments.visibility = TextView.GONE + } else { + tvAttachments.visibility = TextView.VISIBLE + tvAttachments.text = getString(R.string.mail_attachments) + ":\n" + + loaded.attachments.joinToString("\n") { + "· ${it.name}(${formatSize(it.size)})" + } + } + // 已读标记由首页「点开即已读」负责(本地缓存 + 服务端各一次), + // 这里不再重复连一次 IMAP;只提示列表:摘要已回填,返回后需要刷新这一条 + dataChanged = true + } catch (e: MailApi.GoneException) { + // 邮件已被服务端清理(缓存已同步移除):置位变更,返回列表后这封邮件就消失 + webViewMail.visibility = TextView.GONE + tvBody.visibility = TextView.VISIBLE + tvBody.text = "读取邮件失败:${e.message ?: "邮件已不存在"}" + dataChanged = true + } catch (e: Exception) { + webViewMail.visibility = TextView.GONE + tvBody.visibility = TextView.VISIBLE + tvBody.text = "读取邮件失败:${e.message ?: "未知错误"}" + } finally { + progress.visibility = TextView.GONE + } + } + } + + /** WebView 只渲染,不开脚本、不开文件访问,保证邮件内容安全 */ + private fun setupWebView() { + webViewMail.visibility = TextView.GONE + webViewMail.setBackgroundColor(android.graphics.Color.TRANSPARENT) + // 高度自适应内容:渲染完成后按 contentHeight 定成固定像素再重排。 + // 比依赖 wrap_content 测量更可靠(WebView 的测量优化要求父容器是 match_parent)。 + webViewMail.webViewClient = object : android.webkit.WebViewClient() { + override fun onPageFinished(view: WebView, url: String?) { + // onPageFinished 只代表 HTML 就绪,邮件里的图片是异步加载的, + // 只算一次会把图片撑高的部分裁掉。分几个时间点各补算一次, + // 同步里只在变高时才更新,不会来回抖动。 + for (delay in longArrayOf(0L, 350L, 1200L)) { + view.postDelayed({ syncWebViewHeight(view) }, delay) + } + } + } + webViewMail.settings.apply { + javaScriptEnabled = false + allowFileAccess = false + allowContentAccess = false + builtInZoomControls = false + displayZoomControls = false + // 邮件里常见 http 图片,放开混合内容才能显示 + mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW + textZoom = 100 + } + } + + /** + * 按 HTML 实际内容高度定 WebView 高度。 + * + * contentHeight 单位是 CSS px;页面按 device-width 渲染,1 CSS px ≈ 1dp。 + * 只在变高时更新:图片陆续加载完会多次回调,反复 requestLayout 会让页面跳动。 + */ + private fun syncWebViewHeight(view: WebView) { + // 三次延时里有两次在页面显示之后,可能已经退出详情页 + if (isFinishing || isDestroyed) return + val height = (view.contentHeight * view.resources.displayMetrics.density).toInt() + if (height <= 0) return + val current = view.layoutParams?.height ?: 0 + if (height <= current) return + view.layoutParams = view.layoutParams.also { it.height = height } + view.requestLayout() + } + + /** 深色模式判断,给邮件 HTML 注入对应底色 */ + private fun isDarkMode(): Boolean = + (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == + Configuration.UI_MODE_NIGHT_YES + + /** + * HTML 邮件净化:去掉脚本 / 内嵌框架,图片与表格限制在屏宽内。 + * 深色模式强制深色:所有容器背景透明、文字继承正文浅色(!important 压过邮件内联样式), + * 避免模板邮件在深色下仍是刺眼白块;链接用主题橙、标题近白。 + * 浅色模式保留邮件原样,仅注入底色兜底。 + */ + private fun showHtmlMail(html: String) { + val dark = isDarkMode() + var s = html + .replace(Regex("", RegexOption.IGNORE_CASE), "") + .replace(Regex("]*/>", RegexOption.IGNORE_CASE), "") + .replace(Regex("", RegexOption.IGNORE_CASE), "") + .replace(Regex(""), "") + val theme = buildString { + append("body{margin:0;padding:0;font-family:sans-serif;") + append("-webkit-text-size-adjust:100%;word-wrap:break-word;overflow-wrap:break-word;") + if (dark) { + append("background:#191B1F!important;color:#EFEBE4!important;}") + // 容器背景全部拍平透明、文字一律继承,保证深色下永远可读 + append("table,td,th,tr,tbody,thead,tfoot,div,span,p,li,ul,ol,dl,dd,dt,") + append("section,article,figure,figcaption,header,footer,aside,blockquote,pre,code,") + append("font,h1,h2,h3,h4,h5,h6,strong,b,em,i,u,small,label") + append("{background-color:transparent!important;color:inherit!important;}") + append("a,a *{color:#D4814F!important;}") + append("h1,h2,h3,h4,h5,h6{color:#FAF7F1!important;}") + } else { + append("background:#FFFFFF;color:#1D1B18;}") + } + append("img{max-width:100%!important;height:auto!important;}") + append("table{max-width:100%!important;}") + append("pre,code{white-space:pre-wrap;max-width:100%;}") + } + val page = "" + + "" + + "$s" + tvBody.visibility = TextView.GONE + webViewMail.visibility = TextView.VISIBLE + // 底色同步:深色下滚动过冲区域也是深色 + webViewMail.setBackgroundColor( + android.graphics.Color.parseColor(if (dark) "#191B1F" else "#FFFFFF"), + ) + webViewMail.loadDataWithBaseURL(null, page, "text/html", "utf-8", null) + } + + /** 回复:引用原文,正文输入后用当前邮箱的 SMTP 直接发送 */ + private fun showReplyDialog() { + val current = detail ?: run { + toast("邮件还没加载完,稍后再试") + return + } + val input = EditText(this).apply { + hint = "输入回复内容" + minLines = 4 + setTextSize(14f) + setPadding( + (16 * resources.displayMetrics.density).toInt(), + (12 * resources.displayMetrics.density).toInt(), + (16 * resources.displayMetrics.density).toInt(), + (12 * resources.displayMetrics.density).toInt(), + ) + } + val wrap = FrameLayout(this).apply { + val pad = (16 * resources.displayMetrics.density).toInt() + setPadding(pad, pad / 2, pad, 0) + addView( + input, + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ), + ) + } + + AlertDialog.Builder(this) + .setTitle("回复:${current.item.subject}") + .setView(wrap) + .setPositiveButton("发送") { _, _ -> + val text = input.text.toString().trim() + if (text.isEmpty()) { + toast("回复内容为空") + return@setPositiveButton + } + sendReply(current, text) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun sendReply(current: MailApi.MailDetail, replyText: String) { + progress.visibility = TextView.VISIBLE + lifecycleScope.launch { + try { + val to = current.item.from + val subject = if (current.item.subject.startsWith("Re:", true)) { + current.item.subject + } else { + "Re: ${current.item.subject}" + } + val quoted = current.body.ifBlank { current.item.snippet } + .lines().joinToString("\n") { "> $it" } + val date = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US) + .format(Date(if (current.item.date > 0) current.item.date else System.currentTimeMillis())) + val text = buildString { + append(replyText) + append("\n\n\n在 ").append(date).append(",") + append(current.item.fromName.ifBlank { current.item.from }).append(" 写道:\n") + append(quoted) + } + withContext(Dispatchers.IO) { MailApi.send(account, to, subject, text) } + toast("已回复到 $to") + } catch (e: Exception) { + AlertDialog.Builder(this@MailDetailActivity) + .setTitle("发送失败") + .setMessage(e.message ?: "未知错误") + .setPositiveButton(android.R.string.ok, null) + .show() + } finally { + progress.visibility = TextView.GONE + } + } + } + + /** 删除:确认后 IMAP 删除并从缓存移除,返回列表页刷新 */ + private fun confirmDelete() { + AlertDialog.Builder(this) + .setTitle("删除邮件") + .setMessage("确定删除「${tvSubject.text}」?服务端与本地缓存都会移除。") + .setPositiveButton("删除") { _, _ -> + progress.visibility = TextView.VISIBLE + lifecycleScope.launch { + try { + withContext(Dispatchers.IO) { MailApi.delete(prefs, account, uid, folder) } + dataChanged = true + toast("已删除") + finish() + } catch (e: MailApi.GoneException) { + // 服务端本来就没有这封邮件,缓存已清理:直接返回列表 + progress.visibility = TextView.GONE + dataChanged = true + toast(e.message ?: "邮件已不存在,已从列表移除") + finish() + } catch (e: Exception) { + progress.visibility = TextView.GONE + AlertDialog.Builder(this@MailDetailActivity) + .setTitle("删除失败") + .setMessage(e.message ?: "未知错误") + .setPositiveButton(android.R.string.ok, null) + .show() + } + } + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun formatDate(ts: Long): String = if (ts <= 0) "" else + SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(ts)) + + private fun formatSize(size: Long): String = when { + size < 1024 -> "$size B" + size < 1024 * 1024 -> "${size / 1024} KB" + else -> "${size / 1024 / 1024} MB" + } + + private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show() +} diff --git a/src/main/java/com/shitoucuo/postpad/MainActivity.kt b/src/main/java/com/shitoucuo/postpad/MainActivity.kt new file mode 100644 index 0000000..e5c4889 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/MainActivity.kt @@ -0,0 +1,1365 @@ +package com.shitoucuo.postpad + +import android.content.Intent +import android.content.res.Configuration +import android.net.Uri +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.os.Handler +import android.os.Looper +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.ArrayAdapter +import android.widget.EditText +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ListView +import android.widget.MultiAutoCompleteTextView +import android.widget.PopupWindow +import android.widget.Spinner +import android.widget.ScrollView +import android.widget.TextView +import android.widget.Toast +import androidx.activity.result.PickVisualMediaRequest +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.core.content.ContextCompat +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject + +/** + * 主界面:发文(Typecho) / 发博(Memos) / 设置。 + * + * 语音输入交给系统输入法(微信输入法的语音键),本应用只负责编辑与发布, + * 所以界面里没有任何录音控件,配置界面也没有音频相关权限。 + * + * 发文的分类与标签都在编辑页现场选择:分类走下拉,标签可联想补全也可直接输入, + * 输入的新标签会在发布时自动创建。 + * + * 插图与发博不一样:发文走网页端「上传附件」那条路,传到站点(装了七牛就是七牛), + * 点缩略图把 ![名字](地址) 插到光标处,正文照样是 Markdown。 + */ +class MainActivity : AppCompatActivity() { + + private lateinit var prefs: Prefs + + private lateinit var tabPublish: TextView + private lateinit var tabMemo: TextView + private lateinit var panelPublish: View + private lateinit var panelMemo: View + private lateinit var panelEmpty: View + private lateinit var tvEmptyTitle: TextView + private lateinit var tvEmptyTip: TextView + private lateinit var btnTheme: ImageView + + private lateinit var etTitle: EditText + private lateinit var etContent: EditText + private lateinit var spinnerCategory: Spinner + private lateinit var etTags: MultiAutoCompleteTextView + private lateinit var btnPublish: TextView + + private lateinit var btnArticleImage: TextView + private lateinit var articleImages: LinearLayout + private lateinit var btnPolish: TextView + private lateinit var btnExpand: TextView + private lateinit var btnUndo: TextView + + private lateinit var etMemo: EditText + private lateinit var memoImages: LinearLayout + private lateinit var btnAddImage: TextView + private lateinit var btnMemo: TextView + private lateinit var visPrivate: TextView + private lateinit var visProtected: TextView + private lateinit var visPublic: TextView + + private lateinit var tvStatus: TextView + + /** 发布目标站点(多站点切换) */ + private lateinit var btnSitePick: TextView + + /** 发博已经选好、还没上传的图 */ + private val memoPicked = mutableListOf() + + /** 发文已经传好、可以插入的图 */ + private val articlePicked = mutableListOf() + + /** 每次 AI 改写前的版本,撤回一次弹一个 */ + private val aiHistory = mutableListOf() + + private var busy = false + private var uploading = false + private var tab = TAB_PUBLISH + + /** 分类与标签的元数据,进入发文页时从站点拉一次 */ + private var categories: List = emptyList() + private val tagNames = mutableListOf() + private var tagIds: Map = emptyMap() + private var tagPopup: PopupWindow? = null + private var metasLoaded = false + private var metasLoading = false + + /** 发文面板高度基准:键盘弹出时沿用无键盘时算出的正文高度,避免正文被挤没 */ + private var basePanelHeight = 0 + private var articleCardTarget = 0 + + /** 一张已上传的发文配图 */ + private data class ArticleImage( + val picked: ImageUtils.PickedImage, + val cid: Long, + val name: String, + val url: String, + ) + + private val pickMemoImages = registerForActivityResult( + ActivityResultContracts.PickMultipleVisualMedia(MAX_MEMO_IMAGES) + ) { uris -> + uris.forEach { uri -> + if (memoPicked.size < MAX_MEMO_IMAGES) { + memoPicked.add(ImageUtils.picked(this, uri)) + } + } + renderMemoImages() + } + + private val pickArticleImages = registerForActivityResult( + ActivityResultContracts.PickMultipleVisualMedia(MAX_ARTICLE_IMAGES) + ) { uris -> + if (uris.isNotEmpty()) uploadArticleImages(uris) + } + + override fun onCreate(savedInstanceState: Bundle?) { + prefs = Prefs(this) + applyNightMode() + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + bindViews() + setupCategoryDropdown() + restoreTagCache() + setupTagsInput() + restoreState(savedInstanceState) + + // 从首页「发布」菜单进入时,按传入值定位初始面板 + when (intent.getStringExtra(EXTRA_TAB)) { + "memo" -> showTab(TAB_MEMO) + "publish" -> showTab(TAB_PUBLISH) + } + + btnTheme.setOnClickListener { toggleTheme() } + tabPublish.setOnClickListener { showTab(TAB_PUBLISH) } + tabMemo.setOnClickListener { showTab(TAB_MEMO) } + findViewById(R.id.btnSettings).setOnClickListener { + startActivity(Intent(this, SettingsActivity::class.java)) + } + findViewById(R.id.btnGoSettings).setOnClickListener { + startActivity(Intent(this, SettingsActivity::class.java)) + } + + btnPublish.setOnClickListener { publish() } + btnMemo.setOnClickListener { publishMemo() } + + btnArticleImage.setOnClickListener { pickArticleImagesNow() } + btnAddImage.setOnClickListener { + pickMemoImages.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + } + + btnPolish.setOnClickListener { runAi(AiApi.MODE_POLISH) } + btnExpand.setOnClickListener { runAi(AiApi.MODE_EXPAND) } + btnUndo.setOnClickListener { undoAi() } + + visPrivate.setOnClickListener { setVisibilityChip(Prefs.VISIBILITY_PRIVATE) } + visProtected.setOnClickListener { setVisibilityChip(Prefs.VISIBILITY_PROTECTED) } + visPublic.setOnClickListener { setVisibilityChip(Prefs.VISIBILITY_PUBLIC) } + + setVisibilityChip(prefs.memosVisibility) + renderMemoImages() + renderArticleImages() + renderAiChips() + // 切深浅色会重建界面,回到重建前那个 Tab + showTab(tab) + } + + override fun onResume() { + super.onResume() + // 从设置页返回后,配置可能刚填好,重新判定一次 + showTab(tab) + // 站点可能被设置页改过,刷新一下发布面板的站点标签 + if (::btnSitePick.isInitialized) { + btnSitePick.text = "站点 · ${prefs.siteLabel(prefs.typechoCurrent)}" + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + // 切换深浅色会把 Activity 重建,撤回栈和配图列表跟着存一下,别让用户白干 + outState.putStringArrayList(KEY_AI_HISTORY, ArrayList(aiHistory)) + val array = JSONArray() + articlePicked.forEach { image -> + array.put(JSONObject().apply { + put("uri", image.picked.uri.toString()) + put("name", image.name) + put("mime", image.picked.mime) + put("url", image.url) + put("cid", image.cid) + }) + } + outState.putString(KEY_ARTICLE_IMAGES, array.toString()) + // 发博配图同样要存,否则切深浅色重建后已选图片全丢 + val memoArray = JSONArray() + memoPicked.forEach { image -> + memoArray.put(JSONObject().apply { + put("uri", image.uri.toString()) + put("name", image.name) + put("mime", image.mime) + }) + } + outState.putString(KEY_MEMO_IMAGES, memoArray.toString()) + outState.putInt(KEY_TAB, tab) + } + + private fun restoreState(state: Bundle?) { + if (state == null) return + tab = state.getInt(KEY_TAB, TAB_PUBLISH) + state.getStringArrayList(KEY_AI_HISTORY)?.let { aiHistory.addAll(it) } + + restoreArticleImages(state.getString(KEY_ARTICLE_IMAGES).orEmpty()) + restoreMemoImages(state.getString(KEY_MEMO_IMAGES).orEmpty()) + } + + private fun restoreArticleImages(raw: String) { + if (raw.isEmpty()) return + try { + val array = JSONArray(raw) + for (index in 0 until array.length()) { + val item = array.optJSONObject(index) ?: continue + val uri = Uri.parse(item.optString("uri")) + if (uri.toString().isEmpty()) continue + articlePicked.add( + ArticleImage( + picked = ImageUtils.PickedImage( + uri, + item.optString("name"), + item.optString("mime").ifEmpty { "image/jpeg" }, + ), + cid = item.optLong("cid"), + name = item.optString("name"), + url = item.optString("url"), + ) + ) + } + } catch (e: Exception) { + // 存的内容坏了就当没有,不影响使用 + } + } + + private fun restoreMemoImages(raw: String) { + if (raw.isEmpty()) return + try { + val array = JSONArray(raw) + for (index in 0 until array.length()) { + val item = array.optJSONObject(index) ?: continue + val uri = Uri.parse(item.optString("uri")) + if (uri.toString().isEmpty()) continue + memoPicked.add( + ImageUtils.PickedImage( + uri, + item.optString("name"), + item.optString("mime").ifEmpty { "image/jpeg" }, + ) + ) + } + } catch (e: Exception) { + // 同上,坏数据直接忽略 + } + } + + private fun bindViews() { + tabPublish = findViewById(R.id.tabPublish) + tabMemo = findViewById(R.id.tabMemo) + panelPublish = findViewById(R.id.panelPublish) + panelMemo = findViewById(R.id.panelMemo) + panelEmpty = findViewById(R.id.panelEmpty) + tvEmptyTitle = findViewById(R.id.tvEmptyTitle) + tvEmptyTip = findViewById(R.id.tvEmptyTip) + btnTheme = findViewById(R.id.btnTheme) + + etTitle = findViewById(R.id.etTitle) + etContent = findViewById(R.id.etContent) + spinnerCategory = findViewById(R.id.spinnerCategory) + etTags = findViewById(R.id.etTags) + btnPublish = findViewById(R.id.btnPublish) + + btnArticleImage = findViewById(R.id.btnArticleImage) + articleImages = findViewById(R.id.articleImages) + btnPolish = findViewById(R.id.btnPolish) + btnExpand = findViewById(R.id.btnExpand) + btnUndo = findViewById(R.id.btnUndo) + + etMemo = findViewById(R.id.etMemo) + memoImages = findViewById(R.id.memoImages) + btnAddImage = findViewById(R.id.btnAddImage) + btnMemo = findViewById(R.id.btnMemo) + visPrivate = findViewById(R.id.visPrivate) + visProtected = findViewById(R.id.visProtected) + visPublic = findViewById(R.id.visPublic) + + tvStatus = findViewById(R.id.tvStatus) + + btnSitePick = findViewById(R.id.btnSitePick) + setupSitePick() + + btnTheme.setImageResource(if (isNight()) R.drawable.ic_sun else R.drawable.ic_moon) + + // 发文面板可滚动:键盘弹出时把正在编辑的行滚到可见位置,标签联想才不会被挡 + (panelPublish as? ScrollView)?.let { scroll -> + etContent.setOnFocusChangeListener { _, focused -> + if (focused) revealInScroll(scroll, etContent) + } + // etTags 的焦点监听在 setupTagsInput() 里统一处理(滚入可视区 + 弹联想), + // View 只能挂一个 OnFocusChangeListener,这里再设会把它覆盖掉,故不重复设置。 + scroll.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitArticleCard() } + } + fitArticleCard() + } + + // ==================== 发布站点切换 ==================== + + /** 发布面板顶部的站点选择:与分类下拉同款弹窗,向上展开 */ + private fun setupSitePick() { + btnSitePick.text = "站点 · ${prefs.siteLabel(prefs.typechoCurrent)}" + btnSitePick.setOnClickListener { showSitePickPopup() } + } + + private fun showSitePickPopup() { + val count = prefs.siteCount() + if (count == 0) return + val labels = (0 until count).map { prefs.siteLabel(it) } + + val listView = ListView(this).apply { + adapter = ArrayAdapter( + this@MainActivity, + R.layout.item_spinner_dropdown, + labels.mapIndexed { i, name -> + if (i == prefs.typechoCurrent) "✓ $name" else name + }, + ) + dividerHeight = 0 + setPadding(0, dp(6), 0, dp(6)) + scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY + } + val listH = (labels.size * dp(46) + dp(12)).coerceAtMost(dp(320)) + val popupH = listH + dp(12) + val popup = PopupWindow(listView, btnSitePick.width, popupH, true).apply { + isOutsideTouchable = true + setBackgroundDrawable(Ui.popupPalette(this@MainActivity).background()) + elevation = dp(8).toFloat() + } + listView.setOnItemClickListener { _, _, position, _ -> + popup.dismiss() + if (position == prefs.typechoCurrent) return@setOnItemClickListener + prefs.typechoCurrent = position + btnSitePick.text = "站点 · ${prefs.siteLabel(position)}" + // 换站点后分类与标签要重新拉 + metasLoaded = false + categories = emptyList() + tagIds = emptyMap() + tagNames.clear() + applyCategories(emptyList()) + dismissTagPopup() + setStatus("") + loadMetas() + } + val loc = IntArray(2) + val rootLoc = IntArray(2) + btnSitePick.getLocationOnScreen(loc) + btnSitePick.rootView.getLocationOnScreen(rootLoc) + popup.showAtLocation( + btnSitePick.rootView, + Gravity.TOP or Gravity.START, + loc[0] - rootLoc[0], + loc[1] - rootLoc[1] - popupH - dp(6), + ) + } + + /** 分类下拉改为自绘弹窗:与输入框等宽、左右对齐,底部与输入框留一点距离 */ + private fun setupCategoryDropdown() { + spinnerCategory.setOnTouchListener { _, event -> + if (event.actionMasked == MotionEvent.ACTION_UP) showCategoryPopup() + true + } + } + + private fun showCategoryPopup() { + val names = categories.map { it.name } + if (names.isEmpty()) return + + val listView = ListView(this).apply { + adapter = ArrayAdapter(this@MainActivity, R.layout.item_spinner_dropdown, names) + dividerHeight = 0 + // 滚动条落到背景内边距里,不贴圆角 + setPadding(0, dp(6), 0, dp(6)) + scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY + } + val listH = (names.size * dp(46) + dp(12)).coerceAtMost(dp(320)) + val popupH = listH + dp(12) // 上下各 6dp 背景内边距 + // 宽度只比最宽的分类名稍宽一点,不再与输入框等宽; + // extraDp 覆盖背景 6dp×2 + 行内边距 14dp×2 + 滚动条 + val popupW = Ui.menuWidth( + this, names, textSizeSp = 15f, extraDp = 52, minDp = 110, maxDp = 320, + ) + val popup = PopupWindow(listView, popupW, popupH, true).apply { + isOutsideTouchable = true + setBackgroundDrawable(Ui.popupPalette(this@MainActivity).background()) + elevation = dp(8).toFloat() + } + listView.setOnItemClickListener { _, _, position, _ -> + spinnerCategory.setSelection(position) + popup.dismiss() + } + val loc = IntArray(2) + val rootLoc = IntArray(2) + spinnerCategory.getLocationOnScreen(loc) + spinnerCategory.rootView.getLocationOnScreen(rootLoc) + popup.showAtLocation( + spinnerCategory.rootView, + Gravity.TOP or Gravity.START, + loc[0] - rootLoc[0], + loc[1] - rootLoc[1] - popupH - dp(6), // 底部与输入框之间留 6dp + ) + } + + /** + * 发文卡片高度:无键盘时按可视高度撑满;键盘弹出时保持原高度, + * 多出的内容交给外层 ScrollView 滚动,正文不会被固定行挤没。 + */ + private fun fitArticleCard() { + val scroll = panelPublish as? ScrollView ?: return + val card = findViewById(R.id.cardArticle) ?: return + scroll.post { + val inner = scroll.getChildAt(0) as? ViewGroup ?: return@post + // 只累加除正文卡片外各行的真实高度与 margin。 + // 不能用 inner.height - card.height:fillViewport 会把 inner 拉伸到视口高度, + // 差值里混入了底部空白,正文卡片就吃不掉它,标签行下方多出一段空隙, + // 到发布按钮的距离就与发博面板不一致。 + var others = 0 + for (i in 0 until inner.childCount) { + val child = inner.getChildAt(i) + if (child === card) continue + others += child.height + val lp = child.layoutParams as? ViewGroup.MarginLayoutParams + if (lp != null) others += lp.topMargin + lp.bottomMargin + } + if (basePanelHeight == 0 || scroll.height > basePanelHeight) { + basePanelHeight = scroll.height + } + val keyboardShown = basePanelHeight - scroll.height > dp(120) + val target = if (keyboardShown && articleCardTarget > 0) { + articleCardTarget + } else { + (scroll.height - others).coerceAtLeast(dp(280)).also { articleCardTarget = it } + } + if (card.minimumHeight != target) card.minimumHeight = target + + var fixed = 0 + for (i in 0 until card.childCount) { + val child = card.getChildAt(i) + if (child !== etContent) fixed += child.height + } + val contentHeight = (target - fixed).coerceAtLeast(dp(120)) + if (etContent.layoutParams.height != contentHeight) { + etContent.layoutParams.height = contentHeight + etContent.requestLayout() + } + } + } + + /** 键盘展开约 200ms 后布局才稳定,再把目标行滚到可见位置 */ + private fun revealInScroll(scroll: ScrollView, target: View) { + scroll.postDelayed({ + scroll.smoothScrollTo(0, (offsetInScroll(scroll, target) - dp(10)).coerceAtLeast(0)) + }, 260) + } + + /** target 在 scroll 内容坐标系里的纵向偏移 */ + private fun offsetInScroll(scroll: ScrollView, target: View): Int { + var y = 0 + var current: View? = target + while (current != null && current !== scroll) { + y += current.top + current = current.parent as? View + } + return y + } + + // ==================== 深浅色 ==================== + + /** 在 super.onCreate 之前定好主题,避免界面先亮一下再跳变 */ + private fun applyNightMode() { + val target = prefs.nightMode() + if (AppCompatDelegate.getDefaultNightMode() != target) { + AppCompatDelegate.setDefaultNightMode(target) + } + } + + private fun isNight(): Boolean = + (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == + Configuration.UI_MODE_NIGHT_YES + + private fun toggleTheme() { + val night = isNight() + prefs.darkMode = if (night) Prefs.MODE_LIGHT else Prefs.MODE_DARK + // setDefaultNightMode 会自动重建当前界面,不用自己 recreate + AppCompatDelegate.setDefaultNightMode( + if (night) AppCompatDelegate.MODE_NIGHT_NO else AppCompatDelegate.MODE_NIGHT_YES + ) + } + + // ==================== Tab 切换 ==================== + + private fun showTab(target: Int) { + tab = target + val isPublish = target == TAB_PUBLISH + val ready = if (isPublish) prefs.typechoReady else prefs.memosReady + + tabPublish.setBackgroundResource(if (isPublish) R.drawable.bg_segment_on else 0) + tabMemo.setBackgroundResource(if (isPublish) 0 else R.drawable.bg_segment_on) + tabPublish.setTextColor( + color(if (isPublish) R.color.text else R.color.text_secondary) + ) + tabMemo.setTextColor( + color(if (isPublish) R.color.text_secondary else R.color.text) + ) + + panelPublish.visibility = if (isPublish && ready) View.VISIBLE else View.GONE + panelMemo.visibility = if (!isPublish && ready) View.VISIBLE else View.GONE + panelEmpty.visibility = if (ready) View.GONE else View.VISIBLE + + // 发布键在面板外面(固定在底部),跟着 Tab 与配置状态切 + btnPublish.visibility = if (isPublish && ready) View.VISIBLE else View.GONE + btnMemo.visibility = if (!isPublish && ready) View.VISIBLE else View.GONE + + if (!ready) { + tvEmptyTitle.text = getString( + if (isPublish) R.string.empty_typecho_title else R.string.empty_memos_title + ) + tvEmptyTip.text = getString( + if (isPublish) R.string.empty_typecho else R.string.empty_memos + ) + } + + setStatus("") + + if (isPublish && ready && !metasLoaded) { + loadMetas() + } + } + + // ==================== 分类 / 标签 ==================== + + /** + * 标签输入框:自绘联想弹窗,位置与分类下拉同款(同背景、同 6dp 间距), + * 也可直接敲新标签;逗号作为分隔符。 + */ + private fun setupTagsInput() { + etTags.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + if (!suppressTagWatch) updateTagPopup() + } + override fun afterTextChanged(s: Editable?) {} + }) + // 焦点监听只此一处:输入框拿到焦点时既要把本行滚到键盘上方, + // 又要在滚动结束后再弹联想,否则弹窗按滚动前的旧坐标定位,会被键盘挡住或错位。 + etTags.setOnFocusChangeListener { _, focused -> + if (!focused) { + dismissTagPopup() + return@setOnFocusChangeListener + } + val scroll = panelPublish as? ScrollView + if (scroll == null) { + updateTagPopup() + return@setOnFocusChangeListener + } + revealInScroll(scroll, etTags) + // revealInScroll 在 260ms 后滚动,这里留出余量等它停稳再定位弹窗 + scroll.postDelayed({ + if (etTags.hasFocus()) updateTagPopup() + }, 320) + } + } + + /** + * 先用上次成功拉取的标签名填充联想池。 + * 进入发文页立刻就能联想,不必等 /api/tags 的网络往返; + * 请求失败时也不会出现「一个候选都没有」。 + */ + private fun restoreTagCache() { + val cached = prefs.tagCache + if (cached.isBlank()) return + // 新快照用换行分隔;旧版本是逗号格式,读时兼容,升级后第一次联网即自动改写 + val separator = if (cached.contains('\n')) "\n" else "," + val names = cached.split(separator).map { it.trim() }.filter { it.isNotEmpty() } + if (names.isEmpty()) return + tagNames.clear() + tagNames.addAll(names.sorted()) + } + + /** 选中标签回填时暂停联想,避免弹窗反复闪现 */ + private var suppressTagWatch = false + + /** 取光标前最后一个逗号后的片段作为联想关键字 */ + private fun currentTagPrefix(): Pair { + val text = etTags.text?.toString().orEmpty() + val cursor = etTags.selectionStart.coerceAtLeast(0).coerceAtMost(text.length) + val head = text.substring(0, cursor) + val comma = maxOf(head.lastIndexOf(','), head.lastIndexOf(',')) + return Pair(comma + 1, head.substring(comma + 1).trim()) + } + + private fun updateTagPopup() { + // 只有标签输入框正持有焦点才弹:/api/tags 回来时用户可能已经点去别处, + // 旧写法会自己冒出一个下拉,看起来像界面失控。 + if (!etTags.hasFocus()) { + dismissTagPopup() + return + } + val (_, prefix) = currentTagPrefix() + if (prefix.isEmpty() || tagNames.isEmpty()) { + dismissTagPopup() + return + } + // 不再排除「与输入完全一致」的标签:输入完整标签名时若把自身过滤掉, + // 候选为空会直接关掉弹窗,看起来就是「联想没有了」。 + // 前缀命中的排在前面,同前缀时短标签优先,便于按字数递进选择。 + val matches = tagNames + .filter { it.contains(prefix, ignoreCase = true) } + .sortedWith(compareBy({ !it.startsWith(prefix, ignoreCase = true) }, { it.length })) + .take(30) + if (matches.isEmpty()) { + dismissTagPopup() + return + } + showTagPopup(matches) + } + + private fun dismissTagPopup() { + tagPopup?.dismiss() + tagPopup = null + } + + /** + * 标签联想弹窗:与分类下拉同款背景与项布局,固定向上展开, + * 底部与输入框留 6dp,不遮挡输入法与正在输入的内容。 + */ + private fun showTagPopup(matches: List) { + dismissTagPopup() + val listView = ListView(this).apply { + adapter = ArrayAdapter(this@MainActivity, R.layout.item_spinner_dropdown, matches) + dividerHeight = 0 + setPadding(0, dp(6), 0, dp(6)) + scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY + } + val listH = (matches.size * dp(46) + dp(12)).coerceAtMost(dp(320)) + val popupH = listH + dp(12) + // 联想宽度跟随候选文字:extraDp 覆盖背景 6dp×2 + 行内边距 14dp×2 + // + 滚动条余量,保证 4~6 个字的标签完整显示,不再被 ellipsize 截成两个字。 + // maxDp 只作兜底,实际再限制到屏幕宽度内,避免长标签把弹窗顶出屏幕。 + val screenW = resources.displayMetrics.widthPixels - dp(24) + val popupW = Ui.menuWidth( + this, matches, textSizeSp = 15f, extraDp = 56, minDp = 130, maxDp = 420, + ).coerceAtMost(screenW) + val popup = PopupWindow(listView, popupW, popupH, false).apply { + isOutsideTouchable = true + setBackgroundDrawable(Ui.popupPalette(this@MainActivity).background()) + elevation = dp(8).toFloat() + } + listView.setOnItemClickListener { _, _, position, _ -> + val chosen = matches[position] + val text = etTags.text?.toString().orEmpty() + val cursor = etTags.selectionStart.coerceAtLeast(0).coerceAtMost(text.length) + val (start, _) = currentTagPrefix() + val tail = text.substring(cursor) + val insert = "$chosen, " + suppressTagWatch = true + etTags.setText(text.substring(0, start) + insert + tail) + etTags.setSelection(start + insert.length) + suppressTagWatch = false + dismissTagPopup() + etTags.requestFocus() + } + val loc = IntArray(2) + val rootLoc = IntArray(2) + etTags.getLocationOnScreen(loc) + etTags.rootView.getLocationOnScreen(rootLoc) + val rootW = etTags.rootView.width + val x = (loc[0] - rootLoc[0]) + .coerceIn(0, (rootW - popupW).coerceAtLeast(0)) + + val gap = dp(6) + val screenH = resources.displayMetrics.heightPixels + val spaceAbove = loc[1] - gap + val spaceBelow = screenH - (loc[1] + etTags.height) - gap + // 默认向上展开;上方放不下、下方更宽裕时改为向下。 + // 原来固定向上,输入框位置偏高时弹窗会被顶出屏幕,表现为「联想没有出现」。 + val showBelow = spaceAbove < popupH && spaceBelow > spaceAbove + val finalH = popupH + .coerceAtMost(if (showBelow) spaceBelow else spaceAbove) + .coerceAtLeast(dp(60)) + popup.height = finalH + val yScreen = if (showBelow) { + loc[1] + etTags.height + gap + } else { + loc[1] - finalH - gap + } + popup.showAtLocation( + etTags.rootView, + Gravity.TOP or Gravity.START, + x, + (yScreen - rootLoc[1]).coerceAtLeast(0), + ) + tagPopup = popup + } + + /** 拉一次分类与标签,失败时只提示、不阻塞发布(可以不带分类标签发) */ + private fun loadMetas() { + if (metasLoading) return + metasLoading = true + + lifecycleScope.launch { + // 分类与标签互不依赖:并行拉取,且各自 runCatching。 + // 旧写法串行 + 共用一个 try,分类接口一报错,标签请求就整个跳过, + // 联想池永远为空 —— 这是「输入已有标签也没有下拉」的另一条根因。 + val categoryJob = async { runCatching { TypechoApi.categories(prefs) } } + val tagJob = async { runCatching { TypechoApi.tags(prefs) } } + try { + val categories = categoryJob.await() + val tags = tagJob.await() + categories.onSuccess { applyCategories(it) } + tags.onSuccess { applyTags(it) } + // 以标签是否成功作为「已加载」的判据:标签是联想的关键路径, + // 失败就留 false,下次进发文页再试一次(期间由本地快照先顶上)。 + if (tags.isSuccess) metasLoaded = true + // 接口失败或一个标签都没拿到时,用本地快照兜底 + if (tagNames.isEmpty()) restoreTagCache() + (categories.exceptionOrNull() ?: tags.exceptionOrNull())?.let { + setStatus(getString(R.string.metas_failed, friendly(it))) + } + } finally { + metasLoading = false + } + } + } + + private fun applyCategories(list: List) { + categories = list + val labels = list.map { it.name } + + val adapter = ArrayAdapter(this, R.layout.item_spinner, labels) + adapter.setDropDownViewResource(R.layout.item_spinner_dropdown) + spinnerCategory.adapter = adapter + setupCategoryDropdown() + } + + private fun applyTags(list: List) { + tagIds = list.associate { it.name to it.mid } + tagNames.clear() + tagNames.addAll(list.map { it.name }.sorted()) + // 只有真正拉到数据才覆盖快照,避免一次失败把可用缓存冲成空。 + // 用换行分隔:标签名本身可能含逗号(如「Kotlin, Android」),逗号拼接会把它拆坏。 + if (tagNames.isNotEmpty()) prefs.tagCache = tagNames.joinToString("\n") + updateTagPopup() + } + + private fun selectedCategoryId(): Long { + val index = spinnerCategory.selectedItemPosition + return categories.getOrNull(index)?.mid ?: 0L + } + + private fun parseTags(raw: String): List = + raw.split(',', ',') + .map { it.trim() } + .filter { it.isNotEmpty() } + .distinct() + + /** 逐个解析标签名:已有的直接用 mid,没有的先建再取 mid */ + private suspend fun resolveTagIds(names: List): List { + val result = mutableListOf() + for (name in names) { + val existing = tagIds[name] + if (existing != null && existing > 0) { + result.add(existing) + continue + } + + setStatus("创建标签:$name…") + val created = TypechoApi.createTag(prefs, name) + if (created > 0) { + result.add(created) + tagIds = tagIds + (name to created) + if (!tagNames.contains(name)) { + tagNames.add(name) + tagNames.sort() + } + } + } + return result + } + + // ==================== 发文:Typecho ==================== + + private fun publish() { + if (busy || uploading) return + + val content = etContent.text.toString().trim() + if (content.isEmpty()) { + toast(getString(R.string.err_empty_content)) + return + } + if (!prefs.typechoReady) { + showTab(TAB_PUBLISH) + return + } + + // 传了图却没插进正文:先问一句,免得图传上去了文章里一张也没有 + val unused = articlePicked.count { it.url.isNotEmpty() && !content.contains(it.url) } + if (unused > 0) { + AlertDialog.Builder(this) + .setTitle(getString(R.string.image_unused_title)) + .setMessage(getString(R.string.image_unused_msg, unused)) + .setNegativeButton(getString(R.string.image_unused_back), null) + .setPositiveButton(getString(R.string.image_unused_go)) { _, _ -> doPublish() } + .show() + return + } + + doPublish() + } + + private fun doPublish() { + if (busy || uploading) return + val content = etContent.text.toString().trim() + if (content.isEmpty()) { + toast(getString(R.string.err_empty_content)) + return + } + + val title = etTitle.text.toString().trim().ifEmpty { makeTitle(content) } + val categoryId = selectedCategoryId() + val tagList = parseTags(etTags.text.toString()) + + busy = true + btnPublish.text = getString(R.string.publishing) + setStatus(getString(R.string.publishing)) + + lifecycleScope.launch { + try { + val tagIdList = resolveTagIds(tagList) + val mids = mutableListOf() + if (categoryId > 0) mids.add(categoryId) + mids.addAll(tagIdList) + + val result = TypechoApi.publish( + prefs, + title, + content, + mids, + articlePicked.map { it.cid }, + ) + + // 成功后立刻清空编辑区,接着写下一条;链接留在状态行 + clearArticleEditor() + // 链接比普通提示留得久一些(10 秒),否则长 URL 还没读清就消失了 + setStatus(getString(R.string.publish_done, result.permalink), 10_000L) + // 点一下状态行即可复制链接,省得手抄 + tvStatus.setOnClickListener { + val clipboard = getSystemService(android.content.ClipboardManager::class.java) + clipboard?.setPrimaryClip( + android.content.ClipData.newPlainText("链接", result.permalink) + ) + toast("链接已复制") + } + toast(getString(R.string.publish_pending)) + } catch (e: Exception) { + val message = friendly(e) + setStatus("发布失败:$message") + toast("发布失败:$message") + } finally { + busy = false + btnPublish.text = getString(R.string.publish) + } + } + } + + /** + * 发布成功后清空发文编辑区。 + * + * 链接与提示留在状态行,正文与配图一起清掉,方便接着写下一篇; + * 撤回栈也一并清空——上一篇文章的旧版本,留在这里只会误用。 + */ + private fun clearArticleEditor() { + etTitle.setText("") + etContent.setText("") + etTags.setText("") + articlePicked.clear() + aiHistory.clear() + renderArticleImages() + renderAiChips() + if (spinnerCategory.adapter != null) { + spinnerCategory.setSelection(0) + } + etContent.clearFocus() + etTitle.clearFocus() + } + + // ==================== 发文配图 ==================== + + private fun pickArticleImagesNow() { + if (uploading || busy) return + if (articlePicked.size >= MAX_ARTICLE_IMAGES) { + toast(getString(R.string.image_full, MAX_ARTICLE_IMAGES)) + return + } + pickArticleImages.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + } + + /** + * 选完就传,不等发布。 + * + * 这样点缩略图能立刻拿到真实地址插入正文,发布时也不用再等一轮上传; + * 传失败的那几张只影响自己,不打断其它图片。 + */ + private fun uploadArticleImages(uris: List) { + if (uploading || busy) return + if (!prefs.typechoReady) { + setStatus(getString(R.string.upload_need_config)) + return + } + + val room = MAX_ARTICLE_IMAGES - articlePicked.size + if (room <= 0) { + toast(getString(R.string.image_full, MAX_ARTICLE_IMAGES)) + return + } + val batch = uris.take(room) + + uploading = true + refreshArticleImageButton() + + lifecycleScope.launch { + var failed = 0 + var reason = "" + batch.forEachIndexed { index, uri -> + setStatus(getString(R.string.uploading_image, index + 1, batch.size)) + try { + val picked = withContext(Dispatchers.IO) { ImageUtils.picked(this@MainActivity, uri) } + val bytes = withContext(Dispatchers.IO) { + ImageUtils.readBytes(this@MainActivity, uri) + } + val uploaded = TypechoApi.upload(prefs, bytes, picked.name, picked.mime) + articlePicked.add( + ArticleImage(picked, uploaded.cid, uploaded.name, uploaded.url) + ) + renderArticleImages() + } catch (e: Exception) { + failed++ + reason = friendly(e) + } + } + + uploading = false + refreshArticleImageButton() + if (failed == 0) { + setStatus(getString(R.string.upload_done, batch.size)) + } else { + setStatus(getString(R.string.upload_partial, failed, reason)) + } + } + } + + /** + * 缩略图后台解码。 + * 原实现直接在 onResume/添加/删除时同步解码,20 张图删一张会重解 19 张, + * 首帧明显卡顿。现在解码走 IO,且 ImageUtils 内有字节限额缓存。 + */ + private fun loadThumbAsync(view: ImageView, uri: Uri, maxSize: Int) { + view.tag = uri + lifecycleScope.launch { + val bitmap = withContext(Dispatchers.IO) { + ImageUtils.loadThumbnail(this@MainActivity, uri, maxSize) + } + // 视图可能已被复用/移除,tag 不一致就丢弃结果 + if (bitmap != null && view.tag == uri) view.setImageBitmap(bitmap) + } + } + + private fun renderArticleImages() { + articleImages.removeAllViews() + val side = dp(44) + val gap = dp(8) + + articlePicked.forEachIndexed { index, image -> + val box = FrameLayout(this) + box.layoutParams = LinearLayout.LayoutParams(side, side).apply { rightMargin = gap } + box.background = ContextCompat.getDrawable(this, R.drawable.bg_input) + + val preview = ImageView(this) + preview.layoutParams = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ) + preview.scaleType = ImageView.ScaleType.CENTER_CROP + loadThumbAsync(preview, image.picked.uri, 180) + box.addView(preview) + + val remove = TextView(this) + val closeSide = dp(18) + remove.layoutParams = FrameLayout.LayoutParams(closeSide, closeSide).apply { + gravity = Gravity.TOP or Gravity.END + topMargin = dp(2) + rightMargin = dp(2) + } + remove.background = ContextCompat.getDrawable(this, R.drawable.bg_thumb_close) + remove.gravity = Gravity.CENTER + remove.text = "×" + remove.setTextColor(0xFFFFFFFF.toInt()) + remove.textSize = 12f + remove.setOnClickListener { + if (index in articlePicked.indices) { + articlePicked.removeAt(index) + renderArticleImages() + } + } + box.addView(remove) + + // 点图本体 = 把 Markdown 图片代码插到光标处 + box.setOnClickListener { insertImageMarkdown(image) } + + articleImages.addView(box) + } + + refreshArticleImageButton() + } + + private fun refreshArticleImageButton() { + btnArticleImage.alpha = if (uploading) 0.55f else 1f + btnArticleImage.text = if (uploading) { + getString(R.string.uploading) + } else if (articlePicked.isEmpty()) { + getString(R.string.add_image) + } else { + "${getString(R.string.add_image)}(${articlePicked.size}/$MAX_ARTICLE_IMAGES)" + } + } + + /** 把 ![名字](地址) 插到当前光标处;名字里的方括号会让语法断掉,统一换掉 */ + private fun insertImageMarkdown(image: ArticleImage) { + val alt = image.name.replace('[', ' ').replace(']', ' ').trim().ifEmpty { "图片" } + val url = image.url + if (url.isEmpty()) { + toast(getString(R.string.image_no_url)) + return + } + + val editable = etContent.text + val start = etContent.selectionStart.coerceIn(0, editable.length) + val end = etContent.selectionEnd.coerceIn(0, editable.length) + val from = minOf(start, end) + val to = maxOf(start, end) + + val snippet = buildString { + if (from > 0 && editable[from - 1] != '\n') append("\n") + append("![") + append(alt) + append("](") + append(url) + append(")") + append("\n") + } + + editable.replace(from, to, snippet) + etContent.setSelection(minOf(from + snippet.length, etContent.text.length)) + } + + // ==================== 润色 / 完善 / 撤回 ==================== + + private fun runAi(mode: String) { + if (busy || uploading) return + + val content = etContent.text.toString() + if (content.trim().isEmpty()) { + toast(getString(R.string.err_empty_content)) + return + } + if (!prefs.aiReady) { + setStatus(getString(R.string.ai_need_key)) + toast(getString(R.string.ai_need_key)) + startActivity(Intent(this, SettingsActivity::class.java)) + return + } + if (content.length > AiApi.MAX_INPUT) { + setStatus(getString(R.string.ai_too_long, AiApi.MAX_INPUT)) + toast(getString(R.string.ai_too_long, AiApi.MAX_INPUT)) + return + } + + val polishing = mode == AiApi.MODE_POLISH + busy = true + setChipsEnabled(false) + setStatus(getString(if (polishing) R.string.ai_polishing else R.string.ai_expanding)) + // 点按钮自动全选:整篇都是处理对象 + etContent.selectAll() + + lifecycleScope.launch { + try { + val result = AiApi.run(prefs, content, mode) + // 改写成功才记一版,撤回才有东西可回 + aiHistory.add(content) + if (aiHistory.size > MAX_AI_HISTORY) aiHistory.removeAt(0) + + etContent.setText(result) + etContent.setSelection(result.length) + setStatus(getString(if (polishing) R.string.ai_polished else R.string.ai_expanded)) + } catch (e: Exception) { + val message = friendly(e) + setStatus(getString(R.string.ai_failed, message)) + toast(getString(R.string.ai_failed, message)) + } finally { + busy = false + setChipsEnabled(true) + renderAiChips() + } + } + } + + private fun undoAi() { + if (busy || uploading) return + if (aiHistory.isEmpty()) { + toast(getString(R.string.ai_undo_empty)) + return + } + + val previous = aiHistory.removeAt(aiHistory.lastIndex) + etContent.setText(previous) + etContent.setSelection(previous.length) + setStatus( + getString(if (aiHistory.isEmpty()) R.string.ai_undo_last else R.string.ai_undo_done) + ) + renderAiChips() + } + + private fun renderAiChips() { + btnUndo.alpha = if (aiHistory.isEmpty()) 0.45f else 1f + } + + private fun setChipsEnabled(enabled: Boolean) { + listOf(btnPolish, btnExpand, btnUndo).forEach { chip -> + chip.isEnabled = enabled + chip.alpha = if (enabled) 1f else 0.55f + } + if (enabled) renderAiChips() + } + + // ==================== 发博:Memos ==================== + + private fun publishMemo() { + if (busy || uploading) return + + val text = etMemo.text.toString().trim() + if (text.isEmpty() && memoPicked.isEmpty()) { + toast(getString(R.string.err_empty_memo)) + return + } + if (!prefs.memosReady) { + showTab(TAB_MEMO) + return + } + + val total = memoPicked.size + busy = true + btnMemo.text = getString(R.string.publishing) + setStatus(getString(R.string.publishing)) + + lifecycleScope.launch { + try { + val uploaded = mutableListOf() + memoPicked.forEachIndexed { index, image -> + setStatus("上传图片 ${index + 1}/$total…") + val bytes = withContext(Dispatchers.IO) { + ImageUtils.readBytes(this@MainActivity, image.uri) + } + uploaded.add(MemosApi.upload(prefs, bytes, image.name, image.mime)) + } + + setStatus(getString(R.string.publishing)) + val memo = MemosApi.create(prefs, text, prefs.memosVisibility, uploaded) + + etMemo.setText("") + memoPicked.clear() + renderMemoImages() + setStatus(getString(R.string.memo_done, memo.link)) + toast(getString(R.string.publish_ok)) + } catch (e: Exception) { + val message = friendly(e) + setStatus("发布失败:$message") + toast("发布失败:$message") + } finally { + busy = false + btnMemo.text = getString(R.string.memo_publish) + } + } + } + + // ==================== 发博配图 ==================== + + private fun renderMemoImages() { + memoImages.removeAllViews() + val side = dp(76) + val gap = dp(8) + + memoPicked.forEachIndexed { index, image -> + val box = FrameLayout(this) + box.layoutParams = LinearLayout.LayoutParams(side, side).apply { rightMargin = gap } + box.background = ContextCompat.getDrawable(this, R.drawable.bg_input) + + val preview = ImageView(this) + preview.layoutParams = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ) + preview.scaleType = ImageView.ScaleType.CENTER_CROP + loadThumbAsync(preview, image.uri, 240) + box.addView(preview) + + val remove = TextView(this) + val closeSide = dp(20) + remove.layoutParams = FrameLayout.LayoutParams(closeSide, closeSide).apply { + gravity = Gravity.TOP or Gravity.END + topMargin = dp(3) + rightMargin = dp(3) + } + remove.background = ContextCompat.getDrawable(this, R.drawable.bg_thumb_close) + remove.gravity = Gravity.CENTER + remove.text = "×" + remove.setTextColor(0xFFFFFFFF.toInt()) + remove.textSize = 13f + remove.setOnClickListener { + if (index in memoPicked.indices) { + memoPicked.removeAt(index) + renderMemoImages() + } + } + box.addView(remove) + + memoImages.addView(box) + } + + btnAddImage.visibility = + if (memoPicked.size >= MAX_MEMO_IMAGES) View.GONE else View.VISIBLE + btnAddImage.text = if (memoPicked.isEmpty()) { + getString(R.string.add_image) + } else { + "${getString(R.string.add_image)}(${memoPicked.size}/$MAX_MEMO_IMAGES)" + } + } + + private fun setVisibilityChip(value: String) { + prefs.memosVisibility = value + applyChip(visPrivate, value == Prefs.VISIBILITY_PRIVATE) + applyChip(visProtected, value == Prefs.VISIBILITY_PROTECTED) + applyChip(visPublic, value == Prefs.VISIBILITY_PUBLIC) + } + + private fun applyChip(chip: TextView, selected: Boolean) { + chip.setBackgroundResource(if (selected) R.drawable.bg_chip_on else R.drawable.bg_chip_off) + chip.setTextColor( + if (selected) color(R.color.on_brand) + else color(R.color.text_secondary) + ) + } + + // ==================== 通用 ==================== + + /** 站点返回的英文报错翻成人能看懂的一句 */ + private fun friendly(e: Throwable): String { + val raw = e.message ?: "未知错误" + return when { + raw.contains("disabled", true) -> + "插件里没开启对应接口,去 TypechoToObsidian 设置里勾上「文件管理」" + raw.contains("logged in", true) -> + "插件开了「高敏接口校验后台登录」,在插件设置里关掉" + else -> raw + } + } + + /** 没写标题时取正文前 20 字,去掉换行与常见 Markdown 符号 */ + private fun makeTitle(content: String): String { + val plain = content + .replace(Regex("[\\r\\n]+"), " ") + .replace(Regex("!?\\[[^\\]]*\\]\\([^)]*\\)"), " ") + .replace(Regex("[#>*`_~\\[\\]()]"), "") + .replace(Regex("\\s+"), " ") + .trim() + return if (plain.length <= 20) plain else plain.substring(0, 20) + } + + /** + * 状态行:没有内容时不占位。 + * 普通提示 1 秒后自动消失,不长期占着发布按钮下方的位置; + * 发布成功的链接由调用方传更长的 autoHideMs,并单独挂点击复制。 + * 结果文字仍会以 Toast 短暂弹出,失败原因不会因此看不到。 + */ + private fun setStatus(text: String, autoHideMs: Long = 1000L) { + statusHandler.removeCallbacks(hideStatus) + tvStatus.text = text + tvStatus.visibility = if (text.isEmpty()) View.GONE else View.VISIBLE + // 清掉上一次(发布成功)挂的复制监听,避免复制到旧链接 + tvStatus.setOnClickListener(null) + if (text.isNotEmpty() && autoHideMs > 0) { + statusHandler.postDelayed(hideStatus, autoHideMs) + } + } + + private val statusHandler = Handler(Looper.getMainLooper()) + private val hideStatus = Runnable { + tvStatus.text = "" + tvStatus.visibility = View.GONE + } + + private fun color(id: Int): Int = ContextCompat.getColor(this, id) + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + private fun toast(text: String) { + Toast.makeText(this, text, Toast.LENGTH_SHORT).show() + } + + companion object { + /** 首页发布菜单传入的初始面板:publish / memo */ + const val EXTRA_TAB = "extra_tab" + + const val TAB_PUBLISH = 0 + const val TAB_MEMO = 1 + const val MAX_MEMO_IMAGES = 9 + const val MAX_ARTICLE_IMAGES = 20 + const val MAX_AI_HISTORY = 20 + const val KEY_AI_HISTORY = "ai_history" + const val KEY_ARTICLE_IMAGES = "article_images" + const val KEY_MEMO_IMAGES = "memo_images" + const val KEY_TAB = "current_tab" + } +} diff --git a/src/main/java/com/shitoucuo/postpad/MdThemePlugin.kt b/src/main/java/com/shitoucuo/postpad/MdThemePlugin.kt new file mode 100644 index 0000000..182ebb2 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/MdThemePlugin.kt @@ -0,0 +1,38 @@ +package com.shitoucuo.postpad + +import android.content.Context +import androidx.core.content.ContextCompat +import io.noties.markwon.AbstractMarkwonPlugin +import io.noties.markwon.core.MarkwonTheme + +/** + * Markdown 排版样式:标题字号层次、代码底色、引用条、分割线、链接色。 + * 颜色全部取自主题资源(带 values-night 变体),深浅色自动适配; + * 主题切换会重建 Activity,Markwon 随之重建,样式跟随。 + */ +class MdThemePlugin(private val context: Context) : AbstractMarkwonPlugin() { + + private val d = context.resources.displayMetrics.density + + override fun configureTheme(builder: MarkwonTheme.Builder) { + builder + // # / ## / ### ... 字号逐级递减 + .headingTextSizeMultipliers(floatArrayOf(1.5f, 1.32f, 1.2f, 1.1f, 1.05f, 1f)) + .headingBreakHeight((1 * d).toInt()) + .headingBreakColor(ContextCompat.getColor(context, R.color.divider)) + // 行内代码与代码块 + .codeBackgroundColor(ContextCompat.getColor(context, R.color.input_bg)) + .codeTextColor(ContextCompat.getColor(context, R.color.text)) + .codeTextSize((13 * d).toInt()) + .codeBlockBackgroundColor(ContextCompat.getColor(context, R.color.input_bg)) + .codeBlockTextColor(ContextCompat.getColor(context, R.color.text)) + .codeBlockTextSize((13 * d).toInt()) + .codeBlockMargin((8 * d).toInt()) + // 引用条用品牌橙,分割线用主题分隔色,链接可点击 + .blockQuoteColor(ContextCompat.getColor(context, R.color.brand)) + .blockQuoteWidth((3 * d).toInt()) + .thematicBreakColor(ContextCompat.getColor(context, R.color.divider)) + .thematicBreakHeight((1 * d).toInt()) + .linkColor(ContextCompat.getColor(context, R.color.brand)) + } +} diff --git a/src/main/java/com/shitoucuo/postpad/MemosApi.kt b/src/main/java/com/shitoucuo/postpad/MemosApi.kt new file mode 100644 index 0000000..6f84d94 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/MemosApi.kt @@ -0,0 +1,265 @@ +package com.shitoucuo.postpad + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.MultipartBody +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject +import java.util.concurrent.TimeUnit + +/** + * Memos 官方 REST API 的最小封装(与 Obsidian 的 Memos 插件同一条链路)。 + * + * 鉴权:Authorization: Bearer + * 建博:POST /api/v1/memos(v0.22+),老版本是 /api/v1/memo,404/405 时自动换一个再试 + * 传图:POST /api/v1/resource/blob(multipart,字段名 file),拿到资源 id 后 + * 随 memo 的 resourceIdList 一起提交,与网页端上传完全一致 + */ +object MemosApi { + + private val JSON = "application/json; charset=utf-8".toMediaType() + + private val client: OkHttpClient = Http.newWith(20, 180, 120, TimeUnit.SECONDS) + + class ApiException(message: String, val code: Int = 0) : Exception(message) + + data class UploadedResource(val id: Any, val link: String) + + data class CreatedMemo(val id: String, val link: String) + + /** Memos 列表项:正文就是 Markdown,图片在 resourceList 里 */ + data class MemoItem( + val id: String, + val content: String, + val createdTs: Long, + val pinned: Boolean, + val images: List, + ) + + data class MemoPage(val memos: List, val nextPageToken: String) + + suspend fun check(prefs: Prefs): String = withContext(Dispatchers.IO) { + val text = exec(baseBuilder(prefs).url(prefs.memosUrl + "/api/v1/status").get().build()) + val json = try { + JSONObject(text) + } catch (e: Exception) { + // 地址填错时常常返回登录页或 404 页面,这里给出可操作的提示 + throw ApiException("服务器返回的不是 JSON,检查地址是否为 Memos 根地址(不要带 /api/v1)") + } + val version = json.optJSONObject("profile")?.optString("version").orEmpty() + if (version.isNotEmpty()) "连接正常,Memos v$version" else "连接正常" + } + + suspend fun upload( + prefs: Prefs, + bytes: ByteArray, + filename: String, + mime: String, + ): UploadedResource = withContext(Dispatchers.IO) { + val body = MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", filename, bytes.toRequestBody(mime.toMediaTypeOrNull())) + .build() + + val request = baseBuilder(prefs) + .url(prefs.memosUrl + "/api/v1/resource/blob") + .post(body) + .build() + + val json = JSONObject(exec(request)) + val rawId = json.opt("id") + val id: Any = if (rawId == null || rawId == JSONObject.NULL) { + json.optString("name") + } else { + rawId + } + UploadedResource(id, json.optString("externalLink")) + } + + suspend fun create( + prefs: Prefs, + content: String, + visibility: String, + resources: List, + ): CreatedMemo = withContext(Dispatchers.IO) { + val payload = JSONObject().apply { + put("content", content) + put("visibility", visibility) + if (resources.isNotEmpty()) { + val array = JSONArray() + resources.forEach { array.put(it.id) } + put("resourceIdList", array) + } + } + + val body = payload.toString().toRequestBody(JSON) + var failure: ApiException? = null + + for (path in listOf("/api/v1/memos", "/api/v1/memo")) { + val request = baseBuilder(prefs) + .url(prefs.memosUrl + path) + .post(body) + .build() + try { + val json = JSONObject(exec(request)) + return@withContext CreatedMemo(memoId(json), memoLink(prefs.memosUrl, json)) + } catch (e: ApiException) { + failure = e + if (e.code != 404 && e.code != 405) throw e + } + } + throw failure ?: ApiException("Memos 接口不可用") + } + + /** + * Memos 列表。 + * + * v0.18.x(当前服务器)实际是:GET /api/v1/memo?limit=N&offset=N, + * 直接返回一个 JSON 数组;v0.22+ 才是 /api/v1/memos + pageToken + {memos:[...]}。 + * 这里两条路径都试,并把两种响应结构统一成 MemoPage。 + * + * pageToken 约定:普通数字表示 offset;"pt:xxx" 表示新版本的游标。 + */ + suspend fun list( + prefs: Prefs, + pageSize: Int = 20, + pageToken: String = "", + ): MemoPage = withContext(Dispatchers.IO) { + if (!prefs.memosReady) throw ApiException("先填 Memos 网站地址和 Access Token") + + val isCursor = pageToken.startsWith("pt:") + val offset = if (isCursor) 0L else (pageToken.toLongOrNull() ?: 0L) + val paths = if (isCursor) { + listOf("/api/v1/memos", "/api/v1/memo") + } else { + listOf("/api/v1/memo", "/api/v1/memos") + } + + var failure: ApiException? = null + for (path in paths) { + val query = StringBuilder("limit=$pageSize&offset=$offset&pageSize=$pageSize") + if (isCursor) { + query.append("&pageToken=") + .append(java.net.URLEncoder.encode(pageToken.removePrefix("pt:"), "UTF-8")) + } + try { + val text = exec(baseBuilder(prefs).url(prefs.memosUrl + path + "?" + query).get().build()) + val parsed = parseMemoList(text, offset, pageSize) + val out = ArrayList(parsed.first.length()) + for (i in 0 until parsed.first.length()) { + val obj = parsed.first.optJSONObject(i) ?: continue + val id = memoId(obj) + if (id.isEmpty()) continue + out.add( + MemoItem( + id = id, + content = obj.optString("content"), + createdTs = obj.optLong("createdTs", obj.optLong("displayTs", 0L)), + pinned = obj.optBoolean("pinned", false), + images = resourceImages(obj.optJSONArray("resourceList")), + ) + ) + } + return@withContext MemoPage(out, parsed.second) + } catch (e: ApiException) { + failure = e + if (e.code != 404 && e.code != 405) throw e + } + } + throw failure ?: ApiException("Memos 列表接口不可用") + } + + /** 返回值:Pair(memos 数组, 下一页游标) */ + private fun parseMemoList(text: String, offset: Long, pageSize: Int): Pair { + val trimmed = text.trim() + if (trimmed.startsWith("[")) { + val array = JSONArray(trimmed) + val next = if (array.length() >= pageSize) (offset + array.length()).toString() else "" + return array to next + } + val json = JSONObject(trimmed) + val array = json.optJSONArray("memos") + ?: json.optJSONArray("data") + ?: JSONArray() + val next = json.optString("nextPageToken").ifBlank { + if (array.length() >= pageSize) (offset + array.length()).toString() else "" + } + return array to next + } + + private fun resourceImages(array: JSONArray?): List { + if (array == null) return emptyList() + val out = ArrayList() + for (i in 0 until array.length()) { + val item = array.optJSONObject(i) ?: continue + val type = item.optString("type") + val link = item.optString("externalLink") + .ifBlank { item.optString("publicUrl") } + .ifBlank { item.optString("uri") } + if (type.startsWith("image/", true) && link.isNotEmpty()) out.add(link) + } + return out + } + + private fun baseBuilder(prefs: Prefs): Request.Builder = + Request.Builder() + .header("Authorization", "Bearer ${prefs.memosToken}") + .header("Accept", "application/json") + .header("User-Agent", RssApi.UA_BROWSER) + + private fun exec(request: Request): String { + client.newCall(request).execute().use { response -> + val text = response.body?.string().orEmpty() + if (!response.isSuccessful) { + throw ApiException(friendlyMessage(response.code, text), response.code) + } + return text + } + } + + private fun friendlyMessage(code: Int, text: String): String { + val detail = try { + val json = JSONObject(text) + json.optString("message").ifBlank { + json.optString("error").ifBlank { json.optString("detail") } + } + } catch (e: Exception) { + text.take(160) + } + + val prefix = when (code) { + 401 -> "Token 无效或已过期" + 403 -> "没有权限,检查 Token 是否含 memos:write / resource:write" + 404 -> "接口不存在,检查网站地址和 Memos 版本" + 413 -> "内容或图片过大" + else -> "HTTP $code" + } + return if (detail.isBlank()) prefix else "$prefix:$detail" + } + + private fun memoId(json: JSONObject): String { + val name = json.optString("name") + if (name.isNotEmpty()) return name + val raw = json.opt("id") + return if (raw == null || raw == JSONObject.NULL) "" else raw.toString() + } + + /** 网页端链接形如 {base}/m/{id};新版 id 是 "memos/xxx",只取最后一段 */ + private fun memoLink(base: String, json: JSONObject): String { + val name = json.optString("name") + val tail = when { + name.startsWith("memos/") -> name.removePrefix("memos/") + name.isNotEmpty() -> name + else -> { + val raw = json.opt("id") + if (raw == null || raw == JSONObject.NULL) "" else raw.toString() + } + } + return if (tail.isEmpty()) base else "$base/m/$tail" + } +} diff --git a/src/main/java/com/shitoucuo/postpad/Prefs.kt b/src/main/java/com/shitoucuo/postpad/Prefs.kt new file mode 100644 index 0000000..db2e11b --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/Prefs.kt @@ -0,0 +1,627 @@ +package com.shitoucuo.postpad + +import android.content.Context +import androidx.appcompat.app.AppCompatDelegate +import org.json.JSONArray +import org.json.JSONObject + +/** + * 两套独立配置,都存在应用私有 SharedPreferences 里。 + * + * 这里只放「空默认值」:源码中不保留任何账号、密码、Token、站点地址。 + * 首次安装由用户在设置页填写,之后存在应用私有目录内(未加密, + * 仅限非 root 设备;如需更高强度可后续接入 EncryptedSharedPreferences)。 + */ +class Prefs(context: Context) { + + private val appContext = context.applicationContext + + private val sp = appContext.getSharedPreferences("postpad", Context.MODE_PRIVATE) + + // ==================== 发文:Typecho ==================== + + /** + * 站点根地址,同时用作请求的 Origin 头;读写都指向当前选中的站点。 + * + * 读写都过一遍 normalizeSite(),所以即使曾经存进过 "https://x.com/index.php/api" + * 这种带接口后缀的地址,读出来也会自动收敛成 "https://x.com",无需用户手动改。 + */ + var siteUrl: String + get() = normalizeSite(currentSite()?.optString("url").orEmpty()) + set(value) = editSite { it.put("url", normalizeSite(value)) } + + /** + * 接口路径前缀,空串表示伪静态可用的 "/api","/index.php" 表示走 index.php 形式。 + * 由 TypechoApi 探测后回写,不在设置页暴露。 + */ + var apiPrefix: String + get() = read(KEY_API_PREFIX).ifEmpty { "" } + set(value) = write(KEY_API_PREFIX, value) + + var token: String + get() = currentSite()?.optString("token").orEmpty() + set(value) = editSite { it.put("token", value) } + + var authorId: String + // Typecho 管理员默认 UID 为 1;这是公开约定,不属于凭据 + get() = currentSite()?.optString("authorId").orEmpty().ifEmpty { "1" } + set(value) = editSite { it.put("authorId", value) } + + /** 当前站点的显示名称,空串时下拉里回退显示网址 */ + var siteName: String + get() = currentSite()?.optString("name").orEmpty() + set(value) = editSite { it.put("name", value.trim()) } + + val typechoReady: Boolean + get() = siteUrl.isNotEmpty() && token.isNotEmpty() && authorId.isNotEmpty() + + // ==================== 多站点(Typecho) ==================== + + /** 站点配置按 JSON 数组存在 KEY_SITES,typechoCurrent 指向正在使用的那个 */ + var typechoCurrent: Int + get() = read(KEY_SITE_CURRENT).toIntOrNull()?.takeIf { it >= 0 } ?: 0 + set(value) = write(KEY_SITE_CURRENT, value.toString()) + + data class SiteEntry(val url: String, val token: String, val authorId: String, val name: String = "") + + // 解析结果按原始字符串缓存:列表页每条都要取站点名,避免反复解析 JSON + private var siteCache: JSONArray? = null + private var siteCacheRaw: String? = null + + private fun siteArray(): JSONArray { + val raw = readOrDefault(KEY_SITES, "[]") + var arr = siteCache + if (arr == null || siteCacheRaw != raw) { + arr = JSONArray(raw) + siteCacheRaw = raw + siteCache = arr + } + return arr + } + + private fun saveSiteArray(array: JSONArray) { + val json = array.toString() + write(KEY_SITES, json) + siteCacheRaw = json + siteCache = array + } + + private fun currentSite(): JSONObject? { + val arr = siteArray() + if (arr.length() == 0) return null + return arr.optJSONObject(typechoCurrent.coerceIn(0, arr.length() - 1)) + } + + /** 写当前站点;列表为空时先建出第一条 */ + private fun editSite(block: (JSONObject) -> Unit) { + val arr = siteArray() + val index = typechoCurrent.coerceIn(0, if (arr.length() == 0) 0 else arr.length() - 1) + val obj = arr.optJSONObject(index) ?: JSONObject().also { arr.put(index, it) } + block(obj) + saveSiteArray(arr) + } + + fun siteCount(): Int = siteArray().length() + + fun siteAt(index: Int): SiteEntry? = siteArray().optJSONObject(index)?.let { + SiteEntry(it.optString("url"), it.optString("token"), it.optString("authorId"), it.optString("name")) + } + + fun setSiteAt( + index: Int, + url: String, + token: String, + authorId: String, + name: String? = null, + ) { + val arr = siteArray() + val obj = arr.optJSONObject(index) ?: JSONObject().also { arr.put(index, it) } + obj.put("url", normalizeSite(url)) + obj.put("token", token) + obj.put("authorId", authorId) + if (name != null) obj.put("name", name.trim()) + saveSiteArray(arr) + } + + /** 新增一个空白站点,返回它的序号 */ + fun addSite(): Int { + val arr = siteArray() + arr.put(JSONObject()) + saveSiteArray(arr) + return arr.length() - 1 + } + + /** 删除站点;至少保留一个,返回删除后的数量 */ + fun removeSiteAt(index: Int): Int { + val arr = siteArray() + if (arr.length() > 1 && index in 0 until arr.length()) { + arr.remove(index) + } + saveSiteArray(arr) + if (typechoCurrent >= arr.length()) typechoCurrent = 0 + return arr.length() + } + + /** 下拉里显示的站点短名:优先用户设置的名称,没设则去掉协议前缀 */ + fun siteLabel(index: Int): String { + val entry = siteAt(index) + entry?.name?.takeIf { it.isNotEmpty() }?.let { return it } + val url = entry?.url.orEmpty() + return url.removePrefix("https://").removePrefix("http://") + .ifBlank { "站点 ${index + 1}" } + } + + // ==================== 发博:Memos ==================== + + var memosUrl: String + get() = read(KEY_MEMOS_URL) + set(value) = write(KEY_MEMOS_URL, value.trim().trimEnd('/')) + + var memosToken: String + get() = read(KEY_MEMOS_TOKEN) + set(value) = write(KEY_MEMOS_TOKEN, value) + + /** PRIVATE / PROTECTED / PUBLIC,默认公开,记住上次选择 */ + var memosVisibility: String + get() = read(KEY_MEMOS_VIS).ifEmpty { VISIBILITY_PUBLIC } + set(value) = write(KEY_MEMOS_VIS, value) + + val memosReady: Boolean + get() = memosUrl.isNotEmpty() && memosToken.isNotEmpty() + + // ==================== RSS 信息(站点 RssUnion 接口) ==================== + + /** 抓取 RSS 的站点根地址,接口形如 {site}/action/rssunion */ + var rssSite: String + get() = normalizeSite(read(KEY_RSS_SITE)) + set(value) = write(KEY_RSS_SITE, normalizeSite(value)) + + /** 站点会员授权码,形如 ruo_xxx */ + var rssCode: String + get() = read(KEY_RSS_CODE) + set(value) = write(KEY_RSS_CODE, value.trim()) + + /** 每页条数,站点上限 100 */ + var rssPageSize: Int + get() = read(KEY_RSS_PAGE).toIntOrNull()?.takeIf { it in 5..100 } ?: 20 + set(value) = write(KEY_RSS_PAGE, value.toString()) + + val rssReady: Boolean + get() = rssSite.isNotEmpty() && rssCode.isNotEmpty() + + // ==================== 邮件(IMAP 直连,多账户) ==================== + + /** 当前邮箱序号;邮箱列表按 JSON 数组存 KEY_MAIL_ACCOUNTS */ + var mailCurrent: Int + get() = read(KEY_MAIL_CURRENT).toIntOrNull()?.takeIf { it >= 0 } ?: 0 + set(value) = write(KEY_MAIL_CURRENT, value.toString()) + + data class MailEntry( + val email: String, + val auth: String, + val host: String, + val port: Int, + val secure: Boolean, + val days: Int, + val name: String = "", + ) { + /** 三项齐全才算可用;列表聚合时只对可用的账户做同步 */ + val ready: Boolean + get() = email.isNotBlank() && auth.isNotBlank() && host.isNotBlank() + + /** 卡片与下拉里显示的短名:优先自定义名称,否则邮箱地址 */ + val label: String + get() = name.ifBlank { email.ifBlank { "未命名邮箱" } } + } + + // 同站点缓存:邮箱列表的解析结果也只保留一份 + private var mailCache: JSONArray? = null + private var mailCacheRaw: String? = null + + private fun mailArray(): JSONArray { + val raw = readOrDefault(KEY_MAIL_ACCOUNTS, "[]") + var arr = mailCache + if (arr == null || mailCacheRaw != raw) { + arr = JSONArray(raw) + mailCacheRaw = raw + mailCache = arr + } + return arr + } + + private fun saveMailArray(array: JSONArray) { + val json = array.toString() + write(KEY_MAIL_ACCOUNTS, json) + mailCacheRaw = json + mailCache = array + } + + private fun currentMail(): JSONObject? { + val arr = mailArray() + if (arr.length() == 0) return null + return arr.optJSONObject(mailCurrent.coerceIn(0, arr.length() - 1)) + } + + /** 写当前邮箱;列表为空时先建出第一条 */ + private fun editMail(block: (JSONObject) -> Unit) { + val arr = mailArray() + val index = mailCurrent.coerceIn(0, if (arr.length() == 0) 0 else arr.length() - 1) + val obj = arr.optJSONObject(index) ?: JSONObject().also { arr.put(index, it) } + block(obj) + saveMailArray(arr) + } + + var mailEmail: String + get() = currentMail()?.optString("email").orEmpty() + set(value) = editMail { it.put("email", value.trim()) } + + /** 邮箱授权码(不是登录密码) */ + var mailAuthCode: String + get() = currentMail()?.optString("auth").orEmpty() + set(value) = editMail { it.put("auth", value.trim()) } + + var mailImapHost: String + get() = resolveImapHost(currentMail()?.optString("host").orEmpty(), mailEmail) + set(value) = editMail { it.put("host", value.trim()) } + + var mailImapPort: Int + get() = currentMail()?.optInt("port")?.takeIf { it in 1..65535 } ?: 993 + set(value) = editMail { it.put("port", value) } + + /** 是否走 SSL(993 端口通常为 true) */ + var mailSecure: Boolean + get() = currentMail()?.optString("secure")?.takeIf { it.isNotEmpty() } + ?.equals("true", true) ?: true + set(value) = editMail { it.put("secure", value.toString()) } + + /** 首次同步拉取最近多少天的邮件 */ + var mailFetchDays: Int + get() = currentMail()?.optInt("days")?.takeIf { it in 1..365 } ?: 30 + set(value) = editMail { it.put("days", value) } + + /** 当前邮箱的显示名称,空串时回退显示邮箱地址 */ + var mailDisplayName: String + get() = currentMail()?.optString("name").orEmpty() + set(value) = editMail { it.put("name", value.trim()) } + + val mailReady: Boolean + get() = mailEmail.isNotEmpty() && mailAuthCode.isNotEmpty() && mailImapHost.isNotEmpty() + + fun mailCount(): Int = mailArray().length() + + fun mailAt(index: Int): MailEntry? = mailArray().optJSONObject(index)?.let { + MailEntry( + email = it.optString("email"), + auth = it.optString("auth"), + host = resolveImapHost(it.optString("host"), it.optString("email")), + port = it.optInt("port").takeIf { p -> p in 1..65535 } ?: 993, + secure = it.optString("secure").takeIf { s -> s.isNotEmpty() } + ?.equals("true", true) ?: true, + days = it.optInt("days").takeIf { d -> d in 1..365 } ?: 30, + name = it.optString("name"), + ) + } + + /** + * 决定实际使用的 IMAP 主机。 + * + * 两种会连错服务器的情况都在这里收口: + * 1. 留空 → 按邮箱域名推断; + * 2. 历史误填(126 / 163 账号被填成 imap.qq.com)→ 同样按域名纠正。 + * QQ 的 IMAP 只服务 qq.com / foxmail.com,这种组合不可能连通, + * 而且从输入框里看不出问题,用户只会以为授权码错了。 + */ + private fun resolveImapHost(stored: String, email: String): String { + val host = stored.trim() + if (host.isEmpty()) return imapHostFor(email) + if (host.equals("imap.qq.com", true) && !isQqMail(email)) return imapHostFor(email) + return host + } + + private fun isQqMail(email: String): Boolean { + val domain = email.substringAfter('@', "").trim().lowercase() + return domain == "qq.com" || domain == "foxmail.com" + } + + /** + * IMAP 服务器地址:用户没填时按邮箱域名推断。 + * + * 原先一律兜底 imap.qq.com —— 126 / 163 的账号会被送到 QQ 的服务器上认证, + * 必然报"授权码错误"或超时;而同一账号在 Obsidian 插件里填的是 imap.126.com, + * 所以那边正常、App 这边失败。未收录的域名走 imap.<域名>,覆盖自建邮局。 + */ + private fun imapHostFor(email: String): String { + val domain = email.substringAfter('@', "").trim().lowercase() + if (domain.isEmpty()) return DEFAULT_MAIL_HOST + return when (domain) { + "qq.com", "foxmail.com" -> "imap.qq.com" + "126.com" -> "imap.126.com" + "163.com" -> "imap.163.com" + "yeah.net" -> "imap.yeah.net" + "sina.com", "sina.cn" -> "imap.sina.com" + "gmail.com" -> "imap.gmail.com" + "outlook.com", "hotmail.com", "live.com" -> "outlook.office365.com" + "aliyun.com" -> "imap.aliyun.com" + else -> "imap.$domain" + } + } + + fun setMailAt( + index: Int, + email: String, + auth: String, + host: String, + port: Int, + secure: Boolean, + days: Int, + name: String? = null, + ) { + val arr = mailArray() + val obj = arr.optJSONObject(index) ?: JSONObject().also { arr.put(index, it) } + obj.put("email", email.trim()) + obj.put("auth", auth.trim()) + obj.put("host", host.trim()) + obj.put("port", port) + obj.put("secure", secure.toString()) + obj.put("days", days) + if (name != null) obj.put("name", name.trim()) + saveMailArray(arr) + } + + /** 新增一个空白邮箱,返回它的序号 */ + fun addMail(): Int { + val arr = mailArray() + arr.put(JSONObject()) + saveMailArray(arr) + return arr.length() - 1 + } + + /** 删除邮箱;至少保留一个,返回删除后的数量 */ + fun removeMailAt(index: Int): Int { + val arr = mailArray() + if (arr.length() > 1 && index in 0 until arr.length()) { + arr.remove(index) + } + saveMailArray(arr) + if (mailCurrent >= arr.length()) mailCurrent = 0 + return arr.length() + } + + /** 下拉里显示的邮箱短名:优先名称,没设则显示邮箱地址 */ + fun mailLabel(index: Int): String { + val entry = mailAt(index) + entry?.name?.takeIf { it.isNotEmpty() }?.let { return it } + return entry?.email?.ifBlank { "邮箱 ${index + 1}" } ?: "邮箱 ${index + 1}" + } + + /** + * 全部邮箱的**快照列表**。 + * + * 邮件同步、缓存读写一律拿这份快照跑,不再在流程中途读 prefs.mailEmail: + * 用户切邮箱时 prefs 指向的账户会立刻变,而同步是个持续几十秒的流程, + * 中途改读就会把 A 的邮件写进 B 的缓存文件(列表串号、点开提示已删除的根因)。 + */ + fun mailAccounts(): List = (0 until mailCount()).mapNotNull { mailAt(it) } + + /** 按邮箱地址找配置;地址是账户的稳定标识,增删其它账户不影响它 */ + fun mailAccount(email: String): MailEntry? { + val key = email.trim() + if (key.isEmpty()) return null + return mailAccounts().firstOrNull { it.email.equals(key, true) } + } + + val currentMailAccount: MailEntry? + get() = mailAt(mailCurrent) + + /** 每个邮箱一份列表缓存,切邮箱互不影响 */ + fun mailCacheFile(email: String): java.io.File { + val tag = Integer.toHexString(email.trim().lowercase().hashCode()) + return java.io.File(appContext.filesDir, "postpad_mail_cache_$tag.json") + } + + /** 应用私有文件目录(缓存迁移等场景用) */ + val filesDir: java.io.File + get() = appContext.filesDir + + /** 版本号,用于 IMAP 客户端标识,避免那边写死的版本号长期不更新 */ + val appVersion: String + get() = runCatching { + appContext.packageManager.getPackageInfo(appContext.packageName, 0).versionName + }.getOrNull().orEmpty() + + /** + * 标签名的本地快照,英文逗号分隔。 + * + * 标签联想依赖 /api/tags 一次网络请求,断网或接口异常时下拉会整体消失。 + * 每次拉取成功写一份,失败时用上次的结果兜底,避免「已有标签也联想不出来」。 + */ + var tagCache: String + get() = read(KEY_TAG_CACHE) + set(value) = write(KEY_TAG_CACHE, value) + + // ==================== 外观 ==================== + + /** + * 深浅色:空串表示跟随系统,light / dark 是用户在首页顶栏手动切过的结果。 + * 切换按钮只有「亮 / 暗」两态,第一次点击才落成明确值。 + */ + var darkMode: String + get() = read(KEY_DARK_MODE) + set(value) = write(KEY_DARK_MODE, value) + + /** 给 AppCompatDelegate 用;按存下的值换算成 NightMode 常量 */ + fun nightMode(): Int = when (darkMode) { + MODE_LIGHT -> AppCompatDelegate.MODE_NIGHT_NO + MODE_DARK -> AppCompatDelegate.MODE_NIGHT_YES + else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM + } + + // ==================== AI:润色 / 完善 ==================== + + /** deepseek / zhipu,与 AIAssist 插件用的是同一家的接口 */ + var aiProvider: String + get() = read(KEY_AI_PROVIDER).ifEmpty { AiApi.PROVIDER_DEEPSEEK } + set(value) = write(KEY_AI_PROVIDER, value) + + var aiKey: String + get() = read(KEY_AI_KEY) + set(value) = write(KEY_AI_KEY, value) + + /** 留空则用各家的默认对话模型 */ + var aiModel: String + get() = read(KEY_AI_MODEL) + set(value) = write(KEY_AI_MODEL, value) + + val aiReady: Boolean + get() = aiKey.isNotEmpty() + + /** RSS 已读状态单独存,避免和主配置混在一起 */ + private val rssReadSp = appContext.getSharedPreferences("postpad_rss_read", Context.MODE_PRIVATE) + + fun isRssRead(id: String): Boolean = rssReadSp.getBoolean(id, false) + + fun setRssRead(id: String, read: Boolean = true) { + rssReadSp.edit().putBoolean(id, read).apply() + } + + // ==================== RSS / 文章:本地删除(隐藏) ==================== + + /** + * 被「删除」的 RSS / 文章条目 id。 + * + * 站点 RssUnion 接口是只读的(只有 obsidianItems / obsidianTree 这类查询), + * 没有删除条目的入口,所以这两类内容的删除只能是本地隐藏:把 id 记下来, + * 列表渲染与未读统计都跳过它,观感与删除一致,重进 APP、下拉刷新都不会回来。 + * 邮件不同——邮件走 IMAP,删除是真实的服务端删除。 + */ + private val rssHiddenSp = + appContext.getSharedPreferences("postpad_rss_hidden", Context.MODE_PRIVATE) + + @Volatile + private var hiddenCache: Set? = null + + fun hiddenRssIds(): Set { + hiddenCache?.let { return it } + // getStringSet 返回的是集合本体,直接改会污染内存缓存,必须拷贝 + val copy = HashSet(rssHiddenSp.getStringSet(KEY_RSS_HIDDEN, emptySet()) ?: emptySet()) + hiddenCache = copy + return copy + } + + fun isRssHidden(id: String): Boolean = hiddenRssIds().contains(id) + + fun hideRssIds(ids: Collection) { + if (ids.isEmpty()) return + val set = HashSet(hiddenRssIds()) + set.addAll(ids) + // 上限兜底:id 是自增数字,超限时按数值保留较大的(约等于最近删除的),避免无限增长 + val capped = if (set.size > MAX_HIDDEN_RSS) { + set.sortedByDescending { it.toLongOrNull() ?: 0L }.take(MAX_HIDDEN_RSS).toSet() + } else { + set + } + rssHiddenSp.edit().putStringSet(KEY_RSS_HIDDEN, capped).apply() + hiddenCache = capped + } + + /** 清空本地隐藏记录(设置页或调试用) */ + fun clearHiddenRss() { + rssHiddenSp.edit().clear().apply() + hiddenCache = emptySet() + } + + /** 邮件列表本地缓存文件(UID 增量同步用),按邮箱分开存 */ + val legacyMailCacheFile: java.io.File + get() = java.io.File(appContext.filesDir, "postpad_mail_cache.json") + + private fun read(key: String): String = (sp.getString(key, "") ?: "").trim() + + /** 只有非机密的连接参数才允许有兜底值(例如 IMAP 主机名) */ + private fun readOrDefault(key: String, fallback: String): String = + read(key).ifEmpty { fallback } + + private fun write(key: String, value: String) { + sp.edit().putString(key, value).apply() + } + + companion object { + const val VISIBILITY_PRIVATE = "PRIVATE" + const val VISIBILITY_PROTECTED = "PROTECTED" + const val VISIBILITY_PUBLIC = "PUBLIC" + + const val MODE_LIGHT = "light" + const val MODE_DARK = "dark" + + // ==================== 非机密连接参数 ==================== + // 仅保留协议默认值:账号、密码、Token、站点地址一律不再内置, + // 全部由用户在设置页填写(详见 凭据填写清单.txt)。 + private const val DEFAULT_MAIL_HOST = "imap.qq.com" + private const val DEFAULT_MAIL_PORT = "993" + + private const val KEY_SITES = "typecho_sites" + private const val KEY_SITE_CURRENT = "typecho_current" + private const val KEY_API_PREFIX = "api_prefix" + private const val KEY_MEMOS_URL = "memos_url" + private const val KEY_MEMOS_TOKEN = "memos_token" + /** 换了键名:旧版本存过 PRIVATE,这里让新版默认公开生效,不再沿用旧值 */ + private const val KEY_MEMOS_VIS = "memos_visibility_v2" + private const val KEY_DARK_MODE = "dark_mode" + private const val KEY_AI_PROVIDER = "ai_provider" + private const val KEY_AI_KEY = "ai_key" + private const val KEY_AI_MODEL = "ai_model" + + private const val KEY_RSS_SITE = "rss_site" + private const val KEY_RSS_CODE = "rss_code" + private const val KEY_RSS_PAGE = "rss_page_size" + + private const val KEY_MAIL_ACCOUNTS = "mail_accounts" + private const val KEY_MAIL_CURRENT = "mail_current" + /** 本地「已删除」的 RSS / 文章 id 集合 */ + private const val KEY_RSS_HIDDEN = "rss_hidden_ids" + /** 隐藏记录上限:超过后按 id 数值保留最近的,防止 SharedPreferences 越写越大 */ + private const val MAX_HIDDEN_RSS = 2000 + /** 标签名快照,联想在断网时的兜底数据 */ + private const val KEY_TAG_CACHE = "tag_cache" + + /** 接口路径候选:优先伪静态写法,不通再退回 index.php 写法 */ + val API_PREFIXES = listOf("", "/index.php") + + /** 需要剥离的接口后缀,长的在前,避免 /api 先把 /index.php/api 截断成半截 */ + private val SITE_SUFFIXES = listOf( + "/index.php/api/posts", + "/index.php/api", + "/api/posts", + "/action/rssunion", + "/api", + "/index.php", + ) + + /** + * 收敛成站点根地址:补协议、去尾斜杠、剥离接口后缀。 + * + * 这样 "https://x.com/index.php/api" 与 "x.com/api" 都会变成 "https://x.com", + * 避免拼出 /api/api/posts 这种路径。 + */ + fun normalizeSite(raw: String): String { + var value = raw.trim().trimEnd('/') + if (value.isEmpty()) return "" + + if (!value.startsWith("http://", true) && !value.startsWith("https://", true)) { + value = "https://$value" + } + + var stripped = true + while (stripped) { + stripped = false + for (suffix in SITE_SUFFIXES) { + if (value.length > suffix.length && value.endsWith(suffix, true)) { + value = value.dropLast(suffix.length).trimEnd('/') + stripped = true + break + } + } + } + return value + } + } +} diff --git a/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt b/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt new file mode 100644 index 0000000..7080518 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt @@ -0,0 +1,634 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Color +import android.graphics.Outline +import android.net.Uri +import android.os.Bundle +import android.app.Dialog +import android.text.method.LinkMovementMethod +import android.util.LruCache +import android.view.View +import android.view.ViewGroup +import android.view.ViewOutlineProvider +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.TextView +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.core.content.ContextCompat +import androidx.lifecycle.lifecycleScope +import io.noties.markwon.Markwon +import io.noties.markwon.image.ImagesPlugin +import io.noties.markwon.image.network.OkHttpNetworkSchemeHandler +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import okhttp3.Request +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** 统一阅读页:文章 / Memos / RSS 都在这里看 Markdown 正文 */ +class ReaderActivity : AppCompatActivity() { + + private lateinit var prefs: Prefs + private lateinit var tvTitle: TextView + private lateinit var tvMeta: TextView + private lateinit var bodyContainer: LinearLayout + private lateinit var progress: ProgressBar + private lateinit var btnOriginal: TextView + private lateinit var markwon: Markwon + private lateinit var imageClient: OkHttpClient + + private var originalUrl: String = "" + + companion object { + private const val EXTRA_KIND = "kind" + private const val EXTRA_ID = "id" + private const val EXTRA_TITLE = "title" + private const val EXTRA_SOURCE = "source" + private const val EXTRA_DATE = "date" + private const val EXTRA_CONTENT = "content" + private const val EXTRA_LINK = "link" + + const val KIND_RSS = "rss" + const val KIND_ARTICLE = "article" + const val KIND_MEMO = "memo" + + fun open( + context: Context, + kind: String, + id: String, + title: String, + source: String, + date: Long, + content: String, + link: String, + ) { + val intent = Intent(context, ReaderActivity::class.java).apply { + putExtra(EXTRA_KIND, kind) + putExtra(EXTRA_ID, id) + putExtra(EXTRA_TITLE, title) + putExtra(EXTRA_SOURCE, source) + putExtra(EXTRA_DATE, date) + putExtra(EXTRA_CONTENT, content) + putExtra(EXTRA_LINK, link) + } + context.startActivity(intent) + } + } + + 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_reader) + + tvTitle = findViewById(R.id.tvReaderTitle) + tvMeta = findViewById(R.id.tvReaderMeta) + bodyContainer = findViewById(R.id.bodyContainer) + progress = findViewById(R.id.readerProgress) + btnOriginal = findViewById(R.id.btnOpenOriginal) + + imageClient = OkHttpClient.Builder() + .connectTimeout(20, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS) + .build() + val imagePlugin = ImagesPlugin.create() + .addSchemeHandler(OkHttpNetworkSchemeHandler.create(imageClient)) + markwon = Markwon.builder(this) + .usePlugin(imagePlugin) + .usePlugin(MdThemePlugin(this)) + .build() + + val kind = intent.getStringExtra(EXTRA_KIND).orEmpty() + val id = intent.getStringExtra(EXTRA_ID).orEmpty() + val title = intent.getStringExtra(EXTRA_TITLE).orEmpty() + val source = intent.getStringExtra(EXTRA_SOURCE).orEmpty() + val date = intent.getLongExtra(EXTRA_DATE, 0L) + val preloaded = intent.getStringExtra(EXTRA_CONTENT).orEmpty() + originalUrl = intent.getStringExtra(EXTRA_LINK).orEmpty() + + tvTitle.text = title.ifBlank { getString(R.string.reader_untitled) } + tvMeta.text = buildString { + if (source.isNotEmpty()) append(source) + if (date > 0) { + if (isNotEmpty()) append(" · ") + append(formatDate(date)) + } + } + + 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("打不开浏览器") } + } + + when (kind) { + KIND_ARTICLE -> loadArticle(id, preloaded) + KIND_RSS -> loadRss(preloaded) + else -> render(preloaded.ifBlank { "(empty)" }) + } + } + + private fun loadArticle(cid: String, preloaded: String) { + if (preloaded.isNotBlank()) { + render(preloaded) + return + } + progress.visibility = TextView.VISIBLE + lifecycleScope.launch { + try { + val detail = withContext(Dispatchers.IO) { + TypechoApi.postDetail(prefs, cid.toLongOrNull() ?: 0L) + } + originalUrl = detail.permalink.ifBlank { originalUrl } + tvTitle.text = detail.title + render(detail.markdown.ifBlank { detail.text }) + } catch (e: Exception) { + render("读取文章失败:${e.message ?: "未知错误"}") + } finally { + progress.visibility = TextView.GONE + } + } + } + + private fun loadRss(excerpt: String) { + if (originalUrl.isBlank()) { + render(excerpt.ifBlank { "(这条内容没有正文)" }) + return + } + progress.visibility = TextView.VISIBLE + lifecycleScope.launch { + try { + val markdown = withContext(Dispatchers.IO) { RssApi.article(originalUrl) } + val body = stripDuplicateHeader(markdown.ifBlank { excerpt }) + render(body.ifBlank { excerpt.ifBlank { "(原文里没有抓到正文)" } }) + } catch (e: Exception) { + // 抓不到原文时用站端摘要兜底,至少能读个大概 + render(excerpt.ifNotBlank() ?: "抓取原文失败:${e.message ?: "未知错误"}") + } finally { + progress.visibility = TextView.GONE + } + } + } + + /** + * 原文页面的 article 标签里常带着站名标题和发布日期, + * 顶栏已经显示了这两样,开头再出现一遍就去掉; + * 开头的分类 / 标签 / 来源等 meta 行也一并清掉,只留正文。 + */ + private fun stripDuplicateHeader(markdown: String): String { + var s = markdown.trim() + val heading = Regex("^#{1,6}\\s*(.+?)[\\r\\n]+") + heading.find(s)?.let { m -> + val h = m.groupValues[1].trim() + val title = tvTitle.text.toString().trim() + if (title.isEmpty() || h == title || title.contains(h) || h.contains(title)) { + s = s.substring(m.range.last + 1).trim() + } + } + // 开头的日期行:2026-06-08、2026年6月8日、2026/06/08 09:46 等,可能连续几行 meta + val dateLine = Regex("^[\\r\\n]*\\d{4}[-/年]\\d{1,2}[-/月]\\d{1,2}日?[^\\n]{0,30}[\\r\\n]+") + while (true) { + val next = dateLine.replaceFirst(s, "").trim() + if (next == s || next.isEmpty()) break + s = next + } + // 开头的 meta 行:作者 / 分类 / 标签 / 来源 / 字数 / 阅读次数 + val metaLine = Regex( + "^[\\r\\n]*(作者|分类|标签|来源|发布于|发表于|更新于|字数|阅读|浏览|字体大小)[::\\s][^\\n]{0,40}[\\r\\n]+", + ) + while (true) { + val next = metaLine.replaceFirst(s, "").trim() + if (next == s || next.isEmpty()) break + s = next + } + return s.trim() + } + + private fun String.ifNotBlank(): String? = takeIf { isNotBlank() } + + /** + * ATX 标题 # 后补空格:CommonMark 要求 `#` 与文字之间必须有空格才会识别为标题, + * 站里常写成 `#标题`。代码块 / 行内代码先占位保护再还原,代码里的 # 不受影响。 + */ + private fun ensureHeadingSpaces(md: String): String { + if (!md.contains('#')) return md + val blocks = mutableListOf() + var s = Regex("```[\\s\\S]*?```").replace(md) { m -> + blocks.add(m.value); "\u0000K${blocks.size - 1}\u0000" + } + val inlines = mutableListOf() + s = Regex("`[^`\\n]+`").replace(s) { m -> + inlines.add(m.value); "\u0000k${inlines.size - 1}\u0000" + } + s = Regex("(?m)^(#{1,6})([^#\\s])").replace(s) { m -> + "${m.groupValues[1]} ${m.groupValues[2]}" + } + inlines.forEachIndexed { i, b -> s = s.replace("\u0000k$i\u0000", b) } + blocks.forEachIndexed { i, b -> s = s.replace("\u0000K$i\u0000", b) } + return s + } + + /** + * 轻量 HTML → Markdown:正文里混写的 HTML 标签不再裸露。 + * 代码块 / 行内代码先占位保护,转换完再还原,避免代码里的 HTML 被误改。 + */ + private fun htmlToMarkdownLite(html: String): String { + if (!html.contains('<')) return html + val blocks = mutableListOf() + var s = Regex("```[\\s\\S]*?```").replace(html) { m -> + blocks.add(m.value); "\u0000B${blocks.size - 1}\u0000" + } + val inlines = mutableListOf() + s = Regex("`[^`\\n]+`").replace(s) { m -> + inlines.add(m.value); "\u0000I${inlines.size - 1}\u0000" + } + // 注释与 img(转成 markdown 图片,独立成行的后面会转成铺满整行的大图) + s = s.replace(Regex(""), "") + s = Regex("]*>", RegexOption.IGNORE_CASE).replace(s) { m -> + val src = Regex("\\b(?:data-src|src)\\s*=\\s*['\"]([^'\"]+)['\"]", RegexOption.IGNORE_CASE) + .find(m.value)?.groupValues?.get(1).orEmpty() + val alt = Regex("alt\\s*=\\s*['\"]([^'\"]*)['\"]", RegexOption.IGNORE_CASE) + .find(m.value)?.groupValues?.get(1).orEmpty() + if (src.isBlank()) "" else "\n\n![$alt]($src)\n\n" + } + s = s.replace(Regex("", RegexOption.IGNORE_CASE), "\n") + // 标题 + for (i in 1..6) { + s = Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE) + .replace(s) { m -> "\n\n${"#".repeat(i)} ${m.groupValues[1].trim()}\n\n" } + } + // 块级元素闭合转段落分隔;li 转列表项 + s = s.replace(Regex("|||", RegexOption.IGNORE_CASE), "\n\n") + s = s.replace(Regex("]*>", RegexOption.IGNORE_CASE), "- ") + // 行内样式 + s = s.replace(Regex("<(strong|b)\\b[^>]*>", RegexOption.IGNORE_CASE), "**") + .replace(Regex("", RegexOption.IGNORE_CASE), "**") + .replace(Regex("<(em|i)\\b[^>]*>", RegexOption.IGNORE_CASE), "*") + .replace(Regex("", RegexOption.IGNORE_CASE), "*") + .replace(Regex("]*>", RegexOption.IGNORE_CASE), "\n> ") + // 链接 + s = Regex( + "]*href\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>([\\s\\S]*?)", + RegexOption.IGNORE_CASE, + ).replace(s) { m -> "[${m.groupValues[2]}](${m.groupValues[1]})" } + // 剩余未知标签一律剥掉(含自闭合),正文不再露出 之类 + s = s.replace(Regex("]*>"), "") + s = s.replace(Regex("\\n{3,}"), "\n\n") + // 还原代码块 / 行内代码 + blocks.forEachIndexed { i, b -> s = s.replace("\u0000B$i\u0000", b) } + inlines.forEachIndexed { i, b -> s = s.replace("\u0000I$i\u0000", b) } + return s + } + + /** 渲染:文字段走 Markwon,FlexPhoto 图组横排,独立图片铺满整行 */ + private fun render(markdown: String) { + var raw = if (markdown.contains("")) markdown.replace("", "") + else markdown + // MyTrack 足迹地图短代码 {map-数字}:APP 端无法渲染,直接隐藏 + raw = raw.replace(Regex("\\{map-\\d+\\}", RegexOption.IGNORE_CASE), "") + // 正文混写 HTML 支持:

/
///

等转成 Markdown,其余标签剥掉 + raw = htmlToMarkdownLite(raw) + // 站里标题常写成 "#标题"(# 后无空格,CommonMark 不识别),补上空格;代码块内不动 + raw = ensureHeadingSpaces(raw) + var body = normalizeFlexTokens(raw) + // 收集文末引用定义行(站里的定义行带前导空格),供引用式图片解析 + val refs = Regex("(?m)^\\s*\\[([^\\]]+)\\]:\\s*(\\S+)") + .findAll(body) + .associate { it.groupValues[1].trim() to it.groupValues[2].trim() } + // 单独成行的引用式图片 ![alt][id] → 铺满整行的图片 + body = Regex("(?m)^\\s*!\\[([^\\]]*)\\]\\[([^\\]]*)\\]\\s*$").replace(body) { m -> + val key = m.groupValues[2].trim().ifEmpty { m.groupValues[1].trim() } + refs[key]?.let { "\n%%IMG%%\n$it\n%%/IMG%%\n" } ?: m.value + } + // 单独成行的内联式图片 ![alt](url) → 铺满整行的图片 + body = Regex("(?m)^\\s*!\\[[^\\]]*\\]\\(\\s*([^)\\s]+?)(?:\\s+\"[^\"]*\")?\\s*\\)\\s*$") + .replace(body) { m -> "\n%%IMG%%\n${m.groupValues[1].trim()}\n%%/IMG%%\n" } + // 删掉引用定义行(文末 [1]: url 之类),不在正文里显示图片地址 + body = body.replace(Regex("(?m)^\\s*\\[[^\\]]+\\]:\\s*\\S+.*$"), "") + bodyContainer.removeAllViews() + val tokenRe = Regex("%%(FLEXP|IMG)%%\\s*([\\s\\S]*?)\\s*%%/\\1%%") + var last = 0 + for (m in tokenRe.findAll(body)) { + addTextSegment(body.substring(last, m.range.first).trim()) + val urls = m.groupValues[2].lines().map { it.trim() }.filter { it.isNotEmpty() } + when (m.groupValues[1]) { + "IMG" -> urls.forEach { addFullImage(it) } + else -> if (urls.isNotEmpty()) addFlexPhotoRow(urls) + } + last = m.range.last + 1 + } + addTextSegment(body.substring(last).trim()) + } + + private fun addTextSegment(text: String) { + if (text.isBlank()) return + val tv = TextView(this).apply { + textSize = 15f + setTextColor(ContextCompat.getColor(context, R.color.text)) + setLineSpacing(dp(4).toFloat(), 1f) + movementMethod = LinkMovementMethod.getInstance() + } + markwon.setMarkdown(tv, text) + bodyContainer.addView( + tv, + LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ).apply { topMargin = dp(10) }, + ) + } + + /** + * FlexPhoto 图组:N 张图按各自宽高比分摊整行宽度,正好铺满一行—— + * 2 张各占一半、3 张各占三分之一、单张自然占满整行; + * 图片全部加载完后统一排版,点击任意一张全屏放大。 + */ + private fun addFlexPhotoRow(urls: List) { + val resolved = urls.map { resolveUrl(it) } + val gap = dp(8) + val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL } + val views = resolved.map { _ -> + ImageView(this).apply { + scaleType = ImageView.ScaleType.FIT_CENTER + setBackgroundColor(ContextCompat.getColor(context, R.color.segment_track)) + outlineProvider = RoundedOutline(dp(10)) + clipToOutline = true + layoutParams = LinearLayout.LayoutParams(0, dp(120), 1f).apply { + marginEnd = gap + } + row.addView(this) + } + } + (views.last().layoutParams as LinearLayout.LayoutParams).marginEnd = 0 + bodyContainer.addView( + row, + LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ).apply { topMargin = dp(10) }, + ) + + // 拿到全部图片后按宽高比分摊:总宽 = rowW,共用高度 = (rowW - 间距) / 宽高比之和 + val bitmaps = arrayOfNulls(resolved.size) + var pending = resolved.size + fun relayout() { + val rowW = row.width.takeIf { it > 0 } ?: return + val aspects = bitmaps.map { b -> + if (b != null && b.height > 0) b.width.toFloat() / b.height else 1f + } + val h = ((rowW - gap * (resolved.size - 1)) / aspects.sum()) + .toInt().coerceAtLeast(dp(80)).coerceAtMost(rowW * 2) + resolved.forEachIndexed { i, _ -> + views[i].layoutParams = LinearLayout.LayoutParams( + (aspects[i] * h).toInt().coerceAtLeast(dp(40)), + h, + ).apply { if (i < resolved.size - 1) marginEnd = gap } + } + row.requestLayout() + } + + resolved.forEachIndexed { index, url -> + val iv = views[index] + iv.tag = url + iv.setOnClickListener { showZoomDialog(resolved, index) } + loadThumb(url, iv, resources.displayMetrics.widthPixels) { bmp -> + bitmaps[index] = bmp + pending-- + if (pending == 0) row.post { relayout() } + } + } + } + + private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt() + + /** 独立图片:铺满整行、高度按图片比例,点击放大 */ + private fun addFullImage(url: String) { + val resolved = resolveUrl(url) + val iv = ImageView(this).apply { + scaleType = ImageView.ScaleType.FIT_CENTER + setBackgroundColor(ContextCompat.getColor(context, R.color.segment_track)) + setOnClickListener { showZoomDialog(listOf(resolved), 0) } + } + bodyContainer.addView( + iv, + LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ).apply { topMargin = dp(10) }, + ) + loadFullWidth(resolved, iv) + } + + private fun loadFullWidth(url: String, view: ImageView) { + view.tag = url + // "w:" 前缀表示正文宽度规格,与缩略图、全屏图各自独立的键 + val key = "w:$url" + synchronized(cacheLock) { thumbCache.get(key) }?.let { applyFullBitmap(view, it); return } + lifecycleScope.launch { + val screenW = resources.displayMetrics.widthPixels - dp(32) + val bmp = withContext(Dispatchers.IO) { fetchBitmap(url, screenW / 2) } ?: return@launch + synchronized(cacheLock) { thumbCache.put(key, bmp) } + if (view.tag == url) applyFullBitmap(view, bmp) + } + } + + private fun applyFullBitmap(view: ImageView, bmp: Bitmap) { + view.setImageBitmap(bmp) + val w = resources.displayMetrics.widthPixels - dp(32) + val h = (w.toFloat() * bmp.height / bmp.width).toInt().coerceAtMost(dp(2400)) + view.layoutParams = LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + h, + ).apply { topMargin = dp(10) } + view.requestLayout() + } + + private class RoundedOutline(private val radius: Int) : ViewOutlineProvider() { + override fun getOutline(view: View, outline: Outline) { + outline.setRoundRect(0, 0, view.width, view.height, radius.toFloat()) + } + } + + /** 相对地址补全成绝对地址(uploads 图片常以 / 开头) */ + private fun resolveUrl(url: String): String = when { + url.startsWith("http://") || url.startsWith("https://") -> url + url.startsWith("//") -> "https:$url" + originalUrl.isNotBlank() -> runCatching { + java.net.URL(java.net.URL(originalUrl), url).toString() + }.getOrDefault(url) + else -> url + } + + // ---- 图片加载:内存缓存 + 后台解码 ---- + + /** + * 按字节限额而不是按张数:旧实现 thumbCache 限 64 张、fullCache 限 8 张, + * 一张 4000px 的图解码后可达 48MB,64 张上限在低端机上必然 OOM。 + * 这里取可用堆的 1/16 与 1/32(合计约 9%);上一版是 1/8 + 1/16(18.75%), + * 对 256MB 堆的机器仍留了太多余量,收窄后宁可多解一次也不要把堆吃满。 + */ + private val thumbBudget = (Runtime.getRuntime().maxMemory() / 16).toInt() + private val fullBudget = (Runtime.getRuntime().maxMemory() / 32).toInt() + + private val thumbCache = object : LruCache(thumbBudget) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount + } + private val fullCache = object : LruCache(fullBudget) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount + } + private val cacheLock = Any() + + private fun loadThumb(url: String, view: ImageView, sizePx: Int, onLoaded: ((Bitmap?) -> Unit)? = null) { + view.tag = url + // 键里带尺寸:同一张图会按缩略图、正文宽度两种规格各解一次, + // 共用一个键会让正文图命中缩略图(放大后发虚),或缩略图命中大图(白占内存)。 + val key = "t$sizePx:$url" + val cached = synchronized(cacheLock) { thumbCache.get(key) } + if (cached != null) { + view.setImageBitmap(cached) + onLoaded?.invoke(cached) + return + } + lifecycleScope.launch { + val bmp = withContext(Dispatchers.IO) { fetchBitmap(url, sizePx) } + if (bmp != null) synchronized(cacheLock) { thumbCache.put(key, bmp) } + if (view.tag == url && bmp != null) view.setImageBitmap(bmp) + onLoaded?.invoke(bmp) + } + } + + /** targetSize > 0 时按长边降采样解码;0 表示不采样(仍受调用方尺寸约束) */ + private fun fetchBitmap(url: String, targetSize: Int): Bitmap? = runCatching { + val request = Request.Builder() + .url(url) + .header("User-Agent", RssApi.UA_BROWSER) + .build() + imageClient.newCall(request).execute().use { response -> + if (!response.isSuccessful) return@runCatching null + val bytes = response.body?.bytes() ?: return@runCatching null + val opts = BitmapFactory.Options().apply { + if (targetSize > 0) { + inJustDecodeBounds = true + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, this) + inJustDecodeBounds = false + var sample = 1 + // 按长边判断:竖长图若同时要求宽高都达标,会采样不足直接爆内存 + while (maxOf(outWidth, outHeight) / (sample * 2) >= targetSize) { + sample *= 2 + } + inSampleSize = sample + } + } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts) + } + }.getOrNull() + + private fun showZoomDialog(urls: List, index: Int) { + val dialog = Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) + val zoom = ZoomableImageView(this) { dialog.dismiss() } + zoom.setBackgroundColor(Color.BLACK) + dialog.setContentView( + zoom, + ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ), + ) + dialog.show() + val url = urls[index] + // 全屏查看按屏幕长边采样即可;原实现 targetSize=0 解原图, + // 一张 4000×3000 的照片就是 48MB,连开两张低端机必崩。 + val metrics = resources.displayMetrics + val zoomTarget = maxOf(metrics.widthPixels, metrics.heightPixels) + // 全屏图单独一个 "z:" 键:正文宽度图是降采样的,直接拿去放大一定发虚 + val cacheKey = "z:$url" + lifecycleScope.launch { + val bmp = withContext(Dispatchers.IO) { + synchronized(cacheLock) { fullCache.get(cacheKey) } + ?: fetchBitmap(url, zoomTarget) + ?.also { synchronized(cacheLock) { fullCache.put(cacheKey, it) } } + } + if (isFinishing || isDestroyed) return@launch + if (bmp == null) { + dialog.dismiss() + toast("图片加载失败") + } else { + zoom.setBitmap(bmp) + } + } + } + + /** + * FlexPhoto 多种形态统一转 token: + * 1) 原始 markdown:{flex ...} 组内可能是 Markdown 图片(含引用式 ![x][1])、HTML img + * 2) 服务端渲染:RssApi 已转 token,这里兜底漏网的 flexphoto div + */ + private fun normalizeFlexTokens(markdown: String): String { + val imgRe = Regex("]*>", RegexOption.IGNORE_CASE) + val srcRe = Regex("\\b(?:data-src|src)\\s*=\\s*['\"]([^'\"]+)['\"]", RegexOption.IGNORE_CASE) + // 内联式 markdown 图片:![alt](url) / ![alt](url "title") + val mdImgRe = Regex("!\\[[^\\]]*\\]\\(\\s*([^)\\s]+?)(?:\\s+\"[^\"]*\")?\\s*\\)") + // 引用式 markdown 图片:![alt][id],地址在文末 [id]: url 定义行(站里的定义行带前导空格) + val refImgRe = Regex("!\\[([^\\]]*)\\]\\[([^\\]]*)\\]") + val refDefRe = Regex("(?m)^\\s*\\[([^\\]]+)\\]:\\s*(\\S+)") + val refs = refDefRe.findAll(markdown) + .associate { it.groupValues[1].trim() to it.groupValues[2].trim() } + fun toToken(fragment: String): String { + val urls = mutableListOf() + imgRe.findAll(fragment).forEach { img -> + srcRe.find(img.value)?.groupValues?.get(1)?.trim() + ?.takeIf { it.isNotEmpty() }?.let { urls.add(it) } + } + mdImgRe.findAll(fragment).forEach { m -> + val u = m.groupValues[1].trim() + if (u.isNotEmpty()) urls.add(u) + } + refImgRe.findAll(fragment).forEach { m -> + val key = m.groupValues[2].trim().ifEmpty { m.groupValues[1].trim() } + refs[key]?.let { urls.add(it) } + } + if (urls.isNotEmpty()) { + return "\n%%FLEXP%%\n" + urls.joinToString("\n") + "\n%%/FLEXP%%\n" + } + // 兜底:任何形态都解析不到地址时不再整组删除, + // 去掉 flex 标记保留原文,图片至少能以竖排显示 + val kept = fragment.trim() + return if (kept.isBlank()) "" else "\n$kept\n" + } + var s = markdown + s = Regex( + "]*class=\"[^\"]*flexphoto[^\"]*\"[^>]*>[\\s\\S]*?", + RegexOption.IGNORE_CASE, + ).replace(s) { m -> toToken(m.value) } + s = Regex("\\{flex[^{}]*\\}([\\s\\S]*?)\\{/flex\\}", RegexOption.IGNORE_CASE) + .replace(s) { m -> toToken(m.groupValues[1]) } + s = Regex("\\{flex[^{}]*\\}([\\s\\S]*?)/flex\\}", RegexOption.IGNORE_CASE) + .replace(s) { m -> toToken(m.groupValues[1]) } + return s + } + + private fun formatDate(ts: Long): String { + val seconds = if (ts > 1_000_000_000_000L) ts / 1000 else ts + return SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(seconds * 1000)) + } + + private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show() +} diff --git a/src/main/java/com/shitoucuo/postpad/RssApi.kt b/src/main/java/com/shitoucuo/postpad/RssApi.kt new file mode 100644 index 0000000..5ec4b13 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/RssApi.kt @@ -0,0 +1,410 @@ +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。 + * 站端只给摘要,正文需按 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(图片横排插件)服务端渲染出的
图组: + * 转 markdown 会打散成竖排图片,这里先换成 token, + * 阅读页遇到 token 再渲染成横排小图(点击放大)。 + */ + private fun flexPhotoTokens(html: String): String { + val divRe = Regex( + "]*class=\"[^\"]*flexphoto[^\"]*\"[^>]*>[\\s\\S]*?
", + RegexOption.IGNORE_CASE, + ) + val imgRe = Regex("]*>", 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 { + 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 = 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 { + val array = value as? JSONArray ?: return emptyList() + val out = ArrayList(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("", RegexOption.IGNORE_CASE), " ") + .replace(Regex("", 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]*?)", RegexOption.IGNORE_CASE) + val match = regex.find(html) + if (match != null && match.groupValues[1].length > 200) return match.groupValues[1] + } + val body = Regex("]*>([\\s\\S]*?)", 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]*?", + 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("", RegexOption.IGNORE_CASE), "") + s = s.replace(Regex("", RegexOption.IGNORE_CASE), "") + s = s.replace(Regex("", RegexOption.IGNORE_CASE), "") + s = s.replace(Regex("", RegexOption.IGNORE_CASE), "") + // 懒加载图片:先取 data-* 里的地址 + s = s.replace( + Regex("]*?(?:data-src|data-original|data-actualsrc|data-lazy-src)=\"([^\"]+)\"[^>]*?>", RegexOption.IGNORE_CASE), + ) { m -> "" } + for (level in 1..6) { + s = s.replace( + Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE), + ) { m -> "\n\n${"#".repeat(level)} ${stripTags(m.groupValues[1]).trim()}\n\n" } + } + s = s.replace(Regex("]*>([\\s\\S]*?)
", RegexOption.IGNORE_CASE)) { m -> "**${stripTags(m.groupValues[1])}**" } + s = s.replace(Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE)) { m -> "**${stripTags(m.groupValues[1])}**" } + s = s.replace(Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE)) { m -> "*${stripTags(m.groupValues[1])}*" } + s = s.replace(Regex("]*href=\"([^\"]+)\"[^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE)) { m -> + "[${stripTags(m.groupValues[2]).trim()}](${m.groupValues[1]})" + } + s = s.replace(Regex("]*src=\"([^\"]+)\"[^>]*?>", RegexOption.IGNORE_CASE)) { m -> + "\n\n![图片](${m.groupValues[1]})\n\n" + } + s = s.replace(Regex("]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE)) { m -> + "\n- ${stripTags(m.groupValues[1]).trim()}" + } + s = s.replace(Regex("", RegexOption.IGNORE_CASE), "\n") + s = s.replace(Regex("", 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("<[^>]*>"), "") +} diff --git a/src/main/java/com/shitoucuo/postpad/SettingsActivity.kt b/src/main/java/com/shitoucuo/postpad/SettingsActivity.kt new file mode 100644 index 0000000..c444edb --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/SettingsActivity.kt @@ -0,0 +1,672 @@ +package com.shitoucuo.postpad + +import android.os.Bundle +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager +import android.widget.ArrayAdapter +import android.widget.EditText +import android.widget.ImageView +import android.widget.ListView +import android.widget.PopupWindow +import android.widget.Spinner +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.launch + +/** + * 三组互不影响的配置:发文(Typecho 插件接口)、发博(Memos 官方 API)、AI(润色/完善)。 + * 只填一组也能用,另一组会在首页提示去配置。 + */ +class SettingsActivity : AppCompatActivity() { + + private lateinit var prefs: Prefs + + private lateinit var etSiteName: EditText + private lateinit var etSiteUrl: EditText + private lateinit var etToken: EditText + private lateinit var etAuthorId: TextView + private var selectedUserId: Long = 0L + private var selectedUserName: String = "" + private lateinit var btnTestTypecho: TextView + private lateinit var tvTestTypecho: TextView + + private lateinit var etMemosUrl: EditText + private lateinit var etMemosToken: EditText + private lateinit var btnTestMemos: TextView + private lateinit var tvTestMemos: TextView + + private lateinit var spinnerAiProvider: Spinner + private lateinit var etAiKey: EditText + private lateinit var etAiModel: EditText + + private lateinit var etRssSite: EditText + private lateinit var etRssCode: EditText + private lateinit var etRssPage: EditText + private lateinit var btnTestRss: TextView + private lateinit var tvTestRss: TextView + + private lateinit var etMailName: EditText + private lateinit var etMailEmail: EditText + private lateinit var etMailAuth: EditText + private lateinit var etMailHost: EditText + private lateinit var etMailPort: EditText + private lateinit var spinnerMailSecure: Spinner + private lateinit var etMailDays: EditText + private lateinit var btnTestMail: TextView + private lateinit var tvTestMail: TextView + + private lateinit var btnSave: TextView + private lateinit var tvVersion: TextView + + private lateinit var btnSitePick: TextView + private lateinit var btnSiteAdd: TextView + private lateinit var btnSiteDel: TextView + private lateinit var btnMailPick: TextView + private lateinit var btnMailAdd: TextView + private lateinit var btnMailDel: TextView + private lateinit var btnMailHostPick: TextView + + /** 正在编辑的站点 / 邮箱序号(保存或测试时先落回 Prefs) */ + private var editingSiteIndex = 0 + private var editingMailIndex = 0 + + /** 与 Prefs.aiProvider 的值一一对应 */ + private val aiProviders = listOf(AiApi.PROVIDER_DEEPSEEK, AiApi.PROVIDER_ZHIPU) + + /** Spinner 显示值:SSL 开 / 关 */ + private val secureOptions = listOf("开启(推荐)", "关闭") + + override fun onCreate(savedInstanceState: Bundle?) { + prefs = Prefs(this) + // 主题在 super.onCreate 之前定好,设置页不会先亮一下再变暗 + val target = prefs.nightMode() + if (AppCompatDelegate.getDefaultNightMode() != target) { + AppCompatDelegate.setDefaultNightMode(target) + } + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_settings) + + etSiteName = findViewById(R.id.etSiteName) + etSiteUrl = findViewById(R.id.etSiteUrl) + etToken = findViewById(R.id.etToken) + etAuthorId = findViewById(R.id.etAuthorId) + btnTestTypecho = findViewById(R.id.btnTestTypecho) + tvTestTypecho = findViewById(R.id.tvTestTypecho) + + etMemosUrl = findViewById(R.id.etMemosUrl) + etMemosToken = findViewById(R.id.etMemosToken) + btnTestMemos = findViewById(R.id.btnTestMemos) + tvTestMemos = findViewById(R.id.tvTestMemos) + + spinnerAiProvider = findViewById(R.id.spinnerAiProvider) + etAiKey = findViewById(R.id.etAiKey) + etAiModel = findViewById(R.id.etAiModel) + + etRssSite = findViewById(R.id.etRssSite) + etRssCode = findViewById(R.id.etRssCode) + etRssPage = findViewById(R.id.etRssPage) + btnTestRss = findViewById(R.id.btnTestRss) + tvTestRss = findViewById(R.id.tvTestRss) + + etMailName = findViewById(R.id.etMailName) + etMailEmail = findViewById(R.id.etMailEmail) + etMailAuth = findViewById(R.id.etMailAuth) + etMailHost = findViewById(R.id.etMailHost) + etMailPort = findViewById(R.id.etMailPort) + spinnerMailSecure = findViewById(R.id.spinnerMailSecure) + etMailDays = findViewById(R.id.etMailDays) + btnTestMail = findViewById(R.id.btnTestMail) + tvTestMail = findViewById(R.id.tvTestMail) + + btnSave = findViewById(R.id.btnSave) + tvVersion = findViewById(R.id.tvVersion) + tvVersion.text = versionLabel() + + btnSitePick = findViewById(R.id.btnSitePick) + btnSiteAdd = findViewById(R.id.btnSiteAdd) + btnSiteDel = findViewById(R.id.btnSiteDel) + btnMailPick = findViewById(R.id.btnMailPick) + btnMailAdd = findViewById(R.id.btnMailAdd) + btnMailDel = findViewById(R.id.btnMailDel) + btnMailHostPick = findViewById(R.id.btnMailHostPick) + + findViewById(R.id.btnBack).setOnClickListener { finish() } + + // 老版本只有单条配置:物化成列表第一条,方便继续加 + if (prefs.siteCount() == 0) { + prefs.setSiteAt(0, prefs.siteUrl, prefs.token, prefs.authorId) + } + if (prefs.mailCount() == 0) { + prefs.setMailAt( + 0, prefs.mailEmail, prefs.mailAuthCode, prefs.mailImapHost, + prefs.mailImapPort, prefs.mailSecure, prefs.mailFetchDays, + ) + } + editingSiteIndex = prefs.typechoCurrent + editingMailIndex = prefs.mailCurrent + + loadSiteFields() + etAuthorId.setOnClickListener { pickAuthor() } + etMemosUrl.setText(prefs.memosUrl) + etMemosToken.setText(prefs.memosToken) + + setupAiProvider() + etAiKey.setText(prefs.aiKey) + etAiModel.setText(prefs.aiModel) + + etRssSite.setText(prefs.rssSite) + etRssCode.setText(prefs.rssCode) + etRssPage.setText(prefs.rssPageSize.toString()) + + setupMailSecure() + loadMailFields() + + btnSitePick.setOnClickListener { pickSite() } + btnSiteAdd.setOnClickListener { addSite() } + btnSiteDel.setOnClickListener { removeSite() } + btnMailPick.setOnClickListener { pickMail() } + btnMailAdd.setOnClickListener { addMail() } + btnMailDel.setOnClickListener { removeMail() } + setupMailHostPick() + + btnSave.setOnClickListener { + if (save()) { + toast(getString(R.string.saved)) + finish() + } + } + btnTestTypecho.setOnClickListener { testTypecho() } + btnTestMemos.setOnClickListener { testMemos() } + btnTestRss.setOnClickListener { testRss() } + btnTestMail.setOnClickListener { testMail() } + } + + // ==================== 多站点编辑 ==================== + + private fun loadSiteFields() { + val entry = prefs.siteAt(editingSiteIndex) + etSiteName.setText(entry?.name.orEmpty()) + etSiteUrl.setText(entry?.url.orEmpty()) + etToken.setText(entry?.token.orEmpty()) + selectedUserId = entry?.authorId?.toLongOrNull() ?: 0L + etAuthorId.text = if (selectedUserId > 0) "UID $selectedUserId" else "" + btnSitePick.text = + "站点 ${editingSiteIndex + 1}/${prefs.siteCount()} · ${prefs.siteLabel(editingSiteIndex)}" + } + + /** 把当前表单写回正在编辑的站点条目 */ + private fun saveSiteFields() { + prefs.setSiteAt( + editingSiteIndex, + etSiteUrl.text.toString(), + etToken.text.toString(), + selectedUserId.toString(), + etSiteName.text.toString().trim(), + ) + } + + private fun pickSite() { + val labels = (0 until prefs.siteCount()).map { + "${it + 1}. ${prefs.siteLabel(it)}" + } + showPickPopup(btnSitePick, labels, editingSiteIndex) { which -> + if (which != editingSiteIndex) { + saveSiteFields() + editingSiteIndex = which + prefs.typechoCurrent = which + loadSiteFields() + } + } + } + + /** + * 自绘下拉弹窗:与发文页分类菜单同款样式(圆角面板、向上展开、与按钮等宽), + * 当前项文字高亮,替代原来的系统对话框。 + */ + private fun showPickPopup(anchor: View, labels: List, checked: Int, onPick: (Int) -> Unit) { + val palette = Ui.popupPalette(this) + val listView = ListView(this).apply { + adapter = object : ArrayAdapter( + this@SettingsActivity, R.layout.item_spinner_dropdown, labels, + ) { + override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { + val view = super.getView(position, convertView, parent) as TextView + view.setTextColor(if (position == checked) palette.brand else palette.text) + return view + } + } + dividerHeight = 0 + setPadding(0, dp(6), 0, dp(6)) + scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY + } + val listH = (labels.size * dp(46) + dp(12)).coerceAtMost(dp(320)) + val popupH = listH + dp(12) + // 宽度只比最宽的选项文字稍宽一点;extraDp 覆盖背景与行内边距 + val popupW = Ui.menuWidth( + this, labels, textSizeSp = 15f, extraDp = 52, minDp = 110, maxDp = 320, + ) + val popup = PopupWindow(listView, popupW, popupH, true).apply { + isOutsideTouchable = true + setBackgroundDrawable(palette.background()) + elevation = dp(8).toFloat() + } + listView.setOnItemClickListener { _, _, position, _ -> + popup.dismiss() + onPick(position) + } + val loc = IntArray(2) + val rootLoc = IntArray(2) + anchor.getLocationOnScreen(loc) + anchor.rootView.getLocationOnScreen(rootLoc) + val anchorY = loc[1] - rootLoc[1] + val x = loc[0] - rootLoc[0] + // 默认在锚点上方展开;上方放不下(矮屏、或选项多到 320dp 上限)时改到下方, + // 否则弹窗会被顶出屏幕,看起来像"点了没反应"。 + var y = anchorY - popupH - dp(6) + if (y < dp(8)) { + val below = anchorY + anchor.height + dp(6) + y = if (below + popupH <= anchor.rootView.height - dp(8)) below + else dp(8) + } + popup.showAtLocation(anchor.rootView, Gravity.TOP or Gravity.START, x, y) + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + private fun addSite() { + saveSiteFields() + editingSiteIndex = prefs.addSite() + prefs.typechoCurrent = editingSiteIndex + loadSiteFields() + toast("已新增站点,填好地址和 Token 后点保存") + } + + private fun removeSite() { + if (prefs.siteCount() <= 1) { + toast("至少保留一个站点") + return + } + AlertDialog.Builder(this) + .setTitle("删除站点") + .setMessage("确定删除「${prefs.siteLabel(editingSiteIndex)}」?") + .setPositiveButton("删除") { _, _ -> + prefs.removeSiteAt(editingSiteIndex) + editingSiteIndex = prefs.typechoCurrent + loadSiteFields() + toast("已删除") + } + .setNegativeButton("取消", null) + .show() + } + + // ==================== 多邮箱编辑 ==================== + + private fun loadMailFields() { + val entry = prefs.mailAt(editingMailIndex) + etMailName.setText(entry?.name.orEmpty()) + etMailEmail.setText(entry?.email.orEmpty()) + etMailAuth.setText(entry?.auth.orEmpty()) + etMailHost.setText(entry?.host.orEmpty()) + etMailPort.setText((entry?.port ?: 993).toString()) + etMailDays.setText((entry?.days ?: 30).toString()) + spinnerMailSecure.setSelection(if (entry?.secure != false) 0 else 1) + btnMailPick.text = + "邮箱 ${editingMailIndex + 1}/${prefs.mailCount()} · ${prefs.mailLabel(editingMailIndex)}" + } + + private fun saveMailFields() { + prefs.setMailAt( + editingMailIndex, + etMailEmail.text.toString(), + etMailAuth.text.toString(), + etMailHost.text.toString(), + etMailPort.text.toString().toIntOrNull()?.takeIf { it in 1..65535 } ?: 993, + spinnerMailSecure.selectedItemPosition == 0, + etMailDays.text.toString().toIntOrNull()?.takeIf { it in 1..365 } ?: 30, + etMailName.text.toString().trim(), + ) + } + + private fun pickMail() { + val labels = (0 until prefs.mailCount()).map { + "${it + 1}. ${prefs.mailLabel(it)}" + } + showPickPopup(btnMailPick, labels, editingMailIndex) { which -> + if (which != editingMailIndex) { + saveMailFields() + editingMailIndex = which + prefs.mailCurrent = which + loadMailFields() + } + } + } + + private fun addMail() { + saveMailFields() + editingMailIndex = prefs.addMail() + prefs.mailCurrent = editingMailIndex + loadMailFields() + toast("已新增邮箱,填好后点保存") + } + + private fun removeMail() { + if (prefs.mailCount() <= 1) { + toast("至少保留一个邮箱") + return + } + AlertDialog.Builder(this) + .setTitle("删除邮箱") + .setMessage("确定删除「${prefs.mailLabel(editingMailIndex)}」?") + .setPositiveButton("删除") { _, _ -> + prefs.removeMailAt(editingMailIndex) + editingMailIndex = prefs.mailCurrent + loadMailFields() + toast("已删除") + } + .setNegativeButton("取消", null) + .show() + } + + private fun setupMailSecure() { + val adapter = ArrayAdapter(this, R.layout.item_spinner, secureOptions) + adapter.setDropDownViewResource(R.layout.item_spinner_dropdown) + spinnerMailSecure.adapter = adapter + spinnerMailSecure.setSelection(if (prefs.mailSecure) 0 else 1) + } + + /** + * 常用 IMAP 服务器。列出的这些服务商都是 993 + SSL,选中即一并改好端口与开关, + * 用户只需再填授权码。最后一档是「自定义」,落到输入框手动敲, + * 自建邮局或服务商未收录的情况走这里。 + */ + private val mailHostPresets = listOf( + "imap.126.com", + "imap.163.com", + "imap.qq.com", + "imap.yeah.net", + "imap.sina.com", + "imap.gmail.com", + "outlook.office365.com", + "imap.aliyun.com", + ) + + private fun setupMailHostPick() { + btnMailHostPick.setOnClickListener { + val labels = mailHostPresets + getString(R.string.mail_host_custom) + val current = etMailHost.text.toString().trim() + val checked = mailHostPresets.indexOfFirst { it.equals(current, true) } + showPickPopup(btnMailHostPick, labels, checked) { which -> + if (which < 0 || which >= mailHostPresets.size) { + // 自定义:把已填内容整体选中,直接敲就是覆盖,不必先长按删除 + etMailHost.requestFocus() + etMailHost.setSelection(0, etMailHost.text.length) + etMailHost.post { + getSystemService(InputMethodManager::class.java) + ?.showSoftInput(etMailHost, InputMethodManager.SHOW_IMPLICIT) + } + return@showPickPopup + } + val host = mailHostPresets[which] + etMailHost.setText(host) + etMailHost.setSelection(host.length) + etMailPort.setText("993") + spinnerMailSecure.setSelection(0) + toast("已填入 $host(端口 993,SSL)") + } + } + } + + private fun setupAiProvider() { + val labels = listOf("DeepSeek", "智谱 GLM") + val adapter = ArrayAdapter(this, R.layout.item_spinner, labels) + adapter.setDropDownViewResource(R.layout.item_spinner_dropdown) + spinnerAiProvider.adapter = adapter + + val index = aiProviders.indexOf(prefs.aiProvider) + spinnerAiProvider.setSelection(if (index >= 0) index else 0) + } + + private fun collect() { + // 当前正在编辑的条目才是这些字段的目标 + prefs.typechoCurrent = editingSiteIndex + prefs.mailCurrent = editingMailIndex + prefs.siteUrl = normalizeSite(etSiteUrl) + prefs.token = etToken.text.toString() + prefs.authorId = selectedUserId.toString() + // 站点名称也要落盘,否则改名后保存无效 + prefs.siteName = etSiteName.text.toString() + prefs.memosUrl = normalizeMemos(etMemosUrl) + prefs.memosToken = etMemosToken.text.toString() + + val index = spinnerAiProvider.selectedItemPosition + prefs.aiProvider = aiProviders.getOrElse(index) { AiApi.PROVIDER_DEEPSEEK } + prefs.aiKey = etAiKey.text.toString() + prefs.aiModel = etAiModel.text.toString() + + prefs.rssSite = normalizeSite(etRssSite) + prefs.rssCode = etRssCode.text.toString() + prefs.rssPageSize = etRssPage.text.toString().toIntOrNull()?.takeIf { it in 5..100 } ?: 20 + + // 当前邮箱整条一次写全(含名称)。原先逐项赋值,唯独漏了「邮箱名称」, + // 于是改名后保存无效,首页与邮件页顶部一直显示邮箱地址而不是名称。 + // 改走 saveMailFields() 与切换/新增邮箱时的写回共用同一段逻辑, + // 以后加字段也不会再漏一处。 + val days = etMailDays.text.toString().toIntOrNull()?.takeIf { it in 1..365 } ?: 30 + val daysChanged = days != prefs.mailFetchDays + saveMailFields() + // 同步天数变了要清掉该邮箱缓存:增量只取「比缓存最新 UID 更新」的邮件, + // 不清缓存的话把 30 天改成 90 天也看不到更早的邮件,设置项等于没生效。 + if (daysChanged) { + prefs.mailAt(editingMailIndex)?.let { MailApi.resetCache(prefs, it) } + } + } + + /** + * 站点地址:补协议、剥离 /api、/index.php 这类接口后缀,并把结果写回输入框, + * 让用户直接看到程序实际使用的地址,避免"填了 /index.php/api 导致路径重复"这类问题。 + */ + private fun normalizeSite(field: EditText): String { + val raw = field.text.toString() + val value = Prefs.normalizeSite(raw) + if (value != raw) { + field.setText(value) + field.setSelection(value.length) + } + return value + } + + /** Memos 地址:要根地址,顺手去掉误填的 /api、/api/v1 */ + private fun normalizeMemos(field: EditText): String { + val raw = field.text.toString() + var value = raw.trim().trimEnd('/') + if (value.isNotEmpty()) { + if (!value.startsWith("http://", true) && !value.startsWith("https://", true)) { + value = "https://$value" + } + for (suffix in listOf("/api/v1", "/api")) { + if (value.length > suffix.length && value.endsWith(suffix, true)) { + value = value.dropLast(suffix.length).trimEnd('/') + } + } + } + if (value != raw) { + field.setText(value) + field.setSelection(value.length) + } + return value + } + + /** + * 作者从站点用户列表里选:先把界面上填的网站地址/Token 落到 Prefs 供接口使用, + * 拉到列表后弹单选对话框,选中即回填显示名并记住 uid(保存时写入 authorId)。 + */ + private fun pickAuthor() { + val site = normalizeSite(etSiteUrl) + val token = etToken.text.toString().trim() + if (site.isEmpty() || token.isEmpty()) { + showResult(tvTestTypecho, "先填网站地址和 API Token,才能查询管理员列表") + return + } + // 仅临时写入查询所需的两项,不动 authorId 等其它配置 + prefs.siteUrl = site + prefs.token = token + + etAuthorId.isEnabled = false + showResult(tvTestTypecho, "正在查询管理员列表…") + lifecycleScope.launch { + try { + val users = TypechoApi.users(prefs) + if (users.isEmpty()) { + showResult(tvTestTypecho, "没有查到用户,请确认已开启「用户列表」接口") + return@launch + } + val labels = users.map { "${it.name}(UID ${it.uid})" }.toTypedArray() + val checked = users.indexOfFirst { it.uid == selectedUserId } + AlertDialog.Builder(this@SettingsActivity) + .setTitle("选择发布作者") + .setSingleChoiceItems(labels, checked) { dialog, which -> + val picked = users[which] + selectedUserId = picked.uid + selectedUserName = picked.name + etAuthorId.text = "${picked.name}(UID ${picked.uid})" + showResult(tvTestTypecho, "已选择作者:${picked.name}") + dialog.dismiss() + } + .setNegativeButton("取消", null) + .show() + } catch (e: Exception) { + showResult(tvTestTypecho, "查询失败:${e.message ?: "未知错误"}") + } finally { + etAuthorId.isEnabled = true + } + } + } + + private fun save(): Boolean { + collect() + if (!prefs.typechoReady && !prefs.memosReady && !prefs.aiReady && + !prefs.rssReady && !prefs.mailReady + ) { + toast("至少配置一组:发文、发博、AI、RSS 或邮件") + return false + } + return true + } + + private fun testTypecho() { + collect() + if (!prefs.typechoReady) { + showResult(tvTestTypecho, "先填完网站地址、API Token 并选择作者") + return + } + + setTesting(btnTestTypecho, true) + showResult(tvTestTypecho, getString(R.string.testing)) + + lifecycleScope.launch { + try { + showResult(tvTestTypecho, TypechoApi.check(prefs)) + } catch (e: Exception) { + showResult(tvTestTypecho, "失败:${e.message ?: "未知错误"}") + } finally { + setTesting(btnTestTypecho, false) + } + } + } + + private fun testMemos() { + collect() + if (!prefs.memosReady) { + showResult(tvTestMemos, "先填完 Memos 网站地址和 Access Token") + return + } + + setTesting(btnTestMemos, true) + showResult(tvTestMemos, getString(R.string.testing)) + + lifecycleScope.launch { + try { + showResult(tvTestMemos, MemosApi.check(prefs)) + } catch (e: Exception) { + showResult(tvTestMemos, "失败:${e.message ?: "未知错误"}") + } finally { + setTesting(btnTestMemos, false) + } + } + } + + private fun testRss() { + collect() + if (!prefs.rssReady) { + showResult(tvTestRss, "先填 RSS 站点地址和授权码") + return + } + setTesting(btnTestRss, true) + showResult(tvTestRss, getString(R.string.testing)) + lifecycleScope.launch { + try { + showResult(tvTestRss, RssApi.check(prefs)) + } catch (e: Exception) { + showResult(tvTestRss, "失败:${e.message ?: "未知错误"}") + } finally { + setTesting(btnTestRss, false) + } + } + } + + private fun testMail() { + collect() + // 测试用「正在编辑的这条」账户快照:prefs 的当前账户就是它,但快照更直接 + val account = prefs.mailAt(editingMailIndex) + if (account == null || !account.ready) { + showResult( + tvTestMail, + when { + account == null || account.email.isBlank() -> "当前邮箱没填邮箱地址" + account.auth.isBlank() -> "当前邮箱没填 IMAP 授权码" + else -> "当前邮箱没填 IMAP 服务器" + }, + ) + return + } + setTesting(btnTestMail, true) + showResult(tvTestMail, getString(R.string.testing)) + // 把实际使用的服务器写进结果:填错服务器(比如 126 账号填了 imap.qq.com) + // 从输入框看不出来,这里一眼能核对 + val endpoint = "${account.host}:${account.port}" + lifecycleScope.launch { + try { + showResult(tvTestMail, "$endpoint · ${MailApi.check(prefs, account)}") + } catch (e: Exception) { + showResult(tvTestMail, "$endpoint · 失败:${e.message ?: "未知错误"}") + } finally { + setTesting(btnTestMail, false) + } + } + } + + /** 结果行平时不占位置,有内容才出现,避免设置页一直悬着两行空白 */ + private fun showResult(view: TextView, text: String) { + view.text = text + view.visibility = if (text.isBlank()) View.GONE else View.VISIBLE + } + + private fun setTesting(button: TextView, testing: Boolean) { + button.isEnabled = !testing + button.alpha = if (testing) 0.55f else 1f + } + + private fun versionLabel(): String = runCatching { + packageManager.getPackageInfo(packageName, 0).versionName + }.getOrNull()?.takeIf { it.isNotBlank() }?.let { "v$it" }.orEmpty() + + private fun toast(text: String) { + Toast.makeText(this, text, Toast.LENGTH_SHORT).show() + } +} diff --git a/src/main/java/com/shitoucuo/postpad/TypechoApi.kt b/src/main/java/com/shitoucuo/postpad/TypechoApi.kt new file mode 100644 index 0000000..2755fdd --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/TypechoApi.kt @@ -0,0 +1,475 @@ +package com.shitoucuo.postpad + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.MultipartBody +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject +import java.util.concurrent.TimeUnit + +/** + * TypechoToObsidian 插件对外接口的最小封装。 + * + * 两个必须的请求头(少一个都会被插件拦掉): + * - token :与插件设置里的 apiToken 一致,否则 403 apiToken is invalid + * - Origin :必须命中插件 origin 白名单,否则 400 非法请求 + * 这里直接复用站点根地址作为 Origin。 + * + * 接口路径有两种可用形式: + * - 伪静态 https://站点/api/posts + * - 兼容 https://站点/index.php/api/posts + * 二者由 withFallback() 自动选择,结果记进 Prefs,后续请求直接用上次成功的那个。 + */ +object TypechoApi { + + private val JSON = "application/json; charset=utf-8".toMediaType() + + private val client: OkHttpClient = Http.newWith(20, 60, 90, TimeUnit.SECONDS) + + class ApiException(message: String, val code: Int = 0) : Exception(message) + + data class PublishResult(val cid: Long, val permalink: String) + + /** 分类 / 标签在 Typecho 里都是 metas 记录,用 mid 区分 */ + data class Meta(val mid: Long, val name: String) + + /** 文章列表项(/api/posts 不含分类标签,列表只展示标题与摘要) */ + data class Post( + val cid: Long, + val title: String, + val created: Long, + val digest: String, + val permalink: String, + val comments: Int, + ) + + /** 文章列表分页结果 */ + data class PostPage(val posts: List, val page: Int, val pages: Int, val total: Int) + + /** 文章详情:markdown 是带 标记的原文 */ + data class PostDetail( + val cid: Long, + val title: String, + val markdown: String, + val text: String, + val created: Long, + val permalink: String, + val categories: List, + val tags: List, + ) + + /** 站点用户(管理员),uid 发布时作为 authorId,name 只用于下拉显示 */ + data class User(val uid: Long, val name: String) + + /** Typecho 的内容状态:publish 直接公开,waiting 是后台的「待审核」 */ + const val STATUS_WAITING = "waiting" + + /** 刚传完的附件一定在最近几条里,取一页就够 */ + private const val RESOLVE_PAGE_SIZE = 12 + + /** 连通性检查:拉一篇文章列表,顺便回报站点文章总数 */ + suspend fun check(prefs: Prefs): String = withContext(Dispatchers.IO) { + val total = withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/posts?pageSize=1") + .get() + .build() + + execute(request) { json -> + json.optJSONObject("data")?.optInt("count", 0) ?: 0 + } + } + "连接正常,站点现有文章 $total 篇" + } + + /** + * 发布文章。 + * + * - status 固定传 waiting,落库即为后台的「待审核」,不在前台直接公开。 + * - mids 是分类与标签的 mid 列表,服务端用逗号分隔的字符串接收。 + * - text 前置 `` 是 Typecho 的 Markdown 渲染标记, + * 与 Obsidian 插件的做法一致;不加的话正文会按纯 HTML 处理,换行全丢。 + */ + suspend fun publish( + prefs: Prefs, + title: String, + markdown: String, + mids: List, + fileIds: List = emptyList(), + ): PublishResult = withContext(Dispatchers.IO) { + val payload = JSONObject().apply { + put("title", title) + put("text", "" + markdown) + put("authorId", prefs.authorId) + put("status", STATUS_WAITING) + if (mids.isNotEmpty()) { + put("mid", mids.joinToString(",")) + } + // 附件在文章还没有 cid 时就传上去了,parent 只能是 0; + // 把附件 cid 一起报上去,插件写完文章会把它们挂到这篇下面, + // 网页端编辑页的「附件」列表才看得到这些图。 + if (fileIds.isNotEmpty()) { + put("files", fileIds.joinToString(",")) + } + } + val body = payload.toString().toRequestBody(JSON) + + withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/postArticle") + .post(body) + .build() + + execute(request) { json -> + val data = json.optJSONObject("data") + PublishResult( + cid = data?.optLong("cid") ?: 0L, + permalink = data?.optString("permalink").orEmpty(), + ) + } + } + } + + // ==================== 附件(发文插图) ==================== + + /** 上传成功后的附件:cid 用于回查真实地址,name 是服务端文件名,url 是可直接写进 Markdown 的地址 */ + data class Uploaded(val cid: Long, val name: String, val url: String) + + /** 附件列表里的一行,只取回查地址要用的两个字段 */ + private data class AttachmentUrl(val cid: Long, val url: String) + + /** + * 上传一张图,与网页端「写文章 → 上传附件」走同一个接口 /api/upload。 + * + * 必须用 multipart:插件里的 Util::getUploadFile 只有拿到 $_FILES 才会带上 tmp_name, + * 而七牛插件的 uploadFile 又要求有 tmp_name,否则直接返回 false。 + * + * 装了七牛后,接口回的 url 只是对象 key(typecho/2026/11/xxx.webp), + * 真正能访问的是 CDN 域名 + 这个 key,而且带 ?imageView2 参数—— + * 所以这里再查一次附件列表拿现成地址(插件用的就是 attachmentHandle 的返回值)。 + */ + suspend fun upload( + prefs: Prefs, + bytes: ByteArray, + filename: String, + mime: String, + ): Uploaded = withContext(Dispatchers.IO) { + val body = MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", filename, bytes.toRequestBody(mime.toMediaTypeOrNull())) + .build() + + var host = prefs.siteUrl + val uploaded = withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/upload") + .post(body) + .build() + + execute(request) { json -> + val data = json.optJSONObject("data") + host = data?.optString("host").orEmpty().ifEmpty { prefs.siteUrl } + Uploaded( + cid = data?.optLong("cid") ?: 0L, + name = data?.optString("title").orEmpty(), + url = data?.optString("url").orEmpty(), + ) + } + } + + if (uploaded.url.startsWith("http", true)) { + uploaded + } else { + uploaded.copy(url = resolveUrl(prefs, uploaded.cid, uploaded.url, host)) + } + } + + /** + * 把相对 key 换成可访问地址。 + * + * 优先问附件列表(七牛域名、imageView2 参数都在里面); + * 列表接口没开或查不到时退化成「站点地址 + 路径」,本地存储的站点这样也能正常显示。 + */ + private suspend fun resolveUrl(prefs: Prefs, cid: Long, path: String, host: String): String { + if (path.isEmpty()) return "" + val found = try { + attachments(prefs, RESOLVE_PAGE_SIZE) + .firstOrNull { it.cid == cid && it.url.isNotEmpty() } + ?.url + } catch (e: Exception) { + null + } + if (!found.isNullOrEmpty()) return found + + val base = host.ifEmpty { prefs.siteUrl } + return if (base.isEmpty()) path else "$base/${path.trimStart('/')}" + } + + private suspend fun attachments(prefs: Prefs, pageSize: Int): List = + withContext(Dispatchers.IO) { + withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/fileList?page=1&pageSize=$pageSize") + .get() + .build() + + execute(request) { json -> + val array = json.optJSONObject("data")?.optJSONArray("dataSet") ?: JSONArray() + val list = ArrayList(array.length()) + for (index in 0 until array.length()) { + val item = array.optJSONObject(index) ?: continue + val id = item.optLong("cid", 0L) + if (id <= 0) continue + list.add(AttachmentUrl(id, item.optString("url"))) + } + list + } + } + } + + /** + * 站点用户列表,供设置页选作者(发布时的 authorId)。 + * /api/userList 返回 data 是数组:uid / screenName / mail / url / count / posts。 + */ + suspend fun users(prefs: Prefs): List = withContext(Dispatchers.IO) { + withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/userList") + .get() + .build() + + execute(request) { json -> + val array = json.optJSONArray("data") ?: JSONArray() + val list = ArrayList(array.length()) + for (index in 0 until array.length()) { + val item = array.optJSONObject(index) ?: continue + val uid = item.optLong("uid", 0L) + val name = item.optString("screenName").ifBlank { "UID $uid" } + if (uid > 0) list.add(User(uid, name)) + } + list + } + } + } + + // ==================== 阅读:列表与详情 ==================== + + /** + * 文章列表。showDigest=excerpt&limit=N 让服务端给简短摘要, + * 而不是默认的整篇渲染 HTML。 + */ + suspend fun posts(prefs: Prefs, page: Int, pageSize: Int = 20): PostPage = + withContext(Dispatchers.IO) { + withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/posts?page=$page&pageSize=$pageSize&showDigest=excerpt&limit=160") + .get() + .build() + execute(request) { json -> + // 插件实际返回:{ status:"success", data:{ page, pages, count, dataSet:[...] } } + // 旧代码直接读根节点的 dataSet,结果永远是空列表。 + val block = json.optJSONObject("data") ?: JSONObject() + val array = block.optJSONArray("dataSet") ?: JSONArray() + val out = ArrayList(array.length()) + for (i in 0 until array.length()) { + val obj = array.optJSONObject(i) ?: continue + val cid = obj.optLong("cid", 0L) + if (cid <= 0) continue + out.add( + Post( + cid = cid, + title = obj.optString("title").ifBlank { "无标题" }, + created = obj.optLong("created", 0L), + digest = stripTags(obj.optString("digest")).take(200), + permalink = obj.optString("permalink").ifBlank { obj.optString("url") }, + comments = obj.optInt("commentsNum", 0), + ) + ) + } + PostPage( + posts = out, + page = block.optInt("page", page), + pages = block.optInt("pages", 1), + total = block.optInt("count", out.size), + ) + } + } + } + + /** 文章详情:优先 postDetail(Markdown + 分类标签),旧插件回退 /api/post */ + suspend fun postDetail(prefs: Prefs, cid: Long, slug: String = ""): PostDetail = + withContext(Dispatchers.IO) { + val key = if (slug.isNotEmpty()) "slug=$slug" else "cid=$cid" + var lastError: Exception? = null + + for (path in listOf("postDetail", "post")) { + try { + return@withContext withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/$path?$key") + .get() + .build() + execute(request) { json -> + // 与列表一样,正文也在 data 节点里;根节点只有 status/message/data。 + val data = json.optJSONObject("data") ?: json + val markdown = data.optString("markdown") + val text = data.optString("text") + PostDetail( + cid = data.optLong("cid", cid), + title = data.optString("title").ifBlank { "无标题" }, + markdown = markdown, + text = text, + created = data.optLong("created", 0L), + permalink = data.optString("permalink").ifBlank { data.optString("url") }, + categories = nameList(data.opt("categories")), + tags = nameList(data.opt("tags")), + ) + } + } + } catch (e: ApiException) { + lastError = e + if (e.code != 404) throw e + } + } + throw lastError ?: ApiException("文章详情接口不可用") + } + + private fun nameList(value: Any?): List { + val array = value as? JSONArray ?: return emptyList() + val out = ArrayList(array.length()) + for (i in 0 until array.length()) { + val item = array.opt(i) + val name = when (item) { + is String -> item + is JSONObject -> item.optString("name") + else -> "" + }.trim() + if (name.isNotEmpty() && name !in out) out.add(name) + } + return out + } + + private fun stripTags(s: String): String = s + .replace(Regex(""), " ") + .replace(Regex("<[^>]*>"), " ") + .replace(Regex("\\s+"), " ") + .trim() + + /** 分类列表,供发文页下拉选择 */ + suspend fun categories(prefs: Prefs): List = metas(prefs, "categories") + + /** 标签列表,供发文页联想补全 */ + suspend fun tags(prefs: Prefs): List = metas(prefs, "tags") + + /** + * 新建标签,返回它的 mid;同名标签已存在时直接复用,不重复创建。 + * + * addMetas 只回插入结果不带 mid,所以创建后重新拉一次标签列表按名字匹配。 + */ + suspend fun createTag(prefs: Prefs, name: String): Long = withContext(Dispatchers.IO) { + val payload = JSONObject().apply { + put("name", name) + put("type", "tag") + put("slug", name) + } + val body = payload.toString().toRequestBody(JSON) + + withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/addMetas") + .post(body) + .build() + // execute 内已把 status != success 的情况抛成异常,这里走到就代表创建成功 + execute(request) { } + } + + tags(prefs).firstOrNull { it.name == name }?.mid ?: 0L + } + + private suspend fun metas(prefs: Prefs, path: String): List = + withContext(Dispatchers.IO) { + withFallback(prefs) { prefix -> + val request = baseRequest(prefs) + .url("${prefs.siteUrl}$prefix/api/$path") + .get() + .build() + + execute(request) { json -> + val array = json.optJSONArray("data") ?: JSONArray() + val list = ArrayList(array.length()) + for (index in 0 until array.length()) { + val item = array.optJSONObject(index) ?: continue + val mid = item.optLong("mid", 0L) + val name = item.optString("name") + if (mid > 0 && name.isNotEmpty()) { + list.add(Meta(mid, name)) + } + } + list + } + } + } + + private fun baseRequest(prefs: Prefs): Request.Builder = + Request.Builder() + .header("token", prefs.token) + .header("Origin", prefs.siteUrl) + .header("Accept", "application/json") + .header("User-Agent", RssApi.UA_BROWSER) + + /** + * 依次尝试候选路径前缀:先试上次成功过的,再试其它候选。 + * + * 只对 404 换路径重试——那是「路由没命中」的确定信号; + * 403(token 错)、500 等属于真实业务错误,直接抛出,避免重试掩盖问题。 + * 成功一次就把前缀写回 Prefs,正常使用时不会有额外请求。 + */ + private fun withFallback(prefs: Prefs, block: (String) -> T): T { + val ordered = LinkedHashSet() + ordered.add(prefs.apiPrefix) + ordered.addAll(Prefs.API_PREFIXES) + + var last: ApiException? = null + for (prefix in ordered) { + try { + val result = block(prefix) + prefs.apiPrefix = prefix + return result + } catch (e: ApiException) { + last = e + if (e.code != 404) throw e + } + } + throw last ?: ApiException("接口路径都无法访问,请检查网站地址") + } + + private fun execute(request: Request, parse: (JSONObject) -> T): T { + client.newCall(request).execute().use { response -> + val body = response.body?.string().orEmpty() + val json = try { + JSONObject(body) + } catch (e: Exception) { + // 非 JSON 响应多为伪静态 404 页或 502 网关页,剥掉标签留可读内容方便排查 + val brief = body + .replace(Regex("<[^>]*>"), " ") + .replace(Regex("\\s+"), " ") + .trim() + .take(160) + throw ApiException( + "HTTP ${response.code}:${brief.ifBlank { "响应为空" }}", + response.code, + ) + } + if (json.optString("status") != "success") { + val message = json.optString("message").ifBlank { "请求失败" } + throw ApiException("$message(HTTP ${response.code})", response.code) + } + return parse(json) + } + } +} diff --git a/src/main/java/com/shitoucuo/postpad/Ui.kt b/src/main/java/com/shitoucuo/postpad/Ui.kt new file mode 100644 index 0000000..41dc041 --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/Ui.kt @@ -0,0 +1,132 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.content.res.Configuration +import android.graphics.Color +import android.graphics.Paint +import android.graphics.drawable.Drawable +import android.graphics.drawable.GradientDrawable +import android.graphics.drawable.InsetDrawable +import android.text.TextPaint +import android.util.TypedValue + +/** 通用 UI 小工具 */ +object Ui { + + /** + * 弹窗配色板:背景、文字、分隔线、高亮色一次性取齐,且**全部来自同一个 Resources 实例**。 + * + * 这是「深色切浅色后下拉菜单黑底黑字」的根因修复。旧实现 + * `popupBackground(context, night)` 会按 night 参数 `createConfigurationContext()` + * 另造一份资源去取 surface,而菜单项文字仍旧由页面按当前资源染色(`R.color.text`)。 + * 一旦这两份资源对深浅色的判断不一致——切到浅色时恰好发生了——就成了 + * 背景取深色 surface、文字取浅色 text,即黑底黑字。 + * + * 现在统一走 `context.resources`,即弹出弹窗的那个页面自己的资源: + * 页面是什么色,弹窗就是什么色,背景与文字必然同一套,不可能再同色。 + */ + class PopupPalette internal constructor( + val surface: Int, + val stroke: Int, + val text: Int, + val textSecondary: Int, + val divider: Int, + val brand: Int, + val night: Boolean, + private val density: Float, + ) { + /** 圆角面板 + 1px 描边,6dp 内边距让文字不压到圆角与描边 */ + fun background(cornerDp: Int = 12): Drawable { + val shape = GradientDrawable().apply { + shape = GradientDrawable.RECTANGLE + cornerRadius = cornerDp * density + setColor(surface) + setStroke((1 * density).toInt().coerceAtLeast(1), stroke) + } + return InsetDrawable(shape, (6 * density).toInt()) + } + } + + /** + * 取当前页面的弹窗配色板。 + * + * 必须传 Activity(不能用 applicationContext):Activity 的资源才是页面真正 + * 生效的那份,只有取自同一份资源,弹窗与页面才不会深浅错位。 + */ + fun popupPalette(context: Context): PopupPalette { + val res = context.resources + val surface = res.getColor(R.color.surface, null) + var text = res.getColor(R.color.text, null) + var brand = res.getColor(R.color.brand, null) + // 兜底:同源取色时对比度必然充足,正常不会进这里。万一将来又有人在别处 + // 混用两套资源(或厂商 ROM 的资源缓存出问题),这里至少保证文字与背景 + // 分得开,绝不会再出现"背景黑、字也黑"这种完全看不见的情况。 + if (contrastRatio(surface, text) < 3.0) { + text = if (luminance(surface) < 0.5) Color.WHITE else Color.BLACK + } + if (contrastRatio(surface, brand) < 2.0) brand = text + return PopupPalette( + surface = surface, + stroke = res.getColor(R.color.card_stroke, null), + text = text, + textSecondary = res.getColor(R.color.text_secondary, null), + divider = res.getColor(R.color.divider, null), + brand = brand, + night = (res.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == + Configuration.UI_MODE_NIGHT_YES, + density = res.displayMetrics.density, + ) + } + + /** 相对亮度(WCAG 2.0),用于判断前景与背景是否够区分 */ + private fun luminance(color: Int): Double { + fun channel(value: Int): Double { + val s = value / 255.0 + return if (s <= 0.03928) s / 12.92 else Math.pow((s + 0.055) / 1.055, 2.4) + } + return 0.2126 * channel(Color.red(color)) + + 0.7152 * channel(Color.green(color)) + + 0.0722 * channel(Color.blue(color)) + } + + /** 对比度(1~21),正文可读的经验下限约 3.0 */ + private fun contrastRatio(a: Int, b: Int): Double { + val la = luminance(a) + val lb = luminance(b) + return (maxOf(la, lb) + 0.05) / (minOf(la, lb) + 0.05) + } + + /** 只要背景时的便捷入口(与 popupPalette(context).background() 等价) */ + fun popupBackground(context: Context, cornerDp: Int = 12): Drawable = + popupPalette(context).background(cornerDp) + + /** + * 按最宽文本计算下拉菜单宽度:比文字稍宽即可,不再与锚点控件等宽。 + * + * @param textSizeSp 菜单文字字号(与 item 布局保持一致) + * @param extraDp 额外预留:左右内边距 + 背景 + 滚动条 + * @param minDp/maxDp 宽度上下限 + */ + fun menuWidth( + context: Context, + texts: List, + textSizeSp: Float = 15f, + extraDp: Int = 32, + minDp: Int = 96, + maxDp: Int = 240, + ): Int { + val dm = context.resources.displayMetrics + val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { + // 走 applyDimension 而不是直接乘已废弃的 scaledDensity: + // 系统字号放大后(尤其 Android 14 的非线性字体缩放),手乘得到的宽度 + // 会小于实际渲染宽度,菜单项又带 ellipsize,四五个字就会被截成两三个。 + textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSizeSp, dm) + } + var text = 0f + for (t in texts) text = maxOf(text, paint.measureText(t)) + val d = dm.density + // +0.5f 是四舍五入:直接 toInt() 会向下取整,宽度总比算出来的少 1px + return (text + extraDp * d + 0.5f).toInt() + .coerceIn((minDp * d).toInt(), (maxDp * d).toInt()) + } +} diff --git a/src/main/java/com/shitoucuo/postpad/ZoomableImageView.kt b/src/main/java/com/shitoucuo/postpad/ZoomableImageView.kt new file mode 100644 index 0000000..9ea670e --- /dev/null +++ b/src/main/java/com/shitoucuo/postpad/ZoomableImageView.kt @@ -0,0 +1,158 @@ +package com.shitoucuo.postpad + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Matrix +import android.graphics.RectF +import android.view.GestureDetector +import android.view.MotionEvent +import android.view.ScaleGestureDetector +import android.view.View + +/** + * 图片缩放视图:双指缩放、拖动、双击放大/还原、单击关闭。 + * 用于阅读页 FlexPhoto 图组点击放大查看。 + */ +class ZoomableImageView(context: Context, private val onTapClose: () -> Unit) : View(context) { + + private var bitmap: Bitmap? = null + private val drawMatrix = Matrix() + private val saved = Matrix() + private val displayRect = RectF() + private var minScale = 0.5f + private val maxScale = 6f + + private val scaleDetector = ScaleGestureDetector( + context, + object : ScaleGestureDetector.SimpleOnScaleGestureListener() { + override fun onScaleBegin(detector: ScaleGestureDetector): Boolean { + saved.set(drawMatrix) + return true + } + + override fun onScale(detector: ScaleGestureDetector): Boolean { + drawMatrix.set(saved) + drawMatrix.postScale( + detector.scaleFactor, detector.scaleFactor, + detector.focusX, detector.focusY, + ) + clamp() + invalidate() + return true + } + }, + ) + + private val gestureDetector = GestureDetector( + context, + object : GestureDetector.SimpleOnGestureListener() { + override fun onDown(e: MotionEvent): Boolean { + saved.set(drawMatrix) + return true + } + + override fun onScroll(e1: MotionEvent?, e2: MotionEvent, dx: Float, dy: Float): Boolean { + drawMatrix.set(saved) + drawMatrix.postTranslate(-dx, -dy) + clamp() + invalidate() + return true + } + + override fun onDoubleTap(e: MotionEvent): Boolean { + val current = scale() + if (current > minScale * 1.2f) { + resetFit() + } else { + drawMatrix.postScale(2.5f / current, 2.5f / current, e.x, e.y) + clamp() + } + invalidate() + return true + } + + override fun onSingleTapConfirmed(e: MotionEvent): Boolean { + onTapClose() + return true + } + }, + ) + + fun setBitmap(bmp: Bitmap) { + bitmap = bmp + resetFit() + invalidate() + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val bmp = bitmap ?: return + canvas.drawBitmap(bmp, drawMatrix, null) + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + scaleDetector.onTouchEvent(event) + gestureDetector.onTouchEvent(event) + if (event.actionMasked == MotionEvent.ACTION_UP || + event.actionMasked == MotionEvent.ACTION_CANCEL + ) { + saved.set(drawMatrix) + } + return true + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + resetFit() + invalidate() + } + + private fun scale(): Float { + val values = FloatArray(9) + drawMatrix.getValues(values) + return values[Matrix.MSCALE_X] + } + + /** 初始按视图大小完整显示 */ + private fun resetFit() { + val bmp = bitmap ?: return + val w = width.toFloat() + val h = height.toFloat() + if (w <= 0 || h <= 0) return + drawMatrix.reset() + val scale = minOf(w / bmp.width, h / bmp.height) + drawMatrix.postScale(scale, scale, w / 2, h / 2) + drawMatrix.postTranslate(w / 2 - bmp.width * scale / 2, h / 2 - bmp.height * scale / 2) + minScale = scale * 0.8f + clamp() + } + + /** 缩放限制在 [minScale, maxScale],位移保证图片不会完全拖出屏幕 */ + private fun clamp() { + val bmp = bitmap ?: return + val values = FloatArray(9) + drawMatrix.getValues(values) + val s = values[Matrix.MSCALE_X].coerceIn(minScale, maxScale) + if (values[Matrix.MSCALE_X] != s) { + drawMatrix.setScale(s, s, width / 2f, height / 2f) + } + displayRect.set(0f, 0f, bmp.width.toFloat(), bmp.height.toFloat()) + drawMatrix.mapRect(displayRect) + var dx = 0f + var dy = 0f + if (displayRect.width() <= width) { + dx = width / 2f - displayRect.centerX() + } else { + if (displayRect.left > 0) dx = -displayRect.left + if (displayRect.right < width) dx = width - displayRect.right + } + if (displayRect.height() <= height) { + dy = height / 2f - displayRect.centerY() + } else { + if (displayRect.top > 0) dy = -displayRect.top + if (displayRect.bottom < height) dy = height - displayRect.bottom + } + if (dx != 0f || dy != 0f) drawMatrix.postTranslate(dx, dy) + } +} diff --git a/src/main/res/drawable-night/bg_icon_button.xml b/src/main/res/drawable-night/bg_icon_button.xml new file mode 100644 index 0000000..98300dc --- /dev/null +++ b/src/main/res/drawable-night/bg_icon_button.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/res/drawable/bg_brand_soft.xml b/src/main/res/drawable/bg_brand_soft.xml new file mode 100644 index 0000000..0e43055 --- /dev/null +++ b/src/main/res/drawable/bg_brand_soft.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/src/main/res/drawable/bg_button_ghost.xml b/src/main/res/drawable/bg_button_ghost.xml new file mode 100644 index 0000000..a96564e --- /dev/null +++ b/src/main/res/drawable/bg_button_ghost.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/bg_button_primary.xml b/src/main/res/drawable/bg_button_primary.xml new file mode 100644 index 0000000..c22a2a9 --- /dev/null +++ b/src/main/res/drawable/bg_button_primary.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/res/drawable/bg_button_primary_circle.xml b/src/main/res/drawable/bg_button_primary_circle.xml new file mode 100644 index 0000000..fba7aa1 --- /dev/null +++ b/src/main/res/drawable/bg_button_primary_circle.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/res/drawable/bg_card.xml b/src/main/res/drawable/bg_card.xml new file mode 100644 index 0000000..510cfd2 --- /dev/null +++ b/src/main/res/drawable/bg_card.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/src/main/res/drawable/bg_chip_off.xml b/src/main/res/drawable/bg_chip_off.xml new file mode 100644 index 0000000..e6e6b1f --- /dev/null +++ b/src/main/res/drawable/bg_chip_off.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/bg_chip_on.xml b/src/main/res/drawable/bg_chip_on.xml new file mode 100644 index 0000000..4929e94 --- /dev/null +++ b/src/main/res/drawable/bg_chip_on.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/src/main/res/drawable/bg_dropdown_input.xml b/src/main/res/drawable/bg_dropdown_input.xml new file mode 100644 index 0000000..5944078 --- /dev/null +++ b/src/main/res/drawable/bg_dropdown_input.xml @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/src/main/res/drawable/bg_field.xml b/src/main/res/drawable/bg_field.xml new file mode 100644 index 0000000..d1234e0 --- /dev/null +++ b/src/main/res/drawable/bg_field.xml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/src/main/res/drawable/bg_field_dropdown.xml b/src/main/res/drawable/bg_field_dropdown.xml new file mode 100644 index 0000000..0c98f36 --- /dev/null +++ b/src/main/res/drawable/bg_field_dropdown.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + diff --git a/src/main/res/drawable/bg_icon_button.xml b/src/main/res/drawable/bg_icon_button.xml new file mode 100644 index 0000000..94ac4c6 --- /dev/null +++ b/src/main/res/drawable/bg_icon_button.xml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/src/main/res/drawable/bg_input.xml b/src/main/res/drawable/bg_input.xml new file mode 100644 index 0000000..3f6b9eb --- /dev/null +++ b/src/main/res/drawable/bg_input.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/src/main/res/drawable/bg_nav_badge.xml b/src/main/res/drawable/bg_nav_badge.xml new file mode 100644 index 0000000..31f2be6 --- /dev/null +++ b/src/main/res/drawable/bg_nav_badge.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/src/main/res/drawable/bg_segment.xml b/src/main/res/drawable/bg_segment.xml new file mode 100644 index 0000000..5aa1a71 --- /dev/null +++ b/src/main/res/drawable/bg_segment.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/src/main/res/drawable/bg_segment_on.xml b/src/main/res/drawable/bg_segment_on.xml new file mode 100644 index 0000000..4450387 --- /dev/null +++ b/src/main/res/drawable/bg_segment_on.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/src/main/res/drawable/bg_status.xml b/src/main/res/drawable/bg_status.xml new file mode 100644 index 0000000..170d4cd --- /dev/null +++ b/src/main/res/drawable/bg_status.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/src/main/res/drawable/bg_thumb_close.xml b/src/main/res/drawable/bg_thumb_close.xml new file mode 100644 index 0000000..f300b9f --- /dev/null +++ b/src/main/res/drawable/bg_thumb_close.xml @@ -0,0 +1,5 @@ + + + + diff --git a/src/main/res/drawable/ic_add.xml b/src/main/res/drawable/ic_add.xml new file mode 100644 index 0000000..2bd72bb --- /dev/null +++ b/src/main/res/drawable/ic_add.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_alert.xml b/src/main/res/drawable/ic_alert.xml new file mode 100644 index 0000000..d513713 --- /dev/null +++ b/src/main/res/drawable/ic_alert.xml @@ -0,0 +1,10 @@ + + + + diff --git a/src/main/res/drawable/ic_article.xml b/src/main/res/drawable/ic_article.xml new file mode 100644 index 0000000..6626402 --- /dev/null +++ b/src/main/res/drawable/ic_article.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_back.xml b/src/main/res/drawable/ic_back.xml new file mode 100644 index 0000000..0ec8c49 --- /dev/null +++ b/src/main/res/drawable/ic_back.xml @@ -0,0 +1,13 @@ + + + + diff --git a/src/main/res/drawable/ic_check.xml b/src/main/res/drawable/ic_check.xml new file mode 100644 index 0000000..e25adf7 --- /dev/null +++ b/src/main/res/drawable/ic_check.xml @@ -0,0 +1,10 @@ + + + + diff --git a/src/main/res/drawable/ic_check_circle_off.xml b/src/main/res/drawable/ic_check_circle_off.xml new file mode 100644 index 0000000..f030b6b --- /dev/null +++ b/src/main/res/drawable/ic_check_circle_off.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/src/main/res/drawable/ic_check_circle_on.xml b/src/main/res/drawable/ic_check_circle_on.xml new file mode 100644 index 0000000..3ea0e06 --- /dev/null +++ b/src/main/res/drawable/ic_check_circle_on.xml @@ -0,0 +1,16 @@ + + + + + diff --git a/src/main/res/drawable/ic_chevron.xml b/src/main/res/drawable/ic_chevron.xml new file mode 100644 index 0000000..ec06dc2 --- /dev/null +++ b/src/main/res/drawable/ic_chevron.xml @@ -0,0 +1,13 @@ + + + + diff --git a/src/main/res/drawable/ic_disc.xml b/src/main/res/drawable/ic_disc.xml new file mode 100644 index 0000000..5cd28ac --- /dev/null +++ b/src/main/res/drawable/ic_disc.xml @@ -0,0 +1,25 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/ic_house.xml b/src/main/res/drawable/ic_house.xml new file mode 100644 index 0000000..48d84ef --- /dev/null +++ b/src/main/res/drawable/ic_house.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/drawable/ic_image.xml b/src/main/res/drawable/ic_image.xml new file mode 100644 index 0000000..3ac5545 --- /dev/null +++ b/src/main/res/drawable/ic_image.xml @@ -0,0 +1,10 @@ + + + + diff --git a/src/main/res/drawable/ic_launcher_background.xml b/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..221ec15 --- /dev/null +++ b/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,26 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/ic_mark.xml b/src/main/res/drawable/ic_mark.xml new file mode 100644 index 0000000..905ec90 --- /dev/null +++ b/src/main/res/drawable/ic_mark.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/drawable/ic_memo.xml b/src/main/res/drawable/ic_memo.xml new file mode 100644 index 0000000..2bee4f8 --- /dev/null +++ b/src/main/res/drawable/ic_memo.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_moon.xml b/src/main/res/drawable/ic_moon.xml new file mode 100644 index 0000000..c3ae934 --- /dev/null +++ b/src/main/res/drawable/ic_moon.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/src/main/res/drawable/ic_plane.xml b/src/main/res/drawable/ic_plane.xml new file mode 100644 index 0000000..a5f7e5f --- /dev/null +++ b/src/main/res/drawable/ic_plane.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + diff --git a/src/main/res/drawable/ic_reply.xml b/src/main/res/drawable/ic_reply.xml new file mode 100644 index 0000000..83b97b4 --- /dev/null +++ b/src/main/res/drawable/ic_reply.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_send.xml b/src/main/res/drawable/ic_send.xml new file mode 100644 index 0000000..83d9a37 --- /dev/null +++ b/src/main/res/drawable/ic_send.xml @@ -0,0 +1,10 @@ + + + + diff --git a/src/main/res/drawable/ic_settings.xml b/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..4f20fe6 --- /dev/null +++ b/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,10 @@ + + + + diff --git a/src/main/res/drawable/ic_sun.xml b/src/main/res/drawable/ic_sun.xml new file mode 100644 index 0000000..d24aa05 --- /dev/null +++ b/src/main/res/drawable/ic_sun.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/src/main/res/drawable/ic_trash.xml b/src/main/res/drawable/ic_trash.xml new file mode 100644 index 0000000..e759135 --- /dev/null +++ b/src/main/res/drawable/ic_trash.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/layout/activity_home.xml b/src/main/res/layout/activity_home.xml new file mode 100644 index 0000000..35d6eda --- /dev/null +++ b/src/main/res/layout/activity_home.xml @@ -0,0 +1,410 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_mail_detail.xml b/src/main/res/layout/activity_mail_detail.xml new file mode 100644 index 0000000..657b146 --- /dev/null +++ b/src/main/res/layout/activity_mail_detail.xml @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_main.xml b/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..e0af678 --- /dev/null +++ b/src/main/res/layout/activity_main.xml @@ -0,0 +1,535 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_reader.xml b/src/main/res/layout/activity_reader.xml new file mode 100644 index 0000000..74bba29 --- /dev/null +++ b/src/main/res/layout/activity_reader.xml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_settings.xml b/src/main/res/layout/activity_settings.xml new file mode 100644 index 0000000..2b65515 --- /dev/null +++ b/src/main/res/layout/activity_settings.xml @@ -0,0 +1,986 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/item_dropdown_center.xml b/src/main/res/layout/item_dropdown_center.xml new file mode 100644 index 0000000..2f13fd4 --- /dev/null +++ b/src/main/res/layout/item_dropdown_center.xml @@ -0,0 +1,14 @@ + + diff --git a/src/main/res/layout/item_feed.xml b/src/main/res/layout/item_feed.xml new file mode 100644 index 0000000..96ef5ca --- /dev/null +++ b/src/main/res/layout/item_feed.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/item_spinner.xml b/src/main/res/layout/item_spinner.xml new file mode 100644 index 0000000..bdb4b6d --- /dev/null +++ b/src/main/res/layout/item_spinner.xml @@ -0,0 +1,9 @@ + + diff --git a/src/main/res/layout/item_spinner_dropdown.xml b/src/main/res/layout/item_spinner_dropdown.xml new file mode 100644 index 0000000..c71c1f0 --- /dev/null +++ b/src/main/res/layout/item_spinner_dropdown.xml @@ -0,0 +1,13 @@ + + diff --git a/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..2c0ba5a --- /dev/null +++ b/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..2c0ba5a --- /dev/null +++ b/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/res/mipmap-anydpi/ic_launcher.xml b/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..3ea5a5c --- /dev/null +++ b/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..3ea5a5c --- /dev/null +++ b/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/values-night/colors.xml b/src/main/res/values-night/colors.xml new file mode 100644 index 0000000..42724d3 --- /dev/null +++ b/src/main/res/values-night/colors.xml @@ -0,0 +1,36 @@ + + + #D4814F + #B25F35 + #2ED4814F + #FFFFFF + + #E36B5E + #5BB98A + + #101215 + #191B1F + #22252A + #262A30 + + #EFEBE4 + + #FAF7F1 + #9C968C + #726D65 + + #2A2E34 + #22252A + #33383F + #1E2126 + #2B2F35 + + #33FFFFFF + #2EFFFFFF + #EDE7DB + #D3CABA + #D4814F + #E9A86E + #2C3138 + #191C21 + diff --git a/src/main/res/values-night/themes.xml b/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..8637f8b --- /dev/null +++ b/src/main/res/values-night/themes.xml @@ -0,0 +1,19 @@ + + + + diff --git a/src/main/res/values/colors.xml b/src/main/res/values/colors.xml new file mode 100644 index 0000000..ade1b24 --- /dev/null +++ b/src/main/res/values/colors.xml @@ -0,0 +1,52 @@ + + + + #B25F35 + #8E4726 + #1FB25F35 + #FFFFFF + + #C0392B + #2E7D51 + + + #F2F0EB + #FFFFFF + #F4F2ED + #EAE5DC + + + #1D1B18 + + #1D1B18 + #6E6960 + #9C968C + + #E7E2D9 + #F4F2ED + #DCD5C8 + #EAE7E0 + #FFFFFF + + #33FFFFFF + #14000000 + + + #5C93FF + #2F6BF0 + #1638B4 + #FFFFFF + #C9DBFB + + #EDE7DB + #D3CABA + #D4814F + #E9A86E + #2C3138 + #191C21 + diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml new file mode 100644 index 0000000..f2831f3 --- /dev/null +++ b/src/main/res/values/strings.xml @@ -0,0 +1,199 @@ + + + 石头厝 + 知识人间烟火 + + 设置 + 设置 + 返回 + 切换深浅色 + + 发文 + 发博 + + 标题,留空自动取正文前 20 字 + 在这里写点东西…\n想用语音就按输入法的语音键 + 此刻的想法… + + 发布 + 发布 + 添加图片 + + 分类 + 标签 + 逗号分隔,有联想可直接选 + + 私有 + 工作区 + 公开 + + 去设置 + 正在发布… + 上传中… + + 还没配置发文 + 填好网站地址、API Token 并选择作者,就能把文字发到自己的站点。 + 还没配置发博 + 填好 Memos 网站地址和 Access Token,就能随手记一笔,还能配图。 + + 发文 · Typecho + typecho v1.3 API + 发博 · Memos + Memos v0.18.2 API + AI · 润色 / 完善 + 润色完善AI接口 + AI + + 网站名称 + 如:三股水(列表里显示这个) + 网站地址 + https://www.example.com + API Token + 与插件设置里的 apiToken 一致 + 发布作者 + 点击选择管理员 + + 网站地址 + https://memos.example.com + Access Token + Memos「设置 → 访问令牌」里创建 + + 服务商 + API Key + 与 AIAssist 插件里填的 Key 相同 + 模型(可留空) + 留空用默认:deepseek-chat / glm-4-flash + + 测试链接 + 测试连接 + 测试中… + 保存 + 已保存 + + 1. 网站地址只填主域名,例如 https://www.example.com,不要带 /api 或 /index.php,多余部分会自动去掉。\n\n2. 分类在发文页选;标签直接新建或联想,新标签发布时自动建。发文提交后为「待审核」,需后台审核通过才公开。\n\n3. 发文配图走网页端「上传附件」接口,按正常模式走本地或第三方云存储,图片上传完成点缩略图以MD格式插到光标处。\n\n4. 润色 / 完善用 DeepSeek 或智谱接口,模型留空用默认;不满意可点「撤回」逐版回退。\n\n5. Memos Token 在「设置 → 访问令牌」创建或复制已有,至少勾 memos:write 和 resource:write。 + + 正文为空,无法发布 + 内容和图片都是空的,无法发布 + 发布成功 + 已提交,等待审核 + 已提交,等待审核 · %1$s + 已发布 · %1$s + 分类/标签加载失败:%1$s + + 上传图片 %1$d/%2$d… + 已上传 %1$d 张,点缩略图把图片插到正文 + 有 %1$d 张没传上去:%2$s + 先把发文配置填好,才能上传图片 + 最多 %1$d 张图片 + 这张图没有拿到地址,删掉重传一次 + 还有图片没插进正文 + 已上传 %1$d 张图片,但正文里没有对应的 ![](地址),直接发布这些图不会出现。点缩略图可以插到光标处。 + 返回插入 + 继续发布 + + 润色 + 完善 + 撤回 + 润色中,正在改错别字和病句… + 完善中,正在补充扩写… + 已润色,不满意可以点撤回 + 已完善,不满意可以点撤回 + AI 出错:%1$s + 还没填 AI Key,去设置里填一下 + 内容超过 %1$d 字,分段处理更稳 + 没有可撤回的版本 + 已撤回上一次修改 + 已撤回上一次修改,没有更早的版本了 + + + 信息 + 发布 + 邮件 + 发布文章 + 发布微博 + 信息 + 文章 + 动态 + 全部 + 未读 + 已读 + 搜索标题、来源或内容… + 这里还没有内容 + 先到设置里填 RSS 站点地址和授权码 + 先到设置里填发文配置 + 先到设置里填 Memos 配置 + 先到设置里填邮箱和 IMAP 授权码 + 配置正常,所有邮箱最近 %1$d 天都没有邮件;可在设置里调大同步天数 + 全部邮箱 + 加载中… + 没有更多了 + 查看原文 + 标为已读 + 标为未读 + 已标为已读 + + + 选择 + 取消 + 完成 + 全选 + 取消全选 + 设为已读 + 删除 + 已选 %1$d 项 + 删除 %1$d 项 + 邮件会从邮箱服务器一起删除,删除后无法恢复。确定继续? + 这些条目会从列表中永久隐藏,之后不再显示。确定继续? + 已删除 %1$d 项 + 有 %1$d 项删除失败:%2$s + 已标为已读 + 选中的都已经是已读了 + 点卡片可多选,长按也能进入选择 + 阅读 + 无标题 + 邮件详情 + 回复 + 删除 + 发件人 + 收件人 + 时间 + 附件 + 这封邮件没有正文 + 标记已读失败:%1$s + + + 信息 · RSS + 站点 RssUnion 接口 + RSS + RSS 站点地址 + https://www.example.com + 授权码 + ruo_ 开头的站点授权码 + 每页条数 + 测试 RSS + + 邮件 · IMAP + 直连邮箱,授权码登录 + 邮件 + 邮箱名称 + 如:QQ邮箱(列表里显示这个) + 邮箱地址 + name@example.com + 授权码 + 邮箱设置里生成的 IMAP 授权码 + IMAP 主机 + 留空自动识别,或点右侧预设 + 预设 + 自定义(手动输入) + 端口 + 993 + SSL + 拉取天数 + 30 + 测试邮箱 + + 1. 网站地址只填主域名,例如 https://www.example.com,不要带 /api 或 /index.php,多余部分会自动去掉。\n\n2. 分类在发文页选;标签直接新建或联想,新标签发布时自动建。发文提交后为「待审核」,需后台审核通过才公开。\n\n3. 发文配图走网页端「上传附件」接口,按正常模式走本地或第三方云存储,图片上传完成点缩略图以MD格式插到光标处。\n\n4. 润色 / 完善用 DeepSeek 或智谱接口,模型留空用默认;不满意可点「撤回」逐版回退。\n\n5. Memos Token 在「设置 → 访问令牌」创建或复制已有,至少勾 memos:write 和 resource:write。\n\n6. RSS 填你站点的 RssUnion 地址和 ruo_ 授权码;邮件填邮箱、IMAP 授权码与服务器(服务器可留空,按邮箱域名自动识别;QQ 为 imap.qq.com、126 为 imap.126.com,端口 993 + SSL)。 + 图片加载失败,点击重试 + 关闭 + ✕ + diff --git a/src/main/res/values/themes.xml b/src/main/res/values/themes.xml new file mode 100644 index 0000000..b14ebf4 --- /dev/null +++ b/src/main/res/values/themes.xml @@ -0,0 +1,19 @@ + + + +