package eu.friedcutlet.yokan.ui.screens.activity import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.LibraryIndex import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.observeSnapshot import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.data.toDomain import eu.friedcutlet.yokan.data.toDomainMangas import eu.friedcutlet.yokan.database.DbUpdatesFilter import eu.friedcutlet.yokan.database.DbActivityPreferences import eu.friedcutlet.yokan.domain.Category import eu.friedcutlet.yokan.domain.normalizeScanlator import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbUpdateError import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.UpdateEntry import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.download.ChapterDownloads import eu.friedcutlet.yokan.services.library.LibraryUpdateController import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch /** One Updates row with its title, chapter and download resolved once per data change. */ data class UpdateRowModel( val update: UpdateEntry, val manga: Manga?, val chapter: Chapter?, val download: DbDownload?, ) { val title: String = manga?.name?.takeIf { it.isNotBlank() } ?: update.title val chapterName: String = chapter?.name?.takeIf { it.isNotBlank() } ?: update.chapterName val isRead: Boolean = chapter?.isRead ?: update.isRead } data class UpdatesState( /** Rows per item type, newest first. */ val rowsByType: Map> = emptyMap(), /** Latest update time of a favourite, non-local title per item type; absent when never updated. */ val lastUpdatedAt: Map = emptyMap(), val dateFormat: String = "", val relativeTimestamps: Int = 0, val hasUpdateErrors: Boolean = false, val refreshing: Boolean = false, /** Errors of the last manual refresh; non-null shows the failure dialog. */ val failedUpdates: List? = null, val categoriesByType: Map> = emptyMap(), val filters: DbActivityPreferences = DbActivityPreferences(), ) private class UpdatesSource( val updates: List, val titles: Map, val lastUpdatedAt: Map, val categories: Map>, ) private data class UpdatesPreferences( val filters: DbActivityPreferences, val scanlators: Map>, ) class UpdatesViewModel( private val repository: YokanRepository, private val settings: SettingsStore, libraryIndex: LibraryIndexStore, private val libraryUpdates: LibraryUpdateController, private val downloads: ChapterDownloads, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow(UpdatesState()) val state: StateFlow = _state.asStateFlow() init { val source = repository.observeSnapshot({ listOf(it.updates, it.mangas, it.settings.titleMetadata, it.categories) }, workDispatcher) { snapshot -> val titles = snapshot.mangas.toDomainMangas(snapshot.settings).associateBy { it.id } UpdatesSource( updates = snapshot.updates.mapNotNull { update -> val id = update.mangaId ?: return@mapNotNull null val manga = titles[id] UpdateEntry(update.id, id, update.chapterId ?: 0L, manga?.itemType ?: ItemType.Manga, manga?.name.orEmpty(), update.chapterName.orEmpty(), manga?.source.orEmpty(), update.date.orEmpty(), false, update.updatedAt) }, titles = titles, lastUpdatedAt = titles.values.groupBy { it.itemType }.mapNotNull { (type, list) -> lastLibraryUpdate(list)?.let { type to it } }.toMap(), categories = snapshot.categories.map { it.toDomain() }.groupBy { it.forItemType } .mapValues { (_, values) -> values.sortedBy { it.position } }, ) } val downloadRecords = repository.observeSnapshot({ it.downloads }, workDispatcher) { it.downloads } viewModelScope.launch { val rows = combine(source, libraryIndex.index.filter { it !== LibraryIndex.Empty }, downloadRecords) { data, index, records -> Triple(data, buildUpdateRows(data.updates, data.titles, index, records), index.downloadedChapterIds) } val preferences = settings.db.map { db -> UpdatesPreferences(DbActivityPreferences(updates = db.features.activity.updates), db.filterScanlatorList.orEmpty().mapNotNull { entry -> entry.mangaId?.let { id -> id to entry.scanlators.orEmpty().map(::normalizeScanlator).toSet() } }.distinctBy { it.first }.toMap()) }.distinctUntilChanged() combine(rows, preferences) { (data, built, downloaded), prefs -> Triple(data, built.mapValues { (type, values) -> filterUpdateRows(values, prefs.filters.updates(type.toDb()), data.categories[type].orEmpty(), downloaded, prefs.scanlators) }, prefs.filters) }.flowOn(workDispatcher) .collect { (data, filtered, filters) -> _state.update { it.copy(rowsByType = filtered, lastUpdatedAt = data.lastUpdatedAt, categoriesByType = data.categories, filters = filters) } } } viewModelScope.launch { settings.db.collect { db -> _state.update { it.copy( dateFormat = db.dateFormat, relativeTimestamps = db.relativeTimesTamps, hasUpdateErrors = db.updateErrors.orEmpty().isNotEmpty(), ) } } } } fun updateFilters(type: ItemType, transform: (DbUpdatesFilter) -> DbUpdatesFilter) { settings.updateDb { db -> db.copy(features = db.features.copy(activity = db.features.activity.let { prefs -> prefs.withUpdates(type.toDb(), transform(prefs.updates(type.toDb()))) })) } } fun refresh(itemType: ItemType) { if (state.value.refreshing) return _state.update { it.copy(refreshing = true) } viewModelScope.launch { val errors = catchingNonCancellation { libraryUpdates.run(itemType) }.getOrNull()?.errors.orEmpty() _state.update { it.copy(refreshing = false, failedUpdates = errors.ifEmpty { it.failedUpdates }) } } } fun dismissFailedUpdates() { _state.update { it.copy(failedUpdates = null) } } fun clearUpdates(itemType: ItemType) { repository.clearUpdates(itemType) } fun download(row: UpdateRowModel) { val manga = row.manga ?: return val chapter = row.chapter ?: return downloads.enqueue(manga, chapter, destinationRoot = null) } fun cancelDownload(downloadId: Long) { downloads.cancel(downloadId) } fun removeDownload(downloadId: Long) { downloads.remove(downloadId) } fun openDownloadLocation(downloadId: Long) { downloads.openLocation(downloadId) } } private fun lastLibraryUpdate(titles: List): Long? = titles.asSequence() .filter { it.favorite && !it.isLocalArchive } .maxOfOrNull { it.lastUpdateMillis } ?.takeIf { it > 0L } /** * Resolves every update's title, chapter and first download record once, grouped by item type and * sorted newest first. The chapter is looked up only when the title still exists. */ internal fun buildUpdateRows( updates: List, titles: Map, index: LibraryIndex, downloads: List, ): Map> { val downloadByChapter = HashMap() for (download in downloads) { val chapterId = download.chapterId ?: continue if (chapterId !in downloadByChapter) downloadByChapter[chapterId] = download } // Resolve each chapter once, including long-running titles with thousands of update records. val chaptersByTitle = HashMap>() return updates.sortedByDescending { it.updatedAt } .groupBy { it.itemType } .mapValues { (_, entries) -> entries.map { update -> val manga = titles[update.mangaId] UpdateRowModel( update = update, manga = manga, chapter = manga?.let { title -> chaptersByTitle.getOrPut(title.id) { index.chapters(title.id).associateBy { it.id } }[update.chapterId] }, download = downloadByChapter[update.chapterId], ) } } }