package eu.friedcutlet.yokan.ui.screens.settings.about import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.logging.CrashReportStore import eu.friedcutlet.yokan.services.notifications.InAppNotifications import eu.friedcutlet.yokan.services.updates.ReleaseAsset import eu.friedcutlet.yokan.services.updates.ReleaseInfo import eu.friedcutlet.yokan.services.updates.YOKAN_VERSION import eu.friedcutlet.yokan.services.updates.fetchLatestRelease import eu.friedcutlet.yokan.services.updates.installPackageFromFile import eu.friedcutlet.yokan.services.updates.isNewerVersion import eu.friedcutlet.yokan.ui.screens.reader.shareImage import kotlinx.coroutines.CoroutineDispatcher import eu.friedcutlet.yokan.services.blockingDispatcher import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext internal data class AboutSettingsState( val checkingUpdate: Boolean = false, val release: ReleaseInfo? = null, val updateMessage: String? = null, /** Names of shown release assets already present in the update cache. */ val downloadedAssets: Set = emptySet(), val crashReport: String? = null, ) internal class AboutSettingsViewModel( private val http: HttpService, private val files: LocalFileService, private val workDispatcher: CoroutineDispatcher = blockingDispatcher, private val share: (ByteArray, String, String) -> Boolean = ::shareImage, ) : ViewModel() { private val _state = MutableStateFlow(AboutSettingsState()) val state: StateFlow = _state.asStateFlow() init { viewModelScope.launch { val report = withContext(workDispatcher) { CrashReportStore.read(files) } _state.update { it.copy(crashReport = report) } } } fun checkForUpdate() { if (_state.value.checkingUpdate) return _state.update { it.copy(checkingUpdate = true, updateMessage = "Searching…") } viewModelScope.launch { val info = fetchLatestRelease(http) val newer = info?.takeIf { isNewerVersion(it.tag) } _state.update { it.copy( release = newer, downloadedAssets = emptySet(), updateMessage = when { info == null -> "Network error" newer != null -> "Update available: ${info.tag} • ${info.assets.size} assets" else -> "You're up to date ($YOKAN_VERSION)" }, checkingUpdate = false, ) } newer?.let { refreshDownloaded(it.assets.take(ShownAssets)) } } } fun downloadAsset(asset: ReleaseAsset) { viewModelScope.launch { val downloadedPath = assetPath(asset) val installed = catchingNonCancellation { val response = http.request(HttpRequest(asset.url)) if (response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) { withContext(workDispatcher) { files.writeBytes(downloadedPath, response.bodyBytes) } // Android launches the package installer; other // platforms reveal the artifact for manual install. if (!installPackageFromFile(downloadedPath)) { files.openLocation(downloadedPath.substringBeforeLast('/')) } true } else { false } }.getOrDefault(false) if (!installed) { InAppNotifications.post("Update download failed", asset.name) } refreshDownloaded(listOf(asset)) } } /** Hands the log to the platform share sheet (Mangayomi's Share.shareXFiles); falls back to revealing the folder. */ fun shareLog(path: String) { viewModelScope.launch { val bytes = catchingNonCancellation { withContext(workDispatcher) { files.readBytesAsync(path) } }.getOrDefault(ByteArray(0)) currentCoroutineContext().ensureActive() val shared = bytes.isNotEmpty() && share(bytes, "yokan.log", "text/plain") if (!shared) files.openLocation(path.substringBeforeLast('/')) } } fun shareCrashReport() { val report = _state.value.crashReport ?: return val shared = share(report.encodeToByteArray(), "yokan-crash-report.txt", "text/plain") if (!shared) files.openLocation(files.cacheRoot) } fun deleteCrashReport() { viewModelScope.launch { withContext(workDispatcher) { CrashReportStore.delete(files) } _state.update { it.copy(crashReport = null) } } } private fun assetPath(asset: ReleaseAsset) = "${files.cacheRoot}/updates/${asset.name}" private suspend fun refreshDownloaded(assets: List) { val present = withContext(workDispatcher) { assets.associate { it.name to files.exists(assetPath(it)) } } _state.update { s -> s.copy(downloadedAssets = s.downloadedAssets - present.keys + present.filterValues { it }.keys) } } } /** Release assets listed under the check-for-update row. */ internal const val ShownAssets = 5