Bimba.git

ref: v3.7.0

app/src/main/java/xyz/apiote/bimba/czwek/api/transitous.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
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package xyz.apiote.bimba.czwek.api

import android.content.Context
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import xyz.apiote.bimba.czwek.R
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

suspend fun askTransitous(context: Context, json: String): Result {
	return withContext(Dispatchers.IO) {
		val url = URL("https://routing.spline.de/api/")
		val c = (url.openConnection() as HttpURLConnection).apply {
			setRequestProperty(
				"User-Agent",
				"${context.getString(R.string.applicationId)}/${context.getString(R.string.versionName)} (${Build.VERSION.SDK_INT})"
			)
			addRequestProperty("Content-Type", "application/json")
			requestMethod = "POST"
			doOutput = true
			outputStream.write(json.toByteArray())
		}
		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))
		}
	}
}