OXYGENHUB
# dfbc3e972872 oxygenhub-android / app / src / main / java / io / oxygenhub / android / api / HubClient.kt
18.0 KiB · last changed Releases and search on the phone (refs #3) 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 releases, newest first. */
73
    suspend fun releases(owner: String, name: String): List<Release>
74
75
    /** Issues and proposals matching [query], across the repositories the caller can read. */
76
    suspend fun search(query: String): List<SearchHit>
77
78
    /** A repository's runs, newest first. */
79
    suspend fun runs(owner: String, name: String): List<FlowRun>
80
81
    /** One run, with its jobs. */
82
    suspend fun run(owner: String, name: String, number: Long): FlowRun
83
84
    /** A job's log lines after [after] (0: from the start). */
85
    suspend fun jobLog(owner: String, name: String, number: Long, job: String, after: Long): List<LogLine>
86
87
    suspend fun rerunRun(owner: String, name: String, number: Long)
88
89
    /** Run [job] again in the same run, with the jobs that depend on it. */
90
    suspend fun rerunJob(owner: String, name: String, number: Long, job: String)
91
92
    suspend fun cancelRun(owner: String, name: String, number: Long)
93
94
    /** [owner]'s project boards the caller can see. */
95
    suspend fun projects(owner: String): List<Project>
96
97
    suspend fun board(owner: String, number: Long): Board
98
99
    /** Move a card to the column named [column]. */
100
    suspend fun moveCard(owner: String, number: Long, card: Long, column: String)
101
102
    suspend fun issueComments(owner: String, name: String, number: Long): List<Comment>
103
104
    suspend fun comment(owner: String, name: String, number: Long, body: String): Comment
105
106
    /** Close (with why: `completed` or `not_planned`) or reopen. */
107
    suspend fun setIssueState(owner: String, name: String, number: Long, open: Boolean, reason: String = "completed"): Issue
108
109
    suspend fun createIssue(owner: String, name: String, title: String, body: String): Issue
110
111
    /** The repository's labels, to choose from. */
112
    suspend fun labels(owner: String, name: String): List<Label>
113
114
    /** The issue's whole set of labels (triage). */
115
    suspend fun setIssueLabels(owner: String, name: String, number: Long, labels: List<String>): Issue
116
117
    /** One repository (`GET /repos/{owner}/{name}`): its default bookmark, for the code browser. */
118
    suspend fun repository(owner: String, name: String): Repository
119
120
    /** A directory of the tree at [ref] (a bookmark, tag or change), [path] "" for the top. */
121
    suspend fun tree(owner: String, name: String, ref: String, path: String = ""): List<TreeEntry>
122
123
    /** A file's bytes at [ref], as text. */
124
    suspend fun file(owner: String, name: String, ref: String, path: String): String
125
126
    /** [ref]'s history, newest first; only changes to [path] when given. */
127
    suspend fun history(owner: String, name: String, ref: String, path: String? = null, offset: Int = 0, limit: Int = 50): History
128
129
    suspend fun change(owner: String, name: String, hash: String): ChangeDetail
130
131
    /** The repository's bookmarks and tags, to browse at. */
132
    suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>>
133
134
    /** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */
135
    suspend fun avatar(name: String): Avatar?
136
}
137
138
/**
139
 * The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub
140
 * refuses the token (revoked on the web, or 90 days unused), so the app
141
 * can drop the session and ask for a new sign-in.
142
 */
143
class HubClient(
144
    hub: String,
145
    private val token: String,
146
    private val http: OkHttpClient,
147
    private val onUnauthorized: () -> Unit = {},
148
) : HubApi {
149
    private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl()
150
    private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl()
151
152
    override suspend fun user(): User = get("user", User.serializer())
153
154
    override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer()))
155
156
    override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> =
157
        get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer()))
158
159
    override suspend fun inbox(limit: Int): Inbox =
160
        get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer())
161
162
    override suspend fun runnerToken(): RunnerToken = send("POST", url("user", "runner-token"), RunnerToken.serializer())
163
164
    override suspend fun releases(owner: String, name: String): List<Release> =
165
        get(url("repos", owner, name, "releases"), ListSerializer(Release.serializer()))
166
167
    override suspend fun search(query: String): List<SearchHit> =
