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

geesawra.industries/old-fella

Old people's social media app

0
1
main
120 lines · 5.3 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    static func postDate(_ value: Any?) -> Date? {
        guard let value = value as? String else { return nil }
        return (try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(value))
            ?? (try? Date.ISO8601FormatStyle().parse(value))
    }

    static func uniqueURLs(_ urls: [URL]) -> [URL] {
        var seen: Set<String> = []
        return urls.filter { seen.insert($0.absoluteString).inserted }
    }

    static func suppressesQuote(_ embed: [String: Any]) -> Bool {
        let outer = embed["record"] as? [String: Any] ?? [:]
        let record = outer["record"] as? [String: Any] ?? outer
        if let author = record["author"] as? [String: Any], isMuted(author) { return true }
        let type = record["$type"] as? String
        return type == "app.bsky.embed.record#viewBlocked" || type == "app.bsky.embed.record#viewNotFound"
            || type == "app.bsky.embed.record#viewDetached"
    }

    static func quote(from embed: [String: Any], postID: String) -> Post.Quote {
        let outer = embed["record"] as? [String: Any] ?? [:]
        let record = outer["record"] as? [String: Any] ?? outer
        guard let author = record["author"] as? [String: Any],
            !isMuted(author),
            let did = author["did"] as? String,
            let handle = author["handle"] as? String,
            let value = record["value"] as? [String: Any],
            let text = value["text"] as? String
        else {
            return Post.Quote(postID: postID)
        }
        let embeds = record["embeds"] as? [[String: Any]] ?? []
        let media = embeds.map { attachedMedia(from: $0) }
        let facets = BlueskyPostMapper.decodedFacets(from: value["facets"], text: text)
        let urls =
            Self.urls(in: text)
            + facets.compactMap { facet -> URL? in
                if case .link(let url) = facet.feature { return url }
                return nil
            }
        return Post.Quote(
            postID: postID,
            author: Post.Author(
                id: did, name: author["displayName"] as? String ?? handle, handle: handle,
                avatarURL: url(author["avatar"]), moderationLabels: moderationLabels(author["labels"]),
                isFollowing: (author["viewer"] as? [String: Any])?["following"] != nil),
            text: text,
            facets: facets,
            links: externalLinks(from: embeds, excluding: Set(urls)),
            imageURLs: uniqueURLs(media.flatMap(\.images) + urls.filter { Post.destination(for: $0) == .image }),
            imageThumbnailURLs: embeds.reduce(into: [:]) { result, embed in
                result.merge(imageThumbnailURLs(from: embed)) { first, _ in first }
            },
            videoURLs: uniqueURLs(media.flatMap(\.videos) + urls.filter { Post.destination(for: $0) == .video }),
            gifURLs: uniqueURLs(media.flatMap(\.gifs) + urls.filter { Post.destination(for: $0) == .gif }),
            inlineGIFVideoURLs: uniqueURLs(media.flatMap(\.inlineGIFVideos)),
            createdAt: postDate(value["createdAt"]) ?? postDate(record["indexedAt"]),
            imageDescriptions: embeds.reduce(into: [:]) { result, embed in
                result.merge(imageDescriptions(from: embed)) { first, _ in first }
            },
            moderationLabels: moderationLabels(record["labels"]),
            languages: value["langs"] as? [String] ?? [],
            tags: (value["tags"] as? [String] ?? [])
                + facets.compactMap {
                    if case .tag(let tag) = $0.feature { return tag }
                    return nil
                },
            externalTitle: embeds.compactMap { externalMetadata(from: $0)?.title }.first,
            externalDescription: embeds.compactMap { externalMetadata(from: $0)?.description }.first
        )
    }

    static func quoteURI(from embed: [String: Any]) -> String? {
        let record = embed["record"] as? [String: Any]
        if let uri = record?["uri"] as? String { return uri }
        let nested = record?["record"] as? [String: Any]
        return nested?["uri"] as? String
    }

    func appendThread(_ thread: [String: Any], to posts: inout [Post]) {
        if let postObject = thread["post"] as? [String: Any], let post = mapPost(postObject) {
            posts.append(post)
        }
        let replies = thread["replies"] as? [[String: Any]] ?? []
        for reply in replies {
            appendThread(reply, to: &posts)
        }
    }

    static func urls(in text: String) -> [URL] {
        text.split(whereSeparator: { $0.isWhitespace }).compactMap { part in
            let value = String(part).trimmingCharacters(in: CharacterSet(charactersIn: "<>()[]{}.,!?\"'"))
            guard let url = URL(string: value), ["https", "http"].contains(url.scheme?.lowercased() ?? "") else {
                return nil
            }
            return url
        }
    }

    static func url(_ value: Any?) -> URL? {
        guard let value = value as? String else { return nil }
        return URL(string: value)
    }

    func decodeObject(_ data: Data) throws -> [String: Any] {
        guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
            throw ServiceError.invalidResponse
        }
        return object
    }
}