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

geesawra.industries/old-fella

Old people's social media app

0
1
main
104 lines · 5.1 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    func setFollowing(_ following: Bool, actorID: String) async throws -> String? {
        guard let current = stored else { throw ServiceError.noSession }
        let generation = sessionGeneration
        let profile: AppBskyLexicon.Actor.ProfileViewDetailedDefinition
        do {
            profile = try await getProfile(actorID: actorID)
        } catch {
            throw ActionNotSentError(underlying: error)
        }
        guard generation == sessionGeneration else { throw ActionNotSentError(underlying: ServiceError.noSession) }
        let subjectDID = profile.actorDID
        if following {
            let record: [String: Any] = [
                "$type": "app.bsky.graph.follow", "subject": subjectDID,
                "createdAt": ISO8601DateFormatter().string(from: Date())
            ]
            let uri = try await createRecord(collection: "app.bsky.graph.follow", record: record).uri
            if generation == sessionGeneration { followRecordURIs[actorID] = uri }
            return uri
        }
        guard let followURI = followRecordURIs[actorID] ?? profile.viewer?.followingURI else {
            throw ActionNotSentError(underlying: ServiceError.invalidResponse)
        }
        try await deleteRecord(uri: followURI, repository: current.did)
        if generation == sessionGeneration { followRecordURIs.removeValue(forKey: actorID) }
        return nil
    }

    func moderationState(actorID: String) async throws -> ModerationState {
        guard stored != nil else { throw ServiceError.noSession }
        let object = try await readObject { try await $0.getProfile(for: actorID) }
        guard let viewer = object["viewer"] as? [String: Any] else { throw ServiceError.invalidResponse }
        return ModerationState(isMuted: viewer["muted"] as? Bool ?? false, blockURI: viewer["blocking"] as? String)
    }

    func moderationRequest(_ method: String, body: [String: Any], proxy: String? = nil) async throws -> [String:
        Any] {
        guard let current = stored else { throw ModerationWriteError.rejected("Sign in again.") }
        let url = current.pdsURL.appendingPathComponent("xrpc/\(method)")
        let data: Data
        do { data = try JSONSerialization.data(withJSONObject: body) } catch {
            throw ModerationWriteError.rejected("The request could not be prepared.")
        }
        let (response, _) = try await send(
            to: url, method: "POST", body: data, contentType: "application/json", authenticated: true,
            proxyService: proxy, classifyModerationWrite: true)
        if response.isEmpty { return [:] }
        return try decodeObject(response)
    }

    func setMuted(_ muted: Bool, actorID: String) async throws {
        let method = muted ? "app.bsky.graph.muteActor" : "app.bsky.graph.unmuteActor"
        _ = try await moderationRequest(method, body: ["actor": actorID], proxy: "did:web:api.bsky.app#bsky_appview")
    }

    func setBlocked(_ blocked: Bool, actorID: String, blockURI: String?) async throws -> String? {
        guard let current = stored else { throw ModerationWriteError.rejected("Sign in again.") }
        if blocked {
            let record: [String: Any] = [
                "$type": "app.bsky.graph.block", "subject": actorID,
                "createdAt": ISO8601DateFormatter().string(from: Date())
            ]
            let result = try await moderationRequest(
                "com.atproto.repo.createRecord",
                body: ["repo": current.did, "collection": "app.bsky.graph.block", "record": record])
            guard let uri = result["uri"] as? String else { throw ServiceError.invalidRecordResponse }
            return uri
        }
        guard let blockURI else {
            throw ModerationWriteError.rejected("The block record is missing. Reload account controls.")
        }
        let parts = blockURI.split(separator: "/")
        guard parts.count == 4, parts[1] == Substring(current.did), parts[2] == "app.bsky.graph.block" else {
            throw ModerationWriteError.rejected("The block record is invalid. Reload account controls.")
        }
        _ = try await moderationRequest(
            "com.atproto.repo.deleteRecord",
            body: ["repo": current.did, "collection": "app.bsky.graph.block", "rkey": String(parts[3])])
        return nil
    }

    func report(_ subject: ReportSubject, reason: String) async throws {
        let value: [String: Any]
        switch subject {
        case .account(let did): value = ["$type": "com.atproto.admin.defs#repoRef", "did": did]
        case .post(let uri, let cid):
            guard !cid.isEmpty else {
                throw ModerationWriteError.rejected("This post is missing information needed for a report.")
            }
            value = ["$type": "com.atproto.repo.strongRef", "uri": uri, "cid": cid]
        }
        _ = try await moderationRequest(
            "com.atproto.moderation.createReport", body: ["reasonType": reason, "subject": value],
            proxy: "did:plc:ar7c4by46qjdydhdevvrndac#atproto_labeler")
    }
}