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