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

geesawra.industries/old-fella

Old people's social media app

0
1
main
94 lines · 5.0 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    func loadSubscribedFeeds() async throws -> [CustomFeed] {
        guard stored != nil else { throw ServiceError.noSession }
        let object = try await readObject { try await $0.getPreferences() }
        guard let preferences = object["preferences"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
        let uris: [String]
        if let saved = preferences.last(where: { $0["$type"] as? String == "app.bsky.actor.defs#savedFeedsPrefV2" }) {
            guard let items = saved["items"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
            uris = items.filter { $0["type"] as? String == "feed" }.compactMap { $0["value"] as? String }
        } else if let saved = preferences.last(where: { $0["$type"] as? String == "app.bsky.actor.defs#savedFeedsPref" }
        ) {
            uris = (saved["saved"] as? [String] ?? []) + (saved["pinned"] as? [String] ?? [])
        } else {
            uris = []
        }
        var seen = Set<String>()
        let uniqueURIs = uris.filter { seen.insert($0).inserted }
        var feedsByURI: [String: CustomFeed] = [:]
        for start in stride(from: 0, to: uniqueURIs.count, by: 25) {
            let batch = Array(uniqueURIs[start..<min(start + 25, uniqueURIs.count)])
            let response = try await readObject { try await $0.getFeedGenerators(by: batch) }
            guard let feeds = response["feeds"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
            for feed in feeds {
                guard let uri = feed["uri"] as? String, let name = feed["displayName"] as? String else {
                    throw ServiceError.invalidResponse
                }
                feedsByURI[uri] = CustomFeed(id: uri, name: name, avatarURL: Self.url(feed["avatar"]))
            }
        }
        return uniqueURIs.compactMap { feedsByURI[$0] }
    }

    func loadCustomFeed(uri: String, cursor: String?) async throws -> FeedPage {
        guard stored != nil else { throw ServiceError.noSession }
        do {
            let object = try await readObject {
                try await $0.getFeed(by: uri, limit: Self.feedPageSize, cursor: cursor)
            }
            guard object["feed"] is [[String: Any]] else { throw ServiceError.invalidResponse }
            return mapFeedPage(object, hideBlockedPosts: true)
        } catch ATAPIError.notFound {
            throw CustomFeedError.unavailable
        }
    }

    func loadFollowingFeed(cursor: String?) async throws -> FeedPage {
        guard stored != nil else { throw ServiceError.noSession }
        let object = try await readObject { try await $0.getTimeline(limit: Self.feedPageSize, cursor: cursor) }
        return mapFeedPage(object, hideBlockedPosts: true)
    }

    func suggestAccounts(query: String) async throws -> [Post.Author] {
        guard stored != nil else { throw ServiceError.noSession }
        let object = try await readObject { try await $0.searchActorsTypeahead(matching: query, limit: 10) }
        return try accountSummaries(from: object, key: "actors")
    }

    func searchAccounts(query: String, cursor: String?) async throws -> AccountSearchPage {
        guard stored != nil else { throw ServiceError.noSession }
        let object = try await readObject { try await $0.searchActors(matching: query, limit: 30, cursor: cursor) }
        return AccountSearchPage(
            accounts: try accountSummaries(from: object, key: "actors"), cursor: object["cursor"] as? String)
    }

    func accountSummaries(from object: [String: Any], key: String) throws -> [Post.Author] {
        guard let actors = object[key] as? [[String: Any]] else { throw ServiceError.invalidResponse }
        return actors.compactMap { actor -> Post.Author? in
            guard !Self.isMuted(actor), !isBlockedPost(["author": actor]) else { return nil }
            guard let did = actor["did"] as? String, let handle = actor["handle"] as? String else { return nil }
            return Post.Author(
                id: did, name: actor["displayName"] as? String ?? handle, handle: handle,
                avatarURL: Self.url(actor["avatar"]), moderationLabels: Self.moderationLabels(actor["labels"]),
                isFollowing: (actor["viewer"] as? [String: Any])?["following"] != nil,
                bio: actor["description"] as? String)
        }
    }

    func searchPosts(query: String, cursor: String?, authorID: String? = nil) async throws -> FeedPage {
        guard stored != nil else { throw ServiceError.noSession }
        let object = try await readObject {
            try await $0.searchPosts(matching: query, sortRanking: .latest, author: authorID, limit: 30, cursor: cursor)
        }
        guard let posts = object["posts"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
        return mapFeedPage(
            ["feed": posts.map { ["post": $0] }, "cursor": object["cursor"] as Any], hideBlockedPosts: true)
    }
}