Yokan / rebuild
Course 1 8624561

SourceCatalogService.kt

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

implementation106 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbSource5import eu.friedcutlet.yokan.database.DbSourceCodeLanguage6import eu.friedcutlet.yokan.services.catchingNonCancellation7import eu.friedcutlet.yokan.services.files.LocalFileService8import eu.friedcutlet.yokan.services.http.HttpRequest9import eu.friedcutlet.yokan.services.http.HttpService10import eu.friedcutlet.yokan.services.logging.AppLogger11import eu.friedcutlet.yokan.services.logging.redactUrlForLog12import kotlinx.serialization.json.Json13import kotlinx.serialization.json.JsonArray14import kotlinx.serialization.json.JsonObject1516interface SourceCatalogService {17    suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource>18    suspend fun validateRepository(repoUrl: String): Boolean19    suspend fun fetchSourcePayload(source: DbSource): ByteArray?20}2122/** Production catalog: fetches Mangayomi JSON and protobuf repository indexes over HTTP. */23class HttpSourceCatalogService(24    private val http: HttpService,25    private val files: LocalFileService? = null,26) : SourceCatalogService {27    private val json = Json {28        ignoreUnknownKeys = true29        isLenient = true30    }3132    override suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource> =33        if (repoUrl.isProtobufRepository()) {34            catchingNonCancellation { protobufSources(repoUrl) }35                .onFailure { AppLogger.warn("[extensions] repository ${redactUrlForLog(repoUrl)} could not be read: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }36                .getOrDefault(emptyList())37        } else {38            catalogEntries(repoUrl)39                .flatMap { entry -> catalogEntrySources(repoUrl, entry) }40        }.filter { source -> source.itemType == itemType }4142    override suspend fun validateRepository(repoUrl: String): Boolean =43        catchingNonCancellation {44            if (repoUrl.isProtobufRepository()) protobufSources(repoUrl).isNotEmpty()45            else catalogEntries(repoUrl).isNotEmpty()46        }.onFailure { AppLogger.warn("[extensions] validating repository ${redactUrlForLog(repoUrl)} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }47            .getOrDefault(false)4849    override suspend fun fetchSourcePayload(source: DbSource): ByteArray? {50        val url = source.sourceCodeUrl.takeIf { it.isNotBlank() } ?: return null51        if (url.startsWith("file://")) {52            val repositoryUrl = source.repo?.jsonUrl?.takeIf { it.startsWith("file://") } ?: return null53            val localFiles = files ?: return null54            if (!localFiles.exists(url)) return null55            val repositoryPath = localFiles.canonicalPath(repositoryDirectoryUrl(repositoryUrl)) ?: return null56            val sourcePath = localFiles.canonicalPath(url) ?: return null57            if (!isPathWithin(repositoryPath, sourcePath)) return null58        }59        val bytes = resourceBytes(url)?.takeIf { it.isNotEmpty() } ?: return null60        if (source.sourceCodeLanguage != DbSourceCodeLanguage.Mihon &&61            source.sourceCodeLanguage != DbSourceCodeLanguage.Aidoku &&62            bytes.decodeToString().isBlank()63        ) return null64        return bytes65    }6667    private suspend fun catalogEntries(repoUrl: String): List<JsonObject> {68        if (!repoUrl.startsWith("http") && !repoUrl.startsWith("file://")) return emptyList()69        val bytes = resourceBytes(repoUrl)70            ?: throw IllegalStateException("Repository could not be read: $repoUrl")71        val root = json.parseToJsonElement(bytes.decodeToString())72        val entries = when (root) {73            is JsonArray -> root74            is JsonObject -> root.array("sources") ?: root.array("extensions") ?: root.array("data") ?: JsonArray(listOf(root))75            else -> JsonArray(emptyList())76        }77        return entries.mapNotNull { it as? JsonObject }78    }7980    private suspend fun protobufSources(repoUrl: String): List<DbSource> {81        if (!repoUrl.startsWith("http") && !repoUrl.startsWith("file://")) return emptyList()82        val compressed = resourceBytes(repoUrl)83            ?: throw IllegalStateException("Repository could not be read: $repoUrl")84        return mihonProtobufSources(repoUrl, ProtobufReader(gzipDecompress(compressed)).readExtensions())85    }8687    private fun String.isProtobufRepository(): Boolean =88        substringBefore('#').substringBefore('?').endsWith(".pb", ignoreCase = true)8990    private suspend fun resourceBytes(url: String): ByteArray? {91        if (url.startsWith("file://")) {92            val localFiles = files ?: return null93            if (!localFiles.exists(url)) return null94            return localFiles.readBytes(url)95        }96        val response = http.request(HttpRequest(url = url))97        if (response.statusCode !in 200..299) return null98        return response.bodyBytes.takeIf { it.isNotEmpty() } ?: response.body.encodeToByteArray()99    }100101    private fun isPathWithin(root: String, candidate: String): Boolean {102        val normalizedRoot = root.replace('\\', '/').trimEnd('/')103        val normalizedCandidate = candidate.replace('\\', '/').trimEnd('/')104        return normalizedCandidate == normalizedRoot || normalizedCandidate.startsWith("$normalizedRoot/")105    }106}107

Search chapters, reference and source filenames.