OXYGENHUB

Coverage / app/src/main/java/io/oxygenhub/android/api/Models.kt 87.9%

268 of 305 lines run, 127 of 212 functions, 20 of 36 branches · run #1623 on main · run missed

1
package io.oxygenhub.android.api
2
3
import kotlinx.serialization.SerialName
4
import kotlinx.serialization.Serializable
5
6
// The hub's JSON, by hand from oxygenhub's crates/hub-api/src/lib.rs (and
7
// the device flow's answers in crates/hub/src/api/device.rs). Field names
8
// are the hub's own, snake case; times are milliseconds since the epoch.
9
// Every field has a default, so an added or missing field never breaks the
10
// app: the hub's types may still change before 1.0.
11
12
/** `GET /api/v1/user`. */
13
@Serializable
14
data class User(
15
    val username: String,
16
    @SerialName("display_name") val displayName: String = "",
17
    @SerialName("is_admin") val isAdmin: Boolean = false,
18
    val keys: List<String> = emptyList(),
19
    @SerialName("created_ms") val createdMs: Long = 0,
20
) {
21
    /** The name to greet: the display name, or the username without one. */
22
    val shownName: String get() = displayName.ifBlank { username }
23
}
24
25
@Serializable
26
enum class Visibility {
27
    @SerialName("public") Public,
28
    @SerialName("internal") Internal,
29
    @SerialName("private") Private,
30
}
31
32
/** A repository as `GET /api/v1/repos` lists it. */
33
@Serializable
34
data class Repository(
35
    val owner: String,
36
    val name: String,
37
    val description: String = "",
38
    @SerialName("default_bookmark") val defaultBookmark: String = "main",
39
    val visibility: Visibility = Visibility.Public,
40
    @SerialName("created_ms") val createdMs: Long = 0,
41
    @SerialName("updated_ms") val updatedMs: Long = 0,
42
    @SerialName("clone_url") val cloneUrl: String = "",
43
) {
44
    val slug: String get() = "$owner/$name"
45
}
46
47
@Serializable
48
data class Label(
49
    val name: String,
50
    /** `#rrggbb`. */
51
    val colour: String = "",
52
    val description: String = "",
53
)
54
55
/** `GET /api/v1/repos/{owner}/{name}/issues`. */
56
@Serializable
57
data class Issue(
58
    val number: Long,
59
    val title: String,
60
    val body: String = "",
61
    val author: String = "",
62
    /** `open` or `closed`. */
63
    val state: String = "open",
64
    /** Why it closed: `completed`, `not_planned`, … (empty while open). */
65
    val reason: String = "",
66
    val labels: List<Label> = emptyList(),
67
    val assignees: List<String> = emptyList(),
68
    val milestone: String? = null,
69
    val comments: Long = 0,
70
    val locked: Boolean = false,
71
    val pinned: Boolean = false,
72
    @SerialName("created_ms") val createdMs: Long = 0,
73
    @SerialName("updated_ms") val updatedMs: Long = 0,
74
    @SerialName("closed_ms") val closedMs: Long? = null,
75
    val url: String = "",
76
) {
77
    val isOpen: Boolean get() = state == "open"
78
}
79
80
/** A release of a repository: its tag, notes and files. */
81
@Serializable
82
data class Release(
83
    val tag: String,
84
    val title: String = "",
85
    val notes: String = "",
86
    val prerelease: Boolean = false,
87
    val latest: Boolean = false,
88
    val author: String = "",
89
    val signer: String? = null,
90
    val assets: List<ReleaseAsset> = emptyList(),
91
    @SerialName("created_ms") val createdMs: Long = 0,
92
    val url: String = "",
93
)
94
95
@Serializable
96
data class ReleaseAsset(val name: String, val size: Long = 0, val hash: String = "", val downloads: Long = 0, val url: String = "")
97
98
/** An issue or proposal search found (`GET /search?q=`). */
99
@Serializable
100
data class SearchHit(
101
    /** `issue` or `proposal`. */
102
    val kind: String = "issue",
103
    val repository: String = "",
104
    val number: Long = 0,
105
    val title: String = "",
106
    val snippet: String = "",
107
) {
108
    val owner: String get() = repository.substringBefore('/')
109
    val name: String get() = repository.substringAfter('/')
110
}
111
112
/** A Flow run of a repository's pipeline (#5). */
113
@Serializable
114
data class FlowRun(
115
    val number: Long,
116
    val bookmark: String = "",
117
    /** `queued`, `running`, `passed`, `failed`, `error` or `cancelled`. */
118
    val status: String = "queued",
119
    /** `push`, `manual`, `schedule`, `proposal` or `rerun:N`. */
120
    val trigger: String = "",
121
    val actor: String = "",
122
    val error: String = "",
123
    @SerialName("created_ms") val createdMs: Long = 0,
124
    @SerialName("finished_ms") val finishedMs: Long? = null,
125
    val url: String = "",
126
    @SerialName("queue_position") val queuePosition: Long? = null,
127
    val jobs: List<FlowJob> = emptyList(),
128
) {
129
    val live: Boolean get() = status == "queued" || status == "running"
130
}
131
132
/** A job of a run. */
133
@Serializable
134
data class FlowJob(
135
    val name: String,
136
    val status: String = "queued",
137
    @SerialName("depends_on") val dependsOn: List<String> = emptyList(),
138
    val runner: String = "",
139
    @SerialName("exit_code") val exitCode: Long? = null,
140
    val error: String = "",
141
    @SerialName("started_ms") val startedMs: Long? = null,
142
    @SerialName("finished_ms") val finishedMs: Long? = null,
143
    @SerialName("log_lines") val logLines: Long = 0,
144
    val waiting: String = "",
145
) {
146
    val live: Boolean get() = status == "queued" || status == "running"
147
148
    /** How long it ran, or has been running, in seconds. */
149
    fun seconds(now: Long = System.currentTimeMillis()): Long? = startedMs?.let { ((finishedMs ?: now) - it) / 1000 }
150
}
151
152
/** A line of a job's log: `stdout`, `stderr` or `flow` (the runner's own). */
153
@Serializable
154
data class LogLine(val seq: Long, val t: Long = 0, val stream: String = "stdout", val text: String = "")
155
156
/** A project board's summary (`GET /projects/{owner}`). */
157
@Serializable
158
data class Project(
159
    val owner: String,
160
    val number: Long,
161
    val title: String = "",
162
    val description: String = "",
163
    val public: Boolean = true,
164
    val closed: Boolean = false,
165
    @SerialName("updated_ms") val updatedMs: Long = 0,
166
    val url: String = "",
167
)
168
169
/** A card on a board: an issue, a proposal or a note. */
170
@Serializable
171
data class ProjectCard(
172
    val id: Long,
173
    /** `issue`, `proposal` or `note`. */
174
    val kind: String = "note",
175
    /** `owner/name#N`; empty for a note. */
176
    val reference: String = "",
177
    val title: String = "",
178
    val state: String = "",
179
    val labels: List<String> = emptyList(),
180
    val assignees: List<String> = emptyList(),
181
) {
182
    /** The repository and number a card refers to, or null for a note. */
183
    val target: Triple<String, String, Long>? get() {
184
        val slug = reference.substringBefore('#', "")
185
        val n = reference.substringAfter('#', "").toLongOrNull() ?: return null
186
        val (owner, name) = slug.split('/').takeIf { it.size == 2 } ?: return null
187
        return Triple(owner, name, n)
188
    }
189
}
190
191
@Serializable
192
data class ProjectColumn(val id: Long, val name: String, val cards: List<ProjectCard> = emptyList())
193
194
/** A board, its columns in order (`GET /projects/{owner}/{n}`). */
195
@Serializable
196
data class Board(val project: Project, val columns: List<ProjectColumn> = emptyList())
197
198
/** A comment on an issue or proposal. */
199
@Serializable
200
data class Comment(
201
    val id: Long = 0,
202
    val author: String = "",
203
    val body: String = "",
204
    @SerialName("created_ms") val createdMs: Long = 0,
205
)
206
207
/** Which issues to list: the hub's `?state=`. */
208
enum class IssueState(val query: String) { Open("open"), Closed("closed"), All("all") }
209
210
/**
211
 * A proposal (`GET /api/v1/repos/{owner}/{name}/proposals`, `…/proposals/{n}`):
212
 * changes asking to join a target bookmark. The hub decides whether it may
213
 * land, and says why not in [blockers], in its own words.
214
 */
