summaryrefslogtreecommitdiff
path: root/Hutch/Views/Patchsets/PatchsetDetailViewModel.swift
blob: 88af3284dd18d6fc488c3aa97be6fed6f7574a56 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import Foundation

// MARK: - Response types (file-private to avoid @MainActor Decodable issues)

private struct PatchsetDetailResponse: Decodable, Sendable {
    let patchset: PatchsetDetailPayload?
}

private struct PatchsetDetailPayload: Decodable, Sendable {
    let id: Int
    let created: Date
    let updated: Date
    let subject: String
    let version: Int
    let prefix: String?
    let status: PatchsetStatus
    let submitter: Entity
    let coverLetter: PatchsetEmailPayload?
    let supersededBy: PatchsetReferencePayload?
    let supersedes: PatchsetReferencePayload?
    let patches: PatchsetPatchPage
    let tools: [PatchsetToolPayload]
    let mbox: URL?
}

private struct PatchsetReferencePayload: Decodable, Sendable {
    let id: Int
}

private struct PatchsetPatchPage: Decodable, Sendable {
    let results: [PatchsetEmailPayload]
    let cursor: String?
}

private struct PatchsetEmailPayload: Decodable, Sendable {
    let id: Int
    let subject: String
    let date: Date?
    let sender: Entity
    let body: String
    let patch: PatchIndexPayload?
}

private struct PatchIndexPayload: Decodable, Sendable {
    let index: Int?
    let count: Int?
}

private struct PatchsetToolPayload: Decodable, Sendable {
    let id: Int
    let icon: PatchsetToolIcon
    let details: String
}

private struct UpdatePatchsetResponse: Decodable, Sendable {
    let patchset: UpdatedPatchsetPayload?
}

private struct UpdatedPatchsetPayload: Decodable, Sendable {
    let status: PatchsetStatus
}

// MARK: - View Model

@Observable
@MainActor
final class PatchsetDetailViewModel {

    let patchsetID: Int

    private(set) var patchset: PatchsetDetail?
    private(set) var isLoading = false
    private(set) var isUpdatingStatus = false
    var error: String?

    private let client: SRHTClient

    init(patchsetID: Int, client: SRHTClient) {
        self.patchsetID = patchsetID
        self.client = client
    }

    // MARK: - Queries

    /// `patches` is paginated, but a series is small and reviewing half of one is
    /// worse than useless, so every page is walked before rendering.
    private static let detailQuery = """
    query patchset($id: Int!, $cursor: Cursor) {
        patchset(id: $id) {
            id
            created
            updated
            subject
            version
            prefix
            status
            submitter { canonicalName }
            supersededBy { id }
            supersedes { id }
            coverLetter {
                id
                subject
                date
                sender { canonicalName }
                body
                patch { index count }
            }
            patches(cursor: $cursor) {
                results {
                    id
                    subject
                    date
                    sender { canonicalName }
                    body
                    patch { index count }
                }
                cursor
            }
            tools { id icon details }
            mbox
        }
    }
    """

    private static let updateStatusMutation = """
    mutation updatePatchset($id: Int!, $status: PatchsetStatus!) {
        patchset: updatePatchset(id: $id, status: $status) {
            status
        }
    }
    """

    // MARK: - Loading

    func loadPatchset() async {
        guard !isLoading else { return }
        isLoading = true
        error = nil
        defer { isLoading = false }

        do {
            patchset = try await fetchPatchset()
        } catch {
            self.error = error.userFacingMessage
        }
    }

