OXYGENHUB
# aa21eb5e0e5b oxygenhub-android / app / src / main / java / io / oxygenhub / android / api / HubClient.kt
18.4 KiB · last changed Alerts from the hub: the phone registers its Cloud Messaging token and an X25519 key kept by the Keystore, and opens and shows what the hub seals to it with the Rust core; Firebase from google-services.json (the release job's firebase-config secret); pins OxygenFlow main (refs #16) 8 days ago source blame history raw
1
package io.oxygenhub.android.api
2
3
import java.io.IOException
4
import kotlinx.serialization.KSerializer
5
import kotlinx.serialization.builtins.ListSerializer
6
import kotlinx.serialization.json.JsonArray
7
import kotlinx.serialization.json.JsonObject
8
import kotlinx.serialization.json.JsonPrimitive
9
import kotlinx.serialization.json.buildJsonObject
10
import kotlinx.serialization.json.put
11
import okhttp3.HttpUrl
12
import okhttp3.HttpUrl.Companion.toHttpUrl
13
import okhttp3.OkHttpClient
14
import okhttp3.Request
15
import okhttp3.RequestBody.Companion.toRequestBody
16
17
/**
18
 * What the app asks of a hub, signed in. The view models see only this, so
19
 * their tests give them a fake. Later screens (oxygenhub-android#3–#5) add
20
 * to it: a repository's tree, history, proposals, runs.
21
 */
22
interface HubApi {
23
    /** The signed-in account (`GET /user`, scope `user:read`). */
24
    suspend fun user(): User
25
26
    /** Every repository the caller can read (`GET /repos`). */
27
    suspend fun repositories(): List<Repository>
28
29
    /** A repository's issues (`GET /repos/{owner}/{name}/issues?state=`). */
30
    suspend fun issues(owner: String, name: String, state: IssueState = IssueState.Open): List<Issue>
31
32
    /** The inbox: the unread count and the newest entries (`GET /notifications`). */
33
    suspend fun inbox(limit: Int = 50): Inbox
34
35
    /** Marks one notification read (`POST /notifications/{id}/read`). */
36
    suspend fun markRead(id: Long)
37
38
    /** Marks the whole inbox read (`POST /notifications/read`). */
39
    suspend fun markAllRead()
40
41
    /** Revokes the token this client signs in with (`DELETE /user/token`). */
42
    suspend fun revokeToken()
43
44
    /**
45
     * This phone takes alerts (#16): its Cloud Messaging [fcmToken] and its
46
     * alert key's [publicKey] (hex), for the token it signed in with
47
     * (`PUT /user/push`). Whether the hub sends alerts at all.
48
     */
49
    suspend fun registerPush(fcmToken: String, publicKey: String): Boolean
50
51
    /**
52
     * The proposals the caller should act on, across repositories (the hub's
53
     * dashboard); with [landable], also those it can land now (#20, oxygenhub#311).
54
     */
55
    suspend fun userProposals(landable: Boolean = false): UserProposals
56
57
    /** A repository's proposals: open (with drafts), landed, closed or all. */
58
    suspend fun proposals(owner: String, name: String, state: ProposalState = ProposalState.Open): List<Proposal>
59
60
    suspend fun proposal(owner: String, name: String, number: Long): Proposal
61
62
    /** The checks on a proposal's projected state. */
63
    suspend fun checks(owner: String, name: String, number: Long): List<Check>
64
65
    /**
66
     * Land it (`repo:write`); the proposal as landed. The hub refuses with 409
67
     * and its reason when it may not land, and 403 when the token lacks the scope.
68
     */
69
    suspend fun land(owner: String, name: String, number: Long): Proposal
70
71
    /** Land it by itself when its checks pass, or not (`repo:write`); the proposal after. */
72
    suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal
73
74
    /** A one-time token registering this phone as a runner for the account's repositories (`repo:write`). */
75
    suspend fun runnerToken(): RunnerToken
76
77
    suspend fun issue(owner: String, name: String, number: Long): Issue
78
79
    /** A repository's runs, newest first. */
80
    suspend fun runs(owner: String, name: String): List<FlowRun>
81
82
    /** One run, with its jobs. */
83
    suspend fun run(owner: String, name: String, number: Long): FlowRun
84
85
    /** A job's log lines after [after] (0: from the start). */
86
    suspend fun jobLog(owner: String, name: String, number: Long, job: String, after: Long): List<LogLine>
87
88
    suspend fun rerunRun(owner: String, name: String, number: Long)
89
90
    /** Run [job] again in the same run, with the jobs that depend on it. */
91
    suspend fun rerunJob(owner: String, name: String, number: Long, job: String)
92
93
    suspend fun cancelRun(owner: String, name: String, number: Long)
94
95
    /** [owner]'s project boards the caller can see. */
96
    suspend fun projects(owner: String): List<Project>
97
98
    suspend fun board(owner: String, number: Long): Board
99
100
    /** Move a card to the column named [column]. */
101
    suspend fun moveCard(owner: String, number: Long, card: Long, column: String)
102
103
    suspend fun issueComments(owner: String, name: String, number: Long): List<Comment>
104
105
    suspend fun comment(owner: String, name: String, number: Long, body: String): Comment
106
107
    /** Close (with why: `completed` or `not_planned`) or reopen. */
108
    suspend fun setIssueState(owner: String, name: String, number: Long, open: Boolean, reason: String = "completed"): Issue
109
110
    suspend fun createIssue(owner: String, name: String, title: String, body: String): Issue
111
112
    /** The repository's labels, to choose from. */
113
    suspend fun labels(owner: String, name: String): List<Label>
114
115
    /** The issue's whole set of labels (triage). */
116
    suspend fun setIssueLabels(owner: String, name: String, number: Long, labels: List<String>): Issue
117
118
    /** One repository (`GET /repos/{owner}/{name}`): its default bookmark, for the code browser. */
119
    suspend fun repository(owner: String, name: String): Repository
120
121
    /** A directory of the tree at [ref] (a bookmark, tag or change), [path] "" for the top. */
122
    suspend fun tree(owner: String, name: String, ref: String, path: String = ""): List<TreeEntry>
123
124
    /** A file's bytes at [ref], as text. */
125
    suspend fun file(owner: String, name: String, ref: String, path: String): String
126
127
    /** [ref]'s history, newest first; only changes to [path] when given. */
128
    suspend fun history(owner: String, name: String, ref: String, path: String? = null, offset: Int = 0, limit: Int = 50): History
129
130
    suspend fun change(owner: String, name: String, hash: String): ChangeDetail
131
132
    /** The repository's bookmarks and tags, to browse at. */
133
    suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>>
134
135
    /** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */
136
    suspend fun avatar(name: String): Avatar?
137
138
    /** An account's public profile, and an organisation's (with its members). */
139
    suspend fun account(name: String): User
140
141
    suspend fun organisation(name: String): Organisation
142
}
143
144
/**
145
 * The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub
146
 * refuses the token (revoked on the web, or 90 days unused), so the app
147
 * can drop the session and ask for a new sign-in.
148
 */
149
class HubClient(
150
    hub: String,
151
    private val token: String,
152
    private val http: OkHttpClient,
153
    private val onUnauthorized: () -> Unit = {},
154
) : HubApi {
155
    private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl()
156
    private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl()
157
158
    override suspend fun user(): User = get("user", User.serializer())
159
160
    override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer()))
