ref: 459b6294c1a664dfb1350d50e88013f5852028da
app/src/main/java/ml/adamsprogs/bimba/api/Api.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
package ml.adamsprogs.bimba.api import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.net.URLEncoder data class Server(val host: String, val token: String, val feeds: String) @Suppress("BlockingMethodInNonBlockingContext") suspend fun getFeeds(server: Server): InputStream? { // todo(error-handling) if 401 then needs token return rawRequest(URL("${hostWithScheme(server.host)}/api/"), server) } suspend fun queryItems(server: Server, query: String, limit: Int? = null): InputStream? { val params = mutableMapOf("q" to query) if (limit != null) { params["limit"] = limit.toString() } return request(server, "items", params) } suspend fun locateItems(server: Server, plusCode: String): InputStream? { return request(server, "items", mapOf("near" to plusCode)) } suspend fun getDepartures(server: Server, stop: String, line: String?): InputStream? { val params = mutableMapOf("code" to stop) if (line != null) { params["line"] = line } return request(server, "departures", params) } @Suppress("BlockingMethodInNonBlockingContext") suspend fun rawRequest(url: URL, server: Server): InputStream? { return withContext(Dispatchers.IO) { val c = (url.openConnection() as HttpURLConnection).apply { setRequestProperty("X-Bimba-Token", server.token) } try { c.inputStream } catch (e: Exception) { Log.e("request", e.stackTraceToString()) null } } } @Suppress("BlockingMethodInNonBlockingContext") suspend fun request( server: Server, resource: String, params: Map<String, String> ): InputStream? { return withContext(Dispatchers.IO) { val url = URL( "${hostWithScheme(server.host)}/api/${server.feeds}/$resource${ params.map { "${it.key}=${ URLEncoder.encode( it.value, "utf-8" ) }" }.joinToString("&", "?") }" ) rawRequest(url, server) } } fun hostWithScheme(host: String): String = if (host.startsWith("http://") or host.startsWith("https://")) { host } else { "https://$host" } |