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

geesawra.industries/old-fella

Old people's social media app

0
1
main
163 lines · 8.0 KB Raw History
import ATProtoKit
import Foundation
import OSLog

extension ATProtoBlueskyService {
    func loadModerationPreferences() async throws -> ModerationPolicy.Preferences {
        guard let account = stored else { throw ServiceError.noSession }
        let generation = sessionGeneration
        let reload = UUID()
        moderationReloadGeneration = reload
        let object = try await readObject { try await $0.getPreferences() }
        guard generation == sessionGeneration, stored?.did == account.did else { throw ServiceError.noSession }
        guard let items = object["preferences"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
        var parsed = ParsedModerationPreferences(accountDID: account.did)
        for item in items { try parsed.apply(item) }
        let activeLabelerIDs =
            [ModerationPolicy.defaultLabelerDID]
            + parsed.labelerIDs.filter { $0 != ModerationPolicy.defaultLabelerDID }
        var result = parsed.preferences
        result.labelers = activeLabelerIDs.map { .init(did: $0, labels: parsed.perLabeler[$0] ?? [:]) }
        var definitions: [String: [ModerationPolicy.LabelDefinition]] = [:]
        var transportError: Error?
        moderationLogger.info("Loading definitions for \(activeLabelerIDs.count, privacy: .public) moderation services")
        do {
            definitions = try await fetchLabelDefinitions(activeLabelerIDs)
        } catch {
            if NetworkFailure.isCancellation(error) { throw error }
            if NetworkFailure.isConnectionFailure(error) { transportError = error }
            try validateModerationReload(generation: generation, accountDID: account.did, reload: reload)
            logLabelDefinitionFailure(error)
            definitions.removeAll()
        }
        try validateModerationReload(generation: generation, accountDID: account.did, reload: reload)
        definitions = try cacheLabelDefinitions(
            definitions, activeIDs: activeLabelerIDs,
            accountDID: account.did, transportError: transportError)
        for did in activeLabelerIDs { result.labelDefinitions += definitions[did] ?? [] }
        selectedLabelers = activeLabelerIDs
        return result
    }

    private func validateModerationReload(generation: UUID, accountDID: String, reload: UUID) throws {
        guard generation == sessionGeneration, stored?.did == accountDID, reload == moderationReloadGeneration else {
            throw ServiceError.noSession
        }
    }

    private func logLabelDefinitionFailure(_ error: Error) {
        let nsError = error as NSError
        moderationLogger.error(
            """
            Definition request or decoding failed: domain=\(nsError.domain, privacy: .public) \
            code=\(nsError.code, privacy: .public) errorType=\(String(reflecting: type(of: error)), privacy: .public)
            """)
        if case DecodingError.keyNotFound(let key, let context) = error {
            moderationLogger.error(
                """
                Missing response key \(key.stringValue, privacy: .public) \
                at depth \(context.codingPath.count, privacy: .public)
                """)
        }
    }

    private func fetchLabelDefinitions(_ activeIDs: [String]) async throws -> [String: [ModerationPolicy
        .LabelDefinition]] {
        let response = try await readObject(allowUntypedLabelerViews: true) {
            try await $0.getLabelerServices(labelerDIDs: activeIDs, isDetailed: true)
        }
        guard let views = response["views"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
        var result: [String: [ModerationPolicy.LabelDefinition]] = [:]
        for view in views {
            let (did, policies) = try labelerPolicies(view, activeIDs: activeIDs, receivedIDs: Set(result.keys))
            result[did] = try (policies["labelValueDefinitions"] as? [[String: Any]] ?? []).compactMap {
                try labelDefinition($0, sourceDID: did)
            }
        }
        return result
    }

    private func labelerPolicies(_ view: [String: Any], activeIDs: [String], receivedIDs: Set<String>) throws
        -> (String, [String: Any]) {
        guard view["$type"] == nil || view["$type"] as? String == "app.bsky.labeler.defs#labelerViewDetailed",
            let creator = view["creator"] as? [String: Any], let did = creator["did"] as? String,
            activeIDs.contains(did), !receivedIDs.contains(did),
            let policies = view["policies"] as? [String: Any],
            policies["labelValueDefinitions"] == nil || policies["labelValueDefinitions"] is [[String: Any]]
        else {
            moderationLogger.error(
                """
                Invalid service view: type=\(view["$type"] as? String ?? "missing", privacy: .public), \
                creator=\(view["creator"] is [String: Any], privacy: .public), \
                policies=\(view["policies"] is [String: Any], privacy: .public)
                """)
            throw ServiceError.invalidResponse
        }
        return (did, policies)
    }

    private func labelDefinition(_ definition: [String: Any], sourceDID: String) throws -> ModerationPolicy
        .LabelDefinition? {
        guard let value = definition["identifier"] as? String, ModerationPolicy.isCustomLabelIdentifier(value) else {
            return nil
        }
        let visibility = Self.labelSetting(definition["defaultSetting"] as? String ?? "warn") ?? .warn
        guard let severity = ModerationPolicy.Severity(rawValue: definition["severity"] as? String ?? "alert"),
            let blur = ModerationPolicy.Blur(rawValue: definition["blurs"] as? String ?? "content")
        else {
            moderationLogger.error(
                """
                Invalid definition: setting=\(definition["defaultSetting"] as? String ?? "missing", privacy: .public), \
                severity=\(definition["severity"] as? String ?? "missing", privacy: .public), \
                blur=\(definition["blurs"] as? String ?? "missing", privacy: .public)
                """)
            throw ServiceError.invalidResponse
        }
        return .init(
            value: value, sourceDID: sourceDID, defaultSetting: visibility,
            adult: definition["adultOnly"] as? Bool ?? false, noSelf: true, severity: severity, blur: blur)
    }

    private func cacheLabelDefinitions(
        _ fetched: [String: [ModerationPolicy.LabelDefinition]], activeIDs: [String],
        accountDID: String, transportError: Error?
    ) throws
        -> [String: [ModerationPolicy.LabelDefinition]] {
        let currentTime = now()
        var definitions = fetched
        var nextCache: [String: CachedLabelDefinitions] = [:]
        for did in activeIDs {
            if let values = definitions[did] {
                nextCache[did] = CachedLabelDefinitions(
                    accountDID: accountDID, definitions: values, fetchedAt: currentTime)
            } else {
                guard let cached = cachedLabelDefinitions[did], cached.accountDID == accountDID,
                    currentTime >= cached.fetchedAt,
                    currentTime.timeIntervalSince(cached.fetchedAt) < labelDefinitionsLifetime
                else {
                    moderationLogger.error(
                        """
                        Definitions unavailable: received \(definitions.count, privacy: .public) \
                        of \(activeIDs.count, privacy: .public) services; \
                        missing service is default: \(did == ModerationPolicy.defaultLabelerDID, privacy: .public)
                        """)
                    if let transportError { throw transportError }
                    throw ServiceError.labelDefinitionsUnavailable
                }
                definitions[did] = cached.definitions
                nextCache[did] = cached
            }
        }
        cachedLabelDefinitions = nextCache
        return definitions
    }

    static func labelSetting(_ value: String?) -> ModerationPolicy.LabelSetting? {
        switch value {
        case "ignore", "show": return .ignore
        case "warn": return .warn
        case "hide": return .hide
        default: return nil
        }
    }
}