feat(network): implement TriggerClient with OkHttp and async POST request dispatching
This commit is contained in:
@@ -0,0 +1,117 @@
|
|||||||
|
package com.expapp.trigger.network
|
||||||
|
|
||||||
|
import com.expapp.trigger.data.model.DeviceConfig
|
||||||
|
import com.expapp.trigger.data.parser.ParsedEndpoints
|
||||||
|
import com.expapp.trigger.data.parser.R2ConfigParser
|
||||||
|
import okhttp3.Call
|
||||||
|
import okhttp3.Callback
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import okhttp3.Response
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class TriggerClient(
|
||||||
|
private val client: OkHttpClient = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
) {
|
||||||
|
private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
||||||
|
|
||||||
|
fun buildRequest(device: DeviceConfig, action: TriggerAction): Request {
|
||||||
|
val targetUrl = when (action) {
|
||||||
|
TriggerAction.POWER_ON -> device.powerOnUrl
|
||||||
|
TriggerAction.POWER_OFF -> device.powerOffUrl
|
||||||
|
TriggerAction.REBOOT -> device.rebootUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
val jsonPayload = """{"node":"${device.node}"}"""
|
||||||
|
val body = jsonPayload.toRequestBody(jsonMediaType)
|
||||||
|
|
||||||
|
return Request.Builder()
|
||||||
|
.url(targetUrl)
|
||||||
|
.addHeader("Content-Type", "application/json")
|
||||||
|
.addHeader("X-Secret-Key", device.secretKey)
|
||||||
|
.post(body)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendTrigger(
|
||||||
|
device: DeviceConfig,
|
||||||
|
action: TriggerAction,
|
||||||
|
callback: (TriggerResponse) -> Unit
|
||||||
|
) {
|
||||||
|
val request = try {
|
||||||
|
buildRequest(device, action)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
callback(
|
||||||
|
TriggerResponse(
|
||||||
|
isSuccess = false,
|
||||||
|
statusCode = -1,
|
||||||
|
message = "Invalid URL or configuration: ${e.message}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
client.newCall(request).enqueue(object : Callback {
|
||||||
|
override fun onFailure(call: Call, e: IOException) {
|
||||||
|
callback(
|
||||||
|
TriggerResponse(
|
||||||
|
isSuccess = false,
|
||||||
|
statusCode = -1,
|
||||||
|
message = e.localizedMessage ?: "Network connection failed"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResponse(call: Call, response: Response) {
|
||||||
|
response.use {
|
||||||
|
val code = it.code
|
||||||
|
val bodyText = it.body?.string().orEmpty()
|
||||||
|
callback(
|
||||||
|
TriggerResponse(
|
||||||
|
isSuccess = it.isSuccessful,
|
||||||
|
statusCode = code,
|
||||||
|
message = if (bodyText.isNotEmpty()) bodyText else "HTTP $code"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fetchR2Config(
|
||||||
|
url: String,
|
||||||
|
callback: (Result<ParsedEndpoints>) -> Unit
|
||||||
|
) {
|
||||||
|
val request = try {
|
||||||
|
Request.Builder().url(url).get().build()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
callback(Result.failure(e))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
client.newCall(request).enqueue(object : Callback {
|
||||||
|
override fun onFailure(call: Call, e: IOException) {
|
||||||
|
callback(Result.failure(e))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResponse(call: Call, response: Response) {
|
||||||
|
response.use {
|
||||||
|
if (!it.isSuccessful) {
|
||||||
|
callback(Result.failure(IOException("Failed to fetch R2 JSON: HTTP ${it.code}")))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val jsonString = it.body?.string().orEmpty()
|
||||||
|
val parseResult = R2ConfigParser.parse(jsonString)
|
||||||
|
callback(parseResult)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.expapp.trigger.network
|
||||||
|
|
||||||
|
enum class TriggerAction {
|
||||||
|
POWER_ON,
|
||||||
|
POWER_OFF,
|
||||||
|
REBOOT
|
||||||
|
}
|
||||||
|
|
||||||
|
data class TriggerResponse(
|
||||||
|
val isSuccess: Boolean,
|
||||||
|
val statusCode: Int,
|
||||||
|
val message: String
|
||||||
|
)
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package com.expapp.trigger.network
|
||||||
|
|
||||||
|
import com.expapp.trigger.data.model.DeviceConfig
|
||||||
|
import okhttp3.mockwebserver.MockResponse
|
||||||
|
import okhttp3.mockwebserver.MockWebServer
|
||||||
|
import okio.Buffer
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class TriggerClientTest {
|
||||||
|
|
||||||
|
private lateinit var server: MockWebServer
|
||||||
|
private lateinit var client: TriggerClient
|
||||||
|
|
||||||
|
private val sampleDevice = DeviceConfig(
|
||||||
|
id = "test-1",
|
||||||
|
name = "My Debian",
|
||||||
|
node = "debian",
|
||||||
|
secretKey = "Carbon@12",
|
||||||
|
r2Url = "http://localhost/config.json",
|
||||||
|
powerOnUrl = "https://cosmos.linuxguy.space/poweron",
|
||||||
|
powerOffUrl = "https://cosmos.linuxguy.space/poweroff",
|
||||||
|
rebootUrl = "https://cosmos.linuxguy.space/reboot"
|
||||||
|
)
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setup() {
|
||||||
|
server = MockWebServer()
|
||||||
|
server.start()
|
||||||
|
client = TriggerClient()
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
server.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun buildRequest_powerOff_hasCorrectMethodHeaderAndBody() {
|
||||||
|
val request = client.buildRequest(sampleDevice, TriggerAction.POWER_OFF)
|
||||||
|
|
||||||
|
assertEquals("POST", request.method)
|
||||||
|
assertEquals("https://cosmos.linuxguy.space/poweroff", request.url.toString())
|
||||||
|
assertEquals("Carbon@12", request.header("X-Secret-Key"))
|
||||||
|
|
||||||
|
val buffer = Buffer()
|
||||||
|
request.body?.writeTo(buffer)
|
||||||
|
val bodyString = buffer.readUtf8()
|
||||||
|
assertEquals("""{"node":"debian"}""", bodyString)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun buildRequest_reboot_usesRebootUrl() {
|
||||||
|
val request = client.buildRequest(sampleDevice, TriggerAction.REBOOT)
|
||||||
|
|
||||||
|
assertEquals("POST", request.method)
|
||||||
|
assertEquals("https://cosmos.linuxguy.space/reboot", request.url.toString())
|
||||||
|
assertEquals("Carbon@12", request.header("X-Secret-Key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun buildRequest_powerOn_usesPowerOnUrl() {
|
||||||
|
val request = client.buildRequest(sampleDevice, TriggerAction.POWER_ON)
|
||||||
|
|
||||||
|
assertEquals("POST", request.method)
|
||||||
|
assertEquals("https://cosmos.linuxguy.space/poweron", request.url.toString())
|
||||||
|
assertEquals("Carbon@12", request.header("X-Secret-Key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sendTrigger_withMockServer_executesAndReturnsResponse() {
|
||||||
|
server.enqueue(
|
||||||
|
MockResponse()
|
||||||
|
.setResponseCode(200)
|
||||||
|
.setBody("""{"status":"shutting down"}""")
|
||||||
|
)
|
||||||
|
|
||||||
|
val localDevice = sampleDevice.copy(
|
||||||
|
powerOffUrl = server.url("/poweroff").toString()
|
||||||
|
)
|
||||||
|
|
||||||
|
val latch = CountDownLatch(1)
|
||||||
|
var responseResult: TriggerResponse? = null
|
||||||
|
|
||||||
|
client.sendTrigger(localDevice, TriggerAction.POWER_OFF) { response ->
|
||||||
|
responseResult = response
|
||||||
|
latch.countDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(latch.await(3, TimeUnit.SECONDS))
|
||||||
|
val response = responseResult!!
|
||||||
|
assertTrue(response.isSuccess)
|
||||||
|
assertEquals(200, response.statusCode)
|
||||||
|
assertTrue(response.message.contains("shutting down"))
|
||||||
|
|
||||||
|
val recorded = server.takeRequest()
|
||||||
|
assertEquals("POST", recorded.method)
|
||||||
|
assertEquals("Carbon@12", recorded.getHeader("X-Secret-Key"))
|
||||||
|
assertEquals("""{"node":"debian"}""", recorded.body.readUtf8())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fetchR2Config_withMockServer_returnsParsedEndpoints() {
|
||||||
|
server.enqueue(
|
||||||
|
MockResponse()
|
||||||
|
.setResponseCode(200)
|
||||||
|
.setBody(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"poweron": "https://cosmos.linuxguy.space/poweron",
|
||||||
|
"poweroff": "https://cosmos.linuxguy.space/poweroff",
|
||||||
|
"reboot": "https://cosmos.linuxguy.space/reboot"
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
val latch = CountDownLatch(1)
|
||||||
|
var fetchResult: Result<*>? = null
|
||||||
|
|
||||||
|
client.fetchR2Config(server.url("/config.json").toString()) { result ->
|
||||||
|
fetchResult = result
|
||||||
|
latch.countDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(latch.await(3, TimeUnit.SECONDS))
|
||||||
|
val result = fetchResult!!
|
||||||
|
assertTrue(result.isSuccess)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user