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

geesawra.industries/old-fella

Old people's social media app

0
1
main
114 lines · 6.2 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    static func moderationLabels(_ value: Any?) -> [ModerationPolicy.Label] {
        (value as? [[String: Any]] ?? []).compactMap { label in
            guard let value = label["val"] as? String, let source = label["src"] as? String else { return nil }
            return .init(
                value: value, sourceDID: source, expiresAt: postDate(label["exp"]),
                isNegated: label["neg"] as? Bool ?? false)
        }
    }

    static func isMuted(_ author: [String: Any]) -> Bool {
        guard let viewer = author["viewer"] as? [String: Any] else { return false }
        return viewer["muted"] as? Bool == true || viewer["mutedByList"] != nil
    }

    func mapPost(_ object: [String: Any]) -> Post? {
        guard let author = object["author"] as? [String: Any], !Self.isMuted(author) else { return nil }
        guard let uri = object["uri"] as? String,
            let cid = object["cid"] as? String,
            let did = author["did"] as? String,
            let handle = author["handle"] as? String
        else { return nil }
        let record = object["record"] as? [String: Any] ?? [:]
        let rawText = record["text"] as? String ?? ""
        let facets = Self.postFacets(record: record, text: rawText)
        let facetURLs = Set(
            facets.compactMap { facet -> URL? in
                if case .link(let url) = facet.feature { return url }
                return nil
            })
        let embed = object["embed"] as? [String: Any] ?? [:]
        let textURLs = Self.urls(in: rawText)
        let inlineURLs = facetURLs.union(facets.flatMap { facet -> [URL] in
            guard case .link = facet.feature else { return [] }
            let label = String(
                decoding: rawText.utf8.dropFirst(facet.byteStart).prefix(facet.byteEnd - facet.byteStart), as: UTF8.self)
            return Self.urls(in: label)
        })
        let links = Self.uniqueURLs(
            textURLs.filter { !inlineURLs.contains($0) }
                + Self.externalLinks(from: [embed], excluding: Set(textURLs).union(inlineURLs)))
        let attachedMedia = Self.attachedMedia(from: embed)
        let mediaLinks = textURLs + Array(facetURLs)
        let images = Self.uniqueURLs(attachedMedia.images + mediaLinks.filter { Post.destination(for: $0) == .image })
        let videos = Self.uniqueURLs(attachedMedia.videos + mediaLinks.filter { Post.destination(for: $0) == .video })
        let gifs = Self.uniqueURLs(attachedMedia.gifs + mediaLinks.filter { Post.destination(for: $0) == .gif })
        let inlineGIFVideos = Self.uniqueURLs(attachedMedia.inlineGIFVideos)
        let viewer = object["viewer"] as? [String: Any]
        let likeURI = viewer?["like"] as? String
        let repostURI = viewer?["repost"] as? String
        let reply = record["reply"] as? [String: Any]
        let root = reply?["root"] as? [String: Any]
        let parent = reply?["parent"] as? [String: Any]
        let quoteURI =
            Self.suppressesQuote(embed)
            ? nil : (Self.quoteURI(from: embed) ?? Self.quoteURI(from: record["embed"] as? [String: Any] ?? [:]))
        return Post(
            id: uri, cid: cid,
            author: Self.postAuthor(author, did: did, handle: handle), text: rawText,
            likeCount: object["likeCount"] as? Int ?? 0, repostCount: object["repostCount"] as? Int ?? 0,
            isLiked: likeURI != nil, isReposted: repostURI != nil, isSaved: viewer?["bookmarked"] as? Bool == true,
            imageURLs: images,
            imageThumbnailURLs: Self.imageThumbnailURLs(from: embed), videoURLs: videos, gifURLs: gifs,
            inlineGIFVideoURLs: inlineGIFVideos, replyRootURI: root?["uri"] as? String,
            replyRootCID: root?["cid"] as? String, replyParentURI: parent?["uri"] as? String,
            replyParentCID: parent?["cid"] as? String, likeURI: likeURI, repostURI: repostURI, links: links,
            facets: facets, quote: quoteURI.map { Self.quote(from: embed, postID: $0) }, replyIDs: [],
            replyCount: object["replyCount"] as? Int ?? 0,
            createdAt: Self.postDate(record["createdAt"]) ?? Self.postDate(object["indexedAt"]),
            imageDescriptions: Self.imageDescriptions(from: embed),
            moderationLabels: Self.moderationLabels(object["labels"]), languages: record["langs"] as? [String] ?? [],
            tags: Self.postTags(record: record, facets: facets),
            externalTitle: Self.externalMetadata(from: embed)?.title,
            externalDescription: Self.externalMetadata(from: embed)?.description)
    }
    private static func postFacets(record: [String: Any], text rawText: String) -> [PostFacet] {
        var facets = BlueskyPostMapper.decodedFacets(from: record["facets"], text: rawText)
        let existingRanges = facets.map { $0.byteStart..<$0.byteEnd }
        let fallbackLinks = ComposerText.facetCandidates(in: rawText).compactMap { candidate -> PostFacet? in
            guard case .link = candidate.kind,
                let url = URL(string: candidate.value),
                ["http", "https"].contains(url.scheme?.lowercased() ?? ""),
                !existingRanges.contains(where: { $0.overlaps(candidate.byteStart..<candidate.byteEnd) })
            else { return nil }
            return PostFacet(byteStart: candidate.byteStart, byteEnd: candidate.byteEnd, feature: .link(url))
        }
        facets.append(contentsOf: fallbackLinks)
        facets.sort { $0.byteStart < $1.byteStart }
        return facets
    }

    private static func postTags(record: [String: Any], facets: [PostFacet]) -> [String] {
        (record["tags"] as? [String] ?? [])
            + facets.compactMap {
                if case .tag(let value) = $0.feature { return value }
                return nil
            }
    }

    private static func postAuthor(_ author: [String: Any], did: String, handle: String) -> Post.Author {
        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)
    }

}