161
162
    override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> =
163
        get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer()))
164
165
    override suspend fun inbox(limit: Int): Inbox =
166
        get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer())
167
168
    override suspend fun runnerToken(): RunnerToken = send("POST", url("user", "runner-token"), RunnerToken.serializer())
169
170
    override suspend fun runs(owner: String, name: String): List<FlowRun> =
171
        get(url("repos", owner, name, "flow", "runs"), ListSerializer(FlowRun.serializer()))
172
173
    override suspend fun run(owner: String, name: String, number: Long): FlowRun =
174
        get(url("repos", owner, name, "flow", "runs", number.toString()), FlowRun.serializer())
175
176
    override suspend fun jobLog(owner: String, name: String, number: Long, job: String, after: Long): List<LogLine> =
177
        get(
178
            url("repos", owner, name, "flow", "runs", number.toString(), "jobs", job, "log") { addQueryParameter("after", after.toString()) },
179
            ListSerializer(LogLine.serializer()),
180
        )
181
182
    override suspend fun rerunRun(owner: String, name: String, number: Long) {
183
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "rerun"))
184
    }
185
186
    override suspend fun rerunJob(owner: String, name: String, number: Long, job: String) {
187
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "jobs", job, "rerun"))
188
    }
189
190
    override suspend fun cancelRun(owner: String, name: String, number: Long) {
191
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "cancel"))
192
    }
