| 1 |
package io.oxygenhub.android.api |
| 2 |
|
| 3 |
import kotlinx.serialization.KSerializer |
| 4 |
import kotlinx.serialization.builtins.ListSerializer |
| 5 |
import okhttp3.HttpUrl |
| 6 |
import okhttp3.HttpUrl.Companion.toHttpUrl |
| 7 |
import okhttp3.OkHttpClient |
| 8 |
import okhttp3.Request |
| 9 |
import okhttp3.RequestBody.Companion.toRequestBody |
| 10 |
import java.io.IOException |
| 11 |
|
| 12 |
/** |
| 13 |
* What the app asks of a hub, signed in. The view models see only this, so |
| 14 |
* their tests give them a fake. Later screens (oxygenhub-android#3–#5) add |
| 15 |
* to it: a repository's tree, history, proposals, runs. |
| 16 |
*/ |
| 17 |
interface HubApi { |
| 18 |
/** The signed-in account (`GET /user`, scope `user:read`). */ |
| 19 |
suspend fun user(): User |
| 20 |
|
| 21 |
/** Every repository the caller can read (`GET /repos`). */ |
| 22 |
suspend fun repositories(): List<Repository> |
| 23 |
|
| 24 |
/** A repository's issues (`GET /repos/{owner}/{name}/issues?state=`). */ |
| 25 |
suspend fun issues(owner: String, name: String, state: IssueState = IssueState.Open): List<Issue> |
| 26 |
|
| 27 |
/** The inbox: the unread count and the newest entries (`GET /notifications`). */ |
| 28 |
suspend fun inbox(limit: Int = 50): Inbox |
| 29 |
|
| 30 |
/** Marks one notification read (`POST /notifications/{id}/read`). */ |
| 31 |
suspend fun markRead(id: Long) |
| 32 |
|
| 33 |
/** Marks the whole inbox read (`POST /notifications/read`). */ |
| 34 |
suspend fun markAllRead() |
| 35 |
|
| 36 |
/** Revokes the token this client signs in with (`DELETE /user/token`). */ |
| 37 |
suspend fun revokeToken() |
| 38 |
|
| 39 |
/** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */ |
| 40 |
suspend fun avatar(name: String): Avatar? |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub |
| 45 |
* refuses the token (revoked on the web, or 90 days unused), so the app |
| 46 |
* can drop the session and ask for a new sign-in. |
| 47 |
*/ |
| 48 |
class HubClient( |
| 49 |
hub: String, |
| 50 |
private val token: String, |
| 51 |
private val http: OkHttpClient, |
| 52 |
private val onUnauthorized: () -> Unit = {}, |
| 53 |
) : HubApi { |
| 54 |
private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl() |
| 55 |
private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl() |
| 56 |
|
| 57 |
override suspend fun user(): User = get("user", User.serializer()) |
| 58 |
|
| 59 |
override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer())) |
| 60 |
|
| 61 |
override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> = |
| 62 |
get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer())) |
| 63 |
|
| 64 |
override suspend fun inbox(limit: Int): Inbox = |
| 65 |
get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer()) |
| 66 |
|
| 67 |
override suspend fun markRead(id: Long) { |
| 68 |
send("POST", url("notifications", id.toString(), "read")) |
| 69 |
} |
| 70 |
|
| 71 |
override suspend fun markAllRead() { |
| 72 |
send("POST", url("notifications", "read")) |
| 73 |
} |
| 74 |
|
| 75 |
override suspend fun revokeToken() { |
| 76 |
send("DELETE", url("user", "token"), notifyUnauthorized = false) |
| 77 |
} |
| 78 |
|
| 79 |
override suspend fun avatar(name: String): Avatar? { |
| 80 |
val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build() |
| 81 |
// A public picture: no token goes with it. |
| 82 |
val response = try { |
| 83 |
http.newCall(Request.Builder().url(url).get().build()).await() |
| 84 |
} catch (e: IOException) { |
| 85 |
throw HubException.Network(e) |
| 86 |
} |
| 87 |
response.use { r -> |
| 88 |
if (r.code == 404) return null |
| 89 |
val bytes = try { |
| 90 |
r.body?.bytes() ?: ByteArray(0) |
| 91 |
} catch (e: IOException) { |
| 92 |
throw HubException.Network(e) |
| 93 |
} |
| 94 |
if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString())) |
| 95 |
return Avatar.parse(r.header("Content-Type"), bytes) |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
// The bearer token is never part of a string anything prints. |
| 100 |
override fun toString(): String = "HubClient(${base})" |
| 101 |
|
| 102 |
private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl { |
| 103 |
val b = base.newBuilder() |
| 104 |
// Each segment is encoded on its own: an owner or name never adds a path level. |
| 105 |
segments.forEach { b.addPathSegment(it) } |
| 106 |
b.query() |
| 107 |
return b.build() |
| 108 |
} |
| 109 |
|
| 110 |
private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer) |
| 111 |
|
| 112 |
private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T { |
| 113 |
val body = call(request(url).get().build(), notifyUnauthorized = true) |
| 114 |
return try { |
| 115 |
HubJson.decodeFromString(serializer, body) |
| 116 |
} catch (e: IllegalArgumentException) { |
| 117 |
// kotlinx.serialization's errors are IllegalArgumentExceptions. |
| 118 |
throw HubException.Unreadable("GET ${url.encodedPath}", e) |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true) { |
| 123 |
val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia) |
| 124 |
call(request(url).method(method, body).build(), notifyUnauthorized) |
| 125 |
} |
| 126 |
|
| 127 |
private fun request(url: HttpUrl): Request.Builder = Request.Builder() |
| 128 |
.url(url) |
| 129 |
.header("Accept", "application/json") |
| 130 |
.header("Authorization", "Bearer $token") |
| 131 |
|
| 132 |
private suspend fun call(request: Request, notifyUnauthorized: Boolean): String { |
| 133 |
val response = try { |
| 134 |
http.newCall(request).await() |
| 135 |
} catch (e: IOException) { |
| 136 |
throw HubException.Network(e) |
| 137 |
} |
| 138 |
response.use { r -> |
| 139 |
val text = try { |
| 140 |
r.body?.string().orEmpty() |
| 141 |
} catch (e: IOException) { |
| 142 |
throw HubException.Network(e) |
| 143 |
} |
| 144 |
if (!r.isSuccessful) { |
| 145 |
if (r.code == 401 && notifyUnauthorized) onUnauthorized() |
| 146 |
throw HubException.Http(r.code, errorDetail(text)) |
| 147 |
} |
| 148 |
return text |
| 149 |
} |
| 150 |
} |
| 151 |
} |