aboutsummaryrefslogtreecommitdiff
path: root/Hutch/Views/Inbox/InboxViewModel.swift
blob: 1d4cfd3ea1551053c1a8a82ccc4c9e156e818692 (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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import Foundation
import os

private let inboxListLogger = Logger(subsystem: "net.cleberg.Hutch", category: "InboxList")

private struct InboxSubscriptionsResponse: Decodable, Sendable {
    let subscriptions: InboxSubscriptionPage
}

private struct InboxSubscriptionPage: Decodable, Sendable {
    let results: [InboxActivitySubscription]
    let cursor: String?
}

private struct InboxActivitySubscription: Decodable, Sendable {
    let id: Int
    let created: Date
    let list: InboxMailingListReference?

    enum CodingKeys: String, CodingKey {
        case id
        case created
        case list
    }
}

private struct InboxListThreadsResponse: Decodable, Sendable {
    let list: InboxMailingListThreads
}

private struct InboxMailingListThreads: Decodable, Sendable {
    let threads: InboxThreadPage
}

private struct InboxThreadPage: Decodable, Sendable {
    let results: [InboxThreadPayload]
    let cursor: String?
}

private struct InboxThreadPayload: Decodable, Sendable {
    let created: Date
    let updated: Date
    let subject: String
    let replies: Int
    let sender: Entity
    let root: InboxEmailPreview
}

private struct InboxEmailPreview: Decodable, Sendable {
    let id: Int
    let subject: String
    let date: Date?
    let received: Date
    let messageID: String
    let body: String
    let patch: InboxPatchPreview?
}

@Observable
@MainActor
final class InboxViewModel {
    private(set) var threads: [InboxThreadSummary] = []
    private(set) var isLoading = false
    var error: String?
    var searchText = ""

    private let client: SRHTClient
    private let listThreadFetchLimit = 10
    private let listFetchConcurrencyLimit = 4

    private static let subscriptionsQuery = """
    query inboxSubscriptions($cursor: Cursor) {
        subscriptions(cursor: $cursor) {
            results {
                ... on MailingListSubscription {
                    id
                    created
                    list {
                        id
                        rid
                        name
                        owner { canonicalName }
                    }
                }
            }
            cursor
        }
    }
    """

    private static let listThreadsQuery = """
    query inboxListThreads($rid: ID!, $cursor: Cursor) {
        list(rid: $rid) {
            threads(cursor: $cursor) {
                results {
                    created
                    updated
                    subject
                    replies
                    sender { canonicalName }
                    root {
                        id
                        subject
                        date
                        received
                        messageID
                        body
                        patch { subject }
                    }
                }
                cursor
            }
        }
    }
    """

    init(client: SRHTClient) {
        self.client = client
    }

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

        do {
            let subscriptions = try await fetchSubscriptions()
            let mailingLists = deduplicateMailingLists(subscriptions.compactMap(\.list))
            let fetchedThreads = try await fetchThreads(for: mailingLists)
            threads = fetchedThreads
                .filter(\.isUnread)
                .sorted { lhs, rhs in
                if lhs.lastActivityAt == rhs.lastActivityAt {
                    return lhs.subject.localizedCaseInsensitiveCompare(rhs.subject) == .orderedAscending
                }
                return lhs.lastActivityAt > rhs.lastActivityAt
            }
            NeedsAttentionSnapshotStore.update(unreadInboxThreads: threads.count)
        } catch {
            inboxListLogger.error("Inbox request failed")
            self.error = "Failed to load inbox"
        }
    }

    func markThreadRead(_ thread: InboxThreadSummary) {
        let viewedAt = max(Date(), thread.lastActivityAt)
        InboxReadStateStore.markViewed(viewedAt, for: thread.id)
        threads.removeAll { $0.id == thread.id }
        NeedsAttentionSnapshotStore.adjustUnreadInboxThreads(by: -1)
    }

    func markThreadUnread(_ thread: InboxThreadSummary) {
        InboxReadStateStore.markUnread(for: thread.id)
        updateThread(thread, isUnread: true)
        NeedsAttentionSnapshotStore.adjustUnreadInboxThreads(by: 1)
    }

    func toggleThreadReadState(_ thread: InboxThreadSummary) {
        if thread.isUnread {
            markThreadRead(thread)
        } else {
            markThreadUnread(thread)
        }
    }

    func thread(withID id: InboxThreadSummary.ID) -> InboxThreadSummary? {
        threads.first(where: { $0.id == id })
    }

    var filteredThreads: [InboxThreadSummary] {
        let q = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        guard !q.isEmpty else { return threads }
        return threads.filter {
            $0.displaySubject.lowercased().contains(q) ||
            $0.listName.lowercased().contains(q) ||
            $0.latestSender.canonicalName.lowercased().contains(q)
        }
    }

    private func fetchSubscriptions() async throws -> [InboxActivitySubscription] {
        var subscriptions: [InboxActivitySubscription] = []
        var cursor: String?

        while true {
            var variables: [String: any Sendable] = [:]
            if let cursor {
                variables["cursor"] = cursor
            }

            let response = try await client.execute(
                service: .lists,
                query: Self.subscriptionsQuery,
                variables: variables.isEmpty ? nil : variables,
                responseType: InboxSubscriptionsResponse.self
            )

            subscriptions.append(contentsOf: response.subscriptions.results)
            guard let nextCursor = response.subscriptions.cursor else {
                break
            }
            cursor = nextCursor
        }

        return subscriptions
    }

    private func fetchThreads(for mailingLists: [InboxMailingListReference]) async throws -> [InboxThreadSummary] {
        guard !mailingLists.isEmpty else { return [] }

        var summaries: [InboxThreadSummary] = []
        var startIndex = mailingLists.startIndex
        var failureMessages: [String] = []

        while startIndex < mailingLists.endIndex {
            let endIndex = mailingLists.index(
                startIndex,
                offsetBy: listFetchConcurrencyLimit,
                limitedBy: mailingLists.endIndex
            ) ?? mailingLists.endIndex
            let batch = Array(mailingLists[startIndex..<endIndex])

            let batchResult = await withTaskGroup(of: ([InboxThreadSummary], String?).self) { group in
                for mailingList in batch {
                    group.addTask {
                        do {
                            return (try await self.fetchThreads(for: mailingList), nil)
                        } catch {
                            return ([], "rid=\(mailingList.rid) error=\(error.localizedDescription)")
                        }
                    }
                }

                var batchSummaries: [InboxThreadSummary] = []
                var batchFailures: [String] = []
                for await result in group {
                    batchSummaries.append(contentsOf: result.0)
                    if let failure = result.1 {
                        batchFailures.append(failure)
                    }
                }
                return (batchSummaries, batchFailures)
            }

            summaries.append(contentsOf: batchResult.0)
            failureMessages.append(contentsOf: batchResult.1)
            for failure in batchResult.1 {
                inboxListLogger.error("Inbox thread list request failed: \(failure, privacy: .private)")
            }
            startIndex = endIndex
        }

        if summaries.isEmpty, let firstFailure = failureMessages.first {
            throw SRHTError.graphQLErrors([GraphQLError(message: firstFailure, locations: nil)])
        }

        return deduplicateThreads(summaries)
    }

    private func fetchThreads(for mailingList: InboxMailingListReference) async throws -> [InboxThreadSummary] {
        let response = try await client.execute(
            service: .lists,
            query: Self.listThreadsQuery,
            variables: ["rid": mailingList.rid],
            responseType: InboxListThreadsResponse.self
        )

        return response.list.threads.results.prefix(listThreadFetchLimit).map { thread in
            let groupingKey = "\(mailingList.rid)#\(thread.subject.replacingOccurrences(of: #"\s+"#, with: " ", options: .regularExpression).trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: #"^(?:(?:re|fwd?)\s*:\s*)+"#, with: "", options: [.regularExpression, .caseInsensitive]).lowercased())"
            let isUnread = InboxReadStateStore.isUnread(threadID: groupingKey, lastActivityAt: thread.updated)
            return InboxThreadSummary(
                rootEmailID: thread.root.id,
                rootMessageID: thread.root.messageID,
                threadRootEmailIDs: [thread.root.id],
                threadRootMessageIDs: [thread.root.messageID],
                listID: mailingList.id,
                listRID: mailingList.rid,
                listName: mailingList.name,
                listOwner: mailingList.owner,
                subject: thread.subject,
                latestSender: thread.sender,
                lastActivityAt: thread.updated,
                messageCount: thread.replies + 1,
                repo: Self.deriveRepositoryName(from: mailingList.name),
                containsPatch: thread.root.patch != nil || thread.subject.localizedCaseInsensitiveContains("[patch"),
                isUnread: isUnread
            )
        }
    }

    private func deduplicateThreads(_ threads: [InboxThreadSummary]) -> [InboxThreadSummary] {
        var grouped: [String: InboxThreadSummary] = [:]

        for thread in threads {
            guard let existing = grouped[thread.threadGroupingKey] else {
                grouped[thread.threadGroupingKey] = thread
                continue
            }

            let latest = thread.lastActivityAt >= existing.lastActivityAt ? thread : existing
            let mergedRootEmailIDs = Array(Set(existing.threadRootEmailIDs + thread.threadRootEmailIDs)).sorted()
            let mergedRootMessageIDs = Array(Set(existing.threadRootMessageIDs + thread.threadRootMessageIDs)).sorted()
            let mergedMessageCount = max(
                existing.messageCount ?? existing.threadRootMessageIDs.count,
                thread.messageCount ?? thread.threadRootMessageIDs.count,
                mergedRootMessageIDs.count
            )

            grouped[thread.threadGroupingKey] = InboxThreadSummary(
                rootEmailID: latest.rootEmailID,
                rootMessageID: latest.rootMessageID,
                threadRootEmailIDs: mergedRootEmailIDs,
                threadRootMessageIDs: mergedRootMessageIDs,
                listID: latest.listID,
                listRID: latest.listRID,
                listName: latest.listName,
                listOwner: latest.listOwner,
                subject: latest.subject,
                latestSender: latest.latestSender,
                lastActivityAt: max(existing.lastActivityAt, thread.lastActivityAt),
                messageCount: mergedMessageCount,
                repo: latest.repo ?? existing.repo,
                containsPatch: latest.containsPatch || existing.containsPatch,
                isUnread: latest.isUnread || existing.isUnread
            )
        }

        return grouped.values.sorted { lhs, rhs in
            if lhs.lastActivityAt == rhs.lastActivityAt {
                return lhs.displaySubject.localizedCaseInsensitiveCompare(rhs.displaySubject) == .orderedAscending
            }
            return lhs.lastActivityAt > rhs.lastActivityAt
        }
    }

    private func updateThread(_ thread: InboxThreadSummary, isUnread: Bool) {
        guard let index = threads.firstIndex(where: { $0.id == thread.id }) else { return }
        let current = threads[index]
        if !isUnread {
            threads.remove(at: index)
            return
        }
        threads[index] = InboxThreadSummary(
            rootEmailID: current.rootEmailID,
            rootMessageID: current.rootMessageID,
            threadRootEmailIDs: current.threadRootEmailIDs,
            threadRootMessageIDs: current.threadRootMessageIDs,
            listID: current.listID,
            listRID: current.listRID,
            listName: current.listName,
            listOwner: current.listOwner,
            subject: current.subject,
            latestSender: current.latestSender,
            lastActivityAt: current.lastActivityAt,
            messageCount: current.messageCount,
            repo: current.repo,
            containsPatch: current.containsPatch,
            isUnread: isUnread
        )
    }

    private func deduplicateMailingLists(_ mailingLists: [InboxMailingListReference]) -> [InboxMailingListReference] {
        var seen = Set<String>()
        return mailingLists.filter { mailingList in
            seen.insert(mailingList.rid).inserted
        }
    }

    nonisolated static func deriveRepositoryName(from listName: String) -> String? {
        let separators = ["-devel", "-patches", "-dev", ".patches"]
        for separator in separators where listName.hasSuffix(separator) {
            return String(listName.dropLast(separator.count))
        }
        return nil
    }
}