DatabaseEntities.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/DatabaseEntities.kt
1package eu.friedcutlet.yokan.database23import eu.friedcutlet.yokan.domain.Manga4import kotlinx.serialization.Serializable56@Serializable7enum class DbActionType {8 RemoveItem,9 RemoveCategory,10 RemoveChapter,11 RemoveHistory,12 RemoveUpdate,13 RemoveExtension,14 RemoveTrack,15}1617@Serializable18enum class DbStatus {19 Ongoing,20 Completed,21 Canceled,22 Unknown,23 OnHiatus,24 PublishingFinished,25 // Append only: legacy metadata.json uses the original six ordinals.26 Licensed,27 Upcoming,28}2930@Serializable31enum class DbItemType {32 Manga,33 Anime,34 Novel,35}3637@Serializable38enum class DbSourceCodeLanguage {39 JavaScript,40 Mihon,41 LnReader,42 Aidoku,43}4445@Serializable46enum class DbTrackStatus {47 Reading,48 Completed,49 OnHold,50 Dropped,51 PlanToRead,52 ReReading,53 Watching,54 PlanToWatch,55 ReWatching,56}5758@Serializable59enum class DbDisplayType {60 CompactGrid,61 ComfortableGrid,62 CoverOnlyGrid,63 List,64}6566@Serializable67enum class DbScaleType {68 FitScreen,69 Stretch,70 FitWidth,71 FitHeight,72 OriginalSize,73 SmartFit,74}7576@Serializable77enum class DbBackgroundColor {78 Black,79 Grey,80 White,81 Automatic,82}8384@Serializable85enum class DbReaderMode {86 Vertical,87 Ltr,88 Rtl,89 VerticalContinuous,90 Webtoon,91 HorizontalContinuous,92 HorizontalContinuousRtl,93}9495@Serializable96enum class DbNovelTextAlign {97 Left,98 Center,99 Right,100 Block,101}102103@Serializable104enum class DbPageMode {105 OnePage,106 DoublePage,107}108109@Serializable110enum class DbSectionType {111 All,112 Anime,113 Manga,114}115116@Serializable117enum class DbDebandingType {118 None,119 Cpu,120 Gpu,121}122123@Serializable124enum class DbAudioChannel(val mpvName: String) {125 Auto("auto"),126 AutoSafe("auto-safe"),127 Mono("mono"),128 Stereo("stereo"),129 ReverseStereo("pan=[stereo|c0=c1|c1=c0]"),130}131132@Serializable133enum class DbColorFilterBlendMode {134 None,135 Multiply,136 Screen,137 Overlay,138 ColorDodge,139 Lighten,140 ColorBurn,141 Darken,142 Difference,143 Saturation,144 SoftLight,145 Plus,146 Exclusion,147}148149@Serializable150data class DbChangedPart(151 val id: Long = 0,152 val actionType: DbActionType,153 val isarId: Long? = null,154 val data: String,155 val clientDate: Long,156)157158/**159 * One unpushed change for the hub: a path of one entity and its new JSON value160 * (`null` = path removed). Keyed by (kind, id, path) so repeated edits coalesce;161 * `seq` orders and `hlc` timestamps the write. See [eu.friedcutlet.yokan.database.sync.SyncPaths].162 */163@Serializable164data class DbOutboxOp(165 val kind: Int,166 val id: Long,167 val path: String,168 val value: String? = null,169 val hlc: Long,170 val seq: Long,171 /** Hub history epoch in which this local operation was created. */172 val epoch: Int = 0,173)174175@Serializable176data class DbCategory(177 val id: Long = 0,178 val name: String,179 val forItemType: DbItemType,180 val position: Int? = null,181 val hidden: Boolean? = null,182 val shouldUpdate: Boolean? = null,183 val updatedAt: Long = 0,184)185186@Serializable187data class DbChapter(188 val id: Long = 0,189 val mangaId: Long? = null,190 val name: String? = null,191 val url: String = "",192 val dateUpload: String = "",193 val scanlator: String = "",194 val isBookmarked: Boolean = false,195 val isRead: Boolean = false,196 val lastPageRead: String = "",197 val archivePath: String = "",198 val isFiller: Boolean = false,199 val thumbnailUrl: String? = null,200 val description: String? = null,201 val downloadSize: String? = null,202 val duration: String? = null,203 val updatedAt: Long = 0,204 /** First successful discovery/import, independent of reading progress and source upload time. */205 val fetchedAt: Long = 0,206 /** Explicit source numbering survives display-title changes; null preserves name recognition. */207 val number: Double? = null,208 val season: Int? = null,209 /** Original source label keeps release edition/language identity when metadata supplies a title. */210 val numberingName: String? = null,211 /** User filler mark; null follows the source/sidecar value kept in [isFiller]. */212 val fillerOverride: Boolean? = null,213)214215/** The user's filler mark wins over the source value, which refresh paths keep writing to [DbChapter.isFiller]. */216val DbChapter.effectiveFiller: Boolean get() = fillerOverride ?: isFiller217218/**219 * Folds [other]'s user state into this copy of the same chapter: read/bookmark marks are kept if220 * either has them, the furthest numeric page wins (otherwise the first non-blank position), the221 * user filler mark falls back to [other]'s, and [DbChapter.updatedAt] is the newer of the two.222 */223internal fun DbChapter.mergeProgress(other: DbChapter): DbChapter = copy(224 isRead = isRead || other.isRead,225 isBookmarked = isBookmarked || other.isBookmarked,226 lastPageRead = mergePagePosition(lastPageRead, other.lastPageRead),227 fillerOverride = fillerOverride ?: other.fillerOverride,228 updatedAt = maxOf(updatedAt, other.updatedAt),229)230231private fun mergePagePosition(first: String, second: String): String {232 if (first.isBlank()) return second233 if (second.isBlank() || first == second) return first234 val firstNumber = first.toLongOrNull()235 val secondNumber = second.toLongOrNull()236 return if (firstNumber != null && secondNumber != null) maxOf(firstNumber, secondNumber).toString() else first237}238239/** Animetail `FetchType`: a [Seasons] title lists child season titles instead of episodes. */240@Serializable241enum class DbFetchType { Seasons, Episodes }242243@Serializable244data class DbCustomButton(245 val id: Long = 0,246 val title: String? = null,247 val codePress: String? = null,248 val codeLongPress: String = "",249 val codeStartup: String = "",250 val isFavourite: Boolean = false,251 val position: Int,252 val updatedAt: Long = 0,253) {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)257258 private fun interpolate(code: String, primaryId: Long): String =259 code.replace("\$id", id.toString()).replace("\$isPrimary", (primaryId == id).toString())260}261262@Serializable263data class DbDownload(264 val id: Long = 0,265 val chapterId: Long? = null,266 val succeeded: Int? = null,267 val failed: Int? = null,268 val total: Int? = null,269 val isDownload: Boolean? = null,270 val isStartDownload: Boolean? = null,271 val isPaused: Boolean = false,272 val storageLocation: String? = null,273 /** Device-local request options for restart recovery. */274 val requestJson: String? = null,275)276277@Serializable278data class DbHistory(279 val id: Long = 0,280 val mangaId: Long? = null,281 val chapterId: Long? = null,282 val itemType: DbItemType,283 val date: String? = null,284 val updatedAt: Long = 0,285 val readingTimeSeconds: Int? = null,286)287288@Serializable289data class DbManga(290 val id: Long = 0,291 val name: String? = null,292 val link: String? = null,293 val imageUrl: String? = null,294 val description: String? = null,295 val author: String? = null,296 val artist: String? = null,297 val status: DbStatus = DbStatus.Unknown,298 val itemType: DbItemType = DbItemType.Manga,299 val genre: List<String>? = null,300 val favorite: Boolean = false,301 val source: String? = null,302 val lang: String? = null,303 val dateAdded: Long? = null,304 val lastUpdate: Long? = null,305 val lastRead: Long = 0,306 val categories: List<Long>? = null,307 val isLocalArchive: Boolean = false,308 val customCoverImage: ByteArray? = null,309 val customCoverFromTracker: String? = null,310 val smartUpdateDays: Int? = null,311 val updatedAt: Long = 0,312 val sourceId: Long? = null,313 /** Private, local text. Excluded from every sync transport. */314 val privateNote: String = "",315 /** Provider-announced next episode airing time in epoch milliseconds; zero means unknown. */316 val nextEpisodeAiringAt: Long = 0,317 val nextEpisodeNumber: Int? = null,318 val airingScheduleUpdatedAt: Long = 0,319 val cast: List<eu.friedcutlet.yokan.domain.TitleCredit> = emptyList(),320 /** Owning Seasons-type title of this season record; null for top-level titles. */321 val parentId: Long? = null,322 val fetchType: DbFetchType = DbFetchType.Episodes,323 /** Source/folder season number; null when unknown (Animetail uses -1). */324 val seasonNumber: Double? = null,325) {326 override fun toString(): String = "DbManga(id=$id)"327328 // Content equality (the array by content): snapshot StateFlows drop "equal" values, so an329 // id-only equals silently swallowed manga edits. hashCode stays on the id, which is consistent.330 override fun equals(other: Any?): Boolean {331 if (this === other) return true332 if (other !is DbManga) return false333 return id == other.id && name == other.name && link == other.link && imageUrl == other.imageUrl &&334 description == other.description && author == other.author && artist == other.artist &&335 status == other.status && itemType == other.itemType && genre == other.genre &&336 favorite == other.favorite && source == other.source && lang == other.lang &&337 dateAdded == other.dateAdded && lastUpdate == other.lastUpdate && lastRead == other.lastRead &&338 categories == other.categories && isLocalArchive == other.isLocalArchive &&339 customCoverImage.contentEquals(other.customCoverImage) &&340 customCoverFromTracker == other.customCoverFromTracker && smartUpdateDays == other.smartUpdateDays &&341 updatedAt == other.updatedAt && sourceId == other.sourceId && privateNote == other.privateNote &&342 nextEpisodeAiringAt == other.nextEpisodeAiringAt && nextEpisodeNumber == other.nextEpisodeNumber &&343 airingScheduleUpdatedAt == other.airingScheduleUpdatedAt && cast == other.cast &&344 parentId == other.parentId && fetchType == other.fetchType && seasonNumber == other.seasonNumber345 }346347 override fun hashCode(): Int = id.hashCode()348}349350/** Season records whose parent chain reaches a library title; cache cleanup must keep them. */351fun Collection<DbManga>.seasonsOwnedByLibrary(): Set<Long> {352 val byId = associateBy { it.id }353 fun owned(manga: DbManga, depth: Int): Boolean =354 manga.favorite || (depth < 32 && manga.parentId?.let(byId::get)?.let { owned(it, depth + 1) } == true)355 return filter { it.parentId != null && owned(it, 0) }.mapTo(HashSet()) { it.id }356}357358@Serializable359data class DbPageUrl(360 val url: String,361 val fileName: String? = null,362 val headers: Map<String, String>? = null,363)364365@Serializable366data class DbRepo(367 val name: String? = null,368 val website: String? = null,369 val jsonUrl: String? = null,370 val hidden: Boolean? = null,371)372373@Serializable374data class DbLocalFolder(375 val name: String,376 val path: String,377)378379@Serializable380data class DbSource(381 val id: Long = 0,382 val name: String = "",383 val baseUrl: String = "",384 val lang: String = "",385 val isActive: Boolean = true,386 val isAdded: Boolean = false,387 val isPinned: Boolean = false,388 val isNsfw: Boolean = false,389 val sourceCode: String = "",390 val sourceCodeUrl: String = "",391 val typeSource: String = "",392 val iconUrl: String = "",393 val isFullData: Boolean = false,394 val hasCloudflare: Boolean = false,395 val lastUsed: Boolean = false,396 val dateFormat: String = "",397 val dateFormatLocale: String = "",398 val apiUrl: String = "",399 val version: String = "0.0.1",400 val versionLast: String = "0.0.1",401 val headers: String = "",402 val supportLatest: Boolean? = null,403 val filterList: String? = null,404 val preferenceList: String? = null,405 val itemType: DbItemType = DbItemType.Manga,406 val appMinVerReq: String = "",407 val additionalParams: String = "",408 val isLocal: Boolean = false,409 val isObsolete: Boolean = false,410 val sourceCodeLanguage: DbSourceCodeLanguage = DbSourceCodeLanguage.JavaScript,411 val notes: String = "",412 val repo: DbRepo? = null,413 val updatedAt: Long = 0,414) {415 val isTorrent: Boolean get() = typeSource.lowercase() == "torrent"416}417418@Serializable419data class DbSyncPreference(420 val syncId: Long? = null,421 val email: String? = null,422 val authToken: String? = null,423 val lastSyncManga: Long? = null,424 val lastSyncHistory: Long? = null,425 val lastSyncUpdate: Long? = null,426 val server: String? = null,427 val syncOn: Boolean = false,428 val autoSyncFrequency: Int = 0,429 val syncHistories: Boolean = false,430 val syncUpdates: Boolean = false,431 val syncSettings: Boolean = false,432 /** Hub delta cursor (`seq` of the last entity received). */433 val hubHead: Long = 0,434 /** Hub history epoch; a mismatch means "resync from zero". */435 val hubEpoch: Int = 0,436 /** A higher-epoch conflict was seen; clear only after the restored pull is applied. */437 val hubRecoveryPending: Boolean = false,438 /** Full-state bootstrap has completed for this configured hub. */439 val hubBootstrapComplete: Boolean = false,440 /** Last hybrid logical clock observed from the hub. */441 val hubHlc: Long = 0,442 /** Stable per-install id sent as `X-Device`. */443 val deviceId: String? = null,444 val serverProvider: SyncServerProvider = SyncServerProvider.YokanHub,445 val mangayomiIdMappings: String? = null,446)447448@Serializable449enum class SyncServerProvider {450 YokanHub,451 Mangayomi,452 /** Self-hosted SyncYomi server: whole Tachiyomi protobuf backup per account, ETag-guarded. */453 SyncYomi,454 /** Application-state file in the user's own Google Drive `appDataFolder` (not the `cloud://` backup path). */455 GoogleDrive,456}457458@Serializable459data class DbTrack(460 val id: Long = 0,461 val libraryId: Long? = null,462 val mediaId: Long? = null,463 val mangaId: Long? = null,464 val syncId: Int? = null,465 val title: String? = null,466 val lastChapterRead: Int? = null,467 val totalChapter: Int? = null,468 val score: Int? = null,469 val status: DbTrackStatus,470 val startedReadingDate: Long? = null,471 val finishedReadingDate: Long? = null,472 val trackingUrl: String? = null,473 val itemType: DbItemType = DbItemType.Manga,474 val updatedAt: Long = 0,475)476477@Serializable478data class DbTrackPreference(479 val syncId: Long? = null,480 val username: String? = null,481 val accountName: String? = null,482 val accountAvatarUrl: String? = null,483 val oauth: String? = null,484 val prefs: String? = null,485 val refreshing: Boolean? = null,486)487488@Serializable489data class DbTrackSearch(490 val id: Long? = null,491 val libraryId: Long? = null,492 val mediaId: Long? = null,493 val syncId: Int? = null,494 val title: String? = null,495 val lastChapterRead: Int? = null,496 val totalChapter: Int? = null,497 val score: Double? = null,498 val status: String = "",499 val startedReadingDate: Long? = null,500 val finishedReadingDate: Long? = null,501 val trackingUrl: String? = null,502 val coverUrl: String = "",503 val summary: String = "",504 val publishingStatus: String = "",505 val publishingType: String = "",506 val startDate: String = "",507)508509@Serializable510data class DbUpdate(511 val id: Long = 0,512 val mangaId: Long? = null,513 val chapterId: Long? = null,514 val chapterName: String? = null,515 val date: String? = null,516 val updatedAt: Long = 0,517)518519@Serializable520data class DbVideoTrack(521 val file: String? = null,522 val label: String? = null,523)524525@Serializable526data class DbVideo(527 val url: String,528 val quality: String,529 val originalUrl: String,530 val headers: Map<String, String>? = null,531 val subtitles: List<DbVideoTrack> = emptyList(),532 val audios: List<DbVideoTrack> = emptyList(),533 /** Source-provided WebVTT seek-preview track (sprite tiles addressed with `#xywh=`). */534 val thumbnailTrack: String? = null,535)536537@Serializable538data class DbCookie(539 val host: String? = null,540 val cookie: String? = null,541)542543@Serializable544data class DbSortLibraryManga(545 val reverse: Boolean = false,546 val index: Int = 0,547)548549@Serializable550data class DbSortChapter(551 val mangaId: Long? = null,552 val reverse: Boolean = false,553 val index: Int = 1,554)555556@Serializable557data class DbChapterFilter(558 val mangaId: Long? = null,559 val type: Int = 0,560)561562/** A chapter's saved page list; see `ChapterPageResolver` for when it is served. */563@Serializable564data class DbChapterPageUrls(565 val chapterId: Long? = null,566 val chapterUrl: String? = null,567 val urls: List<String>? = null,568 val headers: List<String>? = null,569 /** Null for lists saved before timestamps, or ones that needed credentials: never served as fresh. */570 val fetchedAt: Long? = null,571 val sourceId: Long? = null,572 /** The source's `DbSource.version` that produced the list; an update makes the list stale. */573 val sourceVersion: String? = null,574)575576@Serializable577data class DbChapterPageIndex(578 val chapterId: Long? = null,579 val index: Int? = null,580)581582@Serializable583data class DbPersonalReaderMode(584 val mangaId: Long? = null,585 val readerMode: DbReaderMode = DbReaderMode.Vertical,586)587588@Serializable589data class DbAutoScrollPages(590 val mangaId: Long? = null,591 val pageOffset: Double = 10.0,592 val autoScroll: Boolean = false,593)594595@Serializable596data class DbPersonalPageMode(597 val mangaId: Long? = null,598 val pageMode: DbPageMode = DbPageMode.OnePage,599)600601@Serializable602data class DbFilterScanlator(603 val mangaId: Long? = null,604 val scanlators: List<String>? = null,605)606607@Serializable608data class DbL10nLocale(609 val languageCode: String? = null,610 val countryCode: String? = null,611)612613@Serializable614data class DbCustomColorFilter(615 val a: Int? = null,616 val r: Int? = null,617 val g: Int? = null,618 val b: Int? = null,619)620621@Serializable622data class DbPlayerSubtitleSettings(623 val fontSize: Int = 45,624 val useBold: Boolean = true,625 val useItalic: Boolean = false,626 val textColorA: Int = 255,627 val textColorR: Int = 255,628 val textColorG: Int = 255,629 val textColorB: Int = 255,630 val borderColorA: Int = 255,631 val borderColorR: Int = 0,632 val borderColorG: Int = 0,633 val borderColorB: Int = 0,634 val backgroundColorA: Int = 0,635 val backgroundColorR: Int = 0,636 val backgroundColorG: Int = 0,637 val backgroundColorB: Int = 0,638)639640@Serializable641data class DbAlgorithmWeights(642 val genre: Int = 30,643 val setting: Int = 15,644 val synopsis: Int = 40,645 val theme: Int = 20,646)647648@Serializable649data class DbSourcePreference(650 val sourceId: Long,651 val key: String,652 val value: String,653)654655@Serializable656data class DbSavedSearch(657 val sourceId: Long,658 val name: String,659 val query: String,660 // Deterministic for query-only legacy rows; new presets supply a random stable ID.661 val id: String = "legacy:$sourceId:$name",662 val sourceIdentity: DbPresetSource? = null,663 val filters: List<DbPresetFilter> = emptyList(),664 val presetVersion: Int = 1,665 val filterSchemaRecorded: Boolean = false,666 /** Legacy rows whose source was missing during adoption need explicit rebinding. */667 val missingSourceIdentity: Boolean = false,668)669670@Serializable671data class DbUpdateError(672 val mangaId: Long,673 val name: String,674 val error: String,675)676