UpdatesViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdatesViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.activity23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.LibraryIndex6import eu.friedcutlet.yokan.data.LibraryIndexStore7import eu.friedcutlet.yokan.data.SettingsStore8import eu.friedcutlet.yokan.data.YokanRepository9import eu.friedcutlet.yokan.data.observeSnapshot10import eu.friedcutlet.yokan.data.toDb11import eu.friedcutlet.yokan.data.toDomain12import eu.friedcutlet.yokan.data.toDomainMangas13import eu.friedcutlet.yokan.database.DbUpdatesFilter14import eu.friedcutlet.yokan.database.DbActivityPreferences15import eu.friedcutlet.yokan.domain.Category16import eu.friedcutlet.yokan.domain.normalizeScanlator17import eu.friedcutlet.yokan.database.DbDownload18import eu.friedcutlet.yokan.database.DbUpdateError19import eu.friedcutlet.yokan.domain.Chapter20import eu.friedcutlet.yokan.domain.ItemType21import eu.friedcutlet.yokan.domain.Manga22import eu.friedcutlet.yokan.domain.UpdateEntry23import eu.friedcutlet.yokan.services.catchingNonCancellation24import eu.friedcutlet.yokan.services.download.ChapterDownloads25import eu.friedcutlet.yokan.services.library.LibraryUpdateController26import kotlinx.coroutines.Dispatchers27import kotlinx.coroutines.flow.MutableStateFlow28import kotlinx.coroutines.flow.StateFlow29import kotlinx.coroutines.flow.asStateFlow30import kotlinx.coroutines.flow.combine31import kotlinx.coroutines.flow.flowOn32import kotlinx.coroutines.flow.map33import kotlinx.coroutines.flow.distinctUntilChanged34import kotlinx.coroutines.flow.filter35import kotlinx.coroutines.CoroutineDispatcher36import kotlinx.coroutines.flow.update37import kotlinx.coroutines.launch3839/** One Updates row with its title, chapter and download resolved once per data change. */40data class UpdateRowModel(41 val update: UpdateEntry,42 val manga: Manga?,43 val chapter: Chapter?,44 val download: DbDownload?,45) {46 val title: String = manga?.name?.takeIf { it.isNotBlank() } ?: update.title47 val chapterName: String = chapter?.name?.takeIf { it.isNotBlank() } ?: update.chapterName48 val isRead: Boolean = chapter?.isRead ?: update.isRead49}5051data class UpdatesState(52 /** Rows per item type, newest first. */53 val rowsByType: Map<ItemType, List<UpdateRowModel>> = emptyMap(),54 /** Latest update time of a favourite, non-local title per item type; absent when never updated. */55 val lastUpdatedAt: Map<ItemType, Long> = emptyMap(),56 val dateFormat: String = "",57 val relativeTimestamps: Int = 0,58 val hasUpdateErrors: Boolean = false,59 val refreshing: Boolean = false,60 /** Errors of the last manual refresh; non-null shows the failure dialog. */61 val failedUpdates: List<DbUpdateError>? = null,62 val categoriesByType: Map<ItemType, List<Category>> = emptyMap(),63 val filters: DbActivityPreferences = DbActivityPreferences(),64)6566private class UpdatesSource(67 val updates: List<UpdateEntry>,68 val titles: Map<Long, Manga>,69 val lastUpdatedAt: Map<ItemType, Long>,70 val categories: Map<ItemType, List<Category>>,71)7273private data class UpdatesPreferences(74 val filters: DbActivityPreferences,75 val scanlators: Map<Long, Set<String>>,76)7778class UpdatesViewModel(79 private val repository: YokanRepository,80 private val settings: SettingsStore,81 libraryIndex: LibraryIndexStore,82 private val libraryUpdates: LibraryUpdateController,83 private val downloads: ChapterDownloads,84 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,85) : ViewModel() {86 private val _state = MutableStateFlow(UpdatesState())87 val state: StateFlow<UpdatesState> = _state.asStateFlow()8889 init {90 val source = repository.observeSnapshot({ listOf(it.updates, it.mangas, it.settings.titleMetadata, it.categories) }, workDispatcher) { snapshot ->91 val titles = snapshot.mangas.toDomainMangas(snapshot.settings).associateBy { it.id }92 UpdatesSource(93 updates = snapshot.updates.mapNotNull { update ->94 val id = update.mangaId ?: return@mapNotNull null95 val manga = titles[id]96 UpdateEntry(update.id, id, update.chapterId ?: 0L, manga?.itemType ?: ItemType.Manga,97 manga?.name.orEmpty(), update.chapterName.orEmpty(), manga?.source.orEmpty(),98 update.date.orEmpty(), false, update.updatedAt)99 },100 titles = titles,101 lastUpdatedAt = titles.values.groupBy { it.itemType }.mapNotNull { (type, list) ->102 lastLibraryUpdate(list)?.let { type to it }103 }.toMap(),104 categories = snapshot.categories.map { it.toDomain() }.groupBy { it.forItemType }105 .mapValues { (_, values) -> values.sortedBy { it.position } },106 )107 }108 val downloadRecords = repository.observeSnapshot({ it.downloads }, workDispatcher) { it.downloads }109 viewModelScope.launch {110 val rows = combine(source, libraryIndex.index.filter { it !== LibraryIndex.Empty }, downloadRecords) { data, index, records ->111 Triple(data, buildUpdateRows(data.updates, data.titles, index, records), index.downloadedChapterIds)112 }113 val preferences = settings.db.map { db -> UpdatesPreferences(DbActivityPreferences(updates = db.features.activity.updates),114 db.filterScanlatorList.orEmpty().mapNotNull { entry -> entry.mangaId?.let { id ->115 id to entry.scanlators.orEmpty().map(::normalizeScanlator).toSet()116 } }.distinctBy { it.first }.toMap())117 }.distinctUntilChanged()118 combine(rows, preferences) { (data, built, downloaded), prefs ->119 Triple(data, built.mapValues { (type, values) -> filterUpdateRows(values, prefs.filters.updates(type.toDb()),120 data.categories[type].orEmpty(), downloaded, prefs.scanlators) }, prefs.filters)121 }.flowOn(workDispatcher)122 .collect { (data, filtered, filters) ->123 _state.update { it.copy(rowsByType = filtered, lastUpdatedAt = data.lastUpdatedAt,124 categoriesByType = data.categories, filters = filters) }125 }126 }127 viewModelScope.launch {128 settings.db.collect { db ->129 _state.update {130 it.copy(131 dateFormat = db.dateFormat,132 relativeTimestamps = db.relativeTimesTamps,133 hasUpdateErrors = db.updateErrors.orEmpty().isNotEmpty(),134 )135 }136 }137 }138 }139140 fun updateFilters(type: ItemType, transform: (DbUpdatesFilter) -> DbUpdatesFilter) {141 settings.updateDb { db -> db.copy(features = db.features.copy(activity = db.features.activity.let { prefs ->142 prefs.withUpdates(type.toDb(), transform(prefs.updates(type.toDb())))143 })) }144 }145146 fun refresh(itemType: ItemType) {147 if (state.value.refreshing) return148 _state.update { it.copy(refreshing = true) }149 viewModelScope.launch {150 val errors = catchingNonCancellation { libraryUpdates.run(itemType) }.getOrNull()?.errors.orEmpty()151 _state.update { it.copy(refreshing = false, failedUpdates = errors.ifEmpty { it.failedUpdates }) }152 }153 }154155 fun dismissFailedUpdates() {156 _state.update { it.copy(failedUpdates = null) }157 }158159 fun clearUpdates(itemType: ItemType) {160 repository.clearUpdates(itemType)161 }162163 fun download(row: UpdateRowModel) {164 val manga = row.manga ?: return165 val chapter = row.chapter ?: return166 downloads.enqueue(manga, chapter, destinationRoot = null)167 }168169 fun cancelDownload(downloadId: Long) {170 downloads.cancel(downloadId)171 }172173 fun removeDownload(downloadId: Long) {174 downloads.remove(downloadId)175 }176177 fun openDownloadLocation(downloadId: Long) {178 downloads.openLocation(downloadId)179 }180}181182private fun lastLibraryUpdate(titles: List<Manga>): Long? =183 titles.asSequence()184 .filter { it.favorite && !it.isLocalArchive }185 .maxOfOrNull { it.lastUpdateMillis }186 ?.takeIf { it > 0L }187188/**189 * Resolves every update's title, chapter and first download record once, grouped by item type and190 * sorted newest first. The chapter is looked up only when the title still exists.191 */192internal fun buildUpdateRows(193 updates: List<UpdateEntry>,194 titles: Map<Long, Manga>,195 index: LibraryIndex,196 downloads: List<DbDownload>,197): Map<ItemType, List<UpdateRowModel>> {198 val downloadByChapter = HashMap<Long, DbDownload>()199 for (download in downloads) {200 val chapterId = download.chapterId ?: continue201 if (chapterId !in downloadByChapter) downloadByChapter[chapterId] = download202 }203 // Resolve each chapter once, including long-running titles with thousands of update records.204 val chaptersByTitle = HashMap<Long, Map<Long, Chapter>>()205 return updates.sortedByDescending { it.updatedAt }206 .groupBy { it.itemType }207 .mapValues { (_, entries) ->208 entries.map { update ->209 val manga = titles[update.mangaId]210 UpdateRowModel(211 update = update,212 manga = manga,213 chapter = manga?.let { title -> chaptersByTitle.getOrPut(title.id) {214 index.chapters(title.id).associateBy { it.id }215 }[update.chapterId] },216 download = downloadByChapter[update.chapterId],217 )218 }219 }220}221