    private func fetchPatchset() async throws -> PatchsetDetail {
        var cursor: String?
        var payload: PatchsetDetailPayload?
        var patches: [PatchsetEmailPayload] = []

        // Walk the patches pages, keeping the first page's patchset fields.
        while true {
            var variables: [String: any Sendable] = ["id": patchsetID]
            if let cursor {
                variables["cursor"] = cursor
            }

            let response = try await client.execute(
                service: .lists,
                query: Self.detailQuery,
                variables: variables,
                responseType: PatchsetDetailResponse.self
            )

            guard let page = response.patchset else {
                throw SRHTError.graphQLErrors([
                    GraphQLError(message: "That patchset is no longer available.", locations: nil)
                ])
            }

            if payload == nil {
                payload = page
            }
            patches.append(contentsOf: page.patches.results)

            guard let next = page.patches.cursor, !next.isEmpty else { break }
            cursor = next
        }

        guard let payload else {
            throw SRHTError.graphQLErrors([
                GraphQLError(message: "That patchset is no longer available.", locations: nil)
            ])
        }

        return PatchsetDetail(
            id: payload.id,
            created: payload.created,
            updated: payload.updated,
            subject: payload.subject,
            version: payload.version,
            prefix: payload.prefix,
            status: payload.status,
            submitter: payload.submitter,
            coverLetter: payload.coverLetter.map { Self.makeEmail(from: $0, isPatch: false) },
            patches: Self.orderPatches(patches.map { Self.makeEmail(from: $0, isPatch: true) }),
            supersededBy: payload.supersededBy?.id,
            supersedes: payload.supersedes?.id,
            tools: payload.tools.map {
                PatchsetToolResult(id: $0.id, icon: $0.icon, details: $0.details)
            },
            mbox: payload.mbox
        )
    }

    // MARK: - Status

    /// Sets the review status. Returns true on success.
    @discardableResult
    func updateStatus(to newStatus: PatchsetStatus) async -> Bool {
        guard !isUpdatingStatus, let current = patchset else { return false }
        guard newStatus != current.status else { return true }

        isUpdatingStatus = true
        error = nil
        defer { isUpdatingStatus = false }

        do {
            let response = try await client.execute(
                service: .lists,
                query: Self.updateStatusMutation,
                variables: [
                    "id": patchsetID,
                    "status": newStatus.rawValue
                ],
                responseType: UpdatePatchsetResponse.self
            )

            // updatePatchset is nullable: null means the server declined without
            // erroring, so the local status must not be advanced.
            guard let updated = response.patchset else {
                self.error = "SourceHut did not apply that status change."
                return false
            }

            apply(status: updated.status)
            return true
        } catch {
            self.error = error.userFacingMessage
            return false
        }
    }

    private func apply(status: PatchsetStatus) {
        guard let current = patchset else { return }
        patchset = PatchsetDetail(
            id: current.id,
            created: current.created,
            updated: current.updated,
            subject: current.subject,
            version: current.version,
            prefix: current.prefix,
            status: status,
            submitter: current.submitter,
            coverLetter: current.coverLetter,
            patches: current.patches,
            supersededBy: current.supersededBy,
            supersedes: current.supersedes,
            tools: current.tools,
            mbox: current.mbox
        )
    }

    // MARK: - Mapping

    private nonisolated static func makeEmail(
        from payload: PatchsetEmailPayload,
        isPatch: Bool
    ) -> PatchsetEmail {
        PatchsetEmail(
            id: payload.id,
            subject: payload.subject,
            date: payload.date,
            sender: payload.sender,
            contentBlocks: InboxThreadUtilities.segmentMessageBody(payload.body, isPatch: isPatch),
            index: payload.patch?.index,
            count: payload.patch?.count
        )
    }

    /// Orders a series by its `[PATCH n/m]` index.
    ///
    /// sr.ht returns patches in receipt order, which is not series order when a
    /// contributor's mail arrives out of sequence. Patches without an index keep
    /// their relative position at the end rather than being dropped.
    nonisolated static func orderPatches(_ patches: [PatchsetEmail]) -> [PatchsetEmail] {
        let indexed = patches.filter { $0.index != nil }
        let unindexed = patches.filter { $0.index == nil }
        return indexed.sorted { ($0.index ?? 0) < ($1.index ?? 0) } + unindexed
    }
}