Bimba.git

ref: 912f70db2ca99322470dde31169a941352694501

app/src/main/java/xyz/apiote/bimba/czwek/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
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.api

import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.net.ConnectivityManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.settings.feeds.FeedsSettings
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.net.URLEncoder

// todo [3.2] constants
// todo [3.2] split api files to classes files

data class Server(
	val host: String,
	val token: String,
	val feeds: FeedsSettings,
	val apiPath: String
) {
	companion object {
		fun get(context: Context): Server {
			val preferences = context.getSharedPreferences("shp", MODE_PRIVATE)
			val apiPath = preferences.getString("apiPath", "")!!
			val feeds = FeedsSettings.load(context, apiPath)
			val host = preferences.getString("host", "bimba.apiote.xyz")!!
			return Server(
				host, preferences.getString("token", "")!!,
				feeds, apiPath
			)
		}
	}
}

data class Result(val stream: InputStream?, val error: Error?)

data class Error(val statusCode: Int, val stringResource: Int, val imageResource: Int)

suspend fun getBimba(cm: ConnectivityManager, server: Server): Result {
	return try {
		rawRequest(
			URL("${hostWithScheme(server.host)}/.well-known/traffic-api"), server, cm, emptyArray()
		)
	} catch (e: MalformedURLException) {
		Result(null, Error(0, R.string.error_url, R.drawable.error_url))
	}
}

suspend fun getFeeds(cm: ConnectivityManager, server: Server): Result {
	return try {
		rawRequest(
			URL("${server.apiPath}/"), server, cm, arrayOf(1u, 2u)
		)
	} catch (_: MalformedURLException) {
		Result(null, Error(0, R.string.error_url, R.drawable.error_url))
	}
}

suspend fun queryQueryables(
	cm: ConnectivityManager, server: Server, query: String, limit: Int? = null
): Result {
	val params = mutableMapOf("q" to query)
	if (limit != null) {
		params["limit"] = limit.toString()
	}
	return request(
		server,
		"queryables",
		null,
		params,
		cm,
		arrayOf(1u, 2u, 3u),
		null
	)
}

suspend fun locateQueryables(cm: ConnectivityManager, server: Server, near: PositionV1): Result {
	return request(
		server,
		"queryables",
		null,
		mapOf("near" to near.toString()),
		cm,
		arrayOf(1u, 2u, 3u),
		null
	)
}

suspend fun getLocatablesIn(
	cm: ConnectivityManager, server: Server, bl: PositionV1, tr: PositionV1
): Result {
	return request(
		server,
		"locatables",
		null,
		mapOf("lb" to bl.toString(), "rt" to tr.toString()),
		cm,
		arrayOf(1u, 2u, 3u),
		null
	)
}

suspend fun getLine(cm: ConnectivityManager, server: Server, feedID: String, line: String): Result {
	return request(
		server,
		"lines",
		line,
		mapOf(),
		cm,
		arrayOf(1u, 2u),
		feedID
	)
}

suspend fun getDepartures(
	cm: ConnectivityManager,
	server: Server,
	feedID: String,
	stop: String,
	line: String? = null,
	limit: Int? = null
): Result {
	val params = mutableMapOf("code" to stop)
	if (line != null) {
		params["line"] = line
	}
	if (limit != null) {
		params["limit"] = limit.toString(10)
	}
	return request(
		server,
		"departures",
		null,
		params,
		cm,
		arrayOf(1u, 2u, 3u),
		feedID
	)
}

fun mapHttpError(code: Int): Pair<Int, Int> {
	return when (code) {
		41 -> Pair(R.string.error_41, R.drawable.error_other) // TODO error_locality
		400 -> Pair(R.string.error_400, R.drawable.error_app)
		401 -> Pair(R.string.error_401, R.drawable.error_sec)
		403 -> Pair(R.string.error_403, R.drawable.error_sec)
		404 -> Pair(R.string.error_404, R.drawable.error_search)
		406 -> Pair(R.string.error_406, R.drawable.error_accept)
		429 -> Pair(R.string.error_429, R.drawable.error_limit)
		500 -> Pair(R.string.error_50x, R.drawable.error_server)
		502 -> Pair(R.string.error_50x, R.drawable.error_server)
		503 -> Pair(R.string.error_50x, R.drawable.error_server)
		504 -> Pair(R.string.error_50x, R.drawable.error_server)
		else -> Pair(R.string.error_unknown, R.drawable.error_other)
	}
}

suspend fun rawRequest(
	url: URL, server: Server, cm: ConnectivityManager, responseVersion: Array<UInt>
): Result {
	@Suppress("DEPRECATION")  // fixme later(API_29, API_23) https://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetwork()
	if (cm.activeNetworkInfo == null) {
		return Result(null, Error(0, R.string.error_offline, R.drawable.error_net))
	}
	return withContext(Dispatchers.IO) {
		val c = (url.openConnection() as HttpURLConnection).apply {
			setRequestProperty("X-Bimba-Token", server.token)
			responseVersion.forEach { addRequestProperty("Accept", "application/$it+bare") }
		}
		try {
			if (c.responseCode == 200) {
				Result(c.inputStream, null)
			} else {
				val (string, image) = mapHttpError(c.responseCode)
				Result(c.errorStream, Error(c.responseCode, string, image))
			}
		} catch (e: IOException) {
			Result(null, Error(0, R.string.error_connecting, R.drawable.error_server))
		}
	}
}

suspend fun request(
	server: Server,
	resource: String,
	item: String?,
	params: Map<String, String>,
	cm: ConnectivityManager,
	responseVersion: Array<UInt>,
	feeds: String?
): Result {
	return withContext(Dispatchers.IO) {
		val url = URL( // todo [3.2] scheme, host, path, constructed query
			"${server.apiPath}/${feeds?.ifEmpty { server.feeds.getIDs() } ?: server.feeds.getIDs()}/$resource${
				if (item == null) {
					""
				} else {
					"/$item"
				}
			}${
				params.map {
					"${it.key}=${
						URLEncoder.encode(
							it.value, "utf-8"
						)
					}"
				}.joinToString("&", "?")
			}"
		)
		rawRequest(url, server, cm, responseVersion)
	}
}

fun hostWithScheme(host: String): String =
	if (host.startsWith("http://") or host.startsWith("https://")) {
		host
	} else {
		"https://$host"
	}