Yokan / rebuild
Course 1 8624561

RowAdapters.kt

composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/database/room/RowAdapters.kt

implementation308 lines
1package eu.friedcutlet.yokan.database.room23import eu.friedcutlet.yokan.database.DbActionType4import eu.friedcutlet.yokan.database.DbCategory5import eu.friedcutlet.yokan.database.DbChangedPart6import eu.friedcutlet.yokan.database.DbChapter7import eu.friedcutlet.yokan.database.DbChapterPageUrls8import eu.friedcutlet.yokan.database.DbFetchType9import eu.friedcutlet.yokan.database.DbCustomButton10import eu.friedcutlet.yokan.database.DbDownload11import eu.friedcutlet.yokan.database.DbHistory12import eu.friedcutlet.yokan.database.DbItemType13import eu.friedcutlet.yokan.database.DbManga14import eu.friedcutlet.yokan.database.DbOutboxOp15import eu.friedcutlet.yokan.database.DbRepo16import eu.friedcutlet.yokan.database.DbSettings17import eu.friedcutlet.yokan.database.DbSource18import eu.friedcutlet.yokan.database.DbSourceCodeLanguage19import eu.friedcutlet.yokan.database.DbStatus20import eu.friedcutlet.yokan.database.DbSyncPreference21import eu.friedcutlet.yokan.database.SyncServerProvider22import eu.friedcutlet.yokan.database.DbTrack23import eu.friedcutlet.yokan.database.DbTrackPreference24import eu.friedcutlet.yokan.database.DbTrackSearch25import eu.friedcutlet.yokan.database.DbTrackStatus26import eu.friedcutlet.yokan.database.DbUpdate27import kotlinx.serialization.json.Json2829internal val RowJson = Json {30    ignoreUnknownKeys = true31    encodeDefaults = true32}3334private inline fun <reified E : Enum<E>> enumOrDefault(name: String?, default: E): E =35    name?.let { runCatching { enumValueOf<E>(it) }.getOrNull() } ?: default3637// ─── Manga ──────────────────────────────────────────────────────────────────3839internal fun DbManga.toCreditRows(): List<MangaCreditRow> = cast.mapIndexed { index, credit ->40    MangaCreditRow(id, index, credit.name, credit.role, credit.character, credit.imageUrl)41}4243internal fun MangaCreditRow.toCredit() = eu.friedcutlet.yokan.domain.TitleCredit(name, role, character, imageUrl)4445fun DbManga.toRow(): MangaRow = MangaRow(46    id = id,47    name = name,48    link = link,49    imageUrl = imageUrl,50    description = description,51    author = author,52    artist = artist,53    status = status.name,54    itemType = itemType.name,55    genre = genre?.let { RowJson.encodeToString(it) },56    favorite = favorite,57    source = source,58    lang = lang,59    dateAdded = dateAdded,60    lastUpdate = lastUpdate,61    lastRead = lastRead,62    categories = categories?.let { RowJson.encodeToString(it) },63    isLocalArchive = isLocalArchive,64    customCoverImage = customCoverImage,65    customCoverFromTracker = customCoverFromTracker,66    smartUpdateDays = smartUpdateDays,67    updatedAt = updatedAt,68    sourceId = sourceId,69    privateNote = privateNote,70    nextEpisodeAiringAt = nextEpisodeAiringAt,71    nextEpisodeNumber = nextEpisodeNumber,72    airingScheduleUpdatedAt = airingScheduleUpdatedAt,73    parentId = parentId,74    fetchType = fetchType.name,75    seasonNumber = seasonNumber,76)7778fun MangaRow.toDb(): DbManga = DbManga(79    id = id,80    name = name,81    link = link,82    imageUrl = imageUrl,83    description = description,84    author = author,85    artist = artist,86    status = enumOrDefault(status, DbStatus.Unknown),87    itemType = enumOrDefault(itemType, DbItemType.Manga),88    genre = genre?.let { runCatching { RowJson.decodeFromString<List<String>>(it) }.getOrNull() },89    favorite = favorite,90    source = source,91    lang = lang,92    dateAdded = dateAdded,93    lastUpdate = lastUpdate,94    lastRead = lastRead,95    categories = categories?.let { runCatching { RowJson.decodeFromString<List<Long>>(it) }.getOrNull() },96    isLocalArchive = isLocalArchive,97    customCoverImage = customCoverImage,98    customCoverFromTracker = customCoverFromTracker,99    smartUpdateDays = smartUpdateDays,100    updatedAt = updatedAt,101    sourceId = sourceId,102    privateNote = privateNote,103    nextEpisodeAiringAt = nextEpisodeAiringAt,104    nextEpisodeNumber = nextEpisodeNumber,105    airingScheduleUpdatedAt = airingScheduleUpdatedAt,106    parentId = parentId,107    fetchType = enumOrDefault(fetchType, DbFetchType.Episodes),108    seasonNumber = seasonNumber,109)110111// ─── Chapter ────────────────────────────────────────────────────────────────112113fun DbChapter.toRow(): ChapterRow = ChapterRow(114    id = id, mangaId = mangaId, name = name, url = url, dateUpload = dateUpload,115    scanlator = scanlator, isBookmarked = isBookmarked, isRead = isRead,116    lastPageRead = lastPageRead, archivePath = archivePath, isFiller = isFiller,117    thumbnailUrl = thumbnailUrl, description = description, downloadSize = downloadSize,118    duration = duration, updatedAt = updatedAt, fetchedAt = fetchedAt,119    number = number, season = season, numberingName = numberingName, fillerOverride = fillerOverride,120)121122fun ChapterRow.toDb(): DbChapter = DbChapter(123    id = id, mangaId = mangaId, name = name, url = url, dateUpload = dateUpload,124    scanlator = scanlator, isBookmarked = isBookmarked, isRead = isRead,125    lastPageRead = lastPageRead, archivePath = archivePath, isFiller = isFiller,126    thumbnailUrl = thumbnailUrl, description = description, downloadSize = downloadSize,127    duration = duration, updatedAt = updatedAt, fetchedAt = fetchedAt,128    number = number, season = season, numberingName = numberingName, fillerOverride = fillerOverride,129)130131// ─── Category ───────────────────────────────────────────────────────────────132133fun DbCategory.toRow(): CategoryRow = CategoryRow(134    id = id, name = name, forItemType = forItemType.name, position = position,135    hidden = hidden, shouldUpdate = shouldUpdate, updatedAt = updatedAt,136)137138fun CategoryRow.toDb(): DbCategory = DbCategory(139    id = id, name = name, forItemType = enumOrDefault(forItemType, DbItemType.Manga),140    position = position, hidden = hidden, shouldUpdate = shouldUpdate, updatedAt = updatedAt,141)142143// ─── Source ─────────────────────────────────────────────────────────────────144145fun DbSource.toRow(): SourceRow = SourceRow(146    id = id, name = name, baseUrl = baseUrl, lang = lang, isActive = isActive,147    isAdded = isAdded, isPinned = isPinned, isNsfw = isNsfw, sourceCode = sourceCode,148    sourceCodeUrl = sourceCodeUrl, typeSource = typeSource, iconUrl = iconUrl,149    isFullData = isFullData, hasCloudflare = hasCloudflare, lastUsed = lastUsed,150    dateFormat = dateFormat, dateFormatLocale = dateFormatLocale, apiUrl = apiUrl,151    version = version, versionLast = versionLast, headers = headers,152    supportLatest = supportLatest, filterList = filterList, preferenceList = preferenceList,153    itemType = itemType.name, appMinVerReq = appMinVerReq, additionalParams = additionalParams,154    isLocal = isLocal, isObsolete = isObsolete, sourceCodeLanguage = sourceCodeLanguage.name,155    notes = notes, repoJson = repo?.let { RowJson.encodeToString(DbRepo.serializer(), it) },156    updatedAt = updatedAt,157)158159fun SourceRow.toDb(): DbSource = DbSource(160    id = id, name = name, baseUrl = baseUrl, lang = lang, isActive = isActive,161    isAdded = isAdded, isPinned = isPinned, isNsfw = isNsfw, sourceCode = sourceCode,162    sourceCodeUrl = sourceCodeUrl, typeSource = typeSource, iconUrl = iconUrl,163    isFullData = isFullData, hasCloudflare = hasCloudflare, lastUsed = lastUsed,164    dateFormat = dateFormat, dateFormatLocale = dateFormatLocale, apiUrl = apiUrl,165    version = version, versionLast = versionLast, headers = headers,166    supportLatest = supportLatest, filterList = filterList, preferenceList = preferenceList,167    itemType = enumOrDefault(itemType, DbItemType.Manga), appMinVerReq = appMinVerReq,168    additionalParams = additionalParams, isLocal = isLocal, isObsolete = isObsolete,169    sourceCodeLanguage = enumOrDefault(sourceCodeLanguage, DbSourceCodeLanguage.JavaScript),170    notes = notes,171    repo = repoJson?.let { runCatching { RowJson.decodeFromString(DbRepo.serializer(), it) }.getOrNull() },172    updatedAt = updatedAt,173)174175// ─── History ────────────────────────────────────────────────────────────────176177fun DbHistory.toRow(): HistoryRow = HistoryRow(178    id = id, mangaId = mangaId, chapterId = chapterId, itemType = itemType.name,179    date = date, updatedAt = updatedAt, readingTimeSeconds = readingTimeSeconds,180)181182fun HistoryRow.toDb(): DbHistory = DbHistory(183    id = id, mangaId = mangaId, chapterId = chapterId,184    itemType = enumOrDefault(itemType, DbItemType.Manga),185    date = date, updatedAt = updatedAt, readingTimeSeconds = readingTimeSeconds,186)187188// ─── Update / Download / CustomButton / Tracks ─────────────────────────────189190fun DbUpdate.toRow() = UpdateRow(id, mangaId, chapterId, chapterName, date, updatedAt)191fun UpdateRow.toDb() = DbUpdate(id, mangaId, chapterId, chapterName, date, updatedAt)192193fun DbDownload.toRow() = DownloadRow(id, chapterId, succeeded, failed, total, isDownload, isStartDownload, isPaused, storageLocation, requestJson)194fun DownloadRow.toDb() = DbDownload(id, chapterId, succeeded, failed, total, isDownload, isStartDownload, isPaused, storageLocation, requestJson)195196fun DbCustomButton.toRow() = CustomButtonRow(197    id, title, codePress, codeLongPress, codeStartup, isFavourite, position, updatedAt,198)199fun CustomButtonRow.toDb() = DbCustomButton(200    id, title, codePress, codeLongPress, codeStartup, isFavourite, position, updatedAt,201)202203fun DbTrack.toRow(): TrackRow = TrackRow(204    id = id, libraryId = libraryId, mediaId = mediaId, mangaId = mangaId, syncId = syncId,205    title = title, lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score,206    status = status.name, startedReadingDate = startedReadingDate,207    finishedReadingDate = finishedReadingDate, trackingUrl = trackingUrl,208    itemType = itemType.name, updatedAt = updatedAt,209)210211fun TrackRow.toDb(): DbTrack = DbTrack(212    id = id, libraryId = libraryId, mediaId = mediaId, mangaId = mangaId, syncId = syncId,213    title = title, lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score,214    status = enumOrDefault(status, DbTrackStatus.Reading),215    startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate,216    trackingUrl = trackingUrl, itemType = enumOrDefault(itemType, DbItemType.Manga),217    updatedAt = updatedAt,218)219220fun DbTrackPreference.toRow() = TrackPreferenceRow(221    syncId = syncId ?: 0L, username = username, oauth = oauth, prefs = prefs, refreshing = refreshing,222)223fun TrackPreferenceRow.toDb() = DbTrackPreference(224    syncId = if (syncId == 0L) null else syncId, username = username, oauth = oauth, prefs = prefs,225    refreshing = refreshing,226)227228fun DbTrackSearch.toRow() = TrackSearchRow(229    id = id, libraryId = libraryId, mediaId = mediaId, syncId = syncId, title = title,230    lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score, status = status,231    startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate,232    trackingUrl = trackingUrl, coverUrl = coverUrl, summary = summary,233    publishingStatus = publishingStatus, publishingType = publishingType, startDate = startDate,234)235fun TrackSearchRow.toDb() = DbTrackSearch(236    id = id, libraryId = libraryId, mediaId = mediaId, syncId = syncId, title = title,237    lastChapterRead = lastChapterRead, totalChapter = totalChapter, score = score, status = status,238    startedReadingDate = startedReadingDate, finishedReadingDate = finishedReadingDate,239    trackingUrl = trackingUrl, coverUrl = coverUrl, summary = summary,240    publishingStatus = publishingStatus, publishingType = publishingType, startDate = startDate,241)242243fun DbSyncPreference.toRow() = SyncPreferenceRow(244    syncId = syncId ?: 0L, email = email, authToken = authToken,245    lastSyncManga = lastSyncManga, lastSyncHistory = lastSyncHistory, lastSyncUpdate = lastSyncUpdate,246    server = server, syncOn = syncOn, autoSyncFrequency = autoSyncFrequency,247    syncHistories = syncHistories, syncUpdates = syncUpdates, syncSettings = syncSettings,248    hubHead = hubHead, hubEpoch = hubEpoch, hubRecoveryPending = hubRecoveryPending,249    hubBootstrapComplete = hubBootstrapComplete, hubHlc = hubHlc, deviceId = deviceId,250    serverProvider = serverProvider.name,251    mangayomiIdMappings = mangayomiIdMappings,252)253fun SyncPreferenceRow.toDb() = DbSyncPreference(254    syncId = if (syncId == 0L) null else syncId, email = email, authToken = authToken,255    lastSyncManga = lastSyncManga, lastSyncHistory = lastSyncHistory, lastSyncUpdate = lastSyncUpdate,256    server = server, syncOn = syncOn, autoSyncFrequency = autoSyncFrequency,257    syncHistories = syncHistories, syncUpdates = syncUpdates, syncSettings = syncSettings,258    hubHead = hubHead, hubEpoch = hubEpoch, hubRecoveryPending = hubRecoveryPending,259    hubBootstrapComplete = hubBootstrapComplete, hubHlc = hubHlc, deviceId = deviceId,260    serverProvider = enumOrDefault(serverProvider, SyncServerProvider.YokanHub),261    mangayomiIdMappings = mangayomiIdMappings,262)263264fun DbOutboxOp.toRow() = OutboxRow(kind = kind, id = id, path = path, value = value, hlc = hlc, seq = seq, epoch = epoch)265fun OutboxRow.toDb() = DbOutboxOp(kind = kind, id = id, path = path, value = value, hlc = hlc, seq = seq, epoch = epoch)266267fun DbChangedPart.toRow() = ChangedPartRow(268    id = id, actionType = actionType.name, isarId = isarId, data = data, clientDate = clientDate,269)270fun ChangedPartRow.toDb() = DbChangedPart(271    id = id, actionType = enumOrDefault(actionType, DbActionType.RemoveItem),272    isarId = isarId, data = data, clientDate = clientDate,273)274275// ─── Page cache ─────────────────────────────────────────────────────────────276277fun DbChapterPageUrls.toRow(): PageCacheRow = PageCacheRow(278    chapterId = chapterId ?: 0L,279    chapterUrl = chapterUrl,280    urls = urls?.let { RowJson.encodeToString(it) },281    headers = headers?.let { RowJson.encodeToString(it) },282    fetchedAt = fetchedAt,283    sourceId = sourceId,284    sourceVersion = sourceVersion,285)286287fun PageCacheRow.toDb(): DbChapterPageUrls = DbChapterPageUrls(288    chapterId = if (chapterId == 0L) null else chapterId,289    chapterUrl = chapterUrl,290    urls = urls?.let { runCatching { RowJson.decodeFromString<List<String>>(it) }.getOrNull() },291    headers = headers?.let { runCatching { RowJson.decodeFromString<List<String>>(it) }.getOrNull() },292    fetchedAt = fetchedAt,293    sourceId = sourceId,294    sourceVersion = sourceVersion,295)296297// ─── Settings ───────────────────────────────────────────────────────────────298// Single-row JSON encoded. DbSettings has dozens of nested types; storing the299// whole thing as a TEXT blob avoids exploding the schema and keeps backup /300// sync paths reading the same kotlinx.serialization form.301302fun DbSettings.toRow(): SettingsRow = SettingsRow(303    id = 1L,304    json = RowJson.encodeToString(DbSettings.serializer(), this),305)306307fun SettingsRow.toDb(): DbSettings? =308    runCatching { RowJson.decodeFromString(DbSettings.serializer(), json) }.getOrNull()309

Search chapters, reference and source filenames.