SourceRepositoryUrls.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceRepositoryUrls.kt
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbRepo45/**6 * Repository URL normalization and deduplication logic based on upstream Mangayomi (commit f9e04d51).7 */8object SourceRepositoryUrls {910 /**11 * Normalizes a repository URL for consistent storage and matching:12 * - Trims whitespace13 * - Strips redundant trailing slashes14 */15 fun normalizeUrl(url: String?): String {16 if (url.isNullOrBlank()) return ""17 return url.trim().trimEnd('/')18 }1920 /**21 * Checks if two repository URLs refer to the same repository (case-insensitive, trailing slash insensitive,22 * and handles equivalent /index.json vs directory path).23 */24 fun areUrlsEquivalent(url1: String?, url2: String?): Boolean {25 val n1 = normalizeUrl(url1).lowercase()26 val n2 = normalizeUrl(url2).lowercase()27 if (n1.isEmpty() || n2.isEmpty()) return false28 if (n1 == n2) return true2930 val stripped1 = n1.removeIndexFilename()31 val stripped2 = n2.removeIndexFilename()32 return stripped1 == stripped233 }3435 /**36 * Checks whether [inputUrl] already exists in [existingRepos].37 */38 fun isDuplicate(inputUrl: String?, existingRepos: List<DbRepo>): Boolean {39 if (inputUrl.isNullOrBlank()) return false40 return existingRepos.any { existing -> areUrlsEquivalent(inputUrl, existing.jsonUrl) }41 }4243 /**44 * Deduplicates a list of [DbRepo] preserving the first occurrence.45 */46 fun deduplicate(repos: List<DbRepo>): List<DbRepo> {47 val seen = mutableSetOf<String>()48 val result = mutableListOf<DbRepo>()49 for (repo in repos) {50 val key = normalizeUrl(repo.jsonUrl).lowercase()51 if (key.isNotEmpty()) {52 val stripped = key.removeIndexFilename()53 if (seen.add(stripped)) {54 result.add(repo)55 }56 } else {57 result.add(repo)58 }59 }60 return result61 }6263 /**64 * Infers a sensible repository display name from URL when name is missing, empty,65 * or a generic filename like 'index.json'.66 */67 fun resolveDisplayName(name: String?, url: String?, defaultPrefix: String = "Repository"): String {68 val trimmedName = name?.trim().orEmpty()69 if (trimmedName.isNotEmpty() && !trimmedName.endsWith(".json", ignoreCase = true) &&70 !trimmedName.endsWith(".pb", ignoreCase = true)71 ) {72 return trimmedName73 }74 val trimmedUrl = url?.trim().orEmpty()75 if (trimmedUrl.isNotEmpty()) {76 val cleaned = trimmedUrl.replace(Regex("""/[^/]+\.(json|pb)$""", RegexOption.IGNORE_CASE), "")77 val lastSegment = cleaned.split('/').filter { it.isNotEmpty() }.lastOrNull()78 if (!lastSegment.isNullOrBlank() && !lastSegment.contains("://")) {79 return lastSegment80 }81 }82 return if (trimmedName.isNotEmpty()) trimmedName else defaultPrefix83 }8485 private fun String.removeIndexFilename(): String =86 removeSuffix("/index.json").removeSuffix("/index.min.json").removeSuffix("/index.pb")87}88