215
@Serializable
216
data class Proposal(
217
    val number: Long,
218
    val title: String,
219
    val body: String = "",
220
    val author: String = "",
221
    /** `draft`, `open`, `landed` or `closed`. */
222
    val state: String = "open",
223
    /** The bookmark it lands on. */
224
    val target: String = "main",
225
    /** The changes it adds, in dependency order, newest last. */
226
    val changes: List<ProposalChange> = emptyList(),
227
    val conflicted: Boolean = false,
228
    val approvals: List<Approval> = emptyList(),
229
    val landable: Boolean = false,
230
    val blockers: List<String> = emptyList(),
231
    @SerialName("created_ms") val createdMs: Long = 0,
232
    @SerialName("updated_ms") val updatedMs: Long = 0,
233
    val url: String = "",
234
    val landed: Landed? = null,
235
    /** Who set it to land by itself when its checks pass, while set. */
236
    @SerialName("auto_land") val autoLand: String? = null,
237
    @SerialName("requested_reviewers") val requestedReviewers: List<String> = emptyList(),
238
    val labels: List<Label> = emptyList(),
239
) {
240
    val isOpen: Boolean get() = state == "open" || state == "draft"
241
    val isDraft: Boolean get() = state == "draft"
242
}
243
244
/** `GET /api/v1/user/proposals`: the proposals to act on, as the hub's dashboard lists them. */
245
@Serializable
246
data class UserProposals(
247
    /** Open ones by others in the caller's repositories, not yet reviewed by them. */
248
    val review: List<ProposalBrief> = emptyList(),
249
    /** The caller's own open ones and drafts. */
250
    val authored: List<ProposalBrief> = emptyList(),
251
    /** Asked for with `landable=true`: open ones the caller can land now. */
252
    val landable: List<ProposalBrief> = emptyList(),
253
)
254
255
/** An organisation (`GET /orgs/{name}`). */
256
@Serializable
257
data class Organisation(
258
    val name: String,
259
    @SerialName("display_name") val displayName: String = "",
260
    val description: String = "",
261
    val members: List<String> = emptyList(),
262
)
263
264
/** An account or an organisation, as its page shows it. */
265
sealed interface Owner {
266
    val name: String
267
    val shownName: String
268
269
    data class Person(val user: User) : Owner {
270
        override val name get() = user.username
271
        override val shownName get() = user.shownName
272
    }
273
274
    data class Org(val org: Organisation) : Owner {
275
        override val name get() = org.name
276
        override val shownName get() = org.displayName.ifBlank { org.name }
277
    }
278
}
279
280
/** A proposal in a list across repositories. */
281
@Serializable
282
data class ProposalBrief(
283
    /** `owner/name`. */
284
    val repository: String,
285
    val number: Long,
286
    val title: String = "",
287
    val author: String = "",
288
    val state: String = "open",
289
    val conflicted: Boolean = false,
290
    @SerialName("updated_ms") val updatedMs: Long = 0,
291
    val url: String = "",
292
) {
293
    val owner: String get() = repository.substringBefore('/')
294
    val name: String get() = repository.substringAfter('/')
295
}
296
297
/** `POST /api/v1/user/runner-token`: a one-time token that registers a runner for [owner]'s repositories. */
298
@Serializable
299
data class RunnerToken(val token: String, val owner: String = "") {
300
    // The token is a secret until it is used.
301
    override fun toString(): String = "RunnerToken(owner=$owner, token=<redacted>)"
302
}
303
304
/** A change a proposal adds. */
305
@Serializable
306
data class ProposalChange(
307
    val hash: String,
308
    val message: String = "",
309
    /** One that nothing else in the proposal depends on. */
310
    val head: Boolean = false,
311
) {
312
    /** The message's first line. */
313
    val subject: String get() = message.lineSequence().firstOrNull().orEmpty()
314
}
315
316
/** A file or directory of a repository's tree at some reference (the code browser, #3). */
317
@Serializable
318
data class TreeEntry(
319
    val name: String,
320
    val path: String,
321
    /** `file`, `dir`, `symlink` or `subrepo`. */
322
    val kind: String = "file",
323
    val exec: Boolean = false,
324
    val size: Long? = null,
325
    val conflicted: Boolean = false,
326
) {
327
    val isDir: Boolean get() = kind == "dir"
328
}
329
330
/** Who made a change, as the hub knows them. */
331
@Serializable
332
data class ChangeAuthor(val name: String = "", val email: String = "", val account: String? = null)
333
334
/** A change in a history or a proposal. */
335
@Serializable
336
data class ChangeSummary(
337
    val hash: String,
338
    val message: String = "",
339
    val author: ChangeAuthor = ChangeAuthor(),
340
    @SerialName("when_ms") val whenMs: Long = 0,
341
) {
342
    val subject: String get() = message.lineSequence().firstOrNull().orEmpty()
343
    val short: String get() = hash.take(12)
344
}
345
346
/** A page of a reference's history (`GET …/history/{r}`), newest first. */
347
@Serializable
348
data class History(
349
    val reference: String = "",
350
    val total: Int = 0,
351
    val offset: Int = 0,
352
    val changes: List<ChangeSummary> = emptyList(),
353
)
354
355
/** A file a change touched, and how. */
356
@Serializable
357
data class FileChange(
358
    val path: String,
359
    /** `added`, `modified`, `removed` or `renamed`. */
360
    val kind: String = "modified",
361
    val from: String? = null,
362
    val added: Int = 0,
363
    val removed: Int = 0,
364
    /** The diff with three lines of context (hub #320), cut at 2000 lines. */
365
    val lines: List<DiffLine> = emptyList(),
366
    val truncated: Boolean = false,
367
)
368
369
/** A line of a file's diff: `context`, `add`, `del`, or `gap` for lines left out between hunks. */
370
@Serializable
371
data class DiffLine(
372
    val kind: String = "context",
373
    val old: Int? = null,
374
    val new: Int? = null,
375
    val text: String = "",
376
)
377
378
/** One change, whole (`GET …/changes/{hash}`). */
379
@Serializable
380
data class ChangeDetail(
381
    val change: ChangeSummary,
382
    val body: String = "",
383
    @SerialName("in_bookmarks") val inBookmarks: List<String> = emptyList(),
384
    @SerialName("in_tags") val inTags: List<String> = emptyList(),
385
    val files: List<FileChange> = emptyList(),
386
)
387
388
/** A bookmark or tag to browse at. */
389
@Serializable
390
data class NamedRef(val name: String)
391
392
/** A reviewer's approval; it counts only when [sealed] (a seal over every change, by a key linked to them). */
393
@Serializable
394
data class Approval(val account: String, val sealed: Boolean = false)
395
396
/** Who landed a proposal, how (`web`, or `api (token NAME)`), and when. */
397
@Serializable
398
data class Landed(val by: String, val via: String = "", @SerialName("when_ms") val whenMs: Long = 0)
399
400
/** Which proposals to list. `Open` includes drafts, as the hub's own list does. */
401
enum class ProposalState(val query: String) { Open("open"), Landed("landed"), Closed("closed"), All("all") }
402
403
/** A check on a state (`GET …/proposals/{n}/checks`): a Flow job, or another reporter's. */
404
@Serializable
405
data class Check(
406
    val name: String,
407
    /** `queued`, `running`, `passed`, `failed`, `cancelled` or `skipped`. */
408
    val status: String = "queued",
409
    val summary: String = "",
410
    val url: String = "",
411
    @SerialName("started_ms") val startedMs: Long = 0,
412
    @SerialName("finished_ms") val finishedMs: Long? = null,
413
)
414
415
/** One entry in the caller's inbox. */
416
@Serializable
417
data class Notification(
418
    val id: Long,
419
    @SerialName("at_ms") val atMs: Long = 0,
420
    /** `issue.opened`, `proposal.comment`, `mention`, `review`, … */
421
    val kind: String = "",
422
    val title: String = "",
423
    /** The page on the hub, absolute. */
424
    val url: String = "",
425
    val actor: String = "",
426
    val read: Boolean = false,
427
)
428
429
/** `GET /api/v1/notifications`: the unread count and the newest entries, unread first. */
430
@Serializable
431
data class Inbox(
432
    val unread: Long = 0,
433
    val items: List<Notification> = emptyList(),
434
)
435
436
/** An RFC 7807 problem: what the API answers with on an error. */
437
@Serializable
438
data class Problem(
439
    val status: Int = 0,
440
    val title: String = "",
441
    val detail: String = "",
442
)
443
444
/** The device flow's errors, RFC 8628's shape: `{"error": …, "error_description": …}`. */
445
@Serializable
446
data class OAuthError(
447
    val error: String = "",
448
    @SerialName("error_description") val description: String = "",
449
)
450
451
/** `POST /api/v1/device/code`'s answer. */
452
@Serializable
453
data class DeviceCode(
454
    @SerialName("device_code") val deviceCode: String,
455
    @SerialName("user_code") val userCode: String,
456
    @SerialName("verification_uri") val verificationUri: String,
457
    @SerialName("verification_uri_complete") val verificationUriComplete: String = "",
458
    @SerialName("expires_in") val expiresIn: Long = 900,
459
    val interval: Long = 5,
460
) {
461
    /** The page to open: with the code filled in when the hub offers it. */
462
    val pageToOpen: String get() = verificationUriComplete.ifBlank { verificationUri }
463
464
    // The device code is a secret until it is used: never in logs.
465
    override fun toString(): String = "DeviceCode(userCode=$userCode, verificationUri=$verificationUri)"
466
}
467
468
/** `POST /api/v1/device/token`'s answer once the user approved. */
469
@Serializable
470
data class TokenGrant(
471
    @SerialName("access_token") val accessToken: String,
472
    @SerialName("token_type") val tokenType: String = "bearer",
473
    /** The scopes the user allowed, space separated (they may untick some). */
474
    val scope: String = "",
475
    val username: String = "",
476
    @SerialName("expires_in") val expiresIn: Long = 0,
477
) {
478
    val scopes: List<String> get() = scope.split(' ').filter { it.isNotBlank() }
479
480
    override fun toString(): String = "TokenGrant(username=$username, scope=$scope, accessToken=<redacted>)"
481
}