package eu.friedcutlet.yokan.database.room import eu.friedcutlet.yokan.database.DbActionType import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChangedPart import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbChapterPageUrls import eu.friedcutlet.yokan.database.DbFetchType import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbOutboxOp import eu.friedcutlet.yokan.database.DbRepo import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbSourceCodeLanguage import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.DbUpdate import kotlinx.serialization.json.Json internal val RowJson = Json { ignoreUnknownKeys = true encodeDefaults = true } private inline fun > enumOrDefault(name: String?, default: E): E = name?.let { runCatching { enumValueOf(it) }.getOrNull() } ?: default // ─── Manga ────────────────────────────────────────────────────────────────── internal fun DbManga.toCreditRows(): List = cast.mapIndexed { index, credit -> MangaCreditRow(id, index, credit.name, credit.role, credit.character, credit.imageUrl) } internal fun MangaCreditRow.toCredit() = eu.friedcutlet.yokan.domain.TitleCredit(name, role, character, imageUrl) fun DbManga.toRow(): MangaRow = MangaRow( id = id, name = name, link = link, imageUrl = imageUrl, description = description, author = author, artist = artist, status = status.name, itemType = itemType.name, genre = genre?.let { RowJson.encodeToString(it) }, favorite = favorite, source = source, lang = lang, dateAdded = dateAdded, lastUpdate = lastUpdate, lastRead = lastRead, categories = categories?.let { RowJson.encodeToString(it) }, isLocalArchive = isLocalArchive, customCoverImage = customCoverImage, customCoverFromTracker = customCoverFromTracker, smartUpdateDays = smartUpdateDays, updatedAt = updatedAt, sourceId = sourceId, privateNote = privateNote, nextEpisodeAiringAt = nextEpisodeAiringAt, nextEpisodeNumber = nextEpisodeNumber, airingScheduleUpdatedAt = airingScheduleUpdatedAt, parentId = parentId, fetchType = fetchType.name, seasonNumber = seasonNumber, ) fun MangaRow.toDb(): DbManga = DbManga( id = id, name = name, link = link, imageUrl = imageUrl, description = description, author = author, artist = artist, status = enumOrDefault(status, DbStatus.Unknown), itemType = enumOrDefault(itemType, DbItemType.Manga), genre = genre?.let { runCatching { RowJson.decodeFromString>(it) }.getOrNull() }, favorite = favorite, source = source, lang = lang, dateAdded = dateAdded, lastUpdate = lastUpdate, lastRead = lastRead, categories = categories?.let { runCatching { RowJson.decodeFromString>(it) }.getOrNull() }, isLocalArchive = isLocalArchive, customCoverImage = customCoverImage, customCoverFromTracker = customCoverFromTracker, smartUpdateDays = smartUpdateDays, updatedAt = updatedAt, sourceId = sourceId, privateNote = privateNote, nextEpisodeAiringAt = nextEpisodeAiringAt, nextEpisodeNumber = nextEpisodeNumber, airingScheduleUpdatedAt = airingScheduleUpdatedAt, parentId = parentId, fetchType = enumOrDefault(fetchType, DbFetchType.Episodes), seasonNumber = seasonNumber, ) // ─── Chapter ──────────────────────────────────────────────────────────────── fun DbChapter.toRow(): ChapterRow = ChapterRow( id = id, mangaId = mangaId, name = name, url = url, dateUpload = dateUpload, scanlator = scanlator, isBookmarked = isBookmarked, isRead = isRead, lastPageRead = lastPageRead, archivePath = archivePath, isFiller = isFiller, thumbnailUrl = thumbnailUrl, description = description, downloadSize = downloadSize, duration = duration, updatedAt = updatedAt, fetchedAt = fetchedAt, number = number, season = season, numberingName = numberingName, fillerOverride = fillerOverride, ) fun ChapterRow.toDb(): DbChapter = DbChapter( id = id, mangaId = mangaId, name = name, url = url, dateUpload = dateUpload, scanlator = scanlator, isBookmarked = isBookmarked, isRead = isRead, lastPageRead = lastPageRead, archivePath = archivePath, isFiller = isFiller, thumbnailUrl = thumbnailUrl, description = description, downloadSize = downloadSize, duration = duration, updatedAt = updatedAt, fetchedAt = fetchedAt, number = number, season = season, numberingName = numberingName, fillerOverride = fillerOverride, ) // ─── Category ─────────────────────────────────────────────────────────────── fun DbCategory.toRow(): CategoryRow = CategoryRow( id = id, name = name, forItemType = forItemType.name, position = position, hidden = hidden, shouldUpdate = shouldUpdate, updatedAt = updatedAt, ) fun CategoryRow.toDb(): DbCategory = DbCategory( id = id, name = name, forItemType = enumOrDefault(forItemType, DbItemType.Manga), position = position, hidden = hidden, shouldUpdate = shouldUpdate, updatedAt = updatedAt, ) // ─── Source ───────────────────────────────────────────────────────────────── fun DbSource.toRow(): SourceRow = SourceRow( id = id, name = name, baseUrl = baseUrl, lang = lang, isActive = isActive, isAdded = isAdded, isPinned = isPinned, isNsfw = isNsfw, sourceCode = sourceCode, sourceCodeUrl = sourceCodeUrl, typeSource = typeSource, iconUrl = iconUrl, isFullData = isFullData, hasCloudflare = hasCloudflare, lastUsed = lastUsed, dateFormat = dateFormat, dateFormatLocale = dateFormatLocale, apiUrl = apiUrl, version = version, versionLast = versionLast, headers = headers, supportLatest = supportLatest, filterList = filterList, preferenceList = preferenceList, itemType = itemType.name, appMinVerReq = appMinVerReq, additionalParams = additionalParams, isLocal = isLocal, isObsolete = isObsolete, sourceCodeLanguage = sourceCodeLanguage.name, notes = notes, repoJson = repo?.let { RowJson.encodeToString(DbRepo.serializer(), it) }, updatedAt = updatedAt, ) fun SourceRow.toDb(): DbSource = DbSource( id = id, name = name, baseUrl = baseUrl, lang = lang, isActive = isActive, isAdded = isAdded, isPinned = isPinned, isNsfw = isNsfw, sourceCode = sourceCode, sourceCodeUrl = sourceCodeUrl, typeSource = typeSource, iconUrl = iconUrl, isFullData = isFullData, hasCloudflare = hasCloudflare, lastUsed = lastUsed, dateFormat = dateFormat, dateFormatLocale = dateFormatLocale, apiUrl = apiUrl, version = version, versionLast = versionLast, headers = headers, supportLatest = supportLatest, filterList = filterList, preferenceList = preferenceList, itemType = enumOrDefault(itemType, DbItemType.Manga), appMinVerReq = appMinVerReq, additionalParams = additionalParams, isLocal = isLocal, isObsolete = isObsolete, sourceCodeLanguage = enumOrDefault(sourceCodeLanguage, DbSourceCodeLanguage.JavaScript), notes = notes, repo = repoJson?.let { runCatching { RowJson.decodeFromString(DbRepo.serializer(), it) }.getOrNull() }, updatedAt = updatedAt, ) // ─── History ──────────────────────────────────────────────────────────────── fun DbHistory.toRow(): HistoryRow = HistoryRow( id = id, mangaId = mangaId, chapterId = chapterId, itemType = itemType.name, date = date, updatedAt = updatedAt, readingTimeSeconds = readingTimeSeconds, ) fun HistoryRow.toDb(): DbHistory = DbHistory( id = id, mangaId = mangaId, chapterId = chapterId, itemType = enumOrDefault(itemType, DbItemType.Manga), date = date, updatedAt = updatedAt, readingTimeSeconds = readingTimeSeconds, ) // ─── Update / Download / CustomButton / Tracks ───────────────────────────── fun DbUpdate.toRow() = UpdateRow(id, mangaId, chapterId, chapterName, date, updatedAt) fun UpdateRow.toDb() = DbUpdate(id, mangaId, chapterId, chapterName, date, updatedAt) fun DbDownload.toRow() = DownloadRow(id, chapterId, succeeded, failed, total, isDownload, isStartDownload, isPaused, storageLocation, requestJson) fun DownloadRow.toDb() = DbDownload(id, chapterId, succeeded, failed, total, isDownload, isStartDownload, isPaused, storageLocation, requestJson) fun DbCustomButton.toRow() = CustomButtonRow( id, title, codePress, codeLongPress, codeStartup, isFavourite, position, updatedAt, ) fun CustomButtonRow.toDb() = DbCustomButton( id, title, codePress, codeLongPress, codeStartup, isFavourite, position, updatedAt, ) fun DbTrack.toRow(): TrackRow = TrackRow( id = id, libraryId = libraryId, mediaId = mediaId, mangaId = mangaId, syncId = syncId, title = title, lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score, status = status.name, startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate, trackingUrl = trackingUrl, itemType = itemType.name, updatedAt = updatedAt, ) fun TrackRow.toDb(): DbTrack = DbTrack( id = id, libraryId = libraryId, mediaId = mediaId, mangaId = mangaId, syncId = syncId, title = title, lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score, status = enumOrDefault(status, DbTrackStatus.Reading), startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate, trackingUrl = trackingUrl, itemType = enumOrDefault(itemType, DbItemType.Manga), updatedAt = updatedAt, ) fun DbTrackPreference.toRow() = TrackPreferenceRow( syncId = syncId ?: 0L, username = username, oauth = oauth, prefs = prefs, refreshing = refreshing, ) fun TrackPreferenceRow.toDb() = DbTrackPreference( syncId = if (syncId == 0L) null else syncId, username = username, oauth = oauth, prefs = prefs, refreshing = refreshing, ) fun DbTrackSearch.toRow() = TrackSearchRow( id = id, libraryId = libraryId, mediaId = mediaId, syncId = syncId, title = title, lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score, status = status, startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate, trackingUrl = trackingUrl, coverUrl = coverUrl, summary = summary, publishingStatus = publishingStatus, publishingType = publishingType, startDate = startDate, ) fun TrackSearchRow.toDb() = DbTrackSearch( id = id, libraryId = libraryId, mediaId = mediaId, syncId = syncId, title = title, lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score, status = status, startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate, trackingUrl = trackingUrl, coverUrl = coverUrl, summary = summary, publishingStatus = publishingStatus, publishingType = publishingType, startDate = startDate, ) fun DbSyncPreference.toRow() = SyncPreferenceRow( syncId = syncId ?: 0L, email = email, authToken = authToken, lastSyncManga = lastSyncManga, lastSyncHistory = lastSyncHistory, lastSyncUpdate = lastSyncUpdate, server = server, syncOn = syncOn, autoSyncFrequency = autoSyncFrequency, syncHistories = syncHistories, syncUpdates = syncUpdates, syncSettings = syncSettings, hubHead = hubHead, hubEpoch = hubEpoch, hubRecoveryPending = hubRecoveryPending, hubBootstrapComplete = hubBootstrapComplete, hubHlc = hubHlc, deviceId = deviceId, serverProvider = serverProvider.name, mangayomiIdMappings = mangayomiIdMappings, ) fun SyncPreferenceRow.toDb() = DbSyncPreference( syncId = if (syncId == 0L) null else syncId, email = email, authToken = authToken, lastSyncManga = lastSyncManga, lastSyncHistory = lastSyncHistory, lastSyncUpdate = lastSyncUpdate, server = server, syncOn = syncOn, autoSyncFrequency = autoSyncFrequency, syncHistories = syncHistories, syncUpdates = syncUpdates, syncSettings = syncSettings, hubHead = hubHead, hubEpoch = hubEpoch, hubRecoveryPending = hubRecoveryPending, hubBootstrapComplete = hubBootstrapComplete, hubHlc = hubHlc, deviceId = deviceId, serverProvider = enumOrDefault(serverProvider, SyncServerProvider.YokanHub), mangayomiIdMappings = mangayomiIdMappings, ) fun DbOutboxOp.toRow() = OutboxRow(kind = kind, id = id, path = path, value = value, hlc = hlc, seq = seq, epoch = epoch) fun OutboxRow.toDb() = DbOutboxOp(kind = kind, id = id, path = path, value = value, hlc = hlc, seq = seq, epoch = epoch) fun DbChangedPart.toRow() = ChangedPartRow( id = id, actionType = actionType.name, isarId = isarId, data = data, clientDate = clientDate, ) fun ChangedPartRow.toDb() = DbChangedPart( id = id, actionType = enumOrDefault(actionType, DbActionType.RemoveItem), isarId = isarId, data = data, clientDate = clientDate, ) // ─── Page cache ───────────────────────────────────────────────────────────── fun DbChapterPageUrls.toRow(): PageCacheRow = PageCacheRow( chapterId = chapterId ?: 0L, chapterUrl = chapterUrl, urls = urls?.let { RowJson.encodeToString(it) }, headers = headers?.let { RowJson.encodeToString(it) }, fetchedAt = fetchedAt, sourceId = sourceId, sourceVersion = sourceVersion, ) fun PageCacheRow.toDb(): DbChapterPageUrls = DbChapterPageUrls( chapterId = if (chapterId == 0L) null else chapterId, chapterUrl = chapterUrl, urls = urls?.let { runCatching { RowJson.decodeFromString>(it) }.getOrNull() }, headers = headers?.let { runCatching { RowJson.decodeFromString>(it) }.getOrNull() }, fetchedAt = fetchedAt, sourceId = sourceId, sourceVersion = sourceVersion, ) // ─── Settings ─────────────────────────────────────────────────────────────── // Single-row JSON encoded. DbSettings has dozens of nested types; storing the // whole thing as a TEXT blob avoids exploding the schema and keeps backup / // sync paths reading the same kotlinx.serialization form. fun DbSettings.toRow(): SettingsRow = SettingsRow( id = 1L, json = RowJson.encodeToString(DbSettings.serializer(), this), ) fun SettingsRow.toDb(): DbSettings? = runCatching { RowJson.decodeFromString(DbSettings.serializer(), json) }.getOrNull()