OXYGENHUB

Coverage / app/src/main/java/io/oxygenhub/android/api/HubClient.kt 44.1%

67 of 152 lines run, 32 of 72 functions, 16 of 32 branches · run #1625 on main · run missed

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 releases, newest first. */
80
    suspend fun releases(owner: String, name: String): List<Release>
81
82
    /** Issues and proposals matching [query], across the repositories the caller can read. */
83
    suspend fun search(query: String): List<SearchHit>
84
85
    /** A repository's runs, newest first. */
86
    suspend fun runs(owner: String, name: String): List<FlowRun>
87
88
    /** One run, with its jobs. */
89
    suspend fun run(owner: String, name: String, number: Long): FlowRun
90
91
    /** A job's log lines after [after] (0: from the start). */
92
    suspend fun jobLog(owner: String, name: String, number: Long, job: String, after: Long): List<LogLine>
93
94
    suspend fun rerunRun(owner: String, name: String, number: Long)
95
96
    /** Run [job] again in the same run, with the jobs that depend on it. */
97
    suspend fun rerunJob(owner: String, name: String, number: Long, job: String)
98
99
    suspend fun cancelRun(owner: String, name: String, number: Long)
100
101
    /** [owner]'s project boards the caller can see. */
102
    suspend fun projects(owner: String): List<Project>
103
104
    suspend fun board(owner: String, number: Long): Board
105
106
    /** Move a card to the column named [column]. */
107
    suspend fun moveCard(owner: String, number: Long, card: Long, column: String)
108
109
    suspend fun issueComments(owner: String, name: String, number: Long): List<Comment>
110
111
    suspend fun comment(owner: String, name: String, number: Long, body: String): Comment
112
113
    /** Close (with why: `completed` or `not_planned`) or reopen. */
114
    suspend fun setIssueState(owner: String, name: String, number: Long, open: Boolean, reason: String = "completed"): Issue
115
116
    suspend fun createIssue(owner: String, name: String, title: String, body: String): Issue
117
118
    /** The repository's labels, to choose from. */
119
    suspend fun labels(owner: String, name: String): List<Label>
120
121
    /** The issue's whole set of labels (triage). */
122
    suspend fun setIssueLabels(owner: String, name: String, number: Long, labels: List<String>): Issue
123
124
    /** One repository (`GET /repos/{owner}/{name}`): its default bookmark, for the code browser. */
125
    suspend fun repository(owner: String, name: String): Repository
126
127
    /** A directory of the tree at [ref] (a bookmark, tag or change), [path] "" for the top. */
128
    suspend fun tree(owner: String, name: String, ref: String, path: String = ""): List<TreeEntry>
129
130
    /** A file's bytes at [ref], as text. */
131
    suspend fun file(owner: String, name: String, ref: String, path: String): String
132
133
    /** [ref]'s history, newest first; only changes to [path] when given. */
134
    suspend fun history(owner: String, name: String, ref: String, path: String? = null, offset: Int = 0, limit: Int = 50): History
135
136
    suspend fun change(owner: String, name: String, hash: String): ChangeDetail
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 releases(owner: String, name: String): List<Release> =
177
        get(url("repos", owner, name, "releases"), ListSerializer(Release.serializer()))
178
179
    override suspend fun search(query: String): List<SearchHit> =
180
        get(url("search") { addQueryParameter("q", query) }, ListSerializer(SearchHit.serializer()))
181
182
    override suspend fun runs(owner: String, name: String): List<FlowRun> =
183
        get(url("repos", owner, name, "flow", "runs"), ListSerializer(FlowRun.serializer()))
184
185
    override suspend fun run(owner: String, name: String, number: Long): FlowRun =
186
        get(url("repos", owner, name, "flow", "runs", number.toString()), FlowRun.serializer())
187
188
    override suspend fun jobLog(owner: String, name: String, number: Long, job: String, after: Long): List<LogLine> =
189
        get(
190
            url("repos", owner, name, "flow", "runs", number.toString(), "jobs", job, "log") { addQueryParameter("after", after.toString()) },
191
            ListSerializer(LogLine.serializer()),
192
        )
