diff --git a/CHANGELOG.md b/CHANGELOG.md index e514b40..4bb1868 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## SimBridge 2.5.0 + +Update both apps. Pairing is kept. + +### Main phone +- **No more doubled texts:** every text from the SIM phone carries an id, and a resend of one that + already arrived is dropped (ideas from SMS Gateway for Android's message ids). +- **Rules and spam filter** (Settings > Messages): per sender, keyword or SIM choose *always alert*, + *silent*, *archive* or *block*. Unknown promotions with links go to Archived. +- **Quiet hours with VIP contacts** (Settings > Calls): texts stay silent and calls don't ring at + night, except for the people you pick. +- **App notifications from the SIM phone** (Dashboard > Controls): pick apps such as your bank; + their notifications arrive as messages. +- **Suggested replies** in a chat (full build, made on the phone). +- **Fingerprint lock** for remote screen, USSD and switches, and a **history** of what was changed + on the SIM phone (Settings > App). +- **Encrypted backups:** set a password when exporting (AES-256-GCM); rules, quiet hours, VIP list + and swipe choices are included now. +- **Charge limit** (80–95 %) and **daily report** switches on the dashboard. + +### SIM phone (gateway) +- Resends can't run twice when the main phone registers twice in a row. +- **Hotspot works while on Wi-Fi:** it leaves Wi-Fi and tries again. +- **Watchdog:** restarts itself after a crash or when the system stops it, and tells the main phone. +- **Daily report** at 9:00: battery, signal, data used, anything waiting. +- **Audit log** of remote changes, and **app notification forwarding** (notification access is + granted through Shizuku). + ## SimBridge 2.4.0 Update both apps. Pairing is kept. diff --git a/README.md b/README.md index bb00d94..fa36edb 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,9 @@ main phone only ever uses Wi-Fi. See the [disclaimer](DISCLAIMER.md). | 🎧 **HD voice** | 16 kHz wideband audio between the phones (L16), falling back to normal phone quality (G.711) when needed. | | 🔒 **Encrypted and paired** | Pair once by scanning a QR code. Signalling runs over **TLS** pinned to the SIM phone's key, audio over **SRTP**, and every call or text needs the paired password. Mobile-data and internet addresses are refused. | | 💬 **Texts, pictures and group chats** | A Google Messages-style app: conversations, contact photos, bubbles, notifications with **Reply** and **Mark as read**, **Sent / Delivered** reports, picture messages (MMS) and **group texts**. | +| 🧹 **Rules, spam filter, quiet hours** | Choose who always alerts, stays silent, is archived or blocked; promotions go to Archived; quiet hours let only VIP contacts through. | +| 🔔 **App notifications from the SIM phone** | Your bank or carrier app on the SIM phone? Its notifications arrive as messages on the main phone. | +| 🛡️ **Watchdog, daily report, charge limit** | The gateway restarts itself after a crash, sends a morning health text, and can stop charging at 80–95 %. | | 👆 **Swipe, select, pin, archive, search** | Swipe a conversation (you choose what each direction does), select several for one action, pin, archive, star, search inside messages, tap links and phone numbers, and **send later** by holding Send. | | 📥 **System SMS integration (optional)** | Make SimBridge the **default SMS app**: "Message" buttons in Contacts and other apps open it, the Phone app's *Reply with message* sends through the SIM, and texts are saved to Android's SMS database. Or keep Google Messages as default and just copy relayed texts into it (read-only). | | 📵 **Missed calls while offline** | Calls the SIM phone gets while the main phone is out of reach are added to the Phone app's history with a *Call back* notification. | diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 5a12596..bb590ed 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "io.github.simbridge.gateway" minSdk = 30 targetSdk = 36 - versionCode = 450 - versionName = "2.4.0" + versionCode = 460 + versionName = "2.5.0" // Filter all transitive JNI libraries as well as PJSIP's own module outputs. ndk { //abiFilters += listOf("arm64-v8a", "x86_64") diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1b6d8ed..7d7adca 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -127,6 +127,16 @@ + + + + + + () + + override fun onNotificationPosted(sbn: StatusBarNotification) { + val pkg = sbn.packageName + if (pkg !in chosen(this)) return + val n = sbn.notification + if (n.flags and (Notification.FLAG_ONGOING_EVENT or Notification.FLAG_GROUP_SUMMARY) != 0) return + val e = n.extras + val title = e.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty() + val text = (e.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: e.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty() + if (title.isBlank() && text.isBlank()) return + val body = listOf(title, text).filter { it.isNotBlank() }.joinToString("\n") + // Apps re-post the same notification when it updates; send each text once per 10 minutes. + val now = System.currentTimeMillis() + synchronized(recent) { + val k = "$pkg|$body" + if ((recent[k] ?: 0) > now - 600_000) return + recent[k] = now + while (recent.size > 100) recent.remove(recent.keys.first()) + } + val label = runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(pkg, 0)).toString() }.getOrDefault(pkg) + GatewayRuntime.get(this).forwardAppNotification(label, body) + } + + companion object { + private const val PREFS = "control" + fun chosen(c: Context): Set = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet("notif_apps", emptySet()).orEmpty() + fun choose(c: Context, apps: Set) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet("notif_apps", apps).apply() + const val COMPONENT = "io.github.simbridge.gateway/io.github.sparkcyf.voicesipagent.app.AppNotifications" + } +} diff --git a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayApp.kt b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayApp.kt index 59c8330..a1ca884 100644 --- a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayApp.kt +++ b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayApp.kt @@ -5,9 +5,47 @@ import android.app.Application class GatewayApp : Application() { override fun onCreate() { super.onCreate() + installWatchdog() // Telecom may start our process just to bind the InCallService, so the runtime (and with // it the CellularEndpoint) must exist before any activity or service runs. GatewayRuntime.get(this).start() GatewayService.start(this) } + + /** + * On a crash, ask the system to start us again in 5 s and note it, so the main phone is told. + * Samsung's battery manager can also kill the process; the foreground service and the boot + * receiver bring it back, and [GatewayWatchdog] checks every 15 minutes. + */ + private fun installWatchdog() { + val previous = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { t, e -> + runCatching { + getSharedPreferences("control", MODE_PRIVATE).edit().putBoolean("crashed", true).commit() + val pi = android.app.PendingIntent.getService(this, 7, android.content.Intent(this, GatewayService::class.java), + android.app.PendingIntent.FLAG_IMMUTABLE or android.app.PendingIntent.FLAG_UPDATE_CURRENT) + getSystemService(android.app.AlarmManager::class.java) + .set(android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, android.os.SystemClock.elapsedRealtime() + 5000, pi) + } + previous?.uncaughtException(t, e) + } + GatewayWatchdog.schedule(this) + } +} + +/** Every 15 minutes (even in Doze, with an inexact alarm) makes sure the gateway service runs. */ +class GatewayWatchdog : android.content.BroadcastReceiver() { + override fun onReceive(c: android.content.Context, i: android.content.Intent) { + GatewayService.start(c) + schedule(c) + } + + companion object { + fun schedule(c: android.content.Context) { + val pi = android.app.PendingIntent.getBroadcast(c, 8, android.content.Intent(c, GatewayWatchdog::class.java), + android.app.PendingIntent.FLAG_IMMUTABLE or android.app.PendingIntent.FLAG_UPDATE_CURRENT) + c.getSystemService(android.app.AlarmManager::class.java).setAndAllowWhileIdle( + android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, android.os.SystemClock.elapsedRealtime() + 15 * 60_000L, pi) + } + } } diff --git a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt index f1290f9..bc879e4 100644 --- a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt +++ b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt @@ -26,6 +26,24 @@ import org.json.JSONObject * events this phone reports (missed and blocked calls, SMS delivery). Events wait in a small * persistent queue while no phone is registered. */ +/** Control operations that change something on this phone; each is written to the [Audit] log. */ +private val AUDITED = setOf("control", "ussd", "ussd-reply", "screen-start", "network-mode", "apn-select", "apn-add", "sms-app", + "at-place", "charge-limit", "locate", "block-rules", "voicemail") + +/** Who changed what on this phone, and when (the last 200 entries). */ +object Audit { + private const val MAX = 200 + @Synchronized fun note(ctx: android.content.Context, what: String, from: String?) { + val p = ctx.getSharedPreferences("audit", android.content.Context.MODE_PRIVATE) + val a = runCatching { JSONArray(p.getString("log", "[]")) }.getOrDefault(JSONArray()) + a.put(JSONObject().put("t", System.currentTimeMillis()).put("what", what).put("from", from ?: "")) + while (a.length() > MAX) a.remove(0) + p.edit().putString("log", a.toString()).apply() + } + @Synchronized fun recent(ctx: android.content.Context): JSONArray = + runCatching { JSONArray(ctx.getSharedPreferences("audit", android.content.Context.MODE_PRIVATE).getString("log", "[]")) }.getOrDefault(JSONArray()) +} + class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { private val prefs = app.getSharedPreferences("control", Context.MODE_PRIVATE) private val main = Handler(Looper.getMainLooper()) @@ -34,7 +52,24 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { fun handle(json: String, from: java.net.InetSocketAddress? = null) { val o = runCatching { JSONObject(json) }.getOrNull() ?: return - when (o.optString("op")) { + val op = o.optString("op") + if (op in AUDITED) Audit.note(app, op + (o.optString("action").ifBlank { "" }.let { if (it.isEmpty()) "" else " $it" }) + + (if (o.has("on")) (if (o.optBoolean("on")) " on" else " off") else ""), from?.address?.hostAddress) + when (op) { + "apps" -> rt.worker { send(JSONObject().put("op", "apps").put("list", launchableApps()).put("chosen", JSONArray(AppNotifications.chosen(app).toList())), from) } + "notif-apps" -> rt.worker { + val set = (o.optJSONArray("list") ?: JSONArray()).let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } + AppNotifications.choose(app, set) + // Notification access, granted through Shizuku (same as a tap in Settings). + if (set.isNotEmpty()) privilegedRaw("notif-access", AppNotifications.COMPONENT) + send(JSONObject().put("op", "control-result").put("action", "notif-apps").put("ok", true), from) + } + "audit" -> send(JSONObject().put("op", "audit").put("list", Audit.recent(app)), from) + "charge-limit" -> rt.worker { + privileged("charge-limit", o.optString("value", "off")) + send(status(), from) + } + "report" -> prefs.edit().putBoolean("daily_report", o.optBoolean("on", true)).apply() "status" -> send(status(), from) "ussd" -> ussd(o.optString("code"), o.optInt("sim", 0).takeIf { it > 0 }, from) "ussd-reply" -> rt.worker { ussdReply("", privilegedRaw("ussd-reply", o.optString("text").take(40)), from) } @@ -88,8 +123,14 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { } /** A relayed text that no phone confirmed. */ - fun keepSms(from: String?, text: String, sim: Int?) = - keep(JSONObject().put("op", "__sms").put("from", from ?: "").put("text", text).apply { sim?.let { put("sim", it) } }, false) + fun keepSms(from: String?, text: String, sim: Int?, id: String) = + keep(JSONObject().put("op", "__sms").put("from", from ?: "").put("text", text).put("id", id).apply { sim?.let { put("sim", it) } }, false) + + fun keepApp(app: String, text: String, id: String) = + keep(JSONObject().put("op", "__sms").put("from", "app").put("name", app).put("text", text).put("id", id), false) + + /** Queue entries being sent right now: two registrations a second apart must not send them twice. */ + private val inFlight = java.util.Collections.synchronizedSet(HashSet()) private fun keep(o: JSONObject, big: Boolean) { if (big) { queueBig(o); return } @@ -151,13 +192,19 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { for (i in 0 until q.length()) { val o = q.getJSONObject(i) val qid = o.optLong("qid") + if (!inFlight.add(qid)) continue if (o.optString("op") == "__sms") { val from = o.optString("from").ifBlank { null } - ua.sendMessage(from, o.optString("text"), ContactNames.lookup(app, from), - io.github.sparkcyf.voicesipagent.sip.TextMeta(sim = o.optInt("sim", 0).takeIf { it > 0 })) { ok -> if (ok) unqueue(qid) } + val sent = ua.sendMessage(from, o.optString("text"), o.optString("name").ifBlank { null } ?: ContactNames.lookup(app, from), + io.github.sparkcyf.voicesipagent.sip.TextMeta(ref = o.optString("id").ifBlank { null }, sim = o.optInt("sim", 0).takeIf { it > 0 })) { ok -> + if (ok) unqueue(qid) + inFlight.remove(qid) + } + if (!sent) inFlight.remove(qid) } else { val body = JSONObject(o.toString()).apply { remove("qid") }.toString() - ua.sendControl(body) { code -> if (code in 200..299) unqueue(qid) } + val sent = ua.sendControl(body) { code -> if (code in 200..299) unqueue(qid); inFlight.remove(qid) } + if (!sent) inFlight.remove(qid) } } java.io.File(app.filesDir, "outbox").listFiles()?.sortedBy { it.name }?.forEach { f -> @@ -206,6 +253,8 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { o.put("uptimeMin", SystemClock.elapsedRealtime() / 60_000) o.put("version", runCatching { app.packageManager.getPackageInfo(app.packageName, 0).versionName }.getOrNull() ?: "") o.put("hotspot", hotspotOn()) + privilegedRaw("charge-limit-get", "").takeUnless { it.startsWith("error") }?.let { o.put("chargeLimit", it) } + o.put("dailyReport", prefs.getBoolean("daily_report", true)) o.put("smsApp", MmsGateway.isDefaultSmsApp(app)) o.put("noAnswerSec", noAnswerSec) if (hasPhoneState()) runCatching { app.getSystemService(TelephonyManager::class.java).voiceMailNumber }.getOrNull()?.let { o.put("voicemail", it) } @@ -386,6 +435,44 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { return runCatching { svc.remoteAction(action, arg) }.getOrElse { "error: ${it.message}" } } + /** Apps with a launcher icon on this phone: package and name, sorted by name. */ + private fun launchableApps(): JSONArray { + val pm = app.packageManager + val i = android.content.Intent(android.content.Intent.ACTION_MAIN).addCategory(android.content.Intent.CATEGORY_LAUNCHER) + return JSONArray().apply { + pm.queryIntentActivities(i, 0).map { it.activityInfo.packageName to it.loadLabel(pm).toString() } + .distinctBy { it.first }.filter { it.first != app.packageName }.sortedBy { it.second.lowercase() } + .forEach { (p, l) -> put(JSONObject().put("pkg", p).put("name", l)) } + } + } + + // ------------------------------------------------------------ daily report + + /** Once a day (9:00) a short health text: battery, signal, data used, texts kept for later. */ + private fun scheduleReport() { + val c = java.util.Calendar.getInstance().apply { + set(java.util.Calendar.HOUR_OF_DAY, 9); set(java.util.Calendar.MINUTE, 0); set(java.util.Calendar.SECOND, 0) + if (timeInMillis <= System.currentTimeMillis()) add(java.util.Calendar.DAY_OF_YEAR, 1) + } + main.postDelayed({ rt.worker { runCatching { sendReport() }; scheduleReport() } }, c.timeInMillis - System.currentTimeMillis()) + } + + private fun sendReport() { + if (!prefs.getBoolean("daily_report", true)) return + val s = status() + val lines = mutableListOf("📋 SIM phone daily report") + if (s.has("battery")) lines += "Battery ${s.optInt("battery")} %" + (if (s.optBoolean("charging")) ", charging" else "") + + (s.optString("chargeLimit").takeIf { it.isNotEmpty() && it != "off" }?.let { ", stops at $it %" } ?: "") + s.optJSONArray("sims")?.let { a -> for (i in 0 until a.length()) a.getJSONObject(i).let { sim -> + lines += "SIM ${i + 1}: " + listOf(sim.optString("carrier"), sim.optString("network"), sim.optInt("level", -1).let { if (it < 0) "" else "signal $it/4" }) + .filter { it.isNotBlank() }.joinToString(", ") + } } + if (s.has("dataToday")) lines += "Mobile data today: ${android.text.format.Formatter.formatShortFileSize(app, s.optLong("dataToday"))}, this month ${android.text.format.Formatter.formatShortFileSize(app, s.optLong("dataMonth"))}" + val kept = runCatching { JSONArray(prefs.getString("queue", "[]")).length() }.getOrDefault(0) + if (kept > 0) lines += "$kept items waiting for the main phone" + rt.alerts.post(lines.joinToString("\n")) + } + // ------------------------------------------------------------ remote screen /** Opens the encrypted screen stream socket and tells the phone where and with which key. */ @@ -428,6 +515,11 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { /** Called once when the gateway starts. */ fun start() { + scheduleReport() + if (prefs.getBoolean("crashed", false)) { + prefs.edit().putBoolean("crashed", false).apply() + rt.alerts.post("♻️ SimBridge on the SIM phone stopped unexpectedly and restarted itself.") + } watchWifiLoss() // After a restart away from every saved place: make sure the main phone can reach us. main.postDelayed({ rt.worker { hotspotIfNoWifi("started without Wi-Fi") } }, 45_000) diff --git a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt index b979a4a..af524da 100644 --- a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt +++ b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt @@ -900,15 +900,26 @@ class GatewayRuntime private constructor(context: Context) { } /** Forward an incoming cellular SMS to the registered phone (server mode) as a SIP MESSAGE. */ + /** A notification from an app chosen on the main phone; arrives there as a text from "app". */ + fun forwardAppNotification(app: String, text: String) = worker.execute { + val id = "a" + java.util.UUID.randomUUID().toString().replace("-", "").take(20) + val s = sip + val sent = s is SipUserAgent && s.sendMessage("app", text, app, TextMeta(ref = id)) { ok -> if (!ok) control.keepApp(app, text, id) } + if (!sent) control.keepApp(app, text, id) + } + fun forwardSms(from: String?, text: String, subId: Int? = null) = worker.execute { val s = sip val sim = if (subId != null && Sims.dual(app)) Sims.slotForSubId(app, subId) else null + // One id per received text, kept on every resend: the main phone drops copies it already has + // (a reply lost on the Wi-Fi made the old gateway resend texts that had arrived). + val id = "g" + java.util.UUID.randomUUID().toString().replace("-", "").take(20) // Kept and resent on the next registration unless a phone confirms it. - val sent = s is SipUserAgent && s.sendMessage(from, text, ContactNames.lookup(app, from), TextMeta(sim = sim)) { ok -> - if (!ok) { AppLog.w("SMS not confirmed by any phone: kept for later"); control.keepSms(from, text, sim) } + val sent = s is SipUserAgent && s.sendMessage(from, text, ContactNames.lookup(app, from), TextMeta(ref = id, sim = sim)) { ok -> + if (!ok) { AppLog.w("SMS not confirmed by any phone: kept for later"); control.keepSms(from, text, sim, id) } } if (sent) AppLog.i("SMS forwarded to the registered phone") - else { AppLog.w("SMS kept: no phone registered"); control.keepSms(from, text, sim) } + else { AppLog.w("SMS kept: no phone registered"); control.keepSms(from, text, sim, id) } } /** diff --git a/phone/build.gradle.kts b/phone/build.gradle.kts index 7f9727d..ee1ad94 100644 --- a/phone/build.gradle.kts +++ b/phone/build.gradle.kts @@ -14,8 +14,8 @@ android { applicationId = "io.github.simbridge" minSdk = 34 targetSdk = 36 - versionCode = 250 - versionName = "2.4.0" + versionCode = 260 + versionName = "2.5.0" } // Same signing source as the gateway app: a git-ignored signing.properties in the project root. val localSigning = Properties().apply { @@ -83,5 +83,6 @@ dependencies { "fullImplementation"("com.google.android.gms:play-services-code-scanner:16.1.0") // On-device Turkish/English translation for call captions (offline fallback). "fullImplementation"("com.google.mlkit:translate:17.0.3") + "fullImplementation"("com.google.mlkit:smart-reply:17.0.4") } diff --git a/phone/src/foss/kotlin/io/github/simbridge/SmartReplies.kt b/phone/src/foss/kotlin/io/github/simbridge/SmartReplies.kt new file mode 100644 index 0000000..8eca6b7 --- /dev/null +++ b/phone/src/foss/kotlin/io/github/simbridge/SmartReplies.kt @@ -0,0 +1,6 @@ +package io.github.simbridge + +/** F-Droid build: no Google ML Kit, so no suggested replies. */ +object SmartReplies { + @Suppress("UNUSED_PARAMETER") fun suggest(history: List): List = emptyList() +} diff --git a/phone/src/full/kotlin/io/github/simbridge/SmartReplies.kt b/phone/src/full/kotlin/io/github/simbridge/SmartReplies.kt new file mode 100644 index 0000000..a625338 --- /dev/null +++ b/phone/src/full/kotlin/io/github/simbridge/SmartReplies.kt @@ -0,0 +1,23 @@ +package io.github.simbridge + +import com.google.android.gms.tasks.Tasks +import com.google.mlkit.nl.smartreply.SmartReply +import com.google.mlkit.nl.smartreply.SmartReplySuggestionResult +import com.google.mlkit.nl.smartreply.TextMessage +import java.util.concurrent.TimeUnit + +/** Up to 3 short replies for the conversation, made on this phone (ML Kit; English and a few others). */ +object SmartReplies { + private val client by lazy { SmartReply.getClient() } + + /** Call off the main thread. [history]: oldest first. */ + fun suggest(history: List): List = runCatching { + if (history.isEmpty() || history.last().outgoing) return emptyList() + val conv = history.takeLast(10).filter { it.body.isNotBlank() }.map { m -> + if (m.outgoing) TextMessage.createForLocalUser(m.body, m.time) + else TextMessage.createForRemoteUser(m.body, m.time, m.address) + } + val r = Tasks.await(client.suggestReplies(conv), 3, TimeUnit.SECONDS) + if (r.status != SmartReplySuggestionResult.STATUS_SUCCESS) emptyList() else r.suggestions.map { it.text } + }.getOrDefault(emptyList()) +} diff --git a/phone/src/main/kotlin/io/github/simbridge/Backup.kt b/phone/src/main/kotlin/io/github/simbridge/Backup.kt index c9824a3..ea4d5a0 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Backup.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Backup.kt @@ -15,7 +15,43 @@ import org.json.JSONObject object Backup { private const val FORMAT = "simbridge-backup" - fun export(ctx: Context, to: Uri): Int { + /** Thrown by [import] when the file is encrypted and no (or a wrong) password was given. */ + class PasswordNeeded : Exception("This backup is protected by a password") + + private val MAGIC = "SBX1".toByteArray() + + /** AES-256-GCM with a key from the password (PBKDF2-SHA256, 210 000 rounds, random salt). */ + private fun key(password: String, salt: ByteArray): javax.crypto.SecretKey { + val spec = javax.crypto.spec.PBEKeySpec(password.toCharArray(), salt, 210_000, 256) + val raw = javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded + return javax.crypto.spec.SecretKeySpec(raw, "AES") + } + + internal fun seal(plain: ByteArray, password: String): ByteArray { + val rnd = java.security.SecureRandom() + val salt = ByteArray(16).also(rnd::nextBytes); val iv = ByteArray(12).also(rnd::nextBytes) + val c = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") + c.init(javax.crypto.Cipher.ENCRYPT_MODE, key(password, salt), javax.crypto.spec.GCMParameterSpec(128, iv)) + return MAGIC + salt + iv + c.doFinal(plain) + } + + internal fun open(data: ByteArray, password: String?): ByteArray { + if (data.size < 4 || !data.copyOf(4).contentEquals(MAGIC)) return data // a plain (older) backup + if (password.isNullOrEmpty()) throw PasswordNeeded() + val salt = data.copyOfRange(4, 20); val iv = data.copyOfRange(20, 32) + val c = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") + c.init(javax.crypto.Cipher.DECRYPT_MODE, key(password, salt), javax.crypto.spec.GCMParameterSpec(128, iv)) + return runCatching { c.doFinal(data, 32, data.size - 32) }.getOrElse { throw PasswordNeeded() } + } + + /** Settings that make this phone feel like yours again (no keys or passwords). */ + private val SETTING_KEYS = listOf("swipe_right", "swipe_left", "rules", "spam_filter", "quiet_on", "quiet_start", "quiet_end", + "otp_copy", "live_captions", "lock_controls") + + fun isEncrypted(ctx: Context, uri: Uri): Boolean = + ctx.contentResolver.openInputStream(uri)!!.use { s -> ByteArray(4).also { s.read(it) }.contentEquals(MAGIC) } + + fun export(ctx: Context, to: Uri, password: String? = null): Int { val core = LinkApp.core(ctx) val msgs = core.store.all() val o = JSONObject() @@ -23,7 +59,9 @@ object Backup { .put("settings", JSONObject() .put("mirrorToSystem", core.prefs.mirrorToSystem) .put("autoRecord", core.prefs.autoRecord) - .put("blockHidden", core.prefs.blockHidden)) + .put("blockHidden", core.prefs.blockHidden) + .put("more", core.prefs.export(SETTING_KEYS)) + .put("vip", JSONArray(core.prefs.vip.toList()))) .put("blocked", JSONArray(core.prefs.blocked.toList())) .put("messages", JSONArray().apply { msgs.forEach { m -> @@ -39,20 +77,23 @@ object Backup { if (f.exists() && !has(a.file)) put(a.file, android.util.Base64.encodeToString(f.readBytes(), android.util.Base64.NO_WRAP)) } } }) - ctx.contentResolver.openOutputStream(to, "wt")!!.use { it.write(o.toString().toByteArray()) } + val bytes = o.toString().toByteArray() + ctx.contentResolver.openOutputStream(to, "wt")!!.use { it.write(if (password.isNullOrEmpty()) bytes else seal(bytes, password)) } return msgs.size } /** Merges a backup into this phone; returns how many texts were added (duplicates skipped). */ - fun import(ctx: Context, from: Uri): Int { + fun import(ctx: Context, from: Uri, password: String? = null): Int { val core = LinkApp.core(ctx) - val text = ctx.contentResolver.openInputStream(from)!!.use { it.readBytes().toString(Charsets.UTF_8) } + val text = open(ctx.contentResolver.openInputStream(from)!!.use { it.readBytes() }, password).toString(Charsets.UTF_8) val o = JSONObject(text) require(o.optString("format") == FORMAT) { "Not a SimBridge backup" } o.optJSONObject("settings")?.let { s -> core.prefs.mirrorToSystem = s.optBoolean("mirrorToSystem", core.prefs.mirrorToSystem) core.prefs.autoRecord = s.optBoolean("autoRecord", core.prefs.autoRecord) core.prefs.blockHidden = s.optBoolean("blockHidden", core.prefs.blockHidden) + s.optJSONObject("more")?.let { core.prefs.import(it, SETTING_KEYS) } + s.optJSONArray("vip")?.let { a -> core.prefs.vip = core.prefs.vip + (0 until a.length()).map { a.getString(it) } } } o.optJSONObject("files")?.let { files -> val dir = java.io.File(ctx.filesDir, "mms").apply { mkdirs() } diff --git a/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt b/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt index 2b632c4..1daa436 100644 --- a/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt +++ b/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt @@ -43,6 +43,7 @@ data class LinkStatus( class LinkCore(val context: Context) { val prefs = Prefs(context) val store = MessageStore(context) + private val seen = SeenIds(context) val contacts = Contacts(context) val notifier = Notifier(context, this) val control = PhoneControl(this) @@ -210,7 +211,7 @@ class LinkCore(val context: Context) { sipLog, ).apply { setIncomingCallHandler { leg -> onIncomingCall(leg) } - incomingMessageHandler = { number, name, text, meta -> onIncomingText(number, name, text, meta.sim ?: 0); true } + incomingMessageHandler = { number, name, text, meta -> onIncomingText(number, name, text, meta.sim ?: 0, meta.ref); true } controlHandler = { json, _ -> control.handle(json) } addStatusListener { _, _ -> kick() } start() @@ -247,8 +248,15 @@ class LinkCore(val context: Context) { private fun onIncomingCall(leg: CallLeg) { legs[leg.id] = leg lastIncomingLeg = leg.id - leg.ring() val number = leg.remote.number ?: "" + // Quiet hours: only VIP contacts ring; the others go on to voicemail or a missed call. + if (Quiet.now(prefs) && !prefs.isVip(number)) { + Log.i("quiet hours: call not rung") + legs.remove(leg.id) + leg.hangup(HangupCause.BUSY) + return + } + leg.ring() Log.i("incoming call relayed by the SIM phone") val tm = context.getSystemService(TelecomManager::class.java) val inner = Bundle().apply { putString(Telecom.EXTRA_LEG, leg.id) } @@ -281,20 +289,31 @@ class LinkCore(val context: Context) { } /** Also used by adb tests (ControlReceiver op "test-in"). */ - fun onIncomingText(number: String?, name: String?, text: String, sim: Int = 0) { + fun onIncomingText(number: String?, name: String?, text: String, sim: Int = 0, id: String? = null) { + // Same id = a resend of a text that already arrived (its confirmation was lost on the way). + if (id != null && !seen.add(id)) { Log.i("resent text dropped"); return } if (number != "gateway" && prefs.isBlocked(number)) { Log.i("text from a blocked number dropped"); return } val address = when { number.isNullOrBlank() || number == "sms" -> name ?: "Unknown" + number == "app" -> name ?: "App" // a notification forwarded from an app on the SIM phone number == "gateway" -> "SimBridge Gateway" else -> number } // The SIM phone resends a text when it got no confirmation, even if the first copy arrived. if (store.isRecentDuplicate(address, text)) { Log.i("duplicate text dropped"); return } + val rule = if (number == "gateway" || number == "app") null + else Rules.decide(prefs, address, contacts.lookup(address)?.name, text, sim) + if (rule?.action == Rules.Action.BLOCK) { Log.i("text dropped by a rule"); return } val time = System.currentTimeMillis() - val id = store.add(address, text, outgoing = false, status = Msg.RECEIVED, time = time, sim = sim) - if (number != "gateway") mirror(id, address, text, time, outgoing = false) + val msgId = store.add(address, text, outgoing = false, status = Msg.RECEIVED, time = time, sim = sim) + if (number != "gateway" && number != "app") mirror(msgId, address, text, time, outgoing = false) if (prefs.otpCopy) Otp.find(text)?.let { Otp.copy(context, it) } - notifier.showMessages(MessageStore.keyOf(address), address) + val key = MessageStore.keyOf(address) + when (rule?.action) { + Rules.Action.ARCHIVE -> { store.setArchived(setOf(key), true); Log.i("text archived (${rule.why})") } + Rules.Action.SILENT -> notifier.showMessages(key, address, silent = true) + else -> notifier.showMessages(key, address) + } } private fun mirror(id: Long, address: String, text: String, time: Long, outgoing: Boolean) { diff --git a/phone/src/main/kotlin/io/github/simbridge/Notifier.kt b/phone/src/main/kotlin/io/github/simbridge/Notifier.kt index 0a3e08b..97f1c2a 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Notifier.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Notifier.kt @@ -21,6 +21,7 @@ class Notifier(private val context: Context, private val core: LinkCore) { nm.createNotificationChannel(NotificationChannel(CH_MESSAGES, context.getString(R.string.ch_messages), NotificationManager.IMPORTANCE_HIGH).apply { description = context.getString(R.string.ch_messages_d) }) + nm.createNotificationChannel(NotificationChannel(CH_QUIET, context.getString(R.string.ch_quiet), NotificationManager.IMPORTANCE_LOW)) nm.createNotificationChannel(NotificationChannel(CH_STATUS, context.getString(R.string.ch_status), NotificationManager.IMPORTANCE_MIN).apply { setShowBadge(false) }) @@ -53,7 +54,8 @@ class Notifier(private val context: Context, private val core: LinkCore) { .build() } - fun showMessages(key: String, address: String) { + /** [silent]: update the conversation's notification without sound or pop-up (rules, quiet hours). */ + fun showMessages(key: String, address: String, silent: Boolean = false) { val unread = core.store.unreadIn(key) if (unread.isEmpty()) { nm.cancel(key.hashCode()); return } val info = core.contacts.lookup(address) @@ -100,7 +102,7 @@ class Notifier(private val context: Context, private val core: LinkCore) { .setCategories(setOf("android.shortcut.conversation")) .setIntent(open).build()) } - val n = Notification.Builder(context, CH_MESSAGES) + val n = Notification.Builder(context, if (silent) CH_QUIET else CH_MESSAGES) .setSmallIcon(R.drawable.ic_link) .setShortcutId("c:$key") .setLocusId(android.content.LocusId("c:$key")) @@ -219,6 +221,7 @@ class Notifier(private val context: Context, private val core: LinkCore) { companion object { const val CH_MESSAGES = "messages" + const val CH_QUIET = "messages_quiet" const val CH_STATUS = "status" const val CH_ALERTS = "alerts" const val CH_MIC = "mic" diff --git a/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt b/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt index 11a995b..43ab179 100644 --- a/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt +++ b/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt @@ -26,6 +26,9 @@ data class GatewayStatus( /** Minutes until empty (from real drain) or until full; null while not known yet. */ val batteryMin: Int? = null, val chargeMin: Int? = null, + /** Samsung battery protection: "off", or the percent charging stops at. Null when unknown. */ + val chargeLimit: String? = null, + val dailyReport: Boolean = true, val powerSaver: Boolean, val dataOn: Boolean, val hotspot: Boolean, @@ -49,6 +52,8 @@ data class GatewayStatus( charging = o.optBoolean("charging"), batteryMin = if (o.has("batteryMin")) o.optInt("batteryMin") else null, chargeMin = if (o.has("chargeMin")) o.optInt("chargeMin") else null, + chargeLimit = o.optString("chargeLimit").ifBlank { null }, + dailyReport = o.optBoolean("dailyReport", true), powerSaver = o.optBoolean("powerSaver"), dataOn = o.optBoolean("dataOn"), hotspot = o.optBoolean("hotspot"), @@ -121,6 +126,12 @@ class PhoneControl(private val core: LinkCore) { "mms" -> core.onIncomingMms(o) "data-detail" -> _dataDetail.value = DataDetail.parse(o) "screen-ready" -> _screen.value = ScreenOffer.parse(o) + "apps" -> _apps.value = (o.optJSONArray("list") ?: JSONArray()).let { a -> + (0 until a.length()).map { a.getJSONObject(it).let { e -> e.optString("pkg") to e.optString("name") } } + } to (o.optJSONArray("chosen") ?: JSONArray()).let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } + "audit" -> _audit.value = (o.optJSONArray("list") ?: JSONArray()).let { a -> + (0 until a.length()).map { a.getJSONObject(it).let { e -> AuditEntry(e.optLong("t"), e.optString("what"), e.optString("from")) } } + } "speed-ready" -> _speed.value = o.optInt("port") to o.optString("token") "wifi-saved" -> _savedWifi.value = (o.optJSONArray("list") ?: JSONArray()).let { a -> (0 until a.length()).map { a.getString(it) } } "apns" -> _apns.value = (o.optJSONArray("list") ?: JSONArray()).let { a -> @@ -226,6 +237,19 @@ class PhoneControl(private val core: LinkCore) { send(JSONObject().put("op", "apn-add").put("name", name).put("apn", apn).put("mcc", mcc).put("mnc", mnc) .put("user", user).put("password", password)) fun setNoAnswer(seconds: Int) = send(JSONObject().put("op", "voicemail").put("seconds", seconds)) + fun setChargeLimit(value: String) = send(JSONObject().put("op", "charge-limit").put("value", value)) + fun setDailyReport(on: Boolean) = send(JSONObject().put("op", "report").put("on", on)).also { refresh() } + + /** Changes made on the SIM phone (who and when), newest last. */ + private val _audit = MutableStateFlow>(emptyList()) + val audit: StateFlow> = _audit + fun loadAudit() = send(JSONObject().put("op", "audit")) + + /** Apps on the SIM phone (package, name) and those whose notifications are forwarded. */ + private val _apps = MutableStateFlow>, Set>?>(null) + val apps: StateFlow>, Set>?> = _apps + fun loadApps() { _apps.value = null; send(JSONObject().put("op", "apps")) } + fun setNotifApps(pkgs: Set) = send(JSONObject().put("op", "notif-apps").put("list", JSONArray(pkgs.toList()))) private val _audioTest = MutableStateFlow(null) /** Result of the last audio self-test, in plain words. */ @@ -358,3 +382,6 @@ class ScreenOffer(val port: Int, val key: String, val ivDown: String, val ivUp: /** A Wi-Fi network where both phones should use Wi-Fi instead of the hotspot. */ data class Place(val name: String, val ssid: String, val password: String) + +/** One change on the SIM phone: when, what, and from which address. */ +data class AuditEntry(val at: Long, val what: String, val from: String) diff --git a/phone/src/main/kotlin/io/github/simbridge/Prefs.kt b/phone/src/main/kotlin/io/github/simbridge/Prefs.kt index bb1578b..ac8f58f 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Prefs.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Prefs.kt @@ -89,6 +89,43 @@ class Prefs(context: Context) { get() = p.getBoolean("places_auto", false) set(v) = p.edit().putBoolean("places_auto", v).apply() + /** Message rules (JSON, see [Rules]), spam filter, quiet hours (minutes of the day) and VIP numbers. */ + var rules: String + get() = p.getString("rules", "[]")!! + set(v) = p.edit().putString("rules", v).apply() + var spamFilter: Boolean + get() = p.getBoolean("spam_filter", true) + set(v) = p.edit().putBoolean("spam_filter", v).apply() + var quietOn: Boolean + get() = p.getBoolean("quiet_on", false) + set(v) = p.edit().putBoolean("quiet_on", v).apply() + var quietStart: Int + get() = p.getInt("quiet_start", 23 * 60) + set(v) = p.edit().putInt("quiet_start", v).apply() + var quietEnd: Int + get() = p.getInt("quiet_end", 7 * 60) + set(v) = p.edit().putInt("quiet_end", v).apply() + var vip: Set + get() = p.getStringSet("vip", emptySet()).orEmpty().toSortedSet() + set(v) = p.edit().putStringSet("vip", v.toSet()).apply() + fun isVip(number: String?) = vip.any { io.github.sparkcyf.voicesipagent.voice.PhoneNumbers.same(number, it) } + /** Ask for the fingerprint before remote screen, USSD and switches on the SIM phone. */ + var lockControls: Boolean + get() = p.getBoolean("lock_controls", false) + set(v) = p.edit().putBoolean("lock_controls", v).apply() + + /** Plain settings by key, for backups (strings, booleans and numbers only). */ + fun export(keys: List): org.json.JSONObject = org.json.JSONObject().apply { + keys.forEach { k -> p.all[k]?.let { v -> if (v is String || v is Boolean || v is Int || v is Long) put(k, v) } } + } + fun import(o: org.json.JSONObject, keys: List) { + val e = p.edit() + keys.filter { o.has(it) }.forEach { k -> + when (val v = o.get(k)) { is Boolean -> e.putBoolean(k, v); is Int -> e.putInt(k, v); is Long -> e.putLong(k, v); is String -> e.putString(k, v) } + } + e.apply() + } + /** What a swipe on a conversation does: "read", "archive", "delete", "pin" or "none". */ var swipeRight: String get() = p.getString("swipe_right", "read")!! diff --git a/phone/src/main/kotlin/io/github/simbridge/Rules.kt b/phone/src/main/kotlin/io/github/simbridge/Rules.kt new file mode 100644 index 0000000..868a128 --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/Rules.kt @@ -0,0 +1,72 @@ +package io.github.simbridge + +import org.json.JSONArray +import org.json.JSONObject +import java.util.Calendar + +/** + * What happens to an incoming text: rules first (sender, keyword, SIM), then the spam filter, + * then quiet hours. Each rule's action: ALERT (always notify, even in quiet hours), SILENT (keep, + * no sound), ARCHIVE (keep out of the list, no notification), BLOCK (drop). + */ +object Rules { + enum class Action { ALERT, SILENT, ARCHIVE, BLOCK } + + /** [from]: part of the number or contact name (empty = anyone); [word]: part of the text. */ + data class Rule(val from: String, val word: String, val sim: Int, val action: Action) { + fun json(): JSONObject = JSONObject().put("from", from).put("word", word).put("sim", sim).put("action", action.name) + + fun matches(number: String, name: String?, text: String, simSlot: Int): Boolean = + (from.isBlank() || number.contains(from.filter { it.isDigit() || it == '+' }.ifEmpty { "\u0000" }) || + name?.contains(from, ignoreCase = true) == true) && + (word.isBlank() || text.contains(word, ignoreCase = true)) && + (sim == 0 || sim == simSlot) + + companion object { + fun parse(o: JSONObject) = Rule(o.optString("from"), o.optString("word"), o.optInt("sim"), + runCatching { Action.valueOf(o.optString("action")) }.getOrDefault(Action.SILENT)) + } + } + + fun load(json: String): List = runCatching { JSONArray(json) }.getOrDefault(JSONArray()) + .let { a -> (0 until a.length()).map { Rule.parse(a.getJSONObject(it)) } } + + fun save(list: List): String = JSONArray().apply { list.forEach { put(it.json()) } }.toString() + + /** The decision for one text; null = the normal behaviour. */ + data class Decision(val action: Action, val why: String) + + fun decide(prefs: Prefs, number: String, name: String?, text: String, sim: Int, now: Calendar = Calendar.getInstance()): Decision? { + load(prefs.rules).firstOrNull { it.matches(number, name, text, sim) }?.let { return Decision(it.action, "rule") } + val vip = prefs.isVip(number) + if (prefs.spamFilter && !vip && name == null && Spam.looksLike(number, text)) return Decision(Action.ARCHIVE, "spam") + if (!vip && Quiet.now(prefs, now)) return Decision(Action.SILENT, "quiet") + return null + } +} + +/** Unknown senders with promotion words or links (codes are never spam). */ +object Spam { + private val WORDS = Regex("(?i)(kampanya|indirim|fırsat|kazandınız|hediye|bonus|bahis|casino|kredi\\s*başvur|tıkla|" + + "promo|discount|winner|you won|free gift|claim now|bet|loan offer|unsubscribe|iptal için|ret\\s*yaz|smsiptal)") + private val LINK = Regex("(?i)(https?://|www\\.|\\b[a-z0-9-]+\\.(?:ly|gl|cc|xyz|top|click|link|site|info)\\b/?)") + + fun looksLike(number: String, text: String): Boolean { + if (Otp.find(text) != null) return false + // Alphanumeric senders (brands) and short codes are where promotions come from. + val bulk = number.any { it.isLetter() } || number.count { it.isDigit() } in 3..6 + val words = WORDS.containsMatchIn(text) + val link = LINK.containsMatchIn(text) + return words && (link || bulk) || (link && bulk) + } +} + +/** Quiet hours: notifications and calls stay silent between two times (VIP contacts excepted). */ +object Quiet { + fun now(prefs: Prefs, c: Calendar = Calendar.getInstance()): Boolean { + if (!prefs.quietOn) return false + val m = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE) + val s = prefs.quietStart; val e = prefs.quietEnd + return if (s <= e) m in s until e else m >= s || m < e // across midnight: 22:00–07:00 + } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/SeenIds.kt b/phone/src/main/kotlin/io/github/simbridge/SeenIds.kt new file mode 100644 index 0000000..ff45f84 --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/SeenIds.kt @@ -0,0 +1,19 @@ +package io.github.simbridge + +import android.content.Context + +/** Ids of texts already received from the SIM phone (the last [MAX]), kept across restarts. */ +class SeenIds(context: Context) { + private val p = context.getSharedPreferences("seen_ids", Context.MODE_PRIVATE) + private val ids = LinkedHashSet(p.getString("ids", "").orEmpty().split(',').filter { it.isNotBlank() }) + + /** True if [id] is new (and now remembered); false for a copy. */ + @Synchronized fun add(id: String): Boolean { + if (!ids.add(id)) return false + while (ids.size > MAX) ids.remove(ids.first()) + p.edit().putString("ids", ids.joinToString(",")).apply() + return true + } + + private companion object { const val MAX = 500 } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt index 2bf0104..a1cad71 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt @@ -1,6 +1,7 @@ package io.github.simbridge.ui import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll import androidx.compose.material.icons.automirrored.filled.Forward import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Schedule @@ -103,6 +104,11 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin val version by core.store.version.collectAsState() val status by core.status.collectAsState() var msgs by remember { mutableStateOf(emptyList()) } + // Suggested replies to the last incoming text (made on this phone). + var suggestions by remember { mutableStateOf(emptyList()) } + LaunchedEffect(msgs.lastOrNull()?.id) { + suggestions = withContext(Dispatchers.Default) { io.github.simbridge.SmartReplies.suggest(msgs) } + } var draft by remember(key) { mutableStateOf(initialDraft) } var menu by remember { mutableStateOf(false) } // Long-press a bubble to select it; then tap others (copy, star, forward, details, delete). @@ -203,6 +209,13 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin IconButton({ core.store.unschedule(sc.id) }) { Icon(Icons.Filled.Close, stringResource(R.string.cancel)) } } } + if (suggestions.isNotEmpty() && draft.isEmpty() && pending.isEmpty()) + Row(Modifier.fillMaxWidth().horizontalScroll(androidx.compose.foundation.rememberScrollState()).padding(horizontal = 12.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp)) { + suggestions.forEach { t -> + androidx.compose.material3.SuggestionChip({ core.sendText(address, t); suggestions = emptyList() }, label = { Text(t) }) + } + } Composer(draft, { draft = it }, connected = status.state == LinkState.CONNECTED, onSchedule = { if (draft.isNotBlank() && pending.isEmpty()) scheduleAsk = true }, pending = pending, onAttach = { diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/DashboardExtras.kt b/phone/src/main/kotlin/io/github/simbridge/ui/DashboardExtras.kt index 6ad1bc3..736b28f 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/DashboardExtras.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/DashboardExtras.kt @@ -1,5 +1,8 @@ package io.github.simbridge.ui +import androidx.compose.material.icons.filled.Notifications +import androidx.compose.foundation.layout.heightIn +import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.PhoneMissed import androidx.compose.foundation.layout.FlowRow @@ -230,3 +233,38 @@ fun MissedCalls(core: LinkCore) { } } } + +/** Pick apps on the SIM phone whose notifications come here as messages. */ +@Composable +fun AppNotifSection(core: LinkCore, online: Boolean) { + val apps by core.control.apps.collectAsState() + var open by remember { mutableStateOf(false) } + var picked by remember { mutableStateOf?>(null) } + Section(Icons.Filled.Notifications, stringResource(R.string.notif_title), Tint.Purple) { + Muted(stringResource(R.string.notif_sub)) + TextButton({ core.control.loadApps(); picked = null; open = true }, enabled = online) { Text(stringResource(R.string.notif_choose)) } + } + if (open) { + val list = apps + val sel = picked ?: list?.second ?: emptySet() + AlertDialog( + onDismissRequest = { open = false }, + title = { Text(stringResource(R.string.notif_title)) }, + text = { + if (list == null) LinearProgressIndicator(Modifier.fillMaxWidth()) + else androidx.compose.foundation.lazy.LazyColumn(Modifier.heightIn(max = 420.dp)) { + items(list.first.size) { i -> + val (pkg, name) = list.first[i] + Row(Modifier.fillMaxWidth().clickable { picked = if (pkg in sel) sel - pkg else sel + pkg }, + verticalAlignment = Alignment.CenterVertically) { + androidx.compose.material3.Checkbox(pkg in sel, { picked = if (it) sel + pkg else sel - pkg }) + Text(name) + } + } + } + }, + confirmButton = { TextButton({ core.control.setNotifApps(sel); open = false }, enabled = list != null) { Text(stringResource(R.string.save)) } }, + dismissButton = { TextButton({ open = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/Guard.kt b/phone/src/main/kotlin/io/github/simbridge/ui/Guard.kt new file mode 100644 index 0000000..cb1230a --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/ui/Guard.kt @@ -0,0 +1,51 @@ +package io.github.simbridge.ui + +import android.content.Context +import android.content.ContextWrapper +import android.hardware.biometrics.BiometricManager +import android.hardware.biometrics.BiometricPrompt +import android.os.CancellationSignal +import androidx.activity.ComponentActivity +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalContext +import io.github.simbridge.LinkCore +import io.github.simbridge.R + +/** + * Runs an action on the SIM phone only after the fingerprint (or screen lock) when "Lock SIM + * phone controls" is on. One unlock is good for 2 minutes. + */ +@Composable +fun rememberGuard(core: LinkCore): (() -> Unit) -> Unit { + val ctx = LocalContext.current + return remember(core) { { action -> Guard.run(ctx, core, action) } } +} + +internal object Guard { + @Volatile private var okUntil = 0L + + fun run(ctx: Context, core: LinkCore, action: () -> Unit) { + if (!core.prefs.lockControls || System.currentTimeMillis() < okUntil) { action(); return } + val auth = BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL + // No lock set up on this phone: nothing to ask for. + if (ctx.getSystemService(BiometricManager::class.java).canAuthenticate(auth) != BiometricManager.BIOMETRIC_SUCCESS) { action(); return } + BiometricPrompt.Builder(ctx) + .setTitle(ctx.getString(R.string.guard_title)) + .setSubtitle(ctx.getString(R.string.guard_sub)) + .setAllowedAuthenticators(auth) + .build() + .authenticate(CancellationSignal(), ctx.mainExecutor, object : BiometricPrompt.AuthenticationCallback() { + override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { + okUntil = System.currentTimeMillis() + 120_000 + action() + } + }) + } + + tailrec fun activity(c: Context): ComponentActivity? = when (c) { + is ComponentActivity -> c + is ContextWrapper -> activity(c.baseContext) + else -> null + } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/MoreSettings.kt b/phone/src/main/kotlin/io/github/simbridge/ui/MoreSettings.kt new file mode 100644 index 0000000..e694d64 --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/ui/MoreSettings.kt @@ -0,0 +1,170 @@ +package io.github.simbridge.ui + +import android.app.TimePickerDialog +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.FilterAlt +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.Lock +import androidx.compose.material.icons.filled.NightsStay +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +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.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import io.github.simbridge.LinkCore +import io.github.simbridge.R +import io.github.simbridge.Rules + +private fun hm(m: Int) = "%02d:%02d".format(m / 60, m % 60) + +/** Settings > Messages: spam filter and rules for who notifies, stays silent, is archived or blocked. */ +@Composable +fun RulesCard(core: LinkCore) { + val prefs = core.prefs + var spam by remember { mutableStateOf(prefs.spamFilter) } + var rules by remember { mutableStateOf(Rules.load(prefs.rules)) } + var adding by remember { mutableStateOf(false) } + fun save(l: List) { rules = l; prefs.rules = Rules.save(l) } + Card(Icons.Filled.FilterAlt, stringResource(R.string.rules_title), stringResource(R.string.rules_text), ok = true) { + Column { + SwitchRow(stringResource(R.string.rules_spam), spam) { spam = it; prefs.spamFilter = it } + rules.forEach { r -> + Row(verticalAlignment = Alignment.CenterVertically) { + Text(listOfNotNull(r.from.ifBlank { null }, r.word.ifBlank { null }?.let { "“$it”" }, if (r.sim > 0) "SIM ${r.sim}" else null) + .joinToString(" · ").ifEmpty { stringResource(R.string.rules_anyone) } + " → " + stringResource(actionLabel(r.action)), + Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium) + IconButton({ save(rules - r) }) { Icon(Icons.Filled.Close, stringResource(R.string.remove)) } + } + } + TextButton({ adding = true }) { Text(stringResource(R.string.rules_add)) } + } + } + if (adding) { + var from by remember { mutableStateOf("") } + var word by remember { mutableStateOf("") } + var sim by remember { mutableStateOf(0) } + var action by remember { mutableStateOf(Rules.Action.SILENT) } + AlertDialog( + onDismissRequest = { adding = false }, + title = { Text(stringResource(R.string.rules_add)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + OutlinedTextField(from, { from = it }, singleLine = true, label = { Text(stringResource(R.string.rules_from)) }) + OutlinedTextField(word, { word = it }, singleLine = true, label = { Text(stringResource(R.string.rules_word)) }) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + listOf(0, 1, 2).forEach { n -> FilterChip(sim == n, { sim = n }, label = { Text(if (n == 0) stringResource(R.string.rules_any_sim) else "SIM $n") }) } + } + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Rules.Action.entries.forEach { a -> FilterChip(action == a, { action = a }, label = { Text(stringResource(actionLabel(a))) }) } + } + } + }, + confirmButton = { + TextButton({ save(rules + Rules.Rule(from.trim(), word.trim(), sim, action)); adding = false }, + enabled = from.isNotBlank() || word.isNotBlank()) { Text(stringResource(R.string.add)) } + }, + dismissButton = { TextButton({ adding = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +private fun actionLabel(a: Rules.Action) = when (a) { + Rules.Action.ALERT -> R.string.rules_alert + Rules.Action.SILENT -> R.string.rules_silent + Rules.Action.ARCHIVE -> R.string.act_archive + Rules.Action.BLOCK -> R.string.block +} + +/** Settings > Calls: quiet hours and the VIP contacts who still get through. */ +@Composable +fun QuietCard(core: LinkCore) { + val ctx = LocalContext.current + val prefs = core.prefs + var on by remember { mutableStateOf(prefs.quietOn) } + var start by remember { mutableStateOf(prefs.quietStart) } + var end by remember { mutableStateOf(prefs.quietEnd) } + var vip by remember { mutableStateOf(prefs.vip) } + var adding by remember { mutableStateOf(false) } + fun pick(m: Int, set: (Int) -> Unit) = TimePickerDialog(ctx, { _, h, mi -> set(h * 60 + mi) }, m / 60, m % 60, true).show() + Card(Icons.Filled.NightsStay, stringResource(R.string.quiet_title), stringResource(R.string.quiet_text), ok = true) { + Column { + SwitchRow(stringResource(R.string.quiet_on), on) { on = it; prefs.quietOn = it } + Row(verticalAlignment = Alignment.CenterVertically) { + TextButton({ pick(start) { start = it; prefs.quietStart = it } }) { Text(stringResource(R.string.quiet_from, hm(start))) } + TextButton({ pick(end) { end = it; prefs.quietEnd = it } }) { Text(stringResource(R.string.quiet_to, hm(end))) } + } + Text(stringResource(R.string.quiet_vip), style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 6.dp)) + vip.forEach { n -> + Row(verticalAlignment = Alignment.CenterVertically) { + Text(core.contacts.lookup(n)?.name ?: n, Modifier.weight(1f)) + IconButton({ vip = vip - n; prefs.vip = vip }) { Icon(Icons.Filled.Close, stringResource(R.string.remove)) } + } + } + TextButton({ adding = true }) { Text(stringResource(R.string.quiet_add_vip)) } + } + } + if (adding) { + var n by remember { mutableStateOf("") } + AlertDialog( + onDismissRequest = { adding = false }, + title = { Text(stringResource(R.string.quiet_add_vip)) }, + text = { OutlinedTextField(n, { n = it }, singleLine = true, label = { Text(stringResource(R.string.quiet_number)) }) }, + confirmButton = { TextButton({ vip = vip + n.trim(); prefs.vip = vip; adding = false }, enabled = n.count { it.isDigit() } >= 3) { Text(stringResource(R.string.add)) } }, + dismissButton = { TextButton({ adding = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +/** Settings > App: the fingerprint lock, and the list of changes made on the SIM phone. */ +@Composable +fun SecurityExtrasCard(core: LinkCore) { + val ctx = LocalContext.current + var lock by remember { mutableStateOf(core.prefs.lockControls) } + var showLog by remember { mutableStateOf(false) } + val audit by core.control.audit.collectAsState() + Card(Icons.Filled.Lock, stringResource(R.string.guard_card), stringResource(R.string.guard_card_text), ok = true) { + Column { + SwitchRow(stringResource(R.string.guard_switch), lock) { lock = it; core.prefs.lockControls = it } + TextButton({ core.control.loadAudit(); showLog = true }) { + Icon(Icons.Filled.History, null); Text(" " + stringResource(R.string.audit_title)) + } + } + } + if (showLog) AlertDialog( + onDismissRequest = { showLog = false }, + title = { Text(stringResource(R.string.audit_title)) }, + text = { + androidx.compose.foundation.lazy.LazyColumn { + if (audit.isEmpty()) item { Text(stringResource(R.string.audit_none)) } + items(audit.reversed().size) { i -> + val e = audit.reversed()[i] + Text(android.text.format.DateUtils.formatDateTime(ctx, e.at, + android.text.format.DateUtils.FORMAT_SHOW_DATE or android.text.format.DateUtils.FORMAT_SHOW_TIME) + " " + e.what + + (if (e.from.isNotBlank()) " · " + e.from else ""), style = MaterialTheme.typography.bodySmall, + modifier = Modifier.fillMaxWidth().padding(vertical = 3.dp)) + } + } + }, + confirmButton = { TextButton({ showLog = false }) { Text(stringResource(R.string.ok)) } }, + ) +} diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt index f909ec2..1e6c66e 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt @@ -129,16 +129,21 @@ fun SettingsScreen(core: LinkCore, onSimPhone: () -> Unit = {}, onBlocked: () -> var mirrorOn by remember { mutableStateOf(core.prefs.mirrorToSystem) } val paired = remember(tick) { core.prefs.paired } var autoRec by remember { mutableStateOf(core.prefs.autoRecord) } + var backupPw by remember { mutableStateOf(null) } + var pwAsk by remember { mutableStateOf?>(null) } val exportLauncher = androidx.activity.compose.rememberLauncherForActivityResult( - androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json")) { uri -> + androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/octet-stream")) { uri -> uri ?: return@rememberLauncherForActivityResult - val r = runCatching { io.github.simbridge.Backup.export(ctx, uri) } + val r = runCatching { io.github.simbridge.Backup.export(ctx, uri, backupPw) } + backupPw = null android.widget.Toast.makeText(ctx, r.fold({ "Exported $it texts" }, { "Export failed: ${it.message}" }), android.widget.Toast.LENGTH_LONG).show() } val importLauncher = androidx.activity.compose.rememberLauncherForActivityResult( androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri -> uri ?: return@rememberLauncherForActivityResult + // An encrypted file: ask for its password, then import. + if (runCatching { io.github.simbridge.Backup.isEncrypted(ctx, uri) }.getOrDefault(false)) { pwAsk = "import" to uri; return@rememberLauncherForActivityResult } val r = runCatching { io.github.simbridge.Backup.import(ctx, uri) } android.widget.Toast.makeText(ctx, r.fold({ "Imported $it texts" }, { "Import failed: ${it.message}" }), android.widget.Toast.LENGTH_LONG).show() @@ -197,6 +202,7 @@ fun SettingsScreen(core: LinkCore, onSimPhone: () -> Unit = {}, onBlocked: () -> modifier = Modifier.padding(horizontal = 8.dp)) } if (tab == 1) { + QuietCard(core) Card(Icons.Filled.Phone, stringResource(R.string.set_calls), if (accountOn) stringResource(R.string.set_calls_on) else stringResource(R.string.set_calls_off), @@ -252,6 +258,7 @@ fun SettingsScreen(core: LinkCore, onSimPhone: () -> Unit = {}, onBlocked: () -> color = MaterialTheme.colorScheme.onSurfaceVariant) } } + RulesCard(core) Card(Icons.Filled.Sms, stringResource(R.string.set_swipe), stringResource(R.string.set_swipe_text), ok = true) { Column { SwipePicker(stringResource(R.string.set_swipe_right), core.prefs.swipeRight) { core.prefs.swipeRight = it } @@ -268,12 +275,42 @@ fun SettingsScreen(core: LinkCore, onSimPhone: () -> Unit = {}, onBlocked: () -> Card(Icons.Filled.Sms, stringResource(R.string.set_backup), stringResource(R.string.set_backup_text), ok = true) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - FilledTonalButton({ exportLauncher.launch("simbridge-backup-${java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US).format(java.util.Date())}.json") }) { Text("Export") } + FilledTonalButton({ pwAsk = "export" to null }) { Text("Export") } TextButton({ importLauncher.launch(arrayOf("application/json", "text/plain", "application/octet-stream")) }) { Text("Import") } } } + pwAsk?.let { (mode, uri) -> + var pw by remember { mutableStateOf("") } + androidx.compose.material3.AlertDialog( + onDismissRequest = { pwAsk = null }, + title = { Text(stringResource(R.string.backup_pw_title)) }, + text = { + Column { + Text(stringResource(if (mode == "export") R.string.backup_pw_export else R.string.backup_pw_import)) + OutlinedTextField(pw, { pw = it }, singleLine = true, + visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation()) + } + }, + confirmButton = { + TextButton({ + pwAsk = null + if (mode == "export") { + backupPw = pw.ifEmpty { null } + exportLauncher.launch("simbridge-backup-${java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US).format(java.util.Date())}" + + if (pw.isEmpty()) ".json" else ".sbx") + } else { + val r = runCatching { io.github.simbridge.Backup.import(ctx, uri!!, pw) } + android.widget.Toast.makeText(ctx, r.fold({ "Imported $it texts" }, { "Import failed: ${it.message}" }), + android.widget.Toast.LENGTH_LONG).show() + } + }, enabled = mode == "export" || pw.isNotEmpty()) { Text(stringResource(R.string.ok)) } + }, + dismissButton = { TextButton({ pwAsk = null }) { Text(stringResource(R.string.cancel)) } }, + ) + } } if (tab == 3) { + SecurityExtrasCard(core) Card(Icons.Filled.Refresh, stringResource(R.string.set_updates), latest?.let { stringResource(R.string.set_update_available, it) } ?: stringResource(R.string.set_updates_text, io.github.simbridge.BuildConfig.VERSION_NAME), ok = latest == null) { @@ -443,7 +480,7 @@ private fun TranslationCard(core: LinkCore) { } @Composable -private fun SwitchRow(text: String, on: Boolean, set: (Boolean) -> Unit) { +internal fun SwitchRow(text: String, on: Boolean, set: (Boolean) -> Unit) { Row(verticalAlignment = Alignment.CenterVertically) { Text(text, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) Switch(on, set) diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt index 5cf4cc1..92dcb4a 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt @@ -64,6 +64,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.material.icons.filled.BatteryChargingFull import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.material.icons.filled.Settings import kotlinx.coroutines.launch @@ -116,6 +117,7 @@ fun SimPhoneScreen( val pages = listOf(R.string.tab_messages, R.string.dash_tab_overview, R.string.dash_tab_controls, R.string.dash_ussd, R.string.dash_tab_data, R.string.dash_tab_places, R.string.speed_title) val pager = androidx.compose.foundation.pager.rememberPagerState(startPage) { pages.size } + val guard = rememberGuard(core) val scope = androidx.compose.runtime.rememberCoroutineScope() LaunchedEffect(online) { while (online) { core.control.refresh(); delay(30_000) } } LaunchedEffect(ussd) { if (ussd != null) waitingUssd = false } @@ -217,7 +219,7 @@ fun SimPhoneScreen( if (tab == 1) Section(Icons.Filled.SettingsRemote, stringResource(R.string.dash_remote), Tint.Orange) { ToggleRow(stringResource(R.string.dash_saver), stringResource(R.string.dash_saver_sub), s?.powerSaver, online, - pending["power-saver"] as Boolean?) { core.control.control("power-saver", it) } + pending["power-saver"] as Boolean?) { on -> guard { core.control.control("power-saver", on) } } ToggleRow(stringResource(R.string.dash_mobile_data), stringResource(R.string.dash_mobile_data_sub), s?.dataOn, online, pending["mobile-data"] as Boolean?) { confirm = "mobile-data" to it } ToggleRow(stringResource(R.string.dash_hotspot), stringResource(R.string.dash_hotspot_sub), s?.hotspot, online, @@ -232,9 +234,23 @@ fun SimPhoneScreen( if (pending.containsKey("restart")) { Spinner(); Spacer(Modifier.width(8.dp)) } Text(stringResource(R.string.dash_restart)) } - androidx.compose.material3.FilledTonalButton(onRemote, enabled = online) { Text(stringResource(R.string.dash_remote_screen)) } + androidx.compose.material3.FilledTonalButton({ guard(onRemote) }, enabled = online) { Text(stringResource(R.string.dash_remote_screen)) } } } + // Samsung battery protection: stop charging at a level, for a phone that is always plugged in. + if (tab == 1) Section(Icons.Filled.BatteryChargingFull, stringResource(R.string.dash_charge_limit), Tint.Green) { + Muted(stringResource(R.string.dash_charge_limit_sub)) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(top = 6.dp)) { + listOf("off", "80", "85", "90", "95").forEach { v -> + FilterChip(s?.chargeLimit == v, { guard { core.control.setChargeLimit(v) } }, enabled = online, + label = { Text(if (v == "off") stringResource(R.string.off) else "$v %") }) + } + } + ToggleRow(stringResource(R.string.dash_report), stringResource(R.string.dash_report_sub), s?.dailyReport, online, null) { + core.control.setDailyReport(it) + } + } + if (tab == 1) AppNotifSection(core, online) if (tab == 4) PlacesSection(core, online) if (tab == 1) Section(Icons.Filled.Call, stringResource(R.string.dash_calls), Tint.Green) { @@ -337,7 +353,8 @@ fun SimPhoneScreen( Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { if (inMenu) OutlinedButton({ core.control.ussdCancel(); code = "" }, Modifier.weight(1f)) { Text(stringResource(R.string.cancel)) } Button({ - waitingUssd = if (inMenu) core.control.ussdReply(code) else core.control.ussd(code, ussdSim) + val c = code + guard { waitingUssd = if (inMenu) core.control.ussdReply(c) else core.control.ussd(c, ussdSim) } code = "" }, enabled = online && !waitingUssd && (if (inMenu) code.isNotEmpty() else code.endsWith("#")), modifier = Modifier.weight(1f)) { Text(stringResource(if (inMenu) R.string.ussd_reply else R.string.send)) } @@ -354,7 +371,7 @@ fun SimPhoneScreen( onDismissRequest = { confirm = null }, title = { Text(stringResource(if (on) R.string.dash_turn_on_q else R.string.dash_turn_off_q, name)) }, text = { Text(stringResource(if (on) R.string.dash_turn_on_text else R.string.dash_turn_off_text)) }, - confirmButton = { TextButton({ core.control.control(action, on); confirm = null }) { Text(stringResource(R.string.ok)) } }, + confirmButton = { TextButton({ guard { core.control.control(action, on) }; confirm = null }) { Text(stringResource(R.string.ok)) } }, dismissButton = { TextButton({ confirm = null }) { Text(stringResource(R.string.cancel)) } }, ) } diff --git a/phone/src/main/res/values-ar/strings.xml b/phone/src/main/res/values-ar/strings.xml index 63d0415..7f154eb 100644 --- a/phone/src/main/res/values-ar/strings.xml +++ b/phone/src/main/res/values-ar/strings.xml @@ -301,4 +301,40 @@ السحب لليمين السحب لليسار عرض الكلمات أثناء نطقها + رسائل صامتة + أكّد هويتك + للتحكم في هاتف SIM + القفل والسجل + اطلب البصمة قبل الشاشة عن بعد وUSSD والمفاتيح، واعرض ما تغيّر على هاتف SIM. + قفل عناصر التحكم في هاتف SIM + التغييرات على هاتف SIM + لم يتغير شيء بعد. + القواعد والرسائل المزعجة + اختر من ينبّه دائمًا أو يبقى صامتًا أو يُؤرشف أو يُحظر. العروض المجهولة تذهب إلى المؤرشفة. + تصفية الرسائل المزعجة + أي شخص + إضافة قاعدة + الرقم أو الاسم يحتوي + النص يحتوي + أي شريحة + تنبيه دائمًا + صامت + ساعات الهدوء + المكالمات والرسائل صامتة ليلًا. جهات VIP ترن رغم ذلك. + ساعات الهدوء مفعّلة + من %1$s + إلى %1$s + جهات VIP + إضافة VIP + رقم الهاتف + حد الشحن + يوقف الشحن عند هذا المستوى لحماية هاتف موصول دائمًا (حماية بطارية سامسونج). + تقرير يومي + رسالة قصيرة عن الحالة كل صباح الساعة 9:00. + إشعارات التطبيقات + استلم هنا كرسائل إشعارات التطبيقات المختارة على هاتف SIM (البنك، المشغّل). + اختيار التطبيقات + كلمة مرور النسخة الاحتياطية + اتركها فارغة لنسخة عادية، أو ضع كلمة مرور لتشفيرها. + أدخل كلمة مرور هذه النسخة. diff --git a/phone/src/main/res/values-es/strings.xml b/phone/src/main/res/values-es/strings.xml index 023a85f..e7e49e5 100644 --- a/phone/src/main/res/values-es/strings.xml +++ b/phone/src/main/res/values-es/strings.xml @@ -301,4 +301,40 @@ Deslizar a la derecha Deslizar a la izquierda Mostrar las palabras mientras se dicen + Mensajes silenciosos + Confirma que eres tú + Para controlar el teléfono SIM + Bloqueo e historial + Pedir la huella antes de la pantalla remota, el USSD y los interruptores, y ver qué se cambió en el teléfono SIM. + Bloquear los controles del teléfono SIM + Cambios en el teléfono SIM + Aún no hay cambios. + Reglas y spam + Elige quién siempre avisa, queda en silencio, se archiva o se bloquea. Las promociones desconocidas van a Archivados. + Filtrar spam + Cualquiera + Añadir regla + Número o nombre contiene + El texto contiene + Cualquier SIM + Avisar siempre + Silencio + Horas de silencio + Llamadas y SMS en silencio por la noche. Los contactos VIP siguen sonando. + Horas de silencio activadas + Desde %1$s + Hasta %1$s + Contactos VIP + Añadir VIP + Número de teléfono + Límite de carga + Deja de cargar aquí para proteger un teléfono siempre enchufado (protección de batería Samsung). + Informe diario + Un breve resumen cada mañana a las 9:00. + Notificaciones de apps + Recibe aquí como mensajes las notificaciones de apps elegidas del teléfono SIM (banco, operador). + Elegir apps + Contraseña de la copia + Déjalo vacío para una copia simple, o pon una contraseña para cifrarla. + Introduce la contraseña de esta copia. diff --git a/phone/src/main/res/values-fa/strings.xml b/phone/src/main/res/values-fa/strings.xml index c9ad5b1..5e741bc 100644 --- a/phone/src/main/res/values-fa/strings.xml +++ b/phone/src/main/res/values-fa/strings.xml @@ -301,4 +301,40 @@ کشیدن به راست کشیدن به چپ نمایش واژه‌ها هنگام گفتن + پیام‌های بی‌صدا + هویت خود را تأیید کنید + برای کنترل گوشی سیم‌کارت + قفل و تاریخچه + پیش از صفحه از راه دور، USSD و کلیدها اثر انگشت بخواهد و تغییرات گوشی سیم‌کارت را نشان دهد. + قفل کنترل‌های گوشی سیم‌کارت + تغییرات روی گوشی سیم‌کارت + هنوز تغییری نیست. + قوانین و هرزنامه + انتخاب کنید چه کسی همیشه هشدار دهد، بی‌صدا بماند، بایگانی یا مسدود شود. تبلیغات ناشناس به بایگانی می‌روند. + فیلتر هرزنامه + همه + افزودن قانون + شماره یا نام شامل + متن شامل + هر سیم‌کارت + همیشه هشدار + بی‌صدا + ساعات سکوت + شب‌ها تماس‌ها و پیام‌ها بی‌صدا هستند. مخاطبان VIP همچنان زنگ می‌زنند. + ساعات سکوت روشن + از %1$s + تا %1$s + مخاطبان VIP + افزودن VIP + شماره تلفن + محدودیت شارژ + برای محافظت از گوشی همیشه به برق، شارژ را اینجا متوقف می‌کند (محافظت باتری سامسونگ). + گزارش روزانه + یک پیام کوتاه وضعیت هر صبح ساعت ۹. + اعلان‌های برنامه‌ها + اعلان‌های برنامه‌های انتخابی گوشی سیم‌کارت (بانک، اپراتور) را اینجا به‌صورت پیام بگیرید. + انتخاب برنامه‌ها + رمز پشتیبان + برای پشتیبان ساده خالی بگذارید یا برای رمزگذاری رمز بگذارید. + رمز این پشتیبان را وارد کنید. diff --git a/phone/src/main/res/values-fr/strings.xml b/phone/src/main/res/values-fr/strings.xml index 60371bb..ada6f3c 100644 --- a/phone/src/main/res/values-fr/strings.xml +++ b/phone/src/main/res/values-fr/strings.xml @@ -301,4 +301,40 @@ Balayage à droite Balayage à gauche Afficher les mots pendant qu\'ils sont prononcés + Messages silencieux + Confirmez votre identité + Pour contrôler le téléphone SIM + Verrou et historique + Demander l\'empreinte avant l\'écran à distance, l\'USSD et les interrupteurs, et voir ce qui a changé sur le téléphone SIM. + Verrouiller les commandes du téléphone SIM + Changements sur le téléphone SIM + Rien n\'a encore changé. + Règles et spam + Choisissez qui alerte toujours, reste silencieux, est archivé ou bloqué. Les promotions inconnues vont dans Archivés. + Filtrer le spam + Tout le monde + Ajouter une règle + Numéro ou nom contient + Le texte contient + N\'importe quelle SIM + Toujours alerter + Silencieux + Heures calmes + Appels et SMS restent silencieux la nuit. Les contacts VIP sonnent quand même. + Heures calmes activées + De %1$s + À %1$s + Contacts VIP + Ajouter un VIP + Numéro de téléphone + Limite de charge + Arrête la charge à ce niveau pour protéger un téléphone toujours branché (protection de batterie Samsung). + Rapport quotidien + Un court bilan chaque matin à 9 h. + Notifications d\'applis + Recevoir ici, comme messages, les notifications d\'applis choisies du téléphone SIM (banque, opérateur). + Choisir les applis + Mot de passe de la sauvegarde + Laissez vide pour une sauvegarde simple, ou définissez un mot de passe pour la chiffrer. + Saisissez le mot de passe de cette sauvegarde. diff --git a/phone/src/main/res/values-ru/strings.xml b/phone/src/main/res/values-ru/strings.xml index b4b92d3..e51999b 100644 --- a/phone/src/main/res/values-ru/strings.xml +++ b/phone/src/main/res/values-ru/strings.xml @@ -301,4 +301,40 @@ Смахивание вправо Смахивание влево Показывать слова во время речи + Тихие сообщения + Подтвердите, что это вы + Для управления SIM-телефоном + Блокировка и история + Спрашивать отпечаток перед удалённым экраном, USSD и переключателями, и показывать изменения на SIM-телефоне. + Блокировать управление SIM-телефоном + Изменения на SIM-телефоне + Пока ничего не менялось. + Правила и спам + Выберите, кто всегда оповещает, остаётся беззвучным, архивируется или блокируется. Незнакомая реклама попадает в Архив. + Фильтровать спам + Любой + Добавить правило + Номер или имя содержит + Текст содержит + Любая SIM + Всегда оповещать + Беззвучно + Тихие часы + Ночью звонки и SMS беззвучны. VIP-контакты всё равно звонят. + Тихие часы включены + С %1$s + До %1$s + VIP-контакты + Добавить VIP + Номер телефона + Лимит заряда + Прекращает зарядку на этом уровне, чтобы беречь всегда подключённый телефон (защита батареи Samsung). + Ежедневный отчёт + Короткая сводка каждое утро в 9:00. + Уведомления приложений + Получайте здесь как сообщения уведомления выбранных приложений SIM-телефона (банк, оператор). + Выбрать приложения + Пароль резервной копии + Оставьте пустым для обычной копии или задайте пароль для шифрования. + Введите пароль этой копии. diff --git a/phone/src/main/res/values-tr/strings.xml b/phone/src/main/res/values-tr/strings.xml index ceebfce..9f80e1c 100644 --- a/phone/src/main/res/values-tr/strings.xml +++ b/phone/src/main/res/values-tr/strings.xml @@ -336,4 +336,40 @@ Sağa kaydırma Sola kaydırma Sözcükleri söylenirken göster + Sessiz mesajlar + Siz olduğunuzu doğrulayın + SIM telefonu kontrol etmek için + Kilit ve geçmiş + Uzaktan ekran, USSD ve anahtarlardan önce parmak izi iste, SIM telefonda neyin değiştiğini gör. + SIM telefon kontrollerini kilitle + SIM telefondaki değişiklikler + Henüz değişiklik yok. + Kurallar ve spam + Kimin her zaman uyaracağını, sessiz kalacağını, arşivleneceğini veya engelleneceğini seçin. Bilinmeyen reklamlar Arşivlenen\'e gider. + Spam\'i filtrele + Herkes + Kural ekle + Numara veya ad içerir + Metin içerir + Herhangi bir SIM + Her zaman uyar + Sessiz + Sessiz saatler + Gece aramalar ve mesajlar sessiz kalır. VIP kişiler yine çalar. + Sessiz saatler açık + Başlangıç %1$s + Bitiş %1$s + VIP kişiler + VIP ekle + Telefon numarası + Şarj sınırı + Sürekli takılı bir telefonu korumak için şarjı burada durdurur (Samsung pil koruması). + Günlük rapor + Her sabah 9:00\'da kısa bir durum mesajı. + Uygulama bildirimleri + SIM telefondaki seçili uygulamaların (banka, operatör) bildirimlerini burada mesaj olarak alın. + Uygulamaları seç + Yedek şifresi + Düz yedek için boş bırakın veya şifrelemek için bir şifre girin. + Bu yedeğin şifresini girin. diff --git a/phone/src/main/res/values/strings.xml b/phone/src/main/res/values/strings.xml index c686fb7..9d4cac7 100644 --- a/phone/src/main/res/values/strings.xml +++ b/phone/src/main/res/values/strings.xml @@ -337,4 +337,40 @@ Swipe right Swipe left Show words while they are spoken + Quiet messages + Confirm it\'s you + To control the SIM phone + Lock and history + Ask for your fingerprint before remote screen, USSD and switches, and see what was changed on the SIM phone. + Lock SIM phone controls + Changes on the SIM phone + Nothing changed yet. + Rules and spam + Choose who always alerts, stays silent, is archived or blocked. Unknown promotions go to Archived. + Filter spam + Anyone + Add rule + Number or name contains + Text contains + Any SIM + Always alert + Silent + Quiet hours + Calls and texts stay silent at night. VIP contacts still ring. + Quiet hours on + From %1$s + To %1$s + VIP contacts + Add VIP + Phone number + Charge limit + Stops charging here to protect a phone that is always plugged in (Samsung battery protection). + Daily report + A short health text every morning at 9:00. + App notifications + Get notifications of chosen apps on the SIM phone (bank, carrier) as messages here. + Choose apps + Backup password + Leave empty for a plain backup, or set a password to encrypt it. + Enter the password of this backup. diff --git a/privileged/src/main/kotlin/io/github/sparkcyf/voicesipagent/privileged/shell/RemoteActions.kt b/privileged/src/main/kotlin/io/github/sparkcyf/voicesipagent/privileged/shell/RemoteActions.kt index 116f3cc..e7f5afc 100644 --- a/privileged/src/main/kotlin/io/github/sparkcyf/voicesipagent/privileged/shell/RemoteActions.kt +++ b/privileged/src/main/kotlin/io/github/sparkcyf/voicesipagent/privileged/shell/RemoteActions.kt @@ -32,7 +32,36 @@ internal object RemoteActions { val r = ShellEnv.run("svc", "data", if (on) "enable" else "disable") if (r.exit == 0) "mobile data ${if (on) "on" else "off"}" else "error: ${r.out.trim()}" } - "hotspot" -> hotspot(ctx, arg == "on") + "hotspot" -> { + var r = hotspot(ctx, arg == "on") + // Most phones can't host a hotspot while joined to Wi-Fi: leave Wi-Fi and try once more. + if (arg == "on" && r.contains("on Wi-Fi")) { + ShellEnv.run("svc", "wifi", "disable") + Thread.sleep(1500) + r = hotspot(ctx, true).let { if (it.startsWith("error")) it else "on (Wi-Fi turned off for it)" } + } + r + } + "notif-access" -> { + require(Regex("[a-z0-9._]+/[A-Za-z0-9._]+").matches(arg)) { "bad component" } + val r = ShellEnv.run("cmd", "notification", "allow_listener", arg) + if (r.exit == 0) "ok" else "error: ${r.out.trim()}" + } + // Samsung battery protection: "off", or the percent charging stops at (80..95). + "charge-limit" -> { + if (arg == "off") ShellEnv.run("settings", "put", "global", "protect_battery", "0") + else { + val pct = arg.toInt().coerceIn(80, 95) + ShellEnv.run("settings", "put", "global", "battery_protection_threshold", pct.toString()) + ShellEnv.run("settings", "put", "global", "protect_battery", "1") + } + "ok" + } + "charge-limit-get" -> { + val on = ShellEnv.run("settings", "get", "global", "protect_battery").out.trim() + val pct = ShellEnv.run("settings", "get", "global", "battery_protection_threshold").out.trim() + if (on == "0" || on == "null" || on.isEmpty()) "off" else pct.ifEmpty { "80" } + } "screen-stream" -> ScreenStream.start(arg) "screen-stop" -> ScreenStream.stop() "ussd-dial" -> ussdDial(arg)