feat: 实现手机端的设备操作和后台连接
This commit is contained in:
+32
-6
@@ -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")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
|
||||
}
|
||||
@@ -1,16 +1,69 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:name=".TapRemlyApp"
|
||||
android:allowBackup="false"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:roundIcon="@drawable/ic_launcher"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.TapRemly"/>
|
||||
android:theme="@style/Theme.TapRemly"
|
||||
android:usesCleartextTraffic="true">
|
||||
|
||||
<activity
|
||||
android:name=".ui.MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.LoginActivity"
|
||||
android:exported="false"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.DeviceActivity"
|
||||
android:exported="false"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.TrustActivity"
|
||||
android:exported="false"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.SettingsActivity"
|
||||
android:exported="false"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.PublishedActivity"
|
||||
android:exported="false"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.LogsActivity"
|
||||
android:exported="false" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.InboxActivity"
|
||||
android:exported="false" />
|
||||
|
||||
<service
|
||||
android:name=".agent.AgentService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync"
|
||||
android:stopWithTask="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -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<Activity>()
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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<Device>,
|
||||
val groups: List<Group>,
|
||||
val trust: List<String>,
|
||||
val localByRemote: Map<String, List<Shortcut>>,
|
||||
val remoteByRemote: Map<String, List<Shortcut>>,
|
||||
val remoteSyncedAt: Map<String, Long>,
|
||||
val syncing: Set<String>,
|
||||
val published: List<Shortcut>,
|
||||
val blocked: Set<String>,
|
||||
val logs: List<LogEntry>,
|
||||
val inbox: List<InboxText>,
|
||||
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<AgentListener>()
|
||||
private val presence = HashMap<String, Boolean>()
|
||||
private val blocked = HashSet<String>()
|
||||
private val syncing = HashSet<String>()
|
||||
private val outbound = LinkedHashMap<String, Outgoing>()
|
||||
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<String>) {
|
||||
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<String>? = 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<String, Boolean>
|
||||
val blockedCopy: Set<String>
|
||||
val syncingCopy: Set<String>
|
||||
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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<String>): Map<String, Boolean>
|
||||
fun watch(ids: List<String>)
|
||||
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<String>): Map<String, Boolean> = emptyMap()
|
||||
override fun watch(ids: List<String>) = Unit
|
||||
override fun limits(): Limits = Limits()
|
||||
override fun close() = Unit
|
||||
}
|
||||
@@ -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<String>): Map<String, Boolean> {
|
||||
val current = client ?: return emptyMap()
|
||||
val found = HashMap<String, Boolean>()
|
||||
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<String>) {
|
||||
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<String, Any>): Map<String, Boolean> {
|
||||
val items = data["items"] as? List<*> ?: return emptyMap()
|
||||
val out = HashMap<String, Boolean>()
|
||||
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", "没有连上")
|
||||
}
|
||||
}
|
||||
@@ -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<Device>, List<Group>> {
|
||||
val o = data(raw) ?: return emptyList<Device>() 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<LogEntry>): 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.asio.tapremly.core
|
||||
|
||||
/** 本端快捷命令:按远端分开。复制只给选中的远端各插入一条新记录。 */
|
||||
class LocalCommands(private val newId: () -> String = { Protocol.newId() }) {
|
||||
private val rows = mutableListOf<Row>()
|
||||
|
||||
data class Row(
|
||||
val id: String,
|
||||
val remoteId: String,
|
||||
val name: String,
|
||||
val shell: String,
|
||||
val confirm: Boolean,
|
||||
)
|
||||
|
||||
fun forRemote(remoteId: String): List<Shortcut> =
|
||||
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<String>): List<Row> {
|
||||
val src = find(id) ?: return emptyList()
|
||||
val created = mutableListOf<Row>()
|
||||
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<Pair<String, String>>()
|
||||
|
||||
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<LogEntry>()
|
||||
|
||||
fun add(entry: LogEntry) {
|
||||
rows.addLast(entry)
|
||||
while (rows.size > max) rows.removeFirst()
|
||||
}
|
||||
|
||||
fun all(): List<LogEntry> = rows.toList()
|
||||
|
||||
fun latest(n: Int): List<LogEntry> = rows.takeLast(n)
|
||||
}
|
||||
@@ -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<Shortcut>,
|
||||
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<Shortcut>) -> 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())
|
||||
}
|
||||
}
|
||||
@@ -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<String, Pair<Stored, Long>>()
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -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<Shortcut>?,
|
||||
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<Shortcut>): 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
|
||||
}
|
||||
}
|
||||
@@ -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<Device>, groups: List<Group>) = 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<Device> = 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<Group> = 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<String>) = 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<String, List<Shortcut>> = 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<Shortcut>, 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<String, List<Shortcut>> = 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<String, Long> = read(
|
||||
"SELECT remote_id, synced_at FROM remote_sync",
|
||||
) { str(0) to long(1) }.toMap()
|
||||
|
||||
fun listPublished(): List<Shortcut> = 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<String> = 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<LogEntry> = 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<LogEntry> = 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<InboxText> = read(
|
||||
"SELECT at_ms, from_id, body FROM inbox ORDER BY seq DESC",
|
||||
) { InboxText(long(0), str(1), str(2)) }
|
||||
|
||||
private fun <T> 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 <T> read(sql: String, args: Array<String>? = null, map: CursorRow.() -> T): List<T> =
|
||||
synchronized(gate) {
|
||||
val cursor = readableDatabase.rawQuery(sql, args)
|
||||
cursor.use {
|
||||
val out = ArrayList<T>(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<String, Any?>): 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
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<Device>, List<Group>> =
|
||||
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<LogEntry>) {
|
||||
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<String>, 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<String>) {
|
||||
if (setCookies.isEmpty()) return
|
||||
val map = linkedMapOf<String, String>()
|
||||
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('"')
|
||||
}
|
||||
}
|
||||
@@ -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<View>(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
|
||||
}
|
||||
@@ -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<Shortcut>, 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<TextView>(R.id.name).text = item.name
|
||||
view.findViewById<TextView>(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"
|
||||
}
|
||||
}
|
||||
@@ -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<EditText>(R.id.name)
|
||||
val shell = view.findViewById<EditText>(R.id.shell)
|
||||
val confirm = view.findViewById<CheckBox>(R.id.confirm)
|
||||
val error = view.findViewById<TextView>(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<EditText>(R.id.name)
|
||||
val endpoint = view.findViewById<EditText>(R.id.endpoint)
|
||||
val error = view.findViewById<TextView>(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
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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<TextView>(R.id.title).text = "${formatWhen(item.atMs)} 来自 ${item.fromId}"
|
||||
view.findViewById<TextView>(R.id.detail).text = item.text
|
||||
binding.rows.addView(view)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<TextView>(R.id.title).text = "${formatWhen(item.atMs)} $mark ${item.summary}"
|
||||
view.findViewById<TextView>(R.id.detail).text = item.detail
|
||||
binding.rows.addView(view)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Row> {
|
||||
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<Row>()
|
||||
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<RecyclerView.ViewHolder>() {
|
||||
private val rows = ArrayList<Row>()
|
||||
|
||||
fun submit(next: List<Row>) {
|
||||
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) }
|
||||
}
|
||||
}
|
||||
@@ -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<Shortcut>) {
|
||||
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<TextView>(R.id.name).text = item.name
|
||||
view.findViewById<TextView>(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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<TextView>(R.id.endpoint).text = id
|
||||
view.findViewById<View>(R.id.remove).setOnClickListener {
|
||||
confirmDialog("不再信任这个端?") { runtime?.trustRemove(id) }
|
||||
}
|
||||
binding.rows.addView(view)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/surface" />
|
||||
<stroke android:width="1dp" android:color="@color/line" />
|
||||
<corners android:radius="8dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/warn_bg" />
|
||||
<corners android:radius="8dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24"
|
||||
android:autoMirrored="true">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#1F4E8C"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M54,28a26,26 0,1 1,-26 26,26 26,0 0,1 26,-26zM54,40a14,14 0,1 0,14 14,14 14,0 0,0 -14,-14z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12,2A10,10 0,1 1,2 12,10 10,0 0,1 12,2zM12,6A6,6 0,1 0,18 12,6 6,0 0,0 12,6z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,295 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<com.google.android.material.appbar.MaterialToolbar
|
||||
android:id="@+id/toolbar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="?attr/actionBarSize"
|
||||
android:background="@color/primary"
|
||||
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
|
||||
app:navigationIcon="@drawable/ic_back"
|
||||
app:subtitleTextColor="@color/on_primary"
|
||||
app:titleTextColor="@color/on_primary" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/surface"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<com.google.android.material.tabs.TabLayout
|
||||
android:id="@+id/tabs"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
app:tabIndicatorColor="@color/primary"
|
||||
app:tabSelectedTextColor="@color/primary"
|
||||
app:tabTextColor="@color/muted" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/input"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:gravity="top|start"
|
||||
android:hint="@string/hint_shell"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textMultiLine"
|
||||
android:maxLines="5"
|
||||
android:minLines="3"
|
||||
android:padding="12dp"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/saveShortcut"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/save_shortcut" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<com.google.android.material.button.MaterialButtonToggleGroup
|
||||
android:id="@+id/timing"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
app:selectionRequired="true"
|
||||
app:singleSelection="true">
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/timingNow"
|
||||
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/send_now"
|
||||
android:textAllCaps="false" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/timingLater"
|
||||
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/send_later"
|
||||
android:textAllCaps="false" />
|
||||
</com.google.android.material.button.MaterialButtonToggleGroup>
|
||||
|
||||
<CheckBox
|
||||
android:id="@+id/keep"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="4dp"
|
||||
android:text="@string/keep_offline"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<View
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/send"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/send" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/scheduleRow"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:visibility="gone">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/scheduleValue"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/pickTime"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/pick_time" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/ttlRow"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:visibility="gone">
|
||||
|
||||
<HorizontalScrollView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:scrollbars="none">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<Button
|
||||
android:id="@+id/ttl1"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="1 小时" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/ttl12"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="12 小时" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/ttl24"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="1 天" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/ttl168"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="7 天" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/ttl720"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="30 天" />
|
||||
</LinearLayout>
|
||||
</HorizontalScrollView>
|
||||
|
||||
<EditText
|
||||
android:id="@+id/ttlHours"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_input"
|
||||
android:hint="@string/ttl_hint"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="number"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/formError"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="13sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/trustWarn"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:background="@drawable/bg_warn"
|
||||
android:padding="8dp"
|
||||
android:text="@string/trust_warn"
|
||||
android:textColor="@color/warn_ink"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
|
||||
<ScrollView
|
||||
android:id="@+id/shortcutScroll"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:fillViewport="true">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/remote_shortcuts"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/remoteSync"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="8dp"
|
||||
android:text="@string/not_synced"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/remoteList"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:orientation="vertical" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:text="@string/local_shortcuts"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/addLocal"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/add" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/localList"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical" />
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<com.google.android.material.appbar.MaterialToolbar
|
||||
android:id="@+id/toolbar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="?attr/actionBarSize"
|
||||
android:background="@color/primary"
|
||||
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
|
||||
app:navigationIcon="@drawable/ic_back"
|
||||
app:titleTextColor="@color/on_primary" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/help"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="12dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/add"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="8dp"
|
||||
android:text="@string/add"
|
||||
android:visibility="gone" />
|
||||
|
||||
<FrameLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1">
|
||||
|
||||
<ScrollView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/rows"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp" />
|
||||
</ScrollView>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/empty"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="16sp"
|
||||
android:visibility="gone" />
|
||||
</FrameLayout>
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,93 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:fillViewport="true">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="24dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingTop="24dp"
|
||||
android:text="@string/app_name"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="28sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="28dp"
|
||||
android:text="@string/account"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/account"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:autofillHints="username"
|
||||
android:background="@drawable/bg_input"
|
||||
android:inputType="text"
|
||||
android:padding="12dp"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/password"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/password"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:autofillHints="password"
|
||||
android:background="@drawable/bg_input"
|
||||
android:inputType="textPassword"
|
||||
android:padding="12dp"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/error"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/login"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="20dp"
|
||||
android:text="@string/login" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/register"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="注册" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/openSettings"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/settings" />
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
@@ -0,0 +1,139 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="56dp"
|
||||
android:background="@color/primary"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="4dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:text="@string/devices"
|
||||
android:textColor="@color/on_primary"
|
||||
android:textSize="20sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/addDevice"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:text="@string/add_device"
|
||||
android:textColor="@color/on_primary"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/addGroup"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:text="@string/add_group"
|
||||
android:textColor="@color/on_primary"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/more"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="12dp"
|
||||
android:text="@string/more"
|
||||
android:textColor="@color/on_primary"
|
||||
android:textSize="15sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/link"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/listError"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="4dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/search"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="16dp"
|
||||
android:layout_marginTop="8dp"
|
||||
android:layout_marginEnd="16dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:hint="@string/search_hint"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="text"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
|
||||
android:id="@+id/refresh"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_marginTop="8dp"
|
||||
android:layout_weight="1">
|
||||
|
||||
<FrameLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/list"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:clipToPadding="false"
|
||||
android:paddingBottom="12dp" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/empty"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:orientation="vertical"
|
||||
android:padding="24dp"
|
||||
android:visibility="gone">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/emptyText"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/empty_devices"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/emptyAdd"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/add_device" />
|
||||
</LinearLayout>
|
||||
</FrameLayout>
|
||||
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,77 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<com.google.android.material.appbar.MaterialToolbar
|
||||
android:id="@+id/toolbar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="?attr/actionBarSize"
|
||||
android:background="@color/primary"
|
||||
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
|
||||
app:navigationIcon="@drawable/ic_back"
|
||||
app:title="@string/settings"
|
||||
app:titleTextColor="@color/on_primary" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/server"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/server"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textUri"
|
||||
android:padding="12dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/nix"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/nix"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textUri"
|
||||
android:padding="12dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/error"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/save"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="20dp"
|
||||
android:text="@string/save" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<com.google.android.material.appbar.MaterialToolbar
|
||||
android:id="@+id/toolbar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="?attr/actionBarSize"
|
||||
android:background="@color/primary"
|
||||
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
|
||||
app:navigationIcon="@drawable/ic_back"
|
||||
app:title="@string/trust"
|
||||
app:titleTextColor="@color/on_primary" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:padding="16dp"
|
||||
android:text="@string/trust_help"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<ScrollView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/rows"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:paddingBottom="12dp" />
|
||||
</ScrollView>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/surface"
|
||||
android:orientation="vertical"
|
||||
android:padding="12dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/error"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingBottom="6dp"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="13sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<EditText
|
||||
android:id="@+id/endpoint"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:background="@drawable/bg_input"
|
||||
android:hint="@string/endpoint_hint"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="text"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/add"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="8dp"
|
||||
android:text="@string/add" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="20dp"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingEnd="20dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/name"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/name"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="text"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/endpoint_hint"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/endpoint"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="text"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/error"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="20dp"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingEnd="20dp"
|
||||
android:paddingBottom="4dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/name"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/name"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="text"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/shell_label"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/shell"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:gravity="top|start"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textMultiLine"
|
||||
android:minLines="3"
|
||||
android:padding="10dp"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<CheckBox
|
||||
android:id="@+id/confirm"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/confirm_before"
|
||||
android:textColor="@color/ink" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/error"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="14sp"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/surface"
|
||||
android:foreground="?attr/selectableItemBackground"
|
||||
android:minHeight="64dp"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="12dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:paddingBottom="12dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/name"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/online"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="12dp"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/endpoint"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:background="@color/surface"
|
||||
android:gravity="center_vertical"
|
||||
android:minHeight="48dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="8dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/title"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="15sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/rename"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:text="@string/rename"
|
||||
android:textColor="@color/primary"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/delete"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:text="@string/delete"
|
||||
android:textColor="@color/danger"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="8dp"
|
||||
android:background="@color/surface"
|
||||
android:orientation="vertical"
|
||||
android:padding="12dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/detail"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/surface"
|
||||
android:foreground="?attr/selectableItemBackground"
|
||||
android:minHeight="56dp"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="12dp"
|
||||
android:paddingTop="10dp"
|
||||
android:paddingEnd="12dp"
|
||||
android:paddingBottom="10dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/name"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/shell"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="2dp"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="8dp"
|
||||
android:background="@color/surface"
|
||||
android:gravity="center_vertical"
|
||||
android:minHeight="52dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="12dp"
|
||||
android:paddingEnd="4dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/endpoint"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:textColor="@color/ink"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/remove"
|
||||
style="@style/Widget.TapRemly.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/remove"
|
||||
android:textColor="@color/danger" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<menu xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto">
|
||||
<item
|
||||
android:id="@+id/move_group"
|
||||
android:title="分组"
|
||||
app:showAsAction="never" />
|
||||
<item
|
||||
android:id="@+id/remove_device"
|
||||
android:title="从列表移出"
|
||||
app:showAsAction="never" />
|
||||
</menu>
|
||||
@@ -1,16 +1,16 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.TapRemly" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||
<!-- Primary brand color. -->
|
||||
<item name="colorPrimary">@color/purple_200</item>
|
||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
||||
<item name="colorOnPrimary">@color/black</item>
|
||||
<!-- Secondary brand color. -->
|
||||
<item name="colorSecondary">@color/teal_200</item>
|
||||
<item name="colorSecondaryVariant">@color/teal_200</item>
|
||||
<item name="colorOnSecondary">@color/black</item>
|
||||
<!-- Status bar color. -->
|
||||
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
|
||||
<!-- Customize your theme here. -->
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.TapRemly" parent="Theme.MaterialComponents.Light.NoActionBar">
|
||||
<item name="colorPrimary">@color/primary</item>
|
||||
<item name="colorPrimaryVariant">@color/primary_dark</item>
|
||||
<item name="colorOnPrimary">@color/on_primary</item>
|
||||
<item name="colorSecondary">@color/primary</item>
|
||||
<item name="colorOnSecondary">@color/on_primary</item>
|
||||
<item name="android:statusBarColor">@color/primary_dark</item>
|
||||
<item name="android:navigationBarColor">@color/surface</item>
|
||||
<item name="android:windowBackground">@color/bg</item>
|
||||
<item name="android:textColorPrimary">@color/ink</item>
|
||||
<item name="materialButtonStyle">@style/Widget.TapRemly.Button</item>
|
||||
<item name="borderlessButtonStyle">@style/Widget.TapRemly.TextButton</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,10 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
<color name="primary">#1F4E8C</color>
|
||||
<color name="primary_dark">#173C6E</color>
|
||||
<color name="on_primary">#FFFFFF</color>
|
||||
<color name="bg">#F4F6F8</color>
|
||||
<color name="surface">#FFFFFF</color>
|
||||
<color name="ink">#1C2430</color>
|
||||
<color name="muted">#5E6A78</color>
|
||||
<color name="line">#E3E8EE</color>
|
||||
<color name="danger">#A33B3B</color>
|
||||
<color name="ok">#1F7A4D</color>
|
||||
<color name="warn_bg">#FBF3E4</color>
|
||||
<color name="warn_ink">#7A5B17</color>
|
||||
</resources>
|
||||
@@ -1,3 +1,57 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">TapRemly</string>
|
||||
<string name="notice_running">保持连接</string>
|
||||
<string name="login">登录</string>
|
||||
<string name="account">账号</string>
|
||||
<string name="password">密码</string>
|
||||
<string name="settings">设置</string>
|
||||
<string name="devices">设备</string>
|
||||
<string name="add_device">添加设备</string>
|
||||
<string name="add_group">新建分组</string>
|
||||
<string name="more">更多</string>
|
||||
<string name="search_hint">搜索名称或端编号</string>
|
||||
<string name="empty_devices">还没有设备</string>
|
||||
<string name="trust">信任</string>
|
||||
<string name="published">本机命令</string>
|
||||
<string name="logs">执行记录</string>
|
||||
<string name="inbox">收到的文字</string>
|
||||
<string name="logout">退出</string>
|
||||
<string name="tab_command">命令</string>
|
||||
<string name="tab_text">文字</string>
|
||||
<string name="hint_shell">输入要在对方执行的 shell</string>
|
||||
<string name="hint_text">输入要显示在对方设备上的文字</string>
|
||||
<string name="save_shortcut">存为本端快捷命令</string>
|
||||
<string name="send_now">立即</string>
|
||||
<string name="send_later">定时</string>
|
||||
<string name="keep_offline">离线保留</string>
|
||||
<string name="send">发送</string>
|
||||
<string name="pick_time">选择时刻</string>
|
||||
<string name="ttl_hint">小时</string>
|
||||
<string name="trust_warn">对方尚未信任本机,命令不会执行</string>
|
||||
<string name="remote_shortcuts">远端快捷命令</string>
|
||||
<string name="local_shortcuts">本端快捷命令</string>
|
||||
<string name="add">添加</string>
|
||||
<string name="trust_help">这里添加的设备可以命令本机。</string>
|
||||
<string name="endpoint_hint">端编号</string>
|
||||
<string name="server">服务器地址</string>
|
||||
<string name="nix">消息服务地址</string>
|
||||
<string name="save">保存</string>
|
||||
<string name="ungrouped">未分组</string>
|
||||
<string name="rename">重命名</string>
|
||||
<string name="delete">删除</string>
|
||||
<string name="online">在线</string>
|
||||
<string name="offline">不在线</string>
|
||||
<string name="back">返回</string>
|
||||
<string name="name">名称</string>
|
||||
<string name="shell_label">要执行的命令</string>
|
||||
<string name="confirm_before">发送前再确认一次</string>
|
||||
<string name="remove">移除</string>
|
||||
<string name="syncing">同步中</string>
|
||||
<string name="not_synced">尚未同步</string>
|
||||
<string name="no_commands">还没有命令</string>
|
||||
<string name="no_logs">还没有记录</string>
|
||||
<string name="no_texts">还没有收到文字</string>
|
||||
<string name="published_help">其他设备可以让这部手机执行这里的命令。</string>
|
||||
<string name="logging_in">正在登录</string>
|
||||
</resources>
|
||||
@@ -1,16 +1,24 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.TapRemly" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||
<!-- Primary brand color. -->
|
||||
<item name="colorPrimary">@color/purple_500</item>
|
||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
||||
<item name="colorOnPrimary">@color/white</item>
|
||||
<!-- Secondary brand color. -->
|
||||
<item name="colorSecondary">@color/teal_200</item>
|
||||
<item name="colorSecondaryVariant">@color/teal_700</item>
|
||||
<item name="colorOnSecondary">@color/black</item>
|
||||
<!-- Status bar color. -->
|
||||
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
|
||||
<!-- Customize your theme here. -->
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.TapRemly" parent="Theme.MaterialComponents.Light.NoActionBar">
|
||||
<item name="colorPrimary">@color/primary</item>
|
||||
<item name="colorPrimaryVariant">@color/primary_dark</item>
|
||||
<item name="colorOnPrimary">@color/on_primary</item>
|
||||
<item name="colorSecondary">@color/primary</item>
|
||||
<item name="colorOnSecondary">@color/on_primary</item>
|
||||
<item name="android:statusBarColor">@color/primary_dark</item>
|
||||
<item name="android:navigationBarColor">@color/surface</item>
|
||||
<item name="android:windowBackground">@color/bg</item>
|
||||
<item name="android:textColorPrimary">@color/ink</item>
|
||||
<item name="materialButtonStyle">@style/Widget.TapRemly.Button</item>
|
||||
<item name="borderlessButtonStyle">@style/Widget.TapRemly.TextButton</item>
|
||||
</style>
|
||||
|
||||
<style name="Widget.TapRemly.Button" parent="Widget.MaterialComponents.Button">
|
||||
<item name="android:textAllCaps">false</item>
|
||||
</style>
|
||||
|
||||
<style name="Widget.TapRemly.TextButton" parent="Widget.MaterialComponents.Button.TextButton">
|
||||
<item name="android:textAllCaps">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -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<String>()
|
||||
var outcome = ShellOutcome(true, "完成")
|
||||
override fun run(shell: String): ShellOutcome {
|
||||
commands.add(shell)
|
||||
return outcome
|
||||
}
|
||||
}
|
||||
|
||||
private class Harness(
|
||||
trustedIds: Set<String> = emptySet(),
|
||||
var publishedShell: String = "echo now",
|
||||
) {
|
||||
val shell = FakeShell()
|
||||
val trust = trustedIds.toMutableSet()
|
||||
var clock = 1_000L
|
||||
val texts = mutableListOf<Pair<String, String>>()
|
||||
val synced = mutableListOf<Pair<String, List<Shortcut>>>()
|
||||
val logs = mutableListOf<LogEntry>()
|
||||
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\":\"没有成功\""))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -13,3 +13,4 @@ org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# org.gradle.parallel=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
android.useAndroidX=true
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -16,6 +16,7 @@ dependencyResolutionManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
maven { url = uri("https://git.asio.asia/api/packages/nixevol/maven") }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user