Bimba.git

ref: 2919df3a7321d4e904d6ed9cdd1c3c8c32a5ef6c

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
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

suspend fun queryItems(query: String): InputStream? {
	return request("https://bimba.apiote.xyz", "poznan_ztm", "items", mapOf("q" to query))
}

suspend fun locateItems(plusCode: String): InputStream? {
	return request("https://bimba.apiote.xyz", "poznan_ztm", "items", mapOf("near" to plusCode))
}

suspend fun getDepartures(stop: String, line: String?): InputStream? {
	return request("https://bimba.apiote.xyz", "poznan_ztm", "departures", mapOf("code" to stop))
}

@Suppress("BlockingMethodInNonBlockingContext")
suspend fun request(
	host: String,
	feed: String,
	resource: String,
	params: Map<String, String>
): InputStream? {
	return withContext(Dispatchers.IO) {
		val url = URL(
			"$host/api/$feed/$resource${
				params.map {
					"${it.key}=${
						URLEncoder.encode(
							it.value,
							"utf-8"
						)
					}"
				}.joinToString("&", "?")
			}"
		)
		val c = (url.openConnection() as HttpURLConnection).apply {
			setRequestProperty("X-Bimba-Token", "ef0179272e7270e1a2da1710a8ba24e1")
		}
		try {
			c.inputStream
		} catch (e: Exception) {
			Log.e("request", e.stackTraceToString())
			null
		}
	}
}