~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
212 lines · 9.5 KB Raw History
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
    }

}