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? = 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? = 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 = 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.seasonsOwnedByLibrary(): Set { 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? = 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? = null, val subtitles: List = emptyList(), val audios: List = 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? = null, val headers: List? = 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? = 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 = 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, )