diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 13a07fe..ec006ea 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -12,7 +12,7 @@ android {
defaultConfig {
applicationId = "com.asio.tapremly"
- minSdk = 23
+ minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"
@@ -30,13 +30,39 @@ android {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
+ buildFeatures {
+ viewBinding = true
+ }
+ packaging {
+ resources {
+ excludes += setOf(
+ "META-INF/AL2.0",
+ "META-INF/LGPL2.1",
+ "META-INF/LICENSE",
+ "META-INF/LICENSE.txt",
+ "META-INF/LICENSE.md",
+ "META-INF/NOTICE",
+ "META-INF/NOTICE.txt",
+ "META-INF/NOTICE.md",
+ )
+ pickFirsts += setOf(
+ "META-INF/INDEX.LIST",
+ "META-INF/io.netty.versions.properties",
+ )
+ }
+ }
}
dependencies {
- implementation("androidx.core:core-ktx:1.10.1")
- implementation("androidx.appcompat:appcompat:1.6.1")
- implementation("com.google.android.material:material:1.10.0")
+ implementation("androidx.core:core-ktx:1.15.0")
+ implementation("androidx.appcompat:appcompat:1.7.0")
+ implementation("com.google.android.material:material:1.12.0")
+ implementation("androidx.recyclerview:recyclerview:1.4.0")
+ implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")
+ implementation("com.squareup.okhttp3:okhttp:4.12.0")
+ implementation("com.google.code.gson:gson:2.11.0")
+ implementation("asia.asio.nixmsg:nixmsg-sdk:0.1.0")
testImplementation("junit:junit:4.13.2")
- androidTestImplementation("androidx.test.ext:junit:1.1.5")
- androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
-}
\ No newline at end of file
+ androidTestImplementation("androidx.test.ext:junit:1.2.1")
+ androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8df153a..911c0f1 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -1,16 +1,69 @@
-
+
+
+
+
+
+
+ android:name=".TapRemlyApp"
+ android:allowBackup="false"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:roundIcon="@drawable/ic_launcher"
+ android:supportsRtl="true"
+ android:theme="@style/Theme.TapRemly"
+ android:usesCleartextTraffic="true">
-
\ No newline at end of file
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/java/com/asio/tapremly/TapRemlyApp.kt b/app/src/main/java/com/asio/tapremly/TapRemlyApp.kt
new file mode 100644
index 0000000..7e97368
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/TapRemlyApp.kt
@@ -0,0 +1,49 @@
+package com.asio.tapremly
+
+import android.app.Activity
+import android.app.Application
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+
+class TapRemlyApp : Application() {
+ private val activities = ArrayList()
+ private var started = 0
+ private val main = Handler(Looper.getMainLooper())
+ private val leave = Runnable {
+ if (started == 0) {
+ activities.toList().forEach { activity ->
+ if (!activity.isFinishing) activity.finish()
+ }
+ }
+ }
+
+ override fun onCreate() {
+ super.onCreate()
+ registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
+ activities.add(activity)
+ }
+
+ override fun onActivityStarted(activity: Activity) {
+ started += 1
+ main.removeCallbacks(leave)
+ }
+
+ override fun onActivityResumed(activity: Activity) = Unit
+ override fun onActivityPaused(activity: Activity) = Unit
+
+ override fun onActivityStopped(activity: Activity) {
+ started -= 1
+ main.removeCallbacks(leave)
+ main.post(leave)
+ }
+
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
+
+ override fun onActivityDestroyed(activity: Activity) {
+ activities.remove(activity)
+ }
+ })
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/agent/AgentRuntime.kt b/app/src/main/java/com/asio/tapremly/agent/AgentRuntime.kt
new file mode 100644
index 0000000..38c99a1
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/agent/AgentRuntime.kt
@@ -0,0 +1,578 @@
+package com.asio.tapremly.agent
+
+import android.os.Handler
+import android.os.Looper
+import com.asio.tapremly.core.Device
+import com.asio.tapremly.core.Engine
+import com.asio.tapremly.core.ExecutedStore
+import com.asio.tapremly.core.Group
+import com.asio.tapremly.core.InboxText
+import com.asio.tapremly.core.Limits
+import com.asio.tapremly.core.LogEntry
+import com.asio.tapremly.core.Message
+import com.asio.tapremly.core.Protocol
+import com.asio.tapremly.core.SendForm
+import com.asio.tapremly.core.Shortcut
+import com.asio.tapremly.core.Stored
+import com.asio.tapremly.core.WireOpt
+import com.asio.tapremly.core.problems
+import com.asio.tapremly.core.toWire
+import com.asio.tapremly.data.AppDb
+import com.asio.tapremly.data.Prefs
+import com.asio.tapremly.data.TapApi
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+data class Snapshot(
+ val selfId: String,
+ val username: String,
+ val linkLabel: String,
+ val serverUrl: String,
+ val nixUrl: String,
+ val devices: List,
+ val groups: List,
+ val trust: List,
+ val localByRemote: Map>,
+ val remoteByRemote: Map>,
+ val remoteSyncedAt: Map,
+ val syncing: Set,
+ val published: List,
+ val blocked: Set,
+ val logs: List,
+ val inbox: List,
+ val listError: String,
+ val maxTtlSeconds: Long,
+ val maxScheduleSeconds: Long,
+)
+
+interface AgentListener {
+ fun onSnapshot(snapshot: Snapshot) {}
+ fun onNotice(text: String) {}
+ fun onText(fromId: String, text: String) {}
+ fun onLoggedOut() {}
+}
+
+class AgentRuntime(
+ private val prefs: Prefs,
+ private val db: AppDb,
+ private val api: TapApi,
+ private val nix: NixLink,
+ private val shell: com.asio.tapremly.core.ShellRunner,
+) {
+ var onStopRequested: (() -> Unit)? = null
+
+ private val main = Handler(Looper.getMainLooper())
+ private val io: ExecutorService = Executors.newSingleThreadExecutor { runnable ->
+ Thread(runnable, "tapremly-io").apply { isDaemon = true }
+ }
+ private val gate = Any()
+ private val listeners = LinkedHashSet()
+ private val presence = HashMap()
+ private val blocked = HashSet()
+ private val syncing = HashSet()
+ private val outbound = LinkedHashMap()
+ private var linkLabel = "本机未连接"
+ private var listError = ""
+
+ private val engine = Engine(
+ trusted = { db.isTrusted(it) },
+ published = { db.findPublished(it) },
+ allPublished = { db.listPublished() },
+ runner = shell,
+ executed = object : ExecutedStore {
+ override fun get(id: String, now: Long): Stored? = db.getExecuted(id, now)
+ override fun put(id: String, value: Stored, now: Long) {
+ db.putExecuted(id, value, now)
+ }
+ },
+ now = { System.currentTimeMillis() },
+ onText = { from, text ->
+ db.addInbox(InboxText(System.currentTimeMillis(), from, text))
+ main.post { each { it.onText(from, text) } }
+ publish()
+ },
+ onShortcuts = { from, items ->
+ db.replaceRemote(from, items, System.currentTimeMillis())
+ synchronized(gate) {
+ syncing.remove(from)
+ blocked.remove(from)
+ }
+ },
+ onLog = { entry ->
+ db.addLog(entry)
+ val latest = db.latestLogs(20)
+ val endpoint = prefs.endpointId
+ val password = prefs.nixPassword
+ io.execute { runCatching { api.putLogs(endpoint, password, latest) } }
+ },
+ )
+
+ fun start() {
+ nix.onMessage = { from, body -> onIncoming(from, body) }
+ nix.onReceipt = { id, state, reason -> onReceipt(id, state, reason) }
+ nix.onPresence = { id, online ->
+ synchronized(gate) { presence[id] = online }
+ publish()
+ }
+ nix.onConnection = { state, _ ->
+ synchronized(gate) { linkLabel = linkText(state) }
+ publish()
+ if (state == "ONLINE") io.execute { refreshPresence() }
+ }
+ nix.onSession = { token -> prefs.nixToken = token }
+ io.execute {
+ refreshDirectory()
+ ensureSelf()
+ connectSaved()
+ }
+ }
+
+ fun shutdown() {
+ runCatching { nix.close() }
+ io.shutdownNow()
+ }
+
+ fun addListener(listener: AgentListener) {
+ synchronized(listeners) { listeners.add(listener) }
+ val snap = build()
+ main.post { listener.onSnapshot(snap) }
+ }
+
+ fun removeListener(listener: AgentListener) {
+ synchronized(listeners) { listeners.remove(listener) }
+ }
+
+ fun snapshot(): Snapshot = build()
+
+ fun refresh() {
+ io.execute { refreshDirectory() }
+ }
+
+ fun setUrls(server: String, nixUrl: String) {
+ io.execute {
+ val nextServer = server.trim()
+ val nextNix = nixUrl.trim()
+ if (nextServer != prefs.serverUrl) prefs.clearCookies()
+ prefs.serverUrl = nextServer
+ prefs.nixUrl = nextNix
+ refreshDirectory()
+ ensureSelf()
+ if (prefs.loggedIn) connectSaved()
+ }
+ }
+
+ fun logout() {
+ io.execute {
+ runCatching { api.logout() }
+ runCatching { nix.close() }
+ prefs.clearSession()
+ db.clearDirectory()
+ synchronized(gate) {
+ presence.clear()
+ blocked.clear()
+ linkLabel = "本机未连接"
+ listError = ""
+ }
+ publish()
+ main.post { each { it.onLoggedOut() } }
+ main.post { onStopRequested?.invoke() }
+ }
+ }
+
+ fun addDevice(name: String, endpointId: String) = work("没有添加") {
+ api.addDevice(name, endpointId)
+ refreshDirectory()
+ }
+
+ fun createGroup(name: String) = work("没有建成分组") {
+ api.createGroup(name)
+ refreshDirectory()
+ }
+
+ fun renameGroup(id: String, name: String) = work("没有改名") {
+ api.renameGroup(id, name)
+ refreshDirectory()
+ }
+
+ fun deleteGroup(id: String) = work("没有删除分组") {
+ api.deleteGroup(id)
+ refreshDirectory()
+ }
+
+ fun moveDevice(recordId: Long, groupId: String) = work("没有改分组") {
+ api.moveDevice(recordId, groupId)
+ refreshDirectory()
+ }
+
+ fun removeDevice(recordId: Long) = work("没有移出") {
+ api.removeDevice(recordId)
+ refreshDirectory()
+ }
+
+ fun trustAdd(endpointId: String) {
+ io.execute {
+ db.addTrust(endpointId, System.currentTimeMillis())
+ publish()
+ pushPublished(listOf(endpointId))
+ }
+ }
+
+ fun trustRemove(endpointId: String) {
+ io.execute {
+ db.removeTrust(endpointId)
+ publish()
+ }
+ }
+
+ fun addLocal(remoteId: String, name: String, shell: String, confirm: Boolean) {
+ io.execute {
+ if (name.isBlank() || shell.isBlank()) return@execute
+ db.addLocal(remoteId, name.trim(), shell, confirm)
+ publish()
+ }
+ }
+
+ fun updateLocal(id: String, name: String, shell: String, confirm: Boolean) {
+ io.execute {
+ if (name.isBlank() || shell.isBlank()) return@execute
+ db.updateLocal(id, name.trim(), shell, confirm)
+ publish()
+ }
+ }
+
+ fun deleteLocal(id: String) {
+ io.execute {
+ db.deleteLocal(id)
+ publish()
+ }
+ }
+
+ fun addPublished(name: String, shell: String, confirm: Boolean) {
+ io.execute {
+ if (name.isBlank() || shell.isBlank()) return@execute
+ db.addPublished(name.trim(), shell, confirm)
+ publish()
+ pushPublished()
+ }
+ }
+
+ fun updatePublished(id: String, name: String, shell: String, confirm: Boolean) {
+ io.execute {
+ if (name.isBlank() || shell.isBlank()) return@execute
+ db.updatePublished(id, name.trim(), shell, confirm)
+ publish()
+ pushPublished()
+ }
+ }
+
+ fun deletePublished(id: String) {
+ io.execute {
+ db.deletePublished(id)
+ publish()
+ pushPublished()
+ }
+ }
+
+ fun copyTo(name: String, shell: String, confirm: Boolean, remoteIds: List) {
+ io.execute {
+ db.copyLocal(name, shell, confirm, remoteIds)
+ publish()
+ tell("已复制")
+ }
+ }
+
+ fun syncRemote(remoteId: String) {
+ io.execute {
+ synchronized(gate) { syncing.add(remoteId) }
+ publish()
+ val id = Protocol.newId()
+ remember(id, remoteId, command = false)
+ try {
+ nix.send(remoteId, Protocol.shortcutsQuery(id), id, WireOpt())
+ } catch (_: Exception) {
+ synchronized(gate) { syncing.remove(remoteId) }
+ publish()
+ }
+ main.postDelayed({
+ val changed = synchronized(gate) { syncing.remove(remoteId) }
+ if (changed) publish()
+ }, 8_000)
+ }
+ }
+
+ fun sendShell(remoteId: String, shell: String, form: SendForm) {
+ io.execute {
+ if (shell.isBlank()) return@execute
+ val now = System.currentTimeMillis()
+ val problem = form.problems(now, currentLimits())
+ if (problem != null) {
+ tell(problem)
+ return@execute
+ }
+ val id = Protocol.newId()
+ remember(id, remoteId, command = true)
+ deliver(remoteId, Protocol.shell(id, shell), id, form.toWire(now))
+ }
+ }
+
+ fun sendText(remoteId: String, text: String, form: SendForm) {
+ io.execute {
+ if (text.isBlank()) return@execute
+ val now = System.currentTimeMillis()
+ val problem = form.problems(now, currentLimits())
+ if (problem != null) {
+ tell(problem)
+ return@execute
+ }
+ val id = Protocol.newId()
+ remember(id, remoteId, command = false)
+ deliver(remoteId, Protocol.text(id, text), id, form.toWire(now))
+ }
+ }
+
+ fun sendRemoteShortcut(remoteId: String, shortcutId: String, form: SendForm) {
+ io.execute {
+ val now = System.currentTimeMillis()
+ val problem = form.problems(now, currentLimits())
+ if (problem != null) {
+ tell(problem)
+ return@execute
+ }
+ val id = Protocol.newId()
+ remember(id, remoteId, command = true)
+ deliver(remoteId, Protocol.shortcut(id, shortcutId), id, form.toWire(now))
+ }
+ }
+
+ private fun work(fail: String, block: () -> Unit) {
+ io.execute {
+ try {
+ block()
+ } catch (_: Exception) {
+ tell(fail)
+ publish()
+ }
+ }
+ }
+
+ private fun deliver(remoteId: String, body: String, id: String, wire: WireOpt) {
+ try {
+ val state = nix.send(remoteId, body, id, wire)
+ tell(if (state == "scheduled") "已设为定时发送" else "已送出")
+ } catch (e: Exception) {
+ tell(if (e is LinkException && e.code == "not_connected") "没有连上" else "没有发出去")
+ }
+ }
+
+ private fun ensureSelf() {
+ if (!prefs.loggedIn || prefs.nixReady) return
+ try {
+ val made = api.provisionSelf("这部手机")
+ prefs.endpointId = made.endpointId
+ prefs.nixPassword = made.password
+ refreshDirectory()
+ } catch (e: Exception) {
+ val text = e.message?.takeIf { it.isNotBlank() } ?: "暂时无法准备本机"
+ synchronized(gate) { listError = text }
+ publish()
+ }
+ }
+
+ private fun connectSaved() {
+ if (!prefs.nixReady) {
+ synchronized(gate) { linkLabel = "本机未连接" }
+ publish()
+ return
+ }
+ synchronized(gate) { linkLabel = "正在连接" }
+ publish()
+ try {
+ nix.connect(
+ prefs.nixUrl,
+ prefs.endpointId,
+ prefs.nixPassword.ifBlank { null },
+ prefs.nixToken.ifBlank { null },
+ )
+ synchronized(gate) { linkLabel = "本机已连接" }
+ } catch (e: Exception) {
+ val label = if (e is LinkException && (e.code == "bad_credentials" || e.code == "session_invalid")) {
+ "连接已失效"
+ } else {
+ "本机未连接"
+ }
+ synchronized(gate) { linkLabel = label }
+ }
+ publish()
+ }
+
+ private fun refreshDirectory() {
+ if (!prefs.loggedIn) return
+ try {
+ val (devices, groups) = api.directory()
+ db.replaceDirectory(devices, groups)
+ synchronized(gate) { listError = "" }
+ } catch (e: Exception) {
+ val text = e.message?.takeIf { it.isNotBlank() && it != "没有完成操作" } ?: "设备列表没有刷新"
+ synchronized(gate) { listError = text }
+ }
+ refreshPresence()
+ publish()
+ }
+
+ private fun refreshPresence() {
+ val ids = db.devices().map { it.id }.filter { it.isNotBlank() && it != prefs.endpointId }
+ if (ids.isEmpty()) return
+ try {
+ nix.watch(ids)
+ val found = nix.presence(ids)
+ synchronized(gate) {
+ for ((id, online) in found) presence[id] = online
+ }
+ } catch (_: Exception) {
+ }
+ }
+
+ private fun pushPublished(only: List? = null) {
+ val body = Protocol.shortcuts(db.listPublished())
+ val online = synchronized(gate) { presence.toMap() }
+ val targets = (only ?: db.listTrust()).filter { online[it] == true }
+ for (id in targets) {
+ val msgId = Protocol.newId()
+ runCatching { nix.send(id, body, msgId, WireOpt()) }
+ }
+ }
+
+ private fun onIncoming(from: String, raw: String) {
+ val msg = Protocol.parse(raw) ?: return
+ if (msg.v != 1) return
+ if (msg.type == "result") {
+ onResult(msg)
+ return
+ }
+ val reply = engine.handle(from, raw)
+ if (reply != null) {
+ val id = Protocol.newId()
+ runCatching { nix.send(from, reply, id, WireOpt()) }
+ }
+ publish()
+ }
+
+ private fun onResult(msg: Message) {
+ val id = msg.id ?: return
+ val outgoing = synchronized(gate) { outbound[id] }
+ val remote = outgoing?.remoteId
+ if (msg.ok == true) {
+ if (outgoing?.command == true && remote != null) {
+ synchronized(gate) { blocked.remove(remote) }
+ }
+ if (outgoing?.command == true) tell("已执行")
+ } else if (msg.error == "not_trusted") {
+ if (remote != null) synchronized(gate) { blocked.add(remote) }
+ tell("对方尚未信任本机")
+ } else if (outgoing != null) {
+ tell(msg.error?.takeIf { it.isNotBlank() } ?: "没有成功")
+ }
+ synchronized(gate) { if (remote != null) syncing.remove(remote) }
+ publish()
+ }
+
+ private fun onReceipt(id: String, state: String, reason: String) {
+ val outgoing = synchronized(gate) { outbound[id] } ?: return
+ if (!outgoing.command) {
+ if (state == "dropped" || state == "rejected") {
+ synchronized(gate) { syncing.remove(outgoing.remoteId) }
+ publish()
+ }
+ return
+ }
+ if (state == "dropped" && reason == "offline") tell("没有留下")
+ else if (state == "dropped" || state == "rejected") tell("没有送到")
+ }
+
+ private fun remember(id: String, remoteId: String, command: Boolean) {
+ synchronized(gate) {
+ outbound[id] = Outgoing(remoteId, command)
+ while (outbound.size > 200) {
+ val first = outbound.keys.firstOrNull() ?: break
+ outbound.remove(first)
+ }
+ }
+ }
+
+ private fun currentLimits(): Limits = try {
+ nix.limits()
+ } catch (_: Exception) {
+ Limits()
+ }
+
+ private fun build(): Snapshot {
+ val presenceCopy: Map
+ val blockedCopy: Set
+ val syncingCopy: Set
+ val link: String
+ val err: String
+ synchronized(gate) {
+ presenceCopy = presence.toMap()
+ blockedCopy = blocked.toSet()
+ syncingCopy = syncing.toSet()
+ link = linkLabel
+ err = listError
+ }
+ val self = prefs.endpointId
+ val selfOnline = link == "本机已连接"
+ val devices = db.devices().map { device ->
+ val online = when {
+ device.id == self && selfOnline -> true
+ presenceCopy.containsKey(device.id) -> presenceCopy[device.id] == true
+ else -> device.online
+ }
+ device.copy(online = online)
+ }
+ val limits = currentLimits()
+ return Snapshot(
+ selfId = self,
+ username = prefs.username,
+ linkLabel = link,
+ serverUrl = prefs.serverUrl,
+ nixUrl = prefs.nixUrl,
+ devices = devices,
+ groups = db.groups(),
+ trust = db.listTrust(),
+ localByRemote = db.localByRemote(),
+ remoteByRemote = db.remoteByRemote(),
+ remoteSyncedAt = db.remoteSyncAt(),
+ syncing = syncingCopy,
+ published = db.listPublished(),
+ blocked = blockedCopy,
+ logs = db.logs(),
+ inbox = db.inbox(),
+ listError = err,
+ maxTtlSeconds = limits.maxTtlSeconds,
+ maxScheduleSeconds = limits.maxScheduleSeconds,
+ )
+ }
+
+ private fun publish() {
+ val snap = build()
+ main.post { each { it.onSnapshot(snap) } }
+ }
+
+ private fun tell(text: String) {
+ main.post { each { it.onNotice(text) } }
+ }
+
+ private fun each(block: (AgentListener) -> Unit) {
+ val copy = synchronized(listeners) { listeners.toList() }
+ copy.forEach(block)
+ }
+
+ private fun linkText(state: String): String = when (state) {
+ "ONLINE" -> "本机已连接"
+ "CONNECTING", "RECONNECTING" -> "正在连接"
+ "AUTH_FAILED" -> "连接已失效"
+ "KICKED" -> "已在别处连接"
+ else -> "本机未连接"
+ }
+
+ private data class Outgoing(val remoteId: String, val command: Boolean)
+}
diff --git a/app/src/main/java/com/asio/tapremly/agent/AgentService.kt b/app/src/main/java/com/asio/tapremly/agent/AgentService.kt
new file mode 100644
index 0000000..4ab849a
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/agent/AgentService.kt
@@ -0,0 +1,89 @@
+package com.asio.tapremly.agent
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Binder
+import android.os.Build
+import android.os.IBinder
+import androidx.core.app.NotificationCompat
+import com.asio.tapremly.R
+import com.asio.tapremly.data.AppDb
+import com.asio.tapremly.data.Prefs
+import com.asio.tapremly.data.TapApi
+import com.asio.tapremly.ui.MainActivity
+
+class AgentService : Service() {
+ private val binder = LocalBinder()
+ private var runtime: AgentRuntime? = null
+
+ inner class LocalBinder : Binder() {
+ fun get(): AgentRuntime? = runtime
+ }
+
+ override fun onBind(intent: Intent?): IBinder = binder
+
+ override fun onCreate() {
+ super.onCreate()
+ startAsForeground()
+ val prefs = Prefs(this)
+ val nix = try {
+ SdkNixLink()
+ } catch (_: Throwable) {
+ BrokenLink
+ }
+ runtime = AgentRuntime(prefs, AppDb(this), TapApi(prefs), nix, AndroidShell).also { created ->
+ created.onStopRequested = { stopSelf() }
+ created.start()
+ }
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ startAsForeground()
+ return START_STICKY
+ }
+
+ override fun onDestroy() {
+ runtime?.shutdown()
+ runtime = null
+ super.onDestroy()
+ }
+
+ private fun startAsForeground() {
+ val manager = getSystemService(NotificationManager::class.java)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val channel = NotificationChannel(CHANNEL, "连接", NotificationManager.IMPORTANCE_LOW)
+ channel.setSound(null, null)
+ channel.enableVibration(false)
+ manager.createNotificationChannel(channel)
+ }
+ val open = PendingIntent.getActivity(
+ this,
+ 0,
+ Intent(this, MainActivity::class.java),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
+ )
+ val notification = NotificationCompat.Builder(this, CHANNEL)
+ .setSmallIcon(R.drawable.ic_stat)
+ .setContentTitle(getString(R.string.app_name))
+ .setContentText(getString(R.string.notice_running))
+ .setPriority(NotificationCompat.PRIORITY_LOW)
+ .setOngoing(true)
+ .setContentIntent(open)
+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
+ .build()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(NOTE_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ } else {
+ startForeground(NOTE_ID, notification)
+ }
+ }
+
+ companion object {
+ private const val CHANNEL = "tapremly.link"
+ private const val NOTE_ID = 7
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/agent/AndroidShell.kt b/app/src/main/java/com/asio/tapremly/agent/AndroidShell.kt
new file mode 100644
index 0000000..8ac8e89
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/agent/AndroidShell.kt
@@ -0,0 +1,62 @@
+package com.asio.tapremly.agent
+
+import com.asio.tapremly.core.ShellOutcome
+import com.asio.tapremly.core.ShellRunner
+import com.asio.tapremly.core.clip
+import java.io.InputStream
+import java.util.concurrent.TimeUnit
+
+/** 在本应用进程的权限里执行,不提权,也不检查内容。 */
+object AndroidShell : ShellRunner {
+ override fun run(shell: String): ShellOutcome {
+ return try {
+ val process = ProcessBuilder("/system/bin/sh", "-c", shell).start()
+ val out = StringBuilder()
+ val err = StringBuilder()
+ val outThread = Thread { drain(process.inputStream, out) }
+ val errThread = Thread { drain(process.errorStream, err) }
+ outThread.start()
+ errThread.start()
+ if (!process.waitFor(20, TimeUnit.SECONDS)) {
+ process.destroyForcibly()
+ outThread.join(300)
+ errThread.join(300)
+ return ShellOutcome(false, "执行超时")
+ }
+ outThread.join(500)
+ errThread.join(500)
+ if (process.exitValue() == 0) {
+ ShellOutcome(true, clip(out.toString()).ifBlank { "已执行" })
+ } else {
+ val raw = if (err.isNotBlank()) err.toString() else out.toString()
+ ShellOutcome(false, reason(raw))
+ }
+ } catch (_: Exception) {
+ ShellOutcome(false, "无法执行")
+ }
+ }
+
+ private fun drain(input: InputStream, into: StringBuilder) {
+ val buf = ByteArray(1024)
+ var kept = 0
+ try {
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ if (kept < 2048) {
+ val take = minOf(n, 2048 - kept)
+ into.append(String(buf, 0, take, Charsets.UTF_8))
+ kept += take
+ }
+ }
+ } catch (_: Exception) {
+ }
+ }
+
+ private fun reason(raw: String): String {
+ val text = clip(raw)
+ if (text.isBlank()) return "命令没有成功"
+ if (text.contains("Exception") || text.contains("\tat ")) return "无法执行"
+ return text
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/agent/NixLink.kt b/app/src/main/java/com/asio/tapremly/agent/NixLink.kt
new file mode 100644
index 0000000..1de7c17
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/agent/NixLink.kt
@@ -0,0 +1,42 @@
+package com.asio.tapremly.agent
+
+import com.asio.tapremly.core.Limits
+import com.asio.tapremly.core.WireOpt
+
+class LinkException(val code: String, message: String) : Exception(message)
+
+interface NixLink {
+ var onMessage: (from: String, body: String) -> Unit
+ var onReceipt: (id: String, state: String, reason: String) -> Unit
+ var onPresence: (id: String, online: Boolean) -> Unit
+ var onConnection: (state: String, reason: String) -> Unit
+ var onSession: (token: String) -> Unit
+
+ fun connect(url: String, endpointId: String, password: String?, token: String?)
+ fun send(to: String, body: String, messageId: String, opt: WireOpt): String
+ fun presence(ids: List): Map
+ fun watch(ids: List)
+ fun limits(): Limits
+ fun close()
+}
+
+object BrokenLink : NixLink {
+ override var onMessage: (from: String, body: String) -> Unit = { _, _ -> }
+ override var onReceipt: (id: String, state: String, reason: String) -> Unit = { _, _, _ -> }
+ override var onPresence: (id: String, online: Boolean) -> Unit = { _, _ -> }
+ override var onConnection: (state: String, reason: String) -> Unit = { _, _ -> }
+ override var onSession: (token: String) -> Unit = {}
+
+ override fun connect(url: String, endpointId: String, password: String?, token: String?) {
+ throw LinkException("not_connected", "没有连上")
+ }
+
+ override fun send(to: String, body: String, messageId: String, opt: WireOpt): String {
+ throw LinkException("not_connected", "没有连上")
+ }
+
+ override fun presence(ids: List): Map = emptyMap()
+ override fun watch(ids: List) = Unit
+ override fun limits(): Limits = Limits()
+ override fun close() = Unit
+}
diff --git a/app/src/main/java/com/asio/tapremly/agent/SdkNixLink.kt b/app/src/main/java/com/asio/tapremly/agent/SdkNixLink.kt
new file mode 100644
index 0000000..81d7aaf
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/agent/SdkNixLink.kt
@@ -0,0 +1,122 @@
+package com.asio.tapremly.agent
+
+import asia.asio.nixmsg.Client
+import asia.asio.nixmsg.NixMsgException
+import asia.asio.nixmsg.Types
+import com.asio.tapremly.core.DEFAULT_MAX_SCHEDULE_SECONDS
+import com.asio.tapremly.core.DEFAULT_MAX_TTL_SECONDS
+import com.asio.tapremly.core.Limits
+import com.asio.tapremly.core.WireOpt
+import java.util.concurrent.CompletionException
+
+/** 整台手机只在这里创建 NixMsg 连接。 */
+class SdkNixLink : NixLink {
+ override var onMessage: (from: String, body: String) -> Unit = { _, _ -> }
+ override var onReceipt: (id: String, state: String, reason: String) -> Unit = { _, _, _ -> }
+ override var onPresence: (id: String, online: Boolean) -> Unit = { _, _ -> }
+ override var onConnection: (state: String, reason: String) -> Unit = { _, _ -> }
+ override var onSession: (token: String) -> Unit = {}
+
+ private var client: Client? = null
+
+ override fun connect(url: String, endpointId: String, password: String?, token: String?) {
+ client?.close()
+ val next = Client()
+ wire(next)
+ client = next
+ try {
+ next.connect(url, endpointId, password, token).join()
+ } catch (e: Exception) {
+ throw unwrap(e)
+ }
+ }
+
+ override fun send(to: String, body: String, messageId: String, opt: WireOpt): String {
+ val current = client ?: throw LinkException("not_connected", "没有连上")
+ val options = Types.SendOptions()
+ options.messageId = messageId
+ options.keep = opt.keep
+ options.receipt = true
+ if (opt.keep && opt.ttlSeconds != null) options.ttlSeconds = opt.ttlSeconds
+ if (opt.sendAtMs != null) options.sendAt = opt.sendAtMs
+ val payload = Types.Body(body)
+ payload.contentType = "application/json"
+ return try {
+ current.send(Types.Target("endpoint", to), payload, options).join().state
+ } catch (e: Exception) {
+ throw unwrap(e)
+ }
+ }
+
+ override fun presence(ids: List): Map {
+ val current = client ?: return emptyMap()
+ val found = HashMap()
+ for (chunk in ids.chunked(200)) {
+ if (chunk.isEmpty()) continue
+ val data = try {
+ current.presence(chunk).join()
+ } catch (e: Exception) {
+ throw unwrap(e)
+ }
+ found.putAll(readPresence(data))
+ }
+ return found
+ }
+
+ override fun watch(ids: List) {
+ val current = client ?: return
+ if (ids.isEmpty()) return
+ try {
+ current.watchPresence(ids.take(1000), false).join()
+ } catch (e: Exception) {
+ throw unwrap(e)
+ }
+ }
+
+ override fun limits(): Limits {
+ val hello = client?.limits ?: return Limits()
+ return Limits(
+ maxTtlSeconds = if (hello.maxTtlSeconds > 0) hello.maxTtlSeconds else DEFAULT_MAX_TTL_SECONDS,
+ maxScheduleSeconds = if (hello.maxScheduleSeconds > 0) hello.maxScheduleSeconds else DEFAULT_MAX_SCHEDULE_SECONDS,
+ )
+ }
+
+ override fun close() {
+ try {
+ client?.close()
+ } catch (_: Exception) {
+ }
+ client = null
+ }
+
+ private fun wire(next: Client) {
+ next.onMessage { msg -> onMessage(msg.from, msg.body?.data.orEmpty()) }
+ next.onReceipt { receipt -> onReceipt(receipt.id, receipt.state, receipt.reason) }
+ next.onPresence { event -> onPresence(event.id, event.online) }
+ next.onConnection { event -> onConnection(event.state.name, event.reason) }
+ next.onSession { token -> onSession(token) }
+ }
+
+ private fun readPresence(data: Map): Map {
+ val items = data["items"] as? List<*> ?: return emptyMap()
+ val out = HashMap()
+ for (item in items) {
+ val row = item as? Map<*, *> ?: continue
+ val id = row["id"]?.toString().orEmpty()
+ if (id.isBlank() || row["not_found"] == true) continue
+ out[id] = row["online"] == true
+ }
+ return out
+ }
+
+ private fun unwrap(error: Exception): LinkException {
+ var current: Throwable = error
+ while (current is CompletionException && current.cause != null) {
+ current = current.cause!!
+ }
+ val nix = current as? NixMsgException
+ if (nix != null) return LinkException(nix.code, nix.message ?: nix.code)
+ if (current is LinkException) return current
+ return LinkException("not_connected", "没有连上")
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/core/ApiJson.kt b/app/src/main/java/com/asio/tapremly/core/ApiJson.kt
new file mode 100644
index 0000000..ccb29ad
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/core/ApiJson.kt
@@ -0,0 +1,131 @@
+package com.asio.tapremly.core
+
+import com.google.gson.JsonArray
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+
+data class Account(
+ val username: String,
+)
+
+data class Provision(
+ val recordId: Long,
+ val endpointId: String,
+ val password: String,
+)
+
+/** 解析 TapRemly 后端的 JSON。成功响应是 ok + data。 */
+object ApiJson {
+ fun account(raw: String, usernameFallback: String): Account? {
+ val o = data(raw) ?: return null
+ val user = text(o, "username") ?: usernameFallback
+ if (user.isBlank()) return null
+ return Account(user)
+ }
+
+ fun directory(raw: String): Pair, List> {
+ val o = data(raw) ?: return emptyList() to emptyList()
+ val devices = elements(o, "devices").mapNotNull { el ->
+ if (!el.isJsonObject) return@mapNotNull null
+ val item = el.asJsonObject
+ val endpoint = text(item, "endpoint_id") ?: return@mapNotNull null
+ if (endpoint.isBlank()) return@mapNotNull null
+ val presence = text(item, "presence").orEmpty()
+ Device(
+ id = endpoint,
+ recordId = long(item, "id"),
+ name = text(item, "name").orEmpty().ifBlank { endpoint },
+ groupId = idText(item, "group_id"),
+ online = presence == "online" || bool(item, "online"),
+ )
+ }
+ val groups = elements(o, "groups").mapNotNull { el ->
+ if (!el.isJsonObject) return@mapNotNull null
+ val item = el.asJsonObject
+ val id = idText(item, "id")
+ if (id.isBlank()) return@mapNotNull null
+ Group(id, text(item, "name").orEmpty().ifBlank { id })
+ }
+ return devices to groups
+ }
+
+ fun provision(raw: String): Provision? {
+ val o = data(raw) ?: return null
+ val endpoint = text(o, "endpoint_id") ?: return null
+ val password = text(o, "login_password") ?: return null
+ if (endpoint.isBlank() || password.isBlank()) return null
+ return Provision(long(o, "id"), endpoint, password)
+ }
+
+ fun errorMessage(raw: String): String? {
+ val root = obj(raw) ?: return null
+ val error = root.get("error")
+ if (error != null && error.isJsonObject) {
+ val message = text(error.asJsonObject, "message")
+ if (!message.isNullOrBlank()) return message
+ }
+ return null
+ }
+
+ fun logsBody(endpointId: String, items: List): String {
+ val arr = JsonArray()
+ for (item in items) {
+ val o = JsonObject()
+ o.addProperty("at_ms", item.atMs)
+ o.addProperty("summary", item.summary)
+ o.addProperty("ok", item.ok)
+ o.addProperty("result", item.detail)
+ arr.add(o)
+ }
+ val root = JsonObject()
+ root.addProperty("endpoint_id", endpointId)
+ root.add("items", arr)
+ return root.toString()
+ }
+
+ private fun data(raw: String): JsonObject? {
+ val root = obj(raw) ?: return null
+ val nested = root.get("data")
+ return if (nested != null && nested.isJsonObject) nested.asJsonObject else root
+ }
+
+ private fun elements(o: JsonObject, key: String): JsonArray {
+ if (!o.has(key) || !o.get(key).isJsonArray) return JsonArray()
+ return o.getAsJsonArray(key)
+ }
+
+ private fun text(o: JsonObject, key: String): String? {
+ if (!o.has(key) || o.get(key).isJsonNull) return null
+ val el = o.get(key)
+ return if (el.isJsonPrimitive) el.asString else null
+ }
+
+ private fun idText(o: JsonObject, key: String): String {
+ if (!o.has(key) || o.get(key).isJsonNull) return ""
+ val el = o.get(key)
+ if (!el.isJsonPrimitive) return ""
+ val prim = el.asJsonPrimitive
+ return if (prim.isNumber) prim.asLong.toString() else prim.asString
+ }
+
+ private fun long(o: JsonObject, key: String): Long {
+ if (!o.has(key) || o.get(key).isJsonNull || !o.get(key).isJsonPrimitive) return 0L
+ val prim = o.get(key).asJsonPrimitive
+ return if (prim.isNumber) prim.asLong else prim.asString.toLongOrNull() ?: 0L
+ }
+
+ private fun obj(raw: String): JsonObject? {
+ val el = try {
+ JsonParser.parseString(raw)
+ } catch (_: Exception) {
+ return null
+ }
+ return if (el.isJsonObject) el.asJsonObject else null
+ }
+
+ private fun bool(o: JsonObject, key: String): Boolean {
+ if (!o.has(key) || o.get(key).isJsonNull || !o.get(key).isJsonPrimitive) return false
+ val el = o.get(key).asJsonPrimitive
+ return el.isBoolean && el.asBoolean
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/core/Books.kt b/app/src/main/java/com/asio/tapremly/core/Books.kt
new file mode 100644
index 0000000..adce10d
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/core/Books.kt
@@ -0,0 +1,78 @@
+package com.asio.tapremly.core
+
+/** 本端快捷命令:按远端分开。复制只给选中的远端各插入一条新记录。 */
+class LocalCommands(private val newId: () -> String = { Protocol.newId() }) {
+ private val rows = mutableListOf()
+
+ data class Row(
+ val id: String,
+ val remoteId: String,
+ val name: String,
+ val shell: String,
+ val confirm: Boolean,
+ )
+
+ fun forRemote(remoteId: String): List =
+ rows.filter { it.remoteId == remoteId }.map { it.toShortcut() }
+
+ fun find(id: String): Row? = rows.find { it.id == id }
+
+ fun add(remoteId: String, name: String, shell: String, confirm: Boolean): Row {
+ val row = Row(newId(), remoteId, name, shell, confirm)
+ rows.add(row)
+ return row
+ }
+
+ fun update(id: String, name: String, shell: String, confirm: Boolean): Boolean {
+ val i = rows.indexOfFirst { it.id == id }
+ if (i < 0) return false
+ val old = rows[i]
+ rows[i] = old.copy(name = name, shell = shell, confirm = confirm)
+ return true
+ }
+
+ fun delete(id: String): Boolean = rows.removeAll { it.id == id }
+
+ fun copyTo(id: String, remoteIds: List): List {
+ val src = find(id) ?: return emptyList()
+ val created = mutableListOf()
+ for (remote in remoteIds) {
+ if (remote.isBlank()) continue
+ val row = Row(newId(), remote, src.name, src.shell, src.confirm)
+ rows.add(row)
+ created.add(row)
+ }
+ return created
+ }
+
+ private fun Row.toShortcut() = Shortcut(id, name, shell, confirm)
+}
+
+/**
+ * 临时命令只发送,不写入快捷命令。
+ * 只有 save 才会进入当前远端的本端列表。
+ */
+class TempShell(private val book: LocalCommands) {
+ val sent = mutableListOf>()
+
+ fun send(remoteId: String, shell: String) {
+ sent.add(remoteId to shell)
+ }
+
+ fun save(remoteId: String, name: String, shell: String, confirm: Boolean): LocalCommands.Row =
+ book.add(remoteId, name, shell, confirm)
+}
+
+/** 本地命令日志,只留最近 [max] 条。上传用最近 20 条。 */
+class LogBook(private val max: Int = 500) {
+ private val rows = ArrayDeque()
+
+ fun add(entry: LogEntry) {
+ rows.addLast(entry)
+ while (rows.size > max) rows.removeFirst()
+ }
+
+ fun all(): List = rows.toList()
+
+ fun latest(n: Int): List = rows.takeLast(n)
+}
diff --git a/app/src/main/java/com/asio/tapremly/core/Engine.kt b/app/src/main/java/com/asio/tapremly/core/Engine.kt
new file mode 100644
index 0000000..8e2315e
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/core/Engine.kt
@@ -0,0 +1,107 @@
+package com.asio.tapremly.core
+
+/**
+ * 被控端处理。只认本机信任名单,不看命令内容,也不再询问。
+ * 同一个命令号 24 小时内只执行一次,再次到达时重发第一次的结果。
+ * 调用方应在同一条线程上使用。
+ */
+class Engine(
+ private val trusted: (String) -> Boolean,
+ private val published: (String) -> Shortcut?,
+ private val allPublished: () -> List,
+ private val runner: ShellRunner,
+ private val executed: ExecutedStore,
+ private val now: () -> Long,
+ private val onText: (from: String, text: String) -> Unit,
+ private val onShortcuts: (from: String, items: List) -> Unit,
+ private val onLog: (LogEntry) -> Unit,
+) {
+ /** 需要回复时返回正文,否则返回 null。 */
+ fun handle(from: String, raw: String): String? {
+ val msg = Protocol.parse(raw) ?: return null
+ if (msg.v != 1) return null
+ return when (msg.type) {
+ "shell" -> runCommand(from, msg.id, msg.shell, summary = msg.shell.orEmpty())
+ "shortcut" -> runShortcut(from, msg)
+ "text" -> {
+ val text = msg.text
+ if (!text.isNullOrEmpty()) onText(from, text)
+ null
+ }
+ "shortcuts" -> onShortcutMessage(from, msg)
+ else -> null
+ }
+ }
+
+ private fun runShortcut(from: String, msg: Message): String? {
+ val id = msg.id
+ if (!Protocol.validId(id)) return null
+ val sid = msg.shortcutId
+ if (sid.isNullOrBlank()) {
+ return finish(id!!, false, "这条命令已经没有了", "这条命令已经没有了")
+ }
+ val remembered = executed.get(id!!, now())
+ if (remembered != null) {
+ return Protocol.result(id, remembered.ok, remembered.error, duplicate = true)
+ }
+ if (!trusted(from)) {
+ return finish(id, false, "not_trusted", clip(sid))
+ }
+ val item = published(sid)
+ if (item == null) {
+ return finish(id, false, "这条命令已经没有了", sid)
+ }
+ return execute(id, item.shell, item.name.ifBlank { item.shell })
+ }
+
+ private fun runCommand(from: String, id: String?, shell: String?, summary: String): String? {
+ if (!Protocol.validId(id)) return null
+ val remembered = executed.get(id!!, now())
+ if (remembered != null) {
+ return Protocol.result(id, remembered.ok, remembered.error, duplicate = true)
+ }
+ if (!trusted(from)) {
+ return finish(id, false, "not_trusted", summary)
+ }
+ if (shell.isNullOrBlank()) {
+ return finish(id, false, "没有命令", summary)
+ }
+ return execute(id, shell, summary)
+ }
+
+ private fun execute(id: String, shell: String, summary: String): String {
+ // 先记下,进程若被这条命令结束,重试不会再跑一次。
+ executed.put(id, Stored(false, "无法执行"), now())
+ val outcome = try {
+ runner.run(shell)
+ } catch (_: Exception) {
+ ShellOutcome(false, "无法执行")
+ }
+ val error = if (outcome.ok) null else outcome.detail.ifBlank { "命令没有成功" }
+ executed.put(id, Stored(outcome.ok, error), now())
+ val detail = if (outcome.ok) outcome.detail.ifBlank { "已执行" } else error!!
+ onLog(LogEntry(now(), clip(summary), outcome.ok, clip(detail)))
+ return Protocol.result(id, outcome.ok, error, duplicate = false)
+ }
+
+ private fun finish(id: String, ok: Boolean, error: String, summary: String): String {
+ executed.put(id, Stored(ok, error), now())
+ val detail = if (error == "not_trusted") "尚未信任" else error
+ onLog(LogEntry(now(), clip(summary), ok, detail))
+ return Protocol.result(id, ok, error, duplicate = false)
+ }
+
+ private fun onShortcutMessage(from: String, msg: Message): String? {
+ val items = msg.items
+ if (items != null) {
+ onShortcuts(from, items)
+ return null
+ }
+ val id = msg.id
+ if (!Protocol.validId(id)) return null
+ if (!trusted(from)) {
+ return Protocol.result(id!!, false, "not_trusted", duplicate = false)
+ }
+ return Protocol.shortcuts(allPublished())
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/core/Models.kt b/app/src/main/java/com/asio/tapremly/core/Models.kt
new file mode 100644
index 0000000..57624cc
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/core/Models.kt
@@ -0,0 +1,126 @@
+package com.asio.tapremly.core
+
+/** 一天,已执行命令号的最短记忆时间。 */
+const val DAY_MS = 24L * 60L * 60L * 1000L
+
+/** 默认离线保留上限:30 天。握手后用服务器给的值。 */
+const val DEFAULT_MAX_TTL_SECONDS = 30L * 24L * 60L * 60L
+
+/** 默认定时上限:365 天。 */
+const val DEFAULT_MAX_SCHEDULE_SECONDS = 365L * 24L * 60L * 60L
+
+data class Shortcut(
+ val id: String,
+ val name: String,
+ val shell: String,
+ val confirm: Boolean,
+)
+
+data class Device(
+ val id: String,
+ val recordId: Long,
+ val name: String,
+ val groupId: String,
+ val online: Boolean,
+)
+
+data class Group(
+ val id: String,
+ val name: String,
+)
+
+data class LogEntry(
+ val atMs: Long,
+ val summary: String,
+ val ok: Boolean,
+ val detail: String,
+)
+
+data class InboxText(
+ val atMs: Long,
+ val fromId: String,
+ val text: String,
+)
+
+data class Stored(
+ val ok: Boolean,
+ val error: String?,
+)
+
+data class ShellOutcome(
+ val ok: Boolean,
+ val detail: String,
+)
+
+fun interface ShellRunner {
+ fun run(shell: String): ShellOutcome
+}
+
+interface ExecutedStore {
+ fun get(id: String, now: Long): Stored?
+ fun put(id: String, value: Stored, now: Long)
+}
+
+class MemoryExecuted : ExecutedStore {
+ private val rows = HashMap>()
+
+ override fun get(id: String, now: Long): Stored? {
+ val row = rows[id] ?: return null
+ if (now - row.second > DAY_MS) {
+ rows.remove(id)
+ return null
+ }
+ return row.first
+ }
+
+ override fun put(id: String, value: Stored, now: Long) {
+ rows[id] = value to now
+ }
+}
+
+data class Limits(
+ val maxTtlSeconds: Long = DEFAULT_MAX_TTL_SECONDS,
+ val maxScheduleSeconds: Long = DEFAULT_MAX_SCHEDULE_SECONDS,
+)
+
+/** 发送区只有一套选项。keep 默认关。 */
+data class SendForm(
+ val scheduled: Boolean = false,
+ val sendAtMs: Long? = null,
+ val keep: Boolean = false,
+ val ttlSeconds: Long? = null,
+)
+
+/** 交给 SDK 的发送选项。时刻已过则不带定时。 */
+data class WireOpt(
+ val sendAtMs: Long? = null,
+ val keep: Boolean = false,
+ val ttlSeconds: Long? = null,
+)
+
+fun SendForm.problems(now: Long, limits: Limits): String? {
+ if (scheduled) {
+ val at = sendAtMs ?: return "请选择时刻"
+ if (at - now > limits.maxScheduleSeconds * 1000L) return "定时太远了"
+ }
+ if (keep) {
+ val ttl = ttlSeconds ?: return "请填写有效期"
+ if (ttl <= 0L) return "请填写有效期"
+ if (ttl > limits.maxTtlSeconds) return "有效期超过上限"
+ }
+ return null
+}
+
+fun SendForm.toWire(now: Long): WireOpt {
+ val at = if (scheduled && sendAtMs != null && sendAtMs > now) sendAtMs else null
+ return WireOpt(
+ sendAtMs = at,
+ keep = keep,
+ ttlSeconds = if (keep) ttlSeconds else null,
+ )
+}
+
+fun clip(text: String, limit: Int = 80): String {
+ val one = text.replace(Regex("\\s+"), " ").trim()
+ return if (one.length <= limit) one else one.take(limit)
+}
diff --git a/app/src/main/java/com/asio/tapremly/core/Protocol.kt b/app/src/main/java/com/asio/tapremly/core/Protocol.kt
new file mode 100644
index 0000000..4117fc8
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/core/Protocol.kt
@@ -0,0 +1,146 @@
+package com.asio.tapremly.core
+
+import com.google.gson.JsonArray
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+import java.util.UUID
+
+/**
+ * 正文 v=1。类型只有 shell、shortcut、text、shortcuts、result。
+ * shortcuts 带 items 表示对方公布的列表(空数组也算公布);
+ * 不带 items、只带 id,表示向对方要列表。
+ */
+data class Message(
+ val v: Int,
+ val type: String,
+ val id: String?,
+ val shell: String?,
+ val shortcutId: String?,
+ val text: String?,
+ val items: List?,
+ val ok: Boolean?,
+ val error: String?,
+ val duplicate: Boolean,
+)
+
+object Protocol {
+ private val idPattern = Regex("^[A-Za-z0-9_.\\-]{1,64}$")
+
+ fun validId(id: String?): Boolean = id != null && idPattern.matches(id)
+
+ fun newId(): String = UUID.randomUUID().toString()
+
+ fun parse(raw: String): Message? {
+ val root = try {
+ JsonParser.parseString(raw)
+ } catch (_: Exception) {
+ return null
+ }
+ if (!root.isJsonObject) return null
+ val o = root.asJsonObject
+ val items = if (o.has("items") && o.get("items").isJsonArray) {
+ o.getAsJsonArray("items").mapNotNull { el ->
+ if (!el.isJsonObject) return@mapNotNull null
+ val it = el.asJsonObject
+ val id = it.string("id") ?: return@mapNotNull null
+ Shortcut(
+ id = id,
+ name = it.string("name").orEmpty(),
+ shell = it.string("shell").orEmpty(),
+ confirm = it.bool("confirm"),
+ )
+ }
+ } else {
+ null
+ }
+ return Message(
+ v = o.int("v"),
+ type = o.string("type").orEmpty(),
+ id = o.string("id"),
+ shell = o.string("shell"),
+ shortcutId = o.string("shortcut_id"),
+ text = o.string("text"),
+ items = items,
+ ok = if (o.has("ok") && !o.get("ok").isJsonNull) o.get("ok").asBoolean else null,
+ error = o.string("error"),
+ duplicate = o.bool("duplicate"),
+ )
+ }
+
+ fun shell(id: String, shell: String): String = obj {
+ addProperty("v", 1)
+ addProperty("type", "shell")
+ addProperty("id", id)
+ addProperty("shell", shell)
+ }
+
+ fun shortcut(id: String, shortcutId: String): String = obj {
+ addProperty("v", 1)
+ addProperty("type", "shortcut")
+ addProperty("id", id)
+ addProperty("shortcut_id", shortcutId)
+ }
+
+ fun text(id: String, text: String): String = obj {
+ addProperty("v", 1)
+ addProperty("type", "text")
+ addProperty("id", id)
+ addProperty("text", text)
+ }
+
+ fun shortcuts(items: List): String {
+ val arr = JsonArray()
+ for (s in items) {
+ val it = JsonObject()
+ it.addProperty("id", s.id)
+ it.addProperty("name", s.name)
+ it.addProperty("shell", s.shell)
+ it.addProperty("confirm", s.confirm)
+ arr.add(it)
+ }
+ return obj {
+ addProperty("v", 1)
+ addProperty("type", "shortcuts")
+ add("items", arr)
+ }
+ }
+
+ fun shortcutsQuery(id: String): String = obj {
+ addProperty("v", 1)
+ addProperty("type", "shortcuts")
+ addProperty("id", id)
+ }
+
+ fun result(id: String, ok: Boolean, error: String?, duplicate: Boolean): String = obj {
+ addProperty("v", 1)
+ addProperty("type", "result")
+ addProperty("id", id)
+ addProperty("ok", ok)
+ if (!error.isNullOrEmpty()) addProperty("error", error)
+ if (duplicate) addProperty("duplicate", true)
+ }
+
+ private fun obj(fill: JsonObject.() -> Unit): String {
+ val o = JsonObject()
+ o.fill()
+ return o.toString()
+ }
+
+ private fun JsonObject.string(key: String): String? {
+ if (!has(key) || get(key).isJsonNull) return null
+ val el = get(key)
+ return if (el.isJsonPrimitive) el.asString else null
+ }
+
+ private fun JsonObject.bool(key: String): Boolean {
+ if (!has(key) || get(key).isJsonNull || !get(key).isJsonPrimitive) return false
+ val el = get(key)
+ return if (el.asJsonPrimitive.isBoolean) el.asBoolean else false
+ }
+
+ private fun JsonObject.int(key: String): Int {
+ if (!has(key) || get(key).isJsonNull || !get(key).isJsonPrimitive) return 0
+ val el = get(key)
+ return if (el.asJsonPrimitive.isNumber) el.asInt else 0
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/data/AppDb.kt b/app/src/main/java/com/asio/tapremly/data/AppDb.kt
new file mode 100644
index 0000000..2f7fbb3
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/data/AppDb.kt
@@ -0,0 +1,276 @@
+package com.asio.tapremly.data
+
+import android.content.ContentValues
+import android.content.Context
+import android.database.sqlite.SQLiteDatabase
+import android.database.sqlite.SQLiteOpenHelper
+import com.asio.tapremly.core.DAY_MS
+import com.asio.tapremly.core.Device
+import com.asio.tapremly.core.Group
+import com.asio.tapremly.core.InboxText
+import com.asio.tapremly.core.LogEntry
+import com.asio.tapremly.core.Protocol
+import com.asio.tapremly.core.Shortcut
+import com.asio.tapremly.core.Stored
+
+class AppDb(context: Context) : SQLiteOpenHelper(context.applicationContext, "tapremly.db", null, 1) {
+ private val gate = Any()
+
+ override fun onCreate(db: SQLiteDatabase) {
+ db.execSQL("CREATE TABLE device_cache (id TEXT PRIMARY KEY, record_id INTEGER NOT NULL, name TEXT NOT NULL, group_id TEXT NOT NULL, online INTEGER NOT NULL, pos INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE group_cache (id TEXT PRIMARY KEY, name TEXT NOT NULL, pos INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE local_shortcut (id TEXT PRIMARY KEY, remote_id TEXT NOT NULL, name TEXT NOT NULL, shell TEXT NOT NULL, confirm INTEGER NOT NULL)")
+ db.execSQL("CREATE INDEX idx_local_remote ON local_shortcut(remote_id)")
+ db.execSQL("CREATE TABLE remote_shortcut (remote_id TEXT NOT NULL, id TEXT NOT NULL, name TEXT NOT NULL, shell TEXT NOT NULL, confirm INTEGER NOT NULL, PRIMARY KEY(remote_id, id))")
+ db.execSQL("CREATE TABLE remote_sync (remote_id TEXT PRIMARY KEY, synced_at INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE published (id TEXT PRIMARY KEY, name TEXT NOT NULL, shell TEXT NOT NULL, confirm INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE trust (endpoint_id TEXT PRIMARY KEY, added_at INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE executed (id TEXT PRIMARY KEY, ok INTEGER NOT NULL, error TEXT NOT NULL, at_ms INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE command_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, at_ms INTEGER NOT NULL, summary TEXT NOT NULL, ok INTEGER NOT NULL, detail TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE inbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, at_ms INTEGER NOT NULL, from_id TEXT NOT NULL, body TEXT NOT NULL)")
+ }
+
+ override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit
+
+ fun replaceDirectory(devices: List, groups: List) = tx {
+ delete("device_cache", null, null)
+ delete("group_cache", null, null)
+ devices.forEachIndexed { index, device ->
+ insert("device_cache", null, values(
+ "id" to device.id,
+ "record_id" to device.recordId,
+ "name" to device.name,
+ "group_id" to device.groupId,
+ "online" to if (device.online) 1 else 0,
+ "pos" to index,
+ ))
+ }
+ groups.forEachIndexed { index, group ->
+ insert("group_cache", null, values(
+ "id" to group.id,
+ "name" to group.name,
+ "pos" to index,
+ ))
+ }
+ }
+
+ fun clearDirectory() = tx {
+ delete("device_cache", null, null)
+ delete("group_cache", null, null)
+ }
+
+ fun devices(): List = read(
+ "SELECT id, record_id, name, group_id, online FROM device_cache ORDER BY pos",
+ ) {
+ Device(str(0), long(1), str(2), str(3), int(4) != 0)
+ }
+
+ fun groups(): List = read(
+ "SELECT id, name FROM group_cache ORDER BY pos",
+ ) { Group(str(0), str(1)) }
+
+ fun addLocal(remoteId: String, name: String, shell: String, confirm: Boolean): String = tx {
+ val id = Protocol.newId()
+ insert("local_shortcut", null, values(
+ "id" to id,
+ "remote_id" to remoteId,
+ "name" to name,
+ "shell" to shell,
+ "confirm" to if (confirm) 1 else 0,
+ ))
+ id
+ }
+
+ fun updateLocal(id: String, name: String, shell: String, confirm: Boolean) = tx {
+ update("local_shortcut", values(
+ "name" to name,
+ "shell" to shell,
+ "confirm" to if (confirm) 1 else 0,
+ ), "id=?", arrayOf(id))
+ }
+
+ fun deleteLocal(id: String) = tx { delete("local_shortcut", "id=?", arrayOf(id)) }
+
+ fun copyLocal(name: String, shell: String, confirm: Boolean, remoteIds: List) = tx {
+ for (remote in remoteIds) {
+ if (remote.isBlank()) continue
+ insert("local_shortcut", null, values(
+ "id" to Protocol.newId(),
+ "remote_id" to remote,
+ "name" to name,
+ "shell" to shell,
+ "confirm" to if (confirm) 1 else 0,
+ ))
+ }
+ }
+
+ fun localByRemote(): Map> = read(
+ "SELECT id, remote_id, name, shell, confirm FROM local_shortcut ORDER BY rowid",
+ ) {
+ str(1) to Shortcut(str(0), str(2), str(3), int(4) != 0)
+ }.groupBy({ it.first }, { it.second })
+
+ fun replaceRemote(remoteId: String, items: List, atMs: Long) = tx {
+ delete("remote_shortcut", "remote_id=?", arrayOf(remoteId))
+ for (item in items) {
+ insert("remote_shortcut", null, values(
+ "remote_id" to remoteId,
+ "id" to item.id,
+ "name" to item.name,
+ "shell" to item.shell,
+ "confirm" to if (item.confirm) 1 else 0,
+ ))
+ }
+ delete("remote_sync", "remote_id=?", arrayOf(remoteId))
+ insert("remote_sync", null, values("remote_id" to remoteId, "synced_at" to atMs))
+ }
+
+ fun remoteByRemote(): Map> = read(
+ "SELECT remote_id, id, name, shell, confirm FROM remote_shortcut ORDER BY rowid",
+ ) {
+ str(0) to Shortcut(str(1), str(2), str(3), int(4) != 0)
+ }.groupBy({ it.first }, { it.second })
+
+ fun remoteSyncAt(): Map = read(
+ "SELECT remote_id, synced_at FROM remote_sync",
+ ) { str(0) to long(1) }.toMap()
+
+ fun listPublished(): List = read(
+ "SELECT id, name, shell, confirm FROM published ORDER BY rowid",
+ ) { Shortcut(str(0), str(1), str(2), int(3) != 0) }
+
+ fun findPublished(id: String): Shortcut? = read(
+ "SELECT id, name, shell, confirm FROM published WHERE id=?",
+ arrayOf(id),
+ ) { Shortcut(str(0), str(1), str(2), int(3) != 0) }.firstOrNull()
+
+ fun addPublished(name: String, shell: String, confirm: Boolean) = tx {
+ insert("published", null, values(
+ "id" to Protocol.newId(),
+ "name" to name,
+ "shell" to shell,
+ "confirm" to if (confirm) 1 else 0,
+ ))
+ }
+
+ fun updatePublished(id: String, name: String, shell: String, confirm: Boolean) = tx {
+ update("published", values(
+ "name" to name,
+ "shell" to shell,
+ "confirm" to if (confirm) 1 else 0,
+ ), "id=?", arrayOf(id))
+ }
+
+ fun deletePublished(id: String) = tx { delete("published", "id=?", arrayOf(id)) }
+
+ fun listTrust(): List = read(
+ "SELECT endpoint_id FROM trust ORDER BY added_at",
+ ) { str(0) }
+
+ fun addTrust(id: String, atMs: Long) = tx {
+ delete("trust", "endpoint_id=?", arrayOf(id))
+ insert("trust", null, values("endpoint_id" to id, "added_at" to atMs))
+ }
+
+ fun removeTrust(id: String) = tx { delete("trust", "endpoint_id=?", arrayOf(id)) }
+
+ fun isTrusted(id: String): Boolean = read(
+ "SELECT 1 FROM trust WHERE endpoint_id=?",
+ arrayOf(id),
+ ) { 1 }.isNotEmpty()
+
+ fun getExecuted(id: String, now: Long): Stored? {
+ val row = read(
+ "SELECT ok, error, at_ms FROM executed WHERE id=?",
+ arrayOf(id),
+ ) { Triple(int(0) != 0, str(1), long(2)) }.firstOrNull() ?: return null
+ if (now - row.third > DAY_MS) {
+ tx { delete("executed", "id=?", arrayOf(id)) }
+ return null
+ }
+ return Stored(row.first, row.second.ifEmpty { null })
+ }
+
+ fun putExecuted(id: String, value: Stored, now: Long) = tx {
+ delete("executed", "id=?", arrayOf(id))
+ insert("executed", null, values(
+ "id" to id,
+ "ok" to if (value.ok) 1 else 0,
+ "error" to value.error.orEmpty(),
+ "at_ms" to now,
+ ))
+ delete("executed", "at_ms", arrayOf((now - DAY_MS).toString()))
+ }
+
+ fun addLog(entry: LogEntry) = tx {
+ insert("command_log", null, values(
+ "at_ms" to entry.atMs,
+ "summary" to entry.summary,
+ "ok" to if (entry.ok) 1 else 0,
+ "detail" to entry.detail,
+ ))
+ execSQL("DELETE FROM command_log WHERE seq NOT IN (SELECT seq FROM command_log ORDER BY seq DESC LIMIT 500)")
+ }
+
+ fun logs(): List = read(
+ "SELECT at_ms, summary, ok, detail FROM command_log ORDER BY seq",
+ ) { LogEntry(long(0), str(1), int(2) != 0, str(3)) }
+
+ fun latestLogs(n: Int): List = logs().takeLast(n)
+
+ fun addInbox(item: InboxText) = tx {
+ insert("inbox", null, values(
+ "at_ms" to item.atMs,
+ "from_id" to item.fromId,
+ "body" to item.text,
+ ))
+ execSQL("DELETE FROM inbox WHERE seq NOT IN (SELECT seq FROM inbox ORDER BY seq DESC LIMIT 100)")
+ }
+
+ fun inbox(): List = read(
+ "SELECT at_ms, from_id, body FROM inbox ORDER BY seq DESC",
+ ) { InboxText(long(0), str(1), str(2)) }
+
+ private fun tx(block: SQLiteDatabase.() -> T): T = synchronized(gate) {
+ val db = writableDatabase
+ db.beginTransaction()
+ try {
+ val value = db.block()
+ db.setTransactionSuccessful()
+ value
+ } finally {
+ db.endTransaction()
+ }
+ }
+
+ private fun read(sql: String, args: Array? = null, map: CursorRow.() -> T): List =
+ synchronized(gate) {
+ val cursor = readableDatabase.rawQuery(sql, args)
+ cursor.use {
+ val out = ArrayList(it.count)
+ val row = CursorRow(it)
+ while (it.moveToNext()) out.add(row.map())
+ out
+ }
+ }
+}
+
+private class CursorRow(private val cursor: android.database.Cursor) {
+ fun str(i: Int): String = cursor.getString(i).orEmpty()
+ fun int(i: Int): Int = cursor.getInt(i)
+ fun long(i: Int): Long = cursor.getLong(i)
+}
+
+private fun values(vararg pairs: Pair): ContentValues {
+ val values = ContentValues()
+ for ((key, value) in pairs) {
+ when (value) {
+ null -> values.putNull(key)
+ is String -> values.put(key, value)
+ is Int -> values.put(key, value)
+ is Long -> values.put(key, value)
+ else -> values.put(key, value.toString())
+ }
+ }
+ return values
+}
diff --git a/app/src/main/java/com/asio/tapremly/data/Prefs.kt b/app/src/main/java/com/asio/tapremly/data/Prefs.kt
new file mode 100644
index 0000000..0e6377a
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/data/Prefs.kt
@@ -0,0 +1,77 @@
+package com.asio.tapremly.data
+
+import android.content.Context
+
+class Prefs(context: Context) {
+ private val sp = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
+
+ var serverUrl: String
+ get() = sp.getString(KEY_SERVER, DEFAULT_SERVER)?.trim().orEmpty().ifBlank { DEFAULT_SERVER }
+ set(value) = sp.edit().putString(KEY_SERVER, value.trim()).apply()
+
+ var nixUrl: String
+ get() = sp.getString(KEY_NIX, DEFAULT_NIX)?.trim().orEmpty().ifBlank { DEFAULT_NIX }
+ set(value) = sp.edit().putString(KEY_NIX, value.trim()).apply()
+
+ var username: String
+ get() = sp.getString(KEY_USER, "").orEmpty()
+ set(value) = sp.edit().putString(KEY_USER, value).apply()
+
+ var endpointId: String
+ get() = sp.getString(KEY_ENDPOINT, "").orEmpty()
+ set(value) = sp.edit().putString(KEY_ENDPOINT, value).apply()
+
+ var nixToken: String
+ get() = sp.getString(KEY_TOKEN, "").orEmpty()
+ set(value) = sp.edit().putString(KEY_TOKEN, value).apply()
+
+ var nixPassword: String
+ get() = sp.getString(KEY_PASSWORD, "").orEmpty()
+ set(value) = sp.edit().putString(KEY_PASSWORD, value).apply()
+
+ var apiToken: String
+ get() = sp.getString(KEY_API, "").orEmpty()
+ set(value) = sp.edit().putString(KEY_API, value).apply()
+
+ var cookieHeader: String
+ get() = sp.getString(KEY_COOKIE, "").orEmpty()
+ set(value) = sp.edit().putString(KEY_COOKIE, value).commit().let { }
+
+ val loggedIn: Boolean
+ get() = sp.getBoolean(KEY_SIGNED_IN, false) && cookieHeader.isNotBlank()
+
+ val nixReady: Boolean
+ get() = endpointId.isNotBlank() && (nixToken.isNotBlank() || nixPassword.isNotBlank())
+
+ fun saveAccount(username: String) {
+ sp.edit().putString(KEY_USER, username).putBoolean(KEY_SIGNED_IN, true).commit()
+ }
+
+ fun clearSession() {
+ sp.edit()
+ .remove(KEY_USER)
+ .remove(KEY_API)
+ .remove(KEY_COOKIE)
+ .putBoolean(KEY_SIGNED_IN, false)
+ .commit()
+ }
+
+ fun clearCookies() {
+ sp.edit().remove(KEY_COOKIE).commit()
+ }
+
+ companion object {
+ const val DEFAULT_SERVER = "http://10.0.2.2:8080"
+ const val DEFAULT_NIX = "ws://10.0.2.2:7443/mqtt"
+ private const val FILE = "tapremly"
+ private const val KEY_SERVER = "server"
+ private const val KEY_NIX = "nix"
+ private const val KEY_USER = "user"
+ private const val KEY_ENDPOINT = "endpoint"
+ private const val KEY_TOKEN = "nix_token"
+ private const val KEY_PASSWORD = "nix_password"
+ private const val KEY_API = "api_token"
+ private const val KEY_COOKIE = "cookies"
+ private const val KEY_SIGNED_IN = "signed_in"
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/data/TapApi.kt b/app/src/main/java/com/asio/tapremly/data/TapApi.kt
new file mode 100644
index 0000000..d7d27d6
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/data/TapApi.kt
@@ -0,0 +1,164 @@
+package com.asio.tapremly.data
+
+import com.asio.tapremly.core.Account
+import com.asio.tapremly.core.ApiJson
+import com.asio.tapremly.core.Device
+import com.asio.tapremly.core.Group
+import com.asio.tapremly.core.LogEntry
+import com.asio.tapremly.core.Provision
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+class ApiException(message: String) : Exception(message)
+
+class TapApi(private val prefs: Prefs) {
+ private val json = "application/json; charset=utf-8".toMediaType()
+ private val http = OkHttpClient.Builder()
+ .connectTimeout(20, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .build()
+
+ fun login(username: String, password: String): Account = account("login", username, password)
+
+ fun register(username: String, password: String): Account = account("register", username, password)
+
+ fun logout() {
+ call("POST", listOf("api", "logout"), "{}", bearer = null)
+ }
+
+ fun directory(): Pair, List> =
+ ApiJson.directory(call("GET", listOf("api", "devices"), null, bearer = null))
+
+ fun createGroup(name: String) {
+ call("POST", listOf("api", "groups"), """{"name":${quote(name)}}""", bearer = null)
+ }
+
+ fun renameGroup(id: String, name: String) {
+ call("PATCH", listOf("api", "groups", id), """{"name":${quote(name)}}""", bearer = null)
+ }
+
+ fun deleteGroup(id: String) {
+ call("DELETE", listOf("api", "groups", id), null, bearer = null)
+ }
+
+ fun addDevice(name: String, endpointId: String) {
+ call(
+ "POST",
+ listOf("api", "devices"),
+ """{"name":${quote(name)},"endpoint_id":${quote(endpointId)}}""",
+ bearer = null,
+ )
+ }
+
+ fun provisionSelf(name: String): Provision {
+ val raw = call(
+ "POST",
+ listOf("api", "devices"),
+ """{"name":${quote(name)},"endpoint_id":""}""",
+ bearer = null,
+ )
+ return ApiJson.provision(raw) ?: throw ApiException("没有拿到本机的连接信息")
+ }
+
+ fun moveDevice(recordId: Long, groupId: String) {
+ val group = if (groupId.isBlank()) "null" else groupId
+ call(
+ "PATCH",
+ listOf("api", "devices", recordId.toString()),
+ """{"group_id":$group}""",
+ bearer = null,
+ )
+ }
+
+ fun removeDevice(recordId: Long) {
+ call("DELETE", listOf("api", "devices", recordId.toString()), null, bearer = null)
+ }
+
+ fun putLogs(endpointId: String, password: String, items: List) {
+ if (password.isBlank() || items.isEmpty()) return
+ call("PUT", listOf("api", "command-logs"), ApiJson.logsBody(endpointId, items), bearer = password)
+ }
+
+ private fun account(path: String, username: String, password: String): Account {
+ val raw = call(
+ "POST",
+ listOf("api", path),
+ """{"username":${quote(username)},"password":${quote(password)}}""",
+ bearer = null,
+ )
+ val account = ApiJson.account(raw, username) ?: throw ApiException("没有登录成功")
+ prefs.saveAccount(account.username)
+ return account
+ }
+
+ private fun call(method: String, path: List, body: String?, bearer: String?): String {
+ val base = prefs.serverUrl.trim().trimEnd('/').let {
+ if (it.startsWith("http://") || it.startsWith("https://")) it else throw ApiException("服务器地址不对")
+ }
+ val url = base.toHttpUrlOrNull()?.newBuilder()?.apply {
+ path.forEach { addPathSegment(it) }
+ }?.build() ?: throw ApiException("服务器地址不对")
+ val builder = Request.Builder().url(url).header("Accept", "application/json")
+ if (method != "GET") builder.header("X-Tapremly-Request", "1")
+ val cookie = prefs.cookieHeader
+ if (cookie.isNotBlank()) builder.header("Cookie", cookie)
+ if (!bearer.isNullOrBlank()) builder.header("Authorization", "Bearer $bearer")
+ val request = when (method) {
+ "GET" -> builder.get().build()
+ "DELETE" -> builder.delete().build()
+ else -> builder.method(method, (body ?: "{}").toRequestBody(json)).build()
+ }
+ try {
+ http.newCall(request).execute().use { response ->
+ absorbCookies(response.headers("Set-Cookie"))
+ val text = response.body?.string().orEmpty()
+ if (!response.isSuccessful) {
+ throw ApiException(ApiJson.errorMessage(text) ?: "没有完成操作")
+ }
+ return text
+ }
+ } catch (e: ApiException) {
+ throw e
+ } catch (_: IOException) {
+ throw ApiException("暂时连不上服务器")
+ }
+ }
+
+ private fun absorbCookies(setCookies: List) {
+ if (setCookies.isEmpty()) return
+ val map = linkedMapOf()
+ prefs.cookieHeader.split(';').forEach { part ->
+ val piece = part.trim()
+ val name = piece.substringBefore('=', "")
+ if (name.isNotBlank() && piece.contains('=')) map[name] = piece.substringAfter('=')
+ }
+ for (header in setCookies) {
+ val pair = header.substringBefore(';').trim()
+ val name = pair.substringBefore('=', "")
+ if (name.isBlank()) continue
+ val value = pair.substringAfter('=', "")
+ if (value.isEmpty()) map.remove(name) else map[name] = value
+ }
+ prefs.cookieHeader = map.entries.joinToString("; ") { "${it.key}=${it.value}" }
+ }
+
+ private fun quote(value: String): String = buildString {
+ append('"')
+ for (ch in value) {
+ when (ch) {
+ '\\' -> append("\\\\")
+ '"' -> append("\\\"")
+ '\n' -> append("\\n")
+ '\r' -> append("\\r")
+ else -> append(ch)
+ }
+ }
+ append('"')
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/AgentActivity.kt b/app/src/main/java/com/asio/tapremly/ui/AgentActivity.kt
new file mode 100644
index 0000000..ea9740f
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/AgentActivity.kt
@@ -0,0 +1,74 @@
+package com.asio.tapremly.ui
+
+import android.content.ComponentName
+import android.content.Intent
+import android.content.ServiceConnection
+import android.os.IBinder
+import android.view.View
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import com.asio.tapremly.agent.AgentListener
+import com.asio.tapremly.agent.AgentRuntime
+import com.asio.tapremly.agent.AgentService
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.data.Prefs
+import com.google.android.material.snackbar.Snackbar
+
+abstract class AgentActivity : AppCompatActivity(), AgentListener {
+ protected var runtime: AgentRuntime? = null
+ private var bound = false
+ private val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
+ if (!bound) return
+ runtime = (service as AgentService.LocalBinder).get()
+ runtime?.addListener(this@AgentActivity)
+ onBound(runtime)
+ }
+
+ override fun onServiceDisconnected(name: ComponentName?) {
+ runtime?.removeListener(this@AgentActivity)
+ runtime = null
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ if (!Prefs(this).loggedIn) {
+ startActivity(Intent(this, LoginActivity::class.java))
+ finish()
+ return
+ }
+ val intent = Intent(this, AgentService::class.java)
+ ContextCompat.startForegroundService(this, intent)
+ bindService(intent, connection, BIND_AUTO_CREATE)
+ bound = true
+ }
+
+ override fun onStop() {
+ if (bound) {
+ runtime?.removeListener(this)
+ unbindService(connection)
+ bound = false
+ runtime = null
+ }
+ super.onStop()
+ }
+
+ protected open fun onBound(runtime: AgentRuntime?) {}
+
+ override fun onLoggedOut() {
+ startActivity(Intent(this, LoginActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
+ finish()
+ }
+
+ protected fun notice(text: String) {
+ val root = findViewById(android.R.id.content) ?: return
+ Snackbar.make(root, text, Snackbar.LENGTH_SHORT).show()
+ }
+
+ override fun onNotice(text: String) {
+ if (!isFinishing) notice(text)
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) = Unit
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/DeviceActivity.kt b/app/src/main/java/com/asio/tapremly/ui/DeviceActivity.kt
new file mode 100644
index 0000000..a74071a
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/DeviceActivity.kt
@@ -0,0 +1,358 @@
+package com.asio.tapremly.ui
+
+import android.os.Bundle
+import android.text.Editable
+import android.text.TextWatcher
+import android.view.View
+import android.widget.LinearLayout
+import android.widget.PopupMenu
+import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.AgentRuntime
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.core.Limits
+import com.asio.tapremly.core.SendForm
+import com.asio.tapremly.core.Shortcut
+import com.asio.tapremly.core.problems
+import com.asio.tapremly.databinding.ActivityDeviceBinding
+import com.google.android.material.tabs.TabLayout
+import java.util.Calendar
+
+class DeviceActivity : AgentActivity() {
+ private lateinit var binding: ActivityDeviceBinding
+ private lateinit var remoteId: String
+ private var sendAt = 0L
+ private var limits = Limits()
+ private var lastKey = ""
+ private var last: Snapshot? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ remoteId = intent.getStringExtra(EXTRA_REMOTE).orEmpty()
+ binding = ActivityDeviceBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.toolbar.setNavigationOnClickListener { finish() }
+ binding.toolbar.setOnMenuItemClickListener { item ->
+ when (item.itemId) {
+ R.id.move_group -> {
+ chooseGroup()
+ true
+ }
+ R.id.remove_device -> {
+ val record = last?.devices?.find { it.id == remoteId }?.recordId ?: 0L
+ confirmDialog("从列表移出这台设备?信任不会变。") {
+ if (record > 0L) runtime?.removeDevice(record)
+ finish()
+ }
+ true
+ }
+ else -> false
+ }
+ }
+ binding.toolbar.inflateMenu(R.menu.menu_device)
+ binding.tabs.addTab(binding.tabs.newTab().setText(R.string.tab_command))
+ binding.tabs.addTab(binding.tabs.newTab().setText(R.string.tab_text))
+ binding.tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
+ override fun onTabSelected(tab: TabLayout.Tab) = refreshSend()
+ override fun onTabUnselected(tab: TabLayout.Tab) = Unit
+ override fun onTabReselected(tab: TabLayout.Tab) = Unit
+ })
+ binding.timing.check(R.id.timingNow)
+ binding.timing.addOnButtonCheckedListener { _, _, _ ->
+ if (binding.timing.checkedButtonId == R.id.timingLater && sendAt <= System.currentTimeMillis()) {
+ sendAt = System.currentTimeMillis() + 60L * 60L * 1000L
+ }
+ refreshSend()
+ }
+ binding.keep.setOnCheckedChangeListener { _, _ -> refreshSend() }
+ binding.input.addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
+ override fun afterTextChanged(s: Editable?) = refreshSend()
+ })
+ binding.ttlHours.addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
+ override fun afterTextChanged(s: Editable?) = refreshSend()
+ })
+ listOf(
+ binding.ttl1 to 1,
+ binding.ttl12 to 12,
+ binding.ttl24 to 24,
+ binding.ttl168 to 168,
+ binding.ttl720 to 720,
+ ).forEach { (button, hours) ->
+ button.setOnClickListener {
+ binding.ttlHours.setText(hours.toString())
+ }
+ }
+ binding.pickTime.setOnClickListener { pickTime() }
+ binding.send.setOnClickListener { sendCurrent() }
+ binding.saveShortcut.setOnClickListener { saveCurrent() }
+ binding.addLocal.setOnClickListener {
+ shortcutDialog("添加命令", null) { name, shell, confirm ->
+ runtime?.addLocal(remoteId, name, shell, confirm)
+ }
+ }
+ savedInstanceState?.let { state ->
+ binding.input.setText(state.getString("input"))
+ sendAt = state.getLong("sendAt")
+ binding.keep.isChecked = state.getBoolean("keep")
+ binding.ttlHours.setText(state.getString("ttl"))
+ if (state.getBoolean("later")) binding.timing.check(R.id.timingLater)
+ if (state.getInt("tab") == 1) binding.tabs.getTabAt(1)?.select()
+ }
+ refreshSend()
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ outState.putString("input", binding.input.text?.toString())
+ outState.putLong("sendAt", sendAt)
+ outState.putBoolean("keep", binding.keep.isChecked)
+ outState.putBoolean("later", binding.timing.checkedButtonId == R.id.timingLater)
+ outState.putString("ttl", binding.ttlHours.text?.toString())
+ outState.putInt("tab", binding.tabs.selectedTabPosition)
+ }
+
+ override fun onBound(runtime: AgentRuntime?) {
+ runtime?.syncRemote(remoteId)
+ runtime?.snapshot()?.let { onSnapshot(it) }
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) {
+ last = snapshot
+ limits = Limits(snapshot.maxTtlSeconds, snapshot.maxScheduleSeconds)
+ val device = snapshot.devices.find { it.id == remoteId }
+ binding.toolbar.title = device?.name ?: remoteId
+ binding.toolbar.subtitle = if (device?.online == true) getString(R.string.online) else getString(R.string.offline)
+ binding.trustWarn.visibility = if (remoteId in snapshot.blocked) View.VISIBLE else View.GONE
+ val key = shortcutKey(snapshot)
+ if (key != lastKey) {
+ lastKey = key
+ fillShortcuts(snapshot)
+ }
+ refreshSend()
+ }
+
+ override fun onText(fromId: String, text: String) {
+ if (isFinishing) return
+ AlertDialog.Builder(this)
+ .setTitle("收到文字")
+ .setMessage("来自 $fromId\n$text")
+ .setPositiveButton("知道了", null)
+ .show()
+ }
+
+ private fun shortcutKey(snapshot: Snapshot): String {
+ val remote = snapshot.remoteByRemote[remoteId].orEmpty().joinToString("|") { "${it.id}:${it.shell}:${it.confirm}" }
+ val local = snapshot.localByRemote[remoteId].orEmpty().joinToString("|") { "${it.id}:${it.shell}:${it.confirm}" }
+ val sync = snapshot.remoteSyncedAt[remoteId] ?: 0L
+ val syncing = remoteId in snapshot.syncing
+ return "$syncing#$sync#$remote#$local"
+ }
+
+ private fun fillShortcuts(snapshot: Snapshot) {
+ val syncing = remoteId in snapshot.syncing
+ val at = snapshot.remoteSyncedAt[remoteId] ?: 0L
+ binding.remoteSync.text = when {
+ syncing -> getString(R.string.syncing)
+ at > 0L -> "上次同步 ${formatWhen(at)}"
+ else -> getString(R.string.not_synced)
+ }
+ fill(binding.remoteList, snapshot.remoteByRemote[remoteId].orEmpty(), local = false)
+ fill(binding.localList, snapshot.localByRemote[remoteId].orEmpty(), local = true)
+ }
+
+ private fun fill(container: LinearLayout, items: List, local: Boolean) {
+ container.removeAllViews()
+ if (items.isEmpty()) {
+ val empty = TextView(this)
+ empty.text = getString(R.string.no_commands)
+ empty.setTextColor(getColor(R.color.muted))
+ empty.setPadding(8, 12, 8, 12)
+ container.addView(empty)
+ return
+ }
+ for (item in items) {
+ val view = layoutInflater.inflate(R.layout.item_shortcut, container, false)
+ view.findViewById(R.id.name).text = item.name
+ view.findViewById(R.id.shell).text = item.shell
+ view.setOnClickListener { runShortcut(item, remote = !local) }
+ view.setOnLongClickListener {
+ showItemMenu(view, item, local)
+ true
+ }
+ val params = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ )
+ params.bottomMargin = (8 * resources.displayMetrics.density).toInt()
+ view.layoutParams = params
+ container.addView(view)
+ }
+ }
+
+ private fun showItemMenu(anchor: View, item: Shortcut, local: Boolean) {
+ PopupMenu(this, anchor).apply {
+ if (local) {
+ menu.add("编辑").setOnMenuItemClickListener { _ ->
+ shortcutDialog("编辑命令", item) { name, shell, confirm ->
+ runtime?.updateLocal(item.id, name, shell, confirm)
+ }
+ true
+ }
+ menu.add("删除").setOnMenuItemClickListener { _ ->
+ confirmDialog("删除这条命令?") { runtime?.deleteLocal(item.id) }
+ true
+ }
+ }
+ menu.add("复制到其他设备").setOnMenuItemClickListener { _ ->
+ copyItem(item)
+ true
+ }
+ show()
+ }
+ }
+
+ private fun copyItem(item: Shortcut) {
+ val others = last?.devices.orEmpty().filter { it.id != remoteId }
+ if (others.isEmpty()) {
+ notice("没有其他设备")
+ return
+ }
+ val names = others.map { it.name }.toTypedArray()
+ val checked = BooleanArray(others.size)
+ AlertDialog.Builder(this)
+ .setTitle("复制到其他设备")
+ .setMultiChoiceItems(names, checked) { _, which, on -> checked[which] = on }
+ .setPositiveButton("确定") { _, _ ->
+ val ids = others.filterIndexed { index, _ -> checked[index] }.map { it.id }
+ if (ids.isNotEmpty()) runtime?.copyTo(item.name, item.shell, item.confirm, ids)
+ }
+ .setNegativeButton("取消", null)
+ .show()
+ }
+
+ private fun runShortcut(item: Shortcut, remote: Boolean) {
+ val go = {
+ val form = readForm()
+ val problem = form.problems(System.currentTimeMillis(), limits)
+ if (problem != null) notice(problem)
+ else if (remote) runtime?.sendRemoteShortcut(remoteId, item.id, form)
+ else runtime?.sendShell(remoteId, item.shell, form)
+ }
+ if (item.confirm) {
+ AlertDialog.Builder(this)
+ .setTitle(item.name)
+ .setMessage("确定执行")
+ .setPositiveButton("确定") { _, _ -> go() }
+ .setNegativeButton("取消", null)
+ .show()
+ } else {
+ go()
+ }
+ }
+
+ private fun sendCurrent() {
+ val text = binding.input.text?.toString().orEmpty()
+ if (text.isBlank()) return
+ val form = readForm()
+ val problem = form.problems(System.currentTimeMillis(), limits)
+ if (problem != null) {
+ notice(problem)
+ return
+ }
+ if (binding.tabs.selectedTabPosition == 0) runtime?.sendShell(remoteId, text, form)
+ else runtime?.sendText(remoteId, text, form)
+ }
+
+ private fun saveCurrent() {
+ val shell = binding.input.text?.toString().orEmpty()
+ if (shell.isBlank()) return
+ shortcutDialog("存为本端快捷命令", null, shell) { name, saved, confirm ->
+ runtime?.addLocal(remoteId, name, saved, confirm)
+ binding.input.setText("")
+ }
+ }
+
+ private fun readForm(): SendForm {
+ val later = binding.timing.checkedButtonId == R.id.timingLater
+ val keep = binding.keep.isChecked
+ val hours = binding.ttlHours.text?.toString()?.toLongOrNull()
+ return SendForm(
+ scheduled = later,
+ sendAtMs = if (later) sendAt else null,
+ keep = keep,
+ ttlSeconds = if (keep) hours?.times(3600) else null,
+ )
+ }
+
+ private fun refreshSend() {
+ val command = binding.tabs.selectedTabPosition == 0
+ binding.input.hint = getString(if (command) R.string.hint_shell else R.string.hint_text)
+ binding.saveShortcut.visibility = if (command) View.VISIBLE else View.GONE
+ val later = binding.timing.checkedButtonId == R.id.timingLater
+ val keep = binding.keep.isChecked
+ binding.scheduleRow.visibility = if (later) View.VISIBLE else View.GONE
+ binding.ttlRow.visibility = if (keep) View.VISIBLE else View.GONE
+ if (later && sendAt > 0L) binding.scheduleValue.text = formatWhen(sendAt)
+ val text = binding.input.text?.toString().orEmpty()
+ val problem = readForm().problems(System.currentTimeMillis(), limits)
+ binding.formError.text = problem.orEmpty()
+ binding.formError.visibility = if (problem.isNullOrBlank()) View.GONE else View.VISIBLE
+ binding.send.isEnabled = text.isNotBlank() && problem == null
+ binding.saveShortcut.isEnabled = command && text.isNotBlank()
+ }
+
+ private fun pickTime() {
+ val calendar = Calendar.getInstance()
+ if (sendAt > 0L) calendar.timeInMillis = sendAt
+ android.app.DatePickerDialog(
+ this,
+ { _, year, month, day ->
+ calendar.set(Calendar.YEAR, year)
+ calendar.set(Calendar.MONTH, month)
+ calendar.set(Calendar.DAY_OF_MONTH, day)
+ android.app.TimePickerDialog(
+ this,
+ { _, hour, minute ->
+ calendar.set(Calendar.HOUR_OF_DAY, hour)
+ calendar.set(Calendar.MINUTE, minute)
+ calendar.set(Calendar.SECOND, 0)
+ sendAt = calendar.timeInMillis
+ refreshSend()
+ },
+ calendar.get(Calendar.HOUR_OF_DAY),
+ calendar.get(Calendar.MINUTE),
+ true,
+ ).show()
+ },
+ calendar.get(Calendar.YEAR),
+ calendar.get(Calendar.MONTH),
+ calendar.get(Calendar.DAY_OF_MONTH),
+ ).show()
+ }
+
+ private fun chooseGroup() {
+ val groups = last?.groups.orEmpty()
+ val labels = arrayOf(getString(R.string.ungrouped)) + groups.map { it.name }
+ val ids = listOf("") + groups.map { it.id }
+ val current = last?.devices?.find { it.id == remoteId }?.groupId.orEmpty()
+ val checked = ids.indexOf(current).let { if (it < 0) 0 else it }
+ AlertDialog.Builder(this)
+ .setTitle("分组")
+ .setSingleChoiceItems(labels, checked) { dialog, which ->
+ val record = last?.devices?.find { it.id == remoteId }?.recordId ?: 0L
+ if (record > 0L) runtime?.moveDevice(record, ids[which])
+ dialog.dismiss()
+ }
+ .setNegativeButton("取消", null)
+ .show()
+ }
+
+ companion object {
+ const val EXTRA_REMOTE = "remote"
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/Dialogs.kt b/app/src/main/java/com/asio/tapremly/ui/Dialogs.kt
new file mode 100644
index 0000000..1bb30f9
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/Dialogs.kt
@@ -0,0 +1,117 @@
+package com.asio.tapremly.ui
+
+import android.text.InputType
+import android.view.View
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import com.asio.tapremly.R
+import com.asio.tapremly.core.Shortcut
+
+private val endpointPattern = Regex("^[a-z0-9_.\\-]{1,64}$")
+
+fun AppCompatActivity.shortcutDialog(
+ title: String,
+ current: Shortcut?,
+ shellPrefill: String? = null,
+ onSave: (name: String, shell: String, confirm: Boolean) -> Unit,
+) {
+ val view = layoutInflater.inflate(R.layout.dialog_shortcut, null)
+ val name = view.findViewById(R.id.name)
+ val shell = view.findViewById(R.id.shell)
+ val confirm = view.findViewById(R.id.confirm)
+ val error = view.findViewById(R.id.error)
+ name.setText(current?.name.orEmpty())
+ shell.setText(current?.shell ?: shellPrefill.orEmpty())
+ confirm.isChecked = current?.confirm == true
+ val dialog = AlertDialog.Builder(this)
+ .setTitle(title)
+ .setView(view)
+ .setPositiveButton("保存", null)
+ .setNegativeButton("取消", null)
+ .create()
+ dialog.setOnShowListener {
+ dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
+ val nameText = name.text.toString().trim()
+ val shellText = shell.text.toString()
+ when {
+ nameText.isEmpty() -> error.show("请填写名称")
+ shellText.isBlank() -> error.show("请填写要执行的命令")
+ else -> {
+ onSave(nameText, shellText, confirm.isChecked)
+ dialog.dismiss()
+ }
+ }
+ }
+ }
+ dialog.show()
+}
+
+fun AppCompatActivity.nameDialog(title: String, initial: String, onSave: (String) -> Unit) {
+ val input = EditText(this)
+ input.setText(initial)
+ input.setSelection(input.text.length)
+ input.inputType = InputType.TYPE_CLASS_TEXT
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ input.setPadding(pad, pad, pad, pad)
+ val dialog = AlertDialog.Builder(this)
+ .setTitle(title)
+ .setView(input)
+ .setPositiveButton("保存", null)
+ .setNegativeButton("取消", null)
+ .create()
+ dialog.setOnShowListener {
+ dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
+ val text = input.text.toString().trim()
+ if (text.isEmpty()) return@setOnClickListener
+ onSave(text)
+ dialog.dismiss()
+ }
+ }
+ dialog.show()
+}
+
+fun AppCompatActivity.deviceDialog(onSave: (name: String, endpointId: String) -> Unit) {
+ val view = layoutInflater.inflate(R.layout.dialog_device, null)
+ val name = view.findViewById(R.id.name)
+ val endpoint = view.findViewById(R.id.endpoint)
+ val error = view.findViewById(R.id.error)
+ val dialog = AlertDialog.Builder(this)
+ .setTitle("添加设备")
+ .setView(view)
+ .setPositiveButton("添加", null)
+ .setNegativeButton("取消", null)
+ .create()
+ dialog.setOnShowListener {
+ dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
+ val nameText = name.text.toString().trim()
+ val idText = endpoint.text.toString().trim()
+ when {
+ nameText.isEmpty() -> error.show("请填写名称")
+ !endpointPattern.matches(idText) -> error.show("端编号只能使用小写字母、数字、点、横线和下划线")
+ else -> {
+ onSave(nameText, idText)
+ dialog.dismiss()
+ }
+ }
+ }
+ }
+ dialog.show()
+}
+
+fun AppCompatActivity.confirmDialog(message: String, onYes: () -> Unit) {
+ AlertDialog.Builder(this)
+ .setMessage(message)
+ .setPositiveButton("确定") { _, _ -> onYes() }
+ .setNegativeButton("取消", null)
+ .show()
+}
+
+fun endpointOk(id: String): Boolean = endpointPattern.matches(id)
+
+private fun TextView.show(text: String) {
+ this.text = text
+ visibility = View.VISIBLE
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/Format.kt b/app/src/main/java/com/asio/tapremly/ui/Format.kt
new file mode 100644
index 0000000..f6e396e
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/Format.kt
@@ -0,0 +1,10 @@
+package com.asio.tapremly.ui
+
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+fun formatWhen(ms: Long): String {
+ if (ms <= 0L) return ""
+ return SimpleDateFormat("M月d日 HH:mm", Locale.CHINA).format(Date(ms))
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/InboxActivity.kt b/app/src/main/java/com/asio/tapremly/ui/InboxActivity.kt
new file mode 100644
index 0000000..4b4fd02
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/InboxActivity.kt
@@ -0,0 +1,33 @@
+package com.asio.tapremly.ui
+
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.databinding.ActivityListBinding
+
+class InboxActivity : AgentActivity() {
+ private lateinit var binding: ActivityListBinding
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityListBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.toolbar.title = getString(R.string.inbox)
+ binding.toolbar.setNavigationOnClickListener { finish() }
+ binding.toolbar.navigationContentDescription = getString(R.string.back)
+ binding.empty.text = getString(R.string.no_texts)
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) {
+ binding.rows.removeAllViews()
+ binding.empty.visibility = if (snapshot.inbox.isEmpty()) View.VISIBLE else View.GONE
+ for (item in snapshot.inbox) {
+ val view = layoutInflater.inflate(R.layout.item_log, binding.rows, false)
+ view.findViewById(R.id.title).text = "${formatWhen(item.atMs)} 来自 ${item.fromId}"
+ view.findViewById(R.id.detail).text = item.text
+ binding.rows.addView(view)
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/asio/tapremly/ui/LoginActivity.kt b/app/src/main/java/com/asio/tapremly/ui/LoginActivity.kt
new file mode 100644
index 0000000..9519b2e
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/LoginActivity.kt
@@ -0,0 +1,70 @@
+package com.asio.tapremly.ui
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import com.asio.tapremly.agent.AgentService
+import com.asio.tapremly.data.ApiException
+import com.asio.tapremly.data.Prefs
+import com.asio.tapremly.data.TapApi
+import com.asio.tapremly.databinding.ActivityLoginBinding
+
+class LoginActivity : AppCompatActivity() {
+ private lateinit var binding: ActivityLoginBinding
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (Prefs(this).loggedIn) {
+ startActivity(Intent(this, MainActivity::class.java))
+ finish()
+ return
+ }
+ binding = ActivityLoginBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.login.setOnClickListener { submit(register = false) }
+ binding.register.setOnClickListener { submit(register = true) }
+ binding.openSettings.setOnClickListener {
+ startActivity(Intent(this, SettingsActivity::class.java))
+ }
+ }
+
+ private fun submit(register: Boolean) {
+ val account = binding.account.text.toString().trim()
+ val password = binding.password.text.toString()
+ if (account.isEmpty() || password.isEmpty()) {
+ showError("请填写账号和密码")
+ return
+ }
+ binding.login.isEnabled = false
+ binding.register.isEnabled = false
+ binding.login.text = getString(com.asio.tapremly.R.string.logging_in)
+ binding.error.visibility = View.GONE
+ Thread {
+ val api = TapApi(Prefs(this))
+ val result = runCatching {
+ if (register) api.register(account, password) else api.login(account, password)
+ }
+ runOnUiThread {
+ if (isFinishing) return@runOnUiThread
+ binding.login.isEnabled = true
+ binding.register.isEnabled = true
+ binding.login.setText(com.asio.tapremly.R.string.login)
+ result.onSuccess {
+ ContextCompat.startForegroundService(this, Intent(this, AgentService::class.java))
+ startActivity(Intent(this, MainActivity::class.java))
+ finish()
+ }.onFailure { error ->
+ val text = (error as? ApiException)?.message ?: "暂时连不上服务器"
+ showError(text)
+ }
+ }
+ }.start()
+ }
+
+ private fun showError(text: String) {
+ binding.error.text = text
+ binding.error.visibility = View.VISIBLE
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/LogsActivity.kt b/app/src/main/java/com/asio/tapremly/ui/LogsActivity.kt
new file mode 100644
index 0000000..af77bff
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/LogsActivity.kt
@@ -0,0 +1,35 @@
+package com.asio.tapremly.ui
+
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.databinding.ActivityListBinding
+
+class LogsActivity : AgentActivity() {
+ private lateinit var binding: ActivityListBinding
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityListBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.toolbar.title = getString(R.string.logs)
+ binding.toolbar.setNavigationOnClickListener { finish() }
+ binding.toolbar.navigationContentDescription = getString(R.string.back)
+ binding.empty.text = getString(R.string.no_logs)
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) {
+ binding.rows.removeAllViews()
+ val items = snapshot.logs.asReversed()
+ binding.empty.visibility = if (items.isEmpty()) View.VISIBLE else View.GONE
+ for (item in items) {
+ val view = layoutInflater.inflate(R.layout.item_log, binding.rows, false)
+ val mark = if (item.ok) "成功" else "失败"
+ view.findViewById(R.id.title).text = "${formatWhen(item.atMs)} $mark ${item.summary}"
+ view.findViewById(R.id.detail).text = item.detail
+ binding.rows.addView(view)
+ }
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/MainActivity.kt b/app/src/main/java/com/asio/tapremly/ui/MainActivity.kt
new file mode 100644
index 0000000..3c79b1b
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/MainActivity.kt
@@ -0,0 +1,207 @@
+package com.asio.tapremly.ui
+
+import android.content.Intent
+import android.os.Bundle
+import android.text.Editable
+import android.text.TextWatcher
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.PopupMenu
+import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.AgentRuntime
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.core.Device
+import com.asio.tapremly.data.Prefs
+import com.asio.tapremly.databinding.ActivityMainBinding
+
+class MainActivity : AgentActivity() {
+ private var binding: ActivityMainBinding? = null
+ private var last: Snapshot? = null
+ private val adapter = DeviceAdapter(
+ onDevice = { device ->
+ startActivity(Intent(this, DeviceActivity::class.java).putExtra(DeviceActivity.EXTRA_REMOTE, device.id))
+ },
+ onRename = { id, name -> nameDialog("重命名分组", name) { runtime?.renameGroup(id, it) } },
+ onDelete = { id ->
+ confirmDialog("删除后,组里的设备会回到未分组。") { runtime?.deleteGroup(id) }
+ },
+ )
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (!Prefs(this).loggedIn) return
+ val views = ActivityMainBinding.inflate(layoutInflater)
+ binding = views
+ setContentView(views.root)
+ views.list.layoutManager = LinearLayoutManager(this)
+ views.list.adapter = adapter
+ views.addDevice.setOnClickListener { deviceDialog { name, id -> runtime?.addDevice(name, id) } }
+ views.emptyAdd.setOnClickListener { deviceDialog { name, id -> runtime?.addDevice(name, id) } }
+ views.addGroup.setOnClickListener { nameDialog("新建分组", "") { runtime?.createGroup(it) } }
+ views.more.setOnClickListener { showMore(it) }
+ views.refresh.setOnRefreshListener { runtime?.refresh() }
+ views.search.addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
+ override fun afterTextChanged(s: Editable?) = render()
+ })
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) {
+ last = snapshot
+ binding?.refresh?.isRefreshing = false
+ render()
+ }
+
+ override fun onText(fromId: String, text: String) {
+ if (isFinishing) return
+ AlertDialog.Builder(this)
+ .setTitle("收到文字")
+ .setMessage("来自 $fromId\n$text")
+ .setPositiveButton("知道了", null)
+ .show()
+ }
+
+ private fun render() {
+ val views = binding ?: return
+ val snapshot = last ?: return
+ views.link.text = snapshot.linkLabel
+ if (snapshot.listError.isBlank()) {
+ views.listError.visibility = View.GONE
+ } else {
+ views.listError.visibility = View.VISIBLE
+ views.listError.text = snapshot.listError
+ }
+ val query = views.search.text.toString()
+ val rows = buildRows(snapshot, query)
+ adapter.submit(rows)
+ val noDevices = snapshot.devices.isEmpty() && query.isBlank()
+ views.empty.visibility = if (rows.isEmpty()) View.VISIBLE else View.GONE
+ views.emptyText.text = if (query.isBlank()) getString(R.string.empty_devices) else "没有匹配的设备"
+ views.emptyAdd.visibility = if (noDevices) View.VISIBLE else View.GONE
+ }
+
+ private fun showMore(anchor: View) {
+ PopupMenu(this, anchor).apply {
+ menu.add(getString(R.string.trust)).setOnMenuItemClickListener { _ ->
+ startActivity(Intent(this@MainActivity, TrustActivity::class.java)); true
+ }
+ menu.add(getString(R.string.published)).setOnMenuItemClickListener { _ ->
+ startActivity(Intent(this@MainActivity, PublishedActivity::class.java)); true
+ }
+ menu.add(getString(R.string.logs)).setOnMenuItemClickListener { _ ->
+ startActivity(Intent(this@MainActivity, LogsActivity::class.java)); true
+ }
+ menu.add(getString(R.string.inbox)).setOnMenuItemClickListener { _ ->
+ startActivity(Intent(this@MainActivity, InboxActivity::class.java)); true
+ }
+ menu.add(getString(R.string.settings)).setOnMenuItemClickListener { _ ->
+ startActivity(Intent(this@MainActivity, SettingsActivity::class.java)); true
+ }
+ menu.add(getString(R.string.logout)).setOnMenuItemClickListener { _ ->
+ confirmDialog("退出后,这部手机不再保持连接。") { runtime?.logout() }; true
+ }
+ show()
+ }
+ }
+
+ private fun buildRows(snapshot: Snapshot, query: String): List {
+ val q = query.trim()
+ fun match(device: Device) = q.isEmpty() ||
+ device.name.contains(q, ignoreCase = true) ||
+ device.id.contains(q, ignoreCase = true)
+ val devices = snapshot.devices.filter(::match)
+ val known = snapshot.groups.map { it.id }.toSet()
+ val out = ArrayList()
+ val ungrouped = devices.filter { it.groupId.isBlank() || it.groupId !in known }
+ if (ungrouped.isNotEmpty()) {
+ out.add(Row.Header(null, getString(R.string.ungrouped)))
+ ungrouped.forEach { out.add(Row.Dev(it)) }
+ }
+ for (group in snapshot.groups) {
+ val members = devices.filter { it.groupId == group.id }
+ if (q.isNotEmpty() && members.isEmpty()) continue
+ out.add(Row.Header(group.id, group.name))
+ members.forEach { out.add(Row.Dev(it)) }
+ }
+ return out
+ }
+}
+
+private sealed class Row {
+ data class Header(val id: String?, val title: String) : Row()
+ data class Dev(val device: Device) : Row()
+}
+
+private class DeviceAdapter(
+ private val onDevice: (Device) -> Unit,
+ private val onRename: (String, String) -> Unit,
+ private val onDelete: (String) -> Unit,
+) : RecyclerView.Adapter() {
+ private val rows = ArrayList()
+
+ fun submit(next: List) {
+ rows.clear()
+ rows.addAll(next)
+ notifyDataSetChanged()
+ }
+
+ override fun getItemViewType(position: Int): Int = if (rows[position] is Row.Header) 0 else 1
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
+ val inflater = LayoutInflater.from(parent.context)
+ return if (viewType == 0) {
+ HeaderHolder(inflater.inflate(R.layout.item_group, parent, false))
+ } else {
+ DeviceHolder(inflater.inflate(R.layout.item_device, parent, false))
+ }
+ }
+
+ override fun getItemCount(): Int = rows.size
+
+ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
+ when (val row = rows[position]) {
+ is Row.Header -> (holder as HeaderHolder).bind(row, onRename, onDelete)
+ is Row.Dev -> (holder as DeviceHolder).bind(row.device, onDevice)
+ }
+ }
+}
+
+private class HeaderHolder(view: View) : RecyclerView.ViewHolder(view) {
+ private val title: TextView = view.findViewById(R.id.title)
+ private val rename: TextView = view.findViewById(R.id.rename)
+ private val delete: TextView = view.findViewById(R.id.delete)
+
+ fun bind(row: Row.Header, onRename: (String, String) -> Unit, onDelete: (String) -> Unit) {
+ title.text = row.title
+ val editable = row.id != null
+ rename.visibility = if (editable) View.VISIBLE else View.GONE
+ delete.visibility = if (editable) View.VISIBLE else View.GONE
+ rename.setOnClickListener { row.id?.let { onRename(it, row.title) } }
+ delete.setOnClickListener { row.id?.let(onDelete) }
+ }
+}
+
+private class DeviceHolder(view: View) : RecyclerView.ViewHolder(view) {
+ private val name: TextView = view.findViewById(R.id.name)
+ private val online: TextView = view.findViewById(R.id.online)
+ private val endpoint: TextView = view.findViewById(R.id.endpoint)
+
+ fun bind(device: Device, onDevice: (Device) -> Unit) {
+ name.text = device.name
+ endpoint.text = device.id
+ if (device.online) {
+ online.text = itemView.context.getString(R.string.online)
+ online.setTextColor(itemView.context.getColor(R.color.ok))
+ } else {
+ online.text = itemView.context.getString(R.string.offline)
+ online.setTextColor(itemView.context.getColor(R.color.muted))
+ }
+ itemView.setOnClickListener { onDevice(device) }
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/PublishedActivity.kt b/app/src/main/java/com/asio/tapremly/ui/PublishedActivity.kt
new file mode 100644
index 0000000..6162731
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/PublishedActivity.kt
@@ -0,0 +1,70 @@
+package com.asio.tapremly.ui
+
+import android.os.Bundle
+import android.view.View
+import android.widget.LinearLayout
+import android.widget.PopupMenu
+import android.widget.TextView
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.core.Shortcut
+import com.asio.tapremly.databinding.ActivityListBinding
+
+class PublishedActivity : AgentActivity() {
+ private lateinit var binding: ActivityListBinding
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityListBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.toolbar.title = getString(R.string.published)
+ binding.toolbar.setNavigationOnClickListener { finish() }
+ binding.toolbar.navigationContentDescription = getString(R.string.back)
+ binding.help.visibility = View.VISIBLE
+ binding.help.text = getString(R.string.published_help)
+ binding.add.visibility = View.VISIBLE
+ binding.add.setOnClickListener {
+ shortcutDialog("添加命令", null) { name, shell, confirm ->
+ runtime?.addPublished(name, shell, confirm)
+ }
+ }
+ binding.empty.text = getString(R.string.no_commands)
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) {
+ fill(snapshot.published)
+ }
+
+ private fun fill(items: List) {
+ binding.rows.removeAllViews()
+ binding.empty.visibility = if (items.isEmpty()) View.VISIBLE else View.GONE
+ for (item in items) {
+ val view = layoutInflater.inflate(R.layout.item_shortcut, binding.rows, false)
+ view.findViewById(R.id.name).text = item.name
+ view.findViewById(R.id.shell).text = item.shell
+ view.setOnLongClickListener {
+ PopupMenu(this, view).apply {
+ menu.add("编辑").setOnMenuItemClickListener { _ ->
+ shortcutDialog("编辑命令", item) { name, shell, confirm ->
+ runtime?.updatePublished(item.id, name, shell, confirm)
+ }
+ true
+ }
+ menu.add("删除").setOnMenuItemClickListener { _ ->
+ confirmDialog("删除这条命令?") { runtime?.deletePublished(item.id) }
+ true
+ }
+ show()
+ }
+ true
+ }
+ val params = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ )
+ params.bottomMargin = (8 * resources.displayMetrics.density).toInt()
+ view.layoutParams = params
+ binding.rows.addView(view)
+ }
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/SettingsActivity.kt b/app/src/main/java/com/asio/tapremly/ui/SettingsActivity.kt
new file mode 100644
index 0000000..df77658
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/SettingsActivity.kt
@@ -0,0 +1,89 @@
+package com.asio.tapremly.ui
+
+import android.content.ComponentName
+import android.content.Intent
+import android.content.ServiceConnection
+import android.os.Bundle
+import android.os.IBinder
+import android.view.View
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.AgentRuntime
+import com.asio.tapremly.agent.AgentService
+import com.asio.tapremly.data.Prefs
+import com.asio.tapremly.databinding.ActivitySettingsBinding
+
+class SettingsActivity : AppCompatActivity() {
+ private lateinit var binding: ActivitySettingsBinding
+ private var runtime: AgentRuntime? = null
+ private var bound = false
+ private val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
+ if (!bound) return
+ runtime = (service as AgentService.LocalBinder).get()
+ }
+
+ override fun onServiceDisconnected(name: ComponentName?) {
+ runtime = null
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivitySettingsBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ val prefs = Prefs(this)
+ binding.toolbar.setNavigationOnClickListener { finish() }
+ binding.toolbar.navigationContentDescription = getString(R.string.back)
+ binding.server.setText(prefs.serverUrl)
+ binding.nix.setText(prefs.nixUrl)
+ binding.save.setOnClickListener { save() }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ if (!Prefs(this).loggedIn) return
+ val intent = Intent(this, AgentService::class.java)
+ ContextCompat.startForegroundService(this, intent)
+ bindService(intent, connection, BIND_AUTO_CREATE)
+ bound = true
+ }
+
+ override fun onStop() {
+ if (bound) {
+ unbindService(connection)
+ bound = false
+ runtime = null
+ }
+ super.onStop()
+ }
+
+ private fun save() {
+ val server = binding.server.text.toString().trim()
+ val nix = binding.nix.text.toString().trim()
+ when {
+ !server.startsWith("http://") && !server.startsWith("https://") ->
+ show("服务器地址要以 http:// 或 https:// 开头")
+ !nix.startsWith("ws://") && !nix.startsWith("wss://") &&
+ !nix.startsWith("mqtt://") && !nix.startsWith("mqtts://") ->
+ show("消息服务地址要以 ws:// 开头")
+ else -> {
+ val agent = runtime
+ if (agent != null) agent.setUrls(server, nix)
+ else {
+ val prefs = Prefs(this)
+ if (server != prefs.serverUrl) prefs.clearCookies()
+ prefs.serverUrl = server
+ prefs.nixUrl = nix
+ }
+ finish()
+ }
+ }
+ }
+
+ private fun show(text: String) {
+ binding.error.text = text
+ binding.error.visibility = View.VISIBLE
+ }
+}
diff --git a/app/src/main/java/com/asio/tapremly/ui/TrustActivity.kt b/app/src/main/java/com/asio/tapremly/ui/TrustActivity.kt
new file mode 100644
index 0000000..6e1f9ce
--- /dev/null
+++ b/app/src/main/java/com/asio/tapremly/ui/TrustActivity.kt
@@ -0,0 +1,50 @@
+package com.asio.tapremly.ui
+
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import com.asio.tapremly.R
+import com.asio.tapremly.agent.Snapshot
+import com.asio.tapremly.databinding.ActivityTrustBinding
+
+class TrustActivity : AgentActivity() {
+ private lateinit var binding: ActivityTrustBinding
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityTrustBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.toolbar.setNavigationOnClickListener { finish() }
+ binding.toolbar.navigationContentDescription = getString(R.string.back)
+ binding.add.setOnClickListener {
+ val id = binding.endpoint.text.toString().trim()
+ if (!endpointOk(id)) {
+ binding.error.text = "端编号只能使用小写字母、数字、点、横线和下划线"
+ binding.error.visibility = View.VISIBLE
+ return@setOnClickListener
+ }
+ binding.error.visibility = View.GONE
+ runtime?.trustAdd(id)
+ binding.endpoint.setText("")
+ }
+ }
+
+ override fun onSnapshot(snapshot: Snapshot) {
+ binding.rows.removeAllViews()
+ if (snapshot.trust.isEmpty()) {
+ val empty = TextView(this)
+ empty.text = "还没有信任的设备"
+ empty.setTextColor(getColor(R.color.muted))
+ binding.rows.addView(empty)
+ return
+ }
+ for (id in snapshot.trust) {
+ val view = layoutInflater.inflate(R.layout.item_trust, binding.rows, false)
+ view.findViewById(R.id.endpoint).text = id
+ view.findViewById(R.id.remove).setOnClickListener {
+ confirmDialog("不再信任这个端?") { runtime?.trustRemove(id) }
+ }
+ binding.rows.addView(view)
+ }
+ }
+}
diff --git a/app/src/main/res/drawable/bg_input.xml b/app/src/main/res/drawable/bg_input.xml
new file mode 100644
index 0000000..e7a891c
--- /dev/null
+++ b/app/src/main/res/drawable/bg_input.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/bg_warn.xml b/app/src/main/res/drawable/bg_warn.xml
new file mode 100644
index 0000000..af08a07
--- /dev/null
+++ b/app/src/main/res/drawable/bg_warn.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_back.xml b/app/src/main/res/drawable/ic_back.xml
new file mode 100644
index 0000000..1ba78ff
--- /dev/null
+++ b/app/src/main/res/drawable/ic_back.xml
@@ -0,0 +1,11 @@
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/drawable/ic_launcher.xml b/app/src/main/res/drawable/ic_launcher.xml
new file mode 100644
index 0000000..7e99471
--- /dev/null
+++ b/app/src/main/res/drawable/ic_launcher.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_stat.xml b/app/src/main/res/drawable/ic_stat.xml
new file mode 100644
index 0000000..7c25eb0
--- /dev/null
+++ b/app/src/main/res/drawable/ic_stat.xml
@@ -0,0 +1,10 @@
+
+
+
+
diff --git a/app/src/main/res/layout/activity_device.xml b/app/src/main/res/layout/activity_device.xml
new file mode 100644
index 0000000..1280beb
--- /dev/null
+++ b/app/src/main/res/layout/activity_device.xml
@@ -0,0 +1,295 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/activity_list.xml b/app/src/main/res/layout/activity_list.xml
new file mode 100644
index 0000000..9b18cc6
--- /dev/null
+++ b/app/src/main/res/layout/activity_list.xml
@@ -0,0 +1,63 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml
new file mode 100644
index 0000000..9279eaf
--- /dev/null
+++ b/app/src/main/res/layout/activity_login.xml
@@ -0,0 +1,93 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..384c56c
--- /dev/null
+++ b/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,139 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
new file mode 100644
index 0000000..b46540c
--- /dev/null
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -0,0 +1,77 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/activity_trust.xml b/app/src/main/res/layout/activity_trust.xml
new file mode 100644
index 0000000..950e279
--- /dev/null
+++ b/app/src/main/res/layout/activity_trust.xml
@@ -0,0 +1,83 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/dialog_device.xml b/app/src/main/res/layout/dialog_device.xml
new file mode 100644
index 0000000..8f346d8
--- /dev/null
+++ b/app/src/main/res/layout/dialog_device.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/dialog_shortcut.xml b/app/src/main/res/layout/dialog_shortcut.xml
new file mode 100644
index 0000000..8190e15
--- /dev/null
+++ b/app/src/main/res/layout/dialog_shortcut.xml
@@ -0,0 +1,65 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/item_device.xml b/app/src/main/res/layout/item_device.xml
new file mode 100644
index 0000000..79bcb82
--- /dev/null
+++ b/app/src/main/res/layout/item_device.xml
@@ -0,0 +1,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/item_group.xml b/app/src/main/res/layout/item_group.xml
new file mode 100644
index 0000000..bf6c6d5
--- /dev/null
+++ b/app/src/main/res/layout/item_group.xml
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/item_log.xml b/app/src/main/res/layout/item_log.xml
new file mode 100644
index 0000000..a27cc6b
--- /dev/null
+++ b/app/src/main/res/layout/item_log.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/item_shortcut.xml b/app/src/main/res/layout/item_shortcut.xml
new file mode 100644
index 0000000..daf6f4b
--- /dev/null
+++ b/app/src/main/res/layout/item_shortcut.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/item_trust.xml b/app/src/main/res/layout/item_trust.xml
new file mode 100644
index 0000000..e4f4e5f
--- /dev/null
+++ b/app/src/main/res/layout/item_trust.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/menu/menu_device.xml b/app/src/main/res/menu/menu_device.xml
new file mode 100644
index 0000000..1156317
--- /dev/null
+++ b/app/src/main/res/menu/menu_device.xml
@@ -0,0 +1,12 @@
+
+
diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml
index bb29eca..dbd6c10 100644
--- a/app/src/main/res/values-night/themes.xml
+++ b/app/src/main/res/values-night/themes.xml
@@ -1,16 +1,16 @@
-
-
-
-
\ No newline at end of file
+
diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml
index f8c6127..d8de71b 100644
--- a/app/src/main/res/values/colors.xml
+++ b/app/src/main/res/values/colors.xml
@@ -1,10 +1,15 @@
- #FFBB86FC
- #FF6200EE
- #FF3700B3
- #FF03DAC5
- #FF018786
- #FF000000
- #FFFFFFFF
-
\ No newline at end of file
+ #1F4E8C
+ #173C6E
+ #FFFFFF
+ #F4F6F8
+ #FFFFFF
+ #1C2430
+ #5E6A78
+ #E3E8EE
+ #A33B3B
+ #1F7A4D
+ #FBF3E4
+ #7A5B17
+
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index a0835b6..491c31e 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1,3 +1,57 @@
+
TapRemly
-
\ No newline at end of file
+ 保持连接
+ 登录
+ 账号
+ 密码
+ 设置
+ 设备
+ 添加设备
+ 新建分组
+ 更多
+ 搜索名称或端编号
+ 还没有设备
+ 信任
+ 本机命令
+ 执行记录
+ 收到的文字
+ 退出
+ 命令
+ 文字
+ 输入要在对方执行的 shell
+ 输入要显示在对方设备上的文字
+ 存为本端快捷命令
+ 立即
+ 定时
+ 离线保留
+ 发送
+ 选择时刻
+ 小时
+ 对方尚未信任本机,命令不会执行
+ 远端快捷命令
+ 本端快捷命令
+ 添加
+ 这里添加的设备可以命令本机。
+ 端编号
+ 服务器地址
+ 消息服务地址
+ 保存
+ 未分组
+ 重命名
+ 删除
+ 在线
+ 不在线
+ 返回
+ 名称
+ 要执行的命令
+ 发送前再确认一次
+ 移除
+ 同步中
+ 尚未同步
+ 还没有命令
+ 还没有记录
+ 还没有收到文字
+ 其他设备可以让这部手机执行这里的命令。
+ 正在登录
+
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
index 0c34ac4..09b2da2 100644
--- a/app/src/main/res/values/themes.xml
+++ b/app/src/main/res/values/themes.xml
@@ -1,16 +1,24 @@
-
-
-
-
\ No newline at end of file
+
+
+
+
+
diff --git a/app/src/test/java/com/asio/tapremly/CoreTest.kt b/app/src/test/java/com/asio/tapremly/CoreTest.kt
new file mode 100644
index 0000000..fd8a912
--- /dev/null
+++ b/app/src/test/java/com/asio/tapremly/CoreTest.kt
@@ -0,0 +1,222 @@
+package com.asio.tapremly
+
+import com.asio.tapremly.core.ApiJson
+import com.asio.tapremly.core.DAY_MS
+import com.asio.tapremly.core.DEFAULT_MAX_TTL_SECONDS
+import com.asio.tapremly.core.Engine
+import com.asio.tapremly.core.Limits
+import com.asio.tapremly.core.LocalCommands
+import com.asio.tapremly.core.LogBook
+import com.asio.tapremly.core.LogEntry
+import com.asio.tapremly.core.MemoryExecuted
+import com.asio.tapremly.core.Protocol
+import com.asio.tapremly.core.SendForm
+import com.asio.tapremly.core.ShellOutcome
+import com.asio.tapremly.core.ShellRunner
+import com.asio.tapremly.core.Shortcut
+import com.asio.tapremly.core.TempShell
+import com.asio.tapremly.core.problems
+import com.asio.tapremly.core.toWire
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class CoreTest {
+ private class FakeShell : ShellRunner {
+ val commands = mutableListOf()
+ var outcome = ShellOutcome(true, "完成")
+ override fun run(shell: String): ShellOutcome {
+ commands.add(shell)
+ return outcome
+ }
+ }
+
+ private class Harness(
+ trustedIds: Set = emptySet(),
+ var publishedShell: String = "echo now",
+ ) {
+ val shell = FakeShell()
+ val trust = trustedIds.toMutableSet()
+ var clock = 1_000L
+ val texts = mutableListOf>()
+ val synced = mutableListOf>>()
+ val logs = mutableListOf()
+ val engine = Engine(
+ trusted = { it in trust },
+ published = { id ->
+ if (id == "s1") Shortcut("s1", "关机", publishedShell, false) else null
+ },
+ allPublished = {
+ listOf(Shortcut("s1", "关机", publishedShell, true))
+ },
+ runner = shell,
+ executed = MemoryExecuted(),
+ now = { clock },
+ onText = { from, text -> texts.add(from to text) },
+ onShortcuts = { from, items -> synced.add(from to items) },
+ onLog = { logs.add(it) },
+ )
+ }
+
+ @Test
+ fun untrustedShellDoesNotRun() {
+ val h = Harness()
+ val id = Protocol.newId()
+ val reply = Protocol.parse(h.engine.handle("other", Protocol.shell(id, "echo hi"))!!)!!
+ assertFalse(reply.ok!!)
+ assertEquals("not_trusted", reply.error)
+ assertTrue(h.shell.commands.isEmpty())
+ val again = Protocol.parse(h.engine.handle("other", Protocol.shell(id, "echo hi"))!!)!!
+ assertTrue(again.duplicate)
+ assertEquals("not_trusted", again.error)
+ assertTrue(h.shell.commands.isEmpty())
+ assertEquals(1, h.logs.size)
+ }
+
+ @Test
+ fun sameIdRunsOnceWithin24Hours() {
+ val h = Harness(setOf("me"))
+ val id = Protocol.newId()
+ h.engine.handle("me", Protocol.shell(id, "echo hi"))
+ h.engine.handle("me", Protocol.shell(id, "echo hi"))
+ assertEquals(listOf("echo hi"), h.shell.commands)
+ h.clock += DAY_MS
+ h.engine.handle("me", Protocol.shell(id, "echo hi"))
+ assertEquals(1, h.shell.commands.size)
+ h.clock += 1
+ h.engine.handle("me", Protocol.shell(id, "echo hi"))
+ assertEquals(2, h.shell.commands.size)
+ }
+
+ @Test
+ fun shortcutUsesCurrentShellAndMissingDoesNotRun() {
+ val h = Harness(setOf("me"))
+ h.engine.handle("me", Protocol.shortcut(Protocol.newId(), "s1"))
+ h.publishedShell = "echo later"
+ h.engine.handle("me", Protocol.shortcut(Protocol.newId(), "s1"))
+ assertEquals(listOf("echo now", "echo later"), h.shell.commands)
+ val missing = Protocol.parse(h.engine.handle("me", Protocol.shortcut(Protocol.newId(), "gone"))!!)!!
+ assertFalse(missing.ok!!)
+ assertEquals(2, h.shell.commands.size)
+ }
+
+ @Test
+ fun textAndUnknownTypeDoNotRunShell() {
+ val h = Harness(setOf("me"))
+ assertNull(h.engine.handle("me", Protocol.text(Protocol.newId(), "你好")))
+ assertEquals(listOf("me" to "你好"), h.texts)
+ assertNull(h.engine.handle("me", """{"v":1,"type":"other"}"""))
+ assertNull(h.engine.handle("me", """{"v":2,"type":"shell","id":"a","shell":"echo"}"""))
+ assertTrue(h.shell.commands.isEmpty())
+ }
+
+ @Test
+ fun shortcutListQueryRespectsTrust() {
+ val h = Harness(setOf("friend"))
+ val denied = Protocol.parse(h.engine.handle("stranger", Protocol.shortcutsQuery(Protocol.newId()))!!)!!
+ assertEquals("not_trusted", denied.error)
+ val listed = Protocol.parse(h.engine.handle("friend", Protocol.shortcutsQuery(Protocol.newId()))!!)!!
+ assertEquals("shortcuts", listed.type)
+ assertEquals("关机", listed.items!!.single().name)
+ assertTrue(listed.items!!.single().confirm)
+ val pushed = Protocol.shortcuts(listOf(Shortcut("r1", "远端", "pwd", false)))
+ assertNull(h.engine.handle("friend", pushed))
+ assertEquals("r1", h.synced.single().second.single().id)
+ val empty = Protocol.parse("""{"v":1,"type":"shortcuts","items":[]}""")!!
+ assertTrue(empty.items!!.isEmpty())
+ assertNull(Protocol.parse("""{"v":1,"type":"shortcuts","id":"q1"}""")!!.items)
+ }
+
+ @Test
+ fun localShortcutsStayPerRemoteAndCopyMintsIds() {
+ var n = 0
+ val book = LocalCommands { "n${n++}" }
+ book.add("a", "关机", "shutdown -s -t 1", true)
+ book.add("b", "打开", "echo b", false)
+ assertEquals(1, book.forRemote("a").size)
+ assertEquals("打开", book.forRemote("b").single().name)
+ val sourceId = book.forRemote("a").single().id
+ val copied = book.copyTo(sourceId, listOf("b", "c"))
+ assertEquals(2, copied.size)
+ assertNotEquals(copied[0].id, copied[1].id)
+ assertNotEquals(sourceId, copied[0].id)
+ assertEquals("关机", book.forRemote("c").single().name)
+ assertEquals("shutdown -s -t 1", book.forRemote("c").single().shell)
+ assertTrue(book.forRemote("c").single().confirm)
+ assertEquals(1, book.forRemote("a").size)
+ assertEquals(2, book.forRemote("b").size)
+ }
+
+ @Test
+ fun temporaryShellDoesNotSaveUntilAsked() {
+ val book = LocalCommands()
+ val temp = TempShell(book)
+ temp.send("a", "echo hi")
+ assertTrue(book.forRemote("a").isEmpty())
+ assertEquals(1, temp.sent.size)
+ temp.save("a", "打个招呼", "echo hi", false)
+ assertEquals(1, book.forRemote("a").size)
+ assertTrue(book.forRemote("b").isEmpty())
+ assertEquals("打个招呼", book.forRemote("a").single().name)
+ }
+
+ @Test
+ fun logsKeep500AndUpload20() {
+ val book = LogBook()
+ repeat(600) { book.add(LogEntry(it.toLong(), "s$it", true, "d")) }
+ assertEquals(500, book.all().size)
+ assertEquals(100L, book.all().first().atMs)
+ val latest = book.latest(20)
+ assertEquals(20, latest.size)
+ assertEquals(599L, latest.last().atMs)
+ assertEquals(580L, latest.first().atMs)
+ }
+
+ @Test
+ fun sendOptionsDefaultOffAndRejectTooLongTtl() {
+ val form = SendForm()
+ assertFalse(form.keep)
+ assertNull(form.toWire(0).sendAtMs)
+ assertNull(form.toWire(0).ttlSeconds)
+ val tooLong = SendForm(keep = true, ttlSeconds = DEFAULT_MAX_TTL_SECONDS + 1)
+ assertEquals("有效期超过上限", tooLong.problems(0, Limits()))
+ val past = SendForm(scheduled = true, sendAtMs = 1_000, keep = true, ttlSeconds = 60)
+ assertNull(past.problems(5_000, Limits()))
+ assertNull(past.toWire(5_000).sendAtMs)
+ assertEquals(60L, past.toWire(5_000).ttlSeconds)
+ val future = SendForm(scheduled = true, sendAtMs = 9_000)
+ assertEquals(9_000L, future.toWire(1_000).sendAtMs)
+ assertFalse(future.toWire(1_000).keep)
+ }
+
+ @Test
+ fun apiJsonReadsDirectoryAndAccount() {
+ val account = ApiJson.account(
+ """{"ok":true,"data":{"id":1,"username":"aa","role":"user","enabled":true}}""",
+ "fallback",
+ )!!
+ assertEquals("aa", account.username)
+ val (devices, groups) = ApiJson.directory(
+ """{"ok":true,"data":{"devices":[{"id":3,"name":"客厅电脑","endpoint_id":"pc-1","group_id":8,"presence":"online"},{"id":4,"name":"","endpoint_id":"pad-1","group_id":null,"presence":"offline"}],"groups":[{"id":8,"name":"家里"}]}}""",
+ )
+ assertEquals("pc-1", devices[0].id)
+ assertEquals(3L, devices[0].recordId)
+ assertEquals("8", devices[0].groupId)
+ assertTrue(devices[0].online)
+ assertEquals("pad-1", devices[1].name)
+ assertEquals("", devices[1].groupId)
+ assertEquals("家里", groups.single().name)
+ val made = ApiJson.provision(
+ """{"ok":true,"data":{"id":9,"name":"这部手机","endpoint_id":"phone-1","group_id":null,"presence":"unknown","login_password":"secret"}}""",
+ )!!
+ assertEquals("phone-1", made.endpointId)
+ assertEquals("secret", made.password)
+ assertEquals("账号或密码不正确", ApiJson.errorMessage("""{"ok":false,"error":{"code":"unauthorized","message":"账号或密码不正确"}}"""))
+ val body = ApiJson.logsBody("phone-1", listOf(LogEntry(3, "关机", false, "没有成功")))
+ assertTrue(body.contains("\"endpoint_id\":\"phone-1\""))
+ assertTrue(body.contains("\"result\":\"没有成功\""))
+ }
+}
diff --git a/app/src/test/java/com/asio/tapremly/ExampleUnitTest.kt b/app/src/test/java/com/asio/tapremly/ExampleUnitTest.kt
deleted file mode 100644
index 1106efb..0000000
--- a/app/src/test/java/com/asio/tapremly/ExampleUnitTest.kt
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.asio.tapremly
-
-import org.junit.Test
-
-import org.junit.Assert.*
-
-/**
- * Example local unit test, which will execute on the development machine (host).
- *
- * See [testing documentation](http://d.android.com/tools/testing).
- */
-class ExampleUnitTest {
- @Test
- fun addition_isCorrect() {
- assertEquals(4, 2 + 2)
- }
-}
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
index 34c5e9e..73ccdbe 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -12,4 +12,5 @@ org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
-kotlin.code.style=official
\ No newline at end of file
+kotlin.code.style=official
+android.useAndroidX=true
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 9b7cb4a..2e7bb9f 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
diff --git a/settings.gradle.kts b/settings.gradle.kts
index dade36f..90cf10b 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -16,6 +16,7 @@ dependencyResolutionManagement {
repositories {
google()
mavenCentral()
+ maven { url = uri("https://git.asio.asia/api/packages/nixevol/maven") }
}
}