193
194
    override suspend fun rerunRun(owner: String, name: String, number: Long) {
195
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "rerun"))
196
    }
197
198
    override suspend fun rerunJob(owner: String, name: String, number: Long, job: String) {
199
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "jobs", job, "rerun"))
200
    }
201
202
    override suspend fun cancelRun(owner: String, name: String, number: Long) {
203
        send("POST", url("repos", owner, name, "flow", "runs", number.toString(), "cancel"))
204
    }
205
206
    override suspend fun projects(owner: String): List<Project> = get(url("projects", owner), ListSerializer(Project.serializer()))
207
208
    override suspend fun board(owner: String, number: Long): Board = get(url("projects", owner, number.toString()), Board.serializer())
209
210
    override suspend fun moveCard(owner: String, number: Long, card: Long, column: String) {
211
        val json = buildJsonObject { put("column", column) }
212
        call(request(url("projects", owner, number.toString(), "cards", card.toString())).method("PATCH", json.toString().toRequestBody(JsonMedia)).build(), true)
213
    }
214
215
    override suspend fun issue(owner: String, name: String, number: Long): Issue =
216
        get(url("repos", owner, name, "issues", number.toString()), Issue.serializer())
217
218
    override suspend fun issueComments(owner: String, name: String, number: Long): List<Comment> =
219
        get(url("repos", owner, name, "issues", number.toString(), "comments"), ListSerializer(Comment.serializer()))
220
221
    override suspend fun comment(owner: String, name: String, number: Long, body: String): Comment =
222
        sendJson("POST", url("repos", owner, name, "issues", number.toString(), "comments"), buildJsonObject { put("body", body) }, Comment.serializer())
223
224
    override suspend fun setIssueState(owner: String, name: String, number: Long, open: Boolean, reason: String): Issue =
225
        sendJson(
226
            "POST",
227
            url("repos", owner, name, "issues", number.toString()),
228
            buildJsonObject {
229
                put("state", if (open) "open" else "closed")
230
                if (!open) put("reason", reason)
231
            },
232
            Issue.serializer(),
233
        )
234
235
    override suspend fun createIssue(owner: String, name: String, title: String, body: String): Issue =
236
        sendJson("POST", url("repos", owner, name, "issues"), buildJsonObject {
237
            put("title", title)
238
            put("body", body)
239
        }, Issue.serializer())
240
241
    override suspend fun labels(owner: String, name: String): List<Label> =
242
        get(url("repos", owner, name, "labels"), ListSerializer(Label.serializer()))
243
244
    override suspend fun setIssueLabels(owner: String, name: String, number: Long, labels: List<String>): Issue =
245
        sendJson("PATCH", url("repos", owner, name, "issues", number.toString()), buildJsonObject {
246
            put("labels", JsonArray(labels.map { JsonPrimitive(it) }))
247
        }, Issue.serializer())
248
249
    override suspend fun account(name: String): User = get(url("users", name), User.serializer())
250
251
    override suspend fun organisation(name: String): Organisation = get(url("orgs", name), Organisation.serializer())
252
253
    override suspend fun repository(owner: String, name: String): Repository = get(url("repos", owner, name), Repository.serializer())
254
255
    private fun parts(path: String): Array<String> = path.split('/').filter { it.isNotEmpty() }.toTypedArray()
256
257
    override suspend fun tree(owner: String, name: String, ref: String, path: String): List<TreeEntry> =
258
        get(url("repos", owner, name, "tree", ref, *parts(path)), ListSerializer(TreeEntry.serializer()))
259
260
    override suspend fun file(owner: String, name: String, ref: String, path: String): String =
261
        call(request(url("repos", owner, name, "file", ref, *parts(path))).get().build(), notifyUnauthorized = true)
262
263
    override suspend fun history(owner: String, name: String, ref: String, path: String?, offset: Int, limit: Int): History =
264
        get(
265
            url("repos", owner, name, "history", ref) {
266
                path?.let { addQueryParameter("path", it) }
267
                addQueryParameter("offset", offset.toString())
268
                addQueryParameter("limit", limit.toString())
269
            },
270
            History.serializer(),
271
        )
272
273
    override suspend fun change(owner: String, name: String, hash: String): ChangeDetail =
