OXYGENHUB
# e2df27a81e5d oxygenhub-android / app / src / main / java / io / oxygenhub / android / api / HubClient.kt
8.1 KiB · last changed Land proposals from the phone (closes #17) 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
    /** A repository's proposals: open (with drafts), landed, closed or all. */
40
    suspend fun proposals(owner: String, name: String, state: ProposalState = ProposalState.Open): List<Proposal>
41
42
    suspend fun proposal(owner: String, name: String, number: Long): Proposal
43
44
    /** The checks on a proposal's projected state. */
45
    suspend fun checks(owner: String, name: String, number: Long): List<Check>
46
47
    /**
48
     * Land it (`repo:write`); the proposal as landed. The hub refuses with 409
49
     * and its reason when it may not land, and 403 when the token lacks the scope.
50
     */
51
    suspend fun land(owner: String, name: String, number: Long): Proposal
52
53
    /** Land it by itself when its checks pass, or not (`repo:write`); the proposal after. */
54
    suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal
55
56
    /** An account's picture (`/avatar/{name}`, public); null when the hub has none this app can draw. */
57
    suspend fun avatar(name: String): Avatar?
58
}
59
60
/**
61
 * The hub's JSON API over OkHttp. [onUnauthorized] runs when the hub
62
 * refuses the token (revoked on the web, or 90 days unused), so the app
63
 * can drop the session and ask for a new sign-in.
64
 */
65
class HubClient(
66
    hub: String,
67
    private val token: String,
68
    private val http: OkHttpClient,
69
    private val onUnauthorized: () -> Unit = {},
70
) : HubApi {
71
    private val base: HttpUrl = "${hub.trimEnd('/')}/api/v1/".toHttpUrl()
72
    private val root: HttpUrl = "${hub.trimEnd('/')}/".toHttpUrl()
73
74
    override suspend fun user(): User = get("user", User.serializer())
75
76
    override suspend fun repositories(): List<Repository> = get("repos", ListSerializer(Repository.serializer()))
77
78
    override suspend fun issues(owner: String, name: String, state: IssueState): List<Issue> =
79
        get(url("repos", owner, name, "issues") { addQueryParameter("state", state.query) }, ListSerializer(Issue.serializer()))
80
81
    override suspend fun inbox(limit: Int): Inbox =
82
        get(url("notifications") { addQueryParameter("limit", limit.coerceIn(1, 200).toString()) }, Inbox.serializer())
83
84
    override suspend fun proposals(owner: String, name: String, state: ProposalState): List<Proposal> =
85
        get(url("repos", owner, name, "proposals") { addQueryParameter("state", state.query) }, ListSerializer(Proposal.serializer()))
86
87
    override suspend fun proposal(owner: String, name: String, number: Long): Proposal =
88
        get(url("repos", owner, name, "proposals", number.toString()), Proposal.serializer())
89
90
    override suspend fun checks(owner: String, name: String, number: Long): List<Check> =
91
        get(url("repos", owner, name, "proposals", number.toString(), "checks"), ListSerializer(Check.serializer()))
92
93
    override suspend fun land(owner: String, name: String, number: Long): Proposal =
94
        send("POST", url("repos", owner, name, "proposals", number.toString(), "land"), Proposal.serializer())
95
96
    override suspend fun setAutoLand(owner: String, name: String, number: Long, on: Boolean): Proposal =
97
        send(if (on) "POST" else "DELETE", url("repos", owner, name, "proposals", number.toString(), "auto-land"), Proposal.serializer())
98
99
    override suspend fun markRead(id: Long) {
100
        send("POST", url("notifications", id.toString(), "read"))
101
    }
102
103
    override suspend fun markAllRead() {
104
        send("POST", url("notifications", "read"))
105
    }
106
107
    override suspend fun revokeToken() {
108
        send("DELETE", url("user", "token"), notifyUnauthorized = false)
109
    }
110
111
    override suspend fun avatar(name: String): Avatar? {
112
        val url = root.newBuilder().addPathSegment("avatar").addPathSegment(name).build()
113
        // A public picture: no token goes with it.
114
        val response = try {
115
            http.newCall(Request.Builder().url(url).get().build()).await()
116
        } catch (e: IOException) {
117
            throw HubException.Network(e)
118
        }
119
        response.use { r ->
120
            if (r.code == 404) return null
121
            val bytes = try {
122
                r.body?.bytes() ?: ByteArray(0)
123
            } catch (e: IOException) {
124
                throw HubException.Network(e)
125
            }
126
            if (!r.isSuccessful) throw HubException.Http(r.code, errorDetail(bytes.decodeToString()))
127
            return Avatar.parse(r.header("Content-Type"), bytes)
128
        }
129
    }
130
131
    // The bearer token is never part of a string anything prints.
132
    override fun toString(): String = "HubClient(${base})"
133
134
    private fun url(vararg segments: String, query: HttpUrl.Builder.() -> Unit = {}): HttpUrl {
135
        val b = base.newBuilder()
136
        // Each segment is encoded on its own: an owner or name never adds a path level.
137
        segments.forEach { b.addPathSegment(it) }
138
        b.query()
139
        return b.build()
140
    }
141
142
    private suspend fun <T> get(path: String, serializer: KSerializer<T>): T = get(url(*path.split('/').toTypedArray()), serializer)
143
144
    private suspend fun <T> get(url: HttpUrl, serializer: KSerializer<T>): T {
145
        val body = call(request(url).get().build(), notifyUnauthorized = true)
146
        return try {
147
            HubJson.decodeFromString(serializer, body)
148
        } catch (e: IllegalArgumentException) {
149
            // kotlinx.serialization's errors are IllegalArgumentExceptions.
150
            throw HubException.Unreadable("GET ${url.encodedPath}", e)
151
        }
152
    }
153
154
    private suspend fun send(method: String, url: HttpUrl, notifyUnauthorized: Boolean = true): String {
155
        val body = if (method == "DELETE") null else "{}".toRequestBody(JsonMedia)
156
        return call(request(url).method(method, body).build(), notifyUnauthorized)
157
    }
158
159
    private suspend fun <T> send(method: String, url: HttpUrl, serializer: KSerializer<T>): T {
160
        val body = send(method, url)
161
        return try {
162
            HubJson.decodeFromString(serializer, body)
163
        } catch (e: IllegalArgumentException) {
164
            throw HubException.Unreadable("$method ${url.encodedPath}", e)
165
        }
166
    }
167
168
    private fun request(url: HttpUrl): Request.Builder = Request.Builder()
169
        .url(url)
170
        .header("Accept", "application/json")
171
        .header("Authorization", "Bearer $token")
172
173
    private suspend fun call(request: Request, notifyUnauthorized: Boolean): String {
174
        val response = try {
175
            http.newCall(request).await()
176
        } catch (e: IOException) {
177
            throw HubException.Network(e)
178
        }
179
        response.use { r ->
180
            val text = try {
181
                r.body?.string().orEmpty()
182
            } catch (e: IOException) {
183
                throw HubException.Network(e)
184
            }
185
            if (!r.isSuccessful) {
186
                if (r.code == 401 && notifyUnauthorized) onUnauthorized()
187
                throw HubException.Http(r.code, errorDetail(text))
188
            }
189
            return text
190
        }
191
    }
192
}