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