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

geesawra.industries/old-fella

Old people's social media app

0
1
main
226 lines · 11.2 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    func resolvePostURI(_ uri: String) async throws -> String {
        guard uri.hasPrefix("at://"),
            let authorityEnd = uri["at://".endIndex...].firstIndex(of: "/")
        else { return uri }
        let authority = String(uri["at://".endIndex..<authorityEnd])
        guard !authority.hasPrefix("did:") else { return uri }
        let did = try await resolveDID(for: authority)
        return "at://\(did)\(uri[authorityEnd...])"
    }

    func loadPost(uri: String) async throws -> [Post] {
        try await loadThread(uri: uri).posts
    }

    func loadThread(uri: String) async throws -> ThreadResult {
        let resolvedURI = try await resolvePostURI(uri)
        async let positions = loadThreadPositions(anchor: resolvedURI)
        let object = try await readObject {
            try await $0.getPostThread(from: resolvedURI, depth: 1000, parentHeight: 1000)
        }
        guard let thread = object["thread"] as? [String: Any] else { return ThreadResult(posts: [], mutedPostIDs: []) }
        var mutedPostIDs: Set<String> = []
        func recordMuted(_ value: [String: Any]) {
            guard let post = value["post"] as? [String: Any],
                let author = post["author"] as? [String: Any], Self.isMuted(author),
                let id = post["uri"] as? String
            else { return }
            mutedPostIDs.insert(id)
        }
        var ancestors: [Post] = []
        var parent = thread["parent"] as? [String: Any]
        while let parentThread = parent {
            recordMuted(parentThread)
            if let postObject = parentThread["post"] as? [String: Any], let post = mapPost(postObject) {
                ancestors.append(post)
            }
            parent = parentThread["parent"] as? [String: Any]
        }

        func collectMuted(_ value: [String: Any]) {
            recordMuted(value)
            for reply in value["replies"] as? [[String: Any]] ?? [] { collectMuted(reply) }
        }
        collectMuted(thread)
        var selectedAndReplies: [Post] = []
        appendThread(thread, to: &selectedAndReplies)
        guard selectedAndReplies.contains(where: { $0.id == resolvedURI }) else {
            return ThreadResult(posts: [], mutedPostIDs: mutedPostIDs)
        }
        let posts = ancestors.reversed() + selectedAndReplies
        let visibleIDs = Set(posts.map(\.id))
        return await ThreadResult(
            posts: posts, mutedPostIDs: mutedPostIDs, positions: positions.filter { visibleIDs.contains($0.key) })
    }

    private func loadThreadPositions(anchor: String) async -> [String: ThreadPosition] {
        do {
            let object = try await readObject { client in
                guard let baseURL = URL(string: client.pdsURL),
                    var url = URLComponents(
                        url: baseURL.appendingPathComponent("xrpc/app.bsky.unspecced.getPostThreadV2"),
                        resolvingAgainstBaseURL: false)
                else { throw ServiceError.invalidResponse }
                url.queryItems = [
                    URLQueryItem(name: "anchor", value: anchor),
                    URLQueryItem(name: "below", value: "20")
                ]
                guard let requestURL = url.url else { throw ServiceError.invalidResponse }
                return try await client.apiClientService.sendRequest(URLRequest(url: requestURL, timeoutInterval: 4))
            }
            let items = object["thread"] as? [[String: Any]] ?? []
            return items.reduce(into: [:]) { positions, item in
                guard let id = item["uri"] as? String, let value = item["value"] as? [String: Any],
                    value["opThread"] as? Bool == true,
                    value["hiddenByThreadgate"] as? Bool != true, value["mutedByViewer"] as? Bool != true,
                    let post = value["post"] as? [String: Any], post["uri"] as? String == id,
                    let index = value["opThreadPostIndex"] as? Int, let count = value["opThreadPostCount"] as? Int,
                    let position = ThreadPosition(index: index, count: count)
                else { return }
                positions[id] = position
            }
        } catch {
            // The thread stays available if the numbering endpoint fails.
            return [:]
        }
    }

    func loadProfile(actorID: String) async throws -> Profile? {
        let profile = try await readObject { try await $0.getProfile(for: actorID) }
        guard let did = profile["did"] as? String, let handle = profile["handle"] as? String else {
            throw ServiceError.invalidResponse
        }
        let viewer = profile["viewer"] as? [String: Any]
        let following = viewer?["following"] as? String
        let author = Post.Author(
            id: did, name: profile["displayName"] as? String ?? handle, handle: handle,
            avatarURL: Self.url(profile["avatar"]), moderationLabels: Self.moderationLabels(profile["labels"]),
            isFollowing: following != nil)
        let links = (profile["links"] as? [[String: Any]] ?? []).compactMap { value -> Profile.Link? in
            guard let id = value["uri"] as? String,
                let rawURL = value["url"] as? String, let url = URL(string: rawURL),
                ["http", "https"].contains(url.scheme?.lowercased() ?? ""),
                let host = url.host, !host.isEmpty
            else { return nil }
            let title = (value["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
            return Profile.Link(
                id: id, title: title.flatMap { $0.isEmpty ? nil : $0 } ?? rawURL,
                url: url, moderationLabels: Self.moderationLabels(value["labels"]))
        }
        return Profile(
            author: author, bio: profile["description"] as? String ?? "", location: nil, website: nil,
            followerCount: profile["followersCount"] as? Int ?? 0, followingCount: profile["followsCount"] as? Int ?? 0,
            isFollowing: following != nil, followURI: following, isFollowedBy: viewer?["followedBy"] is String,
            links: links)
    }

    func loadProfileConnections(actorID: String, kind: ProfileConnectionKind, cursor: String?) async throws
        -> ProfileConnectionsPage {
        guard stored != nil else { throw ServiceError.noSession }
        let object: [String: Any]
        let key: String
        switch kind {
        case .followers:
            object = try await readObject { try await $0.getFollowers(by: actorID, cursor: cursor) }
            key = "followers"
        case .following:
            object = try await readObject { try await $0.getFollows(from: actorID, cursor: cursor) }
            key = "follows"
        }
        return ProfileConnectionsPage(
            accounts: try accountSummaries(from: object, key: key), cursor: object["cursor"] as? String)
    }

    func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage {
        let object = try await readObject {
            try await $0.getAuthorFeed(
                by: actorID, limit: Self.feedPageSize, cursor: cursor, postFilter: .postsWithReplies,
                shouldIncludePins: false)
        }
        return mapFeedPage(object)
    }

    func mapFeedPage(_ object: [String: Any], hideBlockedPosts: Bool = false) -> FeedPage {
        var contexts: [String: [Post]] = [:]
        var repostedBy: [String: Post.Author] = [:]
        var mutedPostIDs: Set<String> = []
        let posts = (object["feed"] as? [[String: Any]] ?? []).compactMap { item -> Post? in
            let reply = item["reply"] as? [String: Any] ?? [:]
            for value in [item["post"], reply["root"], reply["parent"]] {
                guard let value = value as? [String: Any] else { continue }
                let post = value["post"] as? [String: Any] ?? value
                guard let author = post["author"] as? [String: Any], Self.isMuted(author),
                    let id = post["uri"] as? String
                else { continue }
                mutedPostIDs.insert(id)
            }
            if hideBlockedPosts && ([item["post"], reply["root"], reply["parent"]].contains { isBlockedPost($0) }) {
                return nil
            }
            guard var post = (item["post"] as? [String: Any]).flatMap(mapPost) else { return nil }
            if let author = reply["grandparentAuthor"] as? [String: Any],
                let did = author["did"] as? String, let handle = author["handle"] as? String {
                post.replyGrandparentAuthor = Post.Author(
                    id: did, name: author["displayName"] as? String ?? handle, handle: handle,
                    avatarURL: Self.url(author["avatar"]), moderationLabels: Self.moderationLabels(author["labels"]),
                    isFollowing: (author["viewer"] as? [String: Any])?["following"] != nil
                )
            }
            if let reason = item["reason"] as? [String: Any],
                let author = reason["by"] as? [String: Any], Self.isMuted(author) {
                return nil
            }
            let context = ["root", "parent"].compactMap { key -> Post? in
                guard let value = reply[key] as? [String: Any] else { return nil }
                return mapPost((value["post"] as? [String: Any]) ?? value)
            }
            if !context.isEmpty { contexts[post.id] = context }
            if let author = repostAuthor(from: item["reason"]) {
                repostedBy[post.id] = author
            }
            return post
        }
        let visiblePosts = posts.filter { !mutedPostIDs.contains($0.id) }
        contexts = contexts.filter { !mutedPostIDs.contains($0.key) }.mapValues {
            $0.filter { !mutedPostIDs.contains($0.id) }
        }
        repostedBy = repostedBy.filter { !mutedPostIDs.contains($0.key) }
        return FeedPage(
            posts: visiblePosts, cursor: object["cursor"] as? String, replyContexts: contexts, repostedBy: repostedBy,
            mutedPostIDs: mutedPostIDs)
    }

    func isBlockedPost(_ value: Any?) -> Bool {
        guard let value = value as? [String: Any] else { return false }
        if value["$type"] as? String == "app.bsky.feed.defs#blockedPost" || value["blocked"] as? Bool == true {
            return true
        }
        let post = (value["post"] as? [String: Any]) ?? value
        guard let author = post["author"] as? [String: Any],
            let viewer = author["viewer"] as? [String: Any]
        else { return false }
        return viewer["blocking"] is String || viewer["blockedBy"] as? Bool == true
            || viewer["blockingByList"] != nil
    }

    func repostAuthor(from value: Any?) -> Post.Author? {
        guard let reason = value as? [String: Any],
            reason["$type"] as? String == "app.bsky.feed.defs#reasonRepost",
            let author = reason["by"] as? [String: Any],
            let did = author["did"] as? String, let handle = author["handle"] as? String
        else { return nil }
        return Post.Author(
            id: did, name: author["displayName"] as? String ?? handle, handle: handle,
            avatarURL: Self.url(author["avatar"]),
            moderationLabels: Self.moderationLabels(author["labels"]),
            isFollowing: (author["viewer"] as? [String: Any])?["following"] != nil)
    }
}