OXYGENHUB
# af9f2e514c72 oxygenhub-android / app / src / main / java / io / oxygenhub / android / api / HubClient.kt
19.3 KiB · last changed Review a proposal from the phone: approve, request changes or comment from its Reviews section (refs #4) 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
    /** Review a proposal (#4): [verdict] is `approve`, `changes` or `comment`, with [body] said. */
133
    suspend fun review(owner: String, name: String, number: Long, verdict: String, body: String)
134
135
    /** The files a proposal changes, each with its diff, as the proposal page shows them (#4). */
136
    suspend fun proposalDiff(owner: String, name: String, number: Long): List<FileChange>
137
138
    /** The repository's bookmarks and tags, to browse at. */
139
    suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>>
140
141
    /** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */
142
    suspend fun avatar(name: String): Avatar?
143
144
    /** An account's public profile, and an organisation's (with its members). */
145
    suspend fun account(name: String): User
146
147
    suspend fun organisation(name: String): Organisation
148
}
149
150
/**
151
 * The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub
152
 * refuses the token (revoked on the web, or 90 days unused), so the app
153
 * can drop the session and ask for a new sign-in.
154
 */
155
class HubClient(
156
    hub: String,
157
    private val token: String,
158
    private val http: OkHttpClient,
159
    private val onUnauthorized: () -> Unit = {},
160
) : HubApi {
161
    private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl()
162
    private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl()
163
164
    override suspend fun user(): User = get("user", User.serializer())
165
166
    override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer()))
167
168
    override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> =
169
        get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer()))
170
171
    override suspend fun inbox(limit: Int): Inbox =
172
        get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer())
173
174
    override suspend fun runnerToken(): RunnerToken = send("POST", url("user", "runner-token"), RunnerToken.serializer())
175
176
    override suspend fun runs(owner: String, name: String): List<FlowRun> =
177
        get(url("repos", owner, name, "flow", "runs"), ListSerializer(FlowRun.serializer()))
178
179
    override suspend fun run(owner: String, name: String, number: Long): FlowRun =
180
        get(url("repos", owner, name, "flow", "runs", number.toString()), FlowRun.serializer())
181
182
    override suspend fun jobLog(owner: String, name: String, number: Long, job: String, after: Long): List<LogLine> =
183
        get(
184
            url("repos", owner, name, "flow", "runs", number.toString(), "jobs", job, "log") { addQueryParameter("after", after.toString()) },
185
            ListSerializer(LogLine.serializer()),
186
        )
187
188
    override suspend fun rerunRun(owner: String, name: String, number: Long) {
189
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "rerun"))
190
    }
191
192
    override suspend fun rerunJob(owner: String, name: String, number: Long, job: String) {
193
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "jobs", job, "rerun"))
194
    }
195
196
    override suspend fun cancelRun(owner: String, name: String, number: Long) {
197
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "cancel"))
198
    }
199
200
    override suspend fun projects(owner: String): List<Project> = get(url("projects", owner), ListSerializer(Project.serializer()))
201
202
    override suspend fun board(owner: String, number: Long): Board = get(url("projects", owner, number.toString()), Board.serializer())
203
204
    override suspend fun moveCard(owner: String, number: Long, card: Long, column: String) {
205
        val json = buildJsonObject { put("column", column) }
206
        call(request(url("projects", owner, number.toString(), "cards", card.toString())).method("PATCH", json.toString().toRequestBody(JsonMedia)).build(), true)
207
    }
208
209
    override suspend fun issue(owner: String, name: String, number: Long): Issue =
210
        get(url("repos", owner, name, "issues", number.toString()), Issue.serializer())
211
212
    override suspend fun issueComments(owner: String, name: String, number: Long): List<Comment> =
213
        get(url("repos", owner, name, "issues", number.toString(), "comments"), ListSerializer(Comment.serializer()))
214
215
    override suspend fun comment(owner: String, name: String, number: Long, body: String): Comment =
216
        sendJson("POST", url("repos", owner, name, "issues", number.toString(), "comments"), buildJsonObject { put("body", body) }, Comment.serializer())
217
218
    override suspend fun setIssueState(owner: String, name: String, number: Long, open: Boolean, reason: String): Issue =
219
        sendJson(
220
            "POST",
221
            url("repos", owner, name, "issues", number.toString()),
222
            buildJsonObject {
223
                put("state", if (open) "open" else "closed")
224
                if (!open) put("reason", reason)
225
            },
226
            Issue.serializer(),
227
        )
228
229
    override suspend fun createIssue(owner: String, name: String, title: String, body: String): Issue =
230
        sendJson("POST", url("repos", owner, name, "issues"), buildJsonObject {
231
            put("title", title)
232
            put("body", body)
233
        }, Issue.serializer())
234
235
    override suspend fun labels(owner: String, name: String): List<Label> =
236
        get(url("repos", owner, name, "labels"), ListSerializer(Label.serializer()))
237
238
    override suspend fun setIssueLabels(owner: String, name: String, number: Long, labels: List<String>): Issue =
239
        sendJson("PATCH", url("repos", owner, name, "issues", number.toString()), buildJsonObject {
240
            put("labels", JsonArray(labels.map { JsonPrimitive(it) }))
241
        }, Issue.serializer())
242
243
    override suspend fun account(name: String): User = get(url("users", name), User.serializer())
244
245
    override suspend fun organisation(name: String): Organisation = get(url("orgs", name), Organisation.serializer())
246
247
    override suspend fun repository(owner: String, name: String): Repository = get(url("repos", owner, name), Repository.serializer())
248
249
    private fun parts(path: String): Array<String> = path.split('/').filter { it.isNotEmpty() }.toTypedArray()
