OXYGENHUB
# 74bbbc259910 oxygenhub-android / app / src / main / java / io / oxygenhub / android / api / HubClient.kt
8.6 KiB · last changed The phone as an OxygenFlow runner, first part (refs #8) 10 days ago source blame history raw
1
package io.oxygenhub.android.api
2
3
import kotlinx.serialization.KSerializer
4
import kotlinx.serialization.builtins.ListSerializer
5
import okhttp3.HttpUrl
6
import okhttp3.HttpUrl.Companion.toHttpUrl
7
import okhttp3.OkHttpClient
8
import okhttp3.Request
9
import okhttp3.RequestBody.Companion.toRequestBody
10
import java.io.IOException
11
12
/**
13
 * What the app asks of a hub, signed in. The view models see only this, so
14
 * their tests give them a fake. Later screens (oxygenhub-android#3–#5) add
15
 * to it: a repository's tree, history, proposals, runs.
16
 */
17
interface HubApi {
18
    /** The signed-in account (`GET /user`, scope `user:read`). */
19
    suspend fun user(): User
20
21
    /** Every repository the caller can read (`GET /repos`). */
22
    suspend fun repositories(): List<Repository>
23
24
    /** A repository's issues (`GET /repos/{owner}/{name}/issues?state=`). */
25
    suspend fun issues(owner: String, name: String, state: IssueState = IssueState.Open): List<Issue>
26
27
    /** The inbox: the unread count and the newest entries (`GET /notifications`). */
28
    suspend fun inbox(limit: Int = 50): Inbox
29
30
    /** Marks one notification read (`POST /notifications/{id}/read`). */
31
    suspend fun markRead(id: Long)
32
33
    /** Marks the whole inbox read (`POST /notifications/read`). */
34
    suspend fun markAllRead()
35
36
    /** Revokes the token this client signs in with (`DELETE /user/token`). */
37
    suspend fun revokeToken()
38
39
    /** The proposals the caller should act on, across repositories (the hub's dashboard). */
40
    suspend fun userProposals(): UserProposals
41
42
    /** A repository's proposals: open (with drafts), landed, closed or all. */
43
    suspend fun proposals(owner: String, name: String, state: ProposalState = ProposalState.Open): List<Proposal>
44
45
    suspend fun proposal(owner: String, name: String, number: Long): Proposal
46
47
    /** The checks on a proposal's projected state. */
48
    suspend fun checks(owner: String, name: String, number: Long): List<Check>
49
50
    /**
51
     * Land it (`repo:write`); the proposal as landed. The hub refuses with 409
52
     * and its reason when it may not land, and 403 when the token lacks the scope.
53
     */
54
    suspend fun land(owner: String, name: String, number: Long): Proposal
55
56
    /** Land it by itself when its checks pass, or not (`repo:write`); the proposal after. */
57
    suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal
58
59
    /** A one-time token registering this phone as a runner for the account's repositories (`repo:write`). */
60
    suspend fun runnerToken(): RunnerToken
61
62
    /** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */
63
    suspend fun avatar(name: String): Avatar?
64
}
65
66
/**
67
 * The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub
68
 * refuses the token (revoked on the web, or 90 days unused), so the app
69
 * can drop the session and ask for a new sign-in.
70
 */
71
class HubClient(
72
    hub: String,
73
    private val token: String,
74
    private val http: OkHttpClient,
75
    private val onUnauthorized: () -> Unit = {},
76
) : HubApi {
77
    private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl()
78
    private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl()
79
80
    override suspend fun user(): User = get("user", User.serializer())
81
82
    override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer()))
83
84
    override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> =
85
        get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer()))
86
87
    override suspend fun inbox(limit: Int): Inbox =
88
        get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer())
89
90
    override suspend fun runnerToken(): RunnerToken = send("POST", url("user", "runner-token"), RunnerToken.serializer())
91
92
    override suspend fun userProposals(): UserProposals = get("user/proposals", UserProposals.serializer())
93
94
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
95
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
96
97
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
98
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
99
100
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
101
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
102
103
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
104
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
105
106
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
107
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
108
109
    override suspend fun markRead(id: Long) {
110
        send("POST", url("notifications", id.toString(), "read"))
111
    }
112
113
    override suspend fun markAllRead() {
114
        send("POST", url("notifications", "read"))
115
    }
116
117
    override suspend fun revokeToken() {
118
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
119
    }
120
121
    override suspend fun avatar(name: String): Avatar? {
122
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
123
        // A public picture: no token goes with it.
124
        val response = try {
125
            http.newCall(Request.Builder().url(url).get().build()).await()
126
        } catch (e: IOException) {
127
            throw HubException.Network(e)
128
        }
129
        response.use { r ->
130
            if (r.code == 404) return null
131
            val bytes = try {
132
                r.body?.bytes() ?: ByteArray(0)
133
            } catch (e: IOException) {
134
                throw HubException.Network(e)
135
            }
136
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
137
            return Avatar.parse(r.header("Content-Type"), bytes)
138
        }
139
    }
140
141
    // The bearer token is never part of a string anything prints.
142
    override fun toString(): String = "HubClient(${base})"
143
144
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
145
        val b = base.newBuilder()
146
        // Each segment is encoded on its own: an owner or name never adds a path level.
147
        segments.forEach { b.addPathSegment(it) }
148
        b.query()
149
        return b.build()
150
    }
151
152
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
153
154
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
155
        val body = call(request(url).get().build(), notifyUnauthorized = true)
156
        return try {
157
            HubJson.decodeFromString(serializer, body)
158
        } catch (e: IllegalArgumentException) {
159
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
160
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
161
        }
162
    }
163
164
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
165
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
166
        return call(request(url).method(method, body).build(), notifyUnauthorized)
167
    }
168
169
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
170
        val body = send(method, url)
171
        return try {
172
            HubJson.decodeFromString(serializer, body)
173
        } catch (e: IllegalArgumentException) {
174
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
175
        }
176
    }
177
178
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
179
        .url(url)
180
        .header("Accept", "application/json")
181
        .header("Authorization", "Bearer $token")
182
183
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
184
        val response = try {
185
            http.newCall(request).await()
186
        } catch (e: IOException) {
187
            throw HubException.Network(e)
188
        }
189
        response.use { r ->
190
            val text = try {
191
                r.body?.string().orEmpty()
192
            } catch (e: IOException) {
193
                throw HubException.Network(e)
194
            }
195
            if (!r.isSuccessful) {
196
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
197
                throw HubException.Http(r.code, errorDetail(text))
198
            }
199
            return text
200
        }
201
    }
202
}