import Foundation import SwiftUI extension AppModel { func contentInputsChanged() { preparedContentNeedsUpdate = true if preparedContentUpdateDepth == 0 { prepareContent() } } func moderationInputsChanged() { moderationRevision = UUID() moderationDecisions.removeAll(keepingCapacity: true) moderationExpiryCandidates.removeAll(keepingCapacity: true) contentInputsChanged() } func withContentUpdates(_ update: () -> Void) { preparedContentUpdateDepth += 1 defer { preparedContentUpdateDepth -= 1 if preparedContentUpdateDepth == 0, preparedContentNeedsUpdate { prepareContent() } } update() } func prepareContent() { prepareCachedPosts() preparedContentNeedsUpdate = false contentPreparationCount += 1 let date = now() // Prepare rows before SwiftUI reads them. Loading state does not change these results. if moderationExpiry.map({ $0 <= date }) == true || preparedModerationTime.map({ date < $0 }) == true { moderationDecisions.removeAll(keepingCapacity: true) } preparedModerationTime = date preparedDecisionInputs = [] preparedPostDecisions.removeAll(keepingCapacity: true) preparedAuthorDecisions.removeAll(keepingCapacity: true) preparedQuoteDecisions.removeAll(keepingCapacity: true) let expiry = prepareModerationDecisions(date: date) prepareTimelineRows() prepareNotificationRows() preparePostViewStates() finishModerationPreparation(date: date, expiry: expiry) } private func prepareCachedPosts() { if hasCachedPosts != !posts.isEmpty { hasCachedPosts = !posts.isEmpty } let previousCachedIDs = Set(cachedPostsByID.keys) cachedPostsByID = postsByID for collection in [replyContexts, threadContexts, authorPosts, searchReplyContexts] { for key in collection.keys.sorted() { for post in collection[key] ?? [] where cachedPostsByID[post.id] == nil { cachedPostsByID[post.id] = post } } } for state in padStates.values { for post in state.posts + state.replyContexts.values.flatMap({ $0 }) where cachedPostsByID[post.id] == nil { cachedPostsByID[post.id] = post } } for post in searchPosts where cachedPostsByID[post.id] == nil { cachedPostsByID[post.id] = post } for savedPost in savedPosts { var post = cachedPostsByID[savedPost.id] ?? savedPost post.isSaved = true cachedPostsByID[post.id] = post } cacheNotificationPosts() if previousCachedIDs != Set(cachedPostsByID.keys) { postLookupRevision = UUID() } for (id, post) in cachedPostsByID where postViewStates[id] == nil { postViewStates[id] = PostViewState(post: post) } } private func prepareModerationDecisions(date: Date) -> Date? { var expiry = contentPreferences?.mutedWords.compactMap(\.expiresAt).filter { $0 > date }.min() func recordExpiry(_ labels: [ModerationPolicy.Label]) { for label in labels { if let end = label.expiresAt, end > date { expiry = min(expiry ?? end, end) } } } func prepare(author: Post.Author) { recordExpiry(author.moderationLabels) _ = contentDecision(author: author) } func prepare(post: Post) { recordExpiry(post.moderationLabels) _ = contentDecision(for: post) prepare(author: post.author) if let quote = post.quote, let author = quote.author { recordExpiry(quote.moderationLabels) prepare(author: author) } } preparePostCollections(preparePost: { prepare(post: $0) }, prepareAuthor: { prepare(author: $0) }) prepareAuthorCollections(preparePost: { prepare(post: $0) }, prepareAuthor: { prepare(author: $0) }) return expiry } private func preparePostCollections(preparePost: (Post) -> Void, prepareAuthor: (Post.Author) -> Void) { for post in posts { preparePost(post) } for post in searchPosts { preparePost(post) } for post in savedPosts { preparePost(post) } for author in searchAccounts { prepareAuthor(author) } for state in padStates.values { for post in state.posts + state.replyContexts.values.flatMap({ $0 }) { preparePost(post) } for author in state.repostedBy.values { prepareAuthor(author) } } for collection in [replyContexts, threadContexts, authorPosts, searchReplyContexts] { for context in collection.values { for post in context { preparePost(post) } } } } private func prepareAuthorCollections(preparePost: (Post) -> Void, prepareAuthor: (Post.Author) -> Void) { for author in repostedBy.values { prepareAuthor(author) } for author in searchRepostedBy.values { prepareAuthor(author) } for authors in profileRepostedBy.values { for author in authors.values { prepareAuthor(author) } } for profile in profiles.values { prepareAuthor(profile.author) } for notification in notifications { prepareAuthor(notification.author) if let post = notification.relatedPost { preparePost(post) } if let post = notification.parentPost { preparePost(post) } } } private func prepareTimelineRows() { let timeline = filteredTimelinePosts() if timelinePosts != timeline { timelinePosts = timeline } let rowIDs = timeline.map(\.id) if timelineRowIDs != rowIDs { timelineRows = timeline.map { postViewState(for: $0) } } for state in padStates.values { let visiblePosts = filteredFeedPosts(state.posts, contexts: state.replyContexts, reposts: state.repostedBy) if state.rowIDs != visiblePosts.map(\.id) { state.rows = visiblePosts.map { postViewState(for: $0) } } } } private func prepareNotificationRows() { let visible = visibleNotifications(in: notifications) if visibleNotifications != visible { visibleNotifications = visible } let groups = NotificationGroup.make(from: visible, pageStarts: notificationPageStarts) if notificationGroups != groups { notificationGroups = groups } let previousRows = Dictionary(uniqueKeysWithValues: notificationRows.map { ($0.id, $0) }) let rows = groups.map { group in let row = previousRows[group.id] ?? NotificationGroupState(group: group) row.update(group: group) return row } if notificationRows.map(\.id) != rows.map(\.id) { notificationRows = rows } if hasVisibleNotifications != !visible.isEmpty { hasVisibleNotifications = !visible.isEmpty } let unread = visible.contains { !$0.isRead } if hasUnreadNotifications != unread { hasUnreadNotifications = unread } } private func preparePostViewStates() { for id in postViewStates.keys { updatePostViewState(id: id) } for state in postViewStates.values { state.updateReplyContext(resolvedReplyContext(for: state.post)) } postViewStates = postViewStates.filter { cachedPostsByID[$0.key] != nil } } private func finishModerationPreparation(date: Date, expiry originalExpiry: Date?) { var expiry = originalExpiry let usedInputs = preparedDecisionInputs ?? [] moderationDecisions = moderationDecisions.filter { usedInputs.contains($0.key) } moderationExpiryCandidates = moderationExpiryCandidates.filter { moderationDecisions[$0.key] != nil && $0.value > date } if let cachedExpiry = moderationExpiryCandidates.values.min() { expiry = min(expiry ?? cachedExpiry, cachedExpiry) } preparedDecisionInputs = nil scheduleModerationExpiry(expiry) } func scheduleModerationExpiry(_ expiry: Date?) { guard expiry != moderationExpiry else { return } moderationExpiryTask?.cancel() moderationExpiry = expiry guard let expiry else { moderationExpiryTask = nil return } let delay = max(0, expiry.timeIntervalSince(now())) moderationExpiryTask = Task { [weak self] in do { try await Task.sleep(for: .seconds(delay)) } catch { return } guard let self else { return } self.refreshExpiredModeration() } } func refreshExpiredModeration() { let date = now() guard moderationExpiry.map({ $0 <= date }) == true || preparedModerationTime.map({ date < $0 }) == true else { return } moderationInputsChanged() } private func cacheNotificationPosts() { for notification in notifications { for post in [notification.relatedPost, notification.parentPost].compactMap({ $0 }) where cachedPostsByID[post.id] == nil { cachedPostsByID[post.id] = post } } } }