193
194
    override suspend fun projects(owner: String): List<Project> = get(url("projects", owner), ListSerializer(Project.serializer()))
195
196
    override suspend fun board(owner: String, number: Long): Board = get(url("projects", owner, number.toString()), Board.serializer())
197
198
    override suspend fun moveCard(owner: String, number: Long, card: Long, column: String) {
199
        val json = buildJsonObject { put("column", column) }
200
        call(request(url("projects", owner, number.toString(), "cards", card.toString())).method("PATCH", json.toString().toRequestBody(JsonMedia)).build(), true)
201
    }
202
203
    override suspend fun issue(owner: String, name: String, number: Long): Issue =
204
        get(url("repos", owner, name, "issues", number.toString()), Issue.serializer())
205
206
    override suspend fun issueComments(owner: String, name: String, number: Long): List<Comment> =
207
        get(url("repos", owner, name, "issues", number.toString(), "comments"), ListSerializer(Comment.serializer()))
208
209
    override suspend fun comment(owner: String, name: String, number: Long, body: String): Comment =
210
        sendJson("POST", url("repos", owner, name, "issues", number.toString(), "comments"), buildJsonObject { put("body", body) }, Comment.serializer())
211
212
    override suspend fun setIssueState(owner: String, name: String, number: Long, open: Boolean, reason: String): Issue =
213
        sendJson(
214
            "POST",
215
            url("repos", owner, name, "issues", number.toString()),
216
            buildJsonObject {
217
                put("state", if (open) "open" else "closed")
218
                if (!open) put("reason", reason)
219
            },
220
            Issue.serializer(),
221
        )
222
223
    override suspend fun createIssue(owner: String, name: String, title: String, body: String): Issue =
224
        sendJson("POST", url("repos", owner, name, "issues"), buildJsonObject {
225
            put("title", title)
226
            put("body", body)
227
        }, Issue.serializer())
228
229
    override suspend fun labels(owner: String, name: String): List<Label> =
230
        get(url("repos", owner, name, "labels"), ListSerializer(Label.serializer()))
231
232
    override suspend fun setIssueLabels(owner: String, name: String, number: Long, labels: List<String>): Issue =
233
        sendJson("PATCH", url("repos", owner, name, "issues", number.toString()), buildJsonObject {
234
            put("labels", JsonArray(labels.map { JsonPrimitive(it) }))
235
        }, Issue.serializer())
236
237
    override suspend fun account(name: String): User = get(url("users", name), User.serializer())
238
239
    override suspend fun organisation(name: String): Organisation = get(url("orgs", name), Organisation.serializer())
240
241
    override suspend fun repository(owner: String, name: String): Repository = get(url("repos", owner, name), Repository.serializer())
242
243
    private fun parts(path: String): Array<String> = path.split('/').filter { it.isNotEmpty() }.toTypedArray()
244
245
    override suspend fun tree(owner: String, name: String, ref: String, path: String): List<TreeEntry> =
246
        get(url("repos", owner, name, "tree", ref, *parts(path)), ListSerializer(TreeEntry.serializer()))
247
248
    override suspend fun file(owner: String, name: String, ref: String, path: String): String =
249
        call(request(url("repos", owner, name, "file", ref, *parts(path))).get().build(), notifyUnauthorized = true)
250
251
    override suspend fun history(owner: String, name: String, ref: String, path: String?, offset: Int, limit: Int): History =
252
        get(
253
            url("repos", owner, name, "history", ref) {
254
                path?.let { addQueryParameter("path", it) }
255
                addQueryParameter("offset", offset.toString())
256
                addQueryParameter("limit", limit.toString())
257
            },
258
            History.serializer(),
259
        )
