package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbLocalFolder import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbFetchType import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.getLocalVirtualPath import eu.friedcutlet.yokan.database.localVirtualPathFromStoredPath import eu.friedcutlet.yokan.services.files.BoundedCache import eu.friedcutlet.yokan.services.files.LocalFileEntry import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.files.downloadItemTypeFromFolder import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.files.LocalEntry import eu.friedcutlet.yokan.services.files.LocalDirectoryEntry import eu.friedcutlet.yokan.domain.ChapterRecognition import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders interface LocalLibraryService { suspend fun scan(): LocalLibraryScanResult /** Bypass fingerprint caches for a user-requested full rescan. */ suspend fun scanFresh(): LocalLibraryScanResult = scan() suspend fun reconcile(): LocalLibraryReconciliationResult suspend fun reconcile(scan: LocalLibraryScanResult): LocalLibraryReconciliationResult = reconcile() /** Serializes a complete scan/reconcile with entry-management apply. */ suspend fun withOperationLock(block: suspend () -> T): T = block() /** Called by entry management while [withOperationLock] is held. */ suspend fun reconcileForEntryManagement(): LocalLibraryReconciliationResult = reconcile() /** * Import a torrent file or magnet URL as a local-archive [DbManga] with a single chapter that * carries the file path or magnet URL; playback streams it through TorrServer * (`services/torrent/TorrentStreams`). Returns the upserted manga id, or null on failure. */ suspend fun importTorrent(pathOrMagnet: String, displayName: String? = null): Long? } class DefaultLocalLibraryService( private val database: YokanDatabase, private val files: LocalFileService, private val archives: LocalArchiveService, ) : LocalLibraryService { private val operationMutex = Mutex() private val animeChapterExtensions = setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8", "zip", "rar", "cbr", "cbz", "cbt", "tar") private var metadataCache = BoundedCache(512, 8 * 1024 * 1024) { it.weight } private var episodeCache = BoundedCache(128, 8 * 1024 * 1024) { it.weight } private var coverCache = BoundedCache(128, 32 * 1024 * 1024) { it.size } override suspend fun scanFresh(): LocalLibraryScanResult = withOperationLock { archives.invalidateIndexCache() metadataCache = BoundedCache(512, 8 * 1024 * 1024) { it.weight } episodeCache = BoundedCache(128, 8 * 1024 * 1024) { it.weight } coverCache = BoundedCache(128, 32 * 1024 * 1024) { it.size } scanUnlocked() } /** Listings live for one scan only: additions and removals are always discovered. */ private inner class ScanInventory { private val entries = mutableMapOf?>() private val children = mutableMapOf>() private val directoryEntries = mutableMapOf?>() val episodes = BoundedCache(128, 8 * 1024 * 1024) { it.weight } fun entries(path: String): List? = entries.getOrPut(path) { files.listLocalEntries(path) } fun children(path: String): List = children.getOrPut(path) { files.listFiles(path) } fun directoryEntries(path: String): List? = directoryEntries.getOrPut(path) { files.listDirectoryEntries(path) } fun fingerprint(path: String): LocalFileEntry? = children(path.substringBeforeLast('/', "")) .firstOrNull { it.path == path && it.lastModified > 0L } } override suspend fun withOperationLock(block: suspend () -> T): T = operationMutex.withLock { block() } /** * Bundled default folder rooted at `/local`. Always scanned in * addition to any user-configured virtual folders so a freshly installed app * has a working drop-in location. */ override suspend fun scan(): LocalLibraryScanResult { return withOperationLock { scanUnlocked() } } /** Totals and identity evidence collected over one scan. */ private class ScanAccumulator { var added = 0 var updated = 0 var total = 0 val addedTitleIds = mutableListOf() val observedTitleIds = mutableListOf() val addedChapterIds = mutableListOf() val observedChapterIds = mutableListOf() val healthyFolders = mutableListOf() val unavailableFolders = mutableListOf() val observedTitleIdentities = mutableListOf() val observedChapterIdentities = mutableListOf() fun toResult() = LocalLibraryScanResult( added = added, updated = updated, total = total, addedTitleIds = addedTitleIds.distinct(), observedTitleIds = observedTitleIds.distinct(), addedChapterIds = addedChapterIds.distinct(), observedChapterIds = observedChapterIds.distinct(), healthyFolders = healthyFolders, unavailableFolders = unavailableFolders, observedTitleIdentities = observedTitleIdentities.distinct(), observedChapterIdentities = observedChapterIdentities.distinct(), ) } private suspend fun scanUnlocked(): LocalLibraryScanResult { files.prepare() val inventory = ScanInventory() val importArea = scanCanonicalPath("${files.downloadRoot.trimEnd('/')}/local-imports") val folders = effectiveLocalLibraryFolders(database.settings(), files) if (folders.isEmpty()) return LocalLibraryScanResult(0, 0, 0) val scan = ScanAccumulator() val existingMangas = database.mangas() .asSequence() .filter(DbManga::isLocalLibraryEntry) .associateByTo(mutableMapOf()) { manga -> manga.itemType to localVirtualPathFromStoredPath(manga.link, folders) } val existingChapters = database.chapters() .associateByTo(mutableMapOf()) { chapter -> chapter.mangaId to localVirtualPathFromStoredPath(chapter.archivePath, folders) } folders.forEach { folder -> val entries = listFolderEntries(folder, inventory) ?: run { scan.unavailableFolders += folder return@forEach } scan.healthyFolders += folder val defaultItemType = inferItemType(folder.path) val canonicalFolder = scanCanonicalPath(folder.path) val scansImportAncestor = importArea != null && canonicalFolder != null && (canonicalFolder == importArea || importArea.startsWith("$canonicalFolder/")) fun skipped(entry: LocalEntry) = entry.isInColorizerStagingFolder(folder.path) || (scansImportAncestor && scanCanonicalPath(entry.path).let { path -> path == null || path == importArea || path.startsWith("$importArea/") }) val listedEntries = entries.filterNot(::skipped) .map { it.toScanEntry(folder, defaultItemType) } .distinctBy { it.path } val seasonTree = if (defaultItemType == DbItemType.Anime) animeSeasonTree(folder, inventory) else null val scanEntries = seasonTree?.let { tree -> seasonOrderedEntries(folder, tree, listedEntries) { node -> skipped(LocalEntry(node.path, node.name, false)) } } ?: listedEntries val inheritedLibrary = seasonTree?.let { inheritedLibraryState(it, existingMangas) }.orEmpty() val savedTitleIds = mutableMapOf() scanEntries.forEach { entry -> scan.total += 1 val virtualMangaPath = getLocalVirtualPath(folder, entry.path) val seasonNode = seasonTree?.get(virtualMangaPath) val listsSeasons = seasonNode?.seasons == true val parentId = seasonNode?.parent?.let(savedTitleIds::get) val ancestorIds = generateSequence(seasonNode?.parent) { seasonTree?.get(it)?.parent }.mapNotNull(savedTitleIds::get).toSet() val metadata = readMetadata(entry.path, inventory, entry.itemType) val coverImage = readCoverImage(entry.path, inventory, metadata.cast.orEmpty().mapNotNull { it.imageUrl }.toSet()) val observedExisting = existingMangas[entry.itemType to virtualMangaPath] val now = nowMillis() val chapters = if (listsSeasons) emptyList() else chaptersFor(entry, folder, inventory) val movedChapterIds = mutableSetOf() database.batch { val savedManga = upsertScannedTitle( entry = entry, virtualPath = virtualMangaPath, observedExisting = observedExisting, folders = folders, metadata = metadata, coverImage = coverImage, seasonTree = seasonTree, seasonNode = seasonNode, parentId = parentId, inherited = inheritedLibrary[virtualMangaPath], now = now, scan = scan, ) ?: return@batch existingMangas[entry.itemType to virtualMangaPath] = savedManga savedTitleIds[virtualMangaPath] = savedManga.id chapters.forEach { chapter -> upsertScannedChapter(chapter, entry.itemType, savedManga, ancestorIds, existingChapters, movedChapterIds, folders, now, scan) } if (movedChapterIds.isNotEmpty()) { database.histories().filter { it.chapterId in movedChapterIds } .forEach { database.upsertHistory(it.copy(mangaId = savedManga.id)) } database.updates().filter { it.chapterId in movedChapterIds } .forEach { database.upsertUpdate(it.copy(mangaId = savedManga.id)) } } } } } return scan.toResult() } /** Root entries of a configured folder, or null when it is missing or cannot be listed. */ private fun listFolderEntries(folder: DbLocalFolder, inventory: ScanInventory): List? { if (folder.path.isBlank() || !runCatching { files.exists(folder.path) }.getOrDefault(false)) return null return runCatching { inventory.entries(folder.path) }.getOrNull() } /** * Upserts one scanned title inside the scan batch and records it in [scan]. Null when the row * was deleted, retyped or relinked since the scan read it. */ private fun upsertScannedTitle( entry: LocalScanEntry, virtualPath: String, observedExisting: DbManga?, folders: List, metadata: LocalMetadata, coverImage: ByteArray?, seasonTree: Map?, seasonNode: SeasonNode?, parentId: Long?, inherited: Set?, now: Long, scan: ScanAccumulator, ): DbManga? { // Browser disk reads suspend; reading progress, categories and deletion may change meanwhile. val existing = observedExisting?.let { database.manga(it.id) } if (observedExisting != null && existing == null) return null if (existing != null && (!existing.isLocalLibraryEntry() || existing.itemType != entry.itemType || localVirtualPathFromStoredPath(existing.link, folders) != virtualPath)) return null val nextManga = (existing ?: DbManga()).copy( name = metadata.name ?: entry.name, link = virtualPath, imageUrl = metadata.imageUrl ?: existing?.imageUrl, description = metadata.description ?: existing?.description, author = metadata.author ?: existing?.author, artist = metadata.artist ?: existing?.artist, status = metadata.status ?: existing?.status ?: DbStatus.Unknown, itemType = entry.itemType, genre = metadata.genres ?: existing?.genre, cast = metadata.cast ?: existing?.cast.orEmpty(), isLocalArchive = true, customCoverImage = if (observedExisting != null && !existing?.customCoverImage.contentEquals(observedExisting.customCoverImage)) existing?.customCoverImage else coverImage ?: existing?.customCoverImage, customCoverFromTracker = metadata.customCoverFromTracker ?: existing?.customCoverFromTracker, source = "local", lang = metadata.language ?: existing?.lang ?: "en", dateAdded = existing?.dateAdded ?: now, lastUpdate = now, // Favorite season folders that used to be separate titles keep the show in the library. favorite = (existing?.favorite ?: false) || inherited != null, categories = inherited?.let { (existing?.categories.orEmpty() + it).distinct() } ?: existing?.categories, parentId = if (seasonTree == null) existing?.parentId else parentId, fetchType = when { seasonTree == null -> existing?.fetchType ?: DbFetchType.Episodes seasonNode?.seasons == true -> DbFetchType.Seasons else -> DbFetchType.Episodes }, seasonNumber = if (seasonTree == null) existing?.seasonNumber else seasonNode?.takeIf { it.parent != null }?.let { ChapterRecognition.parseSeasonNumber(it.name)?.toDouble() }, ) val savedManga = if (existing != null && nextManga.copy( dateAdded = existing.dateAdded, lastUpdate = existing.lastUpdate, updatedAt = existing.updatedAt, ) == existing ) existing else database.upsertManga(nextManga) if (existing == null) scan.added += 1 else scan.updated += 1 if (existing == null) scan.addedTitleIds += savedManga.id scan.observedTitleIds += savedManga.id scan.observedTitleIdentities += localLibraryIdentity(LocalLibraryEntityKind.Title, entry.itemType, virtualPath) return savedManga } /** * Upserts one scanned chapter of [savedManga] inside the scan batch and records it in [scan]. * A chapter still owned by one of [ancestorIds] moves to [savedManga] and is added to [movedChapterIds]. */ private fun upsertScannedChapter( chapter: LocalChapterScan, itemType: DbItemType, savedManga: DbManga, ancestorIds: Set, existingChapters: MutableMap, DbChapter>, movedChapterIds: MutableSet, folders: List, now: Long, scan: ScanAccumulator, ) { val virtualChapterPath = chapter.path val chapterKey = savedManga.id to virtualChapterPath // A show that becomes a Seasons title hands its flattened episodes to the season records. val observedChapter = existingChapters[chapterKey] ?: ancestorIds.firstNotNullOfOrNull { existingChapters[it to virtualChapterPath] } val existingChapter = observedChapter?.let { database.chapter(it.id) } if (observedChapter != null && existingChapter == null) return if (existingChapter != null && ((existingChapter.mangaId != savedManga.id && existingChapter.mangaId !in ancestorIds) || localVirtualPathFromStoredPath(existingChapter.archivePath, folders) != virtualChapterPath)) return if (existingChapter != null && existingChapter.mangaId != savedManga.id) { existingChapters.remove(existingChapter.mangaId to virtualChapterPath) movedChapterIds += existingChapter.id } val nextChapter = (existingChapter ?: DbChapter()).copy( mangaId = savedManga.id, name = chapter.label, url = virtualChapterPath, archivePath = virtualChapterPath, dateUpload = chapter.metadata?.dateUpload ?: existingChapter?.dateUpload ?: now.toString(), scanlator = chapter.metadata?.scanlator ?: existingChapter?.scanlator.orEmpty(), isFiller = chapter.metadata?.filler ?: existingChapter?.isFiller ?: false, description = chapter.metadata?.summary ?: existingChapter?.description, thumbnailUrl = chapter.previewUrl ?: existingChapter?.thumbnailUrl, number = chapter.number ?: existingChapter?.number, season = chapter.season ?: existingChapter?.season, numberingName = chapter.numberingName ?: existingChapter?.numberingName, fetchedAt = existingChapter?.fetchedAt ?: now, updatedAt = now, ) val savedChapter = if (existingChapter != null && nextChapter.copy(updatedAt = existingChapter.updatedAt) == existingChapter) { existingChapter } else { database.upsertChapter(nextChapter) } existingChapters[chapterKey] = savedChapter if (existingChapter == null) scan.addedChapterIds += savedChapter.id scan.observedChapterIds += savedChapter.id scan.observedChapterIdentities += localLibraryIdentity(LocalLibraryEntityKind.Chapter, itemType, virtualChapterPath) } private suspend fun reconcileUnlocked(): LocalLibraryReconciliationResult { val scan = scanUnlocked() val folders = effectiveLocalLibraryFolders(database.settings(), files) val operation = localLibraryReconciliationOperation(scan, database, folders) return reconcileLocalLibrary(operation) } override suspend fun reconcile(): LocalLibraryReconciliationResult = withOperationLock { reconcileUnlocked() } override suspend fun reconcile(scan: LocalLibraryScanResult): LocalLibraryReconciliationResult { val folders = effectiveLocalLibraryFolders(database.settings(), files) val operation = localLibraryReconciliationOperation(scan, database, folders) return reconcileLocalLibrary(operation) } override suspend fun reconcileForEntryManagement(): LocalLibraryReconciliationResult = reconcileUnlocked() private data class LocalChapterScan( val path: String, val label: String, val number: Double? = null, val season: Int? = null, val numberingName: String? = null, val metadata: LocalEpisodeMetadata? = null, val previewUrl: String? = null, ) private suspend fun chaptersFor(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory): List { if (entry.itemType != DbItemType.Anime) return chapterPathsFor(entry, folder, inventory).map { LocalChapterScan(it.first, it.second) } val directory = if (entry.isArchive) { if (entry.path.startsWith("content://")) folder.path else entry.path.substringBeforeLast('/', "") } else entry.path val episodes = readEpisodes("${directory.trimEnd('/')}/episodes.json", inventory) val season = ChapterRecognition.parseSeasonNumber(if (entry.isArchive) directory.substringAfterLast('/') else entry.name) val sources = animeEpisodeSources(entry, folder, inventory, directory) return sources.map { source -> val inferred = ChapterRecognition.rawSeasonAndNumber(entry.name, source.label) val localDetails = if (source.directory == directory) null else readEpisodes("${source.directory.trimEnd('/')}/episodes.json", inventory).find(inferred.second) val details = localDetails ?: episodes.find(inferred.second) val previewDirectory = if (localDetails != null) source.directory else directory LocalChapterScan(source.path, details?.name ?: source.label, inferred.second, ChapterRecognition.parseSeasonNumber(source.label) ?: ChapterRecognition.parseSeasonNumber(source.folderName) ?: season, source.label, details, resolveLocalImage(previewDirectory, details?.previewUrl, inventory)) } } private data class LocalEpisodeSource(val path: String, val label: String, val directory: String, val folderName: String = "") /** Root files and one subfolder level, using provider names instead of parsing opaque document IDs. */ private fun animeEpisodeSources(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory, directory: String): List { if (entry.isArchive) return listOf(LocalEpisodeSource(getLocalVirtualPath(folder, entry.path), entry.name, directory)) val children = inventory.directoryEntries(directory) ?: return chapterPathsForLegacyAnime(entry, folder, inventory, directory) val result = mutableListOf() fun addFile(child: LocalDirectoryEntry, parent: String, folderName: String) { if (child.isDirectory || child.name.startsWith('.') || child.name.substringAfterLast('.', "").lowercase() !in animeChapterExtensions) return result += LocalEpisodeSource(getLocalVirtualPath(folder, child.path), child.name.substringBeforeLast('.'), parent, folderName) } children.filterNot { it.name.startsWith('.') }.forEach { child -> if (child.isDirectory) { inventory.directoryEntries(child.path).orEmpty().forEach { addFile(it, child.path, child.name) } } else addFile(child, directory, entry.name) } return result.distinctBy { it.path } } /** Compatibility for custom file backends predating immediate-child listings. */ private fun chapterPathsForLegacyAnime(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory, directory: String): List = inventory.entries(entry.path).orEmpty().filterNot { it.isTitleRootCover(entry.path) } .filter { !it.isArchive || it.path.substringAfterLast('.').lowercase() in animeChapterExtensions } .map { LocalEpisodeSource(getLocalVirtualPath(folder, it.path), it.name, directory) } .ifEmpty { listOf(LocalEpisodeSource(getLocalVirtualPath(folder, entry.path), entry.name, directory)) } private suspend fun readEpisodes(path: String, inventory: ScanInventory): LocalEpisodeMetadataIndex { inventory.episodes[path]?.let { return it } val fingerprint = inventory.fingerprint(path) val parsed = fingerprint?.let { episodeCache[it] } ?: if (!files.exists(path)) null else catchingNonCancellation { parseLocalEpisodes(files.readBytesAsync(path, 1024L * 1024).decodeToString()) }.getOrNull()?.also { if (fingerprint != null) episodeCache[fingerprint] = it } return (parsed ?: LocalEpisodeMetadataIndex(emptyList())).also { inventory.episodes[path] = it } } private suspend fun resolveLocalImage(directory: String, reference: String?, inventory: ScanInventory): String? { val path = reference ?: return null if (path.startsWith("https://", true) || path.startsWith("http://", true)) return path if (path.startsWith('/') || path.contains('\\') || path.contains(':') || path.contains('\u0000')) return null if (path.split('/').any { it.isBlank() || it == "." || it == ".." }) return null return catchingNonCancellation { val root = files.canonicalPath(directory)?.replace('\\', '/')?.trimEnd('/') if (root == null) { // Follow provider children by display name; document IDs need not encode a hierarchy. if (!directory.startsWith("content://")) return@catchingNonCancellation null val parts = path.split('/') if (parts.size > 64) return@catchingNonCancellation null var current = directory for ((index, name) in parts.withIndex()) { val entries = inventory.directoryEntries(current) if (entries == null) { val sibling = if (index == parts.lastIndex) inventory.children(current).firstOrNull { it.name == name } else null return@catchingNonCancellation sibling?.let { files.readableUrl(it.path) } } val child = entries.singleOrNull { it.name == name } ?: return@catchingNonCancellation null if (child.isDirectory != (index != parts.lastIndex)) return@catchingNonCancellation null current = child.path } return@catchingNonCancellation files.readableUrl(current) } val candidate = files.canonicalPath("${directory.trimEnd('/')}/$path")?.replace('\\', '/') ?: return@catchingNonCancellation null if (!candidate.startsWith("$root/") || !files.exists(candidate)) null else files.readableUrl(candidate) }.getOrNull() } private suspend fun chapterPathsFor(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory): List> { if (entry.path.endsWith(".epub", ignoreCase = true)) return epubChapters(folder, entry.path, entry.name) if (entry.isArchive) return listOf(getLocalVirtualPath(folder, entry.path) to entry.name) return inventory.entries(entry.path).orEmpty() .filterNot { it.isTitleRootCover(entry.path) } .filter { entry.itemType != DbItemType.Anime || !it.isArchive || it.path.substringAfterLast('.').lowercase() in animeChapterExtensions } .flatMap { child -> if (child.path.endsWith(".epub", ignoreCase = true)) { epubChapters(folder, child.path, child.name) } else { listOf(getLocalVirtualPath(folder, child.path) to child.name) } } .ifEmpty { listOf(getLocalVirtualPath(folder, entry.path) to entry.name) } } private suspend fun epubChapters(folder: DbLocalFolder, path: String, fallbackName: String): List> { val epubChapters = archives.listEpubChaptersAsync(path) val virtualPath = getLocalVirtualPath(folder, path) return if (epubChapters.isNotEmpty()) { epubChapters.mapIndexed { index, chapter -> "$virtualPath#$index" to chapter.title } } else { listOf(virtualPath to fallbackName) } } /** One anime folder below a library root; [parent] is the virtual path of its Seasons-type owner. */ private data class SeasonNode(val path: String, val name: String, val virtual: String, val parent: String?, val seasons: Boolean) /** * Animetail `LocalAnimeFetchTypeManager`: a folder with a video/archive file lists episodes (Yokan also * flattens its immediate subfolders); otherwise non-hidden subfolders make it a Seasons title whose * subfolders are season titles, recursively. Breadth-first, so parents precede their seasons. * Null when the backend has no immediate-child listings; download-layout type folders are skipped. */ private fun animeSeasonTree(folder: DbLocalFolder, inventory: ScanInventory): Map? { fun visible(entries: List) = entries.filterNot { it.name.startsWith('.') } val roots = visible(inventory.directoryEntries(folder.path) ?: return null) .filter { it.isDirectory && downloadItemTypeFromFolder(it.name) == null } val result = LinkedHashMap() val queue = ArrayDeque(roots.map { it to null as String? }) // ponytail: 10,000-folder cap per library root; page the walk if libraries outgrow it. while (queue.isNotEmpty() && result.size < 10_000) { val (directory, parent) = queue.removeFirst() val virtual = getLocalVirtualPath(folder, directory.path) if (virtual in result) continue val children = visible(inventory.directoryEntries(directory.path) ?: continue) val hasEpisodes = children.any { !it.isDirectory && it.name.substringAfterLast('.', "").lowercase() in animeChapterExtensions } val subfolders = children.filter { it.isDirectory } val seasons = !hasEpisodes && subfolders.isNotEmpty() result[virtual] = SeasonNode(directory.path, directory.name, virtual, parent, seasons) if (seasons) subfolders.forEach { queue.addLast(it to virtual) } } return result } /** Seasons titles and their seasons first (parents before children), then every other listed entry. */ private fun seasonOrderedEntries( folder: DbLocalFolder, tree: Map, listed: List, skipped: (SeasonNode) -> Boolean, ): List { val listedByVirtual = listed.associateBy { getLocalVirtualPath(folder, it.path) } val linked = tree.values.filter { (it.seasons || it.parent != null) && !skipped(it) } val linkedPaths = linked.mapTo(HashSet()) { it.virtual } return linked.map { node -> listedByVirtual[node.virtual] ?: LocalScanEntry(node.path, node.name, false, DbItemType.Anime) } + listed.filterNot { getLocalVirtualPath(folder, it.path) in linkedPaths } } /** * Season folders scanned before season records existed were separate top-level titles. Their library * membership moves to the show once, when they are first linked; later scans leave the user's choice alone. */ private fun inheritedLibraryState(tree: Map, existing: Map, DbManga>): Map> { val result = mutableMapOf>() tree.values.forEach { node -> if (node.parent == null) return@forEach val season = existing[DbItemType.Anime to node.virtual]?.takeIf { it.favorite && it.parentId == null } ?: return@forEach var show = node while (true) show = show.parent?.let(tree::get) ?: break result.getOrPut(show.virtual) { linkedSetOf() } += season.categories.orEmpty() } return result } private data class LocalScanEntry( val path: String, val name: String, val isArchive: Boolean, val itemType: DbItemType, ) private fun LocalEntry.toScanEntry(folder: DbLocalFolder, defaultItemType: DbItemType): LocalScanEntry { downloadedTitleEntry(folder, defaultItemType)?.let { return it } return LocalScanEntry(path = path, name = name, isArchive = isArchive, itemType = defaultItemType) } private fun LocalEntry.downloadedTitleEntry(folder: DbLocalFolder, defaultItemType: DbItemType): LocalScanEntry? { val relativeParts = relativePathUnder(folder.path, path) .split('/') .filter { it.isNotBlank() } val typeIndex = relativeParts.indexOfFirst { downloadItemTypeFromFolder(it) != null } if (typeIndex < 0 || relativeParts.size <= typeIndex + 3) return null val itemType = downloadItemTypeFromFolder(relativeParts[typeIndex]) ?: defaultItemType val titleRelativeParts = relativeParts.take(typeIndex + 3) val titlePath = "${folder.path.trimEnd('/', '\\')}/${titleRelativeParts.joinToString("/")}" return LocalScanEntry( path = titlePath, name = relativeParts[typeIndex + 2], isArchive = false, itemType = itemType, ) } private fun relativePathUnder(base: String, target: String): String { val normalizedBase = base.replace('\\', '/').trimEnd('/') val normalizedTarget = target.replace('\\', '/').trimEnd('/') return if (normalizedTarget.startsWith("$normalizedBase/")) { normalizedTarget.substring(normalizedBase.length + 1) } else { normalizedTarget } } /** Managed import areas are scanned only through their published roots, never an ancestor. */ private fun scanCanonicalPath(path: String): String? = runCatching { files.canonicalPath(path) }.getOrNull()?.replace('\\', '/')?.trimEnd('/') private fun LocalEntry.isInColorizerStagingFolder(folderRoot: String): Boolean { val normalizedRoot = folderRoot.replace('\\', '/').trimEnd('/') val normalizedPath = path.replace('\\', '/').trimEnd('/') if (!normalizedPath.startsWith("$normalizedRoot/")) return false return normalizedPath.substring(normalizedRoot.length + 1) .split('/') .any { it.startsWith(".colorizer-") && it.endsWith(".partial") } } private suspend fun readMetadata(titlePath: String, inventory: ScanInventory, itemType: DbItemType): LocalMetadata { val legacy = readLegacyMetadata(titlePath, inventory) val detailsPath = "${titlePath.trimEnd('/', '\\')}/details.json" val details = if (itemType == DbItemType.Anime && files.exists(detailsPath)) readMetadataFile(detailsPath, inventory, animetail = true) else null val metadata = if (details == null) legacy else LocalMetadata( name = details.name ?: legacy.name, description = details.description ?: legacy.description, author = details.author ?: legacy.author, artist = details.artist ?: legacy.artist, genres = details.genres ?: legacy.genres, status = details.status ?: legacy.status, imageUrl = legacy.imageUrl, customCoverFromTracker = legacy.customCoverFromTracker, language = legacy.language, cast = details.cast ?: legacy.cast, ) return if (metadata.cast == null) metadata else metadata.copy(cast = metadata.cast.map { credit -> credit.copy(imageUrl = resolveLocalImage(titlePath, credit.imageUrl, inventory)) }) } private suspend fun readMetadataFile(path: String, inventory: ScanInventory, animetail: Boolean = false): LocalMetadata? { val fingerprint = inventory.fingerprint(path) fingerprint?.let { metadataCache[it] }?.let { return it } val parsed = catchingNonCancellation { parseLocalMetadata(files.readBytesAsync(path, 64L * 1024).decodeToString(), animetail) }.getOrNull() if (parsed != null && fingerprint != null) metadataCache[fingerprint] = parsed return parsed } private suspend fun readLegacyMetadata(titlePath: String, inventory: ScanInventory): LocalMetadata { metadataCandidates(titlePath, inventory).forEach { path -> readMetadataFile(path, inventory)?.let { return it } } return LocalMetadata() } private fun metadataCandidates(titlePath: String, inventory: ScanInventory): List = buildList { add("${titlePath.trimEnd('/', '\\')}/metadata.json") inventory.entries(titlePath).orEmpty() .map { "${it.path.trimEnd('/', '\\')}/metadata.json" } .forEach(::add) }.filter { files.exists(it) } private suspend fun readCoverImage(titlePath: String, inventory: ScanInventory, excludedImages: Set = emptySet()): ByteArray? { val candidates = inventory.children(titlePath) .filter { it.path.isCoverImagePath() } val imageFiles = if (excludedImages.isEmpty()) candidates else candidates.filterNot { entry -> catchingNonCancellation { files.readableUrl(entry.path) }.getOrNull() in excludedImages } val selected = imageFiles.firstOrNull { it.name.substringBeforeLast('.').equals("cover", ignoreCase = true) } ?: imageFiles.singleOrNull() return selected?.let { entry -> if (entry.lastModified > 0L) coverCache[entry]?.let { return it } catchingNonCancellation { files.readBytesAsync(entry.path, 4L * 1024 * 1024) }.getOrNull()?.also { bytes -> if (entry.lastModified > 0L) coverCache[entry] = bytes } } } private fun LocalEntry.isTitleRootCover(titlePath: String): Boolean { val normalizedTitle = titlePath.replace('\\', '/').trimEnd('/') val normalizedPath = path.replace('\\', '/') val parent = normalizedPath.substringBeforeLast('/', "") return parent == normalizedTitle && normalizedPath.isCoverImagePath() } private fun String.isCoverImagePath(): Boolean { val lower = substringAfterLast('/').lowercase() return lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png") || lower.endsWith(".webp") || lower.endsWith(".gif") || lower.endsWith(".bmp") || lower.endsWith(".avif") } private fun inferItemType(root: String): DbItemType { val name = root.substringAfterLast('/').lowercase() return when { "anime" in name -> DbItemType.Anime "novel" in name -> DbItemType.Novel else -> DbItemType.Manga } } override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? { if (pathOrMagnet.isBlank()) return null val isMagnet = pathOrMagnet.startsWith("magnet:", ignoreCase = true) val extractedName = if (isMagnet) TorrentUtils.extractMagnetDisplayName(pathOrMagnet) else null val extractedHash = if (isMagnet) TorrentUtils.extractInfoHashFromMagnet(pathOrMagnet) else null val baseName = displayName?.takeIf { it.isNotBlank() } ?: extractedName?.takeIf { it.isNotBlank() } ?: if (isMagnet) { if (!extractedHash.isNullOrBlank()) "Torrent (${extractedHash.take(8)})" else "Torrent" } else { pathOrMagnet.substringAfterLast('/') .substringBefore('?') .removeSuffix(".torrent") .ifBlank { "Torrent" } } val now = nowMillis() val existing = database.mangas(DbItemType.Anime) .firstOrNull { it.isLocalArchive == true && it.source == "torrent" && (it.link == pathOrMagnet || (extractedHash != null && TorrentUtils.extractInfoHashFromMagnet(it.link.orEmpty()) == extractedHash)) } val savedManga = database.upsertManga( (existing ?: DbManga()).copy( name = baseName, source = "torrent", itemType = DbItemType.Anime, isLocalArchive = true, link = pathOrMagnet, lang = existing?.lang ?: "en", dateAdded = existing?.dateAdded ?: now, lastUpdate = now, favorite = existing?.favorite ?: true, ), ) val existingChapter = database.chapters(savedManga.id).firstOrNull { it.url == pathOrMagnet } database.upsertChapter( (existingChapter ?: DbChapter()).copy( mangaId = savedManga.id, name = baseName, url = pathOrMagnet, archivePath = if (isMagnet) "" else pathOrMagnet, dateUpload = (existingChapter?.dateUpload ?: now.toString()), fetchedAt = existingChapter?.fetchedAt ?: now, updatedAt = now, ), ) return savedManga.id } }