YokanRepository.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/YokanRepository.kt
1package eu.friedcutlet.yokan.data23import kotlin.coroutines.CoroutineContext4import eu.friedcutlet.yokan.database.DbDownload5import eu.friedcutlet.yokan.database.DbPageUrl6import eu.friedcutlet.yokan.database.DbRepo7import eu.friedcutlet.yokan.database.DbSettings8import eu.friedcutlet.yokan.database.DbSource9import eu.friedcutlet.yokan.database.DbSyncPreference10import eu.friedcutlet.yokan.database.DbTrackSearch11import eu.friedcutlet.yokan.database.DbTrackStatus12import eu.friedcutlet.yokan.domain.Category13import eu.friedcutlet.yokan.domain.Chapter14import eu.friedcutlet.yokan.domain.History15import eu.friedcutlet.yokan.domain.ItemType16import eu.friedcutlet.yokan.domain.Manga17import eu.friedcutlet.yokan.domain.Source18import eu.friedcutlet.yokan.domain.Track19import eu.friedcutlet.yokan.domain.UpdateEntry20import eu.friedcutlet.yokan.domain.UserSettings21import eu.friedcutlet.yokan.services.extensions.RemoteDetail22import eu.friedcutlet.yokan.services.extensions.RemoteManga23import eu.friedcutlet.yokan.services.metadata.LocalMetadataField24import eu.friedcutlet.yokan.services.metadata.MetadataMedia25import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot26import eu.friedcutlet.yokan.util.nowMillis27import kotlinx.coroutines.Dispatchers28import kotlinx.coroutines.flow.Flow29import kotlinx.coroutines.flow.StateFlow30import kotlinx.coroutines.flow.distinctUntilChangedBy31import kotlinx.coroutines.flow.flowOn32import kotlinx.coroutines.flow.map3334interface YokanRepository {35 val snapshots: StateFlow<YokanDatabaseSnapshot>36 fun settings(): UserSettings37 fun dbSettings(): DbSettings38 fun updateSettings(transform: (UserSettings) -> UserSettings): UserSettings39 fun updateDbSettings(transform: (DbSettings) -> DbSettings): DbSettings40 fun syncPreference(syncId: Long = 1): DbSyncPreference41 fun updateSyncPreference(syncId: Long = 1, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference42 fun library(itemType: ItemType): List<Manga>43 fun chapters(mangaId: Long): List<Chapter>4445 /**46 * Returns every chapter in one call. Filter / sort paths that iterate47 * the entire library use this once and group by mangaId in-memory —48 * cheaper than 6 000 separate `chapters(id)` calls.49 */50 fun allChapters(): List<Chapter>51 fun categories(itemType: ItemType): List<Category>52 fun createCategory(itemType: ItemType, name: String): Category53 fun updateCategory(categoryId: Long, name: String? = null, hidden: Boolean? = null, shouldUpdate: Boolean? = null): Category?54 fun moveCategory(itemType: ItemType, categoryId: Long, offset: Int)55 fun removeCategory(categoryId: Long)56 fun sources(itemType: ItemType): List<Source>57 fun source(sourceId: Long): Source?58 fun setSourceActive(sourceId: Long, active: Boolean)59 fun setSourcePinned(sourceId: Long, pinned: Boolean)60 fun setSourceAdded(sourceId: Long, added: Boolean)61 fun markSourceUsed(sourceId: Long)62 fun updateSourceCode(sourceId: Long, code: String)63 fun removeSource(sourceId: Long)64 fun repositories(itemType: ItemType): List<DbRepo>65 fun upsertRepository(itemType: ItemType, repo: DbRepo)66 fun removeRepository(itemType: ItemType, jsonUrl: String)67 fun allTitles(itemType: ItemType): List<Manga>68 fun manga(mangaId: Long): Manga?69 fun history(): List<History>70 fun updates(): List<UpdateEntry>71 fun tracks(): List<Track>72 fun downloads(): List<DbDownload>73 fun removeDownload(downloadId: Long)74 fun cancelDownload(downloadId: Long)75 fun clearChapterDownloads(chapterIds: Set<Long>)76 /** The saved page list as stored, fresh or not; readers go through `ChapterPageResolver`. */77 fun pageUrls(chapterId: Long): List<DbPageUrl>7879 /** Saves [pageUrls] as fetched from [source] at [fetchedAt], minus Cookie/Authorization headers. */80 fun cachePageUrls(81 chapterId: Long,82 chapterUrl: String,83 pageUrls: List<DbPageUrl>,84 source: DbSource? = null,85 fetchedAt: Long = nowMillis(),86 )87 fun clearPageCache()88 fun upsertRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean? = null): Manga89 fun upsertRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean? = null): Manga90 fun applyMetadata(mangaId: Long, metadata: MetadataMedia): Manga?91 fun applyLocalMetadataFields(mangaId: Long, metadata: MetadataMedia, fields: Set<LocalMetadataField>): Manga?92 /** Notes may be edited only while the title is in the library. */93 fun setMangaPrivateNote(mangaId: Long, note: String): Manga?94 fun setMangaDisplayTitle(mangaId: Long, title: String): Manga?95 fun setMangaCustomCover(mangaId: Long, bytes: ByteArray): Manga?96 /** An explicit choice; [favorite] adds the entry in the same transaction, without applying defaults. */97 fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean = false)98 fun setLibraryEntriesRead(mangaIds: Set<Long>, isRead: Boolean)99 /** Active consumption protects files from cleanup and triggers configured download-ahead. */100 fun chapterOpened(chapterId: Long) = Unit101 fun chapterClosed(chapterId: Long) = Unit102 /** Completion observed by a reader/player, distinct from manual read state and progress saves. */103 fun recordChapterConsumption(chapterIds: Set<Long>) = Unit104 fun setChaptersRead(105 chapterIds: Set<Long>,106 isRead: Boolean,107 lastPageRead: String? = null,108 readingTimeSeconds: Int = 0,109 autoReadDuplicates: Boolean = false,110 )111 fun setChaptersBookmarked(chapterIds: Set<Long>, bookmarked: Boolean)112 /** Manual filler mark that wins over the source value; null clears it. */113 fun setChaptersFillerOverride(chapterIds: Set<Long>, filler: Boolean?)114 fun setMangaFavorite(mangaId: Long, favorite: Boolean)115116 /**117 * Persist a per-manga "smart update" cadence. `null` or `0` means always118 * eligible for library updates; positive values are interpreted by119 * `DefaultLibraryUpdaterService.shouldRefresh` as a cooldown in days.120 */121 fun setMangaSmartUpdateDays(mangaId: Long, days: Int?)122 fun removeLibraryEntries(mangaIds: Set<Long>)123 fun deleteChapters(chapterIds: Set<Long>)124 fun setUpdateRead(updateId: Long, isRead: Boolean)125 fun clearUpdates(itemType: ItemType)126 fun removeHistory(historyId: Long)127 fun clearHistory(itemType: ItemType)128 fun clearLibrary(itemType: ItemType)129 /** Deletes local/archive titles and their dependent reading records. */130 fun clearLocalLibrary(): Int131 /**132 * Removes non-favorited entries (cached browsing results that were never133 * added to the library) and their chapter data. Returns the number of134 * entries deleted.135 */136 fun cleanDatabase(): Int137 /**138 * Conservative variant of [cleanDatabase] run automatically at app launch:139 * removes non-favorited titles only when the user never interacted with140 * them (no history, no downloads, no tracking) along with their chapters.141 * Returns the number of entries deleted.142 */143 fun pruneBrowsedTitles(): Int144 /** Binds locally; remote trackers then fetch-or-create their list entry. */145 fun bindTrack(mangaId: Long, search: DbTrackSearch, itemType: ItemType)146 fun updateTrack(trackId: Long, progress: Int, status: DbTrackStatus, score: Int)147148 /** [removeRemote] also deletes the provider's list entry where the tracker supports it. */149 fun removeTrack(trackId: Long, removeRemote: Boolean = false)150151 /** Pulls the remote state of [mangaId]'s bound trackers and syncs enhanced (server) progress both ways. */152 fun refreshTracks(mangaId: Long) {}153}154155/**156 * Re-reads [read] off the main thread whenever the snapshot parts selected by [key] change, e.g.157 * `repository.observe({ it.histories }) { history() }`. Unchanged parts keep their list instance, so158 * the key comparison short-circuits on reference equality and unrelated writes are skipped. Tests pass159 * their test dispatcher as [context] so the re-read stays on the test scheduler.160 */161fun <K, T> YokanRepository.observe(162 key: (YokanDatabaseSnapshot) -> K,163 context: CoroutineContext = Dispatchers.Default,164 read: YokanRepository.() -> T,165): Flow<T> = snapshots.distinctUntilChangedBy(key).map { read() }.flowOn(context)166167/** Derive a read model from the exact published revision whose dependencies changed. */168fun <K, T> YokanRepository.observeSnapshot(169 key: (YokanDatabaseSnapshot) -> K,170 context: CoroutineContext = Dispatchers.Default,171 read: (YokanDatabaseSnapshot) -> T,172): Flow<T> = snapshots.distinctUntilChangedBy(key).map(read).flowOn(context)173