Yokan / rebuild
Course 1 8624561

LocalLibraryService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryService.kt

implementation712 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.DbChapter4import eu.friedcutlet.yokan.database.DbItemType5import eu.friedcutlet.yokan.database.DbLocalFolder6import eu.friedcutlet.yokan.database.DbManga7import eu.friedcutlet.yokan.database.DbFetchType8import eu.friedcutlet.yokan.database.DbStatus9import eu.friedcutlet.yokan.database.YokanDatabase10import eu.friedcutlet.yokan.database.getLocalVirtualPath11import eu.friedcutlet.yokan.database.localVirtualPathFromStoredPath12import eu.friedcutlet.yokan.services.files.BoundedCache13import eu.friedcutlet.yokan.services.files.LocalFileEntry14import eu.friedcutlet.yokan.services.catchingNonCancellation15import eu.friedcutlet.yokan.services.files.downloadItemTypeFromFolder16import eu.friedcutlet.yokan.services.files.LocalArchiveService17import eu.friedcutlet.yokan.services.files.LocalEntry18import eu.friedcutlet.yokan.services.files.LocalDirectoryEntry19import eu.friedcutlet.yokan.domain.ChapterRecognition20import eu.friedcutlet.yokan.services.files.LocalFileService21import eu.friedcutlet.yokan.util.nowMillis22import kotlinx.coroutines.sync.Mutex23import kotlinx.coroutines.sync.withLock24import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders2526interface LocalLibraryService {27    suspend fun scan(): LocalLibraryScanResult28    /** Bypass fingerprint caches for a user-requested full rescan. */29    suspend fun scanFresh(): LocalLibraryScanResult = scan()30    suspend fun reconcile(): LocalLibraryReconciliationResult31    suspend fun reconcile(scan: LocalLibraryScanResult): LocalLibraryReconciliationResult = reconcile()32    /** Serializes a complete scan/reconcile with entry-management apply. */33    suspend fun <T> withOperationLock(block: suspend () -> T): T = block()34    /** Called by entry management while [withOperationLock] is held. */35    suspend fun reconcileForEntryManagement(): LocalLibraryReconciliationResult = reconcile()36    /**37     * Import a torrent file or magnet URL as a local-archive [DbManga] with a single chapter that38     * carries the file path or magnet URL; playback streams it through TorrServer39     * (`services/torrent/TorrentStreams`). Returns the upserted manga id, or null on failure.40     */41    suspend fun importTorrent(pathOrMagnet: String, displayName: String? = null): Long?42}4344class DefaultLocalLibraryService(45    private val database: YokanDatabase,46    private val files: LocalFileService,47    private val archives: LocalArchiveService,48) : LocalLibraryService {49    private val operationMutex = Mutex()50    private val animeChapterExtensions = setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8", "zip", "rar", "cbr", "cbz", "cbt", "tar")51    private var metadataCache = BoundedCache<LocalFileEntry, LocalMetadata>(512, 8 * 1024 * 1024) { it.weight }52    private var episodeCache = BoundedCache<LocalFileEntry, LocalEpisodeMetadataIndex>(128, 8 * 1024 * 1024) { it.weight }53    private var coverCache = BoundedCache<LocalFileEntry, ByteArray>(128, 32 * 1024 * 1024) { it.size }5455    override suspend fun scanFresh(): LocalLibraryScanResult = withOperationLock {56        archives.invalidateIndexCache()57        metadataCache = BoundedCache(512, 8 * 1024 * 1024) { it.weight }58        episodeCache = BoundedCache(128, 8 * 1024 * 1024) { it.weight }59        coverCache = BoundedCache(128, 32 * 1024 * 1024) { it.size }60        scanUnlocked()61    }6263    /** Listings live for one scan only: additions and removals are always discovered. */64    private inner class ScanInventory {65        private val entries = mutableMapOf<String, List<LocalEntry>?>()66        private val children = mutableMapOf<String, List<LocalFileEntry>>()67        private val directoryEntries = mutableMapOf<String, List<LocalDirectoryEntry>?>()68        val episodes = BoundedCache<String, LocalEpisodeMetadataIndex>(128, 8 * 1024 * 1024) { it.weight }69        fun entries(path: String): List<LocalEntry>? = entries.getOrPut(path) { files.listLocalEntries(path) }70        fun children(path: String): List<LocalFileEntry> = children.getOrPut(path) { files.listFiles(path) }71        fun directoryEntries(path: String): List<LocalDirectoryEntry>? = directoryEntries.getOrPut(path) { files.listDirectoryEntries(path) }72        fun fingerprint(path: String): LocalFileEntry? = children(path.substringBeforeLast('/', ""))73            .firstOrNull { it.path == path && it.lastModified > 0L }74    }7576    override suspend fun <T> withOperationLock(block: suspend () -> T): T = operationMutex.withLock { block() }7778    /**79     * Bundled default folder rooted at `<downloadRoot>/local`. Always scanned in80     * addition to any user-configured virtual folders so a freshly installed app81     * has a working drop-in location.82     */83    override suspend fun scan(): LocalLibraryScanResult {84        return withOperationLock { scanUnlocked() }85    }8687    /** Totals and identity evidence collected over one scan. */88    private class ScanAccumulator {89        var added = 090        var updated = 091        var total = 092        val addedTitleIds = mutableListOf<Long>()93        val observedTitleIds = mutableListOf<Long>()94        val addedChapterIds = mutableListOf<Long>()95        val observedChapterIds = mutableListOf<Long>()96        val healthyFolders = mutableListOf<DbLocalFolder>()97        val unavailableFolders = mutableListOf<DbLocalFolder>()98        val observedTitleIdentities = mutableListOf<LocalLibraryIdentity>()99        val observedChapterIdentities = mutableListOf<LocalLibraryIdentity>()100101        fun toResult() = LocalLibraryScanResult(102            added = added,103            updated = updated,104            total = total,105            addedTitleIds = addedTitleIds.distinct(),106            observedTitleIds = observedTitleIds.distinct(),107            addedChapterIds = addedChapterIds.distinct(),108            observedChapterIds = observedChapterIds.distinct(),109            healthyFolders = healthyFolders,110            unavailableFolders = unavailableFolders,111            observedTitleIdentities = observedTitleIdentities.distinct(),112            observedChapterIdentities = observedChapterIdentities.distinct(),113        )114    }115116    private suspend fun scanUnlocked(): LocalLibraryScanResult {117        files.prepare()118        val inventory = ScanInventory()119        val importArea = scanCanonicalPath("${files.downloadRoot.trimEnd('/')}/local-imports")120        val folders = effectiveLocalLibraryFolders(database.settings(), files)121        if (folders.isEmpty()) return LocalLibraryScanResult(0, 0, 0)122        val scan = ScanAccumulator()123        val existingMangas = database.mangas()124            .asSequence()125            .filter(DbManga::isLocalLibraryEntry)126            .associateByTo(mutableMapOf()) { manga ->127                manga.itemType to localVirtualPathFromStoredPath(manga.link, folders)128            }129        val existingChapters = database.chapters()130            .associateByTo(mutableMapOf()) { chapter ->131                chapter.mangaId to localVirtualPathFromStoredPath(chapter.archivePath, folders)132            }133        folders.forEach { folder ->134            val entries = listFolderEntries(folder, inventory) ?: run {135                scan.unavailableFolders += folder136                return@forEach137            }138            scan.healthyFolders += folder139            val defaultItemType = inferItemType(folder.path)140            val canonicalFolder = scanCanonicalPath(folder.path)141            val scansImportAncestor = importArea != null && canonicalFolder != null &&142                (canonicalFolder == importArea || importArea.startsWith("$canonicalFolder/"))143            fun skipped(entry: LocalEntry) = entry.isInColorizerStagingFolder(folder.path) || (scansImportAncestor &&144                scanCanonicalPath(entry.path).let { path -> path == null || path == importArea || path.startsWith("$importArea/") })145            val listedEntries = entries.filterNot(::skipped)146                .map { it.toScanEntry(folder, defaultItemType) }147                .distinctBy { it.path }148            val seasonTree = if (defaultItemType == DbItemType.Anime) animeSeasonTree(folder, inventory) else null149            val scanEntries = seasonTree?.let { tree ->150                seasonOrderedEntries(folder, tree, listedEntries) { node -> skipped(LocalEntry(node.path, node.name, false)) }151            } ?: listedEntries152            val inheritedLibrary = seasonTree?.let { inheritedLibraryState(it, existingMangas) }.orEmpty()153            val savedTitleIds = mutableMapOf<String, Long>()154            scanEntries.forEach { entry ->155                scan.total += 1156                val virtualMangaPath = getLocalVirtualPath(folder, entry.path)157                val seasonNode = seasonTree?.get(virtualMangaPath)158                val listsSeasons = seasonNode?.seasons == true159                val parentId = seasonNode?.parent?.let(savedTitleIds::get)160                val ancestorIds = generateSequence(seasonNode?.parent) { seasonTree?.get(it)?.parent }.mapNotNull(savedTitleIds::get).toSet()161                val metadata = readMetadata(entry.path, inventory, entry.itemType)162                val coverImage = readCoverImage(entry.path, inventory, metadata.cast.orEmpty().mapNotNull { it.imageUrl }.toSet())163                val observedExisting = existingMangas[entry.itemType to virtualMangaPath]164                val now = nowMillis()165                val chapters = if (listsSeasons) emptyList() else chaptersFor(entry, folder, inventory)166                val movedChapterIds = mutableSetOf<Long>()167                database.batch {168                    val savedManga = upsertScannedTitle(169                        entry = entry,170                        virtualPath = virtualMangaPath,171                        observedExisting = observedExisting,172                        folders = folders,173                        metadata = metadata,174                        coverImage = coverImage,175                        seasonTree = seasonTree,176                        seasonNode = seasonNode,177                        parentId = parentId,178                        inherited = inheritedLibrary[virtualMangaPath],179                        now = now,180                        scan = scan,181                    ) ?: return@batch182                    existingMangas[entry.itemType to virtualMangaPath] = savedManga183                    savedTitleIds[virtualMangaPath] = savedManga.id184                    chapters.forEach { chapter ->185                        upsertScannedChapter(chapter, entry.itemType, savedManga, ancestorIds, existingChapters, movedChapterIds, folders, now, scan)186                    }187                    if (movedChapterIds.isNotEmpty()) {188                        database.histories().filter { it.chapterId in movedChapterIds }189                            .forEach { database.upsertHistory(it.copy(mangaId = savedManga.id)) }190                        database.updates().filter { it.chapterId in movedChapterIds }191                            .forEach { database.upsertUpdate(it.copy(mangaId = savedManga.id)) }192                    }193                }194            }195        }196        return scan.toResult()197    }198199    /** Root entries of a configured folder, or null when it is missing or cannot be listed. */200    private fun listFolderEntries(folder: DbLocalFolder, inventory: ScanInventory): List<LocalEntry>? {201        if (folder.path.isBlank() || !runCatching { files.exists(folder.path) }.getOrDefault(false)) return null202        return runCatching { inventory.entries(folder.path) }.getOrNull()203    }204205    /**206     * Upserts one scanned title inside the scan batch and records it in [scan]. Null when the row207     * was deleted, retyped or relinked since the scan read it.208     */209    private fun upsertScannedTitle(210        entry: LocalScanEntry,211        virtualPath: String,212        observedExisting: DbManga?,213        folders: List<DbLocalFolder>,214        metadata: LocalMetadata,215        coverImage: ByteArray?,216        seasonTree: Map<String, SeasonNode>?,217        seasonNode: SeasonNode?,218        parentId: Long?,219        inherited: Set<Long>?,220        now: Long,221        scan: ScanAccumulator,222    ): DbManga? {223        // Browser disk reads suspend; reading progress, categories and deletion may change meanwhile.224        val existing = observedExisting?.let { database.manga(it.id) }225        if (observedExisting != null && existing == null) return null226        if (existing != null && (!existing.isLocalLibraryEntry() || existing.itemType != entry.itemType ||227                localVirtualPathFromStoredPath(existing.link, folders) != virtualPath)) return null228        val nextManga = (existing ?: DbManga()).copy(229            name = metadata.name ?: entry.name,230            link = virtualPath,231            imageUrl = metadata.imageUrl ?: existing?.imageUrl,232            description = metadata.description ?: existing?.description,233            author = metadata.author ?: existing?.author,234            artist = metadata.artist ?: existing?.artist,235            status = metadata.status ?: existing?.status ?: DbStatus.Unknown,236            itemType = entry.itemType,237            genre = metadata.genres ?: existing?.genre,238            cast = metadata.cast ?: existing?.cast.orEmpty(),239            isLocalArchive = true,240            customCoverImage = if (observedExisting != null && !existing?.customCoverImage.contentEquals(observedExisting.customCoverImage))241                existing?.customCoverImage else coverImage ?: existing?.customCoverImage,242            customCoverFromTracker = metadata.customCoverFromTracker ?: existing?.customCoverFromTracker,243            source = "local",244            lang = metadata.language ?: existing?.lang ?: "en",245            dateAdded = existing?.dateAdded ?: now,246            lastUpdate = now,247            // Favorite season folders that used to be separate titles keep the show in the library.248            favorite = (existing?.favorite ?: false) || inherited != null,249            categories = inherited?.let { (existing?.categories.orEmpty() + it).distinct() } ?: existing?.categories,250            parentId = if (seasonTree == null) existing?.parentId else parentId,251            fetchType = when {252                seasonTree == null -> existing?.fetchType ?: DbFetchType.Episodes253                seasonNode?.seasons == true -> DbFetchType.Seasons254                else -> DbFetchType.Episodes255            },256            seasonNumber = if (seasonTree == null) existing?.seasonNumber257                else seasonNode?.takeIf { it.parent != null }?.let { ChapterRecognition.parseSeasonNumber(it.name)?.toDouble() },258        )259        val savedManga = if (existing != null && nextManga.copy(260                dateAdded = existing.dateAdded,261                lastUpdate = existing.lastUpdate,262                updatedAt = existing.updatedAt,263            ) == existing264        ) existing else database.upsertManga(nextManga)265        if (existing == null) scan.added += 1 else scan.updated += 1266        if (existing == null) scan.addedTitleIds += savedManga.id267        scan.observedTitleIds += savedManga.id268        scan.observedTitleIdentities += localLibraryIdentity(LocalLibraryEntityKind.Title, entry.itemType, virtualPath)269        return savedManga270    }271272    /**273     * Upserts one scanned chapter of [savedManga] inside the scan batch and records it in [scan].274     * A chapter still owned by one of [ancestorIds] moves to [savedManga] and is added to [movedChapterIds].275     */276    private fun upsertScannedChapter(277        chapter: LocalChapterScan,278        itemType: DbItemType,279        savedManga: DbManga,280        ancestorIds: Set<Long>,281        existingChapters: MutableMap<Pair<Long?, String>, DbChapter>,282        movedChapterIds: MutableSet<Long>,283        folders: List<DbLocalFolder>,284        now: Long,285        scan: ScanAccumulator,286    ) {287        val virtualChapterPath = chapter.path288        val chapterKey = savedManga.id to virtualChapterPath289        // A show that becomes a Seasons title hands its flattened episodes to the season records.290        val observedChapter = existingChapters[chapterKey]291            ?: ancestorIds.firstNotNullOfOrNull { existingChapters[it to virtualChapterPath] }292        val existingChapter = observedChapter?.let { database.chapter(it.id) }293        if (observedChapter != null && existingChapter == null) return294        if (existingChapter != null && ((existingChapter.mangaId != savedManga.id && existingChapter.mangaId !in ancestorIds) ||295                localVirtualPathFromStoredPath(existingChapter.archivePath, folders) != virtualChapterPath)) return296        if (existingChapter != null && existingChapter.mangaId != savedManga.id) {297            existingChapters.remove(existingChapter.mangaId to virtualChapterPath)298            movedChapterIds += existingChapter.id299        }300        val nextChapter = (existingChapter ?: DbChapter()).copy(301            mangaId = savedManga.id,302            name = chapter.label,303            url = virtualChapterPath,304            archivePath = virtualChapterPath,305            dateUpload = chapter.metadata?.dateUpload ?: existingChapter?.dateUpload ?: now.toString(),306            scanlator = chapter.metadata?.scanlator ?: existingChapter?.scanlator.orEmpty(),307            isFiller = chapter.metadata?.filler ?: existingChapter?.isFiller ?: false,308            description = chapter.metadata?.summary ?: existingChapter?.description,309            thumbnailUrl = chapter.previewUrl ?: existingChapter?.thumbnailUrl,310            number = chapter.number ?: existingChapter?.number,311            season = chapter.season ?: existingChapter?.season,312            numberingName = chapter.numberingName ?: existingChapter?.numberingName,313            fetchedAt = existingChapter?.fetchedAt ?: now,314            updatedAt = now,315        )316        val savedChapter = if (existingChapter != null && nextChapter.copy(updatedAt = existingChapter.updatedAt) == existingChapter) {317            existingChapter318        } else {319            database.upsertChapter(nextChapter)320        }321        existingChapters[chapterKey] = savedChapter322        if (existingChapter == null) scan.addedChapterIds += savedChapter.id323        scan.observedChapterIds += savedChapter.id324        scan.observedChapterIdentities += localLibraryIdentity(LocalLibraryEntityKind.Chapter, itemType, virtualChapterPath)325    }326327    private suspend fun reconcileUnlocked(): LocalLibraryReconciliationResult {328        val scan = scanUnlocked()329        val folders = effectiveLocalLibraryFolders(database.settings(), files)330        val operation = localLibraryReconciliationOperation(scan, database, folders)331        return reconcileLocalLibrary(operation)332    }333334    override suspend fun reconcile(): LocalLibraryReconciliationResult = withOperationLock {335        reconcileUnlocked()336    }337338    override suspend fun reconcile(scan: LocalLibraryScanResult): LocalLibraryReconciliationResult {339        val folders = effectiveLocalLibraryFolders(database.settings(), files)340        val operation = localLibraryReconciliationOperation(scan, database, folders)341        return reconcileLocalLibrary(operation)342    }343344    override suspend fun reconcileForEntryManagement(): LocalLibraryReconciliationResult = reconcileUnlocked()345346    private data class LocalChapterScan(347        val path: String, val label: String,348        val number: Double? = null, val season: Int? = null, val numberingName: String? = null,349        val metadata: LocalEpisodeMetadata? = null, val previewUrl: String? = null,350    )351352    private suspend fun chaptersFor(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory): List<LocalChapterScan> {353        if (entry.itemType != DbItemType.Anime) return chapterPathsFor(entry, folder, inventory).map { LocalChapterScan(it.first, it.second) }354        val directory = if (entry.isArchive) {355            if (entry.path.startsWith("content://")) folder.path else entry.path.substringBeforeLast('/', "")356        } else entry.path357        val episodes = readEpisodes("${directory.trimEnd('/')}/episodes.json", inventory)358        val season = ChapterRecognition.parseSeasonNumber(if (entry.isArchive) directory.substringAfterLast('/') else entry.name)359        val sources = animeEpisodeSources(entry, folder, inventory, directory)360        return sources.map { source ->361            val inferred = ChapterRecognition.rawSeasonAndNumber(entry.name, source.label)362            val localDetails = if (source.directory == directory) null else363                readEpisodes("${source.directory.trimEnd('/')}/episodes.json", inventory).find(inferred.second)364            val details = localDetails ?: episodes.find(inferred.second)365            val previewDirectory = if (localDetails != null) source.directory else directory366            LocalChapterScan(source.path, details?.name ?: source.label, inferred.second,367                ChapterRecognition.parseSeasonNumber(source.label) ?: ChapterRecognition.parseSeasonNumber(source.folderName) ?: season,368                source.label, details, resolveLocalImage(previewDirectory, details?.previewUrl, inventory))369        }370    }371372    private data class LocalEpisodeSource(val path: String, val label: String, val directory: String, val folderName: String = "")373374    /** Root files and one subfolder level, using provider names instead of parsing opaque document IDs. */375    private fun animeEpisodeSources(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory, directory: String): List<LocalEpisodeSource> {376        if (entry.isArchive) return listOf(LocalEpisodeSource(getLocalVirtualPath(folder, entry.path), entry.name, directory))377        val children = inventory.directoryEntries(directory)378            ?: return chapterPathsForLegacyAnime(entry, folder, inventory, directory)379        val result = mutableListOf<LocalEpisodeSource>()380        fun addFile(child: LocalDirectoryEntry, parent: String, folderName: String) {381            if (child.isDirectory || child.name.startsWith('.') || child.name.substringAfterLast('.', "").lowercase() !in animeChapterExtensions) return382            result += LocalEpisodeSource(getLocalVirtualPath(folder, child.path), child.name.substringBeforeLast('.'), parent, folderName)383        }384        children.filterNot { it.name.startsWith('.') }.forEach { child ->385            if (child.isDirectory) {386                inventory.directoryEntries(child.path).orEmpty().forEach { addFile(it, child.path, child.name) }387            } else addFile(child, directory, entry.name)388        }389        return result.distinctBy { it.path }390    }391392    /** Compatibility for custom file backends predating immediate-child listings. */393    private fun chapterPathsForLegacyAnime(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory, directory: String): List<LocalEpisodeSource> =394        inventory.entries(entry.path).orEmpty().filterNot { it.isTitleRootCover(entry.path) }395            .filter { !it.isArchive || it.path.substringAfterLast('.').lowercase() in animeChapterExtensions }396            .map { LocalEpisodeSource(getLocalVirtualPath(folder, it.path), it.name, directory) }397            .ifEmpty { listOf(LocalEpisodeSource(getLocalVirtualPath(folder, entry.path), entry.name, directory)) }398399    private suspend fun readEpisodes(path: String, inventory: ScanInventory): LocalEpisodeMetadataIndex {400        inventory.episodes[path]?.let { return it }401        val fingerprint = inventory.fingerprint(path)402        val parsed = fingerprint?.let { episodeCache[it] } ?: if (!files.exists(path)) null else catchingNonCancellation {403            parseLocalEpisodes(files.readBytesAsync(path, 1024L * 1024).decodeToString())404        }.getOrNull()?.also { if (fingerprint != null) episodeCache[fingerprint] = it }405        return (parsed ?: LocalEpisodeMetadataIndex(emptyList())).also { inventory.episodes[path] = it }406    }407408    private suspend fun resolveLocalImage(directory: String, reference: String?, inventory: ScanInventory): String? {409        val path = reference ?: return null410        if (path.startsWith("https://", true) || path.startsWith("http://", true)) return path411        if (path.startsWith('/') || path.contains('\\') || path.contains(':') || path.contains('\u0000')) return null412        if (path.split('/').any { it.isBlank() || it == "." || it == ".." }) return null413        return catchingNonCancellation {414            val root = files.canonicalPath(directory)?.replace('\\', '/')?.trimEnd('/')415            if (root == null) {416                // Follow provider children by display name; document IDs need not encode a hierarchy.417                if (!directory.startsWith("content://")) return@catchingNonCancellation null418                val parts = path.split('/')419                if (parts.size > 64) return@catchingNonCancellation null420                var current = directory421                for ((index, name) in parts.withIndex()) {422                    val entries = inventory.directoryEntries(current)423                    if (entries == null) {424                        val sibling = if (index == parts.lastIndex) inventory.children(current).firstOrNull { it.name == name } else null425                        return@catchingNonCancellation sibling?.let { files.readableUrl(it.path) }426                    }427                    val child = entries.singleOrNull { it.name == name } ?: return@catchingNonCancellation null428                    if (child.isDirectory != (index != parts.lastIndex)) return@catchingNonCancellation null429                    current = child.path430                }431                return@catchingNonCancellation files.readableUrl(current)432            }433            val candidate = files.canonicalPath("${directory.trimEnd('/')}/$path")?.replace('\\', '/') ?: return@catchingNonCancellation null434            if (!candidate.startsWith("$root/") || !files.exists(candidate)) null else files.readableUrl(candidate)435        }.getOrNull()436    }437438    private suspend fun chapterPathsFor(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory): List<Pair<String, String>> {439        if (entry.path.endsWith(".epub", ignoreCase = true)) return epubChapters(folder, entry.path, entry.name)440        if (entry.isArchive) return listOf(getLocalVirtualPath(folder, entry.path) to entry.name)441        return inventory.entries(entry.path).orEmpty()442            .filterNot { it.isTitleRootCover(entry.path) }443            .filter { entry.itemType != DbItemType.Anime || !it.isArchive ||444                it.path.substringAfterLast('.').lowercase() in animeChapterExtensions }445            .flatMap { child ->446                if (child.path.endsWith(".epub", ignoreCase = true)) {447                    epubChapters(folder, child.path, child.name)448                } else {449                    listOf(getLocalVirtualPath(folder, child.path) to child.name)450                }451            }452            .ifEmpty { listOf(getLocalVirtualPath(folder, entry.path) to entry.name) }453    }454455    private suspend fun epubChapters(folder: DbLocalFolder, path: String, fallbackName: String): List<Pair<String, String>> {456        val epubChapters = archives.listEpubChaptersAsync(path)457        val virtualPath = getLocalVirtualPath(folder, path)458        return if (epubChapters.isNotEmpty()) {459            epubChapters.mapIndexed { index, chapter -> "$virtualPath#$index" to chapter.title }460        } else {461            listOf(virtualPath to fallbackName)462        }463    }464465    /** One anime folder below a library root; [parent] is the virtual path of its Seasons-type owner. */466    private data class SeasonNode(val path: String, val name: String, val virtual: String, val parent: String?, val seasons: Boolean)467468    /**469     * Animetail `LocalAnimeFetchTypeManager`: a folder with a video/archive file lists episodes (Yokan also470     * flattens its immediate subfolders); otherwise non-hidden subfolders make it a Seasons title whose471     * subfolders are season titles, recursively. Breadth-first, so parents precede their seasons.472     * Null when the backend has no immediate-child listings; download-layout type folders are skipped.473     */474    private fun animeSeasonTree(folder: DbLocalFolder, inventory: ScanInventory): Map<String, SeasonNode>? {475        fun visible(entries: List<LocalDirectoryEntry>) = entries.filterNot { it.name.startsWith('.') }476        val roots = visible(inventory.directoryEntries(folder.path) ?: return null)477            .filter { it.isDirectory && downloadItemTypeFromFolder(it.name) == null }478        val result = LinkedHashMap<String, SeasonNode>()479        val queue = ArrayDeque(roots.map { it to null as String? })480        // ponytail: 10,000-folder cap per library root; page the walk if libraries outgrow it.481        while (queue.isNotEmpty() && result.size < 10_000) {482            val (directory, parent) = queue.removeFirst()483            val virtual = getLocalVirtualPath(folder, directory.path)484            if (virtual in result) continue485            val children = visible(inventory.directoryEntries(directory.path) ?: continue)486            val hasEpisodes = children.any { !it.isDirectory && it.name.substringAfterLast('.', "").lowercase() in animeChapterExtensions }487            val subfolders = children.filter { it.isDirectory }488            val seasons = !hasEpisodes && subfolders.isNotEmpty()489            result[virtual] = SeasonNode(directory.path, directory.name, virtual, parent, seasons)490            if (seasons) subfolders.forEach { queue.addLast(it to virtual) }491        }492        return result493    }494495    /** Seasons titles and their seasons first (parents before children), then every other listed entry. */496    private fun seasonOrderedEntries(497        folder: DbLocalFolder,498        tree: Map<String, SeasonNode>,499        listed: List<LocalScanEntry>,500        skipped: (SeasonNode) -> Boolean,501    ): List<LocalScanEntry> {502        val listedByVirtual = listed.associateBy { getLocalVirtualPath(folder, it.path) }503        val linked = tree.values.filter { (it.seasons || it.parent != null) && !skipped(it) }504        val linkedPaths = linked.mapTo(HashSet()) { it.virtual }505        return linked.map { node -> listedByVirtual[node.virtual] ?: LocalScanEntry(node.path, node.name, false, DbItemType.Anime) } +506            listed.filterNot { getLocalVirtualPath(folder, it.path) in linkedPaths }507    }508509    /**510     * Season folders scanned before season records existed were separate top-level titles. Their library511     * membership moves to the show once, when they are first linked; later scans leave the user's choice alone.512     */513    private fun inheritedLibraryState(tree: Map<String, SeasonNode>, existing: Map<Pair<DbItemType, String>, DbManga>): Map<String, Set<Long>> {514        val result = mutableMapOf<String, MutableSet<Long>>()515        tree.values.forEach { node ->516            if (node.parent == null) return@forEach517            val season = existing[DbItemType.Anime to node.virtual]?.takeIf { it.favorite && it.parentId == null } ?: return@forEach518            var show = node519            while (true) show = show.parent?.let(tree::get) ?: break520            result.getOrPut(show.virtual) { linkedSetOf() } += season.categories.orEmpty()521        }522        return result523    }524525    private data class LocalScanEntry(526        val path: String,527        val name: String,528        val isArchive: Boolean,529        val itemType: DbItemType,530    )531532    private fun LocalEntry.toScanEntry(folder: DbLocalFolder, defaultItemType: DbItemType): LocalScanEntry {533        downloadedTitleEntry(folder, defaultItemType)?.let { return it }534        return LocalScanEntry(path = path, name = name, isArchive = isArchive, itemType = defaultItemType)535    }536537    private fun LocalEntry.downloadedTitleEntry(folder: DbLocalFolder, defaultItemType: DbItemType): LocalScanEntry? {538        val relativeParts = relativePathUnder(folder.path, path)539            .split('/')540            .filter { it.isNotBlank() }541        val typeIndex = relativeParts.indexOfFirst { downloadItemTypeFromFolder(it) != null }542        if (typeIndex < 0 || relativeParts.size <= typeIndex + 3) return null543        val itemType = downloadItemTypeFromFolder(relativeParts[typeIndex]) ?: defaultItemType544        val titleRelativeParts = relativeParts.take(typeIndex + 3)545        val titlePath = "${folder.path.trimEnd('/', '\\')}/${titleRelativeParts.joinToString("/")}"546        return LocalScanEntry(547            path = titlePath,548            name = relativeParts[typeIndex + 2],549            isArchive = false,550            itemType = itemType,551        )552    }553554    private fun relativePathUnder(base: String, target: String): String {555        val normalizedBase = base.replace('\\', '/').trimEnd('/')556        val normalizedTarget = target.replace('\\', '/').trimEnd('/')557        return if (normalizedTarget.startsWith("$normalizedBase/")) {558            normalizedTarget.substring(normalizedBase.length + 1)559        } else {560            normalizedTarget561        }562    }563564    /** Managed import areas are scanned only through their published roots, never an ancestor. */565    private fun scanCanonicalPath(path: String): String? =566        runCatching { files.canonicalPath(path) }.getOrNull()?.replace('\\', '/')?.trimEnd('/')567568    private fun LocalEntry.isInColorizerStagingFolder(folderRoot: String): Boolean {569        val normalizedRoot = folderRoot.replace('\\', '/').trimEnd('/')570        val normalizedPath = path.replace('\\', '/').trimEnd('/')571        if (!normalizedPath.startsWith("$normalizedRoot/")) return false572        return normalizedPath.substring(normalizedRoot.length + 1)573            .split('/')574            .any { it.startsWith(".colorizer-") && it.endsWith(".partial") }575    }576577    private suspend fun readMetadata(titlePath: String, inventory: ScanInventory, itemType: DbItemType): LocalMetadata {578        val legacy = readLegacyMetadata(titlePath, inventory)579        val detailsPath = "${titlePath.trimEnd('/', '\\')}/details.json"580        val details = if (itemType == DbItemType.Anime && files.exists(detailsPath)) readMetadataFile(detailsPath, inventory, animetail = true) else null581        val metadata = if (details == null) legacy else LocalMetadata(582            name = details.name ?: legacy.name,583            description = details.description ?: legacy.description,584            author = details.author ?: legacy.author,585            artist = details.artist ?: legacy.artist,586            genres = details.genres ?: legacy.genres,587            status = details.status ?: legacy.status,588            imageUrl = legacy.imageUrl,589            customCoverFromTracker = legacy.customCoverFromTracker,590            language = legacy.language,591            cast = details.cast ?: legacy.cast,592        )593        return if (metadata.cast == null) metadata else metadata.copy(cast = metadata.cast.map { credit ->594            credit.copy(imageUrl = resolveLocalImage(titlePath, credit.imageUrl, inventory))595        })596    }597598    private suspend fun readMetadataFile(path: String, inventory: ScanInventory, animetail: Boolean = false): LocalMetadata? {599        val fingerprint = inventory.fingerprint(path)600        fingerprint?.let { metadataCache[it] }?.let { return it }601        val parsed = catchingNonCancellation {602            parseLocalMetadata(files.readBytesAsync(path, 64L * 1024).decodeToString(), animetail)603        }.getOrNull()604        if (parsed != null && fingerprint != null) metadataCache[fingerprint] = parsed605        return parsed606    }607608    private suspend fun readLegacyMetadata(titlePath: String, inventory: ScanInventory): LocalMetadata {609        metadataCandidates(titlePath, inventory).forEach { path ->610            readMetadataFile(path, inventory)?.let { return it }611        }612        return LocalMetadata()613    }614615    private fun metadataCandidates(titlePath: String, inventory: ScanInventory): List<String> =616        buildList {617            add("${titlePath.trimEnd('/', '\\')}/metadata.json")618            inventory.entries(titlePath).orEmpty()619                .map { "${it.path.trimEnd('/', '\\')}/metadata.json" }620                .forEach(::add)621        }.filter { files.exists(it) }622623    private suspend fun readCoverImage(titlePath: String, inventory: ScanInventory, excludedImages: Set<String> = emptySet()): ByteArray? {624        val candidates = inventory.children(titlePath)625            .filter { it.path.isCoverImagePath() }626        val imageFiles = if (excludedImages.isEmpty()) candidates else candidates.filterNot { entry ->627            catchingNonCancellation { files.readableUrl(entry.path) }.getOrNull() in excludedImages628        }629        val selected = imageFiles.firstOrNull { it.name.substringBeforeLast('.').equals("cover", ignoreCase = true) }630            ?: imageFiles.singleOrNull()631        return selected?.let { entry ->632            if (entry.lastModified > 0L) coverCache[entry]?.let { return it }633            catchingNonCancellation { files.readBytesAsync(entry.path, 4L * 1024 * 1024) }.getOrNull()?.also { bytes ->634                if (entry.lastModified > 0L) coverCache[entry] = bytes635            }636        }637    }638639    private fun LocalEntry.isTitleRootCover(titlePath: String): Boolean {640        val normalizedTitle = titlePath.replace('\\', '/').trimEnd('/')641        val normalizedPath = path.replace('\\', '/')642        val parent = normalizedPath.substringBeforeLast('/', "")643        return parent == normalizedTitle && normalizedPath.isCoverImagePath()644    }645646    private fun String.isCoverImagePath(): Boolean {647        val lower = substringAfterLast('/').lowercase()648        return lower.endsWith(".jpg") || lower.endsWith(".jpeg") ||649            lower.endsWith(".png") || lower.endsWith(".webp") ||650            lower.endsWith(".gif") || lower.endsWith(".bmp") ||651            lower.endsWith(".avif")652    }653654655    private fun inferItemType(root: String): DbItemType {656        val name = root.substringAfterLast('/').lowercase()657        return when {658            "anime" in name -> DbItemType.Anime659            "novel" in name -> DbItemType.Novel660            else -> DbItemType.Manga661        }662    }663664    override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? {665        if (pathOrMagnet.isBlank()) return null666        val isMagnet = pathOrMagnet.startsWith("magnet:", ignoreCase = true)667        val extractedName = if (isMagnet) TorrentUtils.extractMagnetDisplayName(pathOrMagnet) else null668        val extractedHash = if (isMagnet) TorrentUtils.extractInfoHashFromMagnet(pathOrMagnet) else null669        val baseName = displayName?.takeIf { it.isNotBlank() }670            ?: extractedName?.takeIf { it.isNotBlank() }671            ?: if (isMagnet) {672                if (!extractedHash.isNullOrBlank()) "Torrent (${extractedHash.take(8)})" else "Torrent"673            } else {674                pathOrMagnet.substringAfterLast('/')675                    .substringBefore('?')676                    .removeSuffix(".torrent")677                    .ifBlank { "Torrent" }678            }679        val now = nowMillis()680        val existing = database.mangas(DbItemType.Anime)681            .firstOrNull {682                it.isLocalArchive == true && it.source == "torrent" &&683                    (it.link == pathOrMagnet || (extractedHash != null && TorrentUtils.extractInfoHashFromMagnet(it.link.orEmpty()) == extractedHash))684            }685        val savedManga = database.upsertManga(686            (existing ?: DbManga()).copy(687                name = baseName,688                source = "torrent",689                itemType = DbItemType.Anime,690                isLocalArchive = true,691                link = pathOrMagnet,692                lang = existing?.lang ?: "en",693                dateAdded = existing?.dateAdded ?: now,694                lastUpdate = now,695                favorite = existing?.favorite ?: true,696            ),697        )698        val existingChapter = database.chapters(savedManga.id).firstOrNull { it.url == pathOrMagnet }699        database.upsertChapter(700            (existingChapter ?: DbChapter()).copy(701                mangaId = savedManga.id,702                name = baseName,703                url = pathOrMagnet,704                archivePath = if (isMagnet) "" else pathOrMagnet,705                dateUpload = (existingChapter?.dateUpload ?: now.toString()),706                fetchedAt = existingChapter?.fetchedAt ?: now,707                updatedAt = now,708            ),709        )710        return savedManga.id711    }712}713

Search chapters, reference and source filenames.