Yokan / rebuild
Course 1 8624561

HubServers.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubServers.kt

implementation42 lines
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.services.http.HttpRequest5import eu.friedcutlet.yokan.services.http.HttpService6import eu.friedcutlet.yokan.services.http.normalizeHubServer7import eu.friedcutlet.yokan.services.logging.AppLogger8import kotlinx.serialization.Serializable9import kotlinx.serialization.json.Json1011/** The maintained list of public yokan-hub servers, published with the app's releases. */12const val HubServerListUrl = "https://raw.githubusercontent.com/Schnitzel5/yokan/main/servers.json"1314@Serializable15data class HubServerEntry(val name: String, val url: String, val description: String = "")1617@Serializable18private data class HubServerList(val version: Int = 1, val servers: List<HubServerEntry> = emptyList())1920private val hubServerJson = Json { ignoreUnknownKeys = true }2122/** Predefined servers with normalized URLs; empty (and logged) when the list is unreachable or malformed. */23suspend fun fetchHubServers(http: HttpService, url: String = HubServerListUrl): List<HubServerEntry> {24    val response = catchingNonCancellation { http.request(HttpRequest(url)) }.getOrElse {25        AppLogger.warn("[sync] hub server list unavailable: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}")26        return emptyList()27    }28    if (response.statusCode !in 200..299) {29        AppLogger.warn("[sync] hub server list returned HTTP ${response.statusCode}")30        return emptyList()31    }32    val list = runCatching { hubServerJson.decodeFromString(HubServerList.serializer(), response.body) }.getOrElse {33        AppLogger.warn("[sync] hub server list is malformed: ${it.message?.lineSequence()?.firstOrNull()}")34        return emptyList()35    }36    return list.servers37        .mapNotNull { entry -> normalizeHubServer(entry.url)?.let { entry.copy(name = entry.name.trim().ifBlank { it }, url = it) } }38        .distinctBy { it.url }39        .take(MaxHubServers)40}4142private const val MaxHubServers = 5043

Search chapters, reference and source filenames.