Yokan / rebuild
Course 1 8624561

LocalFolders.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/LocalFolders.kt

implementation163 lines
1package eu.friedcutlet.yokan.database23import eu.friedcutlet.yokan.domain.Manga45/**6 * Virtual-folder model for the local library.7 *8 * The original Flutter Mangayomi port stored each local-library root as a bare9 * filesystem path. That broke as soon as the user moved their library to a USB10 * drive or external disk that mounts at a different path on another machine,11 * because every [DbManga.link] and [DbChapter.archivePath] embedded the old12 * physical path.13 *14 * Virtual folders give each root a stable user-chosen *name* and a current15 * *path*. The scanner stores entity paths relative to the folder name16 * (e.g. `MyUSB/MangaTitle/Chapter1.cbz`), so when the user remounts the drive17 * elsewhere they only need to update the folder's path — every stored row keeps18 * working without rewrites.19 */2021/** The reserved name used for the app's built-in `<downloadRoot>/local` folder. */22const val DefaultLocalFolderName: String = "local"2324/**25 * Return the named folders the user has configured, migrating from the legacy26 * [DbSettings.localFolders] string list if [DbSettings.namedLocalFolders] is27 * still null (i.e. the user's persisted snapshot predates the rename).28 */29fun DbSettings.configuredLocalFolders(): List<DbLocalFolder> {30    namedLocalFolders?.let { return normalizeLocalFolders(it) }31    val legacy = localFolders ?: return emptyList()32    return normalizeLocalFolders(legacy.map { path -> DbLocalFolder(name = nameFromPath(path), path = path) })33}3435/**36 * Configured folders prepended with [defaultFolder]. Callers that want the37 * scanner to also walk the app's bundled `<downloadRoot>/local` directory pass38 * it in; callers that only want user-configured roots leave it null.39 */40fun DbSettings.effectiveLocalFolders(defaultFolder: DbLocalFolder?): List<DbLocalFolder> {41    val configured = configuredLocalFolders()42    if (defaultFolder == null) return configured43    return listOf(defaultFolder) + configured.filterNot { it.name == defaultFolder.name }44}4546/**47 * Resolve which configured folder downloads should be written to, given a48 * remembered name. Falls back to the first available folder so a stale name49 * (e.g. the folder was removed) cannot strand the downloader.50 */51fun resolveDownloadFolderName(name: String?, folders: List<DbLocalFolder>): String? {52    if (folders.isEmpty()) return null53    if (name != null && folders.any { it.name == name }) return name54    return folders.first().name55}5657/**58 * Build a virtual entity path under [folder]. The path is always returned with59 * forward slashes so it round-trips between platforms (Android, JVM, iOS).60 */61fun getLocalVirtualPath(folder: DbLocalFolder, entityPath: String): String {62    val folderName = folder.name.trim()63    val folderPath = folder.path64    if (folderName.isEmpty() || folderPath.isEmpty()) return normalizePath(entityPath)65    val relative = relativePath(folderPath, entityPath)66    if (relative.isEmpty() || relative == ".") return folderName67    return "$folderName/${normalizePath(relative)}"68}6970/**71 * Map a stored path (either an already-virtual `<name>/...` path, a current72 * physical path, or a legacy `Mangayomi/local/...` path) back to the canonical73 * virtual representation so scanner output is comparable across runs.74 */75fun localVirtualPathFromStoredPath(storedPath: String?, folders: List<DbLocalFolder>): String {76    if (storedPath.isNullOrBlank()) return ""77    val normalized = normalizePath(storedPath)78    val firstSegment = normalized.substringBefore('/', missingDelimiterValue = normalized)79    if (folders.any { it.name == firstSegment }) return normalized8081    for (folder in folders) {82        if (folder.path.isEmpty()) continue83        val normalizedFolderPath = normalizePath(folder.path)84        if (normalized == normalizedFolderPath || normalized.startsWith("$normalizedFolderPath/")) {85            return getLocalVirtualPath(folder, storedPath)86        }87    }8889    val legacyMarker = "Mangayomi/local"90    val legacyIndex = normalized.indexOf(legacyMarker)91    if (legacyIndex != -1) {92        val relative = normalized.substring(legacyIndex + legacyMarker.length).trimStart('/')93        return if (relative.isEmpty()) DefaultLocalFolderName else "$DefaultLocalFolderName/$relative"94    }95    return normalized96}9798/**99 * Resolve a virtual `<name>/<rest>` path back to the absolute physical path,100 * using the folder name to look up the current mount path. Returns the input101 * unchanged when no matching folder is configured (so callers can still attempt102 * a direct filesystem operation, e.g. when the stored path is still legacy).103 */104fun resolveLocalArchivePath(virtualPath: String, folders: List<DbLocalFolder>): String {105    if (virtualPath.isBlank()) return virtualPath106    val normalized = normalizePath(virtualPath)107    val firstSeparator = normalized.indexOf('/')108    val (name, rest) = if (firstSeparator < 0) normalized to "" else109        normalized.substring(0, firstSeparator) to normalized.substring(firstSeparator + 1)110    val folder = folders.firstOrNull { it.name == name } ?: return virtualPath111    if (folder.path.isEmpty()) return virtualPath112    val base = folder.path.trimEnd('/', '\\')113    return if (rest.isEmpty()) base else "$base/$rest"114}115116/**117 * Strip duplicates and assign collision-free names. The default folder name118 * (`local`) is reserved so the user-configured list can never shadow it.119 */120fun normalizeLocalFolders(folders: List<DbLocalFolder>): List<DbLocalFolder> {121    val used = mutableSetOf(DefaultLocalFolderName)122    val result = mutableListOf<DbLocalFolder>()123    for (folder in folders) {124        val path = folder.path.trim()125        if (path.isEmpty()) continue126        val rawName = folder.name.trim().ifEmpty { nameFromPath(path) }127        val name = uniqueLocalFolderName(rawName, used)128        used.add(name)129        result.add(DbLocalFolder(name = name, path = path))130    }131    return result132}133134internal fun uniqueLocalFolderName(value: String, used: Set<String>): String {135    val sanitized = value.replace('/', '_').replace('\\', '_').trim()136    val base = sanitized.ifEmpty { "Local" }137    // The reserved `local` name is exclusively for the bundled default folder.138    var candidate = if (base.equals(DefaultLocalFolderName, ignoreCase = true)) "Local" else base139    var index = 2140    while (used.contains(candidate)) {141        candidate = "$base $index"142        index++143    }144    return candidate145}146147internal fun nameFromPath(path: String): String {148    val parts = path.replace('\\', '/').split('/').filter { it.isNotBlank() }149    return if (parts.isEmpty()) "Local" else parts.last()150}151152internal fun normalizePath(path: String): String =153    path.replace('\\', '/').trimEnd('/')154155private fun relativePath(base: String, target: String): String {156    val normalizedBase = normalizePath(base)157    val normalizedTarget = normalizePath(target)158    if (normalizedTarget == normalizedBase) return ""159    if (normalizedTarget.startsWith("$normalizedBase/")) {160        return normalizedTarget.substring(normalizedBase.length + 1)161    }162    return normalizedTarget163}164

Search chapters, reference and source filenames.