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

geesawra.industries/old-fella

Old people's social media app

0
1
main
192 lines · 9.3 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    func loadNotifications(cursor: String?) async throws -> NotificationPage {
        guard stored != nil else { throw ServiceError.noSession }
        let generation = sessionGeneration
        let object = try await readObject { try await $0.listNotifications(limit: 50, cursor: cursor) }
        guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
        guard let allNotificationObjects = object["notifications"] as? [[String: Any]] else {
            throw ServiceError.notificationsUnavailable
        }
        let notificationObjects = allNotificationObjects.filter {
            guard let author = $0["author"] as? [String: Any] else { return true }
            return !Self.isMuted(author)
        }
        let postURIs = Set(notificationObjects.flatMap(Self.notificationPostURIs))
        let sortedPostURIs = postURIs.sorted()
        let batches = stride(from: 0, to: sortedPostURIs.count, by: 25).map { start in
            Array(sortedPostURIs[start..<min(start + 25, sortedPostURIs.count)])
        }
        var hydrated = try await loadNotificationPosts(batches, generation: generation)
        let retries = batches.filter { $0.count > 1 }.flatMap { $0 }.filter { !hydrated.returnedURIs.contains($0) }
        hydrated.merge(try await loadNotificationPosts(retries.map { [$0] }, generation: generation))
        try Task.checkCancellation()
        guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
        let postsByURI = hydrated.posts
        let unavailablePostURIs = hydrated.unavailableURIs.union(postURIs.subtracting(hydrated.returnedURIs))
        let notifications = notificationObjects.compactMap {
            Self.notification(from: $0, postsByURI: postsByURI, unavailablePostURIs: unavailablePostURIs)
        }
        return NotificationPage(notifications: notifications, cursor: object["cursor"] as? String)
    }

    func loadNotificationPosts(_ batches: [[String]], generation: UUID) async throws -> NotificationPosts {
        do {
            return try await withThrowingTaskGroup(of: NotificationPosts.self) { group in
                var pending = batches.makeIterator()
                for _ in 0..<Self.notificationPostRequestLimit {
                    guard let batch = pending.next() else { break }
                    group.addTask { try await self.loadNotificationPostBatch(batch, generation: generation) }
                }
                var result = NotificationPosts()
                while let batch = try await group.next() {
                    result.merge(batch)
                    if let next = pending.next() {
                        group.addTask { try await self.loadNotificationPostBatch(next, generation: generation) }
                    }
                }
                return result
            }
        } catch {
            if NetworkFailure.isCancellation(error) || NetworkFailure.isConnectionFailure(error) { throw error }
            throw ServiceError.notificationsUnavailable
        }
    }

    func loadNotificationPostBatch(_ uris: [String], generation: UUID) async throws -> NotificationPosts {
        try Task.checkCancellation()
        guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
        let response = try await readObject { try await $0.getPosts(uris) }
        try Task.checkCancellation()
        guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
        guard let objects = response["posts"] as? [[String: Any]] else { throw ServiceError.notificationsUnavailable }
        var result = NotificationPosts()
        for object in objects {
            guard let uri = object["uri"] as? String, uris.contains(uri), result.returnedURIs.insert(uri).inserted,
                let author = object["author"] as? [String: Any],
                object["cid"] is String, author["did"] is String, author["handle"] is String,
                let record = object["record"] as? [String: Any], record["text"] is String
            else {
                throw ServiceError.notificationsUnavailable
            }
            if Self.isMuted(author) || isBlockedPost(object) {
                result.unavailableURIs.insert(uri)
            } else if let post = mapPost(object) {
                result.posts[uri] = post
            } else {
                throw ServiceError.notificationsUnavailable
            }
        }
        return result
    }

    func markNotificationsRead(seenAt: Date) async throws {
        let client = try await authenticatedClient()
        do {
            try await client.updateSeen(seenAt: seenAt)
            if let id = client.sessionConfiguration?.instanceUUID {
                await UserSessionRegistry.shared.removeSession(for: id)
            }
        } catch {
            if let id = client.sessionConfiguration?.instanceUUID {
                await UserSessionRegistry.shared.removeSession(for: id)
            }
            throw error
        }
    }
    private static func notificationPostURIs(_ item: [String: Any]) -> [String] {
        let reason = FeedNotification.Reason(rawValue: item["reason"] as? String ?? "") ?? .unknown
        let subjectURI = item["reasonSubject"] as? String ?? item["recordSubject"] as? String
        if reason == .reply {
            let record = item["record"] as? [String: Any]
            let reply = record?["reply"] as? [String: Any]
            let parent = reply?["parent"] as? [String: Any]
            return [item["uri"] as? String, subjectURI, parent?["uri"] as? String].compactMap { $0 }
        }
        if reason == .mention || reason == .quote {
            return [item["uri"] as? String].compactMap { $0 }
        }
        return [subjectURI].compactMap { $0 }
    }

    private static func notification(
        from item: [String: Any], postsByURI: [String: Post],
        unavailablePostURIs: Set<String>
    ) -> FeedNotification? {
        guard let uri = item["uri"] as? String,
            let authorObject = item["author"] as? [String: Any],
            !Self.isMuted(authorObject),
            let did = authorObject["did"] as? String,
            let handle = authorObject["handle"] as? String
        else { return nil }
        let reason = FeedNotification.Reason(rawValue: item["reason"] as? String ?? "") ?? .unknown
        let timestamp = Self.notificationDate(item["indexedAt"])
        let activityRecord = item["record"] as? [String: Any]
        let replyRecord = activityRecord?["reply"] as? [String: Any]
        let replyParent = replyRecord?["parent"] as? [String: Any]
        let subjectURI =
            item["reasonSubject"] as? String
            ?? item["recordSubject"] as? String
            ?? replyParent?["uri"] as? String
        let postID =
            reason == .reply || reason == .mention || reason == .quote
            ? item["uri"] as? String
            : subjectURI
        let parentURI = replyParent?["uri"] as? String
        guard
            Self.hasNotificationPosts(
                reason: reason, postID: postID, subjectURI: subjectURI,
                parentURI: parentURI,
                hydrated: NotificationPosts(posts: postsByURI, unavailableURIs: unavailablePostURIs))
        else { return nil }
        let relatedPost = postID.flatMap { postsByURI[$0] }
        return FeedNotification(
            id: uri,
            author: Post.Author(
                id: did, name: authorObject["displayName"] as? String ?? handle, handle: handle,
                avatarURL: Self.url(authorObject["avatar"]),
                moderationLabels: Self.moderationLabels(authorObject["labels"]),
                isFollowing: (authorObject["viewer"] as? [String: Any])?["following"] != nil,
                bio: authorObject["description"] as? String),
            reason: reason,
            indexedAt: timestamp,
            isRead: item["isRead"] as? Bool ?? true,
            postID: postID,
            relatedPost: relatedPost,
            parentPost: reason == .reply ? (replyParent?["uri"] as? String).flatMap { postsByURI[$0] } : nil,
            isFollowedBy: (authorObject["viewer"] as? [String: Any])?["followedBy"] is String
        )
    }

    private static func notificationDate(_ value: Any?) -> Date {
        let indexedAt = value as? String ?? ""
        let fractionalDateFormatter = ISO8601DateFormatter()
        fractionalDateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        return
            fractionalDateFormatter.date(from: indexedAt)
            ?? ISO8601DateFormatter().date(from: indexedAt)
            ?? .distantPast
    }

    private static func hasNotificationPosts(
        reason: FeedNotification.Reason, postID: String?, subjectURI: String?,
        parentURI: String?, hydrated: NotificationPosts
    ) -> Bool {
        let requiredURIs: [String?] = reason == .reply ? [postID, subjectURI, parentURI] : [postID]
        guard !requiredURIs.compactMap({ $0 }).contains(where: { hydrated.unavailableURIs.contains($0) }) else {
            return false
        }
        if [FeedNotification.Reason.reply, .mention, .quote, .like, .repost].contains(reason) {
            guard let postID, hydrated.posts[postID] != nil else { return false }
        }
        if reason == .reply, parentURI == nil { return false }
        return true
    }

}