274
        get(url("repos", owner, name, "changes", hash), ChangeDetail.serializer())
275
276
    override suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>> {
277
        val bookmarks = get(url("repos", owner, name, "bookmarks"), ListSerializer(NamedRef.serializer())).map { it.name }
278
        val tags = get(url("repos", owner, name, "tags"), ListSerializer(NamedRef.serializer())).map { it.name }
279
        return bookmarks to tags
280
    }
281
282
    override suspend fun userProposals(landable: Boolean): UserProposals =
283
        get(url("user", "proposals") { if (landable) addQueryParameter("landable", "true") }, UserProposals.serializer())
284
285
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
286
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
287
288
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
289
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
290
291
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
292
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
293
294
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
295
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
296
297
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
298
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
299
300
    override suspend fun markRead(id: Long) {
301
        send("POST", url("notifications", id.toString(), "read"))
302
    }
303
304
    override suspend fun markAllRead() {
305
        send("POST", url("notifications", "read"))
306
    }
307
308
    override suspend fun revokeToken() {
309
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
310
    }
311
312
    override suspend fun registerPush(fcmToken: String, publicKey: String): Boolean =
313
        sendJson("PUT", url("user", "push"), buildJsonObject {
314
            put("fcm_token", fcmToken)
315
            put("public_key", publicKey)
316
        }, PushRegistered.serializer()).alerts
317
318
    override suspend fun avatar(name: String): Avatar? {
319
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
320
        // A public picture: no token goes with it.
321
        val response = try {
322
            http.newCall(Request.Builder().url(url).get().build()).await()
323
        } catch (e: IOException) {
324
            throw HubException.Network(e)
325
        }
326
        response.use { r ->
327
            if (r.code == 404) return null
328
            val bytes = try {
329
                r.body?.bytes() ?: ByteArray(0)
330
            } catch (e: IOException) {
331
                throw HubException.Network(e)
332
            }
333
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
334
            return Avatar.parse(r.header("Content-Type"), bytes)
335
        }
336
    }
337
338
    // The bearer token is never part of a string anything prints.
339
    override fun toString(): String = "HubClient(${base})"
340
341
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
342
        val b = base.newBuilder()
343
        // Each segment is encoded on its own: an owner or name never adds a path level.
344
        segments.forEach { b.addPathSegment(it) }
345
        b.query()
346
        return b.build()
347
    }
348
349
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
350
351
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
352
        val body = call(request(url).get().build(), notifyUnauthorized = true)
353
        return try {
354
            HubJson.decodeFromString(serializer, body)
355
        } catch (e: IllegalArgumentException) {
356
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
357
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
358
        }
359
    }
360
361
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
362
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
363
        return call(request(url).method(method, body).build(), notifyUnauthorized)
364
    }
365
366
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
367
        val body = send(method, url)
368
        return try {
369
            HubJson.decodeFromString(serializer, body)
370
        } catch (e: IllegalArgumentException) {
371
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
372
        }
373
    }
374
375
    /** [json] as the body; the answer read with [serializer]. */
376
    private suspend fun <T> sendJson(method: String, url: HttpUrl, json: JsonObject, serializer: KSerializer<T>): T {
377
        val body = call(request(url).method(method, json.toString().toRequestBody(JsonMedia)).build(), notifyUnauthorized = true)
378
        return try {
379
            HubJson.decodeFromString(serializer, body)
380
        } catch (e: IllegalArgumentException) {
381
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
382
        }
383
    }
384
385
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
386
        .url(url)
387
        .header("Accept", "application/json")
388
        .header("Authorization", "Bearer $token")
389
390
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
391
        val response = try {
392
            http.newCall(request).await()
393
        } catch (e: IOException) {
394
            throw HubException.Network(e)
395
        }
396
        response.use { r ->
397
            val text = try {
398
                r.body?.string().orEmpty()
399
            } catch (e: IOException) {
400
                throw HubException.Network(e)
401
            }
402
            if (!r.isSuccessful) {
403
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
404
                throw HubException.Http(r.code, errorDetail(text))
405
            }
406
            return text
407
        }
408
    }
409
}