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
import Foundation
extension ATProtoBlueskyService {
struct ParsedModerationPreferences {
var preferences: ModerationPolicy.Preferences
var labelerIDs: [String] = []
var perLabeler: [String: [String: ModerationPolicy.LabelSetting]] = [:]
init(accountDID: String) {
preferences = ModerationPolicy.Preferences(
userDID: accountDID,
labelDefinitions: ModerationPolicy.builtInDefinitions)
}
mutating func apply(_ item: [String: Any]) throws {
switch item["$type"] as? String {
case "app.bsky.actor.defs#adultContentPref":
guard let enabled = item["enabled"] as? Bool else { throw ServiceError.invalidResponse }
preferences.adultContentEnabled = enabled
case "app.bsky.actor.defs#contentLabelPref": try applyLabelPreference(item)
case "app.bsky.actor.defs#labelersPref": try applyLabelers(item)
case "app.bsky.actor.defs#mutedWordsPref": try applyMutedWords(item)
default: break
}
}
private mutating func applyLabelPreference(_ item: [String: Any]) throws {
guard let label = item["label"] as? String,
let visibility = ATProtoBlueskyService.labelSetting(item["visibility"] as? String)
else {
throw ServiceError.invalidResponse
}
if let did = item["labelerDid"] as? String ?? item["did"] as? String {
perLabeler[did, default: [:]][label] = visibility
} else {
preferences.labels[label] = visibility
}
}
private mutating func applyLabelers(_ item: [String: Any]) throws {
guard let labelers = item["labelers"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
for labeler in labelers {
guard let did = labeler["did"] as? String, did.hasPrefix("did:"),
!did.contains(","), !did.contains(" ")
else { throw ServiceError.invalidResponse }
if !labelerIDs.contains(did) { labelerIDs.append(did) }
}
}
private mutating func applyMutedWords(_ item: [String: Any]) throws {
guard let words = item["items"] as? [[String: Any]] else { throw ServiceError.invalidResponse }
for word in words {
guard let value = word["value"] as? String, let targets = word["targets"] as? [String] else {
throw ServiceError.invalidResponse
}
var mapped: Set<ModerationPolicy.MutedWord.Target> = []
if targets.contains("content") { mapped.insert(.content) }
if targets.contains("tag") { mapped.insert(.tag) }
preferences.mutedWords.append(
.init(
value: value, targets: mapped,
excludeFollowing: word["actorTarget"] as? String == "exclude-following",
expiresAt: ATProtoBlueskyService.postDate(word["expiresAt"])))
}
}
}
}