diff --git a/settings.gradle.kts b/settings.gradle.kts index e2691d0b8..7a4fe6b74 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -40,3 +40,7 @@ project(":server").projectDir = File("server") include(":server:core") include(":server:desktop") include(":server:android") + +include(":updater") +project(":updater").projectDir = File("updater") +include("updater:desktop") diff --git a/updater/.gitattributes b/updater/.gitattributes new file mode 100644 index 000000000..00a51aff5 --- /dev/null +++ b/updater/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/updater/.gitignore b/updater/.gitignore new file mode 100644 index 000000000..8ac467fa7 --- /dev/null +++ b/updater/.gitignore @@ -0,0 +1,26 @@ +# Ignore Gradle build output directory +build + +/bin/ +*/bin/ + +MagnetoLib.dll +vrconfig.yml + +# BVH +BVH Recordings + +# AutoBone +Recordings +AutoBone Recordings +Load AutoBone Recordings + +# Logs +*.log.* +*.log.lck +*.log +logs/ + +android/release +android/debug + diff --git a/updater/LICENSE.md b/updater/LICENSE.md new file mode 100644 index 000000000..42bf89d7a --- /dev/null +++ b/updater/LICENSE.md @@ -0,0 +1,6 @@ +This directory and all subdirectories is licensed under the MIT License ([LICENSE-MIT]). + +New contributions still must be dual licensed under both [LICENSE-MIT] and [LICENSE-APACHE]. + +[LICENSE-MIT]: /LICENSE-MIT +[LICENSE-APACHE]: /LICENSE-APACHE diff --git a/updater/build.gradle.kts b/updater/build.gradle.kts new file mode 100644 index 000000000..7d8272e19 --- /dev/null +++ b/updater/build.gradle.kts @@ -0,0 +1,68 @@ +plugins { + id("com.diffplug.spotless") +} + +allprojects { + repositories { + mavenCentral() + maven("https://jitpack.io") + } +} + +configure { + // optional: limit format enforcement to just the files changed by this feature branch + // ratchetFrom "origin/main" + + format("misc") { + // define the files to apply `misc` to + target("*.gradle", "*.md", ".gitignore") + + // define the steps to apply to those files + trimTrailingWhitespace() + endWithNewline() + leadingSpacesToTabs() + } + // format "yaml", { + // target "*.yml", "*.yaml", + + // trimTrailingWhitespace() + // endWithNewline() + // indentWithSpaces(2) // YAML cannot contain tabs: https://yaml.org/faq.html + // } + + val editorConfig = + mapOf( + "max_line_length" to "off", + "ktlint_experimental" to "enabled", + "ktlint_standard_condition-wrapping" to "disabled", + "ktlint_standard_property-naming" to "disabled", + "ij_kotlin_packages_to_use_import_on_demand" to + "java.util.*,kotlin.math.*,dev.slimevr.autobone.errors.*" + + ",io.github.axisangles.ktmath.*,kotlinx.atomicfu.*,kotlinx.coroutines.*" + + ",dev.slimevr.tracking.trackers.*,dev.slimevr.desktop.platform.ProtobufMessages.*" + + ",solarxr_protocol.rpc.*,kotlinx.coroutines.*,com.illposed.osc.*,android.app.*", + "ij_kotlin_allow_trailing_comma" to true, + ) + val ktlintVersion = "1.7.1" + kotlinGradle { + target("**/*.gradle.kts") // default target for kotlinGradle + ktlint(ktlintVersion) + .editorConfigOverride(editorConfig) + } + kotlin { + target("**/*.kt") + targetExclude("**/build/**/**.kt", "bin/") + ktlint(ktlintVersion) + .editorConfigOverride(editorConfig) + } + java { + target("**/*.java") + targetExclude("**/BuildConfig.java") + + removeUnusedImports() + // Use eclipse JDT formatter + eclipse("4.36") + .configFile("spotless.xml") + // .withP2Mirrors(mapOf("https://download.eclipse.org/" to "https://mirror.umd.edu/eclipse/")) + } +} diff --git a/updater/desktop/69-slimevr-devices.rules b/updater/desktop/69-slimevr-devices.rules new file mode 100644 index 000000000..58ee6d1d5 --- /dev/null +++ b/updater/desktop/69-slimevr-devices.rules @@ -0,0 +1,46 @@ +# Copyright 2025 Eiren Rain and SlimeVR Contributors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +## QinHeng +# CH340 +SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="7522", MODE="0660", TAG+="uaccess" +SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="7523", MODE="0660", TAG+="uaccess" +# CH341 +SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="5523", MODE="0660", TAG+="uaccess" +# CH343 +SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="55D3", MODE="0660", TAG+="uaccess" +# CH9102x +SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="55D4", MODE="0660", TAG+="uaccess" + +## Silabs +# CP210x +SUBSYSTEMS=="usb", ATTRS{idVendor}=="10C4", ATTRS{idProduct}=="EA60", MODE="0660", TAG+="uaccess" + +## Espressif +# ESP32-S3 / ESP32-C3 / ESP32-C5 / ESP32-C6 / ESP32-C61 / ESP32-H2 / ESP32-P4 +SUBSYSTEMS=="usb", ATTRS{idVendor}=="303A", ATTRS{idProduct}=="1001", MODE="0660", TAG+="uaccess" +# ESP32-S2 +SUBSYSTEMS=="usb", ATTRS{idVendor}=="303A", ATTRS{idProduct}=="0002", MODE="0660", TAG+="uaccess" + +## FTDI +# FT232BM/L/Q, FT245BM/L/Q +# FT232RL/Q, FT245RL/Q +# VNC1L with VDPS Firmware +# VNC2 with FT232Slave +SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE="0660", TAG+="uaccess" + +## SlimeVR +# smol slime dongle +SUBSYSTEM=="usb", ATTR{idVendor}=="1209", ATTR{idProduct}=="7690", MODE="0660", TAG+="uaccess" +KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690", MODE="0660", TAG+="uaccess" diff --git a/updater/desktop/build.gradle.kts b/updater/desktop/build.gradle.kts new file mode 100644 index 000000000..5519bdfff --- /dev/null +++ b/updater/desktop/build.gradle.kts @@ -0,0 +1,101 @@ +import org.gradle.kotlin.dsl.withType +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + kotlin("jvm") + kotlin("plugin.serialization") version "2.3.10" + application + id("com.gradleup.shadow") + id("com.github.gmazzo.buildconfig") + id("org.ajoberstar.grgit") +} + +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} +tasks.withType { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + freeCompilerArgs.set(listOf("-Xvalue-classes")) + } +} + +// Set compiler to use UTF-8 +tasks.withType { + options.encoding = "UTF-8" +} +tasks.withType { + systemProperty("file.encoding", "UTF-8") +} +tasks.withType { + options.encoding = "UTF-8" +} + +group = "org.example" +version = "unspecified" + +allprojects { + repositories { + // Use jcenter for resolving dependencies. + // You can declare any Maven/Ivy/file repository here. + mavenCentral() + maven(url = "https://jitpack.io") + maven(url = "https://oss.sonatype.org/content/repositories/snapshots") + } +} + +dependencies { + implementation(project(":server:core")) + implementation("io.ktor:ktor-client-core:3.0.3") + implementation("io.ktor:ktor-client-cio:3.0.3") + implementation("io.ktor:ktor-client-content-negotiation:3.0.3") + implementation("io.ktor:ktor-serialization-kotlinx-json:3.0.3") + implementation("commons-cli:commons-cli:1.8.0") + implementation("org.apache.commons:commons-lang3:3.15.0") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") + + + testImplementation(kotlin("test")) +} + +tasks.shadowJar { + minimize { + exclude(dependency("com.fazecast:jSerialComm:.*")) + exclude(dependency("net.java.dev.jna:.*:.*")) + exclude(dependency("com.google.flatbuffers:flatbuffers-java:.*")) + + exclude(project(":solarxr-protocol")) + } + archiveBaseName.set("updater") + archiveClassifier.set("") + archiveVersion.set("") +} + +application { + mainClass.set("dev.slimevr.updater.Main") +} + +buildConfig { + useKotlinOutput { topLevelConstants = true } + packageName("dev.slimevr.updater") + + val gitVersionTag = providers.exec { + commandLine("git", "--no-pager", "tag", "--sort", "-taggerdate", "--points-at", "HEAD") + }.standardOutput.asText.get().split('\n').first() + buildConfigField("String", "GIT_COMMIT_HASH", "\"${grgit.head().abbreviatedId}\"") + buildConfigField("String", "GIT_VERSION_TAG", "\"${gitVersionTag.trim()}\"") + buildConfigField("boolean", "GIT_CLEAN", grgit.status().isClean.toString()) +} + +tasks.run { + standardInput = System.`in` // this is not working + args = listOf("run") +} diff --git a/updater/desktop/curious-slime.gif b/updater/desktop/curious-slime.gif new file mode 100644 index 000000000..a5969c0e1 Binary files /dev/null and b/updater/desktop/curious-slime.gif differ diff --git a/updater/desktop/happy-slime.gif b/updater/desktop/happy-slime.gif new file mode 100644 index 000000000..569ad7080 Binary files /dev/null and b/updater/desktop/happy-slime.gif differ diff --git a/updater/desktop/installusbdrivers.bat b/updater/desktop/installusbdrivers.bat new file mode 100644 index 000000000..74b403169 --- /dev/null +++ b/updater/desktop/installusbdrivers.bat @@ -0,0 +1,15 @@ +@echo off +:: Driver installation doesn't work w/o admin, slimes will be sad. +net session >nul 2>&1 +if %errorlevel% == 0 ( + echo Running with administrative privileges! - Needed for firewall modification! +) else ( + echo Requesting administrative privileges - Needed for Driver installation! + :: Temp script to request admin... Works and doesn't leave a mess. + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + echo UAC.ShellExecute "%~s0", "", "%~dp0", "runas", 1 >> "%temp%\getadmin.vbs" + "%temp%\getadmin.vbs" + exit /B +) + +pnputil /add-driver *.inf /install /subdirs diff --git a/updater/desktop/jumping-slime.gif b/updater/desktop/jumping-slime.gif new file mode 100644 index 000000000..6c4f363b8 Binary files /dev/null and b/updater/desktop/jumping-slime.gif differ diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/Downloader.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Downloader.kt new file mode 100644 index 000000000..140a697d3 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Downloader.kt @@ -0,0 +1,16 @@ +package dev.slimevr.updater + +class Downloader { + + fun downloadServer() { + + } + + fun downloadFeeder() { + + } + + fun downloadDriver() { + + } +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/FeatureFlags.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/FeatureFlags.kt new file mode 100644 index 000000000..6f0d4131f --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/FeatureFlags.kt @@ -0,0 +1,7 @@ +package dev.slimevr.updater + +class FeatureFlags { + var version: String? = null + var listChannels: Boolean = false + var listVersions: Boolean = false +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/Linux.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Linux.kt new file mode 100644 index 000000000..852eaf912 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Linux.kt @@ -0,0 +1,103 @@ +package dev.slimevr.updater + +import java.nio.file.Paths +import kotlin.io.path.Path +import kotlin.io.path.exists + +class Linux { + + val sendMainProgress: (Int) -> Unit = { progress -> updaterGui.mainProgressBar.setProgress(progress) } + val path = Paths.get("").toAbsolutePath().toString() + + suspend fun updateLinux() { + updateLinuxSteamVRDriver() + updateUdev() + feeder() + } + + suspend fun updateFrame() { + updateLinuxSteamVRDriver() + } + + // TODO: tell user in gui to add steamvr launch arguments + suspend fun updateLinuxSteamVRDriver() { + updaterGui.subLabel.text = "Updating SteamVR Driver" + val vrPathRegContents = executeShellCommand("${System.getProperty("user.home")}/.steam/steam/steamapps/common/SteamVR/bin/vrpathreg.sh") + val isDriverRegistered = vrPathRegContents.contains("slimevr") + if (isDriverRegistered) { + updaterGui.subLabel.text = "Downloading SteamVR Driver" + downloadFile(LINUXSTEAMVRDRIVERURL, LINUXSTEAMVRDRIVERNAME) + updaterGui.subLabel.text = "Unzipping SteamVR Driver" + unzip(LINUXSTEAMVRDRIVERNAME, LINUXSTEAMVRDRIVERDIRECTORY) + println("${Paths.get("").toAbsolutePath()}/$LINUXSTEAMVRDRIVERDIRECTORY/slimevr") + executeShellCommand( + "${System.getProperty("user.home")}/.steam/steam/steamapps/common/SteamVR/bin/vrpathreg.sh", + "adddriver", + "$path/$LINUXSTEAMVRDRIVERDIRECTORY/slimevr", + ) + } else { + println("steamVR driver is already registered. Skipping...") + } + updaterGui.subLabel.text = "SteamVR Driver done" + sendMainProgress(33) + } + + fun removeLinuxSteamVRDriver() { + val vrPathRegContents = executeShellCommand("${System.getProperty("user.home")}/.steam/steam/steamapps/common/SteamVR/bin/vrpathreg.sh") + val isDriverRegistered = vrPathRegContents.contains("slimevr") + if (isDriverRegistered) { + println("Removing driver from steamvr") + executeShellCommand( + "${System.getProperty("user.home")}/.steam/steam/steamapps/common/SteamVR/bin/vrpathreg.sh", + "removedriver", + "$path/$LINUXSTEAMVRDRIVERDIRECTORY/slimevr", + ) + } else { + println("steamVR driver isn't registered. Skipping...") + } + } + + suspend fun feeder() { + updaterGui.subLabel.text = "Downloading Feeder App" + downloadFile(LINUXFEEDERURL, LINUXFEEDERNAME) + updaterGui.subLabel.text = "Unzipping Feeder App" + unzip(LINUXFEEDERNAME, LINUXFEEDERDIRECTORY) + updaterGui.subLabel.text = "Registering Feeder App" + executeShellCommand("chmod", "+x", "$path/$LINUXFEEDERDIRECTORY/SlimeVR-Feeder-App") + executeShellCommand("$path/$LINUXFEEDERDIRECTORY/SlimeVR-Feeder-App", "--install") + sendMainProgress(100) + updaterGui.subLabel.text = "Feeder App Done" + } + + // TODO: Find a way to do version checking on udev rules + fun updateUdev() { + updaterGui.subLabel.text = "Setting udev" + val file = Path("/etc/udev/rules.d/69-slimevr-devices.rules") + if (file.exists()) { + updaterGui.subLabel.text = "Udev rules already installed" + return + } + updaterGui.subLabel.text = "Asking for privileges" + val res = executeShellCommand("pkexec", "cp", "$path/69-slimevr-devices.rules", "/etc/udev/rules.d/69-slimevr-devices.rules") + if (res.contains("Error")) { + println("Error installing udev rules") + } else { + println("Successfully installed udev rules") + } + sendMainProgress(66) + updaterGui.subLabel.text = "Udev done" + } + + companion object { + // Linux URLs + private const val LINUXSTEAMVRDRIVERURL = "https://github.com/SlimeVR/SlimeVR-OpenVR-Driver/releases/latest/download/slimevr-openvr-driver-x64-linux.zip" + private const val LINUXSTEAMVRDRIVERNAME = "slimevr-openvr-driver-x64-linux.zip" + private const val LINUXSTEAMVRDRIVERDIRECTORY = "slimevr-openvr-driver-x64-linux" + private const val LINUXFEEDERURL = "https://github.com/SlimeVR/SlimeVR-Feeder-App/releases/latest/download/SlimeVR-Feeder-App-Linux.zip" + private const val LINUXFEEDERNAME = "SlimeVR-Feeder-App-Linux.zip" + private const val LINUXFEEDERDIRECTORY = "SlimeVR-Feeder-App-Linux" + private const val LINUXSERVERURL = "https://github.com/SlimeVR/SlimeVR-Server/releases/latest/download/SlimeVR-amd64.appimage" + private const val LINUXSERVERNAME = "SlimeVR-amd64.appimage" + private const val LINUXSERVERDIRECTORY = "slimevr-linux" + } +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/Main.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Main.kt new file mode 100644 index 000000000..76895997d --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Main.kt @@ -0,0 +1,60 @@ +@file:JvmName("Main") + +package dev.slimevr.updater + +import dev.slimevr.updater.ManifestUtils.Companion.listChannels +import dev.slimevr.updater.ManifestUtils.Companion.listVersions +import org.apache.commons.cli.CommandLine +import org.apache.commons.cli.CommandLineParser +import org.apache.commons.cli.DefaultParser +import org.apache.commons.cli.HelpFormatter +import org.apache.commons.cli.Options +import kotlin.system.exitProcess +import kotlin.text.ifEmpty + +val VERSION = + (GIT_VERSION_TAG.ifEmpty { GIT_COMMIT_HASH }) + + if (GIT_CLEAN) "" else "-dirty" +val updaterGui = UpdaterGui() + +val featureFlags = FeatureFlags() + +fun main(args: Array) { + val parser: CommandLineParser = DefaultParser() + val formatter = HelpFormatter() + val options = Options() + options.addOption("h", "help", false, "Show help") + options.addOption("i", "install", false, "Specify version to update to") + options.addOption("c", "channels", false, "List all release channels") + options.addOption("l", "list", false, "List all versions") + val cmd: CommandLine = try { + parser.parse(options, args, true) + } catch (e: org.apache.commons.cli.ParseException) { + formatter.printHelp("updater.jar", options) + exitProcess(1) + } + if (cmd.hasOption("help")) { + formatter.printHelp("updater.jar", options) + exitProcess(0) + } + if (cmd.hasOption("install")) { + featureFlags.version = cmd.getOptionValue("install") + } + if (cmd.hasOption("channels")) { + featureFlags.listChannels = true + val manifest = Manifest().getManifest() + listChannels(manifest) + exitProcess(0) + } + if (cmd.hasOption("list")) { + featureFlags.listVersions = true + val manifest = Manifest().getManifest() + listVersions(manifest, cmd.getOptionValue("list")) + exitProcess(0) + } + + val manifest = Manifest() + + val updater = Updater() + updater.runUpdater() +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/Manifest.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Manifest.kt new file mode 100644 index 000000000..b292d99a0 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Manifest.kt @@ -0,0 +1,62 @@ +package dev.slimevr.updater + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import java.io.File + +class Manifest { + private val json: Json = Json { ignoreUnknownKeys = true } + private val manifest: ManifestObject + + init { + val file = File("update-manifest.json").readText() + manifest = Json.decodeFromString(file) + val json = Json { + ignoreUnknownKeys = true + } + } + + fun getManifest(): ManifestObject { + return manifest + } +} + +@Serializable +data class Release( + val url: String, + val run: List +) + +@Serializable +data class Versions( + @SerialName("release_notes") + val releaseNotes: String, + val builds: Map> +) + +@Serializable +data class Channel( + val description: String, + @SerialName("current_version") + val currentVersion: String, + val versions: Map +) + +@Serializable +data class ManifestObject( + @SerialName("default_channel") + val defaultChannel: String, + val channels: Map +) + +class ChannelDisplayObject( + val channelName: String, + val Description: String +) + +class VersionDisplayObject( + val version: String, + val Description: String, + val Url: String +) diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/ManifestUtils.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/ManifestUtils.kt new file mode 100644 index 000000000..43b7b0322 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/ManifestUtils.kt @@ -0,0 +1,26 @@ +package dev.slimevr.updater + +class ManifestUtils { + + companion object { + @JvmStatic + fun listChannels(manifest: ManifestObject) { + manifest.channels.forEach { channel -> + println(channel.key) + } + } + + @JvmStatic + fun listVersions(manifest: ManifestObject, channel: String) { + manifest.channels[channel]?.versions?.forEach { version -> + println(version) + } + } + + @JvmStatic + fun getRelease(manifest: ManifestObject, channel: String, version: String, platform: String, release: String): Release? { + val res = manifest.channels[channel]?.versions[version]?.builds[platform]?.get(release) + return res + } + } +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/Updater.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Updater.kt new file mode 100644 index 000000000..559c045fe --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Updater.kt @@ -0,0 +1,78 @@ +package dev.slimevr.updater + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonArray + +class Updater { + + @Serializable + data class GHResponse( + val tag_name: String, + val assets: JsonArray + ) + + @Serializable + data class ReleaseInfo( + val url: String, + val id: Long, + val name: String, + val digest: String + ) + + + val os = System.getProperty("os.name").lowercase() + + fun runUpdater() { + + val manifest = Manifest() + + + + //channels.getChannels("Server") + + /* + val shouldUpdate: Boolean = shouldUpdate() + println("Should update $shouldUpdate") + + /* + if (!shouldUpdate) { + println("Updater didn't find any new version") + return + } + + */ + + if (os.contains("linux")) { + val linuxUpdater = Linux() + val linuxFlavour = executeShellCommand("uname", "-n") + + // Skip some install stuff if running on frame + // if (linuxFlavour.contains("amos")) { + // linuxUpdater.updateFrame() + // } + // else { + linuxUpdater.updateLinux() + // } + } else if (os.contains("windows")) { + println("Running windows updater") + val windowsUpdater = Windows() + windowsUpdater.updateWindows() + } else if (os.contains("darwin")) { + println("I dunno") + } else { + println("guess I'll die") + } + updaterGui.mainLabel.text = "Done Installing" + updaterGui.mainLabel.isVisible = false + + Thread.sleep(1000) + return + + */ + } + + + companion object { + val CDN = "http://127.0.0.1:8080" + } +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/UpdaterGui.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/UpdaterGui.kt new file mode 100644 index 000000000..2b4c4a410 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/UpdaterGui.kt @@ -0,0 +1,163 @@ +package dev.slimevr.updater + +import java.awt.* +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent + + +class UpdaterGui : Frame() { + + val mainLabel = Label("Installing SlimeVR Drivers", Label.CENTER) + val subLabel = Label("", Label.CENTER) + val mainProgressBar: ProgressBar = ProgressBar() + val subProgressBar: ProgressBar = ProgressBar() + + init { + isUndecorated = true + + val frameDragListener: FrameDragListener = FrameDragListener(this) + addMouseListener(frameDragListener) + addMouseMotionListener(frameDragListener) + pack() + setLocationRelativeTo(null) + + setBackground(Color(17, 45, 67)) + setSize(400, 450) + + val dim = Toolkit.getDefaultToolkit().screenSize + this.setLocation( + dim.width / 2 - this.size.width / 2, + dim.height / 2 - this.size.height / 2, + ) + + mainLabel.foreground = Color.WHITE + mainLabel.setFont(Font("Poppins", Font.PLAIN, 16)) + subLabel.foreground = Color.WHITE + + setLayout(GridBagLayout()) + val gbc = GridBagConstraints() + gbc.gridx = 0 + gbc.insets = Insets(0, 10, 5, 10) + + val gifLabel = Label("Loading Animation...", Label.CENTER) + gifLabel.setForeground(Color.WHITE) + + val animatedGif = GifCanvas("jumping-slime.gif") + + gbc.gridy = 0 + add(mainLabel, gbc) + gbc.gridy = 1 + add(animatedGif, gbc) + gbc.gridy = 2 + gbc.fill = GridBagConstraints.HORIZONTAL + add(mainProgressBar, gbc) + gbc.gridy = 3 + add(subLabel, gbc) + gbc.gridy = 4 + add(subProgressBar, gbc) + + isVisible = true + } +} + +class FrameDragListener(private val frame: UpdaterGui) : MouseAdapter() { + private var mouseDownCompCoords: Point? = null + + override fun mouseReleased(e: MouseEvent?) { + mouseDownCompCoords = null + } + + override fun mousePressed(e: MouseEvent) { + mouseDownCompCoords = e.getPoint() + } + + override fun mouseDragged(e: MouseEvent) { + val currCoords: Point = e.locationOnScreen + frame.setLocation( + currCoords.x - mouseDownCompCoords!!.x, + currCoords.y - mouseDownCompCoords!!.y + ) + } +} + +class GifCanvas(path: String?) : Canvas() { + private val img: Image? = Toolkit.getDefaultToolkit().getImage(path) + private val scaledImage: Image? = img?.getScaledInstance(150, 150, Image.SCALE_DEFAULT) + private var offscreen: Image? = null + private var offscreenG: Graphics? = null + + init { + prepareImage(img, this) + val tracker = MediaTracker(this) + tracker.addImage(img, 0) + try { + tracker.waitForID(0) + } catch (e: Exception) { + + } + + } + + override fun update(g: Graphics) { + paint(g) + } + + override fun paint(g: Graphics) { + val w = getWidth() + val h = getHeight() + offscreen = createImage(width, height) + offscreenG = offscreen?.graphics + + offscreenG?.color = Color(17, 45, 67, 255) + offscreenG?.fillRect(0, 0, w, h) + + if (scaledImage != null) { + val iw = scaledImage.getWidth(this) + val ih = scaledImage.getHeight(this) + if (iw > 0 && ih > 0) { + offscreenG?.drawImage(scaledImage, (w - iw) / 2, (h - ih) / 2, this) + } + } + + g.drawImage(offscreen, 0, 0, this) + } + + override fun imageUpdate( + img: Image?, + infoflags: Int, + x: Int, + y: Int, + w: Int, + h: Int, + ): Boolean { + if ((infoflags and (FRAMEBITS or ALLBITS)) != 0) { + repaint() + } + return (infoflags and (ALLBITS or ABORT or ERROR)) == 0 + } + + override fun getPreferredSize(): Dimension = Dimension(200, 200) +} + +class ProgressBar() : Canvas() { + var currentProgress: Int = 0 + val progressBarWidth = 200 + + fun setProgress(newProgress: Int) { + currentProgress = ((newProgress) * (progressBarWidth) / 100) + repaint() + } + init { + setSize(200, 15) + } + + override fun paint(g: Graphics) { + // Background + g.color = Color(8, 30, 48) + g.fillRoundRect(0, 0, progressBarWidth, 10, 5, 5) + + // Progress + g.color = Color(101, 69, 154) + g.fillRoundRect(0, 0, currentProgress, 10, 5, 5) // Static 60% for now + } +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/UpdaterUtils.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/UpdaterUtils.kt new file mode 100644 index 000000000..72c11c238 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/UpdaterUtils.kt @@ -0,0 +1,211 @@ +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.statement.bodyAsChannel +import io.ktor.http.contentLength +import io.ktor.serialization.kotlinx.json.json +import io.ktor.utils.io.jvm.javaio.copyTo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.lang.Exception +import java.math.BigInteger +import java.nio.file.Files +import java.nio.file.Paths +import java.security.MessageDigest +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import kotlin.time.Duration.Companion.seconds + +fun executeShellCommand(vararg command: String): String = try { + val process = ProcessBuilder(*command) + .redirectErrorStream(true) + .start() + process.inputStream.bufferedReader().readText().also { + process.waitFor() + } +} catch (e: IOException) { + "Error executing shell command: ${e.message}" +} + +val sendSubProgress: (Float) -> Unit = { progress -> updaterGui.subProgressBar.setProgress(progress.toInt()) } + +fun downloadFile( + fileUrl: String, + fileName: String, + onProgress: (Float) -> Unit = sendSubProgress, +) { + onProgress(0f) + val client = HttpClient(CIO) + val outputStream = FileOutputStream(fileName) + + runBlocking { + client.prepareGet( + fileUrl, + block = { + val timeout = 30.seconds.inWholeMilliseconds + timeout { + requestTimeoutMillis = timeout + connectTimeoutMillis = timeout + socketTimeoutMillis = timeout + } + onDownload { bytesSentTotal, contentLength -> + val progress = bytesSentTotal.toFloat() / (contentLength?.toFloat() ?: 1f) + onProgress(progress * 100) + } + }, + ).execute { httpResponse -> + if (httpResponse.status.value in 200..299) { + val byteReadChannel = httpResponse.bodyAsChannel() + byteReadChannel.copyTo(outputStream) + } + } + } + checksum(fileName) +} + +// Guard against zip slip +fun resolveSaveFile(destinationPath: File, zipEntry: ZipEntry): File { + val destFile = File(destinationPath, zipEntry.name) + + val destinationDirPath = destinationPath.getCanonicalPath() + val destinationFilePath = destFile.getCanonicalPath() + + if (!destinationFilePath.startsWith(destinationDirPath + File.separator)) { + throw IOException("Entry is outside of the target dir: ${zipEntry.name}") + } + + return destFile +} + +suspend fun unzip( + file: String, + destDir: String, + onProgress: (Float) -> Unit = sendSubProgress, +) { + val destFolder = File(destDir) + if (!destFolder.exists()) { + destFolder.mkdirs() + } + onProgress(0f) + withContext(Dispatchers.IO) { + val zipFile = ZipFile(file) + var progress = 0f + val semaphore = Semaphore(4) + for (entry in zipFile.entries()) { + this.launch() { + semaphore.withPermit { + unzipWorker(zipFile, entry, destDir) + } + } + onProgress(progress / zipFile.size() * 100) + progress++ + } + } + onProgress(100f) +} + +suspend fun unzipWorker(zipFile: ZipFile, zipEntry: ZipEntry, destDir: String) { + val destFolder = File(destDir) + val targetFile = File(destFolder, zipEntry.name) + if (!targetFile.canonicalPath.startsWith(destFolder.canonicalPath)) { + throw IOException("Entry is outside of the target dir: ${zipEntry.name}") + } + + withContext(Dispatchers.IO) { + try { + if (zipEntry.isDirectory) { + if (!targetFile.exists() && !targetFile.mkdirs()) { + throw IOException("Failed to create directory: $targetFile") + } + } else { + targetFile.parentFile?.let { parent -> + if (!parent.exists() && !parent.mkdirs() && !parent.exists()) { + throw IOException("Failed to create parent directory: $parent") + } + } + + zipFile.getInputStream(zipEntry).use { input -> + FileOutputStream(targetFile).use { output -> + input.copyTo(output, bufferSize = 8192) + } + } + } + } catch (e: Exception) { + println("Error during unzip of ${zipEntry.name}: ${e.message}") + } + } +} + +fun deleteFile(file: File) { + if (file.exists() && file.isFile) { + file.delete() + } +} + +fun checksum(file: String) { + val data = Files.readAllBytes(Paths.get(file)) + val hash = MessageDigest.getInstance("SHA-256").digest(data) + val checksum = BigInteger(1, hash).toString(16) +} + +suspend fun shouldUpdate(): Boolean { + println("Current version $VERSION") + // We're running from a git branch don't update + if (VERSION.contains("dirty")) { + return false + } + val client = HttpClient(CIO) { + install(ContentNegotiation) { + json( + Json { + ignoreUnknownKeys = true + }, + ) + } + } + try { + val response: Updater.GHResponse = client.get("https://api.github.com/repos/slimevr/slimevr-server/releases/latest").body() + client.close() + println(response.assets.toString()) + val json = Json { + ignoreUnknownKeys = true + } + val releaseInfos = json.decodeFromString>(response.assets.toString()) + for (releaseInfo in releaseInfos) { + println(releaseInfo.toString()) + } + // Replace this if versioning ever changes + val githubVersionArr = response.tag_name.replace("v", "").split(".") + val localVersionArr = VERSION.replace("v", "").split(".") + // Cursed? + return if (githubVersionArr[0] > localVersionArr[0]) { + true + } else if (githubVersionArr[0] < localVersionArr[0] && githubVersionArr[1] > localVersionArr[1]) { + true + } else if (githubVersionArr[0] < localVersionArr[0] && githubVersionArr[1] < localVersionArr[1] && githubVersionArr[2] > localVersionArr[2]) { + true + } else { + false + } + } catch (e: Exception) { + println("Error getting github release info: ${e.message}") + } + return false +} diff --git a/updater/desktop/src/main/kotlin/dev/slimevr/updater/Windows.kt b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Windows.kt new file mode 100644 index 000000000..735d10372 --- /dev/null +++ b/updater/desktop/src/main/kotlin/dev/slimevr/updater/Windows.kt @@ -0,0 +1,90 @@ +package dev.slimevr.updater + +import java.nio.file.Paths + +class Windows { + + val sendMainProgress: (Int) -> Unit = { progress -> updaterGui.mainProgressBar.setProgress(progress) } + val path = Paths.get("").toAbsolutePath().toString() + + suspend fun updateWindows() { + // First check if everything is already installed. Install it if it isn't + usbDrivers() + steamVRDriver() + feeder() + } + + fun usbDrivers() { + //mainProgressBar.string = "Updating usb drivers" + updaterGui.subLabel.text = "Checking Windows Drivers" + val installedDriversList = + executeShellCommand("powershell.exe", "pnputil /enum-drivers") + val ch341ser = installedDriversList.contains("ch341ser.inf") + val ch343ser = installedDriversList.contains("ch343ser.inf") + val silabser = installedDriversList.contains("silabser.inf") + + if (ch341ser && ch343ser && silabser) { + println("drivers already installed!") + return + } + + println("Cannot find one of the drivers, installing drivers") + val driverinstallOutput = executeShellCommand("$path\\installusbdrivers.bat") + println(driverinstallOutput) + sendMainProgress(33) + } + + + suspend fun feeder() { + updaterGui.subLabel.text = "Downloading Feeder App" + downloadFile(WINDOWSFEEDERURL, WINDOWSFEEDERNAME) + updaterGui.subLabel.text = "Unzipping Feeder App" + unzip(WINDOWSFEEDERNAME, WINDOWSFEEDERDIRECTORY) + updaterGui.subLabel.text = "Registering Feeder App" + executeShellCommand("${path}\\${WINDOWSFEEDERDIRECTORY}\\SlimeVR-Feeder-App.exe", "--install") + sendMainProgress(100) + updaterGui.subLabel.text = "Feeder App Done" + } + + suspend fun steamVRDriver() { + updaterGui.subLabel.text = "Updating SteamVR Driver" + val steamVRLocation = executeShellCommand("powershell.exe", "-Command", "(Get-ItemProperty \'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Steam App 250820\').InstallLocation").trim() + if (!steamVRLocation.contains("SteamVR")) { + println("SteamVR not installed, cannot install SlimeVR Steam driver.") + return + } + val vrPathRegContents = executeShellCommand("${steamVRLocation}\\bin\\win64\\vrpathreg.exe", "finddriver", "slimevr") + val isDriverRegistered = vrPathRegContents.contains("WINDOWSSTEAMVRDRIVERDIRECTORY") + if (isDriverRegistered) { + println("steamVR driver is already registered. Skipping...") + return + } + updaterGui.subLabel.text = "Downloading SteamVR Driver" + downloadFile(WINDOWSSTEAMVRDRIVERURL, WINDOWSSTEAMVRDRIVERNAME) + updaterGui.subLabel.text = "Unzipping SteamVR Driver" + unzip(WINDOWSSTEAMVRDRIVERNAME, WINDOWSSTEAMVRDRIVERDIRECTORY) + executeShellCommand( + "${steamVRLocation}\\bin\\win64\\vrpathreg.exe", + "adddriver", + "${ + Paths.get( + "", + ).toAbsolutePath() + }\\${WINDOWSSTEAMVRDRIVERDIRECTORY}\\slimevr", + ) + updaterGui.subLabel.text = "SteamVR Driver done" + sendMainProgress(66) + } + + companion object { + private const val WINDOWSSTEAMVRDRIVERURL = "https://github.com/SlimeVR/SlimeVR-OpenVR-Driver/releases/latest/download/slimevr-openvr-driver-win64.zip" + private const val WINDOWSSTEAMVRDRIVERNAME = "slimevr-openvr-driver-win64.zip" + private const val WINDOWSSTEAMVRDRIVERDIRECTORY = "slimevr-openvr-driver-win64" + private const val WINDOWSFEEDERURL = "https://github.com/SlimeVR/SlimeVR-Feeder-App/releases/latest/download/SlimeVR-Feeder-App-win64.zip" + private const val WINDOWSFEEDERNAME = "SlimeVR-Feeder-App-win64.zip" + private const val WINDOWSFEEDERDIRECTORY = "SlimeVR-Feeder-App-win64" + private const val WINDOWSSERVERURL = "https://github.com/SlimeVR/SlimeVR-Server/releases/latest/download/SlimeVR-win64.zip" + private const val WINDOWSSERVERNAME = "slimevr-win64.zip" + private const val WINDOWSSERVERDIRECTORY = "slimevr-win64" + } +} diff --git a/updater/desktop/src/test/kotlin/dev/slimevr/updater/UpdaterTest.kt b/updater/desktop/src/test/kotlin/dev/slimevr/updater/UpdaterTest.kt new file mode 100644 index 000000000..1b59fc816 --- /dev/null +++ b/updater/desktop/src/test/kotlin/dev/slimevr/updater/UpdaterTest.kt @@ -0,0 +1,57 @@ +package dev.slimevr.updater + +import dev.slimevr.updater.ManifestUtils.Companion.getRelease +import dev.slimevr.updater.ManifestUtils.Companion.listChannels +import dev.slimevr.updater.ManifestUtils.Companion.listVersions +import kotlin.test.Test + +class UpdaterTest { + + @Test + fun testArguments() { + + } + + @Test + fun testUpdater() { + val updater = Updater() + updater.runUpdater() + } + + @Test + fun testDownload() { + + } + + @Test + fun testListVersions() { + val manifest = Manifest().getManifest() + listVersions(manifest, "stable") + println("/------------------------------------------") + listVersions(manifest, "beta") + } + + @Test + fun testListChannels() { + val manifest = Manifest().getManifest() + listChannels(manifest) + } + + @Test + fun testGetLatestWindowsRelease() { + val manifest = Manifest().getManifest() + val release = getRelease(manifest, "stable", "v19.0.0", "windows", "x86_64") + println(release?.url) + } + + @Test + fun downgrade() { + + } + + @Test + fun updateToSpecificVersion() { + + } + +} diff --git a/updater/spotless.xml b/updater/spotless.xml new file mode 100644 index 000000000..0e364f183 --- /dev/null +++ b/updater/spotless.xml @@ -0,0 +1,401 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +