DesktopExtensionServerInstaller.kt
vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstaller.kt
1package eu.friedcutlet.yokan.ext23import java.io.BufferedInputStream4import java.io.BufferedOutputStream5import java.net.URI6import java.net.http.HttpClient7import java.net.http.HttpRequest8import java.net.http.HttpResponse9import java.nio.file.Files10import java.nio.file.Path11import java.nio.file.StandardCopyOption12import java.nio.file.attribute.PosixFilePermission13import java.security.MessageDigest14import java.time.Duration15import java.util.zip.ZipInputStream16import kotlinx.coroutines.Dispatchers17import kotlinx.coroutines.withContext1819class DesktopExtensionServerInstaller(20 private val installRoot: Path,21 private val httpClient: HttpClient = HttpClient.newBuilder()22 .connectTimeout(Duration.ofSeconds(30))23 .followRedirects(HttpClient.Redirect.NORMAL)24 .build(),25) {26 suspend fun discoverLatest(): ExtensionServerRelease = withContext(Dispatchers.IO) {27 val request = HttpRequest.newBuilder(URI.create(ExtensionServerLatestReleaseUrl))28 .header("Accept", "application/vnd.github+json")29 .header("User-Agent", "Yokan")30 .GET()31 .build()32 val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())33 if (response.statusCode() !in 200..299) {34 throw ExtensionServerException(35 "RELEASE_HTTP_ERROR",36 "GitHub release request failed with HTTP ${response.statusCode()}",37 )38 }39 parseExtensionServerRelease(response.body())40 }4142 suspend fun installLatest(43 onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },44 ): InstalledExtensionServerBundle {45 val release = discoverLatest()46 return install(release, release.selectBundle(currentDesktopHost()), onProgress)47 }4849 suspend fun install(50 release: ExtensionServerRelease,51 asset: ExtensionServerReleaseAsset,52 onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },53 ): InstalledExtensionServerBundle = withContext(Dispatchers.IO) {54 require(asset.name.endsWith(".zip", ignoreCase = true)) { "Only ZIP bundles are supported" }55 Files.createDirectories(installRoot)56 val archive = Files.createTempFile(installRoot, ".download-", ".zip")57 val staging = Files.createTempDirectory(installRoot, ".install-")58 val finalDirectory = installRoot.resolve(release.version)59 try {60 download(asset, archive, onProgress)61 verifySha256(archive, asset.sha256)62 extractZip(archive, staging)63 val bundle = resolveBundle(staging, release.version)64 makeJavaExecutable(bundle.jvmPath)65 deleteRecursively(finalDirectory)66 try {67 Files.move(staging, finalDirectory, StandardCopyOption.ATOMIC_MOVE)68 } catch (_: Exception) {69 Files.move(staging, finalDirectory)70 }71 resolveBundle(finalDirectory, release.version)72 } finally {73 Files.deleteIfExists(archive)74 deleteRecursively(staging)75 }76 }7778 fun installedBundle(version: String): InstalledExtensionServerBundle? {79 val directory = installRoot.resolve(version)80 if (!Files.isDirectory(directory)) return null81 return runCatching { resolveBundle(directory, version) }.getOrNull()82 }8384 fun detectBundle(directory: Path): InstalledExtensionServerBundle {85 require(Files.isDirectory(directory)) { "Selected extension server location is not a directory: $directory" }86 return resolveBundle(directory, directory.fileName?.toString().orEmpty().ifBlank { "manual" })87 .also { makeJavaExecutable(it.jvmPath) }88 }8990 private fun download(91 asset: ExtensionServerReleaseAsset,92 target: Path,93 onProgress: (Long, Long) -> Unit,94 ) {95 val request = HttpRequest.newBuilder(URI.create(asset.downloadUrl))96 .header("Accept", "application/octet-stream")97 .header("User-Agent", "Yokan")98 .GET()99 .build()100 val response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream())101 if (response.statusCode() !in 200..299) {102 response.body().close()103 throw ExtensionServerException("DOWNLOAD_HTTP_ERROR", "Bundle download failed with HTTP ${response.statusCode()}")104 }105 val expected = response.headers().firstValueAsLong("content-length").orElse(asset.size)106 response.body().use { source ->107 BufferedInputStream(source).use { input ->108 BufferedOutputStream(Files.newOutputStream(target)).use { output ->109 val buffer = ByteArray(DEFAULT_BUFFER_SIZE)110 var downloaded = 0L111 while (true) {112 val count = input.read(buffer)113 if (count < 0) break114 output.write(buffer, 0, count)115 downloaded += count116 onProgress(downloaded, expected)117 }118 }119 }120 }121 }122123 private fun verifySha256(path: Path, expected: String?) {124 if (expected == null) throw ExtensionServerException("MISSING_DIGEST", "Release asset has no SHA-256 digest")125 val digest = MessageDigest.getInstance("SHA-256")126 Files.newInputStream(path).use { input ->127 val buffer = ByteArray(DEFAULT_BUFFER_SIZE)128 while (true) {129 val count = input.read(buffer)130 if (count < 0) break131 digest.update(buffer, 0, count)132 }133 }134 val actual = digest.digest().joinToString("") { byte -> "%02x".format(byte) }135 if (!actual.equals(expected, ignoreCase = true)) {136 throw ExtensionServerException("DIGEST_MISMATCH", "Bundle SHA-256 mismatch: expected $expected, received $actual")137 }138 }139140 private fun extractZip(archive: Path, destination: Path) {141 ZipInputStream(BufferedInputStream(Files.newInputStream(archive))).use { zip ->142 while (true) {143 val entry = zip.nextEntry ?: break144 val target = destination.resolve(entry.name).normalize()145 if (!target.startsWith(destination)) {146 throw ExtensionServerException("UNSAFE_ARCHIVE", "Bundle contains a path outside its install directory")147 }148 if (entry.isDirectory) {149 Files.createDirectories(target)150 } else {151 Files.createDirectories(target.parent)152 BufferedOutputStream(Files.newOutputStream(target)).use { output -> zip.copyTo(output) }153 }154 zip.closeEntry()155 }156 }157 }158159 private fun resolveBundle(root: Path, version: String): InstalledExtensionServerBundle {160 val allFiles = Files.walk(root).use { paths -> paths.filter(Files::isRegularFile).toList() }161 val jar = allFiles.firstOrNull { path ->162 val name = path.fileName.toString()163 name.endsWith(".jar", ignoreCase = true) && name.contains("ExtensionServer", ignoreCase = true)164 } ?: throw ExtensionServerException("MISSING_JAR", "Downloaded bundle contains no extension server JAR")165 val javaName = if (currentDesktopHost().os == ExtensionServerHostOs.Windows) "java.exe" else "java"166 val java = allFiles.firstOrNull { path ->167 path.fileName.toString().equals(javaName, ignoreCase = true) && path.parent?.fileName?.toString() == "bin"168 } ?: throw ExtensionServerException("MISSING_JAVA", "Downloaded bundle contains no Java executable")169 return InstalledExtensionServerBundle(version, root.toAbsolutePath().toString(), java.toAbsolutePath().toString(), jar.toAbsolutePath().toString())170 }171172 private fun makeJavaExecutable(path: String) {173 val java = Path.of(path)174 runCatching {175 val permissions = Files.getPosixFilePermissions(java).toMutableSet()176 permissions += PosixFilePermission.OWNER_EXECUTE177 Files.setPosixFilePermissions(java, permissions)178 }.getOrElse { java.toFile().setExecutable(true, true) }179 }180181 private fun deleteRecursively(path: Path) {182 if (!Files.exists(path)) return183 Files.walk(path).use { paths ->184 paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)185 }186 }187}188189190fun currentDesktopHost(): ExtensionServerHost {191 val osName = System.getProperty("os.name").lowercase()192 val os = when {193 "win" in osName -> ExtensionServerHostOs.Windows194 "mac" in osName || "darwin" in osName -> ExtensionServerHostOs.MacOs195 "linux" in osName -> ExtensionServerHostOs.Linux196 else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop OS: $osName")197 }198 val archName = System.getProperty("os.arch").lowercase()199 val arch = when (archName) {200 "x86_64", "amd64" -> ExtensionServerHostArch.X64201 "aarch64", "arm64" -> ExtensionServerHostArch.Arm64202 else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop architecture: $archName")203 }204 return ExtensionServerHost(os, arch)205}206