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

geesawra.industries/old-fella

Old people's social media app

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

}