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

geesawra.industries/old-fella

Old people's social media app

0
1
main
43 lines · 1.9 KB Raw History
import ATProtoKit
import Foundation

extension ATProtoBlueskyService {
    func loadSavedPosts(cursor: String?) async throws -> FeedPage {
        guard stored != nil else { throw ServiceError.noSession }
        // ATProtoKit 0.34.1 can reject a bookmark with no creation date.
        let object = try await readObject(allowBookmarkDecodingFailure: true) { try await $0.getBookmarks(cursor: cursor) }
        guard let bookmarks = object["bookmarks"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
        let feed = bookmarks.compactMap { bookmark -> [String: Any]? in
            guard var post = bookmark["item"] as? [String: Any],
                post["$type"] as? String == "app.bsky.feed.defs#postView"
            else { return nil }
            var viewer = post["viewer"] as? [String: Any] ?? [:]
            viewer["bookmarked"] = true
            post["viewer"] = viewer
            return ["post": post]
        }
        return mapFeedPage(["feed": feed, "cursor": object["cursor"] as Any], hideBlockedPosts: true)
    }

    func setPostSaved(_ saved: Bool, post: Post) async throws {
        if saved { _ = try strongReference(for: post) }
        let client = try await authenticatedClient()
        do {
            if saved {
                try await client.createBookmark(uri: post.id, cid: post.cid)
            } else {
                try await client.deleteBookmark(uri: post.id)
            }
        } catch ATAPIError.unknown(_, 204, _, _) {
            // ATProtoKit 0.34.1 only accepts HTTP 200 for a successful request.
        } catch {
            if let id = client.sessionConfiguration?.instanceUUID {
                await UserSessionRegistry.shared.removeSession(for: id)
            }
            throw error
        }
        if let id = client.sessionConfiguration?.instanceUUID {
            await UserSessionRegistry.shared.removeSession(for: id)
        }
    }
}