250
251
    override suspend fun tree(owner: String, name: String, ref: String, path: String): List<TreeEntry> =
252
        get(url("repos", owner, name, "tree", ref, *parts(path)), ListSerializer(TreeEntry.serializer()))
253
254
    override suspend fun file(owner: String, name: String, ref: String, path: String): String =
255
        call(request(url("repos", owner, name, "file", ref, *parts(path))).get().build(), notifyUnauthorized = true)
256
257
    override suspend fun history(owner: String, name: String, ref: String, path: String?, offset: Int, limit: Int): History =
258
        get(
259
            url("repos", owner, name, "history", ref) {
260
                path?.let { addQueryParameter("path", it) }
261
                addQueryParameter("offset", offset.toString())
262
                addQueryParameter("limit", limit.toString())
263
            },
264
            History.serializer(),
265
        )
266
267
    override suspend fun review(owner: String, name: String, number: Long, verdict: String, body: String) {
268
        sendJson("POST", url("repos", owner, name, "proposals", number.toString(), "reviews"), buildJsonObject {
269
            put("verdict", verdict)
270
            put("body", body)
271
        }, ReviewPosted.serializer())
272
    }
273
274
    override suspend fun proposalDiff(owner: String, name: String, number: Long): List<FileChange> =
275
        get(url("repos", owner, name, "proposals", number.toString(), "diff"), ListSerializer(FileChange.serializer()))
276
277
    override suspend fun change(owner: String, name: String, hash: String): ChangeDetail =
278
        get(url("repos", owner, name, "changes", hash), ChangeDetail.serializer())
279
280
    override suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>> {
281
        val bookmarks = get(url("repos", owner, name, "bookmarks"), ListSerializer(NamedRef.serializer())).map { it.name }
282
        val tags = get(url("repos", owner, name, "tags"), ListSerializer(NamedRef.serializer())).map { it.name }
283
        return bookmarks to tags
284
    }
285
286
    override suspend fun userProposals(landable: Boolean): UserProposals =
287
        get(url("user", "proposals") { if (landable) addQueryParameter("landable", "true") }, UserProposals.serializer())
288
289
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
290
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
291
292
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
293
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
294
295
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
296
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
297
298
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
299
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
300
301
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
302
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
303
304
    override suspend fun markRead(id: Long) {
305
        send("POST", url("notifications", id.toString(), "read"))
306
    }
307
308
    override suspend fun markAllRead() {
309
        send("POST", url("notifications", "read"))
310
    }
311
312
    override suspend fun revokeToken() {
313
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
314
    }
315
316
    override suspend fun registerPush(fcmToken: String, publicKey: String): Boolean =
317
        sendJson("PUT", url("user", "push"), buildJsonObject {
318
            put("fcm_token", fcmToken)
319
            put("public_key", publicKey)
320
        }, PushRegistered.serializer()).alerts
321
322
    override suspend fun avatar(name: String): Avatar? {
323
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
324
        // A public picture: no token goes with it.
325
        val response = try {
326
            http.newCall(Request.Builder().url(url).get().build()).await()
327
        } catch (e: IOException) {
328
            throw HubException.Network(e)
329
        }
330
        response.use { r ->
331
            if (r.code == 404) return null
332
            val bytes = try {
333
                r.body?.bytes() ?: ByteArray(0)
334
            } catch (e: IOException) {
335
                throw HubException.Network(e)
336
            }
337
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
338
            return Avatar.parse(r.header("Content-Type"), bytes)
339
        }
340
    }
341
342
    // The bearer token is never part of a string anything prints.
343
    override fun toString(): String = "HubClient(${base})"
344
345
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
346
        val b = base.newBuilder()
347
        // Each segment is encoded on its own: an owner or name never adds a path level.
348
        segments.forEach { b.addPathSegment(it) }
349
        b.query()
350
        return b.build()
351
    }
352
353
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
354
355
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
356
        val body = call(request(url).get().build(), notifyUnauthorized = true)
357
        return try {
358
            HubJson.decodeFromString(serializer, body)
359
        } catch (e: IllegalArgumentException) {
360
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
361
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
362
        }
363
    }
364
365
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
366
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
367
        return call(request(url).method(method, body).build(), notifyUnauthorized)
368
    }
369
370
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
371
        val body = send(method, url)
372
        return try {
373
            HubJson.decodeFromString(serializer, body)
374
        } catch (e: IllegalArgumentException) {
375
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
376
        }
377
    }
378
379
    /** [json] as the body; the answer read with [serializer]. */
380
    private suspend fun <T> sendJson(method: String, url: HttpUrl, json: JsonObject, serializer: KSerializer<T>): T {
381
        val body = call(request(url).method(method, json.toString().toRequestBody(JsonMedia)).build(), notifyUnauthorized = true)
382
        return try {
383
            HubJson.decodeFromString(serializer, body)
384
        } catch (e: IllegalArgumentException) {
385
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
386
        }
387
    }
388
389
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
390
        .url(url)
391
        .header("Accept", "application/json")
392
        .header("Authorization", "Bearer $token")
393
394
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
395
        val response = try {
396
            http.newCall(request).await()
397
        } catch (e: IOException) {
398
            throw HubException.Network(e)
399
        }
400
        response.use { r ->
401
            val text = try {
402
                r.body?.string().orEmpty()
403
            } catch (e: IOException) {
404
                throw HubException.Network(e)
405
            }
406
            if (!r.isSuccessful) {
407
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
408
                throw HubException.Http(r.code, errorDetail(text))
409
            }
410
            return text
411
        }
412
    }
413
}