Yokan / rebuild
Course 1 8624561

domain-and-settings-models: file workbook

89 min readSnapshot 8624561Markdown

Implementation chapter · Coverage index

Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.

Pinned baseline for comparison. Use the reviewed listings in the implementation chapters and the reviewed source archive when reconstructing the app. See the architecture review for changes.

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DatabaseEntities.kt
  • Source · implementation · 675 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

7: enum class DbActionType {
18: enum class DbStatus {
31: enum class DbItemType {
38: enum class DbSourceCodeLanguage {
46: enum class DbTrackStatus {
59: enum class DbDisplayType {
67: enum class DbScaleType {
77: enum class DbBackgroundColor {
85: enum class DbReaderMode {
96: enum class DbNovelTextAlign {
104: enum class DbPageMode {
110: enum class DbSectionType {
117: enum class DbDebandingType {
124: enum class DbAudioChannel(val mpvName: String) {
133: enum class DbColorFilterBlendMode {
150: data class DbChangedPart(
164: data class DbOutboxOp(
176: data class DbCategory(
187: data class DbChapter(
223: internal fun DbChapter.mergeProgress(other: DbChapter): DbChapter = copy(
231: private fun mergePagePosition(first: String, second: String): String {
241: enum class DbFetchType { Seasons, Episodes }
244: data class DbCustomButton(
254: fun startupCode(primaryId: Long): String = interpolate(codeStartup, primaryId)
255: fun pressCode(primaryId: Long): String = interpolate(codePress.orEmpty(), primaryId)
256: fun longPressCode(primaryId: Long): String = interpolate(codeLongPress, primaryId)
258: private fun interpolate(code: String, primaryId: Long): String =
263: data class DbDownload(
278: data class DbHistory(
289: data class DbManga(
326: override fun toString(): String = "DbManga(id=$id)"
330: override fun equals(other: Any?): Boolean {
347: override fun hashCode(): Int = id.hashCode()
351: fun Collection<DbManga>.seasonsOwnedByLibrary(): Set<Long> {
353: fun owned(manga: DbManga, depth: Int): Boolean =
359: data class DbPageUrl(
366: data class DbRepo(
374: data class DbLocalFolder(
380: data class DbSource(
419: data class DbSyncPreference(
449: enum class SyncServerProvider {
459: data class DbTrack(
478: data class DbTrackPreference(
489: data class DbTrackSearch(
510: data class DbUpdate(
520: data class DbVideoTrack(
526: data class DbVideo(
538: data class DbCookie(
544: data class DbSortLibraryManga(
550: data class DbSortChapter(
557: data class DbChapterFilter(
564: data class DbChapterPageUrls(
577: data class DbChapterPageIndex(
583: data class DbPersonalReaderMode(
589: data class DbAutoScrollPages(
596: data class DbPersonalPageMode(
602: data class DbFilterScanlator(
608: data class DbL10nLocale(
614: data class DbCustomColorFilter(
622: data class DbPlayerSubtitleSettings(
641: data class DbAlgorithmWeights(
649: data class DbSourcePreference(
656: data class DbSavedSearch(
671: data class DbUpdateError(

How this file works

These are the serializable persistence records and enum values, separate from domain/UI models and Room row classes. Preserve names, constructor defaults and append-only ordinal-sensitive enums. DbChapter.effectiveFiller gives the user's nullable override precedence over the source value. The progress helpers merge user state while retaining the owning release's file location and position rules. Other records describe sources, downloads, trackers, cached pages, custom buttons and sync outbox data; these are later consumed by the database, repository and service chapters.

Exact file bytes / download · SHA-256 a930a16a04230aa8452524b780cdfcb9b484b3e0e3102200030b62d859fb5343.

Complete file

package eu.friedcutlet.yokan.database

import eu.friedcutlet.yokan.domain.Manga
import kotlinx.serialization.Serializable

@Serializable
enum class DbActionType {
    RemoveItem,
    RemoveCategory,
    RemoveChapter,
    RemoveHistory,
    RemoveUpdate,
    RemoveExtension,
    RemoveTrack,
}

@Serializable
enum class DbStatus {
    Ongoing,
    Completed,
    Canceled,
    Unknown,
    OnHiatus,
    PublishingFinished,
    // Append only: legacy metadata.json uses the original six ordinals.
    Licensed,
    Upcoming,
}

@Serializable
enum class DbItemType {
    Manga,
    Anime,
    Novel,
}

@Serializable
enum class DbSourceCodeLanguage {
    JavaScript,
    Mihon,
    LnReader,
    Aidoku,
}

@Serializable
enum class DbTrackStatus {
    Reading,
    Completed,
    OnHold,
    Dropped,
    PlanToRead,
    ReReading,
    Watching,
    PlanToWatch,
    ReWatching,
}

@Serializable
enum class DbDisplayType {
    CompactGrid,
    ComfortableGrid,
    CoverOnlyGrid,
    List,
}

@Serializable
enum class DbScaleType {
    FitScreen,
    Stretch,
    FitWidth,
    FitHeight,
    OriginalSize,
    SmartFit,
}

@Serializable
enum class DbBackgroundColor {
    Black,
    Grey,
    White,
    Automatic,
}

@Serializable
enum class DbReaderMode {
    Vertical,
    Ltr,
    Rtl,
    VerticalContinuous,
    Webtoon,
    HorizontalContinuous,
    HorizontalContinuousRtl,
}

@Serializable
enum class DbNovelTextAlign {
    Left,
    Center,
    Right,
    Block,
}

@Serializable
enum class DbPageMode {
    OnePage,
    DoublePage,
}

@Serializable
enum class DbSectionType {
    All,
    Anime,
    Manga,
}

@Serializable
enum class DbDebandingType {
    None,
    Cpu,
    Gpu,
}

@Serializable
enum class DbAudioChannel(val mpvName: String) {
    Auto("auto"),
    AutoSafe("auto-safe"),
    Mono("mono"),
    Stereo("stereo"),
    ReverseStereo("pan=[stereo|c0=c1|c1=c0]"),
}

@Serializable
enum class DbColorFilterBlendMode {
    None,
    Multiply,
    Screen,
    Overlay,
    ColorDodge,
    Lighten,
    ColorBurn,
    Darken,
    Difference,
    Saturation,
    SoftLight,
    Plus,
    Exclusion,
}

@Serializable
data class DbChangedPart(
    val id: Long = 0,
    val actionType: DbActionType,
    val isarId: Long? = null,
    val data: String,
    val clientDate: Long,
)

/**
 * One unpushed change for the hub: a path of one entity and its new JSON value
 * (`null` = path removed). Keyed by (kind, id, path) so repeated edits coalesce;
 * `seq` orders and `hlc` timestamps the write. See [eu.friedcutlet.yokan.database.sync.SyncPaths].
 */
@Serializable
data class DbOutboxOp(
    val kind: Int,
    val id: Long,
    val path: String,
    val value: String? = null,
    val hlc: Long,
    val seq: Long,
    /** Hub history epoch in which this local operation was created. */
    val epoch: Int = 0,
)

@Serializable
data class DbCategory(
    val id: Long = 0,
    val name: String,
    val forItemType: DbItemType,
    val position: Int? = null,
    val hidden: Boolean? = null,
    val shouldUpdate: Boolean? = null,
    val updatedAt: Long = 0,
)

@Serializable
data class DbChapter(
    val id: Long = 0,
    val mangaId: Long? = null,
    val name: String? = null,
    val url: String = "",
    val dateUpload: String = "",
    val scanlator: String = "",
    val isBookmarked: Boolean = false,
    val isRead: Boolean = false,
    val lastPageRead: String = "",
    val archivePath: String = "",
    val isFiller: Boolean = false,
    val thumbnailUrl: String? = null,
    val description: String? = null,
    val downloadSize: String? = null,
    val duration: String? = null,
    val updatedAt: Long = 0,
    /** First successful discovery/import, independent of reading progress and source upload time. */
    val fetchedAt: Long = 0,
    /** Explicit source numbering survives display-title changes; null preserves name recognition. */
    val number: Double? = null,
    val season: Int? = null,
    /** Original source label keeps release edition/language identity when metadata supplies a title. */
    val numberingName: String? = null,
    /** User filler mark; null follows the source/sidecar value kept in [isFiller]. */
    val fillerOverride: Boolean? = null,
)

/** The user's filler mark wins over the source value, which refresh paths keep writing to [DbChapter.isFiller]. */
val DbChapter.effectiveFiller: Boolean get() = fillerOverride ?: isFiller

/**
 * Folds [other]'s user state into this copy of the same chapter: read/bookmark marks are kept if
 * either has them, the furthest numeric page wins (otherwise the first non-blank position), the
 * user filler mark falls back to [other]'s, and [DbChapter.updatedAt] is the newer of the two.
 */
internal fun DbChapter.mergeProgress(other: DbChapter): DbChapter = copy(
    isRead = isRead || other.isRead,
    isBookmarked = isBookmarked || other.isBookmarked,
    lastPageRead = mergePagePosition(lastPageRead, other.lastPageRead),
    fillerOverride = fillerOverride ?: other.fillerOverride,
    updatedAt = maxOf(updatedAt, other.updatedAt),
)

private fun mergePagePosition(first: String, second: String): String {
    if (first.isBlank()) return second
    if (second.isBlank() || first == second) return first
    val firstNumber = first.toLongOrNull()
    val secondNumber = second.toLongOrNull()
    return if (firstNumber != null && secondNumber != null) maxOf(firstNumber, secondNumber).toString() else first
}

/** Animetail `FetchType`: a [Seasons] title lists child season titles instead of episodes. */
@Serializable
enum class DbFetchType { Seasons, Episodes }

@Serializable
data class DbCustomButton(
    val id: Long = 0,
    val title: String? = null,
    val codePress: String? = null,
    val codeLongPress: String = "",
    val codeStartup: String = "",
    val isFavourite: Boolean = false,
    val position: Int,
    val updatedAt: Long = 0,
) {
    fun startupCode(primaryId: Long): String = interpolate(codeStartup, primaryId)
    fun pressCode(primaryId: Long): String = interpolate(codePress.orEmpty(), primaryId)
    fun longPressCode(primaryId: Long): String = interpolate(codeLongPress, primaryId)

    private fun interpolate(code: String, primaryId: Long): String =
        code.replace("\$id", id.toString()).replace("\$isPrimary", (primaryId == id).toString())
}

@Serializable
data class DbDownload(
    val id: Long = 0,
    val chapterId: Long? = null,
    val succeeded: Int? = null,
    val failed: Int? = null,
    val total: Int? = null,
    val isDownload: Boolean? = null,
    val isStartDownload: Boolean? = null,
    val isPaused: Boolean = false,
    val storageLocation: String? = null,
    /** Device-local request options for restart recovery. */
    val requestJson: String? = null,
)

@Serializable
data class DbHistory(
    val id: Long = 0,
    val mangaId: Long? = null,
    val chapterId: Long? = null,
    val itemType: DbItemType,
    val date: String? = null,
    val updatedAt: Long = 0,
    val readingTimeSeconds: Int? = null,
)

@Serializable
data class DbManga(
    val id: Long = 0,
    val name: String? = null,
    val link: String? = null,
    val imageUrl: String? = null,
    val description: String? = null,
    val author: String? = null,
    val artist: String? = null,
    val status: DbStatus = DbStatus.Unknown,
    val itemType: DbItemType = DbItemType.Manga,
    val genre: List<String>? = null,
    val favorite: Boolean = false,
    val source: String? = null,
    val lang: String? = null,
    val dateAdded: Long? = null,
    val lastUpdate: Long? = null,
    val lastRead: Long = 0,
    val categories: List<Long>? = null,
    val isLocalArchive: Boolean = false,
    val customCoverImage: ByteArray? = null,
    val customCoverFromTracker: String? = null,
    val smartUpdateDays: Int? = null,
    val updatedAt: Long = 0,
    val sourceId: Long? = null,
    /** Private, local text. Excluded from every sync transport. */
    val privateNote: String = "",
    /** Provider-announced next episode airing time in epoch milliseconds; zero means unknown. */
    val nextEpisodeAiringAt: Long = 0,
    val nextEpisodeNumber: Int? = null,
    val airingScheduleUpdatedAt: Long = 0,
    val cast: List<eu.friedcutlet.yokan.domain.TitleCredit> = emptyList(),
    /** Owning Seasons-type title of this season record; null for top-level titles. */
    val parentId: Long? = null,
    val fetchType: DbFetchType = DbFetchType.Episodes,
    /** Source/folder season number; null when unknown (Animetail uses -1). */
    val seasonNumber: Double? = null,
) {
    override fun toString(): String = "DbManga(id=$id)"

    // Content equality (the array by content): snapshot StateFlows drop "equal" values, so an
    // id-only equals silently swallowed manga edits. hashCode stays on the id, which is consistent.
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is DbManga) return false
        return id == other.id && name == other.name && link == other.link && imageUrl == other.imageUrl &&
            description == other.description && author == other.author && artist == other.artist &&
            status == other.status && itemType == other.itemType && genre == other.genre &&
            favorite == other.favorite && source == other.source && lang == other.lang &&
            dateAdded == other.dateAdded && lastUpdate == other.lastUpdate && lastRead == other.lastRead &&
            categories == other.categories && isLocalArchive == other.isLocalArchive &&
            customCoverImage.contentEquals(other.customCoverImage) &&
            customCoverFromTracker == other.customCoverFromTracker && smartUpdateDays == other.smartUpdateDays &&
            updatedAt == other.updatedAt && sourceId == other.sourceId && privateNote == other.privateNote &&
            nextEpisodeAiringAt == other.nextEpisodeAiringAt && nextEpisodeNumber == other.nextEpisodeNumber &&
            airingScheduleUpdatedAt == other.airingScheduleUpdatedAt && cast == other.cast &&
            parentId == other.parentId && fetchType == other.fetchType && seasonNumber == other.seasonNumber
    }

    override fun hashCode(): Int = id.hashCode()
}

/** Season records whose parent chain reaches a library title; cache cleanup must keep them. */
fun Collection<DbManga>.seasonsOwnedByLibrary(): Set<Long> {
    val byId = associateBy { it.id }
    fun owned(manga: DbManga, depth: Int): Boolean =
        manga.favorite || (depth < 32 && manga.parentId?.let(byId::get)?.let { owned(it, depth + 1) } == true)
    return filter { it.parentId != null && owned(it, 0) }.mapTo(HashSet()) { it.id }
}

@Serializable
data class DbPageUrl(
    val url: String,
    val fileName: String? = null,
    val headers: Map<String, String>? = null,
)

@Serializable
data class DbRepo(
    val name: String? = null,
    val website: String? = null,
    val jsonUrl: String? = null,
    val hidden: Boolean? = null,
)

@Serializable
data class DbLocalFolder(
    val name: String,
    val path: String,
)

@Serializable
data class DbSource(
    val id: Long = 0,
    val name: String = "",
    val baseUrl: String = "",
    val lang: String = "",
    val isActive: Boolean = true,
    val isAdded: Boolean = false,
    val isPinned: Boolean = false,
    val isNsfw: Boolean = false,
    val sourceCode: String = "",
    val sourceCodeUrl: String = "",
    val typeSource: String = "",
    val iconUrl: String = "",
    val isFullData: Boolean = false,
    val hasCloudflare: Boolean = false,
    val lastUsed: Boolean = false,
    val dateFormat: String = "",
    val dateFormatLocale: String = "",
    val apiUrl: String = "",
    val version: String = "0.0.1",
    val versionLast: String = "0.0.1",
    val headers: String = "",
    val supportLatest: Boolean? = null,
    val filterList: String? = null,
    val preferenceList: String? = null,
    val itemType: DbItemType = DbItemType.Manga,
    val appMinVerReq: String = "",
    val additionalParams: String = "",
    val isLocal: Boolean = false,
    val isObsolete: Boolean = false,
    val sourceCodeLanguage: DbSourceCodeLanguage = DbSourceCodeLanguage.JavaScript,
    val notes: String = "",
    val repo: DbRepo? = null,
    val updatedAt: Long = 0,
) {
    val isTorrent: Boolean get() = typeSource.lowercase() == "torrent"
}

@Serializable
data class DbSyncPreference(
    val syncId: Long? = null,
    val email: String? = null,
    val authToken: String? = null,
    val lastSyncManga: Long? = null,
    val lastSyncHistory: Long? = null,
    val lastSyncUpdate: Long? = null,
    val server: String? = null,
    val syncOn: Boolean = false,
    val autoSyncFrequency: Int = 0,
    val syncHistories: Boolean = false,
    val syncUpdates: Boolean = false,
    val syncSettings: Boolean = false,
    /** Hub delta cursor (`seq` of the last entity received). */
    val hubHead: Long = 0,
    /** Hub history epoch; a mismatch means "resync from zero". */
    val hubEpoch: Int = 0,
    /** A higher-epoch conflict was seen; clear only after the restored pull is applied. */
    val hubRecoveryPending: Boolean = false,
    /** Full-state bootstrap has completed for this configured hub. */
    val hubBootstrapComplete: Boolean = false,
    /** Last hybrid logical clock observed from the hub. */
    val hubHlc: Long = 0,
    /** Stable per-install id sent as `X-Device`. */
    val deviceId: String? = null,
    val serverProvider: SyncServerProvider = SyncServerProvider.YokanHub,
    val mangayomiIdMappings: String? = null,
)

@Serializable
enum class SyncServerProvider {
    YokanHub,
    Mangayomi,
    /** Self-hosted SyncYomi server: whole Tachiyomi protobuf backup per account, ETag-guarded. */
    SyncYomi,
    /** Application-state file in the user's own Google Drive `appDataFolder` (not the `cloud://` backup path). */
    GoogleDrive,
}

@Serializable
data class DbTrack(
    val id: Long = 0,
    val libraryId: Long? = null,
    val mediaId: Long? = null,
    val mangaId: Long? = null,
    val syncId: Int? = null,
    val title: String? = null,
    val lastChapterRead: Int? = null,
    val totalChapter: Int? = null,
    val score: Int? = null,
    val status: DbTrackStatus,
    val startedReadingDate: Long? = null,
    val finishedReadingDate: Long? = null,
    val trackingUrl: String? = null,
    val itemType: DbItemType = DbItemType.Manga,
    val updatedAt: Long = 0,
)

@Serializable
data class DbTrackPreference(
    val syncId: Long? = null,
    val username: String? = null,
    val accountName: String? = null,
    val accountAvatarUrl: String? = null,
    val oauth: String? = null,
    val prefs: String? = null,
    val refreshing: Boolean? = null,
)

@Serializable
data class DbTrackSearch(
    val id: Long? = null,
    val libraryId: Long? = null,
    val mediaId: Long? = null,
    val syncId: Int? = null,
    val title: String? = null,
    val lastChapterRead: Int? = null,
    val totalChapter: Int? = null,
    val score: Double? = null,
    val status: String = "",
    val startedReadingDate: Long? = null,
    val finishedReadingDate: Long? = null,
    val trackingUrl: String? = null,
    val coverUrl: String = "",
    val summary: String = "",
    val publishingStatus: String = "",
    val publishingType: String = "",
    val startDate: String = "",
)

@Serializable
data class DbUpdate(
    val id: Long = 0,
    val mangaId: Long? = null,
    val chapterId: Long? = null,
    val chapterName: String? = null,
    val date: String? = null,
    val updatedAt: Long = 0,
)

@Serializable
data class DbVideoTrack(
    val file: String? = null,
    val label: String? = null,
)

@Serializable
data class DbVideo(
    val url: String,
    val quality: String,
    val originalUrl: String,
    val headers: Map<String, String>? = null,
    val subtitles: List<DbVideoTrack> = emptyList(),
    val audios: List<DbVideoTrack> = emptyList(),
    /** Source-provided WebVTT seek-preview track (sprite tiles addressed with `#xywh=`). */
    val thumbnailTrack: String? = null,
)

@Serializable
data class DbCookie(
    val host: String? = null,
    val cookie: String? = null,
)

@Serializable
data class DbSortLibraryManga(
    val reverse: Boolean = false,
    val index: Int = 0,
)

@Serializable
data class DbSortChapter(
    val mangaId: Long? = null,
    val reverse: Boolean = false,
    val index: Int = 1,
)

@Serializable
data class DbChapterFilter(
    val mangaId: Long? = null,
    val type: Int = 0,
)

/** A chapter's saved page list; see `ChapterPageResolver` for when it is served. */
@Serializable
data class DbChapterPageUrls(
    val chapterId: Long? = null,
    val chapterUrl: String? = null,
    val urls: List<String>? = null,
    val headers: List<String>? = null,
    /** Null for lists saved before timestamps, or ones that needed credentials: never served as fresh. */
    val fetchedAt: Long? = null,
    val sourceId: Long? = null,
    /** The source's `DbSource.version` that produced the list; an update makes the list stale. */
    val sourceVersion: String? = null,
)

@Serializable
data class DbChapterPageIndex(
    val chapterId: Long? = null,
    val index: Int? = null,
)

@Serializable
data class DbPersonalReaderMode(
    val mangaId: Long? = null,
    val readerMode: DbReaderMode = DbReaderMode.Vertical,
)

@Serializable
data class DbAutoScrollPages(
    val mangaId: Long? = null,
    val pageOffset: Double = 10.0,
    val autoScroll: Boolean = false,
)

@Serializable
data class DbPersonalPageMode(
    val mangaId: Long? = null,
    val pageMode: DbPageMode = DbPageMode.OnePage,
)

@Serializable
data class DbFilterScanlator(
    val mangaId: Long? = null,
    val scanlators: List<String>? = null,
)

@Serializable
data class DbL10nLocale(
    val languageCode: String? = null,
    val countryCode: String? = null,
)

@Serializable
data class DbCustomColorFilter(
    val a: Int? = null,
    val r: Int? = null,
    val g: Int? = null,
    val b: Int? = null,
)

@Serializable
data class DbPlayerSubtitleSettings(
    val fontSize: Int = 45,
    val useBold: Boolean = true,
    val useItalic: Boolean = false,
    val textColorA: Int = 255,
    val textColorR: Int = 255,
    val textColorG: Int = 255,
    val textColorB: Int = 255,
    val borderColorA: Int = 255,
    val borderColorR: Int = 0,
    val borderColorG: Int = 0,
    val borderColorB: Int = 0,
    val backgroundColorA: Int = 0,
    val backgroundColorR: Int = 0,
    val backgroundColorG: Int = 0,
    val backgroundColorB: Int = 0,
)

@Serializable
data class DbAlgorithmWeights(
    val genre: Int = 30,
    val setting: Int = 15,
    val synopsis: Int = 40,
    val theme: Int = 20,
)

@Serializable
data class DbSourcePreference(
    val sourceId: Long,
    val key: String,
    val value: String,
)

@Serializable
data class DbSavedSearch(
    val sourceId: Long,
    val name: String,
    val query: String,
    // Deterministic for query-only legacy rows; new presets supply a random stable ID.
    val id: String = "legacy:$sourceId:$name",
    val sourceIdentity: DbPresetSource? = null,
    val filters: List<DbPresetFilter> = emptyList(),
    val presetVersion: Int = 1,
    val filterSchemaRecorded: Boolean = false,
    /** Legacy rows whose source was missing during adoption need explicit rebinding. */
    val missingSourceIdentity: Boolean = false,
)

@Serializable
data class DbUpdateError(
    val mangaId: Long,
    val name: String,
    val error: String,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbActivityFilters.kt
  • Source · implementation · 64 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

7: data class DbActivityPreferences(
11: fun updates(type: DbItemType) = updates[type] ?: DbUpdatesFilter()
12: fun upcoming(type: DbItemType) = upcoming[type] ?: DbActivityCategoryFilter()
13: fun withUpdates(type: DbItemType, value: DbUpdatesFilter) = copy(
16: fun withUpcoming(type: DbItemType, value: DbActivityCategoryFilter) = copy(
21: enum class UpdatesFilterKind { Downloaded, Unread, Started, Bookmarked }
24: data class DbUpdatesFilter(
32: fun value(kind: UpdatesFilterKind): Int = when (kind) {
39: fun cycled(kind: UpdatesFilterKind): DbUpdatesFilter {
54: data class DbActivityCategoryFilter(val states: Map<Long, Int> = emptyMap()) {
55: fun value(id: Long): Int = states[id]?.takeIf { it in 1..2 } ?: 0
56: fun cycled(id: Long): DbActivityCategoryFilter {

How this file works

Activity filters are keyed independently by media type. Small immutable helper methods cycle states through neutral/include/exclude and remove neutral values from sparse maps. Category ID -1 represents Uncategorized; other nonpositive IDs are rejected. The active getter uses validated states rather than treating arbitrary stored integers as enabled filters.

Exact file bytes / download · SHA-256 84cd701d18da6f715e5cba7f5c0d9fe01394e8a12ff0c748e847f531ab8b55b8.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/** Activity filters are local to a profile and independent for each media type. */
@Serializable
data class DbActivityPreferences(
    val updates: Map<DbItemType, DbUpdatesFilter> = emptyMap(),
    val upcoming: Map<DbItemType, DbActivityCategoryFilter> = emptyMap(),
) {
    fun updates(type: DbItemType) = updates[type] ?: DbUpdatesFilter()
    fun upcoming(type: DbItemType) = upcoming[type] ?: DbActivityCategoryFilter()
    fun withUpdates(type: DbItemType, value: DbUpdatesFilter) = copy(
        updates = if (value == DbUpdatesFilter()) updates - type else updates + (type to value),
    )
    fun withUpcoming(type: DbItemType, value: DbActivityCategoryFilter) = copy(
        upcoming = if (value == DbActivityCategoryFilter()) upcoming - type else upcoming + (type to value),
    )
}

enum class UpdatesFilterKind { Downloaded, Unread, Started, Bookmarked }

@Serializable
data class DbUpdatesFilter(
    val downloaded: Int = 0,
    val unread: Int = 0,
    val started: Int = 0,
    val bookmarked: Int = 0,
    val hideExcludedScanlators: Boolean = false,
    val categories: DbActivityCategoryFilter = DbActivityCategoryFilter(),
) {
    fun value(kind: UpdatesFilterKind): Int = when (kind) {
        UpdatesFilterKind.Downloaded -> downloaded
        UpdatesFilterKind.Unread -> unread
        UpdatesFilterKind.Started -> started
        UpdatesFilterKind.Bookmarked -> bookmarked
    }.takeIf { it in 0..2 } ?: 0

    fun cycled(kind: UpdatesFilterKind): DbUpdatesFilter {
        val next = (value(kind) + 1) % 3
        return when (kind) {
            UpdatesFilterKind.Downloaded -> copy(downloaded = next)
            UpdatesFilterKind.Unread -> copy(unread = next)
            UpdatesFilterKind.Started -> copy(started = next)
            UpdatesFilterKind.Bookmarked -> copy(bookmarked = next)
        }
    }

    val active: Boolean get() = UpdatesFilterKind.entries.any { value(it) != 0 } || hideExcludedScanlators || categories.active
}

/** 1 includes any matching category; 2 excludes any matching category. -1 is Uncategorized. */
@Serializable
data class DbActivityCategoryFilter(val states: Map<Long, Int> = emptyMap()) {
    fun value(id: Long): Int = states[id]?.takeIf { it in 1..2 } ?: 0
    fun cycled(id: Long): DbActivityCategoryFilter {
        if (id <= 0 && id != UncategorizedActivityCategoryId) return this
        val next = (value(id) + 1) % 3
        return copy(states = if (next == 0) states - id else states + (id to next))
    }
    val active: Boolean get() = states.any { (id, value) -> (id > 0 || id == UncategorizedActivityCategoryId) && value in 1..2 }
}

const val UncategorizedActivityCategoryId = -1L
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbAutomaticUpdateConstraints.kt
  • Source · implementation · 18 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

6: data class DbAutomaticUpdateConstraints(
15: enum class DbUpdateNetwork { Legacy, Connected, Unmetered, Wifi }
18: enum class DbUnknownNetworkCost { Wait, Metered, Unmetered }

How this file works

The record expresses a policy rather than measuring the device. Legacy delegates to the existing download-network behavior, while Connected, Unmetered and Wifi request distinct checks. The unknown-cost choice specifies what to do when the platform cannot determine cost. Scheduling adapters in later chapters enforce these values.

Exact file bytes / download · SHA-256 d72e893c9985f645240c585dd011e75fc089af0ab057e136087577d9ac416e0a.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

@Serializable
data class DbAutomaticUpdateConstraints(
    /** Legacy preserves the existing download-network setting and its platform semantics. */
    val network: DbUpdateNetwork = DbUpdateNetwork.Legacy,
    val requireExternalPower: Boolean = false,
    /** Explicit user classification, used only when the platform cannot report network cost. */
    val unknownNetworkCost: DbUnknownNetworkCost = DbUnknownNetworkCost.Wait,
)

@Serializable
enum class DbUpdateNetwork { Legacy, Connected, Unmetered, Wifi }

@Serializable
enum class DbUnknownNetworkCost { Wait, Metered, Unmetered }
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbBrowsePreferences.kt
  • Source · implementation · 24 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

8: data class DbBrowsePreferences(
13: fun hidesLibrary(type: ItemType): Boolean = when (type) {
19: fun withHideLibrary(type: ItemType, hide: Boolean): DbBrowsePreferences = when (type) {

How this file works

Three booleans keep the hide-already-in-library choice independent for manga, anime and novels. The read/write helpers dispatch on ItemType and return immutable copies, so source browse screens and Home source feeds can share the same preference without sharing mutable UI state.

Exact file bytes / download · SHA-256 fc16a8ba5bf7612faedc1a11cfca199da56dc5b0d1aafb7c66f5f15d4cb9f06e.

Complete file

package eu.friedcutlet.yokan.database

import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.serialization.Serializable

/** Animetail "hide entries already in library" for source listings and Home source feeds, per media type. */
@Serializable
data class DbBrowsePreferences(
    val hideLibraryManga: Boolean = false,
    val hideLibraryAnime: Boolean = false,
    val hideLibraryNovel: Boolean = false,
) {
    fun hidesLibrary(type: ItemType): Boolean = when (type) {
        ItemType.Manga -> hideLibraryManga
        ItemType.Anime -> hideLibraryAnime
        ItemType.Novel -> hideLibraryNovel
    }

    fun withHideLibrary(type: ItemType, hide: Boolean): DbBrowsePreferences = when (type) {
        ItemType.Manga -> copy(hideLibraryManga = hide)
        ItemType.Anime -> copy(hideLibraryAnime = hide)
        ItemType.Novel -> copy(hideLibraryNovel = hide)
    }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbChapterReleasePreference.kt
  • Source · implementation · 41 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

8: data class DbChapterReleasePreference(
13: fun toPolicy() = ChapterReleasePreferences(scanlatorPriority, skipDuplicateReleases)
16: fun DbSettings.chapterReleasePreference(mangaId: Long?): DbChapterReleasePreference =
21: fun DbSettings.withChapterReleasePreference(preference: DbChapterReleasePreference): DbSettings = copy(
26: fun DbSettings.withoutChapterReleaseOverride(mangaId: Long): DbSettings = copy(
30: fun orderedScanlators(priority: List<String>, available: List<String>): List<String> =
33: fun movedScanlator(priority: List<String>, available: List<String>, scanlator: String, direction: Int): List<String> {

How this file works

A preference with mangaId = null is the global default. Lookup first chooses a title override, then adapts the global default to that title, then constructs defaults. Writes normalize and deduplicate scanlator names. Removing the title override restores inheritance instead of writing a second global row. Ordering helpers append newly available groups and bounds-check move operations.

Exact file bytes / download · SHA-256 2ec4fc0a1399bcd16b0c0f92cc7da5726c0b4070f10db3898df1bd2e58ca9ba3.

Complete file

package eu.friedcutlet.yokan.database

import eu.friedcutlet.yokan.domain.ChapterReleasePreferences
import eu.friedcutlet.yokan.domain.normalizeScanlator
import kotlinx.serialization.Serializable

@Serializable
data class DbChapterReleasePreference(
    val mangaId: Long? = null,
    val scanlatorPriority: List<String> = emptyList(),
    val skipDuplicateReleases: Boolean = false,
) {
    fun toPolicy() = ChapterReleasePreferences(scanlatorPriority, skipDuplicateReleases)
}

fun DbSettings.chapterReleasePreference(mangaId: Long?): DbChapterReleasePreference =
    chapterReleasePreferences.firstOrNull { it.mangaId == mangaId }
        ?: chapterReleasePreferences.firstOrNull { it.mangaId == null }?.copy(mangaId = mangaId)
        ?: DbChapterReleasePreference(mangaId)

fun DbSettings.withChapterReleasePreference(preference: DbChapterReleasePreference): DbSettings = copy(
    chapterReleasePreferences = chapterReleasePreferences.filterNot { it.mangaId == preference.mangaId } +
        preference.copy(scanlatorPriority = preference.scanlatorPriority.map(::normalizeScanlator).distinct()),
)

fun DbSettings.withoutChapterReleaseOverride(mangaId: Long): DbSettings = copy(
    chapterReleasePreferences = chapterReleasePreferences.filterNot { it.mangaId == mangaId },
)

fun orderedScanlators(priority: List<String>, available: List<String>): List<String> =
    (priority.map(::normalizeScanlator) + available.map(::normalizeScanlator).distinct().sorted()).distinct()

fun movedScanlator(priority: List<String>, available: List<String>, scanlator: String, direction: Int): List<String> {
    val ordered = orderedScanlators(priority, available).toMutableList()
    val index = ordered.indexOf(normalizeScanlator(scanlator))
    val target = index + direction
    if (index < 0 || target !in ordered.indices) return ordered
    val value = ordered.removeAt(index)
    ordered.add(target, value)
    return ordered
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbDiscordPreferences.kt
  • Source · implementation · 64 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

6: enum class DbDiscordStatus(val gatewayValue: String) { Online("online"), Idle("idle"), DoNotDisturb("dnd") }
10: data class DbDiscordAccount(
17: override fun toString(): String = "DbDiscordAccount(id=$id, username=$username)"
21: data class DbDiscordButton(val label: String, val url: String)
30: data class DbDiscordPreferences(
46: fun withAccount(account: DbDiscordAccount): DbDiscordPreferences =
50: fun withoutAccount(id: String): DbDiscordPreferences {
56: fun withActive(id: String): DbDiscordPreferences =
60: fun forExport(): DbDiscordPreferences = copy(accounts = emptyList(), activeAccountId = null)
62: override fun toString(): String =

How this file works

The account list and active account ID are updated together through immutable helpers. Removing the active account selects a remaining account; activating a nonexistent ID is ignored. forExport removes all accounts and active selection, and custom toString methods avoid printing tokens. Presence privacy, buttons and display choices remain in the preference record.

Exact file bytes / download · SHA-256 0e699c65d2525ef2001259c6d6872117e086b3d32862516b9404f90d3516e9bf.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

@Serializable
enum class DbDiscordStatus(val gatewayValue: String) { Online("online"), Idle("idle"), DoNotDisturb("dnd") }

/** A user-owned Discord login. The token is installation-local: never exported, synced or logged. */
@Serializable
data class DbDiscordAccount(
    val id: String,
    val username: String,
    val displayName: String = username,
    val avatarUrl: String? = null,
    val token: String,
) {
    override fun toString(): String = "DbDiscordAccount(id=$id, username=$username)"
}

@Serializable
data class DbDiscordButton(val label: String, val url: String)

val DefaultDiscordButtons = listOf(
    DbDiscordButton("Get Yokan", "https://github.com/Schnitzel5/yokan"),
    DbDiscordButton("Join us", "https://discord.com/invite/EjfBuYahsP"),
)

/** Discord presence customization and accounts; the legacy enable/title/cover toggles stay on [DbSettings]. */
@Serializable
data class DbDiscordPreferences(
    val accounts: List<DbDiscordAccount> = emptyList(),
    val activeAccountId: String? = null,
    val status: DbDiscordStatus = DbDiscordStatus.Online,
    val customMessage: String = "",
    val showTimestamp: Boolean = true,
    val showButtons: Boolean = true,
    val buttons: List<DbDiscordButton> = DefaultDiscordButtons,
    /** Never show what is being read/watched, whatever the title. */
    val alwaysPrivate: Boolean = false,
    /** Titles in these categories (or [UncategorizedActivityCategoryId]) appear without title/cover/progress. */
    val privateCategoryIds: Set<Long> = emptySet(),
) {
    val activeAccount: DbDiscordAccount? get() = accounts.firstOrNull { it.id == activeAccountId }

    /** Adds or refreshes [account] (same Discord user id) and makes it the active one. */
    fun withAccount(account: DbDiscordAccount): DbDiscordPreferences =
        copy(accounts = accounts.filterNot { it.id == account.id } + account, activeAccountId = account.id)

    /** Removing the active account activates the first remaining one. */
    fun withoutAccount(id: String): DbDiscordPreferences {
        val remaining = accounts.filterNot { it.id == id }
        val active = activeAccountId.takeIf { it != id && remaining.any { account -> account.id == it } } ?: remaining.firstOrNull()?.id
        return copy(accounts = remaining, activeAccountId = active)
    }

    fun withActive(id: String): DbDiscordPreferences =
        if (accounts.any { it.id == id }) copy(activeAccountId = id) else this

    /** Credentials stay on this installation. */
    fun forExport(): DbDiscordPreferences = copy(accounts = emptyList(), activeAccountId = null)

    override fun toString(): String =
        "DbDiscordPreferences(accounts=${accounts.size}, active=${activeAccountId != null}, status=$status)"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbEinkPreset.kt
  • Source · implementation · 35 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

10: enum class DbEinkPreset(val label: String, val width: Int, val height: Int) {
27: fun einkScaledSize(width: Int, height: Int, maxShortSide: Int): Pair<Int, Int> {
35: fun einkFullRefreshDue(pageTurns: Int, every: Int): Boolean = every > 0 && pageTurns > 0 && pageTurns % every == 0

How this file works

Each preset records a portrait panel size for download sizing. Scaling caps the short side, preserves aspect ratio and never enlarges a smaller image. Refresh scheduling flashes only on positive page-turn multiples of a positive interval; zero disables scheduled flashes.

Exact file bytes / download · SHA-256 3967e4d8585509790a4ef55bad0806f3d6dec437ac3b0e4bdc9e7500f6558fd2.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/**
 * E-ink screens Yokan targets in e-ink display mode. [width] x [height] is the portrait panel
 * resolution; optimized downloads keep each page's short side at most [width].
 */
@Serializable
enum class DbEinkPreset(val label: String, val width: Int, val height: Int) {
    KindleBasic("Kindle (basic)", 1072, 1448),
    KindlePaperwhite("Kindle Paperwhite", 1264, 1680),
    KindleOasis("Kindle Oasis", 1264, 1680),
    KindleScribe("Kindle Scribe", 1860, 2480),
    KoboClara("Kobo Clara", 1072, 1448),
    KoboLibra("Kobo Libra", 1264, 1680),
    KoboSage("Kobo Sage", 1440, 1920),
    KoboElipsa("Kobo Elipsa", 1404, 1872),
    BooxPage("Boox Page / Leaf (7\")", 1264, 1680),
    BooxNoteAir("Boox Note Air / generic 10\"", 1404, 1872),
}

/** Pages turned between full-screen refreshes; 0 disables the refresh flash. */
val EinkRefreshIntervals = listOf(0, 1, 3, 6, 10, 20)

/** Size that keeps [width] x [height]'s short side at most [maxShortSide]; never upscales. */
fun einkScaledSize(width: Int, height: Int, maxShortSide: Int): Pair<Int, Int> {
    val shortSide = minOf(width, height)
    if (shortSide <= maxShortSide) return width to height
    val scale = maxShortSide.toDouble() / shortSide
    return maxOf(1, kotlin.math.round(width * scale).toInt()) to maxOf(1, kotlin.math.round(height * scale).toInt())
}

/** True on the page turns that should flash a full refresh to clear e-ink ghosting. */
fun einkFullRefreshDue(pageTurns: Int, every: Int): Boolean = every > 0 && pageTurns > 0 && pageTurns % every == 0
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbExternalDownloads.kt
  • Source · implementation · 58 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

11: data class DbExternalDownloads(
20: data class DbRemoteDownloadJob(
46: data class DbRemoteDownloadFile(

How this file works

External download state persists user intent separately from observed server state and classified problems. A job contains multiple server files, an endpoint and an account binding so old controls cannot target a newly configured account. complete and terminal require a nonempty file list and aggregate all files. Temporary URLs/headers and resume bindings have distinct lifetimes; export and submission code must respect those comments.

Exact file bytes / download · SHA-256 276dca3e5397334a672a28e648400cf54707b52e661b82799b83a593031eea26.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

@Serializable enum class PreferredDownloader { BuiltIn, Aria2 }
@Serializable enum class RemoteDownloadState { Pending, Submitting, Active, Waiting, Paused, Error, Complete, Removed, Attention }
@Serializable enum class RemoteDownloadIntent { Run, Pause, Cancel }
@Serializable enum class RemoteDownloadProblem { None, Connection, MissingOrRejected, ServerChanged, InvalidSource }

@Serializable
data class DbExternalDownloads(
    val preferred: PreferredDownloader = PreferredDownloader.BuiltIn,
    val endpoint: String = "",
    val secret: String = "",
    val directory: String = "",
    val jobs: List<DbRemoteDownloadJob> = emptyList(),
)

@Serializable
data class DbRemoteDownloadJob(
    val id: String,
    val chapterId: Long,
    val itemType: DbItemType,
    val mangaName: String,
    val chapterName: String,
    val endpoint: String,
    /** SHA-256 binding; old controls cannot target a newly configured account. */
    val accountBinding: String,
    val directory: String,
    val files: List<DbRemoteDownloadFile>,
    val intent: RemoteDownloadIntent = RemoteDownloadIntent.Run,
    val problem: RemoteDownloadProblem = RemoteDownloadProblem.None,
    val createdAt: Long = 0,
    val mangaId: Long? = null,
    val sourceId: Long? = null,
    val mangaLink: String? = null,
    val chapterUrl: String = "",
    val sourceTitleName: String = "",
    val sourceChapterName: String = "",
) {
    val complete: Boolean get() = files.isNotEmpty() && files.all { it.state == RemoteDownloadState.Complete }
    val terminal: Boolean get() = files.isNotEmpty() && files.all { it.state in setOf(RemoteDownloadState.Complete, RemoteDownloadState.Removed) }
}

@Serializable
data class DbRemoteDownloadFile(
    val gid: String,
    val name: String,
    /** Cleared once the server has accepted the task; never exported or synced. */
    val url: String = "",
    val headers: Map<String, String> = emptyMap(),
    val state: RemoteDownloadState = RemoteDownloadState.Pending,
    val totalBytes: Long = 0,
    val completedBytes: Long = 0,
    val errorCode: Int? = null,
    /** Allows identical-representation retries to resume; changed resources get a fresh output file. */
    val resourceBinding: String = "",
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbFeaturePreferences.kt
  • Source · implementation · 74 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

11: data class DbFeaturePreferences(
29: data class DbTrackingPreferences(
36: class DbFeaturePreferencesSerializer : JsonTransformingSerializer<DbFeaturePreferences>(DbFeaturePreferences.serializer()) {
40: override fun transformDeserialize(element: JsonElement): JsonElement {
47: data class DbDownloadPolicy(
69: fun ahead(type: DbItemType): Int = when (type) {

How this file works

The nested record collects Home, downloads, image transformation, external download jobs, library, activity, tracking, browsing, sync triggers, player, reader, Discord, privacy and torrent preferences. The transforming serializer recognizes prerelease Home-only payloads using the actual DbHomePreferences serializer descriptor, then wraps them under home; checking only for keys beginning with shelf would miss real legacy fields. DbDownloadPolicy.ahead chooses the media-specific look-ahead count and clamps it to 0–100. Keep the policy's consumption bookkeeping fields as well as the visible settings.

Exact file bytes / download · SHA-256 3435324492917164c5b5a52657f3122f640793af7e1c8a23fc7bfaa84fcb190a.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonTransformingSerializer

/** Group new feature settings: DbSettings is already at the JVM method-parameter limit. */
@Serializable
data class DbFeaturePreferences(
    val home: DbHomePreferences = DbHomePreferences(),
    val downloads: DbDownloadPolicy = DbDownloadPolicy(),
    val imageDataSaver: DbImageDataSaver = DbImageDataSaver(),
    val externalDownloads: DbExternalDownloads = DbExternalDownloads(),
    val library: DbLibraryPreferences = DbLibraryPreferences(),
    val activity: DbActivityPreferences = DbActivityPreferences(),
    val tracking: DbTrackingPreferences = DbTrackingPreferences(),
    val browse: DbBrowsePreferences = DbBrowsePreferences(),
    val syncTriggers: DbSyncTriggerPreferences = DbSyncTriggerPreferences(),
    val player: DbPlayerPreferences = DbPlayerPreferences(),
    val reader: DbReaderPreferences = DbReaderPreferences(),
    val discord: DbDiscordPreferences = DbDiscordPreferences(),
    val privacy: DbPrivacyPreferences = DbPrivacyPreferences(),
    val torrent: DbTorrentPreferences = DbTorrentPreferences(),
)

@Serializable
data class DbTrackingPreferences(
    /** Opt-in: bind logged-in trackers whose search has exactly one same-title result when a title is added to the library. */
    val autoBindOnAdd: Boolean = false,
)

/** Read prerelease Home-only settings without losing their layout or installation-local token. */
@OptIn(ExperimentalSerializationApi::class)
class DbFeaturePreferencesSerializer : JsonTransformingSerializer<DbFeaturePreferences>(DbFeaturePreferences.serializer()) {
    private val legacyHomeKeys = DbHomePreferences.serializer().descriptor.let { descriptor ->
        (0 until descriptor.elementsCount).mapTo(mutableSetOf()) { descriptor.getElementName(it) }
    }
    override fun transformDeserialize(element: JsonElement): JsonElement {
        val obj = element as? JsonObject ?: return element
        return if ("home" !in obj && obj.keys.any(legacyHomeKeys::contains)) JsonObject(mapOf("home" to obj)) else obj
    }
}

@Serializable
data class DbDownloadPolicy(
    val splitTallImages: Boolean = false,
    val splitImageHeight: Int = 4096,
    val autoDownloadNew: Boolean = false,
    val includeCategoryIds: Set<Long> = emptySet(),
    val excludeCategoryIds: Set<Long> = emptySet(),
    val unreadOnly: Boolean = true,
    val includeFiller: Boolean = false,
    val aheadManga: Int = 0,
    val aheadAnime: Int = 0,
    val aheadNovel: Int = 0,
    val cleanupAfterConsumption: Boolean = false,
    val cleanupAfterManualMark: Boolean = false,
    val keepLastConsumed: Int = 0,
    val protectBookmarks: Boolean = true,
    val cleanupExcludedCategoryIds: Set<Long> = emptySet(),
    /** Durable handoff from a library-update transaction to the persisted download queue. */
    val pendingNewChapterIds: Set<Long> = emptySet(),
    /** Consumption provenance keeps automatic cleanup separate from manually marking read. */
    val consumedChapterIds: Set<Long> = emptySet(),
    val manuallyMarkedChapterIds: Set<Long> = emptySet(),
) {
    fun ahead(type: DbItemType): Int = when (type) {
        DbItemType.Manga -> aheadManga
        DbItemType.Anime -> aheadAnime
        DbItemType.Novel -> aheadNovel
    }.coerceIn(0, 100)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbHomePreferences.kt
  • Source · implementation · 42 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

6: enum class HomeMediaFilter { All, Anime, Manga, Novel, Movie, Series }
10: enum class HomeSection { Continue, Recommended, BecauseYouRead, PopularAnime, PopularManga, PopularNovels, PopularMovies, PopularSeries, Sources, TmdbRecommended }
13: data class DbHomePreferences(
27: fun forPresentation(): DbHomePreferences = copy(tmdbReadAccessToken = "", sourceFeeds = emptyList())
28: override fun toString(): String = "DbHomePreferences(filter=$filter, feeds=${sourceFeeds.size}, tmdbConfigured=${tmdbReadAccessToken.isNotBlank()})"
32: enum class HomeFeedMode { Popular, Latest, SavedSearch }
36: data class DbHomeSourceFeed(

How this file works

Home uses serialized section names and per-source feed records. A feed key combines source, mode and optional preset ID. forPresentation strips the TMDB token and source feed references before handing preferences to presentation state, while toString reports configuration flags and counts instead of credential values. Preserve section names because stored hidden-section choices depend on them.

Exact file bytes / download · SHA-256 3ad562c19835849e7720a9e6001f92b729c44eb0f4ddeaf0046c5766aee0819a.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

@Serializable
enum class HomeMediaFilter { All, Anime, Manga, Novel, Movie, Series }

/** Persisted by name in [DbHomePreferences.hiddenSections]: append new values, never rename. */
@Serializable
enum class HomeSection { Continue, Recommended, BecauseYouRead, PopularAnime, PopularManga, PopularNovels, PopularMovies, PopularSeries, Sources, TmdbRecommended }

@Serializable
data class DbHomePreferences(
    val filter: HomeMediaFilter = HomeMediaFilter.All,
    val showFeatured: Boolean = true,
    val autoAdvanceFeatured: Boolean = false,
    val featuredLibraryOnly: Boolean = false,
    val itemsPerShelf: Int = 12,
    val hideCompleted: Boolean = false,
    val enableAniList: Boolean = true,
    val enableTmdb: Boolean = false,
    val hiddenSections: Set<HomeSection> = emptySet(),
    val sourceFeeds: List<DbHomeSourceFeed> = emptyList(),
    val tmdbReadAccessToken: String = "",
) {
    /** Presentation state never carries credentials. */
    fun forPresentation(): DbHomePreferences = copy(tmdbReadAccessToken = "", sourceFeeds = emptyList())
    override fun toString(): String = "DbHomePreferences(filter=$filter, feeds=${sourceFeeds.size}, tmdbConfigured=${tmdbReadAccessToken.isNotBlank()})"
}

@Serializable
enum class HomeFeedMode { Popular, Latest, SavedSearch }

/** Installation-local references; a preset is always validated against the current source schema. */
@Serializable
data class DbHomeSourceFeed(
    val sourceId: Long,
    val mode: HomeFeedMode = HomeFeedMode.Popular,
    val presetId: String? = null,
) {
    val key: String get() = "$sourceId:${mode.name}:${presetId.orEmpty()}"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbImageDataSaver.kt
  • Source · implementation · 20 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

9: data class DbImageDataSaver(

How this file works

This record describes an optional image transformation provider, output format, quality, grayscale and exclusions. It does not perform a network request. Keeping reader/download opt-ins independent lets later image services choose whether a page may be sent through the configured provider.

Exact file bytes / download · SHA-256 e5607c7eed8f23b6cb3af4f56874f69d8bbb6c807190fea09da692b1bdc15ad1.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

@Serializable enum class ImageSaverProvider { Off, Wsrv, Resmush, BandwidthHero }
@Serializable enum class ImageSaverFormat { Original, Jpeg, Webp }

@Serializable
data class DbImageDataSaver(
    val provider: ImageSaverProvider = ImageSaverProvider.Off,
    val forReader: Boolean = true,
    val forDownloads: Boolean = false,
    val quality: Int = 80,
    val format: ImageSaverFormat = ImageSaverFormat.Webp,
    val grayscale: Boolean = false,
    val skipJpeg: Boolean = false,
    val skipGif: Boolean = true,
    val excludedSourceIds: Set<Long> = emptySet(),
    val bandwidthHeroUrl: String = "",
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbLibraryPreferences.kt
  • Source · implementation · 105 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

6: data class DbLibraryPreferences(
21: fun chapterListDefault(type: DbItemType) = chapterListDefaults[type] ?: DbChapterListDefaults()
22: fun withChapterListDefault(type: DbItemType, defaults: DbChapterListDefaults) = copy(
25: fun updateRules(type: DbItemType) = updateRulesByType[type] ?: DbSmartUpdateRules()
26: fun updateGroupMode(type: DbItemType) = updateGroupModes[type] ?: DbGroupUpdateMode.Global
27: fun withUpdateRules(type: DbItemType, rules: DbSmartUpdateRules) = copy(
30: fun withUpdateGroupMode(type: DbItemType, mode: DbGroupUpdateMode) = copy(
33: fun grouping(type: DbItemType): DbLibraryGrouping = groupingByType[type] ?: DbLibraryGrouping.Categories
34: fun categories(type: DbItemType): Map<Long, DbCategoryLibraryPreferences> = categoryPreferences[type].orEmpty()
35: fun filters(type: DbItemType): DbLibraryExtraFilters = extraFilters[type] ?: DbLibraryExtraFilters()
36: fun withFilters(type: DbItemType, filters: DbLibraryExtraFilters): DbLibraryPreferences = copy(
40: fun withGrouping(type: DbItemType, grouping: DbLibraryGrouping): DbLibraryPreferences = copy(
44: fun withCategory(type: DbItemType, id: Long, preferences: DbCategoryLibraryPreferences?): DbLibraryPreferences {
49: fun defaultCategory(type: DbItemType): Long? = defaultCategoryIds[type]?.takeIf { it >= 0 }
51: fun withDefaultCategory(type: DbItemType, id: Long?): DbLibraryPreferences = copy(
57: data class DbSmartUpdateRules(
67: data class DbChapterListDefaults(
77: enum class DbGroupUpdateMode { Global, CurrentGroup, CurrentExceptUngrouped }
80: data class DbLibraryExtraFilters(
87: enum class DbLibraryGrouping { Categories, Source, Status, TrackerStatus, Tags, Ungrouped }
90: data class DbCategoryLibraryPreferences(
97: data class DbCategoryLibraryDisplay(

How this file works

Sparse maps hold per-media grouping, category display, filters, update rules and chapter-list defaults. Getters supply defaults; writers remove entries that return to those defaults. Category assignment distinguishes missing (ask), zero (uncategorized) and positive IDs. Per-title filler filters override media defaults. This structure prevents one media type's filter or category choice from overwriting another's.

Exact file bytes / download · SHA-256 aba8ce98f887a1c57ffe7345e4e75955e9d5a641fcd385ef199cd29b26672486.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

@Serializable
data class DbLibraryPreferences(
    /** Missing = ask, zero = uncategorized, positive = a category of the same media type. */
    val defaultCategoryIds: Map<DbItemType, Long> = emptyMap(),
    val groupingByType: Map<DbItemType, DbLibraryGrouping> = emptyMap(),
    val categoryPreferences: Map<DbItemType, Map<Long, DbCategoryLibraryPreferences>> = emptyMap(),
    val extraFilters: Map<DbItemType, DbLibraryExtraFilters> = emptyMap(),
    val randomSeeds: Map<DbItemType, Long> = emptyMap(),
    val updateRulesByType: Map<DbItemType, DbSmartUpdateRules> = emptyMap(),
    val updateGroupModes: Map<DbItemType, DbGroupUpdateMode> = emptyMap(),
    val deviceConstraints: DbAutomaticUpdateConstraints = DbAutomaticUpdateConstraints(),
    /** Animetail "Set as default" chapter/episode list settings; missing = built-in default. */
    val chapterListDefaults: Map<DbItemType, DbChapterListDefaults> = emptyMap(),
    /** Per-title episode filler filter (title id → 1 only filler, 2 hide filler); missing = media type default. */
    val chapterFillerFilters: Map<Long, Int> = emptyMap(),
) {
    fun chapterListDefault(type: DbItemType) = chapterListDefaults[type] ?: DbChapterListDefaults()
    fun withChapterListDefault(type: DbItemType, defaults: DbChapterListDefaults) = copy(
        chapterListDefaults = if (defaults == DbChapterListDefaults()) chapterListDefaults - type else chapterListDefaults + (type to defaults),
    )
    fun updateRules(type: DbItemType) = updateRulesByType[type] ?: DbSmartUpdateRules()
    fun updateGroupMode(type: DbItemType) = updateGroupModes[type] ?: DbGroupUpdateMode.Global
    fun withUpdateRules(type: DbItemType, rules: DbSmartUpdateRules) = copy(
        updateRulesByType = if (rules == DbSmartUpdateRules()) updateRulesByType - type else updateRulesByType + (type to rules),
    )
    fun withUpdateGroupMode(type: DbItemType, mode: DbGroupUpdateMode) = copy(
        updateGroupModes = if (mode == DbGroupUpdateMode.Global) updateGroupModes - type else updateGroupModes + (type to mode),
    )
    fun grouping(type: DbItemType): DbLibraryGrouping = groupingByType[type] ?: DbLibraryGrouping.Categories
    fun categories(type: DbItemType): Map<Long, DbCategoryLibraryPreferences> = categoryPreferences[type].orEmpty()
    fun filters(type: DbItemType): DbLibraryExtraFilters = extraFilters[type] ?: DbLibraryExtraFilters()
    fun withFilters(type: DbItemType, filters: DbLibraryExtraFilters): DbLibraryPreferences = copy(
        extraFilters = if (filters == DbLibraryExtraFilters()) extraFilters - type else extraFilters + (type to filters),
    )

    fun withGrouping(type: DbItemType, grouping: DbLibraryGrouping): DbLibraryPreferences = copy(
        groupingByType = if (grouping == DbLibraryGrouping.Categories) groupingByType - type else groupingByType + (type to grouping),
    )

    fun withCategory(type: DbItemType, id: Long, preferences: DbCategoryLibraryPreferences?): DbLibraryPreferences {
        val updated = if (preferences == null) categories(type) - id else categories(type) + (id to preferences)
        return copy(categoryPreferences = if (updated.isEmpty()) categoryPreferences - type else categoryPreferences + (type to updated))
    }

    fun defaultCategory(type: DbItemType): Long? = defaultCategoryIds[type]?.takeIf { it >= 0 }

    fun withDefaultCategory(type: DbItemType, id: Long?): DbLibraryPreferences = copy(
        defaultCategoryIds = if (id == null || id < 0) defaultCategoryIds - type else defaultCategoryIds + (type to id),
    )
}

@Serializable
data class DbSmartUpdateRules(
    val skipCompleted: Boolean = false,
    val onlyCaughtUp: Boolean = false,
    val onlyStarted: Boolean = false,
    /** Preserve Yokan's existing automatic/manual cadence by default. */
    val respectExpectedReleasePeriod: Boolean = true,
)

/** Used by titles without their own sort/filter entry. Filters: 0 off, 1 only matching, 2 exclude matching. */
@Serializable
data class DbChapterListDefaults(
    val sortIndex: Int = 1,
    val sortReverse: Boolean = false,
    val downloaded: Int = 0,
    val unread: Int = 0,
    val bookmarked: Int = 0,
    val filler: Int = 0,
)

@Serializable
enum class DbGroupUpdateMode { Global, CurrentGroup, CurrentExceptUngrouped }

@Serializable
data class DbLibraryExtraFilters(
    /** Off = absent; 1 = include any selected provider, 2 = exclude every selected provider. */
    val providerTracking: Map<Int, Int> = emptyMap(),
    val customInterval: Int = 0,
)

@Serializable
enum class DbLibraryGrouping { Categories, Source, Status, TrackerStatus, Tags, Ungrouped }

@Serializable
data class DbCategoryLibraryPreferences(
    val sort: DbSortLibraryManga? = null,
    val display: DbCategoryLibraryDisplay? = null,
)

/** Tabs and library-wide counts remain global; these options affect cards in one category. */
@Serializable
data class DbCategoryLibraryDisplay(
    val displayType: DbDisplayType = DbDisplayType.ComfortableGrid,
    val gridSize: Int = 0,
    val downloadBadges: Boolean = true,
    val language: Boolean = false,
    val source: Boolean = false,
    val localBadge: Boolean = true,
    val continueButton: Boolean = true,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbPlayerPreferences.kt
  • Source · implementation · 40 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

10: data class DbPlayerPreferences(
39: fun DbSettings.withPlayer(transform: (DbPlayerPreferences) -> DbPlayerPreferences): DbSettings =

How this file works

Playback additions such as brightness, stream fallback, subtitle ranking, picture-in-picture and external player choice are stored together. withPlayer updates the nested record via two copy operations, preserving all sibling settings groups. The platform services decide which requested capabilities are available.

Exact file bytes / download · SHA-256 4e04f07a941b5896d22cfe47d5e2ff38613e029f64f507d14eeead85573783f9.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/** The speeds Yokan offered before presets became editable. */
val DefaultPlaybackSpeedPresets: List<Double> = listOf(0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0)

/** Player behavior preferences; defaults keep the pre-existing player behavior. */
@Serializable
data class DbPlayerPreferences(
    val speedPresets: List<Double> = DefaultPlaybackSpeedPresets,
    val rememberVolume: Boolean = false,
    /** Last volume in percent (0..100) while [rememberVolume] is on; -1 when none was saved. */
    val volume: Int = -1,
    val rememberBrightness: Boolean = false,
    /** Last brightness (0..1) while [rememberBrightness] is on; -1 keeps the system brightness. */
    val brightness: Float = -1f,
    /** Opt-in: try the episode's next untried stream when playback fails. */
    val switchStreamOnFailure: Boolean = false,
    /** Ordered subtitle languages (codes or names); empty falls back to `defaultSubtitleLang`. */
    val subtitleLanguages: List<String> = emptyList(),
    /** Track-name terms preferred among a language's tracks. */
    val subtitleWhitelist: List<String> = emptyList(),
    /** Track-name terms never auto-selected. */
    val subtitleBlacklist: List<String> = emptyList(),
    val screenshotSubtitles: Boolean = false,
    /** Shows the PiP button and keeps the existing automatic PiP entry when leaving the app. */
    val pipEnabled: Boolean = true,
    /** Back while playing enters PiP (or the in-app mini player where the OS has no PiP). */
    val pipOnExit: Boolean = false,
    val pipEpisodeToasts: Boolean = true,
    /** The first PiP action is "previous episode" instead of "+10 s". */
    val pipReplaceWithPrevious: Boolean = false,
    val alwaysUseExternalPlayer: Boolean = false,
    /** Platform player id from `externalPlayerChoices()`; blank tries the platform defaults. */
    val externalPlayer: String = "",
)

fun DbSettings.withPlayer(transform: (DbPlayerPreferences) -> DbPlayerPreferences): DbSettings =
    copy(features = features.copy(player = transform(features.player)))
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbPrivacyPreferences.kt
  • Source · implementation · 36 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

7: enum class DbSecureScreen { Never, Incognito, Always }
10: data class DbPrivacyPreferences(
21: fun DbSettings.isIncognitoFor(sourceId: Long?): Boolean =
24: fun DbSettings.secureScreenActive(): Boolean = when (features.privacy.secureScreen) {
33: fun appLockDue(timeoutMinutes: Int, backgroundedAtMillis: Long, nowMillis: Long): Boolean = when {

How this file works

Incognito is global or source-specific. Screenshot protection uses its own Never/Incognito/Always policy; its helper checks the global incognito flag for the middle option. App-lock timeout -1 disables relocking, zero locks on return, and positive values compare elapsed milliseconds against minutes. Notification redaction is independent from app lock.

Exact file bytes / download · SHA-256 39d77181a2c44ca6b0d75fc909fc3b35c5ef6773d9c97673e5dad91cfdb88f28.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/** When the app hides its content from screenshots, screen recording and the app switcher. */
@Serializable
enum class DbSecureScreen { Never, Incognito, Always }

@Serializable
data class DbPrivacyPreferences(
    val secureScreen: DbSecureScreen = DbSecureScreen.Never,
    /** Replaces titles in system notifications with generic text, with or without app lock. */
    val hideNotificationContent: Boolean = false,
    /** Minutes in the background before app lock asks again; 0 = as soon as the app leaves, -1 = never. */
    val appLockTimeoutMinutes: Int = 0,
    /** Sources whose titles are always read/watched incognito. */
    val incognitoSourceIds: Set<Long> = emptySet(),
)

/** Global incognito, or the title's source is marked incognito. */
fun DbSettings.isIncognitoFor(sourceId: Long?): Boolean =
    incognitoMode || (sourceId != null && sourceId in features.privacy.incognitoSourceIds)

fun DbSettings.secureScreenActive(): Boolean = when (features.privacy.secureScreen) {
    DbSecureScreen.Never -> false
    DbSecureScreen.Incognito -> incognitoMode
    DbSecureScreen.Always -> true
}

val AppLockTimeoutChoices = listOf(0, 1, 2, 5, 10, -1)

/** Whether returning after [backgroundedAtMillis] must lock again under [timeoutMinutes]. */
fun appLockDue(timeoutMinutes: Int, backgroundedAtMillis: Long, nowMillis: Long): Boolean = when {
    timeoutMinutes < 0 -> false
    else -> nowMillis - backgroundedAtMillis >= timeoutMinutes * 60_000L
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbReaderPreferences.kt
  • Source · implementation · 49 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

7: data class DbReaderModePreferences(
22: data class DbReaderPreferences(
35: fun DbSettings.readerModePreferences(paged: Boolean): DbReaderModePreferences =
43: fun DbSettings.withReader(transform: (DbReaderPreferences) -> DbReaderPreferences): DbSettings =
46: fun DbSettings.withReaderModePreferences(paged: Boolean, transform: (DbReaderModePreferences) -> DbReaderModePreferences): DbSettings {

How this file works

Paged and continuous modes get separate optional preference groups. A null group inherits legacy global values until the user changes that group; eagerly replacing null with defaults would discard an existing user's settings. The helper materializes effective values only for the group being edited and updates it immutably.

Exact file bytes / download · SHA-256 e17331b7a988df63a010721aaf077db888818db853560c56d1e7adb292ce5b96.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/** Page processing and navigation that differ between paged and continuous (webtoon) readers. */
@Serializable
data class DbReaderModePreferences(
    val cropBorders: Boolean = false,
    val animatePageTransitions: Boolean = true,
    val usePageTapZones: Boolean = true,
    val navigationLayout: Int = 0,
    /** Shows a landscape page as two consecutive half pages in reading direction. */
    val splitWidePages: Boolean = false,
    val invertSplit: Boolean = false,
    /** Rotates landscape pages a quarter turn (clockwise unless inverted); splitting takes precedence. */
    val rotateWidePages: Boolean = false,
    val invertRotation: Boolean = false,
)

/** Reader preferences; defaults keep the pre-existing reader behavior. */
@Serializable
data class DbReaderPreferences(
    /** Null until first changed: the group follows the legacy global reader settings. */
    val paged: DbReaderModePreferences? = null,
    val webtoon: DbReaderModePreferences? = null,
    val skipReadChapters: Boolean = false,
    val skipFilteredChapters: Boolean = true,
    val alwaysShowChapterTransition: Boolean = true,
    val saveImagesInTitleFolder: Boolean = false,
    val volumeKeyNavigation: Boolean = false,
    val invertVolumeKeys: Boolean = false,
)

/** [paged] covers LTR/RTL/vertical pagers; every continuous mode uses the webtoon group. */
fun DbSettings.readerModePreferences(paged: Boolean): DbReaderModePreferences =
    (if (paged) features.reader.paged else features.reader.webtoon) ?: DbReaderModePreferences(
        cropBorders = cropBorders,
        animatePageTransitions = animatePageTransitions,
        usePageTapZones = usePageTapZones,
        navigationLayout = readerNavigationLayout,
    )

fun DbSettings.withReader(transform: (DbReaderPreferences) -> DbReaderPreferences): DbSettings =
    copy(features = features.copy(reader = transform(features.reader)))

fun DbSettings.withReaderModePreferences(paged: Boolean, transform: (DbReaderModePreferences) -> DbReaderModePreferences): DbSettings {
    val updated = transform(readerModePreferences(paged))
    return withReader { if (paged) it.copy(paged = updated) else it.copy(webtoon = updated) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbSettings.kt
  • Source · implementation · 306 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

8: enum class DbNovelReadingMode { Scroll, Paged }
11: enum class DbNovelPageMode { Single, Double, Auto }
14: enum class DbGlobalStatusVisibility {
21: data class DbTitleMetadata(
30: data class DbAutomaticReaderLayout(val mangaId: Long, val enabled: Boolean = true, val fallback: DbReaderMode? = null)
34: data class DbSettings(

How this file works

DbSettings is the durable profile settings record. Constructor defaults supply missing fields when decoding older JSON; aliases declared through @JsonNames retain older serialized spellings. New settings groups live under features because generated constructors/copy methods approach JVM parameter limits. The computed home getter delegates to features.home; it is not an additional independent setting. Keep device-local identity and credential fields distinct from settings eligible for backup or synchronization, as the later export mappers do.

Exact file bytes / download · SHA-256 8e1ed236b4362bb24bc4852d76540331a5ebac83b2e0416df1a5d14efce1f2ba.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.JsonNames

@Serializable
enum class DbNovelReadingMode { Scroll, Paged }

@Serializable
enum class DbNovelPageMode { Single, Double, Auto }

@Serializable
enum class DbGlobalStatusVisibility {
    Automatic,
    AlwaysVisible,
    Hidden,
}

@Serializable
data class DbTitleMetadata(
    val mangaId: Long,
    val metadataServerId: String? = null,
    val metadataSource: String? = null,
    val titles: List<String> = emptyList(),
    val updatedAt: Long = 0,
)

@Serializable
data class DbAutomaticReaderLayout(val mangaId: Long, val enabled: Boolean = true, val fallback: DbReaderMode? = null)

@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class DbSettings(
    @JsonNames("home")
    @Serializable(with = DbFeaturePreferencesSerializer::class)
    val features: DbFeaturePreferences = DbFeaturePreferences(),
    val id: Long = 227,
    val updatedAt: Long = 0,
    val completedOnboardingVersion: Int = 0,
    val displayType: DbDisplayType = DbDisplayType.CompactGrid,
    val libraryFilterMangasDownloadType: Int = 0,
    val libraryFilterMangasUnreadType: Int = 0,
    val libraryFilterMangasStartedType: Int = 0,
    val libraryFilterMangasBookMarkedType: Int = 0,
    val libraryShowCategoryTabs: Boolean = false,
    val libraryDownloadedChapters: Boolean = false,
    val libraryShowLanguage: Boolean = false,
    val libraryShowSource: Boolean = false,
    val libraryShowNumbersOfItems: Boolean = false,
    val libraryShowContinueReadingButton: Boolean = false,
    val libraryLocalSource: Boolean? = null,
    val librarySearchQuery: String = "",
    val sortLibraryManga: DbSortLibraryManga? = null,
    val sortChapterList: List<DbSortChapter>? = null,
    val chapterFilterDownloadedList: List<DbChapterFilter>? = null,
    val chapterFilterUnreadList: List<DbChapterFilter>? = null,
    val chapterFilterBookmarkedList: List<DbChapterFilter>? = null,
    val flexColorSchemeBlendLevel: Double = 10.0,
    val dateFormat: String = "M/d/y",
    val relativeTimesTamps: Int = 2,
    val flexSchemeColorIndex: Int = 2,
    val themeIsDark: Boolean = false,
    val followSystemTheme: Boolean = false,
    val incognitoMode: Boolean = false,
    val showPagesNumber: Boolean = true,
    val chapterPageIndexList: List<DbChapterPageIndex>? = null,
    val userAgent: String = DefaultUserAgent,
    val cookiesList: List<DbCookie>? = null,
    val defaultReaderMode: DbReaderMode = DbReaderMode.Vertical,
    val automaticReaderLayout: Boolean = false,
    val readerHoldToScroll: Boolean = false,
    /** E-ink display: monochrome theme, no motion, grayscale pages and periodic full refresh. Device-local. */
    val einkMode: Boolean = false,
    val einkPreset: DbEinkPreset = DbEinkPreset.KindlePaperwhite,
    val einkRefreshEveryPages: Int = 6,
    /** With [einkMode], manga page downloads are stored as grayscale JPEGs sized for [einkPreset]. */
    val einkOptimizeDownloads: Boolean = false,
    val automaticReaderLayouts: List<DbAutomaticReaderLayout> = emptyList(),
    val personalReaderModeList: List<DbPersonalReaderMode>? = null,
    val animatePageTransitions: Boolean = true,
    val doubleTapAnimationSpeed: Int = 1,
    val onlyIncludePinnedSources: Boolean = false,
    val pureBlackDarkMode: Boolean = false,
    val downloadOnlyOnWifi: Boolean = false,
    val saveAsCBZArchive: Boolean = false,
    val deleteDownloadAfterReading: Boolean = false,
    val concurrentDownloads: Int = 2,
    val allowConcurrentDownloads: Boolean = true,
    val downloadDelaySeconds: Int = 0,
    val downloadQueueOrder: List<Long> = emptyList(),
    val networkDownloadSpeedLimitKib: Int = 0,
    val networkUploadSpeedLimitKib: Int = 0,
    val downloadLocation: String = "",
    val filterScanlatorList: List<DbFilterScanlator>? = null,
    val chapterReleasePreferences: List<DbChapterReleasePreference> = emptyList(),
    val autoExtensionsUpdates: Boolean = false,
    /** Relaxes host-only safety gates for local development, e.g. recipe catalogs served from `http://127.0.0.1`. */
    val developerMode: Boolean = false,
    /** Hub URLs the user added next to the published list; may be LAN or loopback, so device-local. */
    val customHubServers: List<String> = emptyList(),
    val cropBorders: Boolean = false,
    val locale: DbL10nLocale? = null,
    val defaultSubtitleLang: DbL10nLocale? = null,
    val animeDisplayType: DbDisplayType = DbDisplayType.CompactGrid,
    val libraryFilterAnimeDownloadType: Int = 0,
    val libraryFilterAnimeUnreadType: Int = 0,
    val libraryFilterAnimeStartedType: Int = 0,
    val libraryFilterAnimeBookMarkedType: Int = 0,
    val animeLibraryShowCategoryTabs: Boolean = false,
    val animeLibraryDownloadedChapters: Boolean = false,
    val animeLibraryShowLanguage: Boolean = false,
    val animeLibraryShowSource: Boolean = false,
    val animeLibraryShowNumbersOfItems: Boolean = false,
    val animeLibraryShowContinueReadingButton: Boolean = false,
    val animeLibraryLocalSource: Boolean? = null,
    val animeLibrarySearchQuery: String = "",
    val sortLibraryAnime: DbSortLibraryManga? = null,
    val pagePreloadAmount: Int = 6,
    val enableLogs: Boolean = false,
    val checkForAppUpdates: Boolean = true,
    val checkForExtensionUpdates: Boolean = true,
    val scaleType: DbScaleType = DbScaleType.FitScreen,
    val backgroundColor: DbBackgroundColor = DbBackgroundColor.Black,
    val personalPageModeList: List<DbPersonalPageMode>? = null,
    val startDateBackup: Long? = null,
    val backupFrequency: Int? = null,
    val backupListOptions: List<Int>? = null,
    val autoBackupLocation: String? = null,
    val usePageTapZones: Boolean = true,
    val alwaysShowChrome: Boolean = false,
    val autoScrollPages: List<DbAutoScrollPages>? = null,
    val autoScrollSpeed: Double = 4.0,
    /**
     * Opt-in: when true, `AppLogger` / `ExtensionLogger` / network logging
     * append timestamped lines to a log file at
     * `LocalFileService.cacheRoot/logs/yokan.log`. Always off by default;
     * stdout output is unaffected.
     */
    val enableFileLogging: Boolean = false,
    val markEpisodeAsSeenType: Int = 85,
    val defaultSkipIntroLength: Int = 85,
    val defaultDoubleTapToSkipLength: Int = 10,
    val defaultPlaybackSpeed: Double = 1.0,
    val fullScreenPlayer: Boolean = false,
    val forceLandscapePlayer: Boolean = false,
    /** Retained only for compatibility with existing serialized settings; no longer used. */
    val desktopUseVlcj: Boolean = false,
    val updateProgressAfterReading: Boolean = true,
    val enableAniSkip: Boolean? = null,
    val enableAutoSkip: Boolean? = null,
    val aniSkipTimeoutLength: Int? = null,
    val customDns: String = "",
    val dohEnabled: Boolean = false,
    val dohProviderId: Int = 0,
    val customDohUrl: String = "",
    val cloudflareBypassProxyUrl: String = "",
    val btServerAddress: String = "127.0.0.1",
    val btServerPort: Int? = null,
    val fullScreenReader: Boolean = true,
    val customColorFilter: DbCustomColorFilter? = null,
    val enableCustomColorFilter: Boolean = false,
    val colorFilterBlendMode: DbColorFilterBlendMode = DbColorFilterBlendMode.None,
    val playerSubtitleSettings: DbPlayerSubtitleSettings? = null,
    val mangaHomeDisplayType: DbDisplayType = DbDisplayType.ComfortableGrid,
    val appFontFamily: String? = null,
    /** UI density scale (1.0 = system default). Multiplies LocalDensity.density and fontScale. */
    val uiScale: Double = 1.0,
    val autoUiScale: Boolean = false,
    val mangaGridSize: Int? = null,
    val animeGridSize: Int? = null,
    val novelGridSize: Int? = null,
    val mangaExtensionsRepo: List<DbRepo>? = null,
    val animeExtensionsRepo: List<DbRepo>? = null,
    val novelExtensionsRepo: List<DbRepo>? = null,
    val androidProxyServer: String? = null,
    val jrePath: String = "",
    val extensionServerPath: String = "",
    val disableSectionType: DbSectionType = DbSectionType.All,
    val useLibass: Boolean = true,
    val hwdecMode: String = "auto",
    val enableHardwareAcceleration: Boolean? = null,
    val libraryFilterNovelDownloadType: Int = 0,
    val libraryFilterNovelUnreadType: Int = 0,
    val libraryFilterNovelStartedType: Int = 0,
    val libraryFilterNovelBookMarkedType: Int = 0,
    val novelLibraryShowCategoryTabs: Boolean = false,
    val novelLibraryDownloadedChapters: Boolean = false,
    val novelLibraryShowLanguage: Boolean = false,
    val novelLibraryShowSource: Boolean = false,
    val novelLibraryShowNumbersOfItems: Boolean = false,
    val novelLibraryShowContinueReadingButton: Boolean = false,
    val novelLibraryLocalSource: Boolean? = null,
    val novelLibrarySearchQuery: String = "",
    val sortLibraryNovel: DbSortLibraryManga? = null,
    val novelDisplayType: DbDisplayType = DbDisplayType.ComfortableGrid,
    val novelFontSize: Int = 14,
    val novelReadingMode: DbNovelReadingMode = DbNovelReadingMode.Scroll,
    val novelPageMode: DbNovelPageMode = DbNovelPageMode.Auto,
    val novelFontFamily: String = "Default",
    val novelTextAlign: DbNovelTextAlign = DbNovelTextAlign.Left,
    val novelReaderTheme: String = "#292832",
    val novelReaderTextColor: String = "#CCCCCC",
    val novelReaderPadding: Int = 16,
    val novelReaderLineHeight: Double = 1.5,
    val novelShowScrollPercentage: Boolean = true,
    val novelRemoveExtraParagraphSpacing: Boolean = false,
    val novelTapToScroll: Boolean = false,
    val navigationOrder: List<String>? = null,
    val hideItems: List<String>? = null,
    val clearChapterCacheOnAppLaunch: Boolean = false,
    val lastTrackerLibraryLocation: String? = null,
    val mergeLibraryNavMobile: Boolean = false,
    val showLocalLibraryNavigation: Boolean = false,
    val enableDiscordRpc: Boolean = true,
    val hideDiscordRpcInIncognito: Boolean = true,
    val rpcShowReadingWatchingProgress: Boolean = true,
    val rpcShowTitle: Boolean = true,
    val rpcShowCoverImage: Boolean = true,
    val useMpvConfig: Boolean = true,
    val debandingType: DbDebandingType = DbDebandingType.None,
    val enableGpuNext: Boolean = false,
    val useYuv420p: Boolean = false,
    val audioPreferredLanguages: String? = null,
    val enableAudioPitchCorrection: Boolean? = null,
    val audioChannels: DbAudioChannel = DbAudioChannel.AutoSafe,
    val volumeBoostCap: Int? = null,
    val downloadedOnlyMode: Boolean = false,
    val globalStatusVisibility: DbGlobalStatusVisibility = DbGlobalStatusVisibility.Automatic,
    val algorithmWeights: DbAlgorithmWeights? = null,
    val sourcePreferences: List<DbSourcePreference>? = null,
    val savedSearches: List<DbSavedSearch>? = null,
    val updateErrors: List<DbUpdateError>? = null,
    val tvUiScale: Double? = null,
    val animeOnlyTvMode: Boolean? = null,
    val tvHomeStyle: Boolean? = null,
    val trackerOrder: List<Int>? = null,
    /** Legacy custom local folders stored before folders had user-facing names. Migrated to [namedLocalFolders] on access. */
    val localFolders: List<String>? = null,
    val namedLocalFolders: List<DbLocalFolder>? = null,
    val downloadLocalFolderName: String? = null,
    val askDownloadDestination: Boolean = true,
    /** ARGB-packed seed color used by MaterialKolor. Null = derive from [flexSchemeColorIndex] for backwards compat. */
    val themeSeedColor: Int? = null,
    /** Path to an image whose dominant color seeds the palette. Takes precedence over [themeSeedColor] when set. */
    val themeSeedImagePath: String? = null,
    /** Material You: on Android 12+ derive scheme from the device wallpaper. Ignored on other platforms. */
    val materialYou: Boolean = false,
    /** Material Expressive: enables MaterialExpressiveTheme and the SPEC_2025 expressive color spec. */
    val materialExpressive: Boolean = false,
    /** PaletteStyle name (TonalSpot, Vibrant, Expressive, Monochrome, …). Defaults to Tonal Spot. */
    val themePaletteStyle: String = "TonalSpot",
    val appLockEnabled: Boolean = false,
    val libraryFilterMangasCompletedType: Int = 0,
    val libraryFilterAnimeCompletedType: Int = 0,
    val libraryFilterNovelCompletedType: Int = 0,
    val libraryFilterMangasTrackingType: Int = 0,
    val libraryFilterAnimeTrackingType: Int = 0,
    val libraryFilterNovelTrackingType: Int = 0,
    val keepScreenOnReader: Boolean = true,
    val webtoonSidePadding: Int = 0,
    val showPageGaps: Boolean = true,
    val autoReadDuplicateChapters: Boolean = false,
    val invertColors: Boolean = false,
    val grayscale: Boolean = false,
    val readerBrightness: Double = 0.0,
    val readerContrast: Double = 1.0,
    val readerSaturation: Double = 1.0,
    val readerNavigationLayout: Int = 0,
    val backupCompressionLevel: Int? = null,
    val backupEncryptionEnabled: Boolean = false,
    val backupEncryptionPassword: String? = null,
    val showNsfw: Boolean = false,
    val ttsSpeechRate: Double = 0.5,
    val ttsPitch: Double = 1.0,
    val ttsLanguage: String? = null,
    val ttsVoice: String? = null,
    /** Base URL for a self-hosted / third-party metadata API server. */
    val metadataServerUrl: String = "http://127.0.0.1:3000",
    /** Opt-in automatic metadata enrichment. Manual checks still use [metadataServerUrl]. */
    val metadataServerEnabled: Boolean = false,
    /** Periodic metadata refresh cadence; zero disables the job. */
    val metadataRefreshFrequencySeconds: Int = 0,
    /** Optional Bearer token used when the metadata server tracker endpoints are enabled. */
    val metadataServerToken: String = "",
    /** Periodic manga/anime/novel library update cadence; zero disables the job. */
    val libraryUpdateFrequencySeconds: Int = 0,
    /**
     * Minutes after local midnight for a fixed daily library update; `-1` means repeat every
     * [libraryUpdateFrequencySeconds] instead. Only honoured while the job is enabled.
     */
    val libraryUpdateDailyAtMinutes: Int = -1,
    /** Desktop only: closing the window hides to the tray so scheduled tasks keep running. Device-local. */
    val desktopCloseToTray: Boolean = false,
    /** Desktop only: register an OS login item that starts Yokan hidden in the tray. Device-local. */
    val desktopLaunchAtLogin: Boolean = false,
    /** Per-entry scraped metadata kept in the settings blob to avoid Room row migrations. */
    val titleMetadata: List<DbTitleMetadata>? = null,
    /** Set once [eu.friedcutlet.yokan.database.sync.SyncIdentityMigration] has rewritten local ids to stable hub ids. Device-local. */
    val syncIdentityVersion: Int = 0,
) {
    val home: DbHomePreferences get() = features.home
}

const val DefaultUserAgent =
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbSourcePreset.kt
  • Source · implementation · 60 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

8: data class DbPresetSource(
19: data class DbPresetOption(val label: String, val value: String)
22: data class DbPresetFilter(
35: sealed interface DbPresetSelection {
44: fun DbSource.presetIdentity(): DbPresetSource = DbPresetSource(
51: fun DbSettings.adoptLegacySourcePresets(sources: List<DbSource>): DbSettings {

How this file works

Saved filter selections use a sealed serializable type with explicit discriminator names. Source identity deliberately omits installation version and local row ID, which can change on restore. Legacy query-only presets are bound to a source identity while that source still exists; missing sources receive an explicit marker rather than being silently rebound to another source.

Exact file bytes / download · SHA-256 f940d19ff058b0e441eb4d23d0fca6465b5f09a4030c8c0c25b39e11ff7bc8f1.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

/** Source identity excludes installed version and local row ID, which can change during restore. */
@Serializable
data class DbPresetSource(
    val name: String,
    val baseUrl: String,
    val lang: String,
    val itemType: DbItemType,
    val runtime: DbSourceCodeLanguage,
    val typeSource: String,
    val repository: String,
)

@Serializable
data class DbPresetOption(val label: String, val value: String)

@Serializable
data class DbPresetFilter(
    val id: String,
    val name: String,
    val type: String,
    val kind: String,
    val stableId: Boolean,
    val options: List<DbPresetOption>,
    val defaultValue: String?,
    val defaultAscending: Boolean = true,
    val selection: DbPresetSelection? = null,
)

@Serializable
sealed interface DbPresetSelection {
    @Serializable @SerialName("toggle") data class Toggle(val checked: Boolean) : DbPresetSelection
    @Serializable @SerialName("single") data class Single(val value: String) : DbPresetSelection
    @Serializable @SerialName("multi") data class Multi(val values: Set<String>) : DbPresetSelection
    @Serializable @SerialName("triState") data class TriState(val state: Int) : DbPresetSelection
    @Serializable @SerialName("text") data class Text(val value: String) : DbPresetSelection
    @Serializable @SerialName("sort") data class Sort(val value: String, val ascending: Boolean) : DbPresetSelection
}

fun DbSource.presetIdentity(): DbPresetSource = DbPresetSource(
    name = name.trim(), baseUrl = baseUrl.trim().trimEnd('/'), lang = lang,
    itemType = itemType, runtime = sourceCodeLanguage, typeSource = typeSource,
    repository = repo?.jsonUrl.orEmpty().trim().trimEnd('/'),
)

/** Bind legacy query-only rows while their original source still exists. */
fun DbSettings.adoptLegacySourcePresets(sources: List<DbSource>): DbSettings {
    if (savedSearches.orEmpty().none { it.sourceIdentity == null && !it.missingSourceIdentity }) return this
    val byId = sources.associateBy { it.id }
    return copy(savedSearches = savedSearches.orEmpty().map { preset ->
        if (preset.sourceIdentity != null || preset.missingSourceIdentity) preset else {
            val source = byId[preset.sourceId]
            preset.copy(sourceIdentity = source?.presetIdentity(), missingSourceIdentity = source == null)
        }
    })
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbSyncTriggerPreferences.kt
  • Source · implementation · 14 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

7: data class DbSyncTriggerPreferences(

How this file works

These opt-in booleans request synchronization at specific reading, playback or app lifecycle events. They live under device-local feature preferences. Event handling and duplicate-trigger suppression belong to the sync services, not this serializable value object.

Exact file bytes / download · SHA-256 70772f6671664374f3a5089d1e0032d2b94dfd876981945fc8bee593c2215a0b.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/** Animetail SyncTriggerOptions. Lives under [DbSettings.features], so it stays device-local like upstream. */
@Serializable
data class DbSyncTriggerPreferences(
    val onChapterRead: Boolean = false,
    val onChapterOpen: Boolean = false,
    val onEpisodeSeen: Boolean = false,
    val onEpisodeOpen: Boolean = false,
    val onAppStart: Boolean = false,
    val onAppResume: Boolean = false,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DbTorrentPreferences.kt
  • Source · implementation · 58 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

12: data class DbTorrentPreferences(
27: fun forExport() = copy(executablePath = "", password = "", proxyUrl = "")

How this file works

The mode chooses a supervised desktop process or a user-run remote server. Proxy enum values map to command-line flags. forExport clears the local executable path, password and proxy URL while preserving exportable configuration. The default tracker list is literal configuration; native process/network behavior is implemented later.

Exact file bytes / download · SHA-256 9efcccc7618221ed1cd15839ff5af37e6ecd5074769d9d4e3c7b916a9a8b2ee6.

Complete file

package eu.friedcutlet.yokan.database

import kotlinx.serialization.Serializable

/** How Yokan reaches TorrServer: a process it supervises itself (desktop) or a user-run server. */
@Serializable enum class TorrServerMode { Managed, Remote }

/** TorrServer's `--proxymode`; [None] launches without a proxy. */
@Serializable enum class TorrServerProxyMode(val flag: String?) { None(null), Tracker("tracker"), Peers("peers"), Full("full") }

@Serializable
data class DbTorrentPreferences(
    val enabled: Boolean = false,
    val mode: TorrServerMode = TorrServerMode.Managed,
    val port: Int = 8090,
    /** User-provided TorrServer binary (desktop); blank uses the verified download. Device-local. */
    val executablePath: String = "",
    val remoteUrl: String = "",
    val username: String = "",
    val password: String = "",
    /** Newline-separated announce URLs pushed to the server's `DefaultTrackers` setting. */
    val trackers: String = DefaultTorrentTrackers,
    val proxyMode: TorrServerProxyMode = TorrServerProxyMode.None,
    val proxyUrl: String = "",
) {
    /** Credentials and machine paths never leave the device. */
    fun forExport() = copy(executablePath = "", password = "", proxyUrl = "")
}

/** Animetail's default anime tracker list (TorrentPreferences.torrServerTrackers). */
val DefaultTorrentTrackers = """
    http://nyaa.tracker.wf:7777/announce
    http://anidex.moe:6969/announce
    http://tracker.anirena.com:80/announce
    udp://tracker.uw0.xyz:6969/announce
    http://share.camoe.cn:8080/announce
    http://t.nyaatracker.com:80/announce
    udp://47.ip-51-68-199.eu:6969/announce
    udp://9.rarbg.me:2940
    udp://9.rarbg.to:2820
    udp://exodus.desync.com:6969/announce
    udp://explodie.org:6969/announce
    udp://ipv4.tracker.harry.lu:80/announce
    udp://open.stealth.si:80/announce
    udp://opentor.org:2710/announce
    udp://opentracker.i2p.rocks:6969/announce
    udp://retracker.lanta-net.ru:2710/announce
    udp://tracker.cyberia.is:6969/announce
    udp://tracker.dler.org:6969/announce
    udp://tracker.ds.is:6969/announce
    udp://tracker.internetwarriors.net:1337
    udp://tracker.openbittorrent.com:6969/announce
    udp://tracker.opentrackr.org:1337/announce
    udp://tracker.tiny-vps.com:6969/announce
    udp://tracker.torrent.eu.org:451/announce
    udp://valakas.rollo.dnsabr.com:2710/announce
    udp://www.torrent.eu.org:451/announce
""".trimIndent()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ChapterRecognition.kt
  • Source · implementation · 205 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

15: object ChapterRecognition {
16: fun rawSeasonAndNumber(mangaTitle: String, chapter: Chapter): Pair<Int, Double?> {
22: fun parseEpisodeNumber(mangaTitle: String, chapter: Chapter): Double = rawSeasonAndNumber(mangaTitle, chapter).second ?: 0.0
33: fun parseSeasonNumber(name: String): Int? = seasonKeyword.find(name.lowercase())?.groupValues?.get(1)?.toIntOrNull()
44: fun parseChapterNumber(mangaTitle: String, chapterName: String): Double {
54: fun parseEpisodeNumber(mangaTitle: String, chapterName: String): Double {
74: fun chapterIdentityKey(
92: fun rawSeasonAndNumber(mangaTitle: String, chapterName: String): Pair<Int, Double?> {
119: fun chapterSortKeys(mangaTitle: String, chapters: List<Chapter>): Map<Long, Double?> {
146: fun missingChapterCount(mangaTitle: String, chapters: List<Chapter>): Int {
165: fun unrecognizedChapterNumberCount(mangaTitle: String, chapters: List<Chapter>): Int {
171: private fun withSeason(season: Int, ep: Double): Double =
174: private fun extractNumber(name: String): Double? {
180: private fun fromMatch(match: MatchResult): Double {
188: private fun decimalAddition(decimal: String?, alpha: String?): Double {
200: private fun parseAlphaPostFix(c: Char): Double {

How this file works

This is the permissive parser used for display, tracker episode numbers and gap counts. The Chapter overload prefers valid explicit number/season metadata and uses numberingName before a renamed display name. Text parsing strips the title and volume noise, prioritizes episode notation, then extracts a chapter or bare number and its decimal/letter suffix. null means unnumbered, while 0.0 is a recognized zero. chapterSortKeys introduces season buckets only after at least three episode numbers collide across seasons. missingChapterCount truncates recognized numbers to integers and counts gaps between the minimum and maximum; it does not count missing leading chapters. This permissive parser is different from the conservative release identity policy below.

Exact file bytes / download · SHA-256 814579dfa3fc1a9d666a7d762cdc12a126f0374a6a1790dc32b989c5a3646bbd.

Complete file

package eu.friedcutlet.yokan.domain

/**
 * Chapter / episode number recognition and missing chapter gap detection.
 *
 * Direct port and enhancement of Mangayomi's `lib/utils/chapter_recognition.dart`
 * (incorporating commits f1170d47, 4af383cb, and 96f1830a).
 *
 * Capabilities:
 * - Preserves decimal chapter precision (e.g. 12.5).
 * - Distinguishes unnumbered chapters (null, e.g. "Special", "Prologue") from genuine chapter 0.0.
 * - Detects missing chapter gaps (e.g. chapters 1, 2, 4, 5 present -> chapter 3 missing).
 * - Multi-season anime bucket sorting when numbering resets across seasons.
 */
object ChapterRecognition {
    fun rawSeasonAndNumber(mangaTitle: String, chapter: Chapter): Pair<Int, Double?> {
        val inferred = rawSeasonAndNumber(mangaTitle, chapter.numberingName?.takeIf(String::isNotBlank) ?: chapter.name)
        return (chapter.season?.takeIf { it >= 0 } ?: inferred.first) to
            (chapter.number?.takeIf { it.isFinite() && it >= 0 } ?: inferred.second)
    }

    fun parseEpisodeNumber(mangaTitle: String, chapter: Chapter): Double = rawSeasonAndNumber(mangaTitle, chapter).second ?: 0.0
    private val unwanted = Regex(
        "\\b(?:v|ver|vol|version|volume|season|staffel|saison|temporada|s)[^a-z]?[0-9]+",
    )
    private val unwantedWhiteSpace = Regex("\\s(?=extra|special|omake)")
    private val seasonKeyword = Regex(
        "\\b(?:staffel|season|saison|temporada|s)\\s*([0-9]+)",
    )
    private val episodeKeyword = Regex(
        "\\b(?:folge|episode|ep\\.?)\\s*([0-9]+(?:\\.[0-9]+)?)",
    )
    fun parseSeasonNumber(name: String): Int? = seasonKeyword.find(name.lowercase())?.groupValues?.get(1)?.toIntOrNull()
    // Lookbehind for "ch." followed by zero or more spaces.
    private val chNotation = Regex(
        "(?<=ch\\.) *([0-9]+)(\\.[0-9]+)?(\\.?[a-z]+)?",
    )
    private val bareNumber = Regex("([0-9]+)(\\.[0-9]+)?(\\.?[a-z]+)?")

    /**
     * Sort key for the UI list. Encodes season into the result so
     * multi-season anime sorts correctly: `season * 100_000 + episode`.
     */
    fun parseChapterNumber(mangaTitle: String, chapterName: String): Double {
        val (season, ep) = rawSeasonAndNumber(mangaTitle, chapterName)
        return withSeason(season, ep ?: 0.0)
    }

    /**
     * Episode number within a season — used for tracker updates
     * (MAL / AniList / Kitsu) and AniSkip lookups. The tracker entry is
     * already season-specific, so the season prefix is stripped.
     */
    fun parseEpisodeNumber(mangaTitle: String, chapterName: String): Double {
        val (_, ep) = rawSeasonAndNumber(mangaTitle, chapterName)
        return ep ?: 0.0
    }

    /**
     * The key that answers "are these two the same chapter / episode".
     *
     * Season is part of the answer. Without it, episode 1 of season 2 is the
     * same chapter as episode 1 of season 1, and whichever arrives second is
     * dropped before it reaches the library. A show with two seasons then
     * displays one of them.
     *
     * Null when the name carries no number at all, because "Special" and
     * "Prologue" are not all the same chapter either. Callers skip the
     * composite check in that case rather than folding them together.
     *
     * [scanlator] is omitted by callers deciding whether read state carries
     * over, since the same episode from a different group is still that episode.
     */
    fun chapterIdentityKey(
        mangaTitle: String?,
        chapterName: String?,
        scanlator: String? = null,
    ): String? {
        val title = mangaTitle.orEmpty()
        val name = chapterName?.takeIf { it.isNotBlank() } ?: return null
        val (season, ep) = rawSeasonAndNumber(title, name)
        if (ep == null || ep <= 0.0) return null
        return "$season::$ep::${scanlator.orEmpty()}"
    }

    /**
     * Raw (season, episode) pair, unbucketed — season is 0 if none matched.
     * Episode keeps its fractional part (e.g. 12.5).
     * Episode is null when the name has no detectable number at all (e.g. "Special", "Prologue") —
     * distinct from a genuine chapter 0.0.
     */
    fun rawSeasonAndNumber(mangaTitle: String, chapterName: String): Pair<Int, Double?> {
        val name = chapterName
            .lowercase()
            .replace(mangaTitle.lowercase(), "")
            .trim()
            .replace(',', '.')
            .replace('-', '.')
            .replace(unwantedWhiteSpace, "")

        val season = seasonKeyword.find(name)?.groupValues?.getOrNull(1)?.toIntOrNull() ?: 0

        episodeKeyword.find(name)?.let { match ->
            val ep = match.groupValues.getOrNull(1)?.toDoubleOrNull()
            return season to ep
        }

        // Strip season / volume noise, then look for ch.X or a bare number.
        val stripped = name.replace(unwanted, "")
        val ep = extractNumber(stripped)
        return season to ep
    }

    /**
     * Sort/identity keys for chapters. Buckets by season only if numbering actually
     * repeats across seasons (collisions >= 3).
     * Returns a map of Chapter ID to sort key. A null key indicates an unnumbered chapter.
     */
    fun chapterSortKeys(mangaTitle: String, chapters: List<Chapter>): Map<Long, Double?> {
        val raw = chapters.associate { it.id to rawSeasonAndNumber(mangaTitle, it) }
        val episodeToSeasons = mutableMapOf<Double, MutableSet<Int>>()

        for (pair in raw.values) {
            val ep = pair.second ?: continue
            episodeToSeasons.getOrPut(ep) { mutableSetOf() }.add(pair.first)
        }

        val collisions = episodeToSeasons.values.count { it.size > 1 }
        val resets = collisions >= 3

        return raw.mapValues { (_, pair) ->
            val ep = pair.second ?: return@mapValues null
            if (resets && pair.first > 0) {
                pair.first * 100_000.0 + ep
            } else {
                ep
            }
        }
    }

    /**
     * Count of whole numbers missing from the recognized chapter sequence.
     * E.g. chapters 1, 2, 4, 5 present means 1 (chapter 3) is missing.
     * Decimal extras (12.5) are floored into their whole chapter.
     */
    fun missingChapterCount(mangaTitle: String, chapters: List<Chapter>): Int {
        val numbers = mutableSetOf<Int>()
        for (chapter in chapters) {
            val (_, ep) = rawSeasonAndNumber(mangaTitle, chapter)
            if (ep != null) {
                numbers.add(ep.toInt())
            }
        }
        if (numbers.size < 2) return 0
        val lowest = numbers.minOrNull() ?: return 0
        val highest = numbers.maxOrNull() ?: return 0
        val expectedCount = highest - lowest + 1
        return maxOf(0, expectedCount - numbers.size)
    }

    /**
     * Number of chapters whose name has no detectable chapter/episode number at all
     * (e.g. "Special", "Prologue", "Extra").
     */
    fun unrecognizedChapterNumberCount(mangaTitle: String, chapters: List<Chapter>): Int {
        return chapters.count { chapter ->
            rawSeasonAndNumber(mangaTitle, chapter).second == null
        }
    }

    private fun withSeason(season: Int, ep: Double): Double =
        if (season > 0) season * 100_000.0 + ep else ep

    private fun extractNumber(name: String): Double? {
        chNotation.find(name)?.let { return fromMatch(it) }
        bareNumber.find(name)?.let { return fromMatch(it) }
        return null
    }

    private fun fromMatch(match: MatchResult): Double {
        val groups = match.groupValues
        val base = groups.getOrNull(1)?.toDoubleOrNull() ?: return 0.0
        val decimal = groups.getOrNull(2)?.takeIf { it.isNotEmpty() }
        val alpha = groups.getOrNull(3)?.takeIf { it.isNotEmpty() }
        return base + decimalAddition(decimal, alpha)
    }

    private fun decimalAddition(decimal: String?, alpha: String?): Double {
        if (!decimal.isNullOrEmpty()) return decimal.toDoubleOrNull() ?: 0.0
        if (!alpha.isNullOrEmpty()) {
            if ("extra" in alpha) return 0.99
            if ("omake" in alpha) return 0.98
            if ("special" in alpha) return 0.97
            val trimmed = alpha.removePrefix(".")
            if (trimmed.length == 1) return parseAlphaPostFix(trimmed[0])
        }
        return 0.0
    }

    private fun parseAlphaPostFix(c: Char): Double {
        val number = c.code - ('a'.code - 1)
        if (number >= 10) return 0.0
        return number / 10.0
    }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ChapterReleasePolicy.kt
  • Source · implementation · 115 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

3: data class ChapterReleasePreferences(
9: data class ChapterReleaseIdentity(
29: fun normalizeScanlator(name: String): String = name.trim().replace(whitespace, " ").lowercase()
31: fun chapterReleaseIdentity(
47: private fun namedChapterReleaseIdentity(mangaTitle: String, chapterName: String): ChapterReleaseIdentity? {
56: fun label(regex: Regex): Int? = regex.find(name)?.groupValues?.get(1)?.toIntOrNull()
64: fun chapterReleaseKey(
70: private fun Chapter.releaseIdentity(title: String): ChapterReleaseIdentity? =
77: fun selectChapterReleases(
87: fun downloaded(chapter: Chapter) = chapter.id in downloadedIds || chapter.downloadSize != null || chapter.archivePath.isNotBlank()
104: fun equivalentReleaseIds(mangaTitle: String, chapters: List<Chapter>, selectedIds: Set<Long>): Set<Long> {
110: fun chapterReadingOrder(mangaTitle: String, chapters: List<Chapter>): List<Chapter> {

How this file works

Release identity preserves number, season, volume, part, language and edition. Ambiguous ranges and unnumbered names remain independent unless explicit metadata establishes an identity. Selection first excludes hidden groups and unavailable offline releases, then ranks candidates by normalized user priority, downloaded status, normalized group, URL and ID. Those final tie-breakers make the winner independent of input order. Read/bookmark flags are projected from all equivalent releases, including filtered ones; the winner keeps its own file and page position. equivalentReleaseIds expands explicit group actions so clearing a flag does not leave it enabled on another equivalent row. chapterReadingOrder sorts by season, volume, number and part, with ID as the final tie-breaker.

Exact file bytes / download · SHA-256 cf9ebc4d3602a57e1e573fa3533ecbfa8eddb0a0f4dfae7f71e0f5711acb7e1f.

Complete file

package eu.friedcutlet.yokan.domain

data class ChapterReleasePreferences(
    val scanlatorPriority: List<String> = emptyList(),
    val skipDuplicates: Boolean = false,
)

/** Only explicit chapter/episode numbers or leading numeric chapter labels establish equivalence. */
data class ChapterReleaseIdentity(
    val number: Double,
    val season: Int?,
    val volume: Int?,
    val part: String,
    val language: String,
    val edition: String,
)

private val explicitNumber = Regex("\\b(?:chapter|chap|ch|episode|ep|folge)\\.?\\s*#?\\s*(\\d+(?:[.,]\\d+)?)([a-z]?)(?=\\s|[:.\\-]|$)")
private val leadingNumber = Regex("^#?(\\d+(?:[.,]\\d+)?)([a-z]?)(?=\\s|[:.\\-]|$)")
private val seasonLabel = Regex("\\b(?:season|staffel|saison|temporada|s)\\.?\\s*(\\d+)\\b")
private val volumeLabel = Regex("\\b(?:volume|vol|v)\\.?\\s*(\\d+)\\b")
private val editionLabel = Regex("\\b(?:special|extra|omake|oneshot|one-shot|colored|coloured|color|colour|remaster(?:ed)?|uncensored|censored|revised|bonus|part\\s*\\d+)\\b")
private val languageLabel = Regex("\\[(?:lang[:=]\\s*)?([a-z]{2}(?:-[a-z]{2})?)\\]")
private val whitespace = Regex("\\s+")
private val numberRange = Regex("^\\s*(?:[-–/&]|and|\\.)\\s*\\d")
private val namedLanguage = Regex("\\b(?:english|spanish|french|german|russian|portuguese|japanese|chinese|korean|italian|turkish)\\b")

/** Case/whitespace normalization only: punctuation and combined group names keep their meaning. */
fun normalizeScanlator(name: String): String = name.trim().replace(whitespace, " ").lowercase()

fun chapterReleaseIdentity(
    mangaTitle: String,
    chapterName: String,
    number: Double? = null,
    season: Int? = null,
    numberingName: String? = null,
): ChapterReleaseIdentity? {
    val named = namedChapterReleaseIdentity(mangaTitle, numberingName?.takeIf(String::isNotBlank) ?: chapterName)
    val validSeason = season?.takeIf { it >= 0 }
    val explicit = number?.takeIf { it.isFinite() && it >= 0 }
    return if (explicit != null) {
        named?.copy(number = explicit, season = validSeason ?: named.season)
            ?: ChapterReleaseIdentity(explicit, validSeason, null, "", "", "")
    } else named?.let { if (validSeason == null) it else it.copy(season = validSeason) }
}

private fun namedChapterReleaseIdentity(mangaTitle: String, chapterName: String): ChapterReleaseIdentity? {
    var name = chapterName.lowercase().trim()
    if (mangaTitle.isNotBlank()) name = name.replace(mangaTitle.lowercase(), "").trim()
    val matches = explicitNumber.findAll(name).toList()
    if (matches.size > 1) return null // Ranges/combined chapters are uncertain.
    val number = matches.singleOrNull() ?: leadingNumber.find(name) ?: return null
    val value = number.groupValues[1].replace(',', '.').toDoubleOrNull()?.takeIf { it.isFinite() } ?: return null
    // A second number after a range separator is not a decimal or a separate release.
    if (numberRange.containsMatchIn(name.substring(number.range.last + 1))) return null
    fun label(regex: Regex): Int? = regex.find(name)?.groupValues?.get(1)?.toIntOrNull()
    return ChapterReleaseIdentity(value, label(seasonLabel), label(volumeLabel), number.groupValues[2],
        (languageLabel.findAll(name).map { it.groupValues[1] } + namedLanguage.findAll(name).map { it.value })
            .distinct().sorted().joinToString("/"),
        editionLabel.findAll(name).map { it.value.replace(whitespace, " ") }.distinct().sorted().joinToString("/"))
}

/** Transient ingestion/read-state key; uncertain names retain their independent URL identity. */
fun chapterReleaseKey(
    mangaTitle: String?, chapterName: String?, scanlator: String? = null,
    number: Double? = null, season: Int? = null, numberingName: String? = null,
): String? = chapterReleaseIdentity(mangaTitle.orEmpty(), chapterName.orEmpty(), number, season, numberingName)
    ?.let { "$it::${normalizeScanlator(scanlator.orEmpty())}" }

private fun Chapter.releaseIdentity(title: String): ChapterReleaseIdentity? =
    chapterReleaseIdentity(title, name, number, season, numberingName)

/**
 * Select without deleting releases. Read/bookmark state belongs to an equivalence group while
 * file locations and page positions always belong to the actual winning release.
 */
fun selectChapterReleases(
    mangaTitle: String,
    chapters: List<Chapter>,
    preferences: ChapterReleasePreferences = ChapterReleasePreferences(),
    excludedScanlators: Set<String> = emptySet(),
    downloadedIds: Set<Long> = emptySet(),
    offlineOnly: Boolean = false,
    showAllReleases: Boolean = false,
): List<Chapter> {
    val hidden = excludedScanlators.map(::normalizeScanlator).toSet()
    fun downloaded(chapter: Chapter) = chapter.id in downloadedIds || chapter.downloadSize != null || chapter.archivePath.isNotBlank()
    val eligible = chapters.filter { normalizeScanlator(it.scanlator) !in hidden && (!offlineOnly || downloaded(it)) }
    if (!preferences.skipDuplicates || showAllReleases) return eligible
    val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) }
    val groups = chapters.groupBy { identities[it.id] ?: it.id }
    val ranks = preferences.scanlatorPriority.map(::normalizeScanlator).distinct().withIndex().associate { it.value to it.index }
    val comparator = compareBy<Chapter> { ranks[normalizeScanlator(it.scanlator)] ?: Int.MAX_VALUE }
        .thenBy { !downloaded(it) }.thenBy { normalizeScanlator(it.scanlator) }
        .thenBy { it.url }.thenBy { it.id }
    return eligible.groupBy { identities[it.id] ?: it.id }.map { (key, releases) ->
        val winner = releases.minWith(comparator)
        val equivalents = groups.getValue(key)
        winner.copy(isRead = equivalents.any { it.isRead }, isBookmarked = equivalents.any { it.isBookmarked })
    }
}

/** Explicit group actions can clear aggregated state as well as set it. Uncertain rows stay local. */
fun equivalentReleaseIds(mangaTitle: String, chapters: List<Chapter>, selectedIds: Set<Long>): Set<Long> {
    val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) }
    val selectedKeys = selectedIds.mapNotNull { identities[it] }.toSet()
    return chapters.filter { it.id in selectedIds || identities[it.id]?.let(selectedKeys::contains) == true }.mapTo(HashSet()) { it.id }
}

fun chapterReadingOrder(mangaTitle: String, chapters: List<Chapter>): List<Chapter> {
    val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) }
    return chapters.sortedWith(compareBy<Chapter> { identities[it.id]?.season ?: 0 }
        .thenBy { identities[it.id]?.volume ?: 0 }.thenBy { identities[it.id]?.number ?: 0.0 }
        .thenBy { identities[it.id]?.part.orEmpty() }.thenBy { it.id })
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ChapterUpdateSchedule.kt
  • Source · implementation · 29 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

12: fun meanChapterUpdateDays(uploadDates: Iterable<String>, now: Long = nowMillis()): Int? {
28: fun effectiveChapterUpdateDays(manualDays: Int?, uploadDates: Iterable<String>, now: Long = nowMillis()): Int =

How this file works

Upload dates are converted to valid past timestamps, deduplicated and sorted. The arithmetic mean of adjacent gaps equals (last - first) / (count - 1), so the function needs only the endpoints and count. It rounds to whole days and clamps a known short interval to one day. Fewer than two valid dates return null. A manual non-null interval overrides inference, including zero, which means always eligible. The default clock comes from util.nowMillis; the explicit now parameter keeps tests deterministic.

Exact file bytes / download · SHA-256 3d76f4ea8f58706350e3e067a940bc26a38dd3242e03b0b862b31a4877411ab1.

Complete file

package eu.friedcutlet.yokan.domain

import eu.friedcutlet.yokan.util.nowMillis
import kotlin.math.roundToInt
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn

private const val DayMillis = 86_400_000L

/** Mean gap between known releases. Duplicate dates do not count as new intervals. */
fun meanChapterUpdateDays(uploadDates: Iterable<String>, now: Long = nowMillis()): Int? {
    val dates = uploadDates.mapNotNull { raw ->
        val value = raw.trim()
        val date = value.toLongOrNull()?.let {
            if (it in 1L until 10_000_000_000L) it * 1_000L else it
        } ?: runCatching {
            LocalDate.parse(value.take(10)).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()
        }.getOrNull()
        date?.takeIf { it > 0 && it <= now }
    }.distinct().sorted()
    if (dates.size < 2) return null
    val mean = (dates.last() - dates.first()).toDouble() / (dates.size - 1) / DayMillis
    return mean.roundToInt().coerceAtLeast(1)
}

/** null = automatic, zero = every update, positive = a manual cooldown. */
fun effectiveChapterUpdateDays(manualDays: Int?, uploadDates: Iterable<String>, now: Long = nowMillis()): Int =
    manualDays?.coerceAtLeast(0) ?: meanChapterUpdateDays(uploadDates, now) ?: 0
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/Models.kt
  • Source · implementation · 295 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

3: enum class ItemType(val label: String) {
9: enum class Status(val label: String) {
20: enum class SourceCodeLanguage(val label: String) {
27: enum class TrackStatus(val label: String) {
39: enum class ReaderMode(val label: String) {
46: data class Repo(
52: data class Source(
75: data class Category(
84: data class Manga(
121: override fun toString(): String = "Manga(id=$id)"
122: override fun equals(other: Any?): Boolean {
165: override fun hashCode(): Int {
203: data class Chapter(
227: data class History(
243: data class Track(
258: data class UpdateEntry(
271: data class UserSettings(
290: enum class DisplayType(val label: String) {

How this file works

Manga is a title for all three media types, selected by ItemType. A Chapter represents either a comic chapter, novel chapter or anime episode. Source identity and title/chapter IDs connect the repository to stored records; display labels are separate from those identities. UserSettings is the smaller domain-facing settings projection, while the serialized database settings contain additional platform and feature preferences. Manga.equals compares cover bytes by content and includes every state field; hashCode follows the same fields. Without content equality, two independently loaded but identical cover arrays compare unequal. That can cause unnecessary state emissions or rendering; it does not by itself create a recomposition loop.

Exact file bytes / download · SHA-256 907fa3202e0c004bc73b89505226eb67767213576fce8b2e3f56ae9e3e8ce8ef.

Complete file

package eu.friedcutlet.yokan.domain

enum class ItemType(val label: String) {
    Manga("Manga"),
    Anime("Anime"),
    Novel("Novel"),
}

enum class Status(val label: String) {
    Ongoing("Ongoing"),
    Completed("Completed"),
    Canceled("Canceled"),
    Unknown("Unknown"),
    OnHiatus("On hiatus"),
    PublishingFinished("Publishing finished"),
    Licensed("Licensed"),
    Upcoming("Upcoming"),
}

enum class SourceCodeLanguage(val label: String) {
    JavaScript("JavaScript"),
    Mihon("Mihon"),
    LnReader("LNReader"),
    Aidoku("Aidoku"),
}

enum class TrackStatus(val label: String) {
    Reading("Reading"),
    Completed("Completed"),
    OnHold("On hold"),
    Dropped("Dropped"),
    PlanToRead("Plan to read"),
    ReReading("Re-reading"),
    Watching("Watching"),
    PlanToWatch("Plan to watch"),
    ReWatching("Re-watching"),
}

enum class ReaderMode(val label: String) {
    Paged("Paged"),
    ContinuousVertical("Continuous vertical"),
    Webtoon("Webtoon"),
    Novel("Novel"),
}

data class Repo(
    val name: String,
    val jsonUrl: String,
    val website: String? = null,
)

data class Source(
    val id: Long,
    val name: String,
    val baseUrl: String,
    val lang: String,
    val itemType: ItemType,
    val typeSource: String,
    val iconUrl: String? = null,
    val isActive: Boolean = true,
    val isAdded: Boolean = false,
    val isPinned: Boolean = false,
    val isNsfw: Boolean = false,
    val hasCloudflare: Boolean = false,
    val supportLatest: Boolean = false,
    val version: String = "0.0.1",
    val versionLast: String = "0.0.1",
    val lastUsed: Boolean = false,
    val isObsolete: Boolean = false,
    val sourceCodeLanguage: SourceCodeLanguage = SourceCodeLanguage.JavaScript,
    val repo: Repo? = null,
    val notes: String = "",
)

data class Category(
    val id: Long,
    val name: String,
    val forItemType: ItemType,
    val position: Int,
    val hidden: Boolean = false,
    val shouldUpdate: Boolean = true,
)

data class Manga(
    val id: Long,
    val name: String,
    val alternativeTitles: List<String> = emptyList(),
    val link: String,
    val imageUrl: String? = null,
    val customCoverImage: ByteArray? = null,
    val customCoverFromTracker: String? = null,
    val description: String,
    val author: String? = null,
    val artist: String? = null,
    val status: Status,
    val itemType: ItemType,
    val genres: List<String> = emptyList(),
    val favorite: Boolean = false,
    val source: String,
    val lang: String,
    val dateAddedMillis: Long,
    val lastUpdateMillis: Long,
    val lastReadMillis: Long = 0L,
    val categories: List<Long> = emptyList(),
    val isLocalArchive: Boolean = false,
    val smartUpdateDays: Int? = null,
    val sourceId: Long? = null,
    val metadataServerId: String? = null,
    val metadataSource: String? = null,
    val metadataUpdatedAt: Long = 0L,
    val privateNote: String = "",
    val nextEpisodeAiringAt: Long = 0,
    val nextEpisodeNumber: Int? = null,
    val cast: List<TitleCredit> = emptyList(),
    /** Owning title when this record is one season of an Animetail Seasons-type title. */
    val parentId: Long? = null,
    /** Animetail `FetchType.Seasons`: this title lists season records instead of episodes. */
    val fetchesSeasons: Boolean = false,
    val seasonNumber: Double? = null,
) {
    override fun toString(): String = "Manga(id=$id)"
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || this::class != other::class) return false

        other as Manga

        if (id != other.id) return false
        if (favorite != other.favorite) return false
        if (dateAddedMillis != other.dateAddedMillis) return false
        if (lastUpdateMillis != other.lastUpdateMillis) return false
        if (lastReadMillis != other.lastReadMillis) return false
        if (isLocalArchive != other.isLocalArchive) return false
        if (smartUpdateDays != other.smartUpdateDays) return false
        if (sourceId != other.sourceId) return false
        if (metadataServerId != other.metadataServerId) return false
        if (metadataSource != other.metadataSource) return false
        if (metadataUpdatedAt != other.metadataUpdatedAt) return false
        if (name != other.name) return false
        if (alternativeTitles != other.alternativeTitles) return false
        if (link != other.link) return false
        if (imageUrl != other.imageUrl) return false
        if (!customCoverImage.contentEquals(other.customCoverImage)) return false
        if (customCoverFromTracker != other.customCoverFromTracker) return false
        if (privateNote != other.privateNote) return false
        if (nextEpisodeAiringAt != other.nextEpisodeAiringAt) return false
        if (nextEpisodeNumber != other.nextEpisodeNumber) return false
        if (description != other.description) return false
        if (author != other.author) return false
        if (artist != other.artist) return false
        if (status != other.status) return false
        if (itemType != other.itemType) return false
        if (genres != other.genres) return false
        if (source != other.source) return false
        if (lang != other.lang) return false
        if (categories != other.categories) return false
        if (cast != other.cast) return false
        if (parentId != other.parentId) return false
        if (fetchesSeasons != other.fetchesSeasons) return false
        if (seasonNumber != other.seasonNumber) return false

        return true
    }

    override fun hashCode(): Int {
        var result = id.hashCode()
        result = 31 * result + favorite.hashCode()
        result = 31 * result + dateAddedMillis.hashCode()
        result = 31 * result + lastUpdateMillis.hashCode()
        result = 31 * result + lastReadMillis.hashCode()
        result = 31 * result + isLocalArchive.hashCode()
        result = 31 * result + (smartUpdateDays ?: 0)
        result = 31 * result + (sourceId?.hashCode() ?: 0)
        result = 31 * result + (metadataServerId?.hashCode() ?: 0)
        result = 31 * result + (metadataSource?.hashCode() ?: 0)
        result = 31 * result + metadataUpdatedAt.hashCode()
        result = 31 * result + name.hashCode()
        result = 31 * result + alternativeTitles.hashCode()
        result = 31 * result + link.hashCode()
        result = 31 * result + (imageUrl?.hashCode() ?: 0)
        result = 31 * result + (customCoverImage?.contentHashCode() ?: 0)
        result = 31 * result + (customCoverFromTracker?.hashCode() ?: 0)
        result = 31 * result + privateNote.hashCode()
        result = 31 * result + nextEpisodeAiringAt.hashCode()
        result = 31 * result + (nextEpisodeNumber ?: 0)
        result = 31 * result + description.hashCode()
        result = 31 * result + (author?.hashCode() ?: 0)
        result = 31 * result + (artist?.hashCode() ?: 0)
        result = 31 * result + status.hashCode()
        result = 31 * result + itemType.hashCode()
        result = 31 * result + genres.hashCode()
        result = 31 * result + source.hashCode()
        result = 31 * result + lang.hashCode()
        result = 31 * result + categories.hashCode()
        result = 31 * result + cast.hashCode()
        result = 31 * result + (parentId?.hashCode() ?: 0)
        result = 31 * result + fetchesSeasons.hashCode()
        result = 31 * result + (seasonNumber?.hashCode() ?: 0)
        return result
    }
}

data class Chapter(
    val id: Long,
    val mangaId: Long,
    val name: String,
    val url: String,
    val dateUpload: String = "",
    val scanlator: String = "",
    val isBookmarked: Boolean = false,
    val isRead: Boolean = false,
    val lastPageRead: String = "",
    val archivePath: String = "",
    /** Effective filler state: the user's [fillerOverride] when set, otherwise the source value. */
    val isFiller: Boolean = false,
    val thumbnailUrl: String? = null,
    val description: String? = null,
    val downloadSize: String? = null,
    val duration: String? = null,
    val fetchedAt: Long = 0,
    val number: Double? = null,
    val season: Int? = null,
    val numberingName: String? = null,
    val fillerOverride: Boolean? = null,
)

data class History(
    val id: Long,
    val mangaId: Long,
    val chapterId: Long,
    val itemType: ItemType,
    val title: String,
    val chapterName: String,
    val date: String,
    val readingTimeSeconds: Int,
    val updatedAt: Long,
    /** Last reading position recorded for the chapter (page number or %). Empty when never opened. */
    val lastPageRead: String = "",
    /** Whether the chapter is fully read; used by the History row to label "Finished" vs "Resume". */
    val chapterIsRead: Boolean = false,
)

data class Track(
    val id: Long,
    val libraryId: Long,
    val mediaId: Long,
    val mangaId: Long,
    val syncId: Int,
    val title: String,
    val progress: Int,
    val total: Int,
    val score: Int,
    val status: TrackStatus,
    val trackingUrl: String,
    val itemType: ItemType,
)

data class UpdateEntry(
    val id: Long,
    val mangaId: Long,
    val chapterId: Long,
    val itemType: ItemType,
    val title: String,
    val chapterName: String,
    val source: String,
    val date: String,
    val isRead: Boolean,
    val updatedAt: Long,
)

data class UserSettings(
    val displayType: DisplayType = DisplayType.ComfortableGrid,
    val followSystemTheme: Boolean = true,
    val darkTheme: Boolean = false,
    val incognitoMode: Boolean = false,
    val downloadedOnly: Boolean = false,
    val defaultReaderMode: ReaderMode = ReaderMode.Paged,
    val libraryShowCategoryTabs: Boolean = true,
    val libraryShowLanguage: Boolean = true,
    val libraryShowSource: Boolean = false,
    val libraryShowNumbersOfItems: Boolean = true,
    val showPagesNumber: Boolean = true,
    val concurrentDownloads: Int = 3,
    val allowConcurrentDownloads: Boolean = true,
    val downloadDelaySeconds: Int = 0,
    val checkForAppUpdates: Boolean = true,
    val checkForExtensionUpdates: Boolean = true,
)

enum class DisplayType(val label: String) {
    CompactGrid("Compact grid"),
    ComfortableGrid("Comfortable grid"),
    CoverOnlyGrid("Cover-only grid"),
    List("List"),
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/PrivateNotes.kt
  • Source · implementation · 11 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

4: fun mergePrivateNotes(existing: String, incoming: String): String {

How this file works

The merge has three early exits: an empty incoming note contributes nothing, an identical note is already present, and a note already appended at the end is not appended again. Otherwise it preserves both texts with a visible separator. This is repeated-import protection for these cases, not a general set-based or commutative text merge.

Exact file bytes / download · SHA-256 ae13c4bc28d337539855b8278215e845159d1e6bf021a07864059f1a5849e36b.

Complete file

package eu.friedcutlet.yokan.domain

/** Retain both texts, without duplicating an unchanged note on a repeated import/migration. */
fun mergePrivateNotes(existing: String, incoming: String): String {
    val separator = "\n\n---\n\n"
    return when {
        incoming.isEmpty() || existing == incoming || existing.endsWith(separator + incoming) -> existing
        existing.isEmpty() -> incoming
        else -> existing + separator + incoming
    }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/TitleCredit.kt
  • Source · implementation · 12 lines.
  • Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):

7: data class TitleCredit(

How this file works

The serializable cast/credit record preserves the external image_url field through @SerialName, while callers use the Kotlin property imageUrl. Optional role, character and image values remain nullable so missing upstream data stays distinct from an invented value.

Exact file bytes / download · SHA-256 7e44e9f5c98af23a8bdf9bd8a2e09afd8eea90af26d2989a0f7d85eb56ccfa22.

Complete file

package eu.friedcutlet.yokan.domain

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class TitleCredit(
    val name: String,
    val role: String? = null,
    val character: String? = null,
    @SerialName("image_url") val imageUrl: String? = null,
)
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/domain/ChapterRecognitionTest.kt
  • Source · test / fixture · 171 lines.
  • Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):

8: class ChapterRecognitionTest {
10: private fun dummyChapter(id: Long, name: String) = Chapter(
18: fun parsesStandardChaptersAndDecimalNumbers() {
33: fun distinguishesUnnumberedChaptersFromChapterZero() {
48: fun detectsMissingChaptersInSequence() {
83: fun countsUnrecognizedChapters() {
95: fun chapterSortKeysPreservesUnnumberedAndDecimals() {
111: fun sameEpisodeNumberInTwoSeasonsIsTwoChapters() {
118: fun shorterSecondSeasonSurvivesTheFirst() {
130: fun twoFullSeasonsOfSameLengthBothSurvive() {
142: fun deduplicationWithinOneSeasonStillWorks() {
149: fun nameWithNoNumberIsNotAnIdentity() {
155: fun decimalChaptersStayApart() {
162: fun scanlatorSeparatesReleasesAndIsOptional() {

How this file works

The assertions cover decimals, chapter zero versus unnumbered content, gap counts, conditional season sort buckets and identity keys. Reproduce the entire suite; the season-reset cases catch regressions that a three-case introductory parser test misses.

Exact file bytes / download · SHA-256 81afad082a382727cdfb7507b16df823256aa903db3b3f591451e2bf844eef5e.

Complete file

package eu.friedcutlet.yokan.domain

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class ChapterRecognitionTest {

    private fun dummyChapter(id: Long, name: String) = Chapter(
        id = id,
        mangaId = 1L,
        url = "/chapter/$id",
        name = name,
    )

    @Test
    fun parsesStandardChaptersAndDecimalNumbers() {
        val (s1, ep1) = ChapterRecognition.rawSeasonAndNumber("One Piece", "Chapter 1050")
        assertEquals(0, s1)
        assertEquals(1050.0, ep1)

        val (s2, ep2) = ChapterRecognition.rawSeasonAndNumber("Spy x Family", "Chapter 12.5 - Extra")
        assertEquals(0, s2)
        assertEquals(12.5, ep2)

        val (s3, ep3) = ChapterRecognition.rawSeasonAndNumber("Attack on Titan", "Season 2 Episode 5")
        assertEquals(2, s3)
        assertEquals(5.0, ep3)
    }

    @Test
    fun distinguishesUnnumberedChaptersFromChapterZero() {
        val (s0, ep0) = ChapterRecognition.rawSeasonAndNumber("Jujutsu Kaisen", "Chapter 0")
        assertEquals(0.0, ep0)

        val (sSpec, epSpec) = ChapterRecognition.rawSeasonAndNumber("Jujutsu Kaisen", "Special")
        assertNull(epSpec)

        val (sPrologue, epPrologue) = ChapterRecognition.rawSeasonAndNumber("Solo Leveling", "Prologue")
        assertNull(epPrologue)

        val (sOmake, epOmake) = ChapterRecognition.rawSeasonAndNumber("Naruto", "Omake")
        assertNull(epOmake)
    }

    @Test
    fun detectsMissingChaptersInSequence() {
        val chapters = listOf(
            dummyChapter(1L, "Chapter 1"),
            dummyChapter(2L, "Chapter 2"),
            dummyChapter(4L, "Chapter 4"),
            dummyChapter(5L, "Chapter 5"),
        )
        // Missing chapter 3
        assertEquals(1, ChapterRecognition.missingChapterCount("Manga", chapters))

        val complete = listOf(
            dummyChapter(1L, "Chapter 1"),
            dummyChapter(2L, "Chapter 2"),
            dummyChapter(3L, "Chapter 3"),
        )
        assertEquals(0, ChapterRecognition.missingChapterCount("Manga", complete))

        // Multiple missing (chapters 2 and 4 missing)
        val gap2 = listOf(
            dummyChapter(1L, "Chapter 1"),
            dummyChapter(3L, "Chapter 3"),
            dummyChapter(5L, "Chapter 5"),
        )
        assertEquals(2, ChapterRecognition.missingChapterCount("Manga", gap2))

        // Decimals do not create false gaps
        val withDecimal = listOf(
            dummyChapter(1L, "Chapter 1"),
            dummyChapter(2L, "Chapter 1.5"),
            dummyChapter(3L, "Chapter 2"),
        )
        assertEquals(0, ChapterRecognition.missingChapterCount("Manga", withDecimal))
    }

    @Test
    fun countsUnrecognizedChapters() {
        val chapters = listOf(
            dummyChapter(1L, "Prologue"),
            dummyChapter(2L, "Chapter 1"),
            dummyChapter(3L, "Special"),
            dummyChapter(4L, "Extra"),
            dummyChapter(5L, "Chapter 2"),
        )
        assertEquals(3, ChapterRecognition.unrecognizedChapterNumberCount("Manga", chapters))
    }

    @Test
    fun chapterSortKeysPreservesUnnumberedAndDecimals() {
        val chapters = listOf(
            dummyChapter(1L, "Special"),
            dummyChapter(2L, "Chapter 12.5"),
            dummyChapter(3L, "Prologue"),
            dummyChapter(4L, "Chapter 13"),
        )
        val keys = ChapterRecognition.chapterSortKeys("Manga", chapters)

        assertNull(keys[1L]) // Special has null key
        assertEquals(12.5, keys[2L])
        assertNull(keys[3L]) // Prologue has null key
        assertEquals(13.0, keys[4L])
    }

    @Test
    fun sameEpisodeNumberInTwoSeasonsIsTwoChapters() {
        val s1 = ChapterRecognition.chapterIdentityKey("Clevatess", "Staffel 1 Folge 1")
        val s2 = ChapterRecognition.chapterIdentityKey("Clevatess", "Staffel 2 Folge 1")
        assertTrue(s1 != s2)
    }

    @Test
    fun shorterSecondSeasonSurvivesTheFirst() {
        val keys = mutableSetOf<String?>()
        for (e in 1..12) {
            keys += ChapterRecognition.chapterIdentityKey("Clevatess", "Staffel 1 Folge $e")
        }
        for (e in 1..8) {
            keys += ChapterRecognition.chapterIdentityKey("Clevatess", "Staffel 2 Folge $e")
        }
        assertEquals(20, keys.size)
    }

    @Test
    fun twoFullSeasonsOfSameLengthBothSurvive() {
        val keys = mutableSetOf<String?>()
        for (e in 1..25) {
            keys += ChapterRecognition.chapterIdentityKey("Code Geass", "Season 1 Episode $e")
        }
        for (e in 1..25) {
            keys += ChapterRecognition.chapterIdentityKey("Code Geass", "Season 2 Episode $e")
        }
        assertEquals(50, keys.size)
    }

    @Test
    fun deduplicationWithinOneSeasonStillWorks() {
        val k1 = ChapterRecognition.chapterIdentityKey("Clevatess", "Staffel 1 Folge 3")
        val k2 = ChapterRecognition.chapterIdentityKey("Clevatess", "Staffel 1 Folge 3")
        assertEquals(k1, k2)
    }

    @Test
    fun nameWithNoNumberIsNotAnIdentity() {
        assertNull(ChapterRecognition.chapterIdentityKey("Code Geass", "Special"))
        assertNull(ChapterRecognition.chapterIdentityKey("Code Geass", "Prologue"))
    }

    @Test
    fun decimalChaptersStayApart() {
        val ch12 = ChapterRecognition.chapterIdentityKey("One Piece", "Chapter 12")
        val ch12_5 = ChapterRecognition.chapterIdentityKey("One Piece", "Chapter 12.5")
        assertTrue(ch12 != ch12_5)
    }

    @Test
    fun scanlatorSeparatesReleasesAndIsOptional() {
        val groupA = ChapterRecognition.chapterIdentityKey("One Piece", "Chapter 12", "GroupA")
        val groupB = ChapterRecognition.chapterIdentityKey("One Piece", "Chapter 12", "GroupB")
        val noGroup = ChapterRecognition.chapterIdentityKey("One Piece", "Chapter 12")

        assertTrue(groupA != groupB)
        assertEquals(noGroup, ChapterRecognition.chapterIdentityKey("One Piece", "Chapter 12"))
    }
}

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/domain/ChapterReleasePolicyTest.kt
  • Source · test / fixture · 101 lines.
  • Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):

18: class ChapterReleasePolicyTest {
19: private fun chapter(id: Long, name: String = "Chapter 1", group: String = "") = Chapter(id, 100, name, "/release/$id", scanlator = group)

How this file works

The tests specify deterministic preferred winners, offline alternatives, conservative identities, state projection and explicit group actions. Pay particular attention to retaining the winning release's own page/file data and keeping uncertain names independent. Some settings/repository assertions need later chapters before they compile.

Exact file bytes / download · SHA-256 725bef6b113124dded09e90cf9886eefa5729e688900f9a418fa26f6abf4cea2.

Complete file

package eu.friedcutlet.yokan.domain

import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.database.movedScanlator
import eu.friedcutlet.yokan.database.withChapterReleasePreference
import eu.friedcutlet.yokan.database.withoutChapterReleaseOverride
import eu.friedcutlet.yokan.services.library.filterChapters
import eu.friedcutlet.yokan.database.DbChapterFilter
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class ChapterReleasePolicyTest {
    private fun chapter(id: Long, name: String = "Chapter 1", group: String = "") = Chapter(id, 100, name, "/release/$id", scanlator = group)
    private val skip = ChapterReleasePreferences(listOf("Preferred", "Fallback"), true)

    @Test fun preferredReleasesWinRegardlessOfInsertionOrderAndExcludedGroupsNeverWin() {
        val rows = listOf(chapter(1, group = "Fallback"), chapter(9, group = " Preferred "), chapter(2, "Chapter 2", "Fallback"))
        val expected = setOf(9L, 2L)
        assertEquals(expected, selectChapterReleases("Fixture", rows, skip).map { it.id }.toSet())
        assertEquals(expected, selectChapterReleases("Fixture", rows.reversed(), skip).map { it.id }.toSet())
        assertEquals(setOf(1L, 2L), selectChapterReleases("Fixture", rows, skip, setOf("PREFERRED")).map { it.id }.toSet())
    }

    @Test fun missingPreferencesUseDeterministicDownloadedFallbackAndOfflineCanUseAnAlternate() {
        val rows = listOf(chapter(1, group = "A"), chapter(2, group = "B").copy(archivePath = "/saved/b"))
        val missing = ChapterReleasePreferences(listOf("Missing"), true)
        assertEquals(2L, selectChapterReleases("Fixture", rows, missing).single().id)
        assertEquals(2L, selectChapterReleases("Fixture", rows.reversed(), missing).single().id)
        val preferA = ChapterReleasePreferences(listOf("A", "B"), true)
        assertEquals(1L, selectChapterReleases("Fixture", rows, preferA).single().id)
        assertEquals(2L, selectChapterReleases("Fixture", rows, preferA, offlineOnly = true).single().id)
    }

    @Test fun identityPreservesSeasonsVolumesFractionsPartsEditionsLanguagesAndChapterZero() {
        val names = listOf("Chapter 1", "Vol. 1 Chapter 1", "Vol. 2 Chapter 1", "Season 1 Episode 1",
            "Season 2 Episode 1", "Chapter 1.5", "Chapter 1a", "Chapter 1 Special", "Chapter 1 Extra",
            "Chapter 1 [en]", "Chapter 1 [fr]", "Chapter 1 English", "Chapter 1 Russian", "Chapter 0")
        val rows = names.mapIndexed { index, name -> chapter(index.toLong() + 1, name) }
        assertEquals(names.size, selectChapterReleases("Fixture", rows, skip).size)
        assertEquals(chapterReleaseIdentity("Fixture", "Ch. 01.50"), chapterReleaseIdentity("Fixture", "Chapter 1.5"))
        assertNotEquals(chapterReleaseIdentity("Fixture", "Chapter 12 Extra"), chapterReleaseIdentity("Fixture", "Chapter 12.99"))
    }

    @Test fun uncertainOrUnnumberedEntriesStaySeparate() {
        val names = listOf("Special", "Special", "Prologue", "A 2026 anniversary", "Chapter 1-2", "Chapter 1 / 2", "Ch. 1 and Ch. 2", "Chapter 1.2.3", "Chapter 1 & 2")
        names.forEach { assertNull(chapterReleaseIdentity("Fixture", it)) }
        assertEquals(names.size, selectChapterReleases("Fixture", names.mapIndexed { index, name -> chapter(index.toLong(), name) }, skip).size)
    }

    @Test fun readAndBookmarkProjectionPreservesTheActualWinnersFilesAndPagePosition() {
        val original = chapter(1, group = "Fallback").copy(isRead = true, isBookmarked = true, lastPageRead = "12", archivePath = "/old")
        val preferred = chapter(2, group = "Preferred").copy(lastPageRead = "3")
        val winner = selectChapterReleases("Fixture", listOf(original, preferred), skip).single()
        assertEquals(preferred.copy(isRead = true, isBookmarked = true), winner)
        assertEquals("/old", original.archivePath)
        assertEquals(setOf(1L, 2L), equivalentReleaseIds("Fixture", listOf(original, preferred), setOf(2L)))
    }

    @Test fun statusFiltersRunAfterSelectionAndNeverChooseAnUnpreferredUnreadDuplicate() {
        val rows = listOf(chapter(1, group = "Fallback").copy(isRead = true), chapter(2, group = "Preferred"))
        val db = DbSettings(chapterReleasePreferences = listOf(DbChapterReleasePreference(scanlatorPriority = listOf("Preferred"), skipDuplicateReleases = true)),
            chapterFilterUnreadList = listOf(DbChapterFilter(100, 1)))
        val manga = Manga(100, "Fixture", link = "/fixture", description = "", status = Status.Ongoing, itemType = ItemType.Manga,
            source = "Fixture", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0)
        assertTrue(filterChapters(manga, rows, db, emptySet()).isEmpty())
        val bookmarked = rows.map { if (it.id == 1L) it.copy(isBookmarked = true) else it }
        assertEquals(2L, filterChapters(manga, bookmarked, db.copy(chapterFilterUnreadList = null,
            chapterFilterBookmarkedList = listOf(DbChapterFilter(100, 1))), emptySet()).single().id)
    }

    @Test fun showingAllReleasesKeepsActualIndividualStateAndStillHonorsExclusions() {
        val rows = listOf(chapter(1, group = "Fallback").copy(isRead = true), chapter(2, group = "Preferred"))
        assertEquals(rows, selectChapterReleases("Fixture", rows, skip, showAllReleases = true))
        assertEquals(listOf(rows.last()), selectChapterReleases("Fixture", rows, skip, setOf("Fallback"), showAllReleases = true))
        assertEquals(rows, selectChapterReleases("Fixture", rows))
    }

    @Test fun preferencesInheritOverrideResetAndSurviveSerializationWithUnknownGroups() {
        val defaults = DbChapterReleasePreference(scanlatorPriority = listOf(" A  Team ", "", "B"), skipDuplicateReleases = true)
        val db = DbSettings().withChapterReleasePreference(defaults)
            .withChapterReleasePreference(DbChapterReleasePreference(100, listOf("B", "A Team", ""), false))
        val reopened = Json.decodeFromString(DbSettings.serializer(), Json.encodeToString(DbSettings.serializer(), db))
        assertEquals(listOf("b", "a team", ""), reopened.chapterReleasePreference(100).scanlatorPriority)
        assertEquals(listOf("a team", "", "b"), reopened.chapterReleasePreference(200).scanlatorPriority)
        assertTrue(reopened.withoutChapterReleaseOverride(100).chapterReleasePreference(100).skipDuplicateReleases)
        assertEquals(listOf("", "a team", "b", "new"), movedScanlator(defaults.scanlatorPriority, listOf("New"), "", -1))
        assertNotEquals(normalizeScanlator("A+B"), normalizeScanlator("A B"))
    }

    @Test fun readingOrderKeepsVolumeAndSeasonResetsEvenWithOnlyOneCollidingChapter() {
        val rows = listOf(chapter(2, "Vol. 2 Chapter 1"), chapter(1, "Vol. 1 Chapter 1"),
            chapter(4, "Season 2 Episode 1"), chapter(3, "Season 1 Episode 1"))
        assertEquals(listOf(1L, 2L, 3L, 4L), chapterReadingOrder("Fixture", rows).map { it.id })
    }
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/domain/ChapterUpdateScheduleTest.kt
  • Source · test / fixture · 31 lines.
  • Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):

7: class ChapterUpdateScheduleTest {

How this file works

A fixed clock makes every expectation reproducible. The 1, 1 and 10 day gaps distinguish arithmetic mean (4 days) from median (1) and latest gap (10). Other cases exercise epoch seconds/milliseconds, future dates, duplicates, minimum known intervals and manual zero overrides.

Exact file bytes / download · SHA-256 a9be983c05ad8c5e957ad2c013b9a60b6e5a553a720aa0c4ac746947b3e7e41c.

Complete file

package eu.friedcutlet.yokan.domain

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class ChapterUpdateScheduleTest {
    private val now = 1_800_000_000_000L

    @Test fun usesArithmeticMeanRatherThanMedianOrLatestGap() {
        // Gaps 1, 1, and 10 days have mean 4, median 1, and latest gap 10.
        assertEquals(4, meanChapterUpdateDays(listOf("2026-01-01", "2026-01-02", "2026-01-03", "2026-01-13"), now))
    }

    @Test fun ignoresUnknownFutureAndDuplicateDatesAndNormalizesEpochSeconds() {
        assertEquals(7, meanChapterUpdateDays(listOf("1767225600", "1767830400000", "2026-01-08", "0", "-1", "unknown", "2099-01-01"), now))
    }

    @Test fun insufficientDataChecksEveryTimeAndShortGapsUseOneDay() {
        assertNull(meanChapterUpdateDays(listOf("2026-01-01", "2026-01-01"), now))
        assertEquals(0, effectiveChapterUpdateDays(null, emptyList(), now))
        assertEquals(1, meanChapterUpdateDays(listOf("1767225600", "1767225660"), now))
    }

    @Test fun manualChoicesOverrideAutomaticIncludingAlways() {
        val dates = listOf("2026-01-01", "2026-01-08")
        assertEquals(7, effectiveChapterUpdateDays(null, dates, now))
        assertEquals(0, effectiveChapterUpdateDays(0, dates, now))
        assertEquals(3, effectiveChapterUpdateDays(3, dates, now))
    }
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/domain/ExplicitChapterNumberTest.kt
  • Source · test / fixture · 62 lines.
  • Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):

10: class ExplicitChapterNumberTest {
11: private fun chapter(id: Long, number: Double, season: Int = 1, group: String = "") = Chapter(

How this file works

Custom display names must not erase explicit episode numbers, season identity, edition/language distinctions or persisted metadata. This suite crosses repository and database boundaries; run it after those dependencies exist. The sequence assertions also ensure opening an alternate release uses that release rather than an unrelated preferred file.

Exact file bytes / download · SHA-256 48f504446a7a8f48b438e00ebadfba665a08ad41067790c32b07ba2710012ad3.

Complete file

package eu.friedcutlet.yokan.domain

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.toDomainChapter
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.library.resolveReadingChapterSequence
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class ExplicitChapterNumberTest {
    private fun chapter(id: Long, number: Double, season: Int = 1, group: String = "") = Chapter(
        id, 1, "Custom title $id", "/episode/$id", scanlator = group,
        number = number, season = season, numberingName = "Episode $number [en]",
    )

    @Test fun renamedEpisodesKeepOrderGapDetectionAndPlaybackNumbering() {
        val chapters = listOf(chapter(1, 3.0), chapter(2, 1.0), chapter(3, 4.0))
        assertEquals(listOf(2L, 1L, 3L), chapterReadingOrder("Show", chapters).map { it.id })
        assertEquals(1, ChapterRecognition.missingChapterCount("Show", chapters))
        assertEquals(0, ChapterRecognition.unrecognizedChapterNumberCount("Show", chapters))
        assertEquals(3.0, ChapterRecognition.parseEpisodeNumber("Show", chapters[0]))
        assertEquals(1 to 3.0, ChapterRecognition.rawSeasonAndNumber("Show", chapters[0]))
        val invalid = chapters[0].copy(number = Double.NaN, season = -1, numberingName = "Episode 12.5")
        assertEquals(0 to 12.5, ChapterRecognition.rawSeasonAndNumber("Show", invalid))
        assertEquals(0, ChapterRecognition.parseSeasonNumber("Season 0"))
        assertEquals(2, ChapterRecognition.parseSeasonNumber("S02E12"))
        assertNull(ChapterRecognition.parseSeasonNumber("Opening Night"))
    }

    @Test fun releaseSelectionPreservesLanguageEditionAndSeasonAcrossCustomTitles() {
        val preferred = chapter(1, 1.0, group = "Preferred")
        val alternate = chapter(2, 1.0, group = "Other")
        val french = chapter(3, 1.0).copy(numberingName = "Episode 1 [fr]")
        val special = chapter(4, 1.0).copy(numberingName = "Episode 1 Special [en]")
        val seasonTwo = chapter(5, 1.0, season = 2)
        val raw = listOf(alternate, french, special, seasonTwo, preferred)
        val selected = selectChapterReleases("Show", raw, ChapterReleasePreferences(listOf("Preferred"), true))
        assertEquals(setOf(1L, 3L, 4L, 5L), selected.map { it.id }.toSet())
        assertEquals(setOf(1L, 2L), equivalentReleaseIds("Show", raw, setOf(2)))
        val sequence = resolveReadingChapterSequence("Show", 2, selected, raw)
        assertTrue(sequence.any { it.id == 2L })
        assertFalse(sequence.any { it.id == 1L })
        assertTrue(sequence.any { it.id == 5L })
    }

    @Test fun persistedNumberingMapsToDomainAndDuplicateReadActionsUseIt() = runTest {
        val source = DbChapter(id = 1, mangaId = 1, name = "Opening", url = "/one", number = 1.0, season = 2, numberingName = "Episode 1 [en]")
        val alternate = source.copy(id = 2, name = "Different title", url = "/alternate", scanlator = "Other")
        val otherSeason = source.copy(id = 3, name = "Opening", url = "/season-one", season = 1)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(mangas = listOf(DbManga(id = 1, itemType = DbItemType.Anime)), chapters = listOf(source, alternate, otherSeason)))
        val repository = DefaultYokanRepository(db)
        repository.setChaptersRead(setOf(1), true, autoReadDuplicates = true)
        assertTrue(assertNotNull(db.chapter(2)).isRead)
        assertFalse(assertNotNull(db.chapter(3)).isRead)
        val mapped = toDomainChapter(source)
        assertEquals(1.0, mapped.number)
        assertEquals(2, mapped.season)
        assertEquals("Episode 1 [en]", mapped.numberingName)
        val restored = DatabaseJson.decodeFromString(DbChapter.serializer(), DatabaseJson.encodeToString(DbChapter.serializer(), source))
        assertEquals(source, restored)
    }
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/domain/TestModels.kt
  • Source · test / fixture · 22 lines.
  • Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):

3: internal fun testManga(

How this file works

The factory creates small valid domain titles with predictable names, links and timestamps. Optional parameters vary only the fields relevant to each test, reducing fixture noise without changing production defaults.

Exact file bytes / download · SHA-256 709b5805e381a056e705e6da3c21be56fbc3eed6e4184e9392b8229a1a8252f2.

Complete file

package eu.friedcutlet.yokan.domain

internal fun testManga(
    id: Long,
    name: String = "Title $id",
    itemType: ItemType = ItemType.Manga,
    favorite: Boolean = true,
    categories: List<Long> = emptyList(),
): Manga = Manga(
    id = id,
    name = name,
    link = "/$id",
    description = "",
    status = Status.Ongoing,
    itemType = itemType,
    favorite = favorite,
    source = "Source",
    lang = "en",
    dateAddedMillis = 0,
    lastUpdateMillis = 0,
    categories = categories,
)

Search chapters, reference and source filenames.