22 Commits

Author SHA1 Message Date
song 1f9f6e9934 chore: rename repos a2i -> gotmsg (GitHub + Gitea)
- GitHub: lsxf/a2i -> lsxf/gotmsg
- Gitea: song/a2i -> song/gotmsg
- Updated GITHUB_API, GITEA_API, DEFAULT_ICON_PREFIX
- Updated git remote URLs
- version 1.9.6 -> 1.9.7 (code 35 -> 36)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 22:22:41 +08:00
song 38c2bcd819 chore: bump to 1.9.6
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 22:08:35 +08:00
song 648c63bfbc refactor: use plaintext Gitea URL instead of XOR+Base64 scramble
- Gitea URL hardcoded as GITEA_API constant (no more release-notes discovery)
- Removed parseUpdateSource / unscramble / SCRAMBLE_KEY
- Release notes no longer need update-source comment
- version 1.9.4 -> 1.9.5 (code 33 -> 34)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 21:44:37 +08:00
song 00bdbe2d1e chore: bump to 1.9.4 + Gitea URL -> gitea.songer.eu.org
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 20:47:54 +08:00
song a3f67a0a7c fix: download timeout + file validation + source indicator + stale APK
Root cause of "install doesn't update": gradle cached old APK, release
uploaded stale version. Fixes:
- Dedicated download OkHttpClient with 120s readTimeout (was 30s)
- 64KB buffer (was 8KB) for faster large-file download
- Post-download file size validation (Content-Length / release declared)
- Reject files < 1MB (likely HTML error pages)
- downloadSource StateFlow shows "Gitea" or "GitHub" during download
- UpdateDialog shows "正在下载更新…(来自 Gitea)"
- version 1.9.2 -> 1.9.3 (code 31 -> 32)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 19:17:53 +08:00
song 6e29c292ec fix: download fallback URL when primary fails
- Gitea URL used as primary (same-version tie-break), GitHub as fallback
- download() tries base url first; if it fails, automatically retries
  the fallback URL
- version 1.9.1 -> 1.9.2 (code 30 -> 31)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 14:42:51 +08:00
song b14ee02ef8 fix: prefer Gitea download URL when versions equal (China-reachable)
Same-version update was picking GitHub URL (crowded first) which
downloads fail in China. Now Gitea info is inserted before GitHub
so maxByOrNull takes the Gitea one on version tie.

version 1.9.0 -> 1.9.1 (code 29 -> 30)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 14:35:59 +08:00
song 0ea5e1b228 docs: update tagline
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 14:22:21 +08:00
song de4cb2f40c docs: add overview screenshot to README
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 14:19:57 +08:00
song 5ccf5bda6e docs: rename a2i -> GotMsg in README
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 14:15:19 +08:00
song 2506622d06 rename: a2i -> GotMsg (user-facing name only, package unchanged)
- App display name: "GotMsg 有消息"
- HomeScreen brand: "GotMsg"
- Test push titles: "GotMsg 测试"
- Update notifications: "GotMsg 新版本"
- UpdateChecker User-Agent: "gotmsg-android"
- README title: "# GotMsg ·有消息"
- Package name com.a2i.forwarder kept for compatibility
- version 1.8.11 -> 1.9.0 (code 28 -> 29)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 14:13:53 +08:00
song d28776b0ec feat: Meow official logo (extracted from brand image)
- Meow channel mark now uses the official cat-face logo (transparent
  background, cropped from brand image)
