1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
}
}
}