Yokan / rebuild
Course 1 8624561

RemoteTitleIngest.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/RemoteTitleIngest.kt

implementation134 lines
1package eu.friedcutlet.yokan.data23import eu.friedcutlet.yokan.database.DbChapter4import eu.friedcutlet.yokan.database.DbFetchType5import eu.friedcutlet.yokan.database.DbManga6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.domain.Manga8import eu.friedcutlet.yokan.domain.Source9import eu.friedcutlet.yokan.domain.chapterReleaseKey10import eu.friedcutlet.yokan.services.extensions.RemoteChapter11import eu.friedcutlet.yokan.services.extensions.RemoteDetail12import eu.friedcutlet.yokan.services.extensions.RemoteManga13import eu.friedcutlet.yokan.services.extensions.normalizeSourceCast14import eu.friedcutlet.yokan.util.nowMillis1516// Writes extension (browse/detail) results into the library, keeping local-only fields.1718internal fun YokanDatabase.ingestRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean?): Manga {19    val existing = findExistingRemote(source, remote.url)20    val now = nowMillis()21    val saved = upsertManga(22        (existing ?: DbManga()).copy(23            name = remote.title,24            link = remote.url,25            imageUrl = remote.thumbnailUrl ?: existing?.imageUrl,26            description = remote.description ?: existing?.description.orEmpty(),27            itemType = source.itemType.toDb(),28            genre = existing?.genre.orEmpty(),29            favorite = favorite ?: existing?.favorite ?: false,30            source = source.name,31            lang = source.lang,32            dateAdded = existing?.dateAdded ?: now,33            lastUpdate = now,34            categories = existing?.categories.orEmpty(),35            isLocalArchive = source.baseUrl.startsWith("file://") || existing?.isLocalArchive == true,36            customCoverImage = existing?.customCoverImage,37            customCoverFromTracker = existing?.customCoverFromTracker,38            smartUpdateDays = existing?.smartUpdateDays,39            sourceId = source.id,40            updatedAt = now,41        ),42    )43    return saved.toDomain(settings())44}4546internal fun YokanDatabase.ingestRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean?): Manga = batch {47    val existing = findExistingRemote(source, detail.url)48    val now = nowMillis()49    val saved = upsertManga(50        (existing ?: DbManga()).copy(51            name = detail.title,52            link = detail.url,53            imageUrl = detail.thumbnailUrl ?: existing?.imageUrl,54            description = detail.description.ifBlank { existing?.description.orEmpty() },55            author = detail.author ?: existing?.author,56            artist = detail.artist ?: existing?.artist,57            cast = detail.cast?.let { normalizeSourceCast(it, source.baseUrl) }58                ?: existing?.cast.orEmpty(),59            itemType = source.itemType.toDb(),60            genre = existing?.genre.orEmpty(),61            favorite = favorite ?: existing?.favorite ?: false,62            source = source.name,63            lang = source.lang,64            dateAdded = existing?.dateAdded ?: now,65            lastUpdate = now,66            categories = existing?.categories.orEmpty(),67            isLocalArchive = source.baseUrl.startsWith("file://") || existing?.isLocalArchive == true,68            customCoverImage = existing?.customCoverImage,69            customCoverFromTracker = existing?.customCoverFromTracker,70            smartUpdateDays = existing?.smartUpdateDays,71            sourceId = source.id,72            fetchType = if (detail.seasons != null) DbFetchType.Seasons else DbFetchType.Episodes,73            updatedAt = now,74        ),75    )76    if (detail.seasons != null) upsertSeasonRecords(saved, detail.seasons, now)77    else upsertRemoteChapters(saved.id, detail.chapters)78    saved.toDomain(settings())79}8081private fun YokanDatabase.findExistingRemote(source: Source, url: String): DbManga? {82    val candidates = mangas(source.itemType.toDb()).filter { it.link == url }83    return candidates.firstOrNull { it.sourceId == source.id }84        ?: candidates.firstOrNull { it.sourceId == null && it.source == source.name }85}8687private fun YokanDatabase.upsertRemoteChapters(mangaId: Long, remote: List<RemoteChapter>) {88    if (remote.isEmpty()) return89    val mangaTitle = manga(mangaId)?.name.orEmpty()90    val existingChapters = chapters(mangaId)91    val existingByUrl = existingChapters.associateBy { it.url }92    val existingByComposite = existingChapters.mapNotNull { c ->93        chapterReleaseKey(mangaTitle, c.name, c.scanlator, c.number, c.season, c.numberingName)?.let { it to c }94    }.toMap()95    val readByEpisode = existingChapters.filter { it.isRead }.mapNotNull { c ->96        chapterReleaseKey(mangaTitle, c.name, number = c.number, season = c.season, numberingName = c.numberingName)97    }.toSet()9899    val seenUrls = mutableSetOf<String>()100    val seenCompositeKeys = mutableSetOf<String>()101102    remote.forEach { chapter ->103        val compositeKey = chapterReleaseKey(mangaTitle, chapter.title, chapter.scanlator)104        val episodeKey = chapterReleaseKey(mangaTitle, chapter.title)105106        if (!seenUrls.add(chapter.url)) return@forEach107        if (compositeKey != null && !seenCompositeKeys.add(compositeKey)) return@forEach108109        val existing = existingByUrl[chapter.url] ?: compositeKey?.let { existingByComposite[it] }110        val carryRead = existing?.isRead ?: (episodeKey != null && episodeKey in readByEpisode)111112        val next = (existing ?: DbChapter()).copy(113            mangaId = mangaId,114            name = chapter.title,115            url = chapter.url,116            dateUpload = chapter.dateUpload,117            scanlator = chapter.scanlator,118            isBookmarked = existing?.isBookmarked ?: false,119            isRead = carryRead,120            lastPageRead = existing?.lastPageRead ?: if (carryRead) "1" else "",121            archivePath = existing?.archivePath.orEmpty(),122            isFiller = existing?.isFiller ?: false,123            thumbnailUrl = existing?.thumbnailUrl,124            description = existing?.description,125            downloadSize = existing?.downloadSize,126            duration = existing?.duration,127            fetchedAt = existing?.fetchedAt ?: nowMillis(),128            updatedAt = existing?.updatedAt ?: 0,129        )130        // An unchanged chapter is not rewritten: `updatedAt` is a synced path, so bumping it131        // alone would cost a write and a hub op per chapter on every refresh.132        if (next != existing) upsertChapter(next.copy(updatedAt = nowMillis()))133    }134}135

Search chapters, reference and source filenames.