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

geesawra.industries/old-fella

Old people's social media app

0
1
main
103 lines · 4.4 KB Raw History
import Foundation
import SwiftUI

extension AppModel {
    func publish(
        text: String, replyTo: String? = nil, quotePostID: String? = nil, images: [ImageAttachment] = [],
        video: VideoAttachment? = nil, draftID: String? = nil
    ) async -> Bool {
        let cleaned = text.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !cleaned.isEmpty || !images.isEmpty || video != nil else { return false }
        let draftKey = ComposerDraftKey(replyTo: replyTo, quotePostID: quotePostID, id: draftID)
        guard account != nil, !isSigningOut, !isPublishing, !uncertainDraftKeys.contains(draftKey) else { return false }
        isPublishing = true
        publishErrorMessage = nil
        publishResultUnknown = false
        let generation = sessionGeneration
        defer { if generation == sessionGeneration { isPublishing = false } }
        do {
            let reply = replyTo.flatMap(post)
            let quote = quotePostID.flatMap(post)
            guard replyTo == nil || reply != nil, quotePostID == nil || quote != nil else {
                throw ServiceError.postReferenceUnavailable
            }
            let newPost = try await service.publish(
                text: cleaned, replyTo: reply, quotePost: quote, images: images, video: video)
            guard generation == sessionGeneration, let account else { return false }
            return acceptPublishedPost(newPost, account: account, images: images, replyTo: replyTo)
        } catch {
            guard generation == sessionGeneration else { return false }
            handlePublishFailure(error, draftKey: draftKey)
            return false
        }
    }

    func clearPublishError() {
        publishErrorMessage = nil
    }

    func discardUncertainDraft(for key: ComposerDraftKey) {
        uncertainDraftKeys.remove(key)
        clearPublishError()
    }
    private func acceptPublishedPost(_ post: Post, account: Account, images: [ImageAttachment], replyTo: String?)
        -> Bool {
        var newPost = post
        newPost.author =
            profiles[account.id]?.author
            ?? Post.Author(
                id: account.id, name: account.displayName, handle: account.handle, avatarURL: account.avatarURL)
        newPost.pendingImages = images
        let context = publishedReplyContext(for: newPost)
        if newPost.replyGrandparentAuthor == nil,
            let parentID = newPost.replyParentURI,
            let grandparentID = self.post(id: parentID)?.replyParentURI {
            newPost.replyGrandparentAuthor = self.post(id: grandparentID)?.author
        }
        guard selectedFeed == nil else {
            cachedPostsByID[newPost.id] = newPost
            return true
        }
        withContentUpdates {
            if !context.isEmpty { replyContexts[newPost.id] = context }
            var updated = posts
            updated.insert(newPost, at: 0)
            if let replyTo, let parentIndex = updated.firstIndex(where: { $0.id == replyTo }) {
                updated[parentIndex].replyIDs.append(newPost.id)
            }
            posts = updated
            timelinePostIDs.insert(newPost.id)
        }
        return true
    }

    private func publishedReplyContext(for post: Post) -> [Post] {
        var seen: Set<String> = [post.id]
        return [post.replyRootURI, post.replyParentURI].compactMap { id in
            guard let id, seen.insert(id).inserted else { return nil }
            return self.post(id: id)
        }
    }

    private func handlePublishFailure(_ error: Error, draftKey: ComposerDraftKey) {
        if error is ActionNotSentError
            || (error as? ServiceError).map({
                if case .noSession = $0 { return true }
                return false
            }) == true {
            if !NetworkFailure.isCancellation(error) { publishErrorMessage = NetworkFailure.message(for: error) }
            return
        }
        switch error as? ServiceError {
        case .postTextTooLong, .tooManyImages, .invalidImage, .imageTooLarge, .postReferenceUnavailable, .noSession:
            publishErrorMessage = error.localizedDescription
        default:
            publishResultUnknown = true
            uncertainDraftKeys.insert(draftKey)
            publishErrorMessage =
                "\(error.localizedDescription)\n\nBluesky may have received this post. "
                + "This draft cannot be posted again until you discard it."
        }
    }

}