Yokan / rebuild
Course 1 8624561

HomeModels.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeModels.kt

implementation211 lines
1package eu.friedcutlet.yokan.ui.screens.home23import androidx.compose.runtime.Immutable4import eu.friedcutlet.yokan.data.toDomainChapter5import eu.friedcutlet.yokan.data.toDomainMangas6import eu.friedcutlet.yokan.database.*7import eu.friedcutlet.yokan.domain.ItemType8import eu.friedcutlet.yokan.domain.Manga9import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue10import eu.friedcutlet.yokan.services.discovery.DiscoveryMedia11import eu.friedcutlet.yokan.services.discovery.TmdbSeed12import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId13import eu.friedcutlet.yokan.services.tracking.tmdbMediaOf14import eu.friedcutlet.yokan.ui.navigation.hiddenNavigationSections15import eu.friedcutlet.yokan.ui.navigation.librarySection16import eu.friedcutlet.yokan.services.library.readingChapterSequence1718@Immutable19internal data class HomeCard(20    val media: DiscoveryMedia,21    val mangaId: Long? = null,22    val chapterId: Long? = null,23    val coverBytes: ByteArray? = null,24    val completed: Boolean = false,25    val chapterName: String? = null,26    val position: Long = 0,27    val progress: Float? = null,28    val novelProgress: Float? = null,29)3031internal data class HomeLocalData(32    val library: List<HomeCard> = emptyList(),33    val resume: List<HomeCard> = emptyList(),34    val seed: HomeCard? = null,35    val titlesByTypeAndName: Map<Pair<ItemType, String>, Manga> = emptyMap(),36    val titlesBySourceUrl: Map<Pair<Long?, String>, Manga> = emptyMap(),37    val sources: List<DbSource> = emptyList(),38    val presets: List<DbSavedSearch> = emptyList(),39    val hiddenTypes: Set<ItemType> = emptySet(),40    /** Most recently updated/watched TMDB-tracked titles feeding [HomeSection.TmdbRecommended]. */41    val tmdbSeeds: List<TmdbSeed> = emptyList(),42    /** Every TMDB-tracked [TmdbSeed.key]; never recommended back. */43    val tmdbTracked: Set<String> = emptySet(),44)4546internal data class HomeRemoteShelf(47    val id: String,48    val section: HomeSection,49    val items: List<DiscoveryMedia> = emptyList(),50    val loading: Boolean = false,51    val issue: DiscoveryIssue? = null,52    val sourceName: String? = null,53)5455internal data class HomeShelf(56    val id: String,57    val section: HomeSection,58    val cards: List<HomeCard>,59    val loading: Boolean = false,60    val issue: DiscoveryIssue? = null,61    val sourceName: String? = null,62)6364internal data class HomeState(65    val preferences: DbHomePreferences = DbHomePreferences(),66    val shelves: List<HomeShelf> = emptyList(),67    val featured: List<HomeCard> = emptyList(),68    val seedTitle: String? = null,69    val sources: List<DbSource> = emptyList(),70    val presets: List<DbSavedSearch> = emptyList(),71    val feeds: List<DbHomeSourceFeed> = emptyList(),72    val tmdbConfigured: Boolean = false,73    val refreshing: Boolean = false,74    val customizeOpen: Boolean = false,75    val searchOpen: Boolean = false,76    val searchQuery: String = "",77    val openIssue: DiscoveryIssue? = null,78)7980internal fun ItemType.homeKind(): HomeMediaFilter = when (this) {81    ItemType.Manga -> HomeMediaFilter.Manga82    ItemType.Anime -> HomeMediaFilter.Anime83    ItemType.Novel -> HomeMediaFilter.Novel84}8586internal fun projectHomeLocal(snapshot: YokanDatabaseSnapshot, trackerScoreRanges: Map<Int, IntRange> = emptyMap()): HomeLocalData {87    val settings = snapshot.settings88    val hidden = hiddenNavigationSections(settings)89    val hiddenTypes = ItemType.entries.filterTo(mutableSetOf()) { it.librarySection() in hidden }90    val blockedSources = snapshot.sources.filter { !settings.showNsfw && it.isNsfw }.mapTo(mutableSetOf()) { it.id }91    val mangas = snapshot.mangas.toDomainMangas(settings).filter { it.itemType !in hiddenTypes && it.sourceId !in blockedSources }92    val byId = mangas.associateBy { it.id }93    val chapters = snapshot.chapters.groupBy { it.mangaId }94    val pageCounts = snapshot.pageCache.associate { it.chapterId to it.urls.orEmpty().size }95    val downloads = snapshot.downloads.filter { it.isDownload == true }.mapNotNullTo(mutableSetOf()) { it.chapterId }96    val scores = snapshot.tracks.groupBy { it.mangaId }.mapValues { (_, rows) -> rows.mapNotNull { track ->97        eu.friedcutlet.yokan.services.tracking.normalizedTrackerScore(track.syncId, track.score,98            trackerScoreRanges[track.syncId]?.last ?: eu.friedcutlet.yokan.services.tracking.trackerScoreMaximum(track.syncId))99    }.average().takeIf { !it.isNaN() } }100    fun card(manga: Manga): HomeCard = HomeCard(101        media = DiscoveryMedia("library:${manga.id}", manga.name, manga.itemType.homeKind(), manga.imageUrl,102            description = manga.description, genres = manga.genres, rating = scores[manga.id], aliases = manga.alternativeTitles),103        mangaId = manga.id, coverBytes = manga.customCoverImage,104        completed = chapters[manga.id].orEmpty().let { it.isNotEmpty() && it.all { chapter -> chapter.isRead } },105    )106    val recent = snapshot.histories.sortedByDescending { it.updatedAt }.distinctBy { it.mangaId }107    val resume = recent.mapNotNull { history ->108        val manga = byId[history.mangaId] ?: return@mapNotNull null109        val all = chapters[manga.id].orEmpty().map(::toDomainChapter)110        val current = all.firstOrNull { it.id == history.chapterId } ?: return@mapNotNull null111        val sequence = readingChapterSequence(manga, current.id, all, settings, downloads)112        val chapter = if (!current.isRead) sequence.firstOrNull { it.id == current.id } else {113            val index = sequence.indexOfFirst { it.id == current.id }114            sequence.drop(index + 1).firstOrNull { !it.isRead }115        } ?: return@mapNotNull null116        val position = chapter.lastPageRead.toLongOrNull()?.coerceAtLeast(0) ?: 0L117        val totalPages = pageCounts[chapter.id] ?: 0118        card(manga).copy(chapterId = chapter.id, chapterName = chapter.name, position = position,119            novelProgress = if (manga.itemType == ItemType.Novel) chapter.lastPageRead.toFloatOrNull()?.coerceIn(0f, 1f) ?: 0f else null,120            progress = when {121                manga.itemType == ItemType.Novel -> chapter.lastPageRead.toFloatOrNull()?.coerceIn(0f, 1f)122                manga.itemType == ItemType.Manga && totalPages > 0 -> ((position + 1f) / totalPages).coerceIn(0f, 1f)123                else -> null124            })125    }.take(24)126    val index = buildMap {127        mangas.sortedByDescending { it.favorite }.forEach { manga ->128            (listOf(manga.name) + manga.alternativeTitles).forEach { name ->129                val key = manga.itemType to normalizedHomeTitle(name)130                if (key !in this) put(key, manga)131            }132        }133    }134    val tmdbTracks = snapshot.tracks.mapNotNull { track ->135        if (track.syncId != TmdbTrackerSyncId) null else tmdbMediaOf(track)?.let { (type, id) -> track to TmdbSeed(type, id) }136    }137    val lastWatched = recent.associate { it.mangaId to it.updatedAt }138    return HomeLocalData(139        library = mangas.filter { it.favorite && it.parentId == null }.sortedByDescending { it.lastReadMillis }.map(::card),140        resume = resume,141        seed = recent.firstNotNullOfOrNull { byId[it.mangaId]?.let(::card) },142        titlesByTypeAndName = index,143        titlesBySourceUrl = mangas.associateBy { it.sourceId to it.link },144        sources = snapshot.sources.filter { it.isAdded && it.isActive && (settings.showNsfw || !it.isNsfw) },145        presets = settings.savedSearches.orEmpty(), hiddenTypes = hiddenTypes,146        tmdbSeeds = tmdbTracks.filter { (track, _) -> track.mangaId in byId }147            .sortedByDescending { (track, _) -> maxOf(track.updatedAt, lastWatched[track.mangaId] ?: 0L) }148            .map { it.second }.distinct().take(TmdbSeedLimit),149        tmdbTracked = tmdbTracks.mapTo(mutableSetOf()) { it.second.key },150    )151}152153private const val TmdbSeedLimit = 8154155internal fun normalizedHomeTitle(title: String): String = title.trim().lowercase().replace(Regex("\\s+"), " ")156157internal fun buildHomeState(local: HomeLocalData, remote: List<HomeRemoteShelf>, settings: DbSettings): HomeState {158    val prefs = settings.home159    val limit = prefs.itemsPerShelf.coerceIn(6, 24)160    val libraryById = local.library.associateBy { it.mangaId }161    fun match(media: DiscoveryMedia): HomeCard {162        val manga = if (media.sourceId != null) local.titlesBySourceUrl[media.sourceId to media.sourceUrl.orEmpty()] else163            (listOf(media.title) + media.aliases).firstNotNullOfOrNull {164            local.titlesByTypeAndName[media.itemType to normalizedHomeTitle(it)]165        }166        return HomeCard(media, manga?.id, coverBytes = manga?.customCoverImage, completed = libraryById[manga?.id]?.completed == true)167    }168    fun visible(card: HomeCard) = card.media.itemType !in local.hiddenTypes &&169        (prefs.filter == HomeMediaFilter.All || prefs.filter == card.media.kind) && (!prefs.hideCompleted || !card.completed)170    fun sectionKind(section: HomeSection): HomeMediaFilter? = when (section) {171        HomeSection.PopularAnime -> HomeMediaFilter.Anime172        HomeSection.PopularManga -> HomeMediaFilter.Manga173        HomeSection.PopularNovels -> HomeMediaFilter.Novel174        HomeSection.PopularMovies -> HomeMediaFilter.Movie175        HomeSection.PopularSeries -> HomeMediaFilter.Series176        HomeSection.BecauseYouRead -> local.seed?.media?.kind177        else -> null178    }179    val remoteShelves = remote.filter { it.section !in prefs.hiddenSections &&180        (prefs.filter == HomeMediaFilter.All || sectionKind(it.section) == null || sectionKind(it.section) == prefs.filter) &&181        sectionKind(it.section)?.let { kind -> DiscoveryMedia("", "", kind).itemType !in local.hiddenTypes } != false &&182        (it.section != HomeSection.TmdbRecommended || (prefs.filter in TmdbFilters && ItemType.Anime !in local.hiddenTypes))183    }.map { shelf ->184        // Source feeds honour Browse's per-type "hide entries already in library" (re-applied on every settings/library change).185        fun hiddenInLibrary(card: HomeCard) = shelf.section == HomeSection.Sources && card.mangaId in libraryById &&186            settings.features.browse.hidesLibrary(card.media.itemType)187        // TMDB recommendations never suggest what the user already tracks or keeps in the library.188        fun known(card: HomeCard) = shelf.section == HomeSection.TmdbRecommended &&189            (card.media.key in local.tmdbTracked || card.mangaId in libraryById)190        HomeShelf(shelf.id, shelf.section, shelf.items.map(::match).filter { visible(it) && !hiddenInLibrary(it) && !known(it) }191            .distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }.take(limit),192            shelf.loading, shelf.issue, shelf.sourceName)193    }194    val seedGenres = local.seed?.media?.genres.orEmpty().mapTo(mutableSetOf()) { it.lowercase() }195    val recommendationCandidates = remote.flatMap { it.items }.map(::match) + local.library196    val recommended = recommendationCandidates.filter(::visible).filter { it.mangaId == null || it.mangaId != local.seed?.mangaId }197        .distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }198        .sortedByDescending { card -> card.media.genres.count { it.lowercase() in seedGenres } }.take(limit)199    val shelves = buildList {200        if (HomeSection.Continue !in prefs.hiddenSections) add(HomeShelf("continue", HomeSection.Continue, local.resume.filter(::visible).take(limit)))201        if (HomeSection.Recommended !in prefs.hiddenSections) add(HomeShelf("recommended", HomeSection.Recommended, recommended,202            loading = remote.any { it.loading } && recommended.isEmpty()))203        addAll(remoteShelves)204    }205    val featuredPool = if (prefs.featuredLibraryOnly) local.library else local.resume + recommended + remoteShelves.flatMap { it.cards }206    val featured = if (prefs.showFeatured) featuredPool.filter(::visible).distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }.take(7) else emptyList()207    return HomeState(prefs.forPresentation(), shelves, featured, local.seed?.media?.title, local.sources, local.presets,208        prefs.sourceFeeds, prefs.tmdbReadAccessToken.isNotBlank(), remote.any { it.loading })209}210211private val TmdbFilters = setOf(HomeMediaFilter.All, HomeMediaFilter.Movie, HomeMediaFilter.Series)212

Search chapters, reference and source filenames.