package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.database.DbRepo /** * Repository URL normalization and deduplication logic based on upstream Mangayomi (commit f9e04d51). */ object SourceRepositoryUrls { /** * Normalizes a repository URL for consistent storage and matching: * - Trims whitespace * - Strips redundant trailing slashes */ fun normalizeUrl(url: String?): String { if (url.isNullOrBlank()) return "" return url.trim().trimEnd('/') } /** * Checks if two repository URLs refer to the same repository (case-insensitive, trailing slash insensitive, * and handles equivalent /index.json vs directory path). */ fun areUrlsEquivalent(url1: String?, url2: String?): Boolean { val n1 = normalizeUrl(url1).lowercase() val n2 = normalizeUrl(url2).lowercase() if (n1.isEmpty() || n2.isEmpty()) return false if (n1 == n2) return true val stripped1 = n1.removeIndexFilename() val stripped2 = n2.removeIndexFilename() return stripped1 == stripped2 } /** * Checks whether [inputUrl] already exists in [existingRepos]. */ fun isDuplicate(inputUrl: String?, existingRepos: List): Boolean { if (inputUrl.isNullOrBlank()) return false return existingRepos.any { existing -> areUrlsEquivalent(inputUrl, existing.jsonUrl) } } /** * Deduplicates a list of [DbRepo] preserving the first occurrence. */ fun deduplicate(repos: List): List { val seen = mutableSetOf() val result = mutableListOf() for (repo in repos) { val key = normalizeUrl(repo.jsonUrl).lowercase() if (key.isNotEmpty()) { val stripped = key.removeIndexFilename() if (seen.add(stripped)) { result.add(repo) } } else { result.add(repo) } } return result } /** * Infers a sensible repository display name from URL when name is missing, empty, * or a generic filename like 'index.json'. */ fun resolveDisplayName(name: String?, url: String?, defaultPrefix: String = "Repository"): String { val trimmedName = name?.trim().orEmpty() if (trimmedName.isNotEmpty() && !trimmedName.endsWith(".json", ignoreCase = true) && !trimmedName.endsWith(".pb", ignoreCase = true) ) { return trimmedName } val trimmedUrl = url?.trim().orEmpty() if (trimmedUrl.isNotEmpty()) { val cleaned = trimmedUrl.replace(Regex("""/[^/]+\.(json|pb)$""", RegexOption.IGNORE_CASE), "") val lastSegment = cleaned.split('/').filter { it.isNotEmpty() }.lastOrNull() if (!lastSegment.isNullOrBlank() && !lastSegment.contains("://")) { return lastSegment } } return if (trimmedName.isNotEmpty()) trimmedName else defaultPrefix } private fun String.removeIndexFilename(): String = removeSuffix("/index.json").removeSuffix("/index.min.json").removeSuffix("/index.pb") }