package eu.friedcutlet.yokan.ext import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.attribute.PosixFilePermission import java.security.MessageDigest import java.time.Duration import java.util.zip.ZipInputStream import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class DesktopExtensionServerInstaller( private val installRoot: Path, private val httpClient: HttpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(30)) .followRedirects(HttpClient.Redirect.NORMAL) .build(), ) { suspend fun discoverLatest(): ExtensionServerRelease = withContext(Dispatchers.IO) { val request = HttpRequest.newBuilder(URI.create(ExtensionServerLatestReleaseUrl)) .header("Accept", "application/vnd.github+json") .header("User-Agent", "Yokan") .GET() .build() val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()) if (response.statusCode() !in 200..299) { throw ExtensionServerException( "RELEASE_HTTP_ERROR", "GitHub release request failed with HTTP ${response.statusCode()}", ) } parseExtensionServerRelease(response.body()) } suspend fun installLatest( onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> }, ): InstalledExtensionServerBundle { val release = discoverLatest() return install(release, release.selectBundle(currentDesktopHost()), onProgress) } suspend fun install( release: ExtensionServerRelease, asset: ExtensionServerReleaseAsset, onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> }, ): InstalledExtensionServerBundle = withContext(Dispatchers.IO) { require(asset.name.endsWith(".zip", ignoreCase = true)) { "Only ZIP bundles are supported" } Files.createDirectories(installRoot) val archive = Files.createTempFile(installRoot, ".download-", ".zip") val staging = Files.createTempDirectory(installRoot, ".install-") val finalDirectory = installRoot.resolve(release.version) try { download(asset, archive, onProgress) verifySha256(archive, asset.sha256) extractZip(archive, staging) val bundle = resolveBundle(staging, release.version) makeJavaExecutable(bundle.jvmPath) deleteRecursively(finalDirectory) try { Files.move(staging, finalDirectory, StandardCopyOption.ATOMIC_MOVE) } catch (_: Exception) { Files.move(staging, finalDirectory) } resolveBundle(finalDirectory, release.version) } finally { Files.deleteIfExists(archive) deleteRecursively(staging) } } fun installedBundle(version: String): InstalledExtensionServerBundle? { val directory = installRoot.resolve(version) if (!Files.isDirectory(directory)) return null return runCatching { resolveBundle(directory, version) }.getOrNull() } fun detectBundle(directory: Path): InstalledExtensionServerBundle { require(Files.isDirectory(directory)) { "Selected extension server location is not a directory: $directory" } return resolveBundle(directory, directory.fileName?.toString().orEmpty().ifBlank { "manual" }) .also { makeJavaExecutable(it.jvmPath) } } private fun download( asset: ExtensionServerReleaseAsset, target: Path, onProgress: (Long, Long) -> Unit, ) { val request = HttpRequest.newBuilder(URI.create(asset.downloadUrl)) .header("Accept", "application/octet-stream") .header("User-Agent", "Yokan") .GET() .build() val response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()) if (response.statusCode() !in 200..299) { response.body().close() throw ExtensionServerException("DOWNLOAD_HTTP_ERROR", "Bundle download failed with HTTP ${response.statusCode()}") } val expected = response.headers().firstValueAsLong("content-length").orElse(asset.size) response.body().use { source -> BufferedInputStream(source).use { input -> BufferedOutputStream(Files.newOutputStream(target)).use { output -> val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var downloaded = 0L while (true) { val count = input.read(buffer) if (count < 0) break output.write(buffer, 0, count) downloaded += count onProgress(downloaded, expected) } } } } } private fun verifySha256(path: Path, expected: String?) { if (expected == null) throw ExtensionServerException("MISSING_DIGEST", "Release asset has no SHA-256 digest") val digest = MessageDigest.getInstance("SHA-256") Files.newInputStream(path).use { input -> val buffer = ByteArray(DEFAULT_BUFFER_SIZE) while (true) { val count = input.read(buffer) if (count < 0) break digest.update(buffer, 0, count) } } val actual = digest.digest().joinToString("") { byte -> "%02x".format(byte) } if (!actual.equals(expected, ignoreCase = true)) { throw ExtensionServerException("DIGEST_MISMATCH", "Bundle SHA-256 mismatch: expected $expected, received $actual") } } private fun extractZip(archive: Path, destination: Path) { ZipInputStream(BufferedInputStream(Files.newInputStream(archive))).use { zip -> while (true) { val entry = zip.nextEntry ?: break val target = destination.resolve(entry.name).normalize() if (!target.startsWith(destination)) { throw ExtensionServerException("UNSAFE_ARCHIVE", "Bundle contains a path outside its install directory") } if (entry.isDirectory) { Files.createDirectories(target) } else { Files.createDirectories(target.parent) BufferedOutputStream(Files.newOutputStream(target)).use { output -> zip.copyTo(output) } } zip.closeEntry() } } } private fun resolveBundle(root: Path, version: String): InstalledExtensionServerBundle { val allFiles = Files.walk(root).use { paths -> paths.filter(Files::isRegularFile).toList() } val jar = allFiles.firstOrNull { path -> val name = path.fileName.toString() name.endsWith(".jar", ignoreCase = true) && name.contains("ExtensionServer", ignoreCase = true) } ?: throw ExtensionServerException("MISSING_JAR", "Downloaded bundle contains no extension server JAR") val javaName = if (currentDesktopHost().os == ExtensionServerHostOs.Windows) "java.exe" else "java" val java = allFiles.firstOrNull { path -> path.fileName.toString().equals(javaName, ignoreCase = true) && path.parent?.fileName?.toString() == "bin" } ?: throw ExtensionServerException("MISSING_JAVA", "Downloaded bundle contains no Java executable") return InstalledExtensionServerBundle(version, root.toAbsolutePath().toString(), java.toAbsolutePath().toString(), jar.toAbsolutePath().toString()) } private fun makeJavaExecutable(path: String) { val java = Path.of(path) runCatching { val permissions = Files.getPosixFilePermissions(java).toMutableSet() permissions += PosixFilePermission.OWNER_EXECUTE Files.setPosixFilePermissions(java, permissions) }.getOrElse { java.toFile().setExecutable(true, true) } } private fun deleteRecursively(path: Path) { if (!Files.exists(path)) return Files.walk(path).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists) } } } fun currentDesktopHost(): ExtensionServerHost { val osName = System.getProperty("os.name").lowercase() val os = when { "win" in osName -> ExtensionServerHostOs.Windows "mac" in osName || "darwin" in osName -> ExtensionServerHostOs.MacOs "linux" in osName -> ExtensionServerHostOs.Linux else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop OS: $osName") } val archName = System.getProperty("os.arch").lowercase() val arch = when (archName) { "x86_64", "amd64" -> ExtensionServerHostArch.X64 "aarch64", "arm64" -> ExtensionServerHostArch.Arm64 else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop architecture: $archName") } return ExtensionServerHost(os, arch) }