AboutSettingsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/about/AboutSettingsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.about23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.services.catchingNonCancellation6import eu.friedcutlet.yokan.services.files.LocalFileService7import eu.friedcutlet.yokan.services.http.HttpRequest8import eu.friedcutlet.yokan.services.http.HttpService9import eu.friedcutlet.yokan.services.logging.CrashReportStore10import eu.friedcutlet.yokan.services.notifications.InAppNotifications11import eu.friedcutlet.yokan.services.updates.ReleaseAsset12import eu.friedcutlet.yokan.services.updates.ReleaseInfo13import eu.friedcutlet.yokan.services.updates.YOKAN_VERSION14import eu.friedcutlet.yokan.services.updates.fetchLatestRelease15import eu.friedcutlet.yokan.services.updates.installPackageFromFile16import eu.friedcutlet.yokan.services.updates.isNewerVersion17import eu.friedcutlet.yokan.ui.screens.reader.shareImage18import kotlinx.coroutines.CoroutineDispatcher19import kotlinx.coroutines.Dispatchers20import kotlinx.coroutines.flow.MutableStateFlow21import kotlinx.coroutines.flow.StateFlow22import kotlinx.coroutines.flow.asStateFlow23import kotlinx.coroutines.flow.update24import kotlinx.coroutines.launch25import kotlinx.coroutines.withContext2627internal data class AboutSettingsState(28 val checkingUpdate: Boolean = false,29 val release: ReleaseInfo? = null,30 val updateMessage: String? = null,31 /** Names of shown release assets already present in the update cache. */32 val downloadedAssets: Set<String> = emptySet(),33 val crashReport: String? = null,34)3536internal class AboutSettingsViewModel(37 private val http: HttpService,38 private val files: LocalFileService,39 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,40) : ViewModel() {41 private val _state = MutableStateFlow(AboutSettingsState())42 val state: StateFlow<AboutSettingsState> = _state.asStateFlow()4344 init {45 viewModelScope.launch {46 val report = withContext(workDispatcher) { CrashReportStore.read(files) }47 _state.update { it.copy(crashReport = report) }48 }49 }5051 fun checkForUpdate() {52 if (_state.value.checkingUpdate) return53 _state.update { it.copy(checkingUpdate = true, updateMessage = "Searching…") }54 viewModelScope.launch {55 val info = fetchLatestRelease(http)56 val newer = info?.takeIf { isNewerVersion(it.tag) }57 _state.update {58 it.copy(59 release = newer,60 downloadedAssets = emptySet(),61 updateMessage = when {62 info == null -> "Network error"63 newer != null -> "Update available: ${info.tag} • ${info.assets.size} assets"64 else -> "You're up to date ($YOKAN_VERSION)"65 },66 checkingUpdate = false,67 )68 }69 newer?.let { refreshDownloaded(it.assets.take(ShownAssets)) }70 }71 }7273 fun downloadAsset(asset: ReleaseAsset) {74 viewModelScope.launch {75 val downloadedPath = assetPath(asset)76 val installed = catchingNonCancellation {77 val response = http.request(HttpRequest(asset.url))78 if (response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) {79 withContext(workDispatcher) { files.writeBytes(downloadedPath, response.bodyBytes) }80 // Android launches the package installer; other81 // platforms reveal the artifact for manual install.82 if (!installPackageFromFile(downloadedPath)) {83 files.openLocation(downloadedPath.substringBeforeLast('/'))84 }85 true86 } else {87 false88 }89 }.getOrDefault(false)90 if (!installed) {91 InAppNotifications.post("Update download failed", asset.name)92 }93 refreshDownloaded(listOf(asset))94 }95 }9697 /** Hands the log to the platform share sheet (Mangayomi's Share.shareXFiles); falls back to revealing the folder. */98 fun shareLog(path: String) {99 val bytes = runCatching { files.readBytes(path) }.getOrDefault(ByteArray(0))100 val shared = bytes.isNotEmpty() && shareImage(bytes, "yokan.log", "text/plain")101 if (!shared) files.openLocation(path.substringBeforeLast('/'))102 }103104 fun shareCrashReport() {105 val report = _state.value.crashReport ?: return106 val shared = shareImage(report.encodeToByteArray(), "yokan-crash-report.txt", "text/plain")107 if (!shared) files.openLocation(files.cacheRoot)108 }109110 fun deleteCrashReport() {111 CrashReportStore.delete(files)112 _state.update { it.copy(crashReport = null) }113 }114115 private fun assetPath(asset: ReleaseAsset) = "${files.cacheRoot}/updates/${asset.name}"116117 private suspend fun refreshDownloaded(assets: List<ReleaseAsset>) {118 val present = withContext(workDispatcher) { assets.associate { it.name to files.exists(assetPath(it)) } }119 _state.update { s -> s.copy(downloadedAssets = s.downloadedAssets - present.keys + present.filterValues { it }.keys) }120 }121}122123/** Release assets listed under the check-for-update row. */124internal const val ShownAssets = 5125