OXYGENHUB
# d1f635be9442 oxygenhub-android / app / src / main / java / io / oxygenhub / android / api / HubClient.kt
8.3 KiB · last changed Proposals on the dashboard (closes #18) 10 days ago source blame history raw
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
    /** The proposals the caller should act on, across repositories (the hub's dashboard). */
40
    suspend fun userProposals(): UserProposals
41
42
    /** A repository's proposals: open (with drafts), landed, closed or all. */
43
    suspend fun proposals(owner: String, name: String, state: ProposalState = ProposalState.Open): List<Proposal>
44
45
    suspend fun proposal(owner: String, name: String, number: Long): Proposal
46
47
    /** The checks on a proposal's projected state. */
48
    suspend fun checks(owner: String, name: String, number: Long): List<Check>
49
50
    /**
51
     * Land it (`repo:write`); the proposal as landed. The hub refuses with 409
52
     * and its reason when it may not land, and 403 when the token lacks the scope.
53
     */
54
    suspend fun land(owner: String, name: String, number: Long): Proposal
55
56
    /** Land it by itself when its checks pass, or not (`repo:write`); the proposal after. */
57
    suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal
58
59
    /** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */
60
    suspend fun avatar(name: String): Avatar?
61
}
62
63
/**
64
 * The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub
65
 * refuses the token (revoked on the web, or 90 days unused), so the app
66
 * can drop the session and ask for a new sign-in.
67
 */
68
class HubClient(
69
    hub: String,
70
    private val token: String,
71
    private val http: OkHttpClient,
72
    private val onUnauthorized: () -> Unit = {},
73
) : HubApi {
74
    private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl()
75
    private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl()
76
77
    override suspend fun user(): User = get("user", User.serializer())
78
79
    override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer()))
80
81
    override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> =
82
        get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer()))
83
84
    override suspend fun inbox(limit: Int): Inbox =
85
        get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer())
86
87
    override suspend fun userProposals(): UserProposals = get("user/proposals", UserProposals.serializer())
88
89
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
90
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
91
92
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
93
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
94
95
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
96
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
97
98
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
99
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
100
101
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
102
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
103
104
    override suspend fun markRead(id: Long) {
105
        send("POST", url("notifications", id.toString(), "read"))
106
    }
107
108
    override suspend fun markAllRead() {
109
        send("POST", url("notifications", "read"))
110
    }
111
112
    override suspend fun revokeToken() {
113
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
114
    }
115
116
    override suspend fun avatar(name: String): Avatar? {
117
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
118
        // A public picture: no token goes with it.
119
        val response = try {
120
            http.newCall(Request.Builder().url(url).get().build()).await()
121
        } catch (e: IOException) {
122
            throw HubException.Network(e)
123
        }
124
        response.use { r ->
125
            if (r.code == 404) return null
126
            val bytes = try {
127
                r.body?.bytes() ?: ByteArray(0)
128
            } catch (e: IOException) {
129
                throw HubException.Network(e)
130
            }
131
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
132
            return Avatar.parse(r.header("Content-Type"), bytes)
133
        }
134
    }
135
136
    // The bearer token is never part of a string anything prints.
137
    override fun toString(): String = "HubClient(${base})"
138
139
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
140
        val b = base.newBuilder()
141
        // Each segment is encoded on its own: an owner or name never adds a path level.
142
        segments.forEach { b.addPathSegment(it) }
143
        b.query()
144
        return b.build()
145
    }
146
147
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
148
149
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
150
        val body = call(request(url).get().build(), notifyUnauthorized = true)
151
        return try {
152
            HubJson.decodeFromString(serializer, body)
153
        } catch (e: IllegalArgumentException) {
154
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
155
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
156
        }
157
    }
158
159
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
160
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
161
        return call(request(url).method(method, body).build(), notifyUnauthorized)
162
    }
163
164
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
165
        val body = send(method, url)
166
        return try {
167
            HubJson.decodeFromString(serializer, body)
168
        } catch (e: IllegalArgumentException) {
169
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
170
        }
171
    }
172
173
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
174
        .url(url)
175
        .header("Accept", "application/json")
176
        .header("Authorization", "Bearer $token")
177
178
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
179
        val response = try {
180
            http.newCall(request).await()
181
        } catch (e: IOException) {
182
            throw HubException.Network(e)
183
        }
184
        response.use { r ->
185
            val text = try {
186
                r.body?.string().orEmpty()
187
            } catch (e: IOException) {
188
                throw HubException.Network(e)
189
            }
190
            if (!r.isSuccessful) {
191
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
192
                throw HubException.Http(r.code, errorDetail(text))
193
            }
194
            return text
195
        }
196
    }
197
}