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
import Foundation
import SwiftUI
extension AppModel {
func loadProfileConnections(actorID: String, kind: ProfileConnectionKind, cursor: String?) async throws
-> ProfileConnectionsPage {
let session = sessionGeneration
guard account != nil, !isSigningOut else { throw CancellationError() }
let page = try await service.loadProfileConnections(actorID: actorID, kind: kind, cursor: cursor)
try Task.checkCancellation()
guard session == sessionGeneration, !isSigningOut else { throw CancellationError() }
return page
}
func loadProfileEdit() async throws -> EditableProfile {
guard let account, !isSigningOut else { throw ServiceError.noSession }
let session = moderationSession
let profile = try await service.loadProfileEdit(accountID: account.id)
guard session == moderationSession, self.account?.id == account.id, !isSigningOut else {
throw ServiceError.noSession
}
return profile
}
func saveProfileEdit(_ draft: ProfileEdit, original: EditableProfile) async throws {
guard let account, !isSigningOut else { throw ServiceError.noSession }
let session = moderationSession
let result = try await service.saveProfileEdit(draft, original: original, accountID: account.id)
let updated = result.account
guard session == moderationSession, self.account?.id == updated.id, !isSigningOut else {
throw ServiceError.noSession
}
profileLoadTasks[updated.id]?.task.cancel()
let revision = UUID()
profileEditRevision = revision
if account.avatarURL != updated.avatarURL || !account.isAvatarURLKnown {
signedInAvatar?.update(for: updated)
}
self.account = updated
if var profile = profiles[updated.id] {
let previous = profile.author
profile.author = Post.Author(
id: updated.id, name: updated.displayName, handle: updated.handle, avatarURL: updated.avatarURL,
moderationLabels: previous.moderationLabels, isFollowing: previous.isFollowing, bio: draft.bio)
profile.bio = draft.bio
if draft.links != original.draft.links {
profile.links = orderedProfileLinks(profile.links, ids: result.linkIDs)
}
storeProfile(profile, actorID: updated.id)
}
profileLoadedAt[updated.id] = .distantPast
Task { await refreshEditedProfile(result, bio: draft.bio, session: session, revision: revision) }
}
private func refreshEditedProfile(_ result: ProfileEditResult, bio: String, session: UUID, revision: UUID) async {
let account = result.account
guard let profile = try? await service.loadProfile(actorID: account.id),
moderationSession == session, profileEditRevision == revision, !isSigningOut,
profile.author.name == account.displayName, profile.bio == bio,
(profile.author.avatarURL == nil) == (account.avatarURL == nil)
else { return }
var refreshed = profile
refreshed.author.avatarURL = account.avatarURL
refreshed.links = orderedProfileLinks(profile.links, ids: result.linkIDs)
storeProfile(refreshed, actorID: account.id)
if refreshed.links.map(\.id) != result.linkIDs { profileLoadedAt[account.id] = .distantPast }
}
private func orderedProfileLinks(_ links: [Profile.Link], ids: [String]) -> [Profile.Link] {
ids.compactMap { id in links.first { $0.id == id } }
}
func loadProfile(actorID: String, forceRefresh: Bool = false) async {
guard !Task.isCancelled else { return }
let forceRefresh = forceRefresh || failedProfileRefreshIDs.contains(actorID)
if let pending = profileLoadTasks[actorID], pending.generation == contentGeneration {
await pending.task.value
guard forceRefresh, !pending.forceRefresh, pending.generation == contentGeneration,
!Task.isCancelled, !isSigningOut
else { return }
if profileLoadTasks[actorID]?.id == pending.id { profileLoadTasks[actorID] = nil }
await loadProfile(actorID: actorID, forceRefresh: true)
return
}
let id = UUID()
let task = Task { await self.loadProfileContents(actorID: actorID, forceRefresh: forceRefresh) }
profileLoadTasks[actorID] = ProfileLoadTask(
id: id, generation: contentGeneration, forceRefresh: forceRefresh, task: task)
await task.value
if profileLoadTasks[actorID]?.id == id { profileLoadTasks[actorID] = nil }
}
func loadProfileContents(actorID: String, forceRefresh: Bool) async {
guard !Task.isCancelled, loadingProfileIDs.insert(actorID).inserted else { return }
let forceRefresh = forceRefresh || failedProfileRefreshIDs.contains(actorID)
let request = UUID()
profileRequests[actorID] = request
if forceRefresh {
moreProfileRequests[actorID] = nil
loadingMoreProfileIDs.remove(actorID)
}
let generation = contentGeneration
defer {
if profileRequests[actorID] == request {
profileRequests[actorID] = nil
loadingProfileIDs.remove(actorID)
}
}
profileErrors[actorID] = nil
do {
guard
try await loadProfileHeader(
actorID: actorID, forceRefresh: forceRefresh,
generation: generation, request: request)
else { return }
if forceRefresh || authorPosts[actorID] == nil {
let page = excludingDeletedPosts(try await service.loadAuthorPosts(actorID: actorID, cursor: nil))
guard !Task.isCancelled else { return }
guard generation == contentGeneration, profileRequests[actorID] == request else {
profileRequestInterrupted(actorID: actorID, request: request)
return
}
applyProfilePage(page, actorID: actorID)
}
profileErrors[actorID] = nil
failedProfileRefreshIDs.remove(actorID)
} catch {
guard generation == contentGeneration, profileRequests[actorID] == request, !Task.isCancelled,
!NetworkFailure.isCancellation(error)
else { return }
profileErrors[actorID] = NetworkFailure.message(for: error)
failedProfileRefreshIDs.insert(actorID)
}
}
func retryProfilePosts(actorID: String) async {
if failedProfileRefreshIDs.contains(actorID) {
await loadProfile(actorID: actorID, forceRefresh: true)
} else {
await loadNextProfilePage(actorID: actorID)
}
}
func loadNextProfilePage(actorID: String) async {
guard let cursor = profileCursors[actorID],
!failedProfileRefreshIDs.contains(actorID),
!loadingProfileIDs.contains(actorID),
!loadingMoreProfileIDs.contains(actorID)
else { return }
loadingMoreProfileIDs.insert(actorID)
let request = UUID()
moreProfileRequests[actorID] = request
let generation = contentGeneration
profileErrors[actorID] = nil
defer {
if moreProfileRequests[actorID] == request {
moreProfileRequests[actorID] = nil
loadingMoreProfileIDs.remove(actorID)
}
}
do {
let page = excludingDeletedPosts(try await service.loadAuthorPosts(actorID: actorID, cursor: cursor))
guard generation == contentGeneration, moreProfileRequests[actorID] == request, !Task.isCancelled else {
return
}
withContentUpdates {
applyMutedPostIDs(page.mutedPostIDs)
updatePosts(postsForCacheUpdate(from: page), appending: page.posts)
var knownProfileIDs = Set(authorPosts[actorID, default: []].map(\.id))
let newProfilePosts = page.posts.filter { knownProfileIDs.insert($0.id).inserted }
if !newProfilePosts.isEmpty {
authorPosts[actorID, default: []].append(contentsOf: newProfilePosts.map { post(id: $0.id) ?? $0 })
}
let replies = replyContexts.merging(page.replyContexts) { _, new in new }
if replyContexts != replies { replyContexts = replies }
let reposts = profileRepostedBy[actorID, default: [:]].merging(page.repostedBy) { _, new in new }
if profileRepostedBy[actorID] != reposts { profileRepostedBy[actorID] = reposts }
profileCursors[actorID] = page.cursor
profileErrors[actorID] = nil
}
} catch {
guard generation == contentGeneration, moreProfileRequests[actorID] == request, !Task.isCancelled,
!NetworkFailure.isCancellation(error)
else { return }
profileErrors[actorID] = NetworkFailure.message(for: error)
}
}
func profile(actorID: String) -> Profile? { profiles[actorID] }
func posts(for actorID: String) -> [Post] {
let profilePosts = authorPosts[actorID] ?? posts.filter { $0.author.id == actorID }
return profilePosts.map { post(id: $0.id) ?? $0 }.filter {
!isHidden($0.author.id)
&& contentDecision(for: $0).map { !$0.ui(.contentList).filter && $0.action != .hide } == true
&& isRepostAuthorVisible(profileRepostedBy[actorID]?[$0.id])
}
}
private func profileRequestInterrupted(actorID: String, request: UUID) {
guard profileRequests[actorID] == request, !Task.isCancelled else { return }
profileErrors[actorID] = "The profile changed while it loaded. Try again."
failedProfileRefreshIDs.insert(actorID)
}
private func loadProfileHeader(actorID: String, forceRefresh: Bool, generation: UUID, request: UUID) async throws
-> Bool {
if forceRefresh || profiles[actorID] == nil
|| Date().timeIntervalSince(profileLoadedAt[actorID] ?? .distantPast) >= profileLifetime {
guard let profile = try await service.loadProfile(actorID: actorID) else {
guard !Task.isCancelled else { return false }
guard generation == contentGeneration, profileRequests[actorID] == request else {
profileRequestInterrupted(actorID: actorID, request: request)
return false
}
profileErrors[actorID] = "This profile could not be found."
failedProfileRefreshIDs.insert(actorID)
return false
}
guard !Task.isCancelled else { return false }
guard generation == contentGeneration, profileRequests[actorID] == request else {
profileRequestInterrupted(actorID: actorID, request: request)
return false
}
storeProfile(profile, actorID: actorID)
}
return true
}
private func storeProfile(_ profile: Profile, actorID: String) {
var currentProfile = profile
if let result = followResults[actorID] { currentProfile.isFollowing = result }
profiles[actorID] = currentProfile
profileLoadedAt[actorID] = Date()
if profiles.count > profileLimit, let oldest = profileLoadedAt.min(by: { $0.value < $1.value })?.key {
profiles[oldest] = nil
profileLoadedAt[oldest] = nil
}
if currentProfile.isFollowing {
followingActorIDs.insert(actorID)
} else {
followingActorIDs.remove(actorID)
}
}
private func applyProfilePage(_ page: FeedPage, actorID: String) {
withContentUpdates {
applyMutedPostIDs(page.mutedPostIDs)
updatePosts(
postsForCacheUpdate(from: page), appending: page.posts, mergingReplyContexts: page.replyContexts
)
profileCursors[actorID] = page.cursor
if authorPosts[actorID] != page.posts { authorPosts[actorID] = page.posts }
if profileRepostedBy[actorID] != page.repostedBy { profileRepostedBy[actorID] = page.repostedBy }
}
}
}