Yokan / rebuild
Course 1 8624561

CatalogEntryMappers.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/CatalogEntryMappers.kt

implementation387 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbRepo5import eu.friedcutlet.yokan.database.DbSource6import eu.friedcutlet.yokan.database.DbSourceCodeLanguage7import eu.friedcutlet.yokan.services.extensions.js.string8import kotlinx.serialization.json.JsonArray9import kotlinx.serialization.json.JsonObject10import kotlinx.serialization.json.JsonPrimitive11import kotlinx.serialization.json.booleanOrNull12import kotlinx.serialization.json.contentOrNull13import kotlinx.serialization.json.intOrNull14import kotlinx.serialization.json.longOrNull1516private val AbsoluteUriPattern = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")1718/** Maps one JSON catalog entry (Mihon, LNReader, Aidoku or Mangayomi format) to its sources. */19internal fun catalogEntrySources(repoUrl: String, entry: JsonObject): List<DbSource> =20    when {21        entry.isMihonEntry() -> mihonSources(repoUrl, entry)22        entry.isLnReaderEntry() -> listOf(lnReaderSource(entry))23        entry.isAidokuEntry() -> aidokuSources(repoUrl, entry)24        else -> listOfNotNull(genericSource(repoUrl, entry))25    }2627/** Maps the extensions of a Mihon protobuf repository index to their sources. */28internal fun mihonProtobufSources(repoUrl: String, extensions: List<PbExtension>): List<DbSource> =29    extensions.flatMap { extension ->30        val version = extension.versionName.ifBlank {31            extension.versionCode?.toString().orEmpty().ifBlank { "0.0.1" }32        }33        val fallbackIcon = extension.packageName.takeIf { it.isNotBlank() }34            ?.let { resolveRepositoryUrl(repoUrl, "icon/$it.png") }35            .orEmpty()36        extension.sources.map { source ->37            val payload = extension.resources.apkUrl.takeIf { it.isNotBlank() }38                ?: extension.resources.jarUrl39            val icon = extension.resources.iconUrl.takeIf { it.isNotBlank() } ?: fallbackIcon40            DbSource(41                id = source.id ?: stableHashId("mihon-${source.name}-${source.language}"),42                name = source.name.ifBlank { extension.name },43                baseUrl = source.homeUrl,44                lang = source.language,45                isActive = true,46                isAdded = false,47                isPinned = false,48                isNsfw = extension.contentWarning == 3,49                sourceCodeUrl = resolveRepositoryUrl(repoUrl, payload),50                additionalParams = source.id?.toString()?.let {51                    JsonObject(mapOf("sourceId" to JsonPrimitive(it))).toString()52                }.orEmpty(),53                iconUrl = resolveRepositoryUrl(repoUrl, icon),54                version = version,55                versionLast = version,56                itemType = DbItemType.Manga,57                isLocal = false,58                isObsolete = false,59                sourceCodeLanguage = DbSourceCodeLanguage.Mihon,60                notes = "Requires ApkBridge for installing and running Mihon extensions.",61                repo = repoFromUrl(repoUrl),62            )63        }64    }6566/** A positive id derived from [value], stable for the same catalog entry. */67internal fun stableHashId(value: String): Long {68    val hash = value.hashCode().toLong()69    return when {70        hash < 0 -> -hash71        hash > 0 -> hash72        else -> 1L73    }74}7576internal fun JsonObject.array(key: String): JsonArray? = this[key] as? JsonArray7778internal fun repositoryDirectoryUrl(repoUrl: String): String {79    val clean = repoUrl.substringBefore('#').substringBefore('?')80    val schemeEnd = clean.indexOf("://")81    if (schemeEnd < 0) return clean.substringBeforeLast('/', missingDelimiterValue = clean).trimEnd('/') + "/"82    val pathStart = clean.indexOf('/', startIndex = schemeEnd + 3)83    if (pathStart < 0) return "$clean/"84    if (clean.endsWith('/')) return clean85    return clean.substringBeforeLast('/') + "/"86}8788private fun mihonSources(repoUrl: String, entry: JsonObject): List<DbSource> {89    val packageName = entry.string("pkg").orEmpty()90    val extensionVersion = entry.versionString()91    val itemType = if (packageName.startsWith("eu.kanade.tachiyomi.animeextension")) DbItemType.Anime else DbItemType.Manga92    val apkName = entry.string("apk").orEmpty()93    val iconUrl = packageName.takeIf { it.isNotBlank() }?.let { resolveRepositoryUrl(repoUrl, "icon/$it.png") }.orEmpty()94    val sourceCodeUrl = apkName.takeIf { it.isNotBlank() }?.let { resolveRepositoryUrl(repoUrl, "apk/$it") }.orEmpty()95    return entry.array("sources").orEmpty()96        .mapNotNull { it as? JsonObject }97        .map { source ->98            DbSource(99                id = stableHashId("mihon-${source.string("id") ?: source.string("name").orEmpty()}"),100                name = source.string("name") ?: entry.string("name").orEmpty(),101                baseUrl = source.string("baseUrl").orEmpty(),102                lang = source.string("lang") ?: entry.string("lang").orEmpty(),103                isActive = true,104                isAdded = false,105                isPinned = false,106                isNsfw = entry.booleanValue("nsfw") ?: false,107                sourceCodeUrl = sourceCodeUrl,108                additionalParams = source.string("id")109                    ?.let { JsonObject(mapOf("sourceId" to JsonPrimitive(it))).toString() }110                    .orEmpty(),111                iconUrl = iconUrl,112                version = extensionVersion,113                versionLast = extensionVersion,114                itemType = itemType,115                appMinVerReq = entry.string("appMinVerReq", "minAppVersion", "minExtVersion").orEmpty(),116                isLocal = false,117                isObsolete = false,118                sourceCodeLanguage = DbSourceCodeLanguage.Mihon,119                notes = "Requires ApkBridge for installing and running Mihon extensions.",120                repo = repoFromUrl(repoUrl),121            )122        }123}124125private fun lnReaderSource(entry: JsonObject): DbSource {126    val lang = normalizeLnReaderLanguage(entry.string("lang"))127    val version = entry.versionString()128    return DbSource(129        id = stableHashId("lnreader-plugin-\"${entry.string("name").orEmpty()}\".\"$lang\""),130        name = entry.string("name").orEmpty(),131        baseUrl = entry.string("site").orEmpty(),132        lang = lang,133        isActive = true,134        isAdded = false,135        isPinned = false,136        isNsfw = false,137        sourceCodeUrl = entry.string("url").orEmpty(),138        iconUrl = entry.string("iconUrl").orEmpty(),139        version = version,140        versionLast = version,141        itemType = DbItemType.Novel,142        sourceCodeLanguage = DbSourceCodeLanguage.LnReader,143        notes = "Performance may be limited by the shared JavaScript runtime.",144    )145}146147private fun genericSource(repoUrl: String, entry: JsonObject): DbSource? {148    val name = entry.string("name") ?: return null149    val itemType = entry.itemTypeValue() ?: DbItemType.Manga150    val version = entry.versionString()151    val unsupportedDartSource = entry.isUnsupportedDartSource()152    val sourceCodeUrl = resolveRepositoryUrl(repoUrl, entry.string("sourceCodeUrl"))153    val notes = entry.string("notes").orEmpty().ifBlank {154        if (unsupportedDartSource) "Dart source metadata imported; execution is unsupported in the KMP port." else ""155    }156    return DbSource(157        id = entry.longValue("id") ?: stableHashId("$sourceCodeUrl-$name-${entry.string("lang").orEmpty()}"),158        name = name,159        baseUrl = entry.string("baseUrl").orEmpty(),160        lang = entry.string("lang").orEmpty(),161        isActive = if (unsupportedDartSource) false else entry.booleanValue("isActive") ?: true,162        isAdded = entry.booleanValue("isAdded") ?: false,163        isPinned = entry.booleanValue("isPinned") ?: false,164        isNsfw = entry.booleanValue("isNsfw") ?: false,165        sourceCode = entry.string("sourceCode").orEmpty(),166        sourceCodeUrl = sourceCodeUrl,167        typeSource = entry.string("typeSource").orEmpty(),168        iconUrl = resolveRepositoryUrl(repoUrl, entry.string("iconUrl")),169        isFullData = entry.booleanValue("isFullData") ?: false,170        hasCloudflare = entry.booleanValue("hasCloudflare") ?: false,171        lastUsed = entry.booleanValue("lastUsed") ?: false,172        dateFormat = entry.string("dateFormat").orEmpty(),173        dateFormatLocale = entry.string("dateFormatLocale").orEmpty(),174        apiUrl = entry.string("apiUrl").orEmpty(),175        version = version,176        versionLast = entry.string("versionLast") ?: version,177        headers = entry.string("headers").orEmpty(),178        supportLatest = entry.booleanValue("supportLatest"),179        filterList = entry.string("filterList"),180        preferenceList = entry.string("preferenceList"),181        itemType = itemType,182        appMinVerReq = entry.string("appMinVerReq").orEmpty(),183        additionalParams = entry.string("additionalParams").orEmpty(),184        isLocal = entry.booleanValue("isLocal") ?: false,185        isObsolete = entry.booleanValue("isObsolete") ?: false,186        sourceCodeLanguage = entry.sourceCodeLanguageValue(),187        notes = notes,188        repo = entry.obj("repo")?.toRepo() ?: repoFromUrl(repoUrl),189        updatedAt = entry.longValue("updatedAt") ?: 0L,190    )191}192193private fun JsonObject.isMihonEntry(): Boolean {194    // Explicit `sourceCodeLanguage` declaration overrides shape detection.195    // Mangayomi-format catalogs sometimes ship JavaScript entries that coincidentally carry196    // `pkg`/`apk` fields left over from Mihon metadata. Without this check those entries get197    // classified as Mihon and every call is incorrectly routed through ApkBridge.198    val declared = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull?.lowercase()199    if (declared != null && declared !in setOf("2", "mihon")) return false200    return string("name") != null &&201        string("pkg") != null &&202        string("version", "code") != null &&203        string("lang") != null &&204        this["nsfw"] != null &&205        array("sources") != null &&206        string("apk") != null207}208209private fun JsonObject.isLnReaderEntry(): Boolean =210    string("id") != null &&211        string("name") != null &&212        string("site") != null &&213        string("lang") != null &&214        string("version") != null &&215        string("url") != null &&216        string("iconUrl") != null217218private fun JsonObject.isAidokuEntry(): Boolean {219    val declared = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull?.lowercase()220    if (declared in setOf("4", "aidoku")) return true221    val file = string("file", "downloadURL", "downloadUrl", "sourceCodeUrl").orEmpty().lowercase()222    return file.endsWith(".aidx") || file.endsWith(".aix")223}224225private fun aidokuSources(repoUrl: String, entry: JsonObject): List<DbSource> {226    val id = entry.string("id") ?: entry.string("name").orEmpty()227    val name = entry.string("name") ?: id228    val rawDownload = entry.string("downloadURL", "downloadUrl", "file", "sourceCodeUrl").orEmpty()229    val downloadUrl = if (rawDownload.isNotBlank()) resolveRepositoryUrl(repoUrl, rawDownload) else ""230    val rawIcon = entry.string("iconURL", "iconUrl", "icon").orEmpty()231    val iconUrl = if (rawIcon.isNotBlank()) {232        resolveRepositoryUrl(repoUrl, rawIcon)233    } else if (id.isNotBlank()) {234        resolveRepositoryUrl(repoUrl, "icons/$id.png")235    } else ""236    val langs = entry.array("languages")?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }237        ?: listOf(entry.string("lang") ?: "all")238    val rating = (entry["contentRating"] as? JsonPrimitive)?.intOrNull ?: if (entry.booleanValue("nsfw") == true) 2 else 0239    val isNsfw = rating >= 2240    val baseUrl = entry.string("baseURL", "baseUrl", "url").orEmpty()241    val version = entry.string("version") ?: "1.0.0"242243    return langs.map { lang ->244        DbSource(245            id = stableHashId("aidoku-$id-$lang"),246            name = name,247            baseUrl = baseUrl,248            lang = lang,249            isActive = true,250            isAdded = false,251            isPinned = false,252            isNsfw = isNsfw,253            sourceCodeUrl = downloadUrl,254            iconUrl = iconUrl,255            version = if (version.contains('.')) version else "$version.0.0",256            versionLast = "0.0.1",257            itemType = DbItemType.Manga,258            sourceCodeLanguage = DbSourceCodeLanguage.Aidoku,259            notes = "Aidoku WASM extension package",260            repo = repoFromUrl(repoUrl),261        )262    }263}264265private fun JsonObject.versionString(): String =266    string("version", "versionName", "code", "versionCode").orEmpty().ifBlank { "0.0.1" }267268private fun JsonObject.itemTypeValue(): DbItemType? {269    val primitive = this["itemType"] as? JsonPrimitive ?: this["isManga"] as? JsonPrimitive270    val raw = primitive?.contentOrNull ?: return null271    return when (raw.lowercase()) {272        "0", "manga", "true" -> DbItemType.Manga273        "1", "anime" -> DbItemType.Anime274        "2", "novel", "false" -> DbItemType.Novel275        else -> null276    }277}278279private fun JsonObject.sourceCodeLanguageValue(): DbSourceCodeLanguage {280    val raw = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull281    return when (raw?.lowercase()) {282        "2", "mihon" -> DbSourceCodeLanguage.Mihon283        "3", "lnreader", "ln_reader", "ln-reader" -> DbSourceCodeLanguage.LnReader284        "4", "aidoku" -> DbSourceCodeLanguage.Aidoku285        else -> {286            val file = string("file", "downloadURL", "downloadUrl", "sourceCodeUrl").orEmpty().lowercase()287            if (file.endsWith(".aidx") || file.endsWith(".aix")) {288                DbSourceCodeLanguage.Aidoku289            } else {290                DbSourceCodeLanguage.JavaScript291            }292        }293    }294}295296private fun JsonObject.isUnsupportedDartSource(): Boolean {297    val raw = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull?.lowercase()298    return raw == "0" || raw == "dart" || string("sourceCodeUrl").orEmpty().endsWith(".dart")299}300301private fun JsonObject.toRepo(): DbRepo =302    DbRepo(303        name = string("name"),304        website = string("website"),305        jsonUrl = string("jsonUrl"),306        hidden = booleanValue("hidden"),307    )308309private fun repoFromUrl(repoUrl: String): DbRepo {310    val website = repositoryDirectoryUrl(repoUrl).trimEnd('/')311    return DbRepo(312        name = website.substringAfterLast('/').ifBlank { "Repository" },313        website = website,314        jsonUrl = repoUrl,315    )316}317318private fun JsonObject.booleanValue(key: String): Boolean? {319    val primitive = this[key] as? JsonPrimitive ?: return null320    return primitive.booleanOrNull321        ?: primitive.intOrNull?.let { it != 0 }322        ?: primitive.contentOrNull?.toBooleanStrictOrNull()323        ?: primitive.contentOrNull?.toIntOrNull()?.let { it != 0 }324}325326private fun JsonObject.longValue(key: String): Long? {327    val primitive = this[key] as? JsonPrimitive ?: return null328    return primitive.longOrNull ?: primitive.contentOrNull?.toLongOrNull()329}330331private fun JsonObject.obj(key: String): JsonObject? = this[key] as? JsonObject332333private fun resolveRepositoryUrl(repoUrl: String, value: String?): String {334    val reference = value?.trim().orEmpty()335    if (reference.isBlank() || AbsoluteUriPattern.containsMatchIn(reference)) return reference336    if (reference.startsWith("//")) {337        val scheme = repoUrl.substringBefore("://", missingDelimiterValue = "https")338        return "$scheme:$reference"339    }340341    val suffixIndex = listOf(reference.indexOf('?'), reference.indexOf('#'))342        .filter { it >= 0 }343        .minOrNull()344        ?: reference.length345    val referencePath = reference.substring(0, suffixIndex)346    val suffix = reference.substring(suffixIndex)347    val cleanBase = repoUrl.substringBefore('#').substringBefore('?')348    if (referencePath.isEmpty()) return "$cleanBase$suffix"349350    val schemeEnd = cleanBase.indexOf("://")351    if (schemeEnd < 0) return reference352    val pathStart = cleanBase.indexOf('/', startIndex = schemeEnd + 3)353    val origin = if (pathStart >= 0) cleanBase.substring(0, pathStart) else cleanBase354    val basePath = if (pathStart >= 0) cleanBase.substring(pathStart) else "/"355    val combinedPath = if (referencePath.startsWith('/')) {356        referencePath357    } else {358        val directory = if (basePath.endsWith('/')) basePath else basePath.substringBeforeLast('/') + "/"359        directory + referencePath360    }361    return origin + normalizeUrlPath(combinedPath) + suffix362}363364private fun normalizeUrlPath(path: String): String {365    val segments = mutableListOf<String>()366    path.split('/').forEach { segment ->367        when (segment) {368            "", "." -> Unit369            ".." -> if (segments.isNotEmpty()) segments.removeAt(segments.lastIndex)370            else -> segments += segment371        }372    }373    val trailingSlash = path.endsWith('/') && segments.isNotEmpty()374    return "/" + segments.joinToString("/") + if (trailingSlash) "/" else ""375}376377private fun normalizeLnReaderLanguage(lang: String?): String = when (lang) {378    "English" -> "en"379    "Bahasa Indonesia" -> "id"380    "Polski" -> "pl"381    "Russian" -> "ru"382    "Spanish" -> "es"383    "Thai" -> "th"384    "Turkish" -> "tr"385    "Vietnamese" -> "vi"386    else -> lang?.takeIf { it.length in 2..3 } ?: "all"387}388

Search chapters, reference and source filenames.