package eu.friedcutlet.yokan.database import eu.friedcutlet.yokan.domain.Manga /** * Virtual-folder model for the local library. * * The original Flutter Mangayomi port stored each local-library root as a bare * filesystem path. That broke as soon as the user moved their library to a USB * drive or external disk that mounts at a different path on another machine, * because every [DbManga.link] and [DbChapter.archivePath] embedded the old * physical path. * * Virtual folders give each root a stable user-chosen *name* and a current * *path*. The scanner stores entity paths relative to the folder name * (e.g. `MyUSB/MangaTitle/Chapter1.cbz`), so when the user remounts the drive * elsewhere they only need to update the folder's path — every stored row keeps * working without rewrites. */ /** The reserved name used for the app's built-in `/local` folder. */ const val DefaultLocalFolderName: String = "local" /** * Return the named folders the user has configured, migrating from the legacy * [DbSettings.localFolders] string list if [DbSettings.namedLocalFolders] is * still null (i.e. the user's persisted snapshot predates the rename). */ fun DbSettings.configuredLocalFolders(): List { namedLocalFolders?.let { return normalizeLocalFolders(it) } val legacy = localFolders ?: return emptyList() return normalizeLocalFolders(legacy.map { path -> DbLocalFolder(name = nameFromPath(path), path = path) }) } /** * Configured folders prepended with [defaultFolder]. Callers that want the * scanner to also walk the app's bundled `/local` directory pass * it in; callers that only want user-configured roots leave it null. */ fun DbSettings.effectiveLocalFolders(defaultFolder: DbLocalFolder?): List { val configured = configuredLocalFolders() if (defaultFolder == null) return configured return listOf(defaultFolder) + configured.filterNot { it.name == defaultFolder.name } } /** * Resolve which configured folder downloads should be written to, given a * remembered name. Falls back to the first available folder so a stale name * (e.g. the folder was removed) cannot strand the downloader. */ fun resolveDownloadFolderName(name: String?, folders: List): String? { if (folders.isEmpty()) return null if (name != null && folders.any { it.name == name }) return name return folders.first().name } /** * Build a virtual entity path under [folder]. The path is always returned with * forward slashes so it round-trips between platforms (Android, JVM, iOS). */ fun getLocalVirtualPath(folder: DbLocalFolder, entityPath: String): String { val folderName = folder.name.trim() val folderPath = folder.path if (folderName.isEmpty() || folderPath.isEmpty()) return normalizePath(entityPath) val relative = relativePath(folderPath, entityPath) if (relative.isEmpty() || relative == ".") return folderName return "$folderName/${normalizePath(relative)}" } /** * Map a stored path (either an already-virtual `/...` path, a current * physical path, or a legacy `Mangayomi/local/...` path) back to the canonical * virtual representation so scanner output is comparable across runs. */ fun localVirtualPathFromStoredPath(storedPath: String?, folders: List): String { if (storedPath.isNullOrBlank()) return "" val normalized = normalizePath(storedPath) val firstSegment = normalized.substringBefore('/', missingDelimiterValue = normalized) if (folders.any { it.name == firstSegment }) return normalized for (folder in folders) { if (folder.path.isEmpty()) continue val normalizedFolderPath = normalizePath(folder.path) if (normalized == normalizedFolderPath || normalized.startsWith("$normalizedFolderPath/")) { return getLocalVirtualPath(folder, storedPath) } } val legacyMarker = "Mangayomi/local" val legacyIndex = normalized.indexOf(legacyMarker) if (legacyIndex != -1) { val relative = normalized.substring(legacyIndex + legacyMarker.length).trimStart('/') return if (relative.isEmpty()) DefaultLocalFolderName else "$DefaultLocalFolderName/$relative" } return normalized } /** * Resolve a virtual `/` path back to the absolute physical path, * using the folder name to look up the current mount path. Returns the input * unchanged when no matching folder is configured (so callers can still attempt * a direct filesystem operation, e.g. when the stored path is still legacy). */ fun resolveLocalArchivePath(virtualPath: String, folders: List): String { if (virtualPath.isBlank()) return virtualPath val normalized = normalizePath(virtualPath) val firstSeparator = normalized.indexOf('/') val (name, rest) = if (firstSeparator < 0) normalized to "" else normalized.substring(0, firstSeparator) to normalized.substring(firstSeparator + 1) val folder = folders.firstOrNull { it.name == name } ?: return virtualPath if (folder.path.isEmpty()) return virtualPath val base = folder.path.trimEnd('/', '\\') return if (rest.isEmpty()) base else "$base/$rest" } /** * Strip duplicates and assign collision-free names. The default folder name * (`local`) is reserved so the user-configured list can never shadow it. */ fun normalizeLocalFolders(folders: List): List { val used = mutableSetOf(DefaultLocalFolderName) val result = mutableListOf() for (folder in folders) { val path = folder.path.trim() if (path.isEmpty()) continue val rawName = folder.name.trim().ifEmpty { nameFromPath(path) } val name = uniqueLocalFolderName(rawName, used) used.add(name) result.add(DbLocalFolder(name = name, path = path)) } return result } internal fun uniqueLocalFolderName(value: String, used: Set): String { val sanitized = value.replace('/', '_').replace('\\', '_').trim() val base = sanitized.ifEmpty { "Local" } // The reserved `local` name is exclusively for the bundled default folder. var candidate = if (base.equals(DefaultLocalFolderName, ignoreCase = true)) "Local" else base var index = 2 while (used.contains(candidate)) { candidate = "$base $index" index++ } return candidate } internal fun nameFromPath(path: String): String { val parts = path.replace('\\', '/').split('/').filter { it.isNotBlank() } return if (parts.isEmpty()) "Local" else parts.last() } internal fun normalizePath(path: String): String = path.replace('\\', '/').trimEnd('/') private fun relativePath(base: String, target: String): String { val normalizedBase = normalizePath(base) val normalizedTarget = normalizePath(target) if (normalizedTarget == normalizedBase) return "" if (normalizedTarget.startsWith("$normalizedBase/")) { return normalizedTarget.substring(normalizedBase.length + 1) } return normalizedTarget }