Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1998fffe30 | ||
|
|
82095e614d | ||
|
|
d72abb5f40 |
@@ -11,8 +11,8 @@ android {
|
||||
applicationId = "com.expapp.trigger"
|
||||
minSdk = 24
|
||||
targetSdk = 34
|
||||
versionCode = 19
|
||||
versionName = "1.3.0"
|
||||
versionCode = 22
|
||||
versionName = "1.3.3"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@style/Theme.ExpApp">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
|
||||
@@ -93,8 +93,25 @@ class MainActivity : FragmentActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
val origHandler = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
|
||||
android.util.Log.e("CrashHandler", "Crash on ${thread.name}", throwable)
|
||||
try {
|
||||
getSharedPreferences("app_settings_prefs", Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString("last_crash_log", "${throwable.javaClass.simpleName}: ${throwable.message}\n" + throwable.stackTraceToString().take(1500))
|
||||
.commit()
|
||||
} catch (_: Exception) {}
|
||||
origHandler?.uncaughtException(thread, throwable)
|
||||
}
|
||||
|
||||
repository = DeviceRepository(SharedPrefsStorage(applicationContext))
|
||||
val settingsPrefs = getSharedPreferences("app_settings_prefs", Context.MODE_PRIVATE)
|
||||
val lastCrash = settingsPrefs.getString("last_crash_log", null)
|
||||
if (!lastCrash.isNullOrBlank()) {
|
||||
settingsPrefs.edit().remove("last_crash_log").apply()
|
||||
android.util.Log.e("CrashReport", "Recovered from crash: $lastCrash")
|
||||
}
|
||||
val hasSeeded = settingsPrefs.getBoolean("has_seeded_default_device", false)
|
||||
if (!hasSeeded) {
|
||||
settingsPrefs.edit().putBoolean("has_seeded_default_device", true).apply()
|
||||
@@ -117,8 +134,11 @@ class MainActivity : FragmentActivity() {
|
||||
}
|
||||
|
||||
// Auto-upgrade existing default device with SysPulse defaults if missing
|
||||
try {
|
||||
repository.getDevices().forEach { dev ->
|
||||
if (dev.node.equals("debian", ignoreCase = true) && dev.syspulseUrl.isBlank()) {
|
||||
val sysUrl = dev.syspulseUrl
|
||||
val nodeName = dev.node
|
||||
if (nodeName.equals("debian", ignoreCase = true) && sysUrl.isBlank()) {
|
||||
val upgraded = dev.copy(
|
||||
syspulseUrl = "http://100.85.63.44:8088",
|
||||
syspulseSecretKey = if (dev.syspulseSecretKey.isBlank()) "default_pulse_secret_key_change_me" else dev.syspulseSecretKey
|
||||
@@ -126,6 +146,9 @@ class MainActivity : FragmentActivity() {
|
||||
repository.updateDevice(upgraded)
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Guard against any startup migration issues
|
||||
}
|
||||
triggerClient = TriggerClient()
|
||||
appSettings = AppSettings(applicationContext)
|
||||
historyRepository = TriggerHistoryRepository(applicationContext)
|
||||
|
||||
@@ -7,7 +7,7 @@ data class DeviceConfig(
|
||||
val name: String,
|
||||
val node: String,
|
||||
val secretKey: String,
|
||||
val r2Url: String,
|
||||
val r2Url: String = "",
|
||||
val powerOnUrl: String,
|
||||
val powerOffUrl: String,
|
||||
val rebootUrl: String,
|
||||
|
||||
@@ -4,7 +4,14 @@ import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.expapp.trigger.data.model.DeviceConfig
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonDeserializationContext
|
||||
import com.google.gson.JsonDeserializer
|
||||
import com.google.gson.JsonElement
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import java.lang.reflect.Type
|
||||
import java.util.UUID
|
||||
|
||||
interface KeyValueStorage {
|
||||
fun getString(key: String, defaultValue: String?): String?
|
||||
@@ -44,8 +51,35 @@ class SharedPrefsStorage(
|
||||
}
|
||||
}
|
||||
|
||||
private fun JsonObject.getStringSafe(key: String, default: String = ""): String {
|
||||
val elem = get(key) ?: return default
|
||||
if (elem.isJsonNull || !elem.isJsonPrimitive) return default
|
||||
return try { elem.asString ?: default } catch (_: Exception) { default }
|
||||
}
|
||||
|
||||
class DeviceConfigDeserializer : JsonDeserializer<DeviceConfig> {
|
||||
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): DeviceConfig {
|
||||
val obj = if (json.isJsonObject) json.asJsonObject else JsonObject()
|
||||
return DeviceConfig(
|
||||
id = obj.getStringSafe("id").ifBlank { UUID.randomUUID().toString() },
|
||||
name = obj.getStringSafe("name", "Server"),
|
||||
node = obj.getStringSafe("node", "debian"),
|
||||
secretKey = obj.getStringSafe("secretKey"),
|
||||
r2Url = obj.getStringSafe("r2Url"),
|
||||
powerOnUrl = obj.getStringSafe("powerOnUrl"),
|
||||
powerOffUrl = obj.getStringSafe("powerOffUrl"),
|
||||
rebootUrl = obj.getStringSafe("rebootUrl"),
|
||||
statusUrl = obj.getStringSafe("statusUrl"),
|
||||
syspulseUrl = obj.getStringSafe("syspulseUrl"),
|
||||
syspulseSecretKey = obj.getStringSafe("syspulseSecretKey")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class DeviceRepository(private val storage: KeyValueStorage) {
|
||||
private val gson = Gson()
|
||||
private val gson: Gson = GsonBuilder()
|
||||
.registerTypeAdapter(DeviceConfig::class.java, DeviceConfigDeserializer())
|
||||
.create()
|
||||
private val storageKey = "saved_devices_json"
|
||||
|
||||
fun getDevices(): List<DeviceConfig> {
|
||||
|
||||
@@ -2,14 +2,23 @@ package com.expapp.trigger.network
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import com.expapp.trigger.data.model.CpuMetrics
|
||||
import com.expapp.trigger.data.model.DeviceConfig
|
||||
import com.expapp.trigger.data.model.DiskMetrics
|
||||
import com.expapp.trigger.data.model.RamMetrics
|
||||
import com.expapp.trigger.data.model.ScheduledTask
|
||||
import com.expapp.trigger.data.model.ScheduledTasksResponse
|
||||
import com.expapp.trigger.data.model.ServiceOperation
|
||||
import com.expapp.trigger.data.model.SysPulseStatus
|
||||
import com.expapp.trigger.data.model.SysServiceInfo
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonDeserializationContext
|
||||
import com.google.gson.JsonDeserializer
|
||||
import com.google.gson.JsonElement
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
@@ -18,8 +27,45 @@ import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.lang.reflect.Type
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class SysPulseStatusDeserializer : JsonDeserializer<SysPulseStatus> {
|
||||
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): SysPulseStatus {
|
||||
if (!json.isJsonObject) return SysPulseStatus()
|
||||
val obj = json.asJsonObject
|
||||
val cpu = if (obj.has("cpu") && obj.get("cpu").isJsonObject) {
|
||||
context.deserialize<CpuMetrics>(obj.get("cpu"), CpuMetrics::class.java) ?: CpuMetrics()
|
||||
} else CpuMetrics()
|
||||
val ram = if (obj.has("ram") && obj.get("ram").isJsonObject) {
|
||||
context.deserialize<RamMetrics>(obj.get("ram"), RamMetrics::class.java) ?: RamMetrics()
|
||||
} else RamMetrics()
|
||||
val disk = if (obj.has("disk") && obj.get("disk").isJsonArray) {
|
||||
val listType = object : TypeToken<List<DiskMetrics>>() {}.type
|
||||
context.deserialize<List<DiskMetrics>>(obj.get("disk"), listType) ?: emptyList()
|
||||
} else emptyList()
|
||||
val services = if (obj.has("services") && obj.get("services").isJsonArray) {
|
||||
val listType = object : TypeToken<List<SysServiceInfo>>() {}.type
|
||||
context.deserialize<List<SysServiceInfo>>(obj.get("services"), listType) ?: emptyList()
|
||||
} else emptyList()
|
||||
val uptime = if (obj.has("uptime") && !obj.get("uptime").isJsonNull && obj.get("uptime").isJsonPrimitive) {
|
||||
try { obj.get("uptime").asString ?: "" } catch (_: Exception) { "" }
|
||||
} else ""
|
||||
val success = if (obj.has("success") && !obj.get("success").isJsonNull && obj.get("success").isJsonPrimitive) {
|
||||
try { obj.get("success").asBoolean } catch (_: Exception) { true }
|
||||
} else true
|
||||
|
||||
return SysPulseStatus(
|
||||
success = success,
|
||||
uptime = uptime,
|
||||
cpu = cpu,
|
||||
ram = ram,
|
||||
disk = disk,
|
||||
services = services
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class SysPulseClient(
|
||||
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
|
||||
.followRedirects(true)
|
||||
@@ -27,7 +73,9 @@ class SysPulseClient(
|
||||
.connectTimeout(8, TimeUnit.SECONDS)
|
||||
.readTimeout(12, TimeUnit.SECONDS)
|
||||
.build(),
|
||||
private val gson: Gson = Gson()
|
||||
private val gson: Gson = GsonBuilder()
|
||||
.registerTypeAdapter(SysPulseStatus::class.java, SysPulseStatusDeserializer())
|
||||
.create()
|
||||
) {
|
||||
companion object {
|
||||
const val DEFAULT_FALLBACK_SECRET = "default_pulse_secret_key_change_me"
|
||||
@@ -49,7 +97,11 @@ class SysPulseClient(
|
||||
|
||||
fun resolveBaseUrl(device: DeviceConfig, nodeStatus: NodeStatus? = null): String {
|
||||
if (device.syspulseUrl.isNotBlank()) {
|
||||
return device.syspulseUrl.trim().removeSuffix("/")
|
||||
return device.syspulseUrl.trim()
|
||||
.removeSuffix("/")
|
||||
.removeSuffix("/api/status")
|
||||
.removeSuffix("/api")
|
||||
.removeSuffix("/")
|
||||
}
|
||||
val ip = nodeStatus?.ip?.trim()
|
||||
if (!ip.isNullOrBlank()) {
|
||||
|
||||
@@ -93,7 +93,8 @@ fun CircularMetricGauge(
|
||||
modifier: Modifier = Modifier,
|
||||
size: Int = 110
|
||||
) {
|
||||
val clampedPct = percentage.coerceIn(0.0, 100.0).toFloat()
|
||||
val safePct = if (percentage.isNaN() || percentage.isInfinite()) 0.0 else percentage
|
||||
val clampedPct = safePct.coerceIn(0.0, 100.0).toFloat()
|
||||
val animatedSweep by animateFloatAsState(
|
||||
targetValue = clampedPct * 2.6f, // 260 degrees arc
|
||||
animationSpec = tween(700, easing = FastOutSlowInEasing),
|
||||
|
||||
@@ -120,4 +120,30 @@ class DeviceRepositoryTest {
|
||||
|
||||
org.junit.Assert.assertFalse(updated)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getDevices_whenOldJsonWithoutSyspulse_doesNotCrash() {
|
||||
val oldJson = """[{"id":"2dc98ae9-9f71-4f29-95a6-a59ac94d7bf6","name":"Server","node":"debian","secretKey":"Carbon@12","r2Url":"https://bucket.linuxguy.space/home-server-app/endpoints.json","powerOnUrl":"https://trigger.macrodroid.com/87f2f62c-09ee-43cb-8796-fd1a6465754b/wakeserver","powerOffUrl":"https://cosmos.linuxguy.space/poweroff?node=debian","rebootUrl":"https://cosmos.linuxguy.space/reboot?node=debian","statusUrl":"https://cosmos.linuxguy.space/status?node=debian"}]"""
|
||||
storage.putString("saved_devices_json", oldJson)
|
||||
|
||||
val devices = repository.getDevices()
|
||||
assertEquals(1, devices.size)
|
||||
val dev = devices[0]
|
||||
assertTrue(dev.syspulseUrl.isBlank())
|
||||
assertTrue(dev.syspulseSecretKey.isBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getDevices_whenJsonContainsExplicitNulls_doesNotCrash() {
|
||||
val jsonWithNulls = """[{"id":"2dc98ae9-9f71-4f29-95a6-a59ac94d7bf6","name":"Server","node":"debian","secretKey":"Carbon@12","r2Url":null,"powerOnUrl":"https://trigger.macrodroid.com","powerOffUrl":"https://cosmos.linuxguy.space","rebootUrl":"https://cosmos.linuxguy.space","statusUrl":null,"syspulseUrl":null,"syspulseSecretKey":null}]"""
|
||||
storage.putString("saved_devices_json", jsonWithNulls)
|
||||
|
||||
val devices = repository.getDevices()
|
||||
assertEquals(1, devices.size)
|
||||
val dev = devices[0]
|
||||
assertEquals("", dev.r2Url)
|
||||
assertEquals("", dev.statusUrl)
|
||||
assertEquals("", dev.syspulseUrl)
|
||||
assertEquals("", dev.syspulseSecretKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.expapp.trigger.network
|
||||
|
||||
import com.expapp.trigger.data.model.SysPulseStatus
|
||||
import com.google.gson.GsonBuilder
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SysPulseClientTest {
|
||||
|
||||
@Test
|
||||
fun testDeserializeSysPulseStatus_realPayload() {
|
||||
val json = """{"cpu":{"cores":4,"load":[0.17,1.25,0.88],"pct":5.01},"disk":[{"mount":"/","pct":31.22,"total_gb":115.83,"used_gb":36.16},{"mount":"/mnt/storage","pct":1.95,"total_gb":1862.11,"used_gb":36.27}],"ram":{"pct":40.78,"total_mb":7855,"used_mb":3203},"services":[{"name":"openclaw","unit":"openclaw-gateway.service","active":true,"enabled":true,"state":"running","pid":927},{"name":"forge","unit":"forge.service","active":true,"enabled":true,"state":"exited","pid":1751},{"name":"oort","unit":"oort.service","active":true,"enabled":true,"state":"running","pid":1752},{"name":"minio","unit":"minio.service","active":true,"enabled":true,"state":"running","pid":1711},{"name":"xrdp","unit":"xrdp.service","active":false,"enabled":false,"state":"stopped"},{"name":"xrdp sesman","unit":"xrdp-sesman.service","active":false,"enabled":false,"state":"stopped"},{"name":"docker","unit":"docker.service","active":true,"enabled":true,"state":"running","pid":1020},{"name":"postgres","unit":"[email protected]","active":true,"enabled":true,"state":"running","pid":1883}],"success":true,"uptime":"16m 15s"}"""
|
||||
|
||||
val gson = GsonBuilder()
|
||||
.registerTypeAdapter(SysPulseStatus::class.java, SysPulseStatusDeserializer())
|
||||
.create()
|
||||
|
||||
val status = gson.fromJson(json, SysPulseStatus::class.java)
|
||||
assertNotNull(status)
|
||||
assertEquals("16m 15s", status.uptime)
|
||||
assertEquals(5.01, status.cpu.pct, 0.01)
|
||||
assertEquals(2, status.disk.size)
|
||||
assertEquals(8, status.services.size)
|
||||
val activeCount = status.services.count { it.active }
|
||||
assertEquals(6, activeCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDeserializeSysPulseStatus_emptyOrErrorPayload() {
|
||||
val errorJson = """{"error":"Unauthorized","success":false}"""
|
||||
|
||||
val gson = GsonBuilder()
|
||||
.registerTypeAdapter(SysPulseStatus::class.java, SysPulseStatusDeserializer())
|
||||
.create()
|
||||
|
||||
val status = gson.fromJson(errorJson, SysPulseStatus::class.java)
|
||||
assertNotNull(status)
|
||||
assertEquals("", status.uptime)
|
||||
assertEquals(0.0, status.cpu.pct, 0.01)
|
||||
assertTrue(status.disk.isEmpty())
|
||||
assertTrue(status.services.isEmpty())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user