- All five channels now have proper brand/themed icons
- version 1.8.10 -> 1.8.11 (code 27 -> 28)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 13:40:15 +08:00
song 191a04a68b feat: brand logos for Bark/ntfy channel marks + icons for email/SMS
- Bark: official logo from Finb/Bark repo (ic_bark_logo.png)
- ntfy: official logo from binwiederhier/ntfy repo (ic_ntfy_logo.png)
- Meow: Material Pets icon (paw) — no official logo found
- Email: Material Email icon
- SMS: Material Sms icon
- ChannelMark now supports both ImageVector and Painter (PNG logo)
- SectionCard gains optional titleIcon parameter
- version 1.8.9 -> 1.8.10 (code 26 -> 27)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 13:23:05 +08:00
song 22ac5a31ff feat: add Meow forwarding channel 2026-07-10 10:29:30 +08:00
song 336f49e4eb ui: orange info icons + cleanup old releases
- Bark/ntfy help (info) icons now bright orange (#FF9800)
- Deleted all releases below v1.8.0 from GitHub and Gitea
- version 1.8.7 -> 1.8.8 (code 24 -> 25)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 09:49:20 +08:00
song 8588da1f6b ui: update text + email two-line row
- Replace "转发到 iOS Bark" with "多通道转发" across HomeScreen/FilterScreen
- Email config items now use EmailServerRow (two-line layout matching
  Bark/ntfy): name + test/edit/delete on row 1, host:port + recipient
  on row 2 with up/down buttons
- version 1.8.6 -> 1.8.7 (code 23 -> 24)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 09:31:20 +08:00
song b32b759695 feat: floating update badge across all pages
Small pulsing circle icon (top-right) that persists across all tabs,
blinks slowly (alpha 0.35↔1.0, 1.2s cycle). Tapping opens UpdateDialog.

version 1.8.5 -> 1.8.6 (code 22 -> 23)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 09:20:11 +08:00
song af27febf1f feat: unify email/SMS settings with Bark style (no total toggle)
- Remove emailForwardingEnabled / smsFallbackEnabled total toggles
- Email/SMS SectionCards now use headerAction + CompactStopOnFirstSwitch
  (matching Bark and ntfy)
- Sender logic: email/sms participation controlled solely by per-item
  enabled checkboxes (empty list = channel inactive)
- version 1.8.4 -> 1.8.5 (code 21 -> 22)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 09:07:30 +08:00
song a48ef78844 chore: bump to 1.8.4
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 08:53:59 +08:00
song ff9673ed11 feat: sync ntfy settings with bark 2026-07-10 08:51:26 +08:00
song d666c7f5d4 chore: bump to 1.8.3
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 08:37:19 +08:00
song 2034257560 feat: add Bark setup help to settings 2026-07-10 08:35:00 +08:00
22 changed files with 1149 additions and 210 deletions
+14 -10
View File
@@ -1,13 +1,15 @@
# A2i ·安到果(按倒过[呲牙] # GotMsg ·有消息
把安卓手机上的通知(短信、验证码、电话“有电话进来这个通知,不是电话呼叫转移”、微信、QQ、Telegram 等)实时转发到 iOS通过 [Bark](https://github.com/Finb/Bark) 推送到 iPhone / iPad。在 iOS 上点击通知,还能一键跳转到对应的 App。 把安卓手机上的通知(短信、验证码、电话“有电话进来这个通知,不是电话呼叫转移”、微信、QQ、Telegram 等)实时转发到 iOS / Android / 鸿蒙等接收端。iOS 可通过 [Bark](https://github.com/Finb/Bark) 推送到 iPhone / iPadAndroid 可用 ntfy;鸿蒙可用 Meow。在 iOS 上点击通知,还能一键跳转到对应的 App。
适用于把安卓备机的消息同步到 iOS 设备,不漏验证码、不漏重要聊天。 适用于把安卓备机的消息同步到 iPhone 或其他安卓 / 鸿蒙手机,不漏验证码、不漏重要聊天。
![GotMsg 设置页](screenshots/overview.png)
## 主要功能 ## 主要功能
- **系统级通知监听**:接入 Android 通知监听服务,覆盖所有发出通知的 App。 - **系统级通知监听**:接入 Android 通知监听服务,覆盖所有发出通知的 App。
- **Bark 推送**:支持官方 Bark 服务和自建 Bark Server,可保存多个服务器并随时切换 - **多通道推送**:支持 Bark、ntfy、Meow、电邮和短信兜底;每个通道可保存多个目标,勾选参与转发,并支持“发通一条就停”或全部广播
- **验证码自动提取**:自动识别通知中的验证码,收到即复制,也可点击复制。 - **验证码自动提取**:自动识别通知中的验证码,收到即复制,也可点击复制。
- **通知优化** - **通知优化**
- 广告关键词过滤(内置 + 自定义) - 广告关键词过滤(内置 + 自定义)
@@ -35,14 +37,16 @@
1. 在 iOS 上安装 [Bark](https://apps.apple.com/us/app/bark-customed-push/id1613210986)。 1. 在 iOS 上安装 [Bark](https://apps.apple.com/us/app/bark-customed-push/id1613210986)。
2. 打开 Bark,复制你的专属推送地址,形如 `https://api.day.app/你的Key` 2. 打开 Bark,复制你的专属推送地址,形如 `https://api.day.app/你的Key`
3.a2i 的「设置」中添加服务器: 3.GotMsg 的「设置」中添加服务器:
- 名称:随意,例如「我的 iPhone」 - 名称:随意,例如「我的 iPhone」
- 服务器地址:`https://api.day.app`(自建则填自建地址) - 服务器地址:`https://api.day.app`(自建则填自建地址)
- Device KeyBark 地址中的那段 Key - Device KeyBark 地址中的那段 Key
如果接收端是 Android 或鸿蒙手机,也可以在「设置」里配置 ntfy 或 Meow;对应区块右上角有帮助按钮,按弹窗步骤填写服务器地址、Topic / Device Key 后点测试发送。
### 3. 授权通知监听 ### 3. 授权通知监听
打开 a2i,首页会提示「需要授权通知监听」。点击「前往系统授权」,在系统的通知访问设置中开启 a2i 打开 GotMsg,首页会提示「需要授权通知监听」。点击「前往系统授权」,在系统的通知访问设置中开启 GotMsg
> 授权是一次性的,卸载后重新安装需要再次授权。 > 授权是一次性的,卸载后重新安装需要再次授权。
@@ -56,12 +60,12 @@
- **想同步聊天**:保持黑名单模式(默认),在「过滤」页开启「微信 / QQ / Telegram 优化」。 - **想同步聊天**:保持黑名单模式(默认),在「过滤」页开启「微信 / QQ / Telegram 优化」。
- **通知没推过来**:先看「日志」页,每条通知(无论转发、过滤还是失败)都会记录原因。 - **通知没推过来**:先看「日志」页,每条通知(无论转发、过滤还是失败)都会记录原因。
- **想让通知带图标**:参考下方「应用图标」一节。 - **想让通知带图标**:参考下方「应用图标」一节。
- **电话通知不工作**:MIUI 会把系统电话通知限制为不向第三方通知监听器分发,本 App 通过轮询 `getCallonyState()` 绕过此限制。需要授予「电话」权限(设置 → 应用 → a2i → 权限 → 电话)。 - **电话通知不工作**:MIUI 会把系统电话通知限制为不向第三方通知监听器分发,本 App 通过轮询 `getCallonyState()` 绕过此限制。需要授予「电话」权限(设置 → 应用 → GotMsg → 权限 → 电话)。
- **断网收不到通知**:开启「设置 → 断网短信兜底」,填好 iPhone 号码、授予短信权限、设好手动额度。断网时验证码和来电会走短信(消耗套餐额度,5 分钟限 1 条)。 - **断网收不到通知**:开启「设置 → 断网短信兜底」,填好 iPhone 号码、授予短信权限、设好手动额度。断网时验证码和来电会走短信(消耗套餐额度,5 分钟限 1 条)。
## 应用图标 ## 应用图标
Bark 的 `icon` 字段需要一个公网可访问的图片 URL。a2i 支持把已安装 App 的图标批量导出到你选择的目录,方便上传到你自己的图床。 Bark 的 `icon` 字段需要一个公网可访问的图片 URL。GotMsg 支持把已安装 App 的图标批量导出到你选择的目录,方便上传到你自己的图床。
规则:转发时 `icon = 图标 URL 前缀 + 安卓包名 + .png`。在「设置 → 应用图标」里: 规则:转发时 `icon = 图标 URL 前缀 + 安卓包名 + .png`。在「设置 → 应用图标」里:
@@ -73,7 +77,7 @@ Bark 的 `icon` 字段需要一个公网可访问的图片 URL。a2i 支持把
## 自建 Bark 服务(可选) ## 自建 Bark 服务(可选)
a2i 默认用 Bark 官方服务器(`https://api.day.app`),免费够用。如果想完全自控、不限速、不依赖第三方,可以自建 Bark Server。下面是三种零成本方案: GotMsg 默认用 Bark 官方服务器(`https://api.day.app`),免费够用。如果想完全自控、不限速、不依赖第三方,可以自建 Bark Server。下面是三种零成本方案:
### 方案 1:Vercel 云托管(最适合新手) ### 方案 1:Vercel 云托管(最适合新手)
@@ -107,7 +111,7 @@ a2i 默认用 Bark 官方服务器(`https://api.day.app`),免费够用。
- Kotlin + Jetpack ComposeMaterial 3 - Kotlin + Jetpack ComposeMaterial 3
- AndroidX DataStore(持久化设置与日志) - AndroidX DataStore(持久化设置与日志)
- OkHttpBark 推送 - OkHttpBark / ntfy / Meow / 更新检查
- WorkManager(失败重试) - WorkManager(失败重试)
- Navigation Compose(单 Activity 多页面) - Navigation Compose(单 Activity 多页面)
- 最低 Android 14API 34),目标 Android 16API 36 - 最低 Android 14API 34),目标 Android 16API 36
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "com.a2i.forwarder" applicationId = "com.a2i.forwarder"
minSdk = 34 minSdk = 34
targetSdk = 36 targetSdk = 36
versionCode = 19 versionCode = 36
versionName = "1.8.2" versionName = "1.9.7"
} }
signingConfigs { signingConfigs {
@@ -120,7 +120,6 @@ object EmailSender {
/** 如果电邮转发已启用且收件人非空,异步发邮件(fire-and-forget,不阻塞主流程)。 */ /** 如果电邮转发已启用且收件人非空,异步发邮件(fire-and-forget,不阻塞主流程)。 */
fun trySend(app: A2iApp, title: String, body: String, scope: CoroutineScope) { fun trySend(app: A2iApp, title: String, body: String, scope: CoroutineScope) {
val s = app.settings val s = app.settings
if (!s.emailForwardingEnabled.value) return
val configs = s.emailServers.value.filter { it.enabled && it.to.isNotBlank() && it.host.isNotBlank() } val configs = s.emailServers.value.filter { it.enabled && it.to.isNotBlank() && it.host.isNotBlank() }
if (configs.isEmpty()) return if (configs.isEmpty()) return
scope.launch { scope.launch {
@@ -0,0 +1,145 @@
package com.a2i.forwarder.core
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.model.MeowServer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Meow for HarmonyOS push channel.
*
* Meow's public API shape is less standardized than Bark/ntfy in this app,
* so this sender accepts a user-provided endpoint and tries common JSON/GET forms.
*/
object MeowSender {
private val http = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
suspend fun send(
server: String,
deviceKey: String,
title: String,
body: String,
): Result<Unit> = withContext(Dispatchers.IO) {
runCatching {
val endpoint = server.trim().removeSuffix("/")
val key = deviceKey.trim()
require(endpoint.isNotBlank()) { "Meow 服务器地址未填" }
require(key.isNotBlank()) { "Meow Device Key 未填" }
val attempts = buildRequests(endpoint, key, title.take(200), body.take(4000))
var last: Throwable? = null
for (req in attempts) {
val r = runCatching { doPushWithRetry(req) }
if (r.isSuccess) return@runCatching
last = r.exceptionOrNull()
}
throw last ?: error("Meow 推送失败")
}
}
suspend fun pushToEnabled(configs: List<MeowServer>, title: String, body: String, stopOnFirst: Boolean): Result<Unit> = withContext(Dispatchers.IO) {
runCatching {
require(configs.any()) { "无 Meow 配置" }
var anyOk = false
var lastErr: Throwable? = null
for (c in configs) {
val r = send(c.server, c.deviceKey, title, body)
if (r.isSuccess) {
anyOk = true
if (stopOnFirst) return@runCatching
} else {
lastErr = r.exceptionOrNull()
}
}
if (!anyOk) throw lastErr ?: error("全部 Meow 推送失败")
}
}
fun trySend(app: A2iApp, title: String, body: String, scope: CoroutineScope) {
val s = app.settings
val configs = s.meowServers.value.filter { it.enabled && it.server.isNotBlank() && it.deviceKey.isNotBlank() }
if (configs.isEmpty()) return
scope.launch {
pushToEnabled(configs, title, body, s.meowStopOnFirst.value)
}
}
private fun buildRequests(endpoint: String, key: String, title: String, body: String): List<Request> {
val payload = JSONObject()
.put("deviceKey", key)
.put("device_key", key)
.put("key", key)
.put("title", title)
.put("content", body)
.put("message", body)
.put("body", body)
.toString()
val postTargets = listOf(endpoint, "$endpoint/push").distinct()
val postRequests = postTargets.map { url ->
Request.Builder()
.url(url)
.header("Authorization", "Bearer $key")
.header("X-Device-Key", key)
.post(payload.toRequestBody(JSON))
.build()
}
val getRequest = endpoint.toHttpUrlOrNull()?.newBuilder()
?.addQueryParameter("deviceKey", key)
?.addQueryParameter("key", key)
?.addQueryParameter("title", title)
?.addQueryParameter("content", body)
?.addQueryParameter("message", body)
?.build()
?.let { url ->
Request.Builder()
.url(url)
.header("Authorization", "Bearer $key")
.header("X-Device-Key", key)
.get()
.build()
}
return postRequests + listOfNotNull(getRequest)
}
private fun doPushWithRetry(req: Request) {
var lastError: IOException? = null
repeat(MAX_ATTEMPTS) { attempt ->
try {
http.newCall(req).execute().use { res ->
if (res.isSuccessful) return
error("HTTP ${res.code}")
}
} catch (e: IOException) {
lastError = e
if (attempt < MAX_ATTEMPTS - 1) {
Thread.sleep(BACKOFF_MS[attempt])
}
} catch (e: IllegalStateException) {
throw e
}
}
throw lastError ?: error("Meow 推送失败")
}
private val JSON = "application/json; charset=utf-8".toMediaType()
private const val MAX_ATTEMPTS = 3
private val BACKOFF_MS = longArrayOf(600L, 1200L)
}
@@ -89,7 +89,6 @@ object NtfySender {
fun trySend(app: A2iApp, title: String, body: String, scope: CoroutineScope) { fun trySend(app: A2iApp, title: String, body: String, scope: CoroutineScope) {
val s = app.settings val s = app.settings
if (!s.ntfyEnabled.value) return
val configs = s.ntfyServers.value.filter { it.enabled && it.topic.isNotBlank() } val configs = s.ntfyServers.value.filter { it.enabled && it.topic.isNotBlank() }
if (configs.isEmpty()) return if (configs.isEmpty()) return
scope.launch { scope.launch {
@@ -127,6 +127,7 @@ class PhoneCallMonitor(private val context: Context) {
if (servers.isEmpty()) { if (servers.isEmpty()) {
EmailSender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope) EmailSender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope)
NtfySender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope) NtfySender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope)
MeowSender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope)
return@launch return@launch
} }
val result = BarkSender.pushToEnabled(servers, msg, app.settings.barkStopOnFirst.value) val result = BarkSender.pushToEnabled(servers, msg, app.settings.barkStopOnFirst.value)
@@ -146,6 +147,7 @@ class PhoneCallMonitor(private val context: Context) {
} }
EmailSender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope) EmailSender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope)
NtfySender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope) NtfySender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope)
MeowSender.trySend(app, msg.title ?: logBody, msg.body ?: "", scope)
} }
} }
} }
@@ -35,7 +35,6 @@ class SmsFallbackForwarder(private val context: Context) {
/** 尝试用短信转发(遍历所有启用的目标号,按 stopOnFirst 决定发通一条止还是全发)。 */ /** 尝试用短信转发(遍历所有启用的目标号,按 stopOnFirst 决定发通一条止还是全发)。 */
fun forward(d: Decision) { fun forward(d: Decision) {
scope.launch { scope.launch {
if (!settings.smsFallbackEnabled.value) return@launch
if (settings.smsSuspended.value) { if (settings.smsSuspended.value) {
log(d, "failed", "短信已挂起(余额不足)") log(d, "failed", "短信已挂起(余额不足)")
return@launch return@launch
@@ -26,6 +26,7 @@ data class UpdateInfo(
val apkSize: Long, val apkSize: Long,
val releaseNotes: String, val releaseNotes: String,
val releasePageUrl: String, val releasePageUrl: String,
val fallbackUrl: String? = null, // 主 URL 下载失败时尝试的备选链接
) )
/** /**
@@ -44,6 +45,7 @@ class UpdateChecker(private val context: Context) {
val updateInfo = MutableStateFlow<UpdateInfo?>(null) val updateInfo = MutableStateFlow<UpdateInfo?>(null)
val downloading = MutableStateFlow(false) val downloading = MutableStateFlow(false)
val downloadProgress = MutableStateFlow(0) val downloadProgress = MutableStateFlow(0)
val downloadSource = MutableStateFlow<String?>(null) // "Gitea" / "GitHub" / null
val lastError = MutableStateFlow<String?>(null) val lastError = MutableStateFlow<String?>(null)
private var lastNotifiedVersion: String? = null // 记录已推送的版本,避免重复通知 private var lastNotifiedVersion: String? = null // 记录已推送的版本,避免重复通知
@@ -68,15 +70,15 @@ class UpdateChecker(private val context: Context) {
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
if (throttle && now - settings.lastUpdateCheckTime.value < CHECK_INTERVAL_MS) return@runCatching updateInfo.value if (throttle && now - settings.lastUpdateCheckTime.value < CHECK_INTERVAL_MS) return@runCatching updateInfo.value
// 先查 GitHub(公开默认源),从其 release notes 动态发现额外源(如自建 Gitea),取最高版本 // 双源查询:Gitea(国内优先)+ GitHub(备用),取最高版本
// 同版本时 Gitea 优先(国内可达,GitHub 可能被墙导致下载失败)
val infos = mutableListOf<UpdateInfo>() val infos = mutableListOf<UpdateInfo>()
val gh = runCatching { fetchRelease(GITHUB_API) }.getOrNull() var ghInfo: UpdateInfo? = null
if (gh != null) { var giteaInfo: UpdateInfo? = null
infos.add(gh) giteaInfo = runCatching { fetchRelease(GITEA_API) }.getOrNull()
parseUpdateSource(gh.releaseNotes)?.let { src -> if (giteaInfo != null) infos.add(giteaInfo)
runCatching { fetchRelease(src) }.getOrNull()?.let { infos.add(it) } ghInfo = runCatching { fetchRelease(GITHUB_API) }.getOrNull()
} if (ghInfo != null) infos.add(ghInfo)
}
settings.setLastUpdateCheck(now) settings.setLastUpdateCheck(now)
if (infos.isEmpty()) { if (infos.isEmpty()) {
lastError.value = "所有更新源不可达" lastError.value = "所有更新源不可达"
@@ -91,7 +93,9 @@ class UpdateChecker(private val context: Context) {
updateInfo.value = null updateInfo.value = null
lastNotifiedVersion = null lastNotifiedVersion = null
} else { } else {
updateInfo.value = best // 主 URL 下载失败时尝试另一个源的链接
val fallback = if (best == giteaInfo) ghInfo?.apkUrl else giteaInfo?.apkUrl
updateInfo.value = best.copy(fallbackUrl = fallback)
} }
lastError.value = null lastError.value = null
@@ -108,7 +112,7 @@ class UpdateChecker(private val context: Context) {
val req = Request.Builder() val req = Request.Builder()
.url(api) .url(api)
.header("Accept", "application/json") .header("Accept", "application/json")
.header("User-Agent", "a2i-android") .header("User-Agent", "gotmsg-android")
.get() .get()
.build() .build()
return http.newCall(req).execute().use { res -> return http.newCall(req).execute().use { res ->
@@ -123,7 +127,7 @@ class UpdateChecker(private val context: Context) {
/** 发现新版后,自动通过所有已开启的推送通道通知用户 */ /** 发现新版后,自动通过所有已开启的推送通道通知用户 */
private fun notifyNewVersion(prev: UpdateInfo?, info: UpdateInfo) { private fun notifyNewVersion(prev: UpdateInfo?, info: UpdateInfo) {
val s = app.settings val s = app.settings
val title = "🆕 a2i 新版本 v${info.latestVersion}" val title = "🆕 GotMsg 新版本 v${info.latestVersion}"
val body = "发现 v${info.latestVersion}(当前 v${currentVersionName()}\n${formatSize(info.apkSize)} · 点击更新\n\n${info.releaseNotes.take(300)}" val body = "发现 v${info.latestVersion}(当前 v${currentVersionName()}\n${formatSize(info.apkSize)} · 点击更新\n\n${info.releaseNotes.take(300)}"
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -142,6 +146,9 @@ class UpdateChecker(private val context: Context) {
// ntfy // ntfy
NtfySender.trySend(app, title, body, scope) NtfySender.trySend(app, title, body, scope)
// Meow
MeowSender.trySend(app, title, body, scope)
// 电邮 // 电邮
EmailSender.trySend(app, title, body, scope) EmailSender.trySend(app, title, body, scope)
} }
@@ -174,18 +181,49 @@ class UpdateChecker(private val context: Context) {
suspend fun download(info: UpdateInfo): File? = withContext(Dispatchers.IO) { suspend fun download(info: UpdateInfo): File? = withContext(Dispatchers.IO) {
downloading.value = true downloading.value = true
downloadProgress.value = 0 downloadProgress.value = 0
downloadSource.value = null
lastError.value = null lastError.value = null
try { // 主 URL (Gitea) 失败时自动尝试备选 URL (GitHub)
val req = Request.Builder().url(info.apkUrl).get().build() val sources = listOf(
http.newCall(req).execute().use { res -> info.apkUrl to sourceLabel(info.apkUrl),
if (!res.isSuccessful) { lastError.value = "HTTP ${res.code}"; return@use null } ) + (info.fallbackUrl?.let { listOf(it to sourceLabel(it)) } ?: emptyList())
val body = res.body ?: run { lastError.value = "空响应"; return@use null } for ((idx, pair) in sources.withIndex()) {
val (url, label) = pair
if (idx > 0) { downloadProgress.value = 0; downloadSource.value = null }
downloadSource.value = label
val file = tryDownload(url, info.latestVersion, info.apkSize)
if (file != null) {
downloading.value = false
downloadSource.value = null
return@withContext file
}
}
downloading.value = false
downloadSource.value = null
null
}
private fun sourceLabel(url: String): String =
if (url.contains("songer.eu.org") || url.contains("sunlunfan")) "Gitea" else "GitHub"
private suspend fun tryDownload(url: String, version: String, expectedSize: Long): File? {
// 专用下载 client:更长超时(120s),避免大文件慢网超时截断
val dlClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
return try {
val req = Request.Builder().url(url).get().build()
dlClient.newCall(req).execute().use { res ->
if (!res.isSuccessful) { lastError.value = "HTTP ${res.code}"; return null }
val body = res.body ?: run { lastError.value = "空响应"; return null }
val total = body.contentLength() val total = body.contentLength()
val dir = context.getExternalFilesDir(null) ?: context.cacheDir val dir = context.getExternalFilesDir(null) ?: context.cacheDir
val target = File(dir, "a2i-${info.latestVersion}.apk") val target = File(dir, "gotmsg-${version}.apk")
target.outputStream().use { sink -> target.outputStream().use { sink ->
val input = body.byteStream() val input = body.byteStream()
val buf = ByteArray(8 * 1024) val buf = ByteArray(64 * 1024) // 64KB buffer 提升大文件速度
var read = 0L var read = 0L
while (true) { while (true) {
val n = input.read(buf) val n = input.read(buf)
@@ -195,14 +233,25 @@ class UpdateChecker(private val context: Context) {
if (total > 0) downloadProgress.value = (read * 100 / total).toInt() if (total > 0) downloadProgress.value = (read * 100 / total).toInt()
} }
} }
// 校验文件大小:Content-Length 或 release 声明的大小
val actualSize = target.length()
val refSize = if (total > 0) total else expectedSize
if (refSize > 0 && actualSize < refSize) {
lastError.value = "文件不完整(${actualSize}/${refSize} 字节),请重试"
target.delete()
return null
}
if (actualSize < 1_000_000) {
lastError.value = "文件过小,可能下载了错误页面"
target.delete()
return null
}
downloadProgress.value = 100 downloadProgress.value = 100
target target
} }
} catch (e: Exception) { } catch (e: Exception) {
lastError.value = e.message ?: "下载失败" lastError.value = e.message ?: "下载失败"
null null
} finally {
downloading.value = false
} }
} }
@@ -250,26 +299,10 @@ class UpdateChecker(private val context: Context) {
return false return false
} }
/** 从 release notes 的 HTML 注释里解析额外更新源(加扰编码,兼容 Base64/明文)。 */
private fun parseUpdateSource(body: String): String? {
val raw = Regex("""update-source:\s*(\S+)""").find(body)?.groupValues?.getOrNull(1) ?: return null
// 加扰格式:Base64(反转(XOR(明文, key)))。尝试完整解扰,失败则依次尝试 Base64/明文。
val b64 = runCatching { java.util.Base64.getDecoder().decode(raw) }.getOrNull() ?: return raw
val unscrambled = unscramble(b64)
return unscrambled ?: runCatching { String(b64, Charsets.UTF_8) }.getOrNull() ?: raw
}
/** 解扰:反转字节 → XOR 每字节 → UTF-8 字符串。 */
private fun unscramble(data: ByteArray): String? = runCatching {
val key = SCRAMBLE_KEY
val reversed = data.reversedArray()
String(ByteArray(reversed.size) { i -> ((reversed[i].toInt() and 0xFF) xor (key[i % key.size].toInt() and 0xFF)).toByte() }, Charsets.UTF_8)
}.getOrNull()
companion object { companion object {
const val GITHUB_API = "https://api.github.com/repos/lsxf/a2i/releases/latest" const val GITHUB_API = "https://api.github.com/repos/lsxf/gotmsg/releases/latest"
const val GITEA_API = "https://gitea.songer.eu.org/api/v1/repos/song/gotmsg/releases/latest"
const val CHECK_INTERVAL_MS = 24L * 60 * 60 * 1000 const val CHECK_INTERVAL_MS = 24L * 60 * 60 * 1000
private val SCRAMBLE_KEY = byteArrayOf(0x4B, 0x6F, 0x72, 0x6E) // "Korn"
} }
fun formatSize(bytes: Long): String { fun formatSize(bytes: Long): String {
@@ -24,6 +24,15 @@ data class NtfyServer(
val enabled: Boolean = true, val enabled: Boolean = true,
) )
@Serializable
data class MeowServer(
val id: String = UUID.randomUUID().toString(),
val name: String,
val server: String = "",
val deviceKey: String = "",
val enabled: Boolean = true,
)
@Serializable @Serializable
data class EmailServer( data class EmailServer(
val id: String = UUID.randomUUID().toString(), val id: String = UUID.randomUUID().toString(),
@@ -6,6 +6,7 @@ import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.core.BarkSender import com.a2i.forwarder.core.BarkSender
import com.a2i.forwarder.core.EmailSender import com.a2i.forwarder.core.EmailSender
import com.a2i.forwarder.core.ForwardLog import com.a2i.forwarder.core.ForwardLog
import com.a2i.forwarder.core.MeowSender
import com.a2i.forwarder.core.NotificationProcessor import com.a2i.forwarder.core.NotificationProcessor
import com.a2i.forwarder.core.NtfySender import com.a2i.forwarder.core.NtfySender
import com.a2i.forwarder.core.PendingPush import com.a2i.forwarder.core.PendingPush
@@ -65,6 +66,7 @@ class NotifyListenerService : NotificationListenerService() {
app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, msg.title, msg.body, "failed", "未配置可用 Bark 服务器")) app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, msg.title, msg.body, "failed", "未配置可用 Bark 服务器"))
EmailSender.trySend(app, msg.title ?: d.appLabel, msg.body, scope) EmailSender.trySend(app, msg.title ?: d.appLabel, msg.body, scope)
NtfySender.trySend(app, msg.title ?: d.appLabel, msg.body, scope) NtfySender.trySend(app, msg.title ?: d.appLabel, msg.body, scope)
MeowSender.trySend(app, msg.title ?: d.appLabel, msg.body, scope)
return return
} }
@@ -80,5 +82,6 @@ class NotifyListenerService : NotificationListenerService() {
} }
EmailSender.trySend(app, msg.title ?: d.appLabel, msg.body, scope) EmailSender.trySend(app, msg.title ?: d.appLabel, msg.body, scope)
NtfySender.trySend(app, msg.title ?: d.appLabel, msg.body, scope) NtfySender.trySend(app, msg.title ?: d.appLabel, msg.body, scope)
MeowSender.trySend(app, msg.title ?: d.appLabel, msg.body, scope)
} }
} }
@@ -11,6 +11,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore import androidx.datastore.preferences.preferencesDataStore
import com.a2i.forwarder.model.BarkServer import com.a2i.forwarder.model.BarkServer
import com.a2i.forwarder.model.EmailServer import com.a2i.forwarder.model.EmailServer
import com.a2i.forwarder.model.MeowServer
import com.a2i.forwarder.model.NtfyServer import com.a2i.forwarder.model.NtfyServer
import com.a2i.forwarder.model.OFFICIAL_BARK_SERVER import com.a2i.forwarder.model.OFFICIAL_BARK_SERVER
import com.a2i.forwarder.model.SmsTarget import com.a2i.forwarder.model.SmsTarget
@@ -44,6 +45,7 @@ class SettingsStore(
// 各通道「发通一条止 / 全发」开关 // 各通道「发通一条止 / 全发」开关
val BARK_STOP_FIRST = booleanPreferencesKey("bark_stop_first") val BARK_STOP_FIRST = booleanPreferencesKey("bark_stop_first")
val NTFY_STOP_FIRST = booleanPreferencesKey("ntfy_stop_first") val NTFY_STOP_FIRST = booleanPreferencesKey("ntfy_stop_first")
val MEOW_STOP_FIRST = booleanPreferencesKey("meow_stop_first")
val EMAIL_STOP_FIRST = booleanPreferencesKey("email_stop_first") val EMAIL_STOP_FIRST = booleanPreferencesKey("email_stop_first")
val SMS_STOP_FIRST = booleanPreferencesKey("sms_stop_first") val SMS_STOP_FIRST = booleanPreferencesKey("sms_stop_first")
// 短信兜底(目标号已列表化;运营商/余额/限频保持全局) // 短信兜底(目标号已列表化;运营商/余额/限频保持全局)
@@ -57,9 +59,8 @@ class SettingsStore(
// 电邮转发 // 电邮转发
val EMAIL_ENABLED = booleanPreferencesKey("email_enabled") val EMAIL_ENABLED = booleanPreferencesKey("email_enabled")
val EMAIL_SERVERS = stringPreferencesKey("email_servers") val EMAIL_SERVERS = stringPreferencesKey("email_servers")
// ntfy 转发
val NTFY_ENABLED = booleanPreferencesKey("ntfy_enabled")
val NTFY_SERVERS = stringPreferencesKey("ntfy_servers") val NTFY_SERVERS = stringPreferencesKey("ntfy_servers")
val MEOW_SERVERS = stringPreferencesKey("meow_servers")
// 应用更新 // 应用更新
val UPDATE_CHECK_AUTO = booleanPreferencesKey("update_check_auto") val UPDATE_CHECK_AUTO = booleanPreferencesKey("update_check_auto")
val LAST_UPDATE_CHECK = longPreferencesKey("last_update_check") val LAST_UPDATE_CHECK = longPreferencesKey("last_update_check")
@@ -89,6 +90,9 @@ class SettingsStore(
private val _ntfyServers = MutableStateFlow<List<NtfyServer>>(emptyList()) private val _ntfyServers = MutableStateFlow<List<NtfyServer>>(emptyList())
val ntfyServers = _ntfyServers.asStateFlow() val ntfyServers = _ntfyServers.asStateFlow()
private val _meowServers = MutableStateFlow<List<MeowServer>>(emptyList())
val meowServers = _meowServers.asStateFlow()
private val _emailServers = MutableStateFlow<List<EmailServer>>(emptyList()) private val _emailServers = MutableStateFlow<List<EmailServer>>(emptyList())
val emailServers = _emailServers.asStateFlow() val emailServers = _emailServers.asStateFlow()
@@ -106,6 +110,7 @@ class SettingsStore(
// 各通道「发通一条止 / 全发」 // 各通道「发通一条止 / 全发」
val barkStopOnFirst = MutableStateFlow(true) val barkStopOnFirst = MutableStateFlow(true)
val ntfyStopOnFirst = MutableStateFlow(false) val ntfyStopOnFirst = MutableStateFlow(false)
val meowStopOnFirst = MutableStateFlow(false)
val emailStopOnFirst = MutableStateFlow(false) val emailStopOnFirst = MutableStateFlow(false)
val smsStopOnFirst = MutableStateFlow(false) val smsStopOnFirst = MutableStateFlow(false)
@@ -117,9 +122,8 @@ class SettingsStore(
val smsSuspended = MutableStateFlow(false) val smsSuspended = MutableStateFlow(false)
val lastSmsSentTime = MutableStateFlow(0L) val lastSmsSentTime = MutableStateFlow(0L)
// 电邮/ntfy 总开关 // 电邮总开关
val emailForwardingEnabled = MutableStateFlow(false) val emailForwardingEnabled = MutableStateFlow(false)
val ntfyEnabled = MutableStateFlow(false)
// 应用更新 // 应用更新
val updateCheckEnabled = MutableStateFlow(true) val updateCheckEnabled = MutableStateFlow(true)
@@ -145,6 +149,7 @@ class SettingsStore(
// 各通道 stopOnFirst // 各通道 stopOnFirst
barkStopOnFirst.value = p[K.BARK_STOP_FIRST] ?: true barkStopOnFirst.value = p[K.BARK_STOP_FIRST] ?: true
ntfyStopOnFirst.value = p[K.NTFY_STOP_FIRST] ?: false ntfyStopOnFirst.value = p[K.NTFY_STOP_FIRST] ?: false
meowStopOnFirst.value = p[K.MEOW_STOP_FIRST] ?: false
emailStopOnFirst.value = p[K.EMAIL_STOP_FIRST] ?: false emailStopOnFirst.value = p[K.EMAIL_STOP_FIRST] ?: false
smsStopOnFirst.value = p[K.SMS_STOP_FIRST] ?: false smsStopOnFirst.value = p[K.SMS_STOP_FIRST] ?: false
// 短信兜底全局 // 短信兜底全局
@@ -154,9 +159,8 @@ class SettingsStore(
smsBalance.value = p[K.SMS_BALANCE] ?: -1 smsBalance.value = p[K.SMS_BALANCE] ?: -1
smsSuspended.value = p[K.SMS_SUSPENDED] ?: false smsSuspended.value = p[K.SMS_SUSPENDED] ?: false
lastSmsSentTime.value = p[K.SMS_LAST_SENT] ?: 0L lastSmsSentTime.value = p[K.SMS_LAST_SENT] ?: 0L
// 电邮/ntfy 总开关 // 电邮总开关
emailForwardingEnabled.value = p[K.EMAIL_ENABLED] ?: false emailForwardingEnabled.value = p[K.EMAIL_ENABLED] ?: false
ntfyEnabled.value = p[K.NTFY_ENABLED] ?: false
// 应用更新 // 应用更新
updateCheckEnabled.value = p[K.UPDATE_CHECK_AUTO] ?: true updateCheckEnabled.value = p[K.UPDATE_CHECK_AUTO] ?: true
lastUpdateCheckTime.value = p[K.LAST_UPDATE_CHECK] ?: 0L lastUpdateCheckTime.value = p[K.LAST_UPDATE_CHECK] ?: 0L
@@ -165,6 +169,9 @@ class SettingsStore(
_ntfyServers.value = p[K.NTFY_SERVERS] _ntfyServers.value = p[K.NTFY_SERVERS]
?.let { runCatching { json.decodeFromString<List<NtfyServer>>(it) }.getOrNull() } ?.let { runCatching { json.decodeFromString<List<NtfyServer>>(it) }.getOrNull() }
?: emptyList() ?: emptyList()
_meowServers.value = p[K.MEOW_SERVERS]
?.let { runCatching { json.decodeFromString<List<MeowServer>>(it) }.getOrNull() }
?: emptyList()
_emailServers.value = p[K.EMAIL_SERVERS] _emailServers.value = p[K.EMAIL_SERVERS]
?.let { runCatching { json.decodeFromString<List<EmailServer>>(it) }.getOrNull() } ?.let { runCatching { json.decodeFromString<List<EmailServer>>(it) }.getOrNull() }
?: emptyList() ?: emptyList()
@@ -265,6 +272,22 @@ class SettingsStore(
} }
suspend fun setNtfyEnabled(id: String, enabled: Boolean) = saveNtfyServers(_ntfyServers.value.map { if (it.id == id) it.copy(enabled = enabled) else it }) suspend fun setNtfyEnabled(id: String, enabled: Boolean) = saveNtfyServers(_ntfyServers.value.map { if (it.id == id) it.copy(enabled = enabled) else it })
// ---- Meow 服务器 CRUD ----
private suspend fun saveMeowServers(list: List<MeowServer>) {
edit { it[K.MEOW_SERVERS] = json.encodeToString(list) }
_meowServers.value = list
}
suspend fun addMeow(s: MeowServer) { saveMeowServers(_meowServers.value + s) }
suspend fun updateMeow(s: MeowServer) = saveMeowServers(_meowServers.value.map { if (it.id == s.id) s else it })
suspend fun deleteMeow(id: String) = saveMeowServers(_meowServers.value.filterNot { it.id == id })
suspend fun moveMeow(id: String, up: Boolean) {
val list = _meowServers.value.toMutableList()
val i = list.indexOfFirst { it.id == id }
if (i in 1..list.lastIndex && up) { java.util.Collections.swap(list, i, i - 1); saveMeowServers(list) }
else if (i in 0 until list.lastIndex && !up) { java.util.Collections.swap(list, i, i + 1); saveMeowServers(list) }
}
suspend fun setMeowEnabled(id: String, enabled: Boolean) = saveMeowServers(_meowServers.value.map { if (it.id == id) it.copy(enabled = enabled) else it })
// ---- 电邮服务器 CRUD ---- // ---- 电邮服务器 CRUD ----
private suspend fun saveEmailServers(list: List<EmailServer>) { private suspend fun saveEmailServers(list: List<EmailServer>) {
edit { it[K.EMAIL_SERVERS] = json.encodeToString(list) } edit { it[K.EMAIL_SERVERS] = json.encodeToString(list) }
@@ -310,6 +333,7 @@ class SettingsStore(
suspend fun setBarkStopOnFirst(v: Boolean) { edit { it[K.BARK_STOP_FIRST] = v }; barkStopOnFirst.value = v } suspend fun setBarkStopOnFirst(v: Boolean) { edit { it[K.BARK_STOP_FIRST] = v }; barkStopOnFirst.value = v }
suspend fun setNtfyStopOnFirst(v: Boolean) { edit { it[K.NTFY_STOP_FIRST] = v }; ntfyStopOnFirst.value = v } suspend fun setNtfyStopOnFirst(v: Boolean) { edit { it[K.NTFY_STOP_FIRST] = v }; ntfyStopOnFirst.value = v }
suspend fun setMeowStopOnFirst(v: Boolean) { edit { it[K.MEOW_STOP_FIRST] = v }; meowStopOnFirst.value = v }
suspend fun setEmailStopOnFirst(v: Boolean) { edit { it[K.EMAIL_STOP_FIRST] = v }; emailStopOnFirst.value = v } suspend fun setEmailStopOnFirst(v: Boolean) { edit { it[K.EMAIL_STOP_FIRST] = v }; emailStopOnFirst.value = v }
suspend fun setSmsStopOnFirst(v: Boolean) { edit { it[K.SMS_STOP_FIRST] = v }; smsStopOnFirst.value = v } suspend fun setSmsStopOnFirst(v: Boolean) { edit { it[K.SMS_STOP_FIRST] = v }; smsStopOnFirst.value = v }
@@ -325,12 +349,11 @@ class SettingsStore(
suspend fun setIgnoredVersion(v: String) { edit { it[K.IGNORED_VERSION] = v }; ignoredVersion.value = v } suspend fun setIgnoredVersion(v: String) { edit { it[K.IGNORED_VERSION] = v }; ignoredVersion.value = v }
suspend fun setEmailForwarding(v: Boolean) { edit { it[K.EMAIL_ENABLED] = v }; emailForwardingEnabled.value = v } suspend fun setEmailForwarding(v: Boolean) { edit { it[K.EMAIL_ENABLED] = v }; emailForwardingEnabled.value = v }
suspend fun setNtfyEnabled(v: Boolean) { edit { it[K.NTFY_ENABLED] = v }; ntfyEnabled.value = v }
suspend fun snapshot() = ds.data.first() suspend fun snapshot() = ds.data.first()
companion object { companion object {
const val ID_OFFICIAL = "official" const val ID_OFFICIAL = "official"
const val DEFAULT_ICON_PREFIX = "https://raw.githubusercontent.com/lsxf/a2i/main/icons/" const val DEFAULT_ICON_PREFIX = "https://raw.githubusercontent.com/lsxf/gotmsg/main/icons/"
} }
} }
@@ -7,6 +7,7 @@ import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -68,6 +69,9 @@ fun SectionCard(
title: String? = null, title: String? = null,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
subtitle: String? = null, subtitle: String? = null,
titleIcon: ImageVector? = null,
titleIconTint: Color = MaterialTheme.colorScheme.primary,
headerAction: (@Composable () -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit, content: @Composable ColumnScope.() -> Unit,
) { ) {
Card( Card(
@@ -79,12 +83,19 @@ fun SectionCard(
) { ) {
Column(Modifier.padding(16.dp)) { Column(Modifier.padding(16.dp)) {
if (title != null) { if (title != null) {
if (headerAction == null) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (titleIcon != null) {
Icon(titleIcon, null, tint = titleIconTint, modifier = Modifier.size(22.dp))
Spacer(Modifier.width(8.dp))
}
Text( Text(
title, title,
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(bottom = if (subtitle == null) 10.dp else 2.dp), modifier = Modifier.padding(bottom = if (subtitle == null) 10.dp else 2.dp),
) )
}
if (subtitle != null) { if (subtitle != null) {
Text( Text(
subtitle, subtitle,
@@ -93,6 +104,38 @@ fun SectionCard(
modifier = Modifier.padding(bottom = 10.dp), modifier = Modifier.padding(bottom = 10.dp),
) )
} }
} else {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 10.dp),
verticalAlignment = Alignment.Top,
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (titleIcon != null) {
Icon(titleIcon, null, tint = titleIconTint, modifier = Modifier.size(22.dp))
Spacer(Modifier.width(8.dp))
}
Text(
title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(bottom = if (subtitle == null) 0.dp else 2.dp),
)
}
if (subtitle != null) {
Text(
subtitle,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Spacer(Modifier.width(12.dp))
headerAction()
}
}
} }
content() content()
} }
@@ -1,7 +1,20 @@
package com.a2i.forwarder.ui.nav package com.a2i.forwarder.ui.nav
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.outlined.Apps import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.FilterAlt import androidx.compose.material.icons.outlined.FilterAlt
import androidx.compose.material.icons.outlined.Notifications import androidx.compose.material.icons.outlined.Notifications
@@ -14,8 +27,15 @@ import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavGraph.Companion.findStartDestination
@@ -23,11 +43,13 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.ui.screens.AppManageScreen import com.a2i.forwarder.ui.screens.AppManageScreen
import com.a2i.forwarder.ui.screens.FilterScreen import com.a2i.forwarder.ui.screens.FilterScreen
import com.a2i.forwarder.ui.screens.HomeScreen import com.a2i.forwarder.ui.screens.HomeScreen
import com.a2i.forwarder.ui.screens.LogScreen import com.a2i.forwarder.ui.screens.LogScreen
import com.a2i.forwarder.ui.screens.SettingsScreen import com.a2i.forwarder.ui.screens.SettingsScreen
import com.a2i.forwarder.ui.screens.UpdateDialog
private sealed class Tab(val route: String, val label: String, val icon: ImageVector) { private sealed class Tab(val route: String, val label: String, val icon: ImageVector) {
object Home : Tab("home", "首页", Icons.Outlined.Notifications) object Home : Tab("home", "首页", Icons.Outlined.Notifications)
@@ -46,6 +68,11 @@ fun AppRoot() {
val current = backStack?.destination?.route val current = backStack?.destination?.route
val showBar = current in tabRoutes val showBar = current in tabRoutes
val app = A2iApp.instance
val updateInfo by app.updateChecker.updateInfo.collectAsState()
var showUpdateDialog by remember { mutableStateOf(false) }
Box {
Scaffold( Scaffold(
containerColor = MaterialTheme.colorScheme.background, containerColor = MaterialTheme.colorScheme.background,
bottomBar = { bottomBar = {
@@ -96,4 +123,49 @@ fun AppRoot() {
composable("log") { LogScreen(onBack = { nav.popBackStack() }) } composable("log") { LogScreen(onBack = { nav.popBackStack() }) }
} }
} }
// 浮动更新提醒小图标(跨所有页面,缓慢闪烁)
if (updateInfo != null) {
UpdateBadge(
modifier = Modifier.align(Alignment.TopEnd),
onClick = { showUpdateDialog = true },
)
}
}
if (showUpdateDialog && updateInfo != null) {
UpdateDialog(updateInfo!!, onDismiss = { showUpdateDialog = false })
}
}
/** 跨页面浮动更新提醒:右上角小圆点 + 缓慢闪烁动画。 */
@Composable
private fun UpdateBadge(modifier: Modifier = Modifier, onClick: () -> Unit) {
val transition = rememberInfiniteTransition(label = "updateBlink")
val pulseAlpha by transition.animateFloat(
initialValue = 0.35f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(1200),
repeatMode = RepeatMode.Reverse,
),
label = "pulseAlpha",
)
Box(
modifier = modifier
.padding(top = 12.dp, end = 12.dp)
.size(40.dp)
.alpha(pulseAlpha)
.background(MaterialTheme.colorScheme.primary, CircleShape)
.clickable(onClick = onClick),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.SystemUpdate,
contentDescription = "发现新版本,点击更新",
tint = Color.White,
modifier = Modifier.size(22.dp),
)
}
} }
@@ -61,7 +61,7 @@ fun FilterScreen() {
modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp), modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
item { ScreenTitle("过滤与优化", "减少噪音,保留真正需要同步到 iOS 的通知") } item { ScreenTitle("过滤与优化", "减少噪音,保留真正需要转发的通知") }
item { item {
SectionCard("功能开关", subtitle = "规则按通知处理流水线顺序执行") { SectionCard("功能开关", subtitle = "规则按通知处理流水线顺序执行") {
@@ -178,7 +178,7 @@ fun HomeScreen(onOpenLog: () -> Unit, onOpenSettings: () -> Unit) {
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text(if (granted) "通知监听已开启" else "需要授权通知监听", style = MaterialTheme.typography.titleMedium) Text(if (granted) "通知监听已开启" else "需要授权通知监听", style = MaterialTheme.typography.titleMedium)
Text( Text(
if (granted) "系统通知将按规则处理并推送到 Bark" else "授权后才能读取 Android 通知并转发", if (granted) "系统通知将按规则处理并多通道转发" else "授权后才能读取 Android 通知并转发",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -202,7 +202,7 @@ fun HomeScreen(onOpenLog: () -> Unit, onOpenSettings: () -> Unit) {
SectionCard("运行状态", subtitle = "转发能力、目标服务器和日志入口") { SectionCard("运行状态", subtitle = "转发能力、目标服务器和日志入口") {
SwitchRow( SwitchRow(
title = "通知转发", title = "通知转发",
subtitle = if (forwarding) "新通知会继续转发到 Bark" else "当前已暂停所有转发", subtitle = if (forwarding) "新通知会继续多通道转发" else "当前已暂停所有转发",
checked = forwarding, checked = forwarding,
icon = Icons.Filled.PowerSettingsNew, icon = Icons.Filled.PowerSettingsNew,
tint = if (forwarding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, tint = if (forwarding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
@@ -285,8 +285,8 @@ private fun HomeHero(
} }
Spacer(Modifier.width(12.dp)) Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text("a2i", style = MaterialTheme.typography.displaySmall, color = Color.White) Text("GotMsg", style = MaterialTheme.typography.displaySmall, color = Color.White)
Text("安卓通知转发到 iOS Bark", style = MaterialTheme.typography.bodyMedium, color = Color.White.copy(alpha = 0.82f)) Text("安卓通知多通道转发", style = MaterialTheme.typography.bodyMedium, color = Color.White.copy(alpha = 0.82f))
} }
StatusBadge( StatusBadge(
text = if (granted && forwarding) "运行中" else "待处理", text = if (granted && forwarding) "运行中" else "待处理",
@@ -295,7 +295,7 @@ private fun HomeHero(
} }
Spacer(Modifier.size(14.dp)) Spacer(Modifier.size(14.dp))
Text( Text(
if (granted && forwarding) "监听、过滤、提取验证码和推送链路已就绪。" else "完成授权并开启转发后,通知会按规则推送到 iOS", if (granted && forwarding) "监听、过滤、提取验证码和推送链路已就绪。" else "完成授权并开启转发后,通知会按规则转发到各通道",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = Color.White.copy(alpha = 0.86f), color = Color.White.copy(alpha = 0.86f),
) )
@@ -6,12 +6,17 @@ import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
@@ -22,10 +27,15 @@ import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Pets
import androidx.compose.material.icons.filled.RestartAlt import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.Sms
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SystemUpdateAlt import androidx.compose.material.icons.filled.SystemUpdateAlt
import androidx.compose.material.icons.filled.Update import androidx.compose.material.icons.filled.Update
@@ -51,18 +61,26 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import com.a2i.forwarder.A2iApp import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.R
import com.a2i.forwarder.core.BarkClient import com.a2i.forwarder.core.BarkClient
import com.a2i.forwarder.core.EmailSender import com.a2i.forwarder.core.EmailSender
import com.a2i.forwarder.core.IconExporter import com.a2i.forwarder.core.IconExporter
import com.a2i.forwarder.core.MeowSender
import com.a2i.forwarder.core.NtfySender import com.a2i.forwarder.core.NtfySender
import com.a2i.forwarder.model.BarkMessage import com.a2i.forwarder.model.BarkMessage
import com.a2i.forwarder.model.BarkServer import com.a2i.forwarder.model.BarkServer
import com.a2i.forwarder.model.EmailServer import com.a2i.forwarder.model.EmailServer
import com.a2i.forwarder.model.MeowServer
import com.a2i.forwarder.model.NtfyServer import com.a2i.forwarder.model.NtfyServer
import com.a2i.forwarder.model.OFFICIAL_BARK_SERVER import com.a2i.forwarder.model.OFFICIAL_BARK_SERVER
import com.a2i.forwarder.model.SmsTarget import com.a2i.forwarder.model.SmsTarget
@@ -74,19 +92,32 @@ import com.a2i.forwarder.ui.SwitchRow
import com.a2i.forwarder.ui.appVersionName import com.a2i.forwarder.ui.appVersionName
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
private const val BARK_APP_STORE_URL = "https://apps.apple.com/app/bark-custom-notifications/id1403753865"
private const val BARK_DOCS_URL = "https://bark.day.app/#/"
private const val BARK_GITHUB_URL = "https://github.com/Finb/Bark"
private const val BARK_OFFICIAL_SERVER = "https://api.day.app"
private const val NTFY_OFFICIAL_SERVER = "https://ntfy.sh"
private const val NTFY_ANDROID_URL = "https://play.google.com/store/apps/details?id=io.heckel.ntfy"
private const val NTFY_IOS_URL = "https://apps.apple.com/us/app/ntfy/id1625396347"
private const val NTFY_FDROID_URL = "https://f-droid.org/en/packages/io.heckel.ntfy/"
private const val NTFY_DOCS_URL = "https://docs.ntfy.sh/subscribe/phone/"
private const val NTFY_PUBLISH_DOCS_URL = "https://docs.ntfy.sh/publish/"
private const val NTFY_GITHUB_URL = "https://github.com/binwiederhier/ntfy"
@Composable @Composable
fun SettingsScreen(onOpenLog: () -> Unit) { fun SettingsScreen(onOpenLog: () -> Unit) {
val context = LocalContext.current val context = LocalContext.current
val app = A2iApp.instance val app = A2iApp.instance
val servers by app.settings.servers.collectAsState() val servers by app.settings.servers.collectAsState()
val ntfyServers by app.settings.ntfyServers.collectAsState() val ntfyServers by app.settings.ntfyServers.collectAsState()
val meowServers by app.settings.meowServers.collectAsState()
val emailServers by app.settings.emailServers.collectAsState() val emailServers by app.settings.emailServers.collectAsState()
val smsTargets by app.settings.smsTargets.collectAsState() val smsTargets by app.settings.smsTargets.collectAsState()
val barkStopFirst by app.settings.barkStopOnFirst.collectAsState() val barkStopFirst by app.settings.barkStopOnFirst.collectAsState()
val ntfyStopFirst by app.settings.ntfyStopOnFirst.collectAsState() val ntfyStopFirst by app.settings.ntfyStopOnFirst.collectAsState()
val meowStopFirst by app.settings.meowStopOnFirst.collectAsState()
val emailStopFirst by app.settings.emailStopOnFirst.collectAsState() val emailStopFirst by app.settings.emailStopOnFirst.collectAsState()
val smsStopFirst by app.settings.smsStopOnFirst.collectAsState() val smsStopFirst by app.settings.smsStopOnFirst.collectAsState()
val ntfyEnabled by app.settings.ntfyEnabled.collectAsState()
val emailEnabled by app.settings.emailForwardingEnabled.collectAsState() val emailEnabled by app.settings.emailForwardingEnabled.collectAsState()
val smsFallback by app.settings.smsFallbackEnabled.collectAsState() val smsFallback by app.settings.smsFallbackEnabled.collectAsState()
val iconPrefix by app.settings.iconPrefix.collectAsState() val iconPrefix by app.settings.iconPrefix.collectAsState()
@@ -118,9 +149,14 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
// 弹窗状态 // 弹窗状态
var showAddBark by remember { mutableStateOf(false) } var showAddBark by remember { mutableStateOf(false) }
var showBarkHelp by remember { mutableStateOf(false) }
var editingBark by remember { mutableStateOf<BarkServer?>(null) } var editingBark by remember { mutableStateOf<BarkServer?>(null) }
var showAddNtfy by remember { mutableStateOf(false) } var showAddNtfy by remember { mutableStateOf(false) }
var showNtfyHelp by remember { mutableStateOf(false) }
var editingNtfy by remember { mutableStateOf<NtfyServer?>(null) } var editingNtfy by remember { mutableStateOf<NtfyServer?>(null) }
var showAddMeow by remember { mutableStateOf(false) }
var showMeowHelp by remember { mutableStateOf(false) }
var editingMeow by remember { mutableStateOf<MeowServer?>(null) }
var showAddEmail by remember { mutableStateOf(false) } var showAddEmail by remember { mutableStateOf(false) }
var editingEmail by remember { mutableStateOf<EmailServer?>(null) } var editingEmail by remember { mutableStateOf<EmailServer?>(null) }
var showAddSms by remember { mutableStateOf(false) } var showAddSms by remember { mutableStateOf(false) }
@@ -134,13 +170,19 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
// ===== Bark 服务器 ===== // ===== Bark 服务器 =====
item { item {
SectionCard("Bark 服务器", subtitle = "勾选的服务器参与转发;开关切换容错/广播") { SectionCard {
SwitchRow( ChannelSectionHeader(
title = "发通一条就停", title = "Bark 服务器",
subtitle = if (barkStopFirst) "容错模式:首个成功即止" else "广播模式:每个都发", summary = "iPhone / iPad 推送目标",
checked = barkStopFirst, mark = "B",
icon = Icons.Filled.Settings, markColor = Color(0xFFFF9800),
) { v -> app.appScope.launch { app.settings.setBarkStopOnFirst(v) } } markLogo = painterResource(R.drawable.ic_bark_logo),
platforms = listOf("iOS"),
stopFirst = barkStopFirst,
onStopFirstChange = { v -> app.appScope.launch { app.settings.setBarkStopOnFirst(v) } },
onHelpClick = { showBarkHelp = true },
helpContentDescription = "Bark 配置帮助",
)
if (servers.isNotEmpty()) { if (servers.isNotEmpty()) {
Spacer(Modifier.size(8.dp)) Spacer(Modifier.size(8.dp))
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -161,23 +203,32 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
// ===== ntfy ===== // ===== ntfy =====
item { item {
SectionCard("ntfy 转发", subtitle = "POST 推送到 ntfy 服务") { SectionCard {
SwitchRow(title = "启用 ntfy 转发", subtitle = if (ntfyEnabled) "已开启" else "已关闭", checked = ntfyEnabled) { v -> app.appScope.launch { app.settings.setNtfyEnabled(v) } } ChannelSectionHeader(
if (ntfyEnabled) { title = "ntfy 转发",
SwitchRow(title = "发通一条就停", subtitle = if (ntfyStopFirst) "容错:首个成功止" else "广播:每个都发", checked = ntfyStopFirst) { v -> app.appScope.launch { app.settings.setNtfyStopOnFirst(v) } } summary = "Android / iOS topic 推送",
mark = "n",
markColor = Color(0xFF43A047),
markLogo = painterResource(R.drawable.ic_ntfy_logo),
platforms = listOf("Android", "iOS"),
stopFirst = ntfyStopFirst,
onStopFirstChange = { v -> app.appScope.launch { app.settings.setNtfyStopOnFirst(v) } },
onHelpClick = { showNtfyHelp = true },
helpContentDescription = "ntfy 配置帮助",
)
if (ntfyServers.isNotEmpty()) { if (ntfyServers.isNotEmpty()) {
Spacer(Modifier.size(8.dp)) Spacer(Modifier.size(8.dp))
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
ntfyServers.forEachIndexed { i, s -> ntfyServers.forEachIndexed { i, s ->
ConfigRow( NtfyServerRow(
title = s.name.ifBlank { s.topic }, server = s,
subtitle = "${s.server} · topic: ${s.topic}${if (s.token.isNotBlank()) " · token已填" else ""}", isFirst = i == 0,
enabled = s.enabled, isFirst = i == 0, isLast = i == ntfyServers.lastIndex, isLast = i == ntfyServers.lastIndex,
onToggle = { v -> app.appScope.launch { app.settings.setNtfyEnabled(s.id, v) } }, onToggle = { v -> app.appScope.launch { app.settings.setNtfyEnabled(s.id, v) } },
onEdit = { editingNtfy = s }, onDelete = { app.appScope.launch { app.settings.deleteNtfy(s.id) } }, onEdit = { editingNtfy = s },
onDelete = { app.appScope.launch { app.settings.deleteNtfy(s.id) } },
onMoveUp = { app.appScope.launch { app.settings.moveNtfy(s.id, true) } }, onMoveUp = { app.appScope.launch { app.settings.moveNtfy(s.id, true) } },
onMoveDown = { app.appScope.launch { app.settings.moveNtfy(s.id, false) } }, onMoveDown = { app.appScope.launch { app.settings.moveNtfy(s.id, false) } },
onTest = { app.appScope.launch { NtfySender.send(s.server, s.topic, s.token, "a2i测试", "ntfy配置测试") } },
) )
} }
} }
@@ -185,27 +236,69 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
AddButton { showAddNtfy = true } AddButton { showAddNtfy = true }
} }
} }
// ===== Meow =====
item {
SectionCard {
ChannelSectionHeader(
title = "Meow 转发",
summary = "鸿蒙手机推送目标",
mark = "M",
markColor = Color(0xFF7E57C2),
markLogo = painterResource(R.drawable.ic_meow_logo),
platforms = listOf("HarmonyOS"),
stopFirst = meowStopFirst,
onStopFirstChange = { v -> app.appScope.launch { app.settings.setMeowStopOnFirst(v) } },
onHelpClick = { showMeowHelp = true },
helpContentDescription = "Meow 配置帮助",
)
if (meowServers.isNotEmpty()) {
Spacer(Modifier.size(8.dp))
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
meowServers.forEachIndexed { i, s ->
MeowServerRow(
server = s,
isFirst = i == 0,
isLast = i == meowServers.lastIndex,
onToggle = { v -> app.appScope.launch { app.settings.setMeowEnabled(s.id, v) } },
onEdit = { editingMeow = s },
onDelete = { app.appScope.launch { app.settings.deleteMeow(s.id) } },
onMoveUp = { app.appScope.launch { app.settings.moveMeow(s.id, true) } },
onMoveDown = { app.appScope.launch { app.settings.moveMeow(s.id, false) } },
)
}
}
}
AddButton { showAddMeow = true }
}
} }
// ===== 电邮 ===== // ===== 电邮 =====
item { item {
SectionCard("电邮转发", subtitle = "SMTPS 直发邮件") { SectionCard {
SwitchRow(title = "启用电邮转发", subtitle = if (emailEnabled) "已开启" else "已关闭", checked = emailEnabled) { v -> app.appScope.launch { app.settings.setEmailForwarding(v) } } ChannelSectionHeader(
if (emailEnabled) { title = "电邮转发",
SwitchRow(title = "发通一条就停", subtitle = if (emailStopFirst) "容错:首个成功止" else "广播:每个都发", checked = emailStopFirst) { v -> app.appScope.launch { app.settings.setEmailStopOnFirst(v) } } summary = "SMTP 邮箱推送目标",
mark = "@",
markColor = Color(0xFF1976D2),
markIcon = Icons.Filled.Email,
platforms = listOf("Email"),
stopFirst = emailStopFirst,
onStopFirstChange = { v -> app.appScope.launch { app.settings.setEmailStopOnFirst(v) } },
)
if (emailServers.isNotEmpty()) { if (emailServers.isNotEmpty()) {
Spacer(Modifier.size(8.dp)) Spacer(Modifier.size(8.dp))
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
emailServers.forEachIndexed { i, s -> emailServers.forEachIndexed { i, s ->
ConfigRow( EmailServerRow(
title = s.name.ifBlank { s.to }, server = s,
subtitle = "${s.host}:${s.port} · ${s.user}${s.to}", isFirst = i == 0,
enabled = s.enabled, isFirst = i == 0, isLast = i == emailServers.lastIndex, isLast = i == emailServers.lastIndex,
onToggle = { v -> app.appScope.launch { app.settings.setEmailEnabled(s.id, v) } }, onToggle = { v -> app.appScope.launch { app.settings.setEmailEnabled(s.id, v) } },
onEdit = { editingEmail = s }, onDelete = { app.appScope.launch { app.settings.deleteEmail(s.id) } }, onEdit = { editingEmail = s },
onDelete = { app.appScope.launch { app.settings.deleteEmail(s.id) } },
onMoveUp = { app.appScope.launch { app.settings.moveEmail(s.id, true) } }, onMoveUp = { app.appScope.launch { app.settings.moveEmail(s.id, true) } },
onMoveDown = { app.appScope.launch { app.settings.moveEmail(s.id, false) } }, onMoveDown = { app.appScope.launch { app.settings.moveEmail(s.id, false) } },
onTest = { app.appScope.launch { EmailSender.send(s.host, s.port, s.user, s.password, s.from, s.to, "a2i测试", "电邮配置测试") } },
) )
} }
} }
@@ -213,14 +306,20 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
AddButton { showAddEmail = true } AddButton { showAddEmail = true }
} }
} }
}
// ===== 短信兜底 ===== // ===== 短信兜底 =====
item { item {
SectionCard("断网短信兜底", subtitle = "无网络时把验证码/来电用短信发出去") { SectionCard {
SwitchRow(title = "启用短信兜底", subtitle = if (smsFallback) "已开启" else "已关闭", checked = smsFallback) { v -> app.appScope.launch { app.settings.setSmsFallback(v) } } ChannelSectionHeader(
if (smsFallback) { title = "断网短信兜底",
SwitchRow(title = "发通一条就停", subtitle = if (smsStopFirst) "容错:首个成功止" else "广播:每个都发", checked = smsStopFirst) { v -> app.appScope.launch { app.settings.setSmsStopOnFirst(v) } } summary = "无网络时发送关键通知",
mark = "S",
markColor = Color(0xFF00897B),
markIcon = Icons.Filled.Sms,
platforms = listOf("SMS"),
stopFirst = smsStopFirst,
onStopFirstChange = { v -> app.appScope.launch { app.settings.setSmsStopOnFirst(v) } },
)
if (!hasSmsPerm) { if (!hasSmsPerm) {
Spacer(Modifier.size(4.dp)) Spacer(Modifier.size(4.dp))
OutlinedButton(onClick = { smsPermLauncher.launch(android.Manifest.permission.SEND_SMS) }, modifier = Modifier.fillMaxWidth()) { Text("授予短信权限") } OutlinedButton(onClick = { smsPermLauncher.launch(android.Manifest.permission.SEND_SMS) }, modifier = Modifier.fillMaxWidth()) { Text("授予短信权限") }
@@ -252,7 +351,6 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
Text("运营商:${detectedCarrier.displayName} · 余额:$balanceText · 手动额度:$smsManualQuota", style = MaterialTheme.typography.bodySmall, color = if (smsSuspended) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) Text("运营商:${detectedCarrier.displayName} · 余额:$balanceText · 手动额度:$smsManualQuota", style = MaterialTheme.typography.bodySmall, color = if (smsSuspended) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
}
// ===== 应用图标 ===== // ===== 应用图标 =====
item { item {
@@ -307,10 +405,15 @@ fun SettingsScreen(onOpenLog: () -> Unit) {
} }
// 弹窗 // 弹窗
if (showBarkHelp) BarkHelpDialog(onDismiss = { showBarkHelp = false })
if (showNtfyHelp) NtfyHelpDialog(onDismiss = { showNtfyHelp = false })
if (showMeowHelp) MeowHelpDialog(onDismiss = { showMeowHelp = false })
if (showAddBark) ServerDialog(onDismiss = { showAddBark = false }, onConfirm = { n, s, k -> app.appScope.launch { app.settings.addServer(n, s, k) }; showAddBark = false }) if (showAddBark) ServerDialog(onDismiss = { showAddBark = false }, onConfirm = { n, s, k -> app.appScope.launch { app.settings.addServer(n, s, k) }; showAddBark = false })
editingBark?.let { srv -> ServerDialog(initial = srv, onDismiss = { editingBark = null }, onConfirm = { n, s, k -> app.appScope.launch { app.settings.updateServer(srv.copy(name = n, server = s, deviceKey = k)) }; editingBark = null }) } editingBark?.let { srv -> ServerDialog(initial = srv, onDismiss = { editingBark = null }, onConfirm = { n, s, k -> app.appScope.launch { app.settings.updateServer(srv.copy(name = n, server = s, deviceKey = k)) }; editingBark = null }) }
if (showAddNtfy) NtfyConfigDialog(onDismiss = { showAddNtfy = false }, onConfirm = { n, sv, t, tk -> app.appScope.launch { app.settings.addNtfy(NtfyServer(name = n, server = sv, topic = t, token = tk)) }; showAddNtfy = false }) if (showAddNtfy) NtfyConfigDialog(onDismiss = { showAddNtfy = false }, onConfirm = { n, sv, t, tk -> app.appScope.launch { app.settings.addNtfy(NtfyServer(name = n, server = sv, topic = t, token = tk)) }; showAddNtfy = false })
editingNtfy?.let { srv -> NtfyConfigDialog(initial = srv, onDismiss = { editingNtfy = null }, onConfirm = { n, sv, t, tk -> app.appScope.launch { app.settings.updateNtfy(srv.copy(name = n, server = sv, topic = t, token = tk)) }; editingNtfy = null }) } editingNtfy?.let { srv -> NtfyConfigDialog(initial = srv, onDismiss = { editingNtfy = null }, onConfirm = { n, sv, t, tk -> app.appScope.launch { app.settings.updateNtfy(srv.copy(name = n, server = sv, topic = t, token = tk)) }; editingNtfy = null }) }
if (showAddMeow) MeowConfigDialog(onDismiss = { showAddMeow = false }, onConfirm = { n, sv, k -> app.appScope.launch { app.settings.addMeow(MeowServer(name = n, server = sv, deviceKey = k)) }; showAddMeow = false })
editingMeow?.let { srv -> MeowConfigDialog(initial = srv, onDismiss = { editingMeow = null }, onConfirm = { n, sv, k -> app.appScope.launch { app.settings.updateMeow(srv.copy(name = n, server = sv, deviceKey = k)) }; editingMeow = null }) }
if (showAddEmail) EmailConfigDialog(onDismiss = { showAddEmail = false }, onConfirm = { c -> app.appScope.launch { app.settings.addEmail(c) }; showAddEmail = false }) if (showAddEmail) EmailConfigDialog(onDismiss = { showAddEmail = false }, onConfirm = { c -> app.appScope.launch { app.settings.addEmail(c) }; showAddEmail = false })
editingEmail?.let { srv -> EmailConfigDialog(initial = srv, onDismiss = { editingEmail = null }, onConfirm = { c -> app.appScope.launch { app.settings.updateEmail(c.copy(id = srv.id)) }; editingEmail = null }) } editingEmail?.let { srv -> EmailConfigDialog(initial = srv, onDismiss = { editingEmail = null }, onConfirm = { c -> app.appScope.launch { app.settings.updateEmail(c.copy(id = srv.id)) }; editingEmail = null }) }
if (showAddSms) SmsConfigDialog(onDismiss = { showAddSms = false }, onConfirm = { n, num -> app.appScope.launch { app.settings.addSmsTarget(SmsTarget(name = n, number = num)) }; showAddSms = false }) if (showAddSms) SmsConfigDialog(onDismiss = { showAddSms = false }, onConfirm = { n, num -> app.appScope.launch { app.settings.addSmsTarget(SmsTarget(name = n, number = num)) }; showAddSms = false })
@@ -326,6 +429,357 @@ private fun AddButton(onClick: () -> Unit) {
} }
} }
@Composable
private fun ChannelSectionHeader(
title: String,
summary: String,
mark: String,
markColor: Color,
markIcon: ImageVector? = null,
markLogo: Painter? = null,
platforms: List<String>,
stopFirst: Boolean,
onStopFirstChange: (Boolean) -> Unit,
onHelpClick: (() -> Unit)? = null,
helpContentDescription: String? = null,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
ChannelMark(mark = mark, tint = markColor, icon = markIcon, logoPainter = markLogo)
Spacer(Modifier.width(10.dp))
Row(
modifier = Modifier.weight(1f),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
if (platforms.isNotEmpty()) {
Spacer(Modifier.width(8.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(5.dp),
verticalAlignment = Alignment.CenterVertically,
) {
platforms.forEach { PlatformBadge(it) }
}
}
}
if (onHelpClick != null) {
Spacer(Modifier.width(8.dp))
IconButton(onClick = onHelpClick, modifier = Modifier.size(40.dp)) {
Icon(
Icons.Filled.Info,
helpContentDescription,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
summary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
Spacer(Modifier.width(8.dp))
DeliveryModeControl(
stopFirst = stopFirst,
onStopFirstChange = onStopFirstChange,
)
}
}
}
@Composable
private fun ChannelMark(mark: String, tint: Color, icon: ImageVector? = null, logoPainter: Painter? = null) {
Surface(
modifier = Modifier.size(36.dp),
shape = RoundedCornerShape(10.dp),
color = tint.copy(alpha = 0.14f),
border = BorderStroke(1.dp, tint.copy(alpha = 0.28f)),
) {
Row(
modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
if (logoPainter != null) {
Image(logoPainter, null, modifier = Modifier.size(24.dp))
} else if (icon != null) {
Icon(icon, null, tint = tint, modifier = Modifier.size(20.dp))
} else {
Text(mark, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = tint, maxLines = 1)
}
}
}
}
@Composable
private fun PlatformBadge(label: String) {
Surface(
shape = RoundedCornerShape(999.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
Text(
label,
modifier = Modifier.padding(horizontal = 7.dp, vertical = 3.dp),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
}
}
@Composable
private fun DeliveryModeControl(
stopFirst: Boolean,
onStopFirstChange: (Boolean) -> Unit,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
"模式",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
Spacer(Modifier.width(6.dp))
DeliveryModeOption(
label = "容错",
selected = stopFirst,
shape = RoundedCornerShape(topStart = 8.dp, topEnd = 0.dp, bottomEnd = 0.dp, bottomStart = 8.dp),
onClick = { onStopFirstChange(true) },
)
DeliveryModeOption(
label = "广播",
selected = !stopFirst,
shape = RoundedCornerShape(topStart = 0.dp, topEnd = 8.dp, bottomEnd = 8.dp, bottomStart = 0.dp),
onClick = { onStopFirstChange(false) },
)
}
}
@Composable
private fun DeliveryModeOption(
label: String,
selected: Boolean,
shape: RoundedCornerShape,
onClick: () -> Unit,
) {
Surface(
modifier = Modifier.clickable(onClick = onClick),
shape = shape,
color = if (selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface,
border = BorderStroke(
1.dp,
if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.50f) else MaterialTheme.colorScheme.outlineVariant,
),
) {
Text(
label,
modifier = Modifier.padding(horizontal = 9.dp, vertical = 5.dp),
style = MaterialTheme.typography.labelMedium,
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
color = if (selected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
}
}
@Composable
private fun BarkHelpDialog(onDismiss: () -> Unit) {
val uriHandler = LocalUriHandler.current
AlertDialog(
onDismissRequest = onDismiss,
icon = { Icon(Icons.Filled.Info, null) },
title = { Text("Bark 配置帮助") },
text = {
Column(
modifier = Modifier
.heightIn(max = 440.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Text(
"Bark 用来把 a2i 处理后的 Android 通知推送到 iPhone / iPad。第一次使用按下面顺序配置即可。",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
HelpStep("1", "在 iPhone / iPad 上安装 Bark,首次打开时允许通知权限。")
HelpStep("2", "打开 Bark,复制首页显示的推送地址,通常类似 $BARK_OFFICIAL_SERVER/你的Key。")
HelpStep("3", "回到 a2i,点击本区域底部的「添加」。服务器地址填 $BARK_OFFICIAL_SERVER,自建服务则填你的自建地址。")
HelpStep("4", "Device Key 填推送地址最后一段 Key,不要把完整 URL 都填进去。")
HelpStep("5", "保存后点服务器行里的发送按钮测试;iPhone 收到「GotMsg 测试」就说明 Bark 通道已通。")
HelpStep("6", "最后回首页开启「通知转发」,并按提示授予系统通知监听权限。")
Text(
"常用链接",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(top = 4.dp),
)
HelpLink("Bark App Store", BARK_APP_STORE_URL) { uriHandler.openUri(it) }
HelpLink("Bark 官方文档", BARK_DOCS_URL) { uriHandler.openUri(it) }
HelpLink("Bark GitHub", BARK_GITHUB_URL) { uriHandler.openUri(it) }
Text(
"提示:如果使用自建 Bark Server,a2i 里的服务器地址要换成自建地址,但 Device Key 仍然来自 Bark App。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 2.dp),
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("知道了") } },
)
}
@Composable
private fun NtfyHelpDialog(onDismiss: () -> Unit) {
val uriHandler = LocalUriHandler.current
AlertDialog(
onDismissRequest = onDismiss,
icon = { Icon(Icons.Filled.Info, null) },
title = { Text("ntfy 配置帮助") },
text = {
Column(
modifier = Modifier
.heightIn(max = 440.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Text(
"ntfy 用来把 a2i 处理后的通知推送到 Android、iOS 或网页版 ntfy。它不需要先建项目,只要接收端和 a2i 使用同一个 server + topic 即可。",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
HelpStep("1", "在接收端安装 ntfy。Android 可用 Google Play / F-Droid / GitHub APKiPhone / iPad 可用 App Store。")
HelpStep("2", "打开 ntfy,添加订阅。服务器通常填 $NTFY_OFFICIAL_SERVERTopic 建议用一串不容易猜到的随机名字,例如 a2i_xxxxxxxx。")
HelpStep("3", "回到 a2i,点击本区域底部的「添加」。服务器和 Topic 要与接收端订阅完全一致。")
HelpStep("4", "Token 是可选项。只有你在 ntfy 账号或自建服务里把 topic 设成需要鉴权时,才填写 access token。")
HelpStep("5", "保存后点 topic 行里的发送按钮测试;接收端收到「GotMsg 测试」就说明 ntfy 通道已通。")
HelpStep("6", "后续只要这一行左侧保持勾选,它就会参与转发;取消勾选就是停用这个 topic。")
Text(
"常用链接",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(top = 4.dp),
)
HelpLink("ntfy Android · Google Play", NTFY_ANDROID_URL) { uriHandler.openUri(it) }
HelpLink("ntfy Android · F-Droid", NTFY_FDROID_URL) { uriHandler.openUri(it) }
HelpLink("ntfy iOS · App Store", NTFY_IOS_URL) { uriHandler.openUri(it) }
HelpLink("ntfy 手机端文档", NTFY_DOCS_URL) { uriHandler.openUri(it) }
HelpLink("ntfy 发布 API 文档", NTFY_PUBLISH_DOCS_URL) { uriHandler.openUri(it) }
HelpLink("ntfy GitHub", NTFY_GITHUB_URL) { uriHandler.openUri(it) }
Text(
"提示:公共 topic 谁知道名字谁就可能订阅或发送,所以 topic 名不要用手机号、姓名、邮箱等可猜信息。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 2.dp),
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("知道了") } },
)
}
@Composable
private fun MeowHelpDialog(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
icon = { Icon(Icons.Filled.Info, null, tint = Color(0xFFFF9800)) },
title = { Text("Meow 配置帮助") },
text = {
Column(
modifier = Modifier
.heightIn(max = 440.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Text(
"Meow 用来把 a2i 处理后的 Android 通知推送到鸿蒙手机。a2i 只负责按你填写的 Meow 接口地址和 Device Key 发出 HTTP 请求。",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
HelpStep("1", "在鸿蒙手机上安装并打开 Meow,先确认 Meow 自身可以正常接收推送。")
HelpStep("2", "在 Meow 里找到推送接口、服务器地址或 API 地址,同时复制对应的 Device Key / Token。")
HelpStep("3", "回到 a2i,点击本区域底部的「添加」。名称按你的鸿蒙设备填写,方便以后区分。")
HelpStep("4", "服务器地址可以填 Meow 给出的完整 API 地址;如果 Meow 只给了服务根地址,a2i 也会尝试常见的 /push 路径。")
HelpStep("5", "Device Key 填 Meow 给你的设备 Key 或 Token,不要填写鸿蒙手机锁屏密码、华为账号密码等敏感账号密码。")
HelpStep("6", "保存后点设备行里的发送按钮测试;鸿蒙手机收到「GotMsg 测试」就说明 Meow 通道已通。")
HelpStep("7", "后续只要这一行左侧保持勾选,它就会参与转发;取消勾选就是停用这个鸿蒙设备。")
Text(
"提示:如果测试失败,优先检查 Meow 里的接口地址是否完整、Key 是否复制完整,以及鸿蒙手机是否允许 Meow 通知。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 2.dp),
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("知道了") } },
)
}
@Composable
private fun HelpStep(
index: String,
text: String,
) {
Row(verticalAlignment = Alignment.Top) {
Text(
"$index.",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.width(24.dp),
)
Text(
text,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
}
}
@Composable
private fun HelpLink(
title: String,
url: String,
onOpen: (String) -> Unit,
) {
OutlinedButton(
onClick = { onOpen(url) },
modifier = Modifier.fillMaxWidth(),
) {
Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
/** 通用配置行(ntfy/电邮/短信 共用,仿 ServerRow 简化版)。 */ /** 通用配置行(ntfy/电邮/短信 共用,仿 ServerRow 简化版)。 */
@Composable @Composable
private fun ConfigRow( private fun ConfigRow(
@@ -358,7 +812,87 @@ private fun ConfigRow(
} }
} }
// ===== Bark 服务器 Row + Dialog(保留原有) ===== // ===== ntfy / Bark Row + Dialog =====
@Composable
private fun MeowServerRow(
server: MeowServer, isFirst: Boolean, isLast: Boolean,
onToggle: (Boolean) -> Unit, onEdit: () -> Unit, onDelete: () -> Unit,
onMoveUp: () -> Unit, onMoveDown: () -> Unit,
) {
val app = A2iApp.instance
var testing by remember { mutableStateOf(false) }
var testMsg by remember { mutableStateOf<String?>(null) }
Surface(
modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp),
color = if (server.enabled) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.40f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.36f),
border = BorderStroke(1.dp, if (server.enabled) MaterialTheme.colorScheme.primary.copy(alpha = 0.30f) else MaterialTheme.colorScheme.outlineVariant),
) {
Column(Modifier.padding(start = 4.dp, end = 4.dp, top = 2.dp, bottom = 6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = server.enabled, onCheckedChange = onToggle)
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
Text(server.name.ifBlank { "鸿蒙手机" }, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (!server.enabled) { Spacer(Modifier.width(8.dp)); StatusBadge("停用", MaterialTheme.colorScheme.onSurfaceVariant) }
}
IconButton(onClick = { if (!testing) app.appScope.launch { testing = true; testMsg = testMeow(server); testing = false } }, enabled = !testing) {
if (testing) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) else Icon(Icons.AutoMirrored.Filled.Send, "测试")
}
IconButton(onClick = onEdit) { Icon(Icons.Filled.Edit, "编辑") }
IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "删除") }
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
Column(Modifier.weight(1f).padding(start = 36.dp)) {
Text(server.server.ifBlank { "服务器地址未填" }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text("device key: " + if (server.deviceKey.isBlank()) "未填" else "已填(${server.deviceKey.length} 位)", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
IconButton(onClick = onMoveUp, enabled = !isFirst) { Icon(Icons.Filled.KeyboardArrowUp, "上移") }
IconButton(onClick = onMoveDown, enabled = !isLast) { Icon(Icons.Filled.KeyboardArrowDown, "下移") }
}
testMsg?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = if (it.startsWith("已发送")) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.error, modifier = Modifier.padding(start = 48.dp, top = 2.dp)) }
}
}
}
@Composable
private fun NtfyServerRow(
server: NtfyServer, isFirst: Boolean, isLast: Boolean,
onToggle: (Boolean) -> Unit, onEdit: () -> Unit, onDelete: () -> Unit,
onMoveUp: () -> Unit, onMoveDown: () -> Unit,
) {
val app = A2iApp.instance
var testing by remember { mutableStateOf(false) }
var testMsg by remember { mutableStateOf<String?>(null) }
Surface(
modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp),
color = if (server.enabled) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.40f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.36f),
border = BorderStroke(1.dp, if (server.enabled) MaterialTheme.colorScheme.primary.copy(alpha = 0.30f) else MaterialTheme.colorScheme.outlineVariant),
) {
Column(Modifier.padding(start = 4.dp, end = 4.dp, top = 2.dp, bottom = 6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = server.enabled, onCheckedChange = onToggle)
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
Text(server.name.ifBlank { server.topic.ifBlank { "未命名" } }, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (!server.enabled) { Spacer(Modifier.width(8.dp)); StatusBadge("停用", MaterialTheme.colorScheme.onSurfaceVariant) }
}
IconButton(onClick = { if (!testing) app.appScope.launch { testing = true; testMsg = testNtfy(server); testing = false } }, enabled = !testing) {
if (testing) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) else Icon(Icons.AutoMirrored.Filled.Send, "测试")
}
IconButton(onClick = onEdit) { Icon(Icons.Filled.Edit, "编辑") }
IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "删除") }
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
Column(Modifier.weight(1f).padding(start = 36.dp)) {
Text(server.server, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text("topic: " + server.topic.ifBlank { "未填" } + if (server.token.isNotBlank()) " · token已填" else "", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
IconButton(onClick = onMoveUp, enabled = !isFirst) { Icon(Icons.Filled.KeyboardArrowUp, "上移") }
IconButton(onClick = onMoveDown, enabled = !isLast) { Icon(Icons.Filled.KeyboardArrowDown, "下移") }
}
testMsg?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = if (it.startsWith("已发送")) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.error, modifier = Modifier.padding(start = 48.dp, top = 2.dp)) }
}
}
}
@Composable @Composable
private fun ServerRow( private fun ServerRow(
server: BarkServer, isFirst: Boolean, isLast: Boolean, server: BarkServer, isFirst: Boolean, isLast: Boolean,
@@ -399,6 +933,52 @@ private fun ServerRow(
} }
} }
@Composable
private fun EmailServerRow(
server: EmailServer, isFirst: Boolean, isLast: Boolean,
onToggle: (Boolean) -> Unit, onEdit: () -> Unit, onDelete: () -> Unit,
onMoveUp: () -> Unit, onMoveDown: () -> Unit,
) {
val app = A2iApp.instance
var testing by remember { mutableStateOf(false) }
var testMsg by remember { mutableStateOf<String?>(null) }
Surface(
modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp),
color = if (server.enabled) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.40f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.36f),
border = BorderStroke(1.dp, if (server.enabled) MaterialTheme.colorScheme.primary.copy(alpha = 0.30f) else MaterialTheme.colorScheme.outlineVariant),
) {
Column(Modifier.padding(start = 4.dp, end = 4.dp, top = 2.dp, bottom = 6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = server.enabled, onCheckedChange = onToggle)
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
Text(server.name.ifBlank { server.to.ifBlank { "未命名" } }, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (!server.enabled) { Spacer(Modifier.width(8.dp)); StatusBadge("停用", MaterialTheme.colorScheme.onSurfaceVariant) }
}
IconButton(onClick = { if (!testing) app.appScope.launch { testing = true; testMsg = testEmail(server); testing = false } }, enabled = !testing) {
if (testing) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) else Icon(Icons.AutoMirrored.Filled.Send, "测试")
}
IconButton(onClick = onEdit) { Icon(Icons.Filled.Edit, "编辑") }
IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "删除") }
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
Column(Modifier.weight(1f).padding(start = 36.dp)) {
Text("${server.host}:${server.port}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(server.to.ifBlank { "收件人未填" }, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
IconButton(onClick = onMoveUp, enabled = !isFirst) { Icon(Icons.Filled.KeyboardArrowUp, "上移") }
IconButton(onClick = onMoveDown, enabled = !isLast) { Icon(Icons.Filled.KeyboardArrowDown, "下移") }
}
testMsg?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = if (it.startsWith("已发送")) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.error, modifier = Modifier.padding(start = 48.dp, top = 2.dp)) }
}
}
}
private suspend fun testEmail(server: EmailServer): String {
if (server.host.isBlank() || server.to.isBlank()) return "SMTP 主机或收件人未填"
val r = EmailSender.send(server.host, server.port, server.user, server.password, server.from, server.to, "GotMsg 测试", "电邮配置测试")
return if (r.isSuccess) "已发送,请查看邮箱" else "发送失败:${r.exceptionOrNull()?.message}"
}
@Composable @Composable
private fun ServerDialog(initial: BarkServer? = null, onDismiss: () -> Unit, onConfirm: (String, String, String) -> Unit) { private fun ServerDialog(initial: BarkServer? = null, onDismiss: () -> Unit, onConfirm: (String, String, String) -> Unit) {
var name by remember { mutableStateOf(initial?.name ?: "") } var name by remember { mutableStateOf(initial?.name ?: "") }
@@ -416,7 +996,7 @@ private fun ServerDialog(initial: BarkServer? = null, onDismiss: () -> Unit, onC
@Composable @Composable
private fun NtfyConfigDialog(initial: NtfyServer? = null, onDismiss: () -> Unit, onConfirm: (String, String, String, String) -> Unit) { private fun NtfyConfigDialog(initial: NtfyServer? = null, onDismiss: () -> Unit, onConfirm: (String, String, String, String) -> Unit) {
var name by remember { mutableStateOf(initial?.name ?: "") } var name by remember { mutableStateOf(initial?.name ?: "") }
var server by remember { mutableStateOf(initial?.server ?: "https://ntfy.sh") } var server by remember { mutableStateOf(initial?.server ?: NTFY_OFFICIAL_SERVER) }
var topic by remember { mutableStateOf(initial?.topic ?: "") } var topic by remember { mutableStateOf(initial?.topic ?: "") }
var token by remember { mutableStateOf(initial?.token ?: "") } var token by remember { mutableStateOf(initial?.token ?: "") }
ConfigDialogSkeleton(title = if (initial == null) "添加 ntfy" else "编辑 ntfy", onDismiss = onDismiss, onConfirm = { onConfirm(name.trim(), server.trim().removeSuffix("/"), topic.trim(), token.trim()) }) { ConfigDialogSkeleton(title = if (initial == null) "添加 ntfy" else "编辑 ntfy", onDismiss = onDismiss, onConfirm = { onConfirm(name.trim(), server.trim().removeSuffix("/"), topic.trim(), token.trim()) }) {
@@ -430,6 +1010,20 @@ private fun NtfyConfigDialog(initial: NtfyServer? = null, onDismiss: () -> Unit,
} }
} }
@Composable
private fun MeowConfigDialog(initial: MeowServer? = null, onDismiss: () -> Unit, onConfirm: (String, String, String) -> Unit) {
var name by remember { mutableStateOf(initial?.name ?: "") }
var server by remember { mutableStateOf(initial?.server ?: "") }
var key by remember { mutableStateOf(initial?.deviceKey ?: "") }
ConfigDialogSkeleton(title = if (initial == null) "添加 Meow" else "编辑 Meow", onDismiss = onDismiss, onConfirm = { onConfirm(name.trim(), server.trim().removeSuffix("/"), key.trim()) }) {
OutlinedTextField(name, { name = it }, label = { Text("名称") }, singleLine = true, modifier = Modifier.fillMaxWidth())
Spacer(Modifier.size(8.dp))
OutlinedTextField(server, { server = it }, label = { Text("服务器 / API 地址") }, singleLine = true, modifier = Modifier.fillMaxWidth(), supportingText = { Text("填写 Meow 提供的完整 API 地址或服务根地址") })
Spacer(Modifier.size(8.dp))
OutlinedTextField(key, { key = it }, label = { Text("Device Key / Token") }, singleLine = true, modifier = Modifier.fillMaxWidth())
}
}
@Composable @Composable
private fun EmailConfigDialog(initial: EmailServer? = null, onDismiss: () -> Unit, onConfirm: (EmailServer) -> Unit) { private fun EmailConfigDialog(initial: EmailServer? = null, onDismiss: () -> Unit, onConfirm: (EmailServer) -> Unit) {
var name by remember { mutableStateOf(initial?.name ?: "") } var name by remember { mutableStateOf(initial?.name ?: "") }
@@ -482,7 +1076,20 @@ private fun ConfigDialogSkeleton(title: String, onDismiss: () -> Unit, onConfirm
private suspend fun testPush(app: A2iApp, server: BarkServer): String { private suspend fun testPush(app: A2iApp, server: BarkServer): String {
if (server.deviceKey.isBlank()) return "未填写 device key" if (server.deviceKey.isBlank()) return "未填写 device key"
val msg = BarkMessage(deviceKey = server.deviceKey, title = "a2i 测试", body = "如果你在 iOS 看到这条推送,说明配置成功", level = "active") val msg = BarkMessage(deviceKey = server.deviceKey, title = "GotMsg 测试", body = "如果你在 iOS 看到这条推送,说明配置成功", level = "active")
val r = BarkClient(server).push(msg) val r = BarkClient(server).push(msg)
return if (r.isSuccess) "已发送,请查看 iOS 端" else "发送失败:${r.exceptionOrNull()?.message}" return if (r.isSuccess) "已发送,请查看 iOS 端" else "发送失败:${r.exceptionOrNull()?.message}"
} }
private suspend fun testNtfy(server: NtfyServer): String {
if (server.topic.isBlank()) return "未填写 topic"
val r = NtfySender.send(server.server, server.topic, server.token, "GotMsg 测试", "如果你在 ntfy 看到这条推送,说明配置成功")
return if (r.isSuccess) "已发送,请查看 ntfy 接收端" else "发送失败:${r.exceptionOrNull()?.message}"
}
private suspend fun testMeow(server: MeowServer): String {
if (server.server.isBlank()) return "未填写服务器地址"
if (server.deviceKey.isBlank()) return "未填写 Device Key"
val r = MeowSender.send(server.server, server.deviceKey, "GotMsg 测试", "如果你在鸿蒙 Meow 看到这条推送,说明配置成功")
return if (r.isSuccess) "已发送,请查看鸿蒙 Meow" else "发送失败:${r.exceptionOrNull()?.message}"
}
@@ -37,6 +37,7 @@ fun UpdateDialog(info: UpdateInfo, onDismiss: () -> Unit) {
val app = A2iApp.instance val app = A2iApp.instance
val downloading by app.updateChecker.downloading.collectAsState() val downloading by app.updateChecker.downloading.collectAsState()
val progress by app.updateChecker.downloadProgress.collectAsState() val progress by app.updateChecker.downloadProgress.collectAsState()
val downloadSource by app.updateChecker.downloadSource.collectAsState()
var downloadedFile by remember { mutableStateOf<File?>(null) } var downloadedFile by remember { mutableStateOf<File?>(null) }
AlertDialog( AlertDialog(
@@ -70,7 +71,7 @@ fun UpdateDialog(info: UpdateInfo, onDismiss: () -> Unit) {
) )
Spacer(Modifier.size(4.dp)) Spacer(Modifier.size(4.dp))
Text( Text(
"正在下载更新…", "正在下载更新…${downloadSource?.let { "(来自 $it" } ?: ""}",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

+1 -1
View File
@@ -1,3 +1,3 @@
<resources> <resources>
<string name="app_name">a2i</string> <string name="app_name">GotMsg 有消息</string>
</resources> </resources>
Binary file not shown.

After

Width:  |  Height:  |  Size: 521 KiB