Updater can now talk to the SlimeVR api (still very much wip)

This commit is contained in:
HannahPadd committed 2026-05-11 18:53:34 +02:00
1 parent 06c3259d38
commit 2fa949d156
7 files changed
+169 -62

No files matched your search

@@ -5,12 +5,15 @@ import com.google.flatbuffers.FlatBufferBuilder
import dev.slimevr.protocol.GenericConnection
import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.rpc.RPCHandler
import io.eiren.util.logging.LogManager
import solarxr_protocol.rpc.RpcMessage
import solarxr_protocol.rpc.RpcMessageHeader
import solarxr_protocol.rpc.UpdaterChannel
import solarxr_protocol.rpc.UpdaterVersion
import solarxr_protocol.rpc.UpdatesResponse
import solarxr_protocol.rpc.UpdatesResponse.createUpdatesResponse
import java.io.File
import java.net.URL
class RPCUpdaterHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
init {
@@ -19,6 +22,13 @@ class RPCUpdaterHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
// TODO Make finding manifest more robust
fun onGetVersionsListRequest(conn: GenericConnection, messageHeader: RpcMessageHeader?) {
try {
val jsonText = URL("http://localhost:3000/manifest").readText()
val file = File("update-manifest.json")
file.writeText(jsonText)
} catch (e: Error) {
LogManager.warning("Error in downloading manifest: $e")
}
val manifest = Manifest("update-manifest.json").getManifest()
val fbb = FlatBufferBuilder(1024)
@@ -145,6 +145,10 @@ class Linux(
subText = ""
}
TerminalUtil.success("Updating server done")
val command = listOf("chmod", "+x", LINUXSERVERNAME)
//TerminalUtil.info(io.executeShellCommand("chmod +x ${LINUXSERVERNAME}"))
}
// Legacy
@@ -0,0 +1,36 @@
package dev.slimevr.updater
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Release(
val run: List<String>,
val platform: String,
val architecture: String,
val url: String,
val checksum: String,
val version: String
)
@Serializable
data class Versions(
@SerialName("release_notes")
val releaseNotes: String,
val builds: Map<String, Map<String, Release>>,
)
@Serializable
data class Channel(
val description: String,
@SerialName("current_version")
val currentVersion: String,
val versions: Map<String, Versions>,
)
@Serializable
data class ManifestObject(
@SerialName("default_channel")
val defaultChannel: String,
val channels: Map<String, Channel>,
)
@@ -15,6 +15,7 @@ import kotlin.io.path.pathString
import kotlin.system.exitProcess
const val SLIMEVR_IDENTIFIER = "dev.slimevr.SlimeVR"
val os = OperatingSystem
class Updater(
val state: UpdaterState,
@@ -22,10 +23,10 @@ class Updater(
) {
suspend fun runUpdater() {
val vrConfig = resolveConfig("vrconfig.yml")
val configDir = resolveConfigDirectory(SLIMEVR_IDENTIFIER)?.toAbsolutePath().toString()
val configDir =
resolveConfigDirectory(SLIMEVR_IDENTIFIER)?.toAbsolutePath().toString()
//LogManager.info("Using config dir: $configDir")
val manifest = Manifest(manifestPath).getManifest()
val os = OperatingSystem
val arch = System.getProperty("os.arch").lowercase()
val normalizedArch = when {
arch.contains("amd64") || arch.contains("x86_64") -> "x86_64"
@@ -57,24 +58,42 @@ class Updater(
return
}
val selectedVersion = getRelease(manifest, "stable", versionTag, os.currentPlatform.descriptor, normalizedArch)
val releases = updaterIO.getReleaseFromApi()
val selectedVersion = releases.find { it.platform == os.currentPlatform.name.lowercase() }
TerminalUtil.info(selectedVersion.toString())
if (selectedVersion == null) {
state.hasError = true
state.errorText = "Could not get selected version"
return
}
state.versionTag = versionTag
state.versionTag = selectedVersion.version
when (os.currentPlatform) {
OperatingSystem.WINDOWS -> {
val windows = Windows(state, updaterIO)
windows.updateWindows(currentVersionTag, versionTag, configDir, vrConfig, selectedVersion.url, "https://github.com/SlimeVR/SlimeVR-OpenVR-Driver/releases/latest/download/slimevr-openvr-driver-win64.zip")
windows.updateWindows(
currentVersionTag,
versionTag,
configDir,
vrConfig,
selectedVersion.url,
"https://github.com/SlimeVR/SlimeVR-OpenVR-Driver/releases/latest/download/slimevr-openvr-driver-win64.zip"
)
}
OperatingSystem.LINUX -> {
val linux = Linux(state, updaterIO)
linux.updateLinux(currentVersionTag, versionTag, configDir, vrConfig, selectedVersion.url, "https://github.com/SlimeVR/SlimeVR-OpenVR-Driver/releases/latest/download/slimevr-openvr-driver-x64-linux.zip")
linux.updateLinux(
currentVersionTag,
versionTag,
configDir,
vrConfig,
selectedVersion.url,
"https://github.com/SlimeVR/SlimeVR-OpenVR-Driver/releases/latest/download/slimevr-openvr-driver-x64-linux.zip"
)
}
OperatingSystem.OSX -> {
@@ -92,44 +111,12 @@ class Updater(
saveCurrentVersionTag()
Thread.sleep(500)
if (featureFlags.restartServer) {
when (os.currentPlatform) {
OperatingSystem.WINDOWS -> {
val exeFile = File("SlimeVR.exe").absoluteFile
if (exeFile.exists()) {
launchDetached(listOf(exeFile.absolutePath))
} else {
TerminalUtil.error("SlimeVR.exe not found at ${exeFile.absolutePath}")
}
}
OperatingSystem.LINUX -> {
launchDetached(listOf("./SlimeVR-amd64.appimage"))
}
else -> {
TerminalUtil.error("Unknown operating system")
return
}
}
launchServer()
}
exitProcess(0)
}
}
fun launchDetached(command: List<String>) {
val processBuilder = ProcessBuilder(command)
processBuilder.redirectOutput(ProcessBuilder.Redirect.DISCARD)
processBuilder.redirectError(ProcessBuilder.Redirect.DISCARD)
try {
processBuilder.start()
println("Process started successfully. Closing parent...")
} catch (e: Exception) {
e.printStackTrace()
}
}
fun resolveConfigDirectory(identifier: String): Path? = when (currentPlatform) {
OperatingSystem.LINUX -> System.getenv("XDG_CONFIG_HOME")?.let { Path(it, identifier) }
@@ -171,5 +158,8 @@ class Updater(
companion object {
val CDN = "http://127.0.0.1:8080"
fun launchServer() {
}
}
}
@@ -10,6 +10,8 @@ import androidx.compose.ui.window.application
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import kotlin.system.exitProcess
class UpdaterController {
@@ -24,7 +26,7 @@ class UpdaterController {
transparent = true,
state = WindowState(width = 400.dp, height = 450.dp, position = WindowPosition(Alignment.Center)),
) {
UpdaterScreen(state, updaterIO)
UpdaterScreen(state, updaterIO, { launchServer() })
scope.launch {
runUpdate()
}
@@ -46,4 +48,41 @@ class UpdaterController {
private suspend fun runHeadless() {
}
fun launchServer() {
TerminalUtil.info("Attempting to launch SlimeVR server")
when (os.currentPlatform) {
OperatingSystem.WINDOWS -> {
val exeFile = File("SlimeVR.exe").absoluteFile
if (exeFile.exists()) {
launchDetached(listOf(exeFile.absolutePath))
} else {
TerminalUtil.error("SlimeVR.exe not found at ${exeFile.absolutePath}")
}
}
OperatingSystem.LINUX -> {
launchDetached(listOf("./SlimeVR-amd64.appimage"))
}
else -> {
TerminalUtil.error("Unknown operating system")
return
}
}
exitProcess(0)
}
fun launchDetached(command: List<String>) {
val processBuilder = ProcessBuilder(command)
processBuilder.redirectOutput(ProcessBuilder.Redirect.DISCARD)
processBuilder.redirectError(ProcessBuilder.Redirect.DISCARD)
try {
processBuilder.start()
println("Process started successfully. Closing parent...")
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@@ -77,7 +77,7 @@ val BaseTextStyle = TextStyle(
)
@Composable
fun WindowScope.UpdaterScreen(state: UpdaterState, updaterIO: UpdaterIO) {
fun WindowScope.UpdaterScreen(state: UpdaterState, updaterIO: UpdaterIO, startServer: () -> Unit) {
WindowDraggableArea {
Column(
modifier = Modifier
@@ -163,7 +163,7 @@ fun WindowScope.UpdaterScreen(state: UpdaterState, updaterIO: UpdaterIO) {
animationSpec = tween(durationMillis = 200)
)
Button(
onClick = { /* ... */ },
onClick = { startServer() },
shape = RoundedCornerShape(6.dp),
interactionSource = secInteractionSource,
colors = ButtonDefaults.buttonColors(backgroundColor = animatedSecColor),
@@ -1,11 +1,21 @@
package dev.slimevr.updater
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.onDownload
import io.ktor.client.plugins.timeout
import io.ktor.client.request.get
import io.ktor.client.request.prepareGet
import io.ktor.client.request.request
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.ContentType.Application.Json
import io.ktor.http.HttpMethod
import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.jvm.javaio.copyTo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
@@ -14,6 +24,7 @@ import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.io.IOException
import kotlinx.serialization.json.Json
import java.io.File
import java.io.FileOutputStream
import java.math.BigInteger
@@ -43,32 +54,49 @@ class UpdaterIO(
"Error executing shell command: ${e.message}"
}
fun downloadFile(fileUrl: String, fileName: String, checksum: String = "") {
suspend fun getReleaseFromApi(): List<Release> {
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
}
val releases: List<Release> = client.get("http://localhost:3000/releases").body()
return releases
}
suspend fun downloadFile(fileUrl: String, fileName: String, checksum: String = "") {
state.subProgress = 0f
val targetFile = File(fileName)
try {
runBlocking {
FileOutputStream(targetFile).use { outputStream ->
client.prepareGet(fileUrl) {
val timeoutVal = 30.seconds.inWholeMilliseconds
timeout {
requestTimeoutMillis = timeoutVal
connectTimeoutMillis = timeoutVal
socketTimeoutMillis = timeoutVal
}
client.prepareGet(fileUrl) {
val timeoutVal = 30.seconds.inWholeMilliseconds
timeout {
requestTimeoutMillis = timeoutVal
connectTimeoutMillis = timeoutVal
socketTimeoutMillis = timeoutVal
}
onDownload { sent, total ->
val progress = sent.toFloat() / (total?.toFloat() ?: 1f)
state.subProgress = progress
}
}.execute { response ->
if (response.status.value in 200..299) {
response.bodyAsChannel().copyTo(outputStream)
} else {
throw IOException("Server returned HTTP ${response.status.value}")
}
onDownload { sent, total ->
val totalBytes = total ?: 1L
val progress = sent.toFloat() / (totalBytes.toFloat())
state.subProgress = progress
}
}.execute { response ->
if (response.status.isSuccess()) {
val channel: ByteReadChannel = response.bodyAsChannel()
targetFile.outputStream().use { output ->
channel.copyTo(output)
}
} else {
throw IOException("Server returned HTTP ${response.status.value}")
}
}