168
        get(url("search") { addQueryParameter("q", query) }, ListSerializer(SearchHit.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 repository(owner: String, name: String): Repository = get(url("repos", owner, name), Repository.serializer())
238
239
    private fun parts(path: String): Array<String> = path.split('/').filter { it.isNotEmpty() }.toTypedArray()
240
241
    override suspend fun tree(owner: String, name: String, ref: String, path: String): List<TreeEntry> =
242
        get(url("repos", owner, name, "tree", ref, *parts(path)), ListSerializer(TreeEntry.serializer()))
243
244
    override suspend fun file(owner: String, name: String, ref: String, path: String): String =
245
        call(request(url("repos", owner, name, "file", ref, *parts(path))).get().build(), notifyUnauthorized = true)
246
247
    override suspend fun history(owner: String, name: String, ref: String, path: String?, offset: Int, limit: Int): History =
248
        get(
249
            url("repos", owner, name, "history", ref) {
250
                path?.let { addQueryParameter("path", it) }
251
                addQueryParameter("offset", offset.toString())
252
                addQueryParameter("limit", limit.toString())
253
            },
254
            History.serializer(),
255
        )
256
257
    override suspend fun change(owner: String, name: String, hash: String): ChangeDetail =
258
        get(url("repos", owner, name, "changes", hash), ChangeDetail.serializer())
259
260
    override suspend fun refs(owner: String, name: String): Pair<List<String>, List<String>> {
261
        val bookmarks = get(url("repos", owner, name, "bookmarks"), ListSerializer(NamedRef.serializer())).map { it.name }
262
        val tags = get(url("repos", owner, name, "tags"), ListSerializer(NamedRef.serializer())).map { it.name }
263
        return bookmarks to tags
264
    }
265
266
    override suspend fun userProposals(landable: Boolean): UserProposals =
267
        get(url("user", "proposals") { if (landable) addQueryParameter("landable", "true") }, UserProposals.serializer())
268
269
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
270
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
271
272
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
273
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
274
275
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
276
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
277
278
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
279
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
280
281
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
282
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
283
284
    override suspend fun markRead(id: Long) {
285
        send("POST", url("notifications", id.toString(), "read"))
286
    }
287
288
    override suspend fun markAllRead() {
289
        send("POST", url("notifications", "read"))
290
    }
291
292
    override suspend fun revokeToken() {
293
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
294
    }
295
296
    override suspend fun avatar(name: String): Avatar? {
297
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
298
        // A public picture: no token goes with it.
299
        val response = try {
300
            http.newCall(Request.Builder().url(url).get().build()).await()
301
        } catch (e: IOException) {
302
            throw HubException.Network(e)
303
        }
304
        response.use { r ->
305
            if (r.code == 404) return null
306
            val bytes = try {
307
                r.body?.bytes() ?: ByteArray(0)
308
            } catch (e: IOException) {
309
                throw HubException.Network(e)
310
            }
311
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
312
            return Avatar.parse(r.header("Content-Type"), bytes)
313
        }
314
    }
315
316
    // The bearer token is never part of a string anything prints.
317
    override fun toString(): String = "HubClient(${base})"
318
319
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
320
        val b = base.newBuilder()
321
        // Each segment is encoded on its own: an owner or name never adds a path level.
322
        segments.forEach { b.addPathSegment(it) }
323
        b.query()
324
        return b.build()
325
    }
326
327
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
328
329
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
330
        val body = call(request(url).get().build(), notifyUnauthorized = true)
331
        return try {
332
            HubJson.decodeFromString(serializer, body)
333
        } catch (e: IllegalArgumentException) {
334
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
335
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
336
        }
337
    }
338
339
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
340
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
341
        return call(request(url).method(method, body).build(), notifyUnauthorized)
342
    }
343
344
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
345
        val body = send(method, url)
346
        return try {
347
            HubJson.decodeFromString(serializer, body)
348
        } catch (e: IllegalArgumentException) {
349
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
350
        }
351
    }
352
353
    /** [json] as the body; the answer read with [serializer]. */
354
    private suspend fun <T> sendJson(method: String, url: HttpUrl, json: JsonObject, serializer: KSerializer<T>): T {
355
        val body = call(request(url).method(method, json.toString().toRequestBody(JsonMedia)).build(), notifyUnauthorized = true)
356
        return try {
357
            HubJson.decodeFromString(serializer, body)
358
        } catch (e: IllegalArgumentException) {
359
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
360
        }
361
    }
362
363
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
364
        .url(url)
365
        .header("Accept", "application/json")
366
        .header("Authorization", "Bearer $token")
367
368
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
369
        val response = try {
370
            http.newCall(request).await()
371
        } catch (e: IOException) {
372
            throw HubException.Network(e)
373
        }
374
        response.use { r ->
375
            val text = try {
376
                r.body?.string().orEmpty()
377
            } catch (e: IOException) {
378
                throw HubException.Network(e)
379
            }
380
            if (!r.isSuccessful) {
381
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
382
                throw HubException.Http(r.code, errorDetail(text))
383
            }
384
            return text
385
        }
386
    }
387
}