feat: add live server status monitoring, automatic status polling, and modernized UI design

This commit is contained in:
2026-11-18 15:26:37 +05:30
parent f31f049877
commit efa200c5fe
12 changed files with 519 additions and 111 deletions
@@ -10,5 +10,6 @@ data class DeviceConfig(
val r2Url: String, val r2Url: String,
val powerOnUrl: String, val powerOnUrl: String,
val powerOffUrl: String, val powerOffUrl: String,
val rebootUrl: String val rebootUrl: String,
val statusUrl: String = ""
) )
@@ -5,7 +5,8 @@ import com.google.gson.JsonParser
data class ParsedEndpoints( data class ParsedEndpoints(
val powerOn: String, val powerOn: String,
val powerOff: String, val powerOff: String,
val reboot: String val reboot: String,
val status: String = ""
) )
object R2ConfigParser { object R2ConfigParser {
@@ -41,10 +42,16 @@ object R2ConfigParser {
?: normalizedMap["reset"] ?: normalizedMap["reset"]
?: throw IllegalArgumentException("Missing required endpoint key: 'reboot'") ?: throw IllegalArgumentException("Missing required endpoint key: 'reboot'")
val status = normalizedMap["status"]
?: normalizedMap["ping"]
?: normalizedMap["health"]
?: ""
ParsedEndpoints( ParsedEndpoints(
powerOn = powerOn, powerOn = powerOn,
powerOff = powerOff, powerOff = powerOff,
reboot = reboot reboot = reboot,
status = status
) )
} }
} }
@@ -58,17 +58,20 @@ class DeviceRepository(private val storage: KeyValueStorage) {
deviceId: String, deviceId: String,
powerOnUrl: String, powerOnUrl: String,
powerOffUrl: String, powerOffUrl: String,
rebootUrl: String rebootUrl: String,
statusUrl: String = ""
): Boolean { ): Boolean {
val current = getDevices().toMutableList() val current = getDevices().toMutableList()
val index = current.indexOfFirst { it.id == deviceId } val index = current.indexOfFirst { it.id == deviceId }
if (index != -1) { if (index != -1) {
val old = current[index] val old = current[index]
if (old.powerOnUrl != powerOnUrl || old.powerOffUrl != powerOffUrl || old.rebootUrl != rebootUrl) { val effectiveStatusUrl = if (statusUrl.isNotBlank()) statusUrl else old.statusUrl
if (old.powerOnUrl != powerOnUrl || old.powerOffUrl != powerOffUrl || old.rebootUrl != rebootUrl || old.statusUrl != effectiveStatusUrl) {
current[index] = old.copy( current[index] = old.copy(
powerOnUrl = powerOnUrl, powerOnUrl = powerOnUrl,
powerOffUrl = powerOffUrl, powerOffUrl = powerOffUrl,
rebootUrl = rebootUrl rebootUrl = rebootUrl,
statusUrl = effectiveStatusUrl
) )
saveDevices(current) saveDevices(current)
return true return true
@@ -127,4 +127,67 @@ class TriggerClient(
} }
}) })
} }
fun checkStatus(
device: DeviceConfig,
callback: (NodeStatus) -> Unit
) {
val baseStatusUrl = if (device.statusUrl.isNotBlank()) {
device.statusUrl
} else {
"https://cosmos.linuxguy.space/status?node=${device.node}"
}
val targetUrl = if (!baseStatusUrl.contains("node=") && device.node.isNotBlank()) {
if (baseStatusUrl.contains("?")) {
"$baseStatusUrl&node=${device.node}"
} else {
"$baseStatusUrl?node=${device.node}"
}
} else {
baseStatusUrl
}
val request = try {
Request.Builder().url(targetUrl).get().build()
} catch (e: Exception) {
callback(NodeStatus(isOnline = false, statusText = "INVALID URL"))
return
}
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
callback(NodeStatus(isOnline = false, statusText = "OFFLINE"))
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!it.isSuccessful) {
callback(NodeStatus(isOnline = false, statusText = "OFFLINE"))
return
}
val body = it.body?.string().orEmpty().trim()
if (body.startsWith("{")) {
try {
val json = com.google.gson.JsonParser.parseString(body).asJsonObject
val online = when {
json.has("online") && json.get("online").isJsonPrimitive && json.get("online").asJsonPrimitive.isBoolean ->
json.get("online").asBoolean
json.has("status") && json.get("status").isJsonPrimitive ->
json.get("status").asString.equals("online", ignoreCase = true)
else -> false
}
val ip = if (json.has("ip") && json.get("ip").isJsonPrimitive) json.get("ip").asString else null
callback(NodeStatus(isOnline = online, statusText = if (online) "ONLINE" else "OFFLINE", ip = ip))
} catch (e: Exception) {
callback(NodeStatus(isOnline = false, statusText = "ERROR"))
}
} else {
val isOnline = body.equals("ONLINE", ignoreCase = true)
callback(NodeStatus(isOnline = isOnline, statusText = if (isOnline) "ONLINE" else "OFFLINE"))
}
}
}
})
}
} }
@@ -11,3 +11,10 @@ data class TriggerResponse(
val statusCode: Int, val statusCode: Int,
val message: String val message: String
) )
data class NodeStatus(
val isOnline: Boolean,
val statusText: String,
val ip: String? = null,
val timestamp: Long = System.currentTimeMillis()
)
@@ -1,7 +1,12 @@
package com.expapp.trigger.ui.components package com.expapp.trigger.ui.components
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
@@ -10,15 +15,19 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@@ -29,60 +38,83 @@ import androidx.compose.ui.unit.sp
fun HugeActionButton( fun HugeActionButton(
text: String, text: String,
subtext: String, subtext: String,
containerColor: Color, gradientColors: List<Color>,
contentColor: Color = Color.White, borderColor: Color,
icon: ImageVector, icon: ImageVector,
isLoading: Boolean = false, isLoading: Boolean = false,
enabled: Boolean = true, enabled: Boolean = true,
onClick: () -> Unit onClick: () -> Unit
) { ) {
Button( val shape = RoundedCornerShape(24.dp)
onClick = onClick, val interactionSource = remember { MutableInteractionSource() }
enabled = enabled && !isLoading,
Box(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(105.dp), .height(115.dp)
shape = RoundedCornerShape(22.dp), .shadow(if (enabled) 8.dp else 0.dp, shape = shape, spotColor = borderColor.copy(alpha = 0.5f))
colors = ButtonDefaults.buttonColors( .clip(shape)
containerColor = containerColor, .background(
contentColor = contentColor, brush = Brush.horizontalGradient(
disabledContainerColor = containerColor.copy(alpha = 0.4f), if (enabled) gradientColors else gradientColors.map { it.copy(alpha = 0.35f) }
disabledContentColor = contentColor.copy(alpha = 0.5f) )
), )
elevation = ButtonDefaults.buttonElevation( .border(
defaultElevation = 6.dp, width = 1.5.dp,
pressedElevation = 2.dp, brush = Brush.horizontalGradient(
disabledElevation = 0.dp if (enabled) listOf(borderColor.copy(alpha = 0.8f), borderColor.copy(alpha = 0.3f))
) else listOf(Color.Transparent, Color.Transparent)
),
shape = shape
)
.clickable(
interactionSource = interactionSource,
indication = rememberRipple(color = Color.White.copy(alpha = 0.3f)),
enabled = enabled && !isLoading,
onClick = onClick
)
.padding(horizontal = 22.dp, vertical = 18.dp)
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier.fillMaxWidth(),
.fillMaxWidth()
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(
Icon( verticalAlignment = Alignment.CenterVertically,
imageVector = icon, modifier = Modifier.weight(1f)
contentDescription = text, ) {
tint = contentColor, Box(
modifier = Modifier.size(38.dp) modifier = Modifier
) .size(54.dp)
Spacer(modifier = Modifier.width(16.dp)) .clip(CircleShape)
.background(Color.White.copy(alpha = if (enabled) 0.15f else 0.07f)),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = icon,
contentDescription = text,
tint = if (enabled) Color.White else Color.White.copy(alpha = 0.5f),
modifier = Modifier.size(32.dp)
)
}
Spacer(modifier = Modifier.width(18.dp))
Column { Column {
Text( Text(
text = text, text = text,
fontSize = 24.sp, fontSize = 22.sp,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.ExtraBold,
color = contentColor, color = if (enabled) Color.White else Color.White.copy(alpha = 0.5f),
letterSpacing = 0.5.sp letterSpacing = 1.sp
) )
Spacer(modifier = Modifier.height(3.dp))
Text( Text(
text = subtext, text = subtext,
fontSize = 13.sp, fontSize = 13.sp,
fontWeight = FontWeight.Normal, fontWeight = FontWeight.Medium,
color = contentColor.copy(alpha = 0.85f) color = if (enabled) Color.White.copy(alpha = 0.85f) else Color.White.copy(alpha = 0.4f)
) )
} }
} }
@@ -90,7 +122,7 @@ fun HugeActionButton(
AnimatedVisibility(visible = isLoading) { AnimatedVisibility(visible = isLoading) {
CircularProgressIndicator( CircularProgressIndicator(
modifier = Modifier.size(28.dp), modifier = Modifier.size(28.dp),
color = contentColor, color = Color.White,
strokeWidth = 3.dp strokeWidth = 3.dp
) )
} }
@@ -245,7 +245,8 @@ fun AddDevicePage(
r2Url = r2Url.trim(), r2Url = r2Url.trim(),
powerOnUrl = endpoints.powerOn, powerOnUrl = endpoints.powerOn,
powerOffUrl = endpoints.powerOff, powerOffUrl = endpoints.powerOff,
rebootUrl = endpoints.reboot rebootUrl = endpoints.reboot,
statusUrl = endpoints.status
) )
onDeviceAdded(newDevice) onDeviceAdded(newDevice)
successMessage = "Device \"${newDevice.name}\" added successfully!" successMessage = "Device \"${newDevice.name}\" added successfully!"
@@ -1,7 +1,9 @@
package com.expapp.trigger.ui.screens package com.expapp.trigger.ui.screens
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -12,18 +14,22 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.PowerOff import androidx.compose.material.icons.filled.PowerOff
import androidx.compose.material.icons.filled.PowerSettingsNew import androidx.compose.material.icons.filled.PowerSettingsNew
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.RestartAlt import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -35,11 +41,13 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.expapp.trigger.data.model.DeviceConfig import com.expapp.trigger.data.model.DeviceConfig
import com.expapp.trigger.network.NodeStatus
import com.expapp.trigger.network.TriggerAction import com.expapp.trigger.network.TriggerAction
import com.expapp.trigger.ui.components.ActionConfirmDialog import com.expapp.trigger.ui.components.ActionConfirmDialog
import com.expapp.trigger.ui.components.HugeActionButton import com.expapp.trigger.ui.components.HugeActionButton
@@ -47,9 +55,19 @@ import com.expapp.trigger.ui.components.StatusBanner
import com.expapp.trigger.ui.theme.DarkCardBorder import com.expapp.trigger.ui.theme.DarkCardBorder
import com.expapp.trigger.ui.theme.DarkSurface import com.expapp.trigger.ui.theme.DarkSurface
import com.expapp.trigger.ui.theme.DarkSurfaceVariant import com.expapp.trigger.ui.theme.DarkSurfaceVariant
import com.expapp.trigger.ui.theme.PowerOffBorder
import com.expapp.trigger.ui.theme.PowerOffGradient
import com.expapp.trigger.ui.theme.PowerOffRed import com.expapp.trigger.ui.theme.PowerOffRed
import com.expapp.trigger.ui.theme.PowerOnGreen import com.expapp.trigger.ui.theme.PowerOnBorder
import com.expapp.trigger.ui.theme.RebootAmber import com.expapp.trigger.ui.theme.PowerOnGradient
import com.expapp.trigger.ui.theme.RebootBorder
import com.expapp.trigger.ui.theme.RebootGradient
import com.expapp.trigger.ui.theme.StatusOfflineBg
import com.expapp.trigger.ui.theme.StatusOfflineBorder
import com.expapp.trigger.ui.theme.StatusOfflineText
import com.expapp.trigger.ui.theme.StatusOnlineBg
import com.expapp.trigger.ui.theme.StatusOnlineBorder
import com.expapp.trigger.ui.theme.StatusOnlineText
import com.expapp.trigger.ui.theme.TextPrimary import com.expapp.trigger.ui.theme.TextPrimary
import com.expapp.trigger.ui.theme.TextSecondary import com.expapp.trigger.ui.theme.TextSecondary
@@ -57,9 +75,12 @@ import com.expapp.trigger.ui.theme.TextSecondary
fun DevicePage( fun DevicePage(
device: DeviceConfig, device: DeviceConfig,
isLoading: Boolean, isLoading: Boolean,
nodeStatus: NodeStatus?,
isCheckingStatus: Boolean,
lastStatus: String?, lastStatus: String?,
lastSuccess: Boolean?, lastSuccess: Boolean?,
onDismissStatus: () -> Unit, onDismissStatus: () -> Unit,
onRefreshStatus: () -> Unit,
onTrigger: (TriggerAction) -> Unit, onTrigger: (TriggerAction) -> Unit,
onDelete: (DeviceConfig) -> Unit, onDelete: (DeviceConfig) -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
@@ -107,66 +128,186 @@ fun DevicePage(
Column( Column(
modifier = modifier modifier = modifier
.fillMaxSize() .fillMaxSize()
.padding(horizontal = 20.dp, vertical = 12.dp), .padding(horizontal = 20.dp, vertical = 10.dp),
verticalArrangement = Arrangement.SpaceBetween verticalArrangement = Arrangement.SpaceBetween
) { ) {
// Device Header Card // Professional Server Info Header Card
Card( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = DarkSurface), colors = CardDefaults.cardColors(containerColor = DarkSurface),
border = CardDefaults.outlinedCardBorder().copy(brush = androidx.compose.ui.graphics.SolidColor(DarkCardBorder)) border = CardDefaults.outlinedCardBorder().copy(brush = androidx.compose.ui.graphics.SolidColor(DarkCardBorder))
) { ) {
Row( Column(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 18.dp, vertical = 14.dp), .padding(horizontal = 18.dp, vertical = 16.dp)
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Column(modifier = Modifier.weight(1f)) { Row(
Text( modifier = Modifier.fillMaxWidth(),
text = device.name, verticalAlignment = Alignment.CenterVertically,
fontSize = 24.sp, horizontalArrangement = Arrangement.SpaceBetween
fontWeight = FontWeight.Bold, ) {
color = TextPrimary Row(
) verticalAlignment = Alignment.CenterVertically,
Spacer(modifier = Modifier.height(4.dp)) modifier = Modifier.weight(1f)
Row(verticalAlignment = Alignment.CenterVertically) { ) {
Box( Box(
modifier = Modifier modifier = Modifier
.background(DarkSurfaceVariant, RoundedCornerShape(8.dp)) .size(44.dp)
.border(1.dp, DarkCardBorder, RoundedCornerShape(8.dp)) .clip(RoundedCornerShape(12.dp))
.padding(horizontal = 8.dp, vertical = 2.dp) .background(DarkSurfaceVariant)
.border(1.dp, DarkCardBorder, RoundedCornerShape(12.dp)),
contentAlignment = Alignment.Center
) { ) {
Icon(
imageVector = Icons.Default.Dns,
contentDescription = null,
tint = if (nodeStatus?.isOnline == true) StatusOnlineText else TextSecondary,
modifier = Modifier.size(24.dp)
)
}
Spacer(modifier = Modifier.width(14.dp))
Column {
Text(
text = device.name,
fontSize = 22.sp,
fontWeight = FontWeight.Bold,
color = TextPrimary,
maxLines = 1
)
Spacer(modifier = Modifier.height(2.dp))
Text( Text(
text = "node: ${device.node}", text = "node: ${device.node}",
fontSize = 12.sp, fontSize = 12.sp,
color = TextSecondary, color = TextSecondary,
fontWeight = FontWeight.SemiBold fontWeight = FontWeight.Medium
) )
} }
} }
IconButton(
onClick = { showDeleteConfirm = true },
modifier = Modifier
.size(36.dp)
.clip(CircleShape)
.background(Color.White.copy(alpha = 0.05f))
) {
Icon(
imageVector = Icons.Default.DeleteOutline,
contentDescription = "Delete device",
tint = Color(0xFFE57373),
modifier = Modifier.size(20.dp)
)
}
} }
IconButton( Spacer(modifier = Modifier.height(14.dp))
onClick = { showDeleteConfirm = true },
modifier = Modifier // Live Server Status Badge & IP Address
.size(42.dp) Row(
.background(Color.White.copy(alpha = 0.05f), CircleShape) modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Icon( Row(verticalAlignment = Alignment.CenterVertically) {
imageVector = Icons.Default.Delete, // Live Status Pill
contentDescription = "Delete device", val isOnline = nodeStatus?.isOnline == true
tint = Color(0xFFE57373) val badgeBg = if (isCheckingStatus) DarkSurfaceVariant else if (isOnline) StatusOnlineBg else StatusOfflineBg
) val badgeBorder = if (isCheckingStatus) DarkCardBorder else if (isOnline) StatusOnlineBorder else StatusOfflineBorder
val badgeText = if (isCheckingStatus) TextSecondary else if (isOnline) StatusOnlineText else StatusOfflineText
Row(
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(badgeBg)
.border(1.dp, badgeBorder, RoundedCornerShape(8.dp))
.clickable { onRefreshStatus() }
.padding(horizontal = 10.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (isCheckingStatus) {
CircularProgressIndicator(
modifier = Modifier.size(10.dp),
strokeWidth = 1.5.dp,
color = TextSecondary
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "PINGING...",
fontSize = 11.sp,
fontWeight = FontWeight.Bold,
color = TextSecondary,
letterSpacing = 0.5.sp
)
} else {
Box(
modifier = Modifier
.size(8.dp)
.clip(CircleShape)
.background(badgeText)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = nodeStatus?.statusText ?: "OFFLINE",
fontSize = 11.sp,
fontWeight = FontWeight.ExtraBold,
color = badgeText,
letterSpacing = 0.5.sp
)
}
}
// IP Address chip if returned
if (!nodeStatus?.ip.isNullOrBlank()) {
Spacer(modifier = Modifier.width(8.dp))
Box(
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(DarkSurfaceVariant)
.border(1.dp, DarkCardBorder, RoundedCornerShape(8.dp))
.padding(horizontal = 8.dp, vertical = 5.dp)
) {
Text(
text = nodeStatus!!.ip!!,
fontSize = 11.sp,
fontWeight = FontWeight.SemiBold,
color = TextSecondary
)
}
}
}
// Tap to re-check indicator
Row(
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.clickable { onRefreshStatus() }
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = "Check Status",
tint = TextSecondary,
modifier = Modifier.size(14.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "check",
fontSize = 11.sp,
color = TextSecondary
)
}
} }
} }
} }
Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(10.dp))
// Status Banner if any // Status Banner for Action Result
StatusBanner( StatusBanner(
status = lastStatus, status = lastStatus,
isSuccess = lastSuccess, isSuccess = lastSuccess,
@@ -175,7 +316,7 @@ fun DevicePage(
Spacer(modifier = Modifier.height(12.dp)) Spacer(modifier = Modifier.height(12.dp))
// 3 Massive Action Buttons // 3 Massive Tactile Action Buttons
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -184,8 +325,9 @@ fun DevicePage(
) { ) {
HugeActionButton( HugeActionButton(
text = "POWER ON", text = "POWER ON",
subtext = "Wake / Turn on remote system", subtext = "Wake / Start Remote Machine",
containerColor = PowerOnGreen, gradientColors = PowerOnGradient,
borderColor = PowerOnBorder,
icon = Icons.Default.PowerSettingsNew, icon = Icons.Default.PowerSettingsNew,
isLoading = isLoading && pendingAction == null, isLoading = isLoading && pendingAction == null,
onClick = { onTrigger(TriggerAction.POWER_ON) } onClick = { onTrigger(TriggerAction.POWER_ON) }
@@ -193,8 +335,9 @@ fun DevicePage(
HugeActionButton( HugeActionButton(
text = "REBOOT", text = "REBOOT",
subtext = "Graceful restart (Key authenticated)", subtext = "Graceful Restart (Auth Required)",
containerColor = RebootAmber, gradientColors = RebootGradient,
borderColor = RebootBorder,
icon = Icons.Default.RestartAlt, icon = Icons.Default.RestartAlt,
isLoading = isLoading && pendingAction == null, isLoading = isLoading && pendingAction == null,
onClick = { pendingAction = TriggerAction.REBOOT } onClick = { pendingAction = TriggerAction.REBOOT }
@@ -202,8 +345,9 @@ fun DevicePage(
HugeActionButton( HugeActionButton(
text = "POWER OFF", text = "POWER OFF",
subtext = "Shut down machine (Key authenticated)", subtext = "Remote Shutdown (Auth Required)",
containerColor = PowerOffRed, gradientColors = PowerOffGradient,
borderColor = PowerOffBorder,
icon = Icons.Default.PowerOff, icon = Icons.Default.PowerOff,
isLoading = isLoading && pendingAction == null, isLoading = isLoading && pendingAction == null,
onClick = { pendingAction = TriggerAction.POWER_OFF } onClick = { pendingAction = TriggerAction.POWER_OFF }
@@ -3,6 +3,7 @@ package com.expapp.trigger.ui.screens
import android.widget.Toast import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -30,6 +31,7 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@@ -46,13 +48,21 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.expapp.trigger.data.model.DeviceConfig import com.expapp.trigger.data.model.DeviceConfig
import com.expapp.trigger.data.repository.DeviceRepository import com.expapp.trigger.data.repository.DeviceRepository
import com.expapp.trigger.network.NodeStatus
import com.expapp.trigger.network.TriggerAction import com.expapp.trigger.network.TriggerAction
import com.expapp.trigger.network.TriggerClient import com.expapp.trigger.network.TriggerClient
import com.expapp.trigger.ui.theme.DarkBackground import com.expapp.trigger.ui.theme.DarkBackground
import com.expapp.trigger.ui.theme.DarkCardBorder
import com.expapp.trigger.ui.theme.DarkSurface import com.expapp.trigger.ui.theme.DarkSurface
import com.expapp.trigger.ui.theme.DarkSurfaceVariant
import com.expapp.trigger.ui.theme.PowerOnBorder
import com.expapp.trigger.ui.theme.PowerOnGreen import com.expapp.trigger.ui.theme.PowerOnGreen
import com.expapp.trigger.ui.theme.StatusOnlineBg
import com.expapp.trigger.ui.theme.StatusOnlineBorder
import com.expapp.trigger.ui.theme.StatusOnlineText
import com.expapp.trigger.ui.theme.TextPrimary import com.expapp.trigger.ui.theme.TextPrimary
import com.expapp.trigger.ui.theme.TextSecondary import com.expapp.trigger.ui.theme.TextSecondary
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@@ -72,8 +82,21 @@ fun MainScreen(
val loadingStates = remember { mutableStateMapOf<String, Boolean>() } val loadingStates = remember { mutableStateMapOf<String, Boolean>() }
// Device ID -> Pair(StatusMessage, IsSuccess) // Device ID -> Pair(StatusMessage, IsSuccess)
val statusStates = remember { mutableStateMapOf<String, Pair<String, Boolean>>() } val statusStates = remember { mutableStateMapOf<String, Pair<String, Boolean>>() }
// Device ID -> Live NodeStatus (online / offline / ip)
val nodeStatuses = remember { mutableStateMapOf<String, NodeStatus>() }
// Device ID -> Is Checking Status
val checkingStatusMap = remember { mutableStateMapOf<String, Boolean>() }
var isSyncing by remember { mutableStateOf(false) } var isSyncing by remember { mutableStateOf(false) }
fun refreshDeviceStatus(device: DeviceConfig) {
checkingStatusMap[device.id] = true
triggerClient.checkStatus(device) { status ->
checkingStatusMap[device.id] = false
nodeStatuses[device.id] = status
}
}
fun syncEndpoints(showToast: Boolean = false) { fun syncEndpoints(showToast: Boolean = false) {
val currentDevices = repository.getDevices() val currentDevices = repository.getDevices()
if (currentDevices.isEmpty()) return if (currentDevices.isEmpty()) return
@@ -84,10 +107,15 @@ fun MainScreen(
if (totalToSync == 0) { if (totalToSync == 0) {
isSyncing = false isSyncing = false
// Still check ping/status for all devices
currentDevices.forEach { refreshDeviceStatus(it) }
return return
} }
currentDevices.forEach { device -> currentDevices.forEach { device ->
// Trigger status check simultaneously
refreshDeviceStatus(device)
if (device.r2Url.isNotBlank()) { if (device.r2Url.isNotBlank()) {
triggerClient.fetchR2Config(device.r2Url) { result -> triggerClient.fetchR2Config(device.r2Url) { result ->
completedCount++ completedCount++
@@ -96,7 +124,8 @@ fun MainScreen(
deviceId = device.id, deviceId = device.id,
powerOnUrl = endpoints.powerOn, powerOnUrl = endpoints.powerOn,
powerOffUrl = endpoints.powerOff, powerOffUrl = endpoints.powerOff,
rebootUrl = endpoints.reboot rebootUrl = endpoints.reboot,
statusUrl = endpoints.status
) )
if (changed) { if (changed) {
updatedCount++ updatedCount++
@@ -121,9 +150,18 @@ fun MainScreen(
} }
} }
// Automatically check Cloudflare R2 on every app launch // Automatically check Cloudflare R2 and device status on every app launch
androidx.compose.runtime.LaunchedEffect(Unit) { LaunchedEffect(Unit) {
syncEndpoints(showToast = false) syncEndpoints(showToast = false)
devices.forEach { refreshDeviceStatus(it) }
}
// Auto-refresh status when swiping to a device
LaunchedEffect(pagerState.currentPage) {
val page = pagerState.currentPage
if (page < devices.size) {
refreshDeviceStatus(devices[page])
}
} }
fun executeAction(device: DeviceConfig, action: TriggerAction) { fun executeAction(device: DeviceConfig, action: TriggerAction) {
@@ -150,6 +188,12 @@ fun MainScreen(
if (response.isSuccess) "$actionLabel successful (${response.statusCode})" else "Failed: ${response.message}", if (response.isSuccess) "$actionLabel successful (${response.statusCode})" else "Failed: ${response.message}",
Toast.LENGTH_SHORT Toast.LENGTH_SHORT
).show() ).show()
// Re-check live status after action
coroutineScope.launch {
delay(2000)
refreshDeviceStatus(device)
}
} }
} }
@@ -160,19 +204,49 @@ fun MainScreen(
CenterAlignedTopAppBar( CenterAlignedTopAppBar(
title = { title = {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Icon( Box(
imageVector = Icons.Default.Dns, modifier = Modifier
contentDescription = null, .size(34.dp)
tint = PowerOnGreen, .clip(RoundedCornerShape(10.dp))
modifier = Modifier.size(24.dp) .background(DarkSurfaceVariant)
) .border(1.dp, DarkCardBorder, RoundedCornerShape(10.dp)),
Spacer(modifier = Modifier.width(8.dp)) contentAlignment = Alignment.Center
) {
Icon(
imageVector = Icons.Default.Dns,
contentDescription = null,
tint = PowerOnBorder,
modifier = Modifier.size(20.dp)
)
}
Spacer(modifier = Modifier.width(10.dp))
Text( Text(
text = "Device Trigger", text = "DEVICE TRIGGER",
fontSize = 20.sp, fontSize = 17.sp,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.ExtraBold,
letterSpacing = 1.sp,
color = TextPrimary color = TextPrimary
) )
// Online counter badge if devices exist
val onlineCount = devices.count { nodeStatuses[it.id]?.isOnline == true }
if (devices.isNotEmpty()) {
Spacer(modifier = Modifier.width(10.dp))
Box(
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.background(if (onlineCount > 0) StatusOnlineBg else DarkSurfaceVariant)
.border(1.dp, if (onlineCount > 0) StatusOnlineBorder else DarkCardBorder, RoundedCornerShape(12.dp))
.padding(horizontal = 7.dp, vertical = 2.dp)
) {
Text(
text = "$onlineCount online",
fontSize = 11.sp,
fontWeight = FontWeight.Bold,
color = if (onlineCount > 0) StatusOnlineText else TextSecondary
)
}
}
} }
}, },
actions = { actions = {
@@ -184,7 +258,7 @@ fun MainScreen(
Icon( Icon(
imageVector = Icons.Default.Refresh, imageVector = Icons.Default.Refresh,
contentDescription = "Sync Endpoints", contentDescription = "Sync Endpoints",
tint = if (isSyncing) TextSecondary.copy(alpha = 0.5f) else PowerOnGreen tint = if (isSyncing) TextSecondary.copy(alpha = 0.5f) else PowerOnBorder
) )
} }
@@ -199,7 +273,7 @@ fun MainScreen(
Icon( Icon(
imageVector = Icons.Default.Add, imageVector = Icons.Default.Add,
contentDescription = "Add Device", contentDescription = "Add Device",
tint = PowerOnGreen tint = PowerOnBorder
) )
} }
}, },
@@ -227,13 +301,13 @@ fun MainScreen(
modifier = Modifier modifier = Modifier
.padding(horizontal = 4.dp) .padding(horizontal = 4.dp)
.height(8.dp) .height(8.dp)
.width(if (isSelected) 22.dp else 8.dp) .width(if (isSelected) 24.dp else 8.dp)
.clip(if (isSelected) RoundedCornerShape(4.dp) else CircleShape) .clip(if (isSelected) RoundedCornerShape(4.dp) else CircleShape)
.background( .background(
when { when {
isSelected -> PowerOnGreen isSelected -> PowerOnBorder
isAddPage -> TextSecondary.copy(alpha = 0.5f) isAddPage -> TextSecondary.copy(alpha = 0.5f)
else -> TextSecondary.copy(alpha = 0.3f) else -> TextSecondary.copy(alpha = 0.25f)
} }
) )
) )
@@ -256,9 +330,12 @@ fun MainScreen(
DevicePage( DevicePage(
device = currentDevice, device = currentDevice,
isLoading = isLoading, isLoading = isLoading,
nodeStatus = nodeStatuses[currentDevice.id],
isCheckingStatus = checkingStatusMap[currentDevice.id] == true,
lastStatus = statusInfo?.first, lastStatus = statusInfo?.first,
lastSuccess = statusInfo?.second, lastSuccess = statusInfo?.second,
onDismissStatus = { statusStates.remove(currentDevice.id) }, onDismissStatus = { statusStates.remove(currentDevice.id) },
onRefreshStatus = { refreshDeviceStatus(currentDevice) },
onTrigger = { action -> executeAction(currentDevice, action) }, onTrigger = { action -> executeAction(currentDevice, action) },
onDelete = { dev -> onDelete = { dev ->
repository.deleteDevice(dev.id) repository.deleteDevice(dev.id)
@@ -271,6 +348,7 @@ fun MainScreen(
onDeviceAdded = { newDevice -> onDeviceAdded = { newDevice ->
repository.addDevice(newDevice) repository.addDevice(newDevice)
devices = repository.getDevices() devices = repository.getDevices()
refreshDeviceStatus(newDevice)
coroutineScope.launch { coroutineScope.launch {
val newPageIndex = devices.indexOfFirst { it.id == newDevice.id } val newPageIndex = devices.indexOfFirst { it.id == newDevice.id }
if (newPageIndex >= 0) { if (newPageIndex >= 0) {
@@ -2,6 +2,15 @@ package com.expapp.trigger.ui.theme
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
val PowerOnGradient = listOf(Color(0xFF1B6A32), Color(0xFF0E431E))
val PowerOnBorder = Color(0xFF38A169)
val RebootGradient = listOf(Color(0xFFC05621), Color(0xFF7B341E))
val RebootBorder = Color(0xFFDD6B20)
val PowerOffGradient = listOf(Color(0xFFC53030), Color(0xFF742A2A))
val PowerOffBorder = Color(0xFFE53E3E)
val PowerOnGreen = Color(0xFF2E7D32) val PowerOnGreen = Color(0xFF2E7D32)
val PowerOnGreenLight = Color(0xFF4CAF50) val PowerOnGreenLight = Color(0xFF4CAF50)
val RebootAmber = Color(0xFFEF6C00) val RebootAmber = Color(0xFFEF6C00)
@@ -9,9 +18,17 @@ val RebootAmberLight = Color(0xFFFF9800)
val PowerOffRed = Color(0xFFC62828) val PowerOffRed = Color(0xFFC62828)
val PowerOffRedLight = Color(0xFFE53935) val PowerOffRedLight = Color(0xFFE53935)
val DarkBackground = Color(0xFF121212) val DarkBackground = Color(0xFF0D0F14)
val DarkSurface = Color(0xFF1E1E1E) val DarkSurface = Color(0xFF161A22)
val DarkSurfaceVariant = Color(0xFF2A2A2A) val DarkSurfaceVariant = Color(0xFF1F2430)
val DarkCardBorder = Color(0xFF383838) val DarkCardBorder = Color(0xFF2B3242)
val TextPrimary = Color(0xFFFFFFFF) val TextPrimary = Color(0xFFF7FAFC)
val TextSecondary = Color(0xFFB0B0B0) val TextSecondary = Color(0xFFA0AEC0)
val StatusOnlineBg = Color(0xFF0B2618)
val StatusOnlineBorder = Color(0xFF1C4532)
val StatusOnlineText = Color(0xFF48BB78)
val StatusOfflineBg = Color(0xFF2D1214)
val StatusOfflineBorder = Color(0xFF63171B)
val StatusOfflineText = Color(0xFFF56565)
@@ -12,7 +12,8 @@ class R2ConfigParserTest {
{ {
"poweron": "https://cosmos.linuxguy.space/poweron", "poweron": "https://cosmos.linuxguy.space/poweron",
"poweroff": "https://cosmos.linuxguy.space/poweroff", "poweroff": "https://cosmos.linuxguy.space/poweroff",
"reboot": "https://cosmos.linuxguy.space/reboot" "reboot": "https://cosmos.linuxguy.space/reboot",
"status": "https://cosmos.linuxguy.space/status"
} }
""".trimIndent() """.trimIndent()
@@ -22,6 +23,7 @@ class R2ConfigParserTest {
assertEquals("https://cosmos.linuxguy.space/poweron", endpoints.powerOn) assertEquals("https://cosmos.linuxguy.space/poweron", endpoints.powerOn)
assertEquals("https://cosmos.linuxguy.space/poweroff", endpoints.powerOff) assertEquals("https://cosmos.linuxguy.space/poweroff", endpoints.powerOff)
assertEquals("https://cosmos.linuxguy.space/reboot", endpoints.reboot) assertEquals("https://cosmos.linuxguy.space/reboot", endpoints.reboot)
assertEquals("https://cosmos.linuxguy.space/status", endpoints.status)
} }
@Test @Test
@@ -133,4 +133,57 @@ class TriggerClientTest {
val result = fetchResult!! val result = fetchResult!!
assertTrue(result.isSuccess) assertTrue(result.isSuccess)
} }
@Test
fun checkStatus_withJsonResponse_parsesOnlineAndIp() {
server.enqueue(
MockResponse()
.setResponseCode(200)
.setBody("""{"node":"debian","online":true,"status":"online","ip":"100.85.63.44"}""")
)
val localDevice = sampleDevice.copy(
statusUrl = server.url("/status").toString()
)
val latch = CountDownLatch(1)
var statusResult: NodeStatus? = null
client.checkStatus(localDevice) { status ->
statusResult = status
latch.countDown()
}
assertTrue(latch.await(3, TimeUnit.SECONDS))
val status = statusResult!!
assertTrue(status.isOnline)
assertEquals("ONLINE", status.statusText)
assertEquals("100.85.63.44", status.ip)
}
@Test
fun checkStatus_withPlainText_parsesOnline() {
server.enqueue(
MockResponse()
.setResponseCode(200)
.setBody("ONLINE")
)
val localDevice = sampleDevice.copy(
statusUrl = server.url("/ping").toString()
)
val latch = CountDownLatch(1)
var statusResult: NodeStatus? = null
client.checkStatus(localDevice) { status ->
statusResult = status
latch.countDown()
}
assertTrue(latch.await(3, TimeUnit.SECONDS))
val status = statusResult!!
assertTrue(status.isOnline)
assertEquals("ONLINE", status.statusText)
}
} }