package com.example.kbbidictionary.data.module import java.io.File import java.security.MessageDigest /** * Handles online module download, verification, and atomic installation. * Each module is an independent language database. */ class ModuleInstaller( private val modulesDir: File, ) { sealed class InstallResult { data class Success(val installedFile: File) : InstallResult() data class Failure(val reason: String) : InstallResult() } suspend fun install(downloadedTempFile: File, manifest: ModuleManifest): InstallResult { // 1. Verify checksum before installation. val actualChecksum = sha256(downloadedTempFile) if (!actualChecksum.equals(manifest.checksumSha256, ignoreCase = true)) { downloadedTempFile.delete() return InstallResult.Failure("Checksum mismatch. Possible corrupted or tampered module.") } // 2. Validate compatibility (min app version, db schema version) before install. // TODO: compare with BuildConfig.VERSION_NAME and supported schema. // 3. Atomic install: write to temp target, then rename/replace. val targetDir = File(modulesDir, manifest.moduleId).apply { mkdirs() } val targetFile = File(targetDir, "dictionary.sqlite") val stagingFile = File(targetDir, "dictionary.sqlite.tmp") downloadedTempFile.copyTo(stagingFile, overwrite = true) if (!stagingFile.renameTo(targetFile)) { stagingFile.delete() return InstallResult.Failure("Atomic replace failed.") } // 4. Update local registry in Room after successful install. return InstallResult.Success(targetFile) } private fun sha256(file: File): String { val digest = MessageDigest.getInstance("SHA-256") file.inputStream().use { input -> val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var read = input.read(buffer) while (read >= 0) { digest.update(buffer, 0, read) read = input.read(buffer) } } return digest.digest().joinToString("") { "%02x".format(it) } } }