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
import Foundation
import SwiftUI
private struct NotificationPageBuffer {
var pendingPageStart: Bool
var acceptedPage = false
var nextCursor: String?
var collected: [FeedNotification] = []
var seen: Set<String>
var pageStarts: Set<String>
var requestedCursors: Set<String>
var visibleCandidate: [FeedNotification]
var candidatePreparation: Int
}
extension AppModel {
func applyingReadState(_ items: [FeedNotification]) -> [FeedNotification] {
guard let notificationsReadThrough else { return items }
return items.map { item in
var item = item
if item.indexedAt <= notificationsReadThrough { item.isRead = true }
return item
}
}
func markNotificationsRead(seenAt: Date = Date()) async throws {
let session = sessionGeneration
let moderation = moderationSession
while markingNotificationsRead {
await withCheckedContinuation { notificationReadWaiters.append($0) }
guard session == sessionGeneration, moderation == moderationSession, !isSigningOut else { return }
try Task.checkCancellation()
}
markingNotificationsRead = true
defer {
markingNotificationsRead = false
let waiters = notificationReadWaiters
notificationReadWaiters = []
for waiter in waiters { waiter.resume() }
}
let readThrough = max(notificationsReadThrough ?? .distantPast, seenAt)
try await service.markNotificationsRead(seenAt: readThrough)
guard session == sessionGeneration, moderation == moderationSession, !isSigningOut else { return }
notificationsReadThrough = readThrough
let updated = applyingReadState(notifications)
if notifications != updated { notifications = updated }
}
@discardableResult
func loadNotificationsIfNeeded() async -> Bool {
if let initialNotificationsTask { return await initialNotificationsTask.value }
if hasLoadedNotifications { return true }
let request = UUID()
initialNotificationsRequest = request
let task = Task { await self.loadNotifications() }
initialNotificationsTask = task
let accepted = await task.value
if request == initialNotificationsRequest { initialNotificationsTask = nil }
return accepted
}
@discardableResult
func loadNotifications() async -> Bool {
let session = sessionGeneration
while notificationsRequest != nil || moreNotificationsRequest != nil {
await withCheckedContinuation { notificationLoadWaiters.append($0) }
guard session == sessionGeneration, !Task.isCancelled else { return false }
}
guard !Task.isCancelled else { return false }
isLoadingNotifications = true
let request = UUID()
notificationsRequest = request
let generation = moderationSession
if notificationsErrorMessage != nil { notificationsErrorMessage = nil }
failedNotificationsPage = false
defer {
if notificationsRequest == request {
notificationsRequest = nil
if isLoadingNotifications { isLoadingNotifications = false }
resumeNotificationLoads()
}
}
return await fillNotifications(refresh: true, request: request, generation: generation)
}
func loadNextNotificationsPage() async {
guard moreNotificationsRequest == nil, notificationsRequest == nil,
!Task.isCancelled, hasMoreNotifications, notificationsCursor != nil
else { return }
isLoadingMoreNotifications = true
let request = UUID()
moreNotificationsRequest = request
let generation = moderationSession
notificationsErrorMessage = nil
defer {
if moreNotificationsRequest == request {
moreNotificationsRequest = nil
isLoadingMoreNotifications = false
resumeNotificationLoads()
}
}
_ = await fillNotifications(refresh: false, request: request, generation: generation)
}
func resumeNotificationLoads() {
let waiters = notificationLoadWaiters
notificationLoadWaiters = []
for waiter in waiters { waiter.resume() }
}
func fillNotifications(refresh: Bool, request: UUID, generation: UUID) async -> Bool {
let initialRows = refresh ? 0 : notificationGroups.count
var buffer = NotificationPageBuffer(
pendingPageStart: refresh ? false : (failedNotificationsPage ? notificationPendingPageStart : true),
nextCursor: refresh ? nil : notificationsCursor,
seen: refresh ? [] : Set(notifications.map(\.id)),
pageStarts: refresh ? [] : notificationPageStarts,
requestedCursors: refresh ? [] : notificationRequestedCursors,
visibleCandidate: refresh ? [] : visibleNotifications,
candidatePreparation: contentPreparationCount)
for _ in 0..<10 {
do {
try Task.checkCancellation()
let page = try await service.loadNotifications(cursor: buffer.nextCursor)
try Task.checkCancellation()
guard notificationsRequestIsCurrent(refresh: refresh, request: request, generation: generation)
else { return false }
acceptNotificationPage(page, buffer: &buffer, refresh: refresh)
let rows = NotificationGroup.make(from: buffer.visibleCandidate, pageStarts: buffer.pageStarts).count
if rows > initialRows || buffer.nextCursor == nil {
publishNotifications(buffer, refresh: refresh)
failedNotificationsPage = false
return true
}
} catch {
guard notificationsRequestIsCurrent(refresh: refresh, request: request, generation: generation)
else { return false }
if NetworkFailure.isCancellation(error) || Task.isCancelled { return false }
publishNotifications(buffer, refresh: refresh, keepingOldRows: true)
failedNotificationsPage = buffer.acceptedPage || !refresh
notificationsErrorMessage = NetworkFailure.message(for: error)
return buffer.acceptedPage
}
}
publishNotifications(buffer, refresh: refresh, keepingOldRows: true)
failedNotificationsPage = false
return buffer.acceptedPage
}
var showsNotificationsPlaceholder: Bool {
(isLoadingNotifications || isLoadingMoreNotifications
|| (!hasLoadedNotifications && notificationsErrorMessage == nil)) && !hasVisibleNotifications
}
var retryNotificationsPage: Bool { failedNotificationsPage }
private func publishNotifications(_ buffer: NotificationPageBuffer, refresh: Bool, keepingOldRows: Bool = false) {
guard buffer.acceptedPage else { return }
let fresh = applyingReadState(excludingDeletedPosts(buffer.collected))
let updated: [FeedNotification]
if refresh {
var ids = Set(fresh.map(\.id))
updated = fresh + (keepingOldRows ? notifications.filter { ids.insert($0.id).inserted } : [])
} else {
var ids = Set(notifications.map(\.id))
updated = notifications + fresh.filter { ids.insert($0.id).inserted }
}
withContentUpdates {
if notifications != updated { notifications = updated }
if notificationPageStarts != buffer.pageStarts { notificationPageStarts = buffer.pageStarts }
}
notificationRequestedCursors = buffer.requestedCursors
notificationPendingPageStart = buffer.pendingPageStart
notificationsCursor = buffer.nextCursor
if hasMoreNotifications != (buffer.nextCursor != nil) { hasMoreNotifications = buffer.nextCursor != nil }
if !hasLoadedNotifications { hasLoadedNotifications = true }
}
private func acceptNotificationPage(_ page: NotificationPage, buffer: inout NotificationPageBuffer, refresh: Bool) {
if let nextCursor = buffer.nextCursor { buffer.requestedCursors.insert(nextCursor) }
let added = excludingDeletedPosts(page.notifications).filter { buffer.seen.insert($0.id).inserted }
let visibleAdded: [FeedNotification]
if buffer.candidatePreparation != contentPreparationCount {
buffer.visibleCandidate = visibleNotifications(
in: (refresh ? buffer.collected : notifications + buffer.collected))
buffer.candidatePreparation = contentPreparationCount
}
visibleAdded = visibleNotifications(in: added)
buffer.collected.append(contentsOf: added)
buffer.visibleCandidate.append(contentsOf: visibleAdded)
if buffer.pendingPageStart, let firstVisible = visibleAdded.first {
buffer.pageStarts.insert(firstVisible.id)
buffer.pendingPageStart = false
}
buffer.acceptedPage = true
buffer.nextCursor = page.cursor.flatMap { buffer.requestedCursors.contains($0) ? nil : $0 }
}
private func notificationsRequestIsCurrent(refresh: Bool, request: UUID, generation: UUID) -> Bool {
guard generation == moderationSession, (refresh ? notificationsRequest : moreNotificationsRequest) == request
else {
if (refresh ? notificationsRequest : moreNotificationsRequest) == request {
notificationsErrorMessage = "Could not load notifications. Try again."
}
return false
}
return true
}
}