260
261
    override suspend fun change(owner: String, name: String, hash: String): ChangeDetail =
262
        get(url("repos", owner, name, "changes", hash), ChangeDetail.serializer())
263
264
    override suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>> {
265
        val bookmarks = get(url("repos", owner, name, "bookmarks"), ListSerializer(NamedRef.serializer())).map { it.name }
266
        val tags = get(url("repos", owner, name, "tags"), ListSerializer(NamedRef.serializer())).map { it.name }
267
        return bookmarks to tags
268
    }
269
270
    override suspend fun userProposals(landable: Boolean): UserProposals =
271
        get(url("user", "proposals") { if (landable) addQueryParameter("landable", "true") }, UserProposals.serializer())
272
273
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
274
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
275
276
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
277
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
278
279
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
280
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
281
282
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
283
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
284
285
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
286
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
287
288
    override suspend fun markRead(id: Long) {
289
        send("POST", url("notifications", id.toString(), "read"))
290
    }
291
292
    override suspend fun markAllRead() {
293
        send("POST", url("notifications", "read"))
294
    }
295
296
    override suspend fun revokeToken() {
297
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
298
    }
299
300
    override suspend fun registerPush(fcmToken: String, publicKey: String): Boolean =
301
        sendJson("PUT", url("user", "push"), buildJsonObject {
302
            put("fcm_token", fcmToken)
303
            put("public_key", publicKey)
304
        }, PushRegistered.serializer()).alerts
305
306
    override suspend fun avatar(name: String): Avatar? {
307
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
308
        // A public picture: no token goes with it.
309
        val response = try {
310
            http.newCall(Request.Builder().url(url).get().build()).await()
311
        } catch (e: IOException) {
312
            throw HubException.Network(e)
313
        }
314
        response.use { r ->
315
            if (r.code == 404) return null
316
            val bytes = try {
317
                r.body?.bytes() ?: ByteArray(0)
318
            } catch (e: IOException) {
319
                throw HubException.Network(e)
320
            }
321
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
322
            return Avatar.parse(r.header("Content-Type"), bytes)
323
        }
324
    }
325
326
    // The bearer token is never part of a string anything prints.
327
    override fun toString(): String = "HubClient(${base})"
328
329
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
330
        val b = base.newBuilder()
331
        // Each segment is encoded on its own: an owner or name never adds a path level.
332
        segments.forEach { b.addPathSegment(it) }
333
        b.query()
334
        return b.build()
335
    }
336
337
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
338
339
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
340
        val body = call(request(url).get().build(), notifyUnauthorized = true)
341
        return try {
342
            HubJson.decodeFromString(serializer, body)
343
        } catch (e: IllegalArgumentException) {
344
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
345
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
346
        }
347
    }
348
349
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
350
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
351
        return call(request(url).method(method, body).build(), notifyUnauthorized)
352
    }
353
354
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
355
        val body = send(method, url)
356
        return try {
357
            HubJson.decodeFromString(serializer, body)
358
        } catch (e: IllegalArgumentException) {
359
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
360
        }
361
    }
362
363
    /** [json] as the body; the answer read with [serializer]. */
364
    private suspend fun <T> sendJson(method: String, url: HttpUrl, json: JsonObject, serializer: KSerializer<T>): T {
365
        val body = call(request(url).method(method, json.toString().toRequestBody(JsonMedia)).build(), notifyUnauthorized = true)
366
        return try {
367
            HubJson.decodeFromString(serializer, body)
368
        } catch (e: IllegalArgumentException) {
369
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
370
        }
371
    }
372
373
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
374
        .url(url)
375
        .header("Accept", "application/json")
376
        .header("Authorization", "Bearer $token")
377
378
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
379
        val response = try {
380
            http.newCall(request).await()
381
        } catch (e: IOException) {
382
            throw HubException.Network(e)
383
        }
384
        response.use { r ->
385
            val text = try {
386
                r.body?.string().orEmpty()
387
            } catch (e: IOException) {
388
                throw HubException.Network(e)
389
            }
390
            if (!r.isSuccessful) {
391
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
392
                throw HubException.Http(r.code, errorDetail(text))
393
            }
394
            return text
395
        }
396
    }
397
}