feat(moderation): apply muted words and label preferences
Oldsky.xcodeproj/project.pbxproj+8−0
| @@ -12,8 +12,10 @@ | ||
1FC93CC2B645B0DE0B5496DA /* ATProtoKit in Frameworks */ = {isa = PBXBuildFile; productRef = C38E0D11567B0A8E681E1E6E /* ATProtoKit */; }; | ||
2727E089A444ED660DCA6FBD /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 14AA13D2048D7CB44D42A687 /* Assets.xcassets */; }; | ||
37345BA4571D4C3923FB6DFE /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A1ABB191814FFEF245E7285 /* Models.swift */; }; | ||
56C03F63AFA345B0649A1969 /* ModerationPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC6525AA8B2A2794C5FA2472 /* ModerationPolicyTests.swift */; }; | ||
5748E268EFD526C08F791DE7 /* BlueskyService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2779C721893B64F0C7710BFB /* BlueskyService.swift */; }; | ||
8CF7EBCC2788E0E871B99021 /* OldskyApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD99E9D9710A09188269126B /* OldskyApp.swift */; }; | ||
8FF49F6F1E25DC79F810CD07 /* ModerationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F59FB833B3B3DCBDEAB0844 /* ModerationPolicy.swift */; }; | ||
AC5ED113B191377C35CC7AAD /* PostLinks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1540B9DF5BA7BFC210E0A873 /* PostLinks.swift */; }; | ||
B7AFAF450FA4B8632008B38E /* AppModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE8BC1C597B2A9CB85D931B0 /* AppModelTests.swift */; }; | ||
CA078A884067F18FDDF07E2A /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6812ADCBE2BA2C489767A918 /* AppModel.swift */; }; | ||
| @@ -45,10 +47,12 @@ | ||
419B22CBC85D0FF85FBDEF85 /* ProfileView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileView.swift; sourceTree = "<group>"; }; | ||
6812ADCBE2BA2C489767A918 /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = "<group>"; }; | ||
7CBB0175B6843A1D814BB1D7 /* OldskyUITests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = OldskyUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; | ||
7F59FB833B3B3DCBDEAB0844 /* ModerationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModerationPolicy.swift; sourceTree = "<group>"; }; | ||
813BB10D77A01E0CA7575D9E /* OldskyUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OldskyUITests.swift; sourceTree = "<group>"; }; | ||
8387EFC128494051D336F147 /* OldskyTests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = OldskyTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; | ||
9A1ABB191814FFEF245E7285 /* Models.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = "<group>"; }; | ||
AD99E9D9710A09188269126B /* OldskyApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OldskyApp.swift; sourceTree = "<group>"; }; | ||
BC6525AA8B2A2794C5FA2472 /* ModerationPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModerationPolicyTests.swift; sourceTree = "<group>"; }; | ||
C9DBEA8CDC0E2002A4CD2C1F /* Oldsky.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Oldsky.app; sourceTree = BUILT_PRODUCTS_DIR; }; | ||
FE8BC1C597B2A9CB85D931B0 /* AppModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModelTests.swift; sourceTree = "<group>"; }; | ||
/* End PBXFileReference section */ | ||
| @@ -80,6 +84,7 @@ | ||
14AA13D2048D7CB44D42A687 /* Assets.xcassets */, | ||
2779C721893B64F0C7710BFB /* BlueskyService.swift */, | ||
9A1ABB191814FFEF245E7285 /* Models.swift */, | ||
7F59FB833B3B3DCBDEAB0844 /* ModerationPolicy.swift */, | ||
AD99E9D9710A09188269126B /* OldskyApp.swift */, | ||
1540B9DF5BA7BFC210E0A873 /* PostLinks.swift */, | ||
419B22CBC85D0FF85FBDEF85 /* ProfileView.swift */, | ||
| @@ -128,6 +133,7 @@ | ||
children = ( | ||
FE8BC1C597B2A9CB85D931B0 /* AppModelTests.swift */, | ||
25B4649EB7F4F1937943943F /* ATProtoServiceTests.swift */, | ||
BC6525AA8B2A2794C5FA2472 /* ModerationPolicyTests.swift */, | ||
); | ||
path = OldskyTests; | ||
sourceTree = "<group>"; | ||
| @@ -255,6 +261,7 @@ | ||
CA078A884067F18FDDF07E2A /* AppModel.swift in Sources */, | ||
5748E268EFD526C08F791DE7 /* BlueskyService.swift in Sources */, | ||
37345BA4571D4C3923FB6DFE /* Models.swift in Sources */, | ||
8FF49F6F1E25DC79F810CD07 /* ModerationPolicy.swift in Sources */, | ||
8CF7EBCC2788E0E871B99021 /* OldskyApp.swift in Sources */, | ||
AC5ED113B191377C35CC7AAD /* PostLinks.swift in Sources */, | ||
081FA53D7337018DAAE8EC4F /* ProfileView.swift in Sources */, | ||
| @@ -275,6 +282,7 @@ | ||
files = ( | ||
0209EFCC96361379925699D8 /* ATProtoServiceTests.swift in Sources */, | ||
B7AFAF450FA4B8632008B38E /* AppModelTests.swift in Sources */, | ||
56C03F63AFA345B0649A1969 /* ModerationPolicyTests.swift in Sources */, | ||
); | ||
runOnlyForDeploymentPostprocessing = 0; | ||
}; | ||
Sources/Oldsky/AppModel.swift+375−44
419 lines changed: not loaded until asked for.
Sources/Oldsky/BlueskyService.swift+312−49
| @@ -11,12 +11,14 @@ protocol BlueskyService { | ||
func loadNotifications(cursor: String?) async throws -> NotificationPage | ||
func markNotificationsRead(seenAt: Date) async throws | ||
func loadPost(uri: String) async throws -> [Post] | ||
func loadThread(uri: String) async throws -> ThreadResult | ||
func loadProfile(actorID: String) async throws -> Profile? | ||
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? | ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post | ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? | ||
func loadModerationPreferences() async throws -> ModerationPolicy.Preferences | ||
func moderationState(actorID: String) async throws -> ModerationState | ||
func setMuted(_ muted: Bool, actorID: String) async throws | ||
func setBlocked(_ blocked: Bool, actorID: String, blockURI: String?) async throws -> String? | ||
| @@ -24,13 +26,24 @@ protocol BlueskyService { | ||
} | ||
| ||
extension BlueskyService { | ||
func loadModerationPreferences() async throws -> ModerationPolicy.Preferences { throw ServiceError.invalidResponse } | ||
func moderationState(actorID: String) async throws -> ModerationState { throw ServiceError.invalidResponse } | ||
func setMuted(_ muted: Bool, actorID: String) async throws { throw ServiceError.invalidResponse } | ||
func setBlocked(_ blocked: Bool, actorID: String, blockURI: String?) async throws -> String? { throw ServiceError.invalidResponse } | ||
func report(_ subject: ReportSubject, reason: String) async throws { throw ServiceError.invalidResponse } | ||
} | ||
| ||
extension BlueskyService { | ||
func loadThread(uri: String) async throws -> ThreadResult { | ||
ThreadResult(posts: try await loadPost(uri: uri), mutedPostIDs: []) | ||
} | ||
} | ||
| ||
struct MockBlueskyService: BlueskyService { | ||
func loadModerationPreferences() async throws -> ModerationPolicy.Preferences { | ||
.init(userDID: account.id, labelers: ProcessInfo.processInfo.arguments.contains("-ui-testing-content-warnings") ? [.init(did: ModerationPolicy.defaultLabelerDID)] : [], labelDefinitions: ModerationPolicy.builtInDefinitions, mutedWords: ProcessInfo.processInfo.arguments.contains("-ui-testing-muted-word") ? [.init(value: "water")] : []) | ||
} | ||
| ||
var failsPublishing = false | ||
var failsMarkingNotificationsRead = false | ||
var requiresAuthFactorToken = false | ||
| @@ -46,6 +59,8 @@ struct MockBlueskyService: BlueskyService { | ||
var notificationsSeenAt: [Date] = [] | ||
var authorFeedActorIDs: [String] = [] | ||
var authorFeedCursors: [String?] = [] | ||
var likes: [String: Bool] = [:] | ||
var reposts: [String: Bool] = [:] | ||
} | ||
private let loadState = LoadState() | ||
var notificationsSeenAt: [Date] { loadState.notificationsSeenAt } | ||
| @@ -101,19 +116,19 @@ struct MockBlueskyService: BlueskyService { | ||
| ||
func loadFollowingFeed(cursor: String?) async throws -> FeedPage { | ||
guard cursor != nil else { return FeedPage(posts: firstPage, cursor: "page-2") } | ||
return FeedPage(posts: [Post(id: "post-4", author: authors[0], text: "Another quiet moment from the neighborhood.", likeCount: 12, repostCount: 2, isLiked: false, isReposted: false, imageURLs: [], replyIDs: [])], cursor: nil) | ||
return FeedPage(posts: [withInteractions(Post(id: "post-4", author: authors[0], text: "Another quiet moment from the neighborhood.", likeCount: 12, repostCount: 2, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []))], cursor: nil) | ||
} | ||
| ||
func loadNotifications(cursor: String?) async throws -> NotificationPage { | ||
let now = Date() | ||
let likedPost = firstPage[0] | ||
if cursor != nil { | ||
let quote = Post(id: "quote-post-1", author: authors[2], text: "A short thought about the quoted post.", likeCount: 2, repostCount: 1, isLiked: false, isReposted: false, imageURLs: [], quote: Post.Quote(postID: "post-1"), replyIDs: []) | ||
let quote = withInteractions(Post(id: "quote-post-1", author: authors[2], text: "A short thought about the quoted post.", likeCount: 2, repostCount: 1, isLiked: false, isReposted: false, imageURLs: [], quote: Post.Quote(postID: "post-1"), replyIDs: [])) | ||
return NotificationPage(notifications: [ | ||
FeedNotification(id: "notification-4", author: authors[0], reason: .follow, indexedAt: now.addingTimeInterval(-172_800), isRead: true, postID: nil), | ||
FeedNotification(id: "notification-5", author: authors[1], reason: .repost, indexedAt: now.addingTimeInterval(-259_200), isRead: false, postID: likedPost.id, relatedPost: likedPost), | ||
FeedNotification(id: "notification-6", author: authors[2], reason: .quote, indexedAt: now.addingTimeInterval(-345_600), isRead: false, postID: quote.id, relatedPost: quote), | ||
FeedNotification(id: "notification-7", author: authors[2], reason: .mention, indexedAt: now.addingTimeInterval(-432_000), isRead: false, postID: "mention-post-1", relatedPost: Post(id: "mention-post-1", author: authors[2], text: "Take a look at this, @demo.bsky.social. The post is the main content.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: [])) | ||
FeedNotification(id: "notification-7", author: authors[2], reason: .mention, indexedAt: now.addingTimeInterval(-432_000), isRead: false, postID: "mention-post-1", relatedPost: withInteractions(Post(id: "mention-post-1", author: authors[2], text: "Take a look at this, @demo.bsky.social. The post is the main content.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []))) | ||
], cursor: nil) | ||
} | ||
let replyParent = ProcessInfo.processInfo.arguments.contains("-ui-testing-own-reply-parent") | ||
| @@ -134,7 +149,7 @@ struct MockBlueskyService: BlueskyService { | ||
) | ||
return NotificationPage(notifications: [ | ||
FeedNotification(id: "notification-1", author: authors[0], reason: .like, indexedAt: now.addingTimeInterval(-300), isRead: false, postID: likedPost.id, relatedPost: likedPost), | ||
FeedNotification(id: "notification-2", author: authors[1], reason: .reply, indexedAt: now.addingTimeInterval(-3600), isRead: false, postID: reply.id, relatedPost: reply, parentPost: replyParent), | ||
FeedNotification(id: "notification-2", author: authors[1], reason: .reply, indexedAt: now.addingTimeInterval(-3600), isRead: false, postID: reply.id, relatedPost: withInteractions(reply), parentPost: withInteractions(replyParent)), | ||
FeedNotification(id: "notification-3", author: authors[2], reason: .follow, indexedAt: now.addingTimeInterval(-86_400), isRead: true, postID: nil) | ||
], cursor: "mock-notifications-page-2") | ||
} | ||
| @@ -156,7 +171,7 @@ struct MockBlueskyService: BlueskyService { | ||
let direct = Post(id: "thread-direct", author: authors[1], text: "A direct reply to the selected post.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: root.id, replyParentURI: selected.id, replyIDs: ["thread-nested"]) | ||
let otherDirect = Post(id: "thread-other-direct", author: authors[2], text: "Another direct reply to the selected post.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: root.id, replyParentURI: selected.id, replyIDs: []) | ||
let nested = Post(id: "thread-nested", author: authors[0], text: "A nested reply that is not shown in this view.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: root.id, replyParentURI: direct.id, replyIDs: []) | ||
return [root, levelOne, levelTwo, selected, direct, nested, otherDirect] | ||
return [root, levelOne, levelTwo, selected, direct, nested, otherDirect].map(withInteractions) | ||
} | ||
| ||
if uri == "reply-post-1" { | ||
| @@ -174,7 +189,7 @@ struct MockBlueskyService: BlueskyService { | ||
replyParentURI: parent.id, | ||
replyIDs: [] | ||
) | ||
return [parent, reply] | ||
return [parent, reply].map(withInteractions) | ||
} | ||
| ||
let allPosts = firstPage | ||
| @@ -240,10 +255,16 @@ struct MockBlueskyService: BlueskyService { | ||
guard actorID == "mae" else { return FeedPage(posts: [], cursor: nil) } | ||
let morePost = Post(id: "profile-post-more", author: authors[0], text: "Another post from Mae.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []) | ||
let duplicate = firstPage.first { $0.author.id == actorID } | ||
return FeedPage(posts: [duplicate, morePost].compactMap { $0 }, cursor: nil) | ||
return FeedPage(posts: [duplicate, morePost].compactMap { $0 }.map(withInteractions), cursor: nil) | ||
} | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { | ||
loadState.likes[post.id] = liked | ||
return liked ? "mock-like-\(post.id)" : nil | ||
} | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { | ||
loadState.reposts[post.id] = reposted | ||
return reposted ? "mock-repost-\(post.id)" : nil | ||
} | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { liked ? "mock-like-\(post.id)" : nil } | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { reposted ? "mock-repost-\(post.id)" : nil } | ||
| ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { | ||
if failsPublishing { throw ServiceError.requestFailed("The post could not be published. Try again.") } | ||
| @@ -295,12 +316,39 @@ struct MockBlueskyService: BlueskyService { | ||
return count | ||
} | ||
| ||
private var firstPage: [Post] { | ||
private func withInteractions(_ original: Post) -> Post { | ||
var post = original | ||
if let liked = loadState.likes[post.id] { | ||
if post.isLiked != liked { post.likeCount = max(0, post.likeCount + (liked ? 1 : -1)) } | ||
post.isLiked = liked | ||
post.likeURI = liked ? "mock-like-\(post.id)" : nil | ||
} | ||
if let reposted = loadState.reposts[post.id] { | ||
if post.isReposted != reposted { post.repostCount = max(0, post.repostCount + (reposted ? 1 : -1)) } | ||
post.isReposted = reposted | ||
post.repostURI = reposted ? "mock-repost-\(post.id)" : nil | ||
} | ||
return post | ||
} | ||
| ||
private var firstPage: [Post] { initialPosts.map(withInteractions) } | ||
| ||
private var initialPosts: [Post] { | ||
var posts = [ | ||
Post(id: "post-1", author: authors[0], text: "Morning walk along the water. The light changed every few minutes.", likeCount: 18, repostCount: 3, isLiked: false, isReposted: false, imageURLs: [], replyIDs: ["post-2"], createdAt: Date(timeIntervalSince1970: 1714998896)), | ||
Post(id: "post-2", author: authors[1], text: "A small reminder to take breaks and look away from the screen.", likeCount: 42, repostCount: 8, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: "post-1", replyRootCID: "", replyParentURI: "post-1", replyParentCID: "", replyIDs: []), | ||
Post(id: "post-3", author: authors[2], text: "This is a quote post. Open the link to read the original.", likeCount: 7, repostCount: 1, isLiked: false, isReposted: false, imageURLs: [], quote: Post.Quote(postID: "post-2"), replyIDs: []) | ||
] | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-content-warnings") { | ||
let warning = ModerationPolicy.Label(value: "!warn", sourceDID: ModerationPolicy.defaultLabelerDID) | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-notification-warning") { | ||
posts[0].moderationLabels = [warning] | ||
} else { | ||
posts[0].quote = Post.Quote(postID: "warning-quote", author: authors[2], text: "A quoted post with a warning.", moderationLabels: [warning]) | ||
posts[1].replyRootURI = nil | ||
posts[1].replyParentURI = nil | ||
} | ||
} | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-context-quote") { | ||
posts[0].text = "A thread starts here with enough text to wrap across several lines. This text must stay above the quoted post." | ||
posts[0].quote = Post.Quote(postID: "post-3", author: authors[2], text: "The quoted post.") | ||
| @@ -377,11 +425,13 @@ actor ATProtoBlueskyService: BlueskyService { | ||
let instanceUUID = UUID() | ||
let token: String | ||
let generation: UUID | ||
let labelers: String? | ||
| ||
init(pdsURL: URL, token: String, generation: UUID) { | ||
init(pdsURL: URL, token: String, generation: UUID, labelers: String?) { | ||
self.pdsURL = pdsURL.absoluteString | ||
self.token = token | ||
self.generation = generation | ||
self.labelers = labelers | ||
} | ||
| ||
func authorization(for request: URLRequest) async throws -> SessionAuthorization? { | ||
| @@ -414,12 +464,23 @@ actor ATProtoBlueskyService: BlueskyService { | ||
private var sessionGeneration = UUID() | ||
private var refreshTask: Task<StoredSession, Error>? | ||
private var followRecordURIs: [String: String] = [:] | ||
private var selectedLabelers: [String] = [] | ||
private struct CachedLabelDefinitions { | ||
let accountDID: String | ||
let definitions: [ModerationPolicy.LabelDefinition] | ||
let fetchedAt: Date | ||
} | ||
private var cachedLabelDefinitions: [String: CachedLabelDefinitions] = [:] | ||
private let now: () -> Date | ||
private let labelDefinitionsLifetime: TimeInterval = 3600 | ||
private var moderationReloadGeneration = UUID() | ||
private let appViewURL = URL(string: "https://public.api.bsky.app")! | ||
| ||
init(defaults: UserDefaults = .standard, session: URLSession = .shared, beforeAuthenticatedDispatch: (@Sendable () async -> Void)? = nil) { | ||
init(defaults: UserDefaults = .standard, session: URLSession = .shared, beforeAuthenticatedDispatch: (@Sendable () async -> Void)? = nil, now: @escaping () -> Date = Date.init) { | ||
self.defaults = defaults | ||
self.session = session | ||
self.beforeAuthenticatedDispatch = beforeAuthenticatedDispatch | ||
self.now = now | ||
} | ||
| ||
private func apiClient(for url: URL, sessionConfiguration: SessionConfiguration? = nil, capture: ResponseCapture? = nil) async -> ATProtoKit { | ||
| @@ -430,6 +491,9 @@ actor ATProtoBlueskyService: BlueskyService { | ||
request.setValue("Bearer \(configuration.token)", forHTTPHeaderField: "Authorization") | ||
if request.url?.path.hasPrefix("/xrpc/app.bsky.") == true { | ||
request.setValue("did:web:api.bsky.app#bsky_appview", forHTTPHeaderField: "atproto-proxy") | ||
if request.httpMethod == "GET", let labelers = configuration.labelers { | ||
request.setValue(labelers, forHTTPHeaderField: "atproto-accept-labelers") | ||
} | ||
} | ||
} | ||
let isWrite = ["/xrpc/com.atproto.repo.createRecord", "/xrpc/com.atproto.repo.deleteRecord"].contains(request.url?.path ?? "") | ||
| @@ -485,7 +549,7 @@ actor ATProtoBlueskyService: BlueskyService { | ||
let generation = sessionGeneration | ||
let token = try await accessToken() | ||
guard generation == sessionGeneration, let current = stored else { throw ServiceError.noSession } | ||
let configuration = LibrarySession(pdsURL: current.pdsURL, token: token, generation: generation) | ||
let configuration = LibrarySession(pdsURL: current.pdsURL, token: token, generation: generation, labelers: selectedLabelers.isEmpty ? nil : selectedLabelers.joined(separator: ",")) | ||
let user = UserSession(handle: current.handle, sessionDID: current.did, isEmailAuthenticationFactorEnabled: nil, isActive: nil, status: nil, serviceEndpoint: current.pdsURL) | ||
await UserSessionRegistry.shared.register(configuration.instanceUUID, session: user) | ||
return await apiClient(for: current.pdsURL, sessionConfiguration: configuration, capture: capture) | ||
| @@ -544,6 +608,8 @@ actor ATProtoBlueskyService: BlueskyService { | ||
func restoreAccount() async throws -> Account? { | ||
let generation = UUID() | ||
sessionGeneration = generation | ||
selectedLabelers.removeAll() | ||
cachedLabelDefinitions.removeAll() | ||
refreshTask = nil | ||
guard let sessionID = defaults.string(forKey: sessionDefaultsKey) else { return nil } | ||
guard let data = try keychainRead(account: sessionID) else { | ||
| @@ -564,6 +630,8 @@ actor ATProtoBlueskyService: BlueskyService { | ||
guard !cleanHandle.isEmpty, !appPassword.isEmpty else { throw ServiceError.invalidCredentials } | ||
let generation = UUID() | ||
sessionGeneration = generation | ||
selectedLabelers.removeAll() | ||
cachedLabelDefinitions.removeAll() | ||
refreshTask = nil | ||
let did = try await resolveDID(for: cleanHandle) | ||
let loginPDSURL = try await resolvePDSURL(for: did) | ||
| @@ -608,9 +676,106 @@ actor ATProtoBlueskyService: BlueskyService { | ||
sessionGeneration = UUID() | ||
refreshTask = nil | ||
stored = nil | ||
selectedLabelers.removeAll() | ||
cachedLabelDefinitions.removeAll() | ||
followRecordURIs.removeAll() | ||
} | ||
| ||
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 result = ModerationPolicy.Preferences(userDID: account.did, labelDefinitions: ModerationPolicy.builtInDefinitions) | ||
var labelerIDs: [String] = [] | ||
var perLabeler: [String: [String: ModerationPolicy.LabelSetting]] = [:] | ||
func setting(_ value: String?) -> ModerationPolicy.LabelSetting? { | ||
switch value { | ||
case "ignore", "show": return .ignore | ||
case "warn": return .warn | ||
case "hide": return .hide | ||
default: return nil | ||
} | ||
} | ||
for item in items { | ||
switch item["$type"] as? String { | ||
case "app.bsky.actor.defs#adultContentPref": | ||
guard let enabled = item["enabled"] as? Bool else { throw ServiceError.invalidResponse } | ||
result.adultContentEnabled = enabled | ||
case "app.bsky.actor.defs#contentLabelPref": | ||
guard let label = item["label"] as? String, let visibility = setting(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 { | ||
result.labels[label] = visibility | ||
} | ||
case "app.bsky.actor.defs#labelersPref": | ||
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) } | ||
} | ||
case "app.bsky.actor.defs#mutedWordsPref": | ||
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) } | ||
result.mutedWords.append(.init(value: value, targets: mapped, excludeFollowing: word["actorTarget"] as? String == "exclude-following", expiresAt: Self.postDate(word["expiresAt"]))) | ||
} | ||
default: break | ||
} | ||
} | ||
let activeLabelerIDs = [ModerationPolicy.defaultLabelerDID] + labelerIDs.filter { $0 != ModerationPolicy.defaultLabelerDID } | ||
result.labelers = activeLabelerIDs.map { .init(did: $0, labels: perLabeler[$0] ?? [:]) } | ||
var definitionsByLabeler: [String: [ModerationPolicy.LabelDefinition]] = [:] | ||
do { | ||
let definitions = try await readObject { try await $0.getLabelerServices(labelerDIDs: activeLabelerIDs, isDetailed: true) } | ||
guard let views = definitions["views"] as? [[String: Any]] else { throw ServiceError.invalidResponse } | ||
for view in views { | ||
guard let creator = view["creator"] as? [String: Any], let did = creator["did"] as? String, | ||
activeLabelerIDs.contains(did), let policies = view["policies"] as? [String: Any] else { throw ServiceError.invalidResponse } | ||
var parsed: [ModerationPolicy.LabelDefinition] = [] | ||
for definition in policies["labelValueDefinitions"] as? [[String: Any]] ?? [] { | ||
guard let value = definition["identifier"] as? String, ModerationPolicy.isCustomLabelIdentifier(value) else { continue } | ||
guard let visibility = setting(definition["defaultSetting"] as? String ?? "warn"), | ||
let severity = ModerationPolicy.Severity(rawValue: definition["severity"] as? String ?? "alert"), | ||
let blur = ModerationPolicy.Blur(rawValue: definition["blurs"] as? String ?? "content") else { throw ServiceError.invalidResponse } | ||
parsed.append(.init(value: value, sourceDID: did, defaultSetting: visibility, adult: definition["adultOnly"] as? Bool ?? false, noSelf: true, severity: severity, blur: blur)) | ||
} | ||
definitionsByLabeler[did] = parsed | ||
} | ||
} catch is CancellationError { | ||
throw CancellationError() | ||
} catch { | ||
guard generation == sessionGeneration, stored?.did == account.did, reload == moderationReloadGeneration else { throw ServiceError.noSession } | ||
definitionsByLabeler.removeAll() | ||
} | ||
guard generation == sessionGeneration, stored?.did == account.did, reload == moderationReloadGeneration else { throw ServiceError.noSession } | ||
let currentTime = now() | ||
var nextCache: [String: CachedLabelDefinitions] = [:] | ||
for did in activeLabelerIDs { | ||
if let definitions = definitionsByLabeler[did] { | ||
nextCache[did] = CachedLabelDefinitions(accountDID: account.did, definitions: definitions, fetchedAt: currentTime) | ||
} else { | ||
guard let cached = cachedLabelDefinitions[did], cached.accountDID == account.did, | ||
currentTime >= cached.fetchedAt, currentTime.timeIntervalSince(cached.fetchedAt) < labelDefinitionsLifetime else { | ||
throw ServiceError.labelDefinitionsUnavailable | ||
} | ||
definitionsByLabeler[did] = cached.definitions | ||
nextCache[did] = cached | ||
} | ||
} | ||
for did in activeLabelerIDs { result.labelDefinitions += definitionsByLabeler[did] ?? [] } | ||
cachedLabelDefinitions = nextCache | ||
selectedLabelers = labelerIDs | ||
return result | ||
} | ||
| ||
func loadFollowingFeed(cursor: String?) async throws -> FeedPage { | ||
guard stored != nil else { throw ServiceError.noSession } | ||
let object = try await readObject { try await $0.getTimeline(limit: 30, cursor: cursor) } | ||
| @@ -620,7 +785,11 @@ actor ATProtoBlueskyService: BlueskyService { | ||
func loadNotifications(cursor: String?) async throws -> NotificationPage { | ||
guard stored != nil else { throw ServiceError.noSession } | ||
let object = try await readObject { try await $0.listNotifications(limit: 50, cursor: cursor) } | ||
let notificationObjects = object["notifications"] as? [[String: Any]] ?? [] | ||
guard let allNotificationObjects = object["notifications"] as? [[String: Any]] else { throw ServiceError.notificationsUnavailable } | ||
let notificationObjects = allNotificationObjects.filter { | ||
guard let author = $0["author"] as? [String: Any] else { return true } | ||
return !Self.isMuted(author) | ||
} | ||
let postURIs = Set(notificationObjects.flatMap { item -> [String] in | ||
let reason = FeedNotification.Reason(rawValue: item["reason"] as? String ?? "") ?? .unknown | ||
let subjectURI = item["reasonSubject"] as? String ?? item["recordSubject"] as? String | ||
| @@ -636,23 +805,51 @@ actor ATProtoBlueskyService: BlueskyService { | ||
return [subjectURI].compactMap { $0 } | ||
}) | ||
var postsByURI: [String: Post] = [:] | ||
var unavailablePostURIs = Set<String>() | ||
func loadPosts(_ uris: [String]) async throws -> Set<String> { | ||
let response = try await readObject { try await $0.getPosts(uris) } | ||
guard let objects = response["posts"] as? [[String: Any]] else { throw ServiceError.notificationsUnavailable } | ||
var returned = Set<String>() | ||
for object in objects { | ||
guard let uri = object["uri"] as? String, uris.contains(uri), returned.insert(uri).inserted, | ||
let author = object["author"] as? [String: Any], | ||
object["cid"] is String, author["did"] is String, author["handle"] is String, | ||
let record = object["record"] as? [String: Any], record["text"] is String else { | ||
throw ServiceError.notificationsUnavailable | ||
} | ||
if Self.isMuted(author) || isBlockedPost(object) { | ||
unavailablePostURIs.insert(uri) | ||
} else if let post = mapPost(object) { | ||
postsByURI[uri] = post | ||
} else { | ||
throw ServiceError.notificationsUnavailable | ||
} | ||
} | ||
return returned | ||
} | ||
let sortedPostURIs = postURIs.sorted() | ||
for batchStart in stride(from: 0, to: sortedPostURIs.count, by: 25) { | ||
let batchEnd = min(batchStart + 25, sortedPostURIs.count) | ||
let batch = sortedPostURIs[batchStart..<batchEnd] | ||
let batch = Array(sortedPostURIs[batchStart..<batchEnd]) | ||
do { | ||
let postObject = try await readObject { try await $0.getPosts(Array(batch)) } | ||
for post in (postObject["posts"] as? [[String: Any]] ?? []).compactMap(mapPost) | ||
where postsByURI[post.id] == nil { | ||
postsByURI[post.id] = post | ||
let returned = try await loadPosts(batch) | ||
for uri in batch where !returned.contains(uri) { | ||
if batch.count > 1 { | ||
let retry = try await loadPosts([uri]) | ||
if !retry.isEmpty { continue } | ||
} | ||
unavailablePostURIs.insert(uri) | ||
} | ||
} catch is CancellationError { | ||
throw CancellationError() | ||
} catch { | ||
continue | ||
throw ServiceError.notificationsUnavailable | ||
} | ||
} | ||
let notifications: [FeedNotification] = notificationObjects.compactMap { item -> FeedNotification? in | ||
guard let uri = item["uri"] as? String, | ||
let authorObject = item["author"] as? [String: Any], | ||
!Self.isMuted(authorObject), | ||
let did = authorObject["did"] as? String, | ||
let handle = authorObject["handle"] as? String else { return nil } | ||
let reason = FeedNotification.Reason(rawValue: item["reason"] as? String ?? "") ?? .unknown | ||
| @@ -671,22 +868,17 @@ actor ATProtoBlueskyService: BlueskyService { | ||
let postID = reason == .reply || reason == .mention || reason == .quote | ||
? item["uri"] as? String | ||
: subjectURI | ||
let activityPostObject: [String: Any]? | ||
if let activityRecord, reason == .reply || reason == .mention || reason == .quote { | ||
activityPostObject = [ | ||
"uri": uri, | ||
"cid": item["cid"] as? String ?? "", | ||
"author": authorObject, | ||
"record": activityRecord | ||
] | ||
} else { | ||
activityPostObject = nil | ||
let parentURI = replyParent?["uri"] as? String | ||
let requiredURIs: [String?] = reason == .reply ? [postID, subjectURI, parentURI] : [postID] | ||
guard !requiredURIs.compactMap({ $0 }).contains(where: { unavailablePostURIs.contains($0) }) else { return nil } | ||
if reason == .reply || reason == .mention || reason == .quote || reason == .like || reason == .repost { | ||
guard let postID, postsByURI[postID] != nil else { return nil } | ||
} | ||
if reason == .reply, parentURI == nil { return nil } | ||
let relatedPost = postID.flatMap { postsByURI[$0] } | ||
?? activityPostObject.flatMap(mapPost) | ||
return FeedNotification( | ||
id: uri, | ||
author: Post.Author(id: did, name: authorObject["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(authorObject["avatar"])), | ||
author: Post.Author(id: did, name: authorObject["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(authorObject["avatar"]), moderationLabels: Self.moderationLabels(authorObject["labels"]), isFollowing: (authorObject["viewer"] as? [String: Any])?["following"] != nil), | ||
reason: reason, | ||
indexedAt: timestamp, | ||
isRead: item["isRead"] as? Bool ?? true, | ||
| @@ -720,28 +912,50 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
| ||
func loadPost(uri: String) async throws -> [Post] { | ||
try await loadThread(uri: uri).posts | ||
} | ||
| ||
func loadThread(uri: String) async throws -> ThreadResult { | ||
let resolvedURI = try await resolvePostURI(uri) | ||
let object = try await readObject { try await $0.getPostThread(from: resolvedURI, depth: 1000, parentHeight: 1000) } | ||
guard let thread = object["thread"] as? [String: Any] else { return [] } | ||
guard let thread = object["thread"] as? [String: Any] else { return ThreadResult(posts: [], mutedPostIDs: []) } | ||
var mutedPostIDs: Set<String> = [] | ||
func recordMuted(_ value: [String: Any]) { | ||
guard let post = value["post"] as? [String: Any], | ||
let author = post["author"] as? [String: Any], Self.isMuted(author), | ||
let id = post["uri"] as? String else { return } | ||
mutedPostIDs.insert(id) | ||
} | ||
var ancestors: [Post] = [] | ||
var parent = thread["parent"] as? [String: Any] | ||
while let parentThread = parent, | ||
let postObject = parentThread["post"] as? [String: Any], | ||
let post = mapPost(postObject) { | ||
ancestors.append(post) | ||
while let parentThread = parent { | ||
recordMuted(parentThread) | ||
if let postObject = parentThread["post"] as? [String: Any], let post = mapPost(postObject) { | ||
ancestors.append(post) | ||
} | ||
parent = parentThread["parent"] as? [String: Any] | ||
} | ||
| ||
func collectMuted(_ value: [String: Any]) { | ||
recordMuted(value) | ||
for reply in value["replies"] as? [[String: Any]] ?? [] { collectMuted(reply) } | ||
} | ||
collectMuted(thread) | ||
var selectedAndReplies: [Post] = [] | ||
appendThread(thread, to: &selectedAndReplies) | ||
guard selectedAndReplies.contains(where: { $0.id == resolvedURI }) else { return [] } | ||
return ancestors.reversed() + selectedAndReplies | ||
guard selectedAndReplies.contains(where: { $0.id == resolvedURI }) else { | ||
return ThreadResult(posts: [], mutedPostIDs: mutedPostIDs) | ||
} | ||
return ThreadResult(posts: ancestors.reversed() + selectedAndReplies, mutedPostIDs: mutedPostIDs) | ||
} | ||
| ||
func loadProfile(actorID: String) async throws -> Profile? { | ||
let profile = try await getProfile(actorID: actorID) | ||
let author = Post.Author(id: profile.actorDID, name: profile.displayName ?? profile.actorHandle, handle: profile.actorHandle, avatarURL: profile.avatarImageURL) | ||
return Profile(author: author, bio: profile.description ?? "", location: nil, website: nil, followerCount: profile.followerCount ?? 0, followingCount: profile.followCount ?? 0, isFollowing: profile.viewer?.followingURI != nil, followURI: profile.viewer?.followingURI) | ||
let profile = try await readObject { try await $0.getProfile(for: actorID) } | ||
guard let did = profile["did"] as? String, let handle = profile["handle"] as? String else { throw ServiceError.invalidResponse } | ||
let viewer = profile["viewer"] as? [String: Any] | ||
let following = viewer?["following"] as? String | ||
let author = Post.Author(id: did, name: profile["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(profile["avatar"]), moderationLabels: Self.moderationLabels(profile["labels"]), isFollowing: following != nil) | ||
return Profile(author: author, bio: profile["description"] as? String ?? "", location: nil, website: nil, followerCount: profile["followersCount"] as? Int ?? 0, followingCount: profile["followsCount"] as? Int ?? 0, isFollowing: following != nil, followURI: following) | ||
} | ||
| ||
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage { | ||
| @@ -752,12 +966,22 @@ actor ATProtoBlueskyService: BlueskyService { | ||
private func mapFeedPage(_ object: [String: Any], hideBlockedPosts: Bool = false) -> FeedPage { | ||
var contexts: [String: [Post]] = [:] | ||
var repostedBy: [String: Post.Author] = [:] | ||
var mutedPostIDs: Set<String> = [] | ||
let posts = (object["feed"] as? [[String: Any]] ?? []).compactMap { item -> Post? in | ||
let reply = item["reply"] as? [String: Any] ?? [:] | ||
for value in [item["post"], reply["root"], reply["parent"]] { | ||
guard let value = value as? [String: Any] else { continue } | ||
let post = value["post"] as? [String: Any] ?? value | ||
guard let author = post["author"] as? [String: Any], Self.isMuted(author), | ||
let id = post["uri"] as? String else { continue } | ||
mutedPostIDs.insert(id) | ||
} | ||
if hideBlockedPosts && ([item["post"], reply["root"], reply["parent"]].contains { isBlockedPost($0) }) { | ||
return nil | ||
} | ||
guard let post = (item["post"] as? [String: Any]).flatMap(mapPost) else { return nil } | ||
if let reason = item["reason"] as? [String: Any], | ||
let by = reason["by"] as? [String: Any], Self.isMuted(by) { return nil } | ||
let context = ["root", "parent"].compactMap { key -> Post? in | ||
guard let value = reply[key] as? [String: Any] else { return nil } | ||
return mapPost((value["post"] as? [String: Any]) ?? value) | ||
| @@ -768,7 +992,10 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
return post | ||
} | ||
return FeedPage(posts: posts, cursor: object["cursor"] as? String, replyContexts: contexts, repostedBy: repostedBy) | ||
let visiblePosts = posts.filter { !mutedPostIDs.contains($0.id) } | ||
contexts = contexts.filter { !mutedPostIDs.contains($0.key) }.mapValues { $0.filter { !mutedPostIDs.contains($0.id) } } | ||
repostedBy = repostedBy.filter { !mutedPostIDs.contains($0.key) } | ||
return FeedPage(posts: visiblePosts, cursor: object["cursor"] as? String, replyContexts: contexts, repostedBy: repostedBy, mutedPostIDs: mutedPostIDs) | ||
} | ||
| ||
private func isBlockedPost(_ value: Any?) -> Bool { | ||
| @@ -787,7 +1014,7 @@ actor ATProtoBlueskyService: BlueskyService { | ||
reason["$type"] as? String == "app.bsky.feed.defs#reasonRepost", | ||
let by = reason["by"] as? [String: Any], | ||
let did = by["did"] as? String, let handle = by["handle"] as? String else { return nil } | ||
return Post.Author(id: did, name: by["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(by["avatar"])) | ||
return Post.Author(id: did, name: by["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(by["avatar"]), moderationLabels: Self.moderationLabels(by["labels"]), isFollowing: (by["viewer"] as? [String: Any])?["following"] != nil) | ||
} | ||
| ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { | ||
| @@ -1284,10 +1511,22 @@ actor ATProtoBlueskyService: BlueskyService { | ||
return ["index": ["byteStart": facet.byteStart, "byteEnd": facet.byteEnd], "features": [feature]] | ||
} | ||
| ||
private 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) | ||
} | ||
} | ||
| ||
private 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 | ||
} | ||
| ||
private 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 author = object["author"] as? [String: Any], | ||
let did = author["did"] as? String, | ||
let handle = author["handle"] as? String else { return nil } | ||
let record = object["record"] as? [String: Any] ?? [:] | ||
| @@ -1320,8 +1559,8 @@ actor ATProtoBlueskyService: BlueskyService { | ||
let reply = record["reply"] as? [String: Any] | ||
let root = reply?["root"] as? [String: Any] | ||
let parent = reply?["parent"] as? [String: Any] | ||
let quoteURI = Self.quoteURI(from: embed) ?? Self.quoteURI(from: record["embed"] as? [String: Any] ?? [:]) | ||
return Post(id: uri, cid: cid, author: Post.Author(id: did, name: author["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(author["avatar"])), text: rawText, likeCount: object["likeCount"] as? Int ?? 0, repostCount: object["repostCount"] as? Int ?? 0, isLiked: likeURI != nil, isReposted: repostURI != nil, imageURLs: images, 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)) | ||
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: 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), text: rawText, likeCount: object["likeCount"] as? Int ?? 0, repostCount: object["repostCount"] as? Int ?? 0, isLiked: likeURI != nil, isReposted: repostURI != nil, imageURLs: images, 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: (record["tags"] as? [String] ?? []) + facets.compactMap { if case .tag(let value) = $0.feature { return value }; return nil }, externalTitle: Self.externalMetadata(from: embed)?.title, externalDescription: Self.externalMetadata(from: embed)?.description) | ||
} | ||
| ||
private static func attachedMedia(from embed: [String: Any]) -> (images: [URL], videos: [URL], gifs: [URL], inlineGIFVideos: [URL]) { | ||
| @@ -1339,6 +1578,12 @@ actor ATProtoBlueskyService: BlueskyService { | ||
return (images, videos, gifs, inlineGIFVideos) | ||
} | ||
| ||
private static func externalMetadata(from embed: [String: Any]) -> (title: String?, description: String?)? { | ||
let media = embed["media"] as? [String: Any] ?? embed | ||
guard let external = media["external"] as? [String: Any] else { return nil } | ||
return (external["title"] as? String, external["description"] as? String) | ||
} | ||
| ||
private static func imageDescriptions(from embed: [String: Any]) -> [URL: String] { | ||
let media = embed["media"] as? [String: Any] ?? embed | ||
var descriptions: [URL: String] = [:] | ||
| @@ -1374,10 +1619,19 @@ actor ATProtoBlueskyService: BlueskyService { | ||
return urls.filter { seen.insert($0.absoluteString).inserted } | ||
} | ||
| ||
private static func suppressesQuote(_ embed: [String: Any]) -> Bool { | ||
let outer = embed["record"] as? [String: Any] ?? [:] | ||
let record = outer["record"] as? [String: Any] ?? outer | ||
if let author = record["author"] as? [String: Any], isMuted(author) { return true } | ||
let type = record["$type"] as? String | ||
return type == "app.bsky.embed.record#viewBlocked" || type == "app.bsky.embed.record#viewNotFound" || type == "app.bsky.embed.record#viewDetached" | ||
} | ||
| ||
private static func quote(from embed: [String: Any], postID: String) -> Post.Quote { | ||
let outer = embed["record"] as? [String: Any] ?? [:] | ||
let record = outer["record"] as? [String: Any] ?? outer | ||
guard let author = record["author"] as? [String: Any], | ||
!isMuted(author), | ||
let did = author["did"] as? String, | ||
let handle = author["handle"] as? String, | ||
let value = record["value"] as? [String: Any], | ||
| @@ -1393,7 +1647,7 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
return Post.Quote( | ||
postID: postID, | ||
author: Post.Author(id: did, name: author["displayName"] as? String ?? handle, handle: handle, avatarURL: url(author["avatar"])), | ||
author: Post.Author(id: did, name: author["displayName"] as? String ?? handle, handle: handle, avatarURL: url(author["avatar"]), moderationLabels: moderationLabels(author["labels"]), isFollowing: (author["viewer"] as? [String: Any])?["following"] != nil), | ||
text: text, | ||
facets: facets, | ||
imageURLs: uniqueURLs(media.flatMap(\.images) + urls.filter { Post.destination(for: $0) == .image }), | ||
| @@ -1402,7 +1656,12 @@ actor ATProtoBlueskyService: BlueskyService { | ||
createdAt: postDate(value["createdAt"]) ?? postDate(record["indexedAt"]), | ||
imageDescriptions: embeds.reduce(into: [:]) { result, embed in | ||
result.merge(imageDescriptions(from: embed)) { first, _ in first } | ||
} | ||
}, | ||
moderationLabels: moderationLabels(record["labels"]), | ||
languages: value["langs"] as? [String] ?? [], | ||
tags: (value["tags"] as? [String] ?? []) + facets.compactMap { if case .tag(let tag) = $0.feature { return tag }; return nil }, | ||
externalTitle: embeds.compactMap { externalMetadata(from: $0)?.title }.first, | ||
externalDescription: embeds.compactMap { externalMetadata(from: $0)?.description }.first | ||
) | ||
} | ||
| ||
| @@ -1517,6 +1776,8 @@ enum ServiceError: LocalizedError { | ||
case invalidRecordResponse | ||
case invalidUploadResponse | ||
case invalidResponse | ||
case notificationsUnavailable | ||
case labelDefinitionsUnavailable | ||
case invalidURL | ||
case requestFailed(String) | ||
case serverResponse(code: String, message: String) | ||
| @@ -1542,6 +1803,8 @@ enum ServiceError: LocalizedError { | ||
case .invalidRecordResponse: "Bluesky did not return the new post." | ||
case .invalidUploadResponse: "Bluesky did not accept the image upload." | ||
case .invalidResponse: "Bluesky returned a response that Old Fella could not read." | ||
case .notificationsUnavailable: "Notifications could not be loaded safely. Try again." | ||
case .labelDefinitionsUnavailable: "Moderation settings could not be loaded. Try again." | ||
case .invalidURL: "Old Fella could not create the Bluesky request." | ||
case .requestFailed(let message): message | ||
case .serverResponse(_, let message): message | ||
Sources/Oldsky/Models.swift+23−2
| @@ -14,17 +14,24 @@ struct ImageAttachment: Equatable, Identifiable { | ||
} | ||
} | ||
| ||
struct ThreadResult { | ||
let posts: [Post] | ||
let mutedPostIDs: Set<String> | ||
} | ||
| ||
struct FeedPage: Equatable { | ||
let posts: [Post] | ||
let cursor: String? | ||
let replyContexts: [String: [Post]] | ||
let repostedBy: [String: Post.Author] | ||
let mutedPostIDs: Set<String> | ||
| ||
init(posts: [Post], cursor: String?, replyContexts: [String: [Post]] = [:], repostedBy: [String: Post.Author] = [:]) { | ||
init(posts: [Post], cursor: String?, replyContexts: [String: [Post]] = [:], repostedBy: [String: Post.Author] = [:], mutedPostIDs: Set<String> = []) { | ||
self.posts = posts | ||
self.cursor = cursor | ||
self.replyContexts = replyContexts | ||
self.repostedBy = repostedBy | ||
self.mutedPostIDs = mutedPostIDs | ||
} | ||
} | ||
| ||
| @@ -72,16 +79,20 @@ struct Post: Identifiable, Equatable { | ||
private let providedName: String | ||
let handle: String | ||
var avatarURL: URL? = nil | ||
var moderationLabels: [ModerationPolicy.Label] = [] | ||
var isFollowing = false | ||
| ||
var name: String { | ||
providedName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? handle : providedName | ||
} | ||
| ||
init(id: String, name: String, handle: String, avatarURL: URL? = nil) { | ||
init(id: String, name: String, handle: String, avatarURL: URL? = nil, moderationLabels: [ModerationPolicy.Label] = [], isFollowing: Bool = false) { | ||
self.id = id | ||
self.providedName = name | ||
self.handle = handle | ||
self.avatarURL = avatarURL | ||
self.moderationLabels = moderationLabels | ||
self.isFollowing = isFollowing | ||
} | ||
} | ||
| ||
| @@ -95,6 +106,11 @@ struct Post: Identifiable, Equatable { | ||
var inlineGIFVideoURLs: [URL] = [] | ||
var createdAt: Date? = nil | ||
var imageDescriptions: [URL: String] = [:] | ||
var moderationLabels: [ModerationPolicy.Label] = [] | ||
var languages: [String] = [] | ||
var tags: [String] = [] | ||
var externalTitle: String? = nil | ||
var externalDescription: String? = nil | ||
} | ||
| ||
let id: String | ||
| @@ -122,6 +138,11 @@ struct Post: Identifiable, Equatable { | ||
var replyCount: Int = 0 | ||
var createdAt: Date? = nil | ||
var imageDescriptions: [URL: String] = [:] | ||
var moderationLabels: [ModerationPolicy.Label] = [] | ||
var languages: [String] = [] | ||
var tags: [String] = [] | ||
var externalTitle: String? = nil | ||
var externalDescription: String? = nil | ||
| ||
static func destination(for url: URL) -> MediaDestination { | ||
let path = url.path.lowercased() | ||
Sources/Oldsky/ModerationPolicy.swiftnew+255−0
| @@ -0,0 +1,255 @@ | ||
import Foundation | ||
| ||
/// A network-independent moderation decision for a post in a content list. | ||
enum ModerationPolicy { | ||
static let defaultLabelerDID = "did:plc:ar7c4by46qjdydhdevvrndac" | ||
| ||
enum Action: Int, Comparable { | ||
case allow, warn, hide | ||
static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } | ||
} | ||
| ||
enum LabelSetting { | ||
case ignore, warn, hide | ||
} | ||
| ||
struct MutedWord { | ||
enum Target: Hashable { case content, tag } | ||
var value: String | ||
var targets: Set<Target> = [.content, .tag] | ||
var excludeFollowing = false | ||
var expiresAt: Date? = nil | ||
} | ||
| ||
struct Label: Equatable { | ||
var value: String | ||
var sourceDID: String | ||
var expiresAt: Date? = nil | ||
var isNegated = false | ||
} | ||
| ||
enum WarningBehavior: String { case blur, blurMedia, alert, none } | ||
enum Severity: String { case alert, inform, none } | ||
enum Blur: String { case content, media, none } | ||
| ||
struct LabelDefinition { | ||
var value: String | ||
/// Set this for a custom definition from one labeler. | ||
var sourceDID: String? = nil | ||
var defaultSetting: LabelSetting = .ignore | ||
var configurable = true | ||
var adult = false | ||
var noSelf = false | ||
var unauthenticatedOnly = false | ||
var noOverride = false | ||
var warningBehavior: WarningBehavior = .blur | ||
var severity: Severity = .alert | ||
var blur: Blur = .content | ||
} | ||
| ||
// Based on atproto moderation/const/labels.ts at cea5189c0ca0e95cce819dcd557cc16d30f408b0. | ||
static let builtInDefinitions: [LabelDefinition] = [ | ||
.init(value: "!hide", defaultSetting: .hide, configurable: false, noOverride: true), | ||
.init(value: "!no-promote", defaultSetting: .hide, configurable: false, warningBehavior: .none), | ||
.init(value: "!warn", defaultSetting: .warn, configurable: false), | ||
.init(value: "!no-unauthenticated", defaultSetting: .hide, configurable: false, unauthenticatedOnly: true, noOverride: true), | ||
.init(value: "dmca-violation", defaultSetting: .hide, configurable: false, noOverride: true), | ||
.init(value: "doxxing", defaultSetting: .hide, configurable: false, noOverride: true) | ||
] + ["porn", "sexual", "nudity", "nsfl", "corpse", "gore", "self-harm"].map { | ||
.init(value: $0, adult: true, warningBehavior: .blurMedia) | ||
} + [.init(value: "torture", adult: true)] | ||
+ ["intolerant-race", "intolerant-gender", "intolerant-sexual-orientation", "intolerant-religion", "intolerant", "threat", "spoiler", "spam", "account-security", "net-abuse"].map { | ||
.init(value: $0) | ||
} + [.init(value: "icon-intolerant", warningBehavior: .blurMedia)] | ||
+ ["impersonation", "scam", "misleading"].map { .init(value: $0, warningBehavior: .alert) } | ||
| ||
struct Labeler { | ||
var did: String | ||
var labels: [String: LabelSetting] = [:] | ||
} | ||
| ||
struct Preferences { | ||
var userDID: String? = nil | ||
var adultContentEnabled = false | ||
var labels: [String: LabelSetting] = [:] | ||
var labelers: [Labeler] = [] | ||
var labelDefinitions: [LabelDefinition] = [] | ||
var mutedWords: [MutedWord] = [] | ||
} | ||
| ||
struct Author { | ||
var did: String | ||
var isFollowing = false | ||
var labels: [Label] = [] | ||
} | ||
| ||
struct Post { | ||
var author: Author | ||
var text: String | ||
var tags: [String] = [] | ||
var languages: [String] = [] | ||
var imageAltTexts: [String] = [] | ||
var embeddedTexts: [String] = [] | ||
var labels: [Label] = [] | ||
} | ||
| ||
enum Reason: Equatable { | ||
case mutedWord(String) | ||
case label(value: String, sourceDID: String, noOverride: Bool) | ||
} | ||
| ||
enum Context { case contentList, contentView, contentMedia, avatar, profileView } | ||
| ||
struct ContextDecision: Equatable { | ||
var filter = false | ||
var blur = false | ||
var alert = false | ||
var inform = false | ||
var noOverride = false | ||
} | ||
| ||
struct Decision: Equatable { | ||
var action: Action | ||
var reasons: [Reason] | ||
var contentList = ContextDecision() | ||
var contentView = ContextDecision() | ||
var contentMedia = ContextDecision() | ||
var avatar = ContextDecision() | ||
var profileView = ContextDecision() | ||
| ||
func ui(_ context: Context) -> ContextDecision { | ||
switch context { | ||
case .contentList: contentList | ||
case .contentView: contentView | ||
case .contentMedia: contentMedia | ||
case .avatar: avatar | ||
case .profileView: profileView | ||
} | ||
} | ||
} | ||
| ||
static func evaluate(post: Post, preferences: Preferences, now: Date) -> Decision { | ||
var action: Action = .allow | ||
var reasons: [Reason] = [] | ||
var contexts = [ContextDecision](repeating: ContextDecision(), count: 5) | ||
let isOwnPost = post.author.did == preferences.userDID | ||
| ||
if !isOwnPost { | ||
for word in preferences.mutedWords where matches(word, post: post, now: now) { | ||
action = .hide | ||
contexts[0].filter = true | ||
reasons.append(.mutedWord(word.value)) | ||
} | ||
} | ||
| ||
for (label, isAuthorLabel) in post.author.labels.map({ ($0, true) }) + post.labels.map({ ($0, false) }) { | ||
guard !label.isNegated, label.expiresAt.map({ $0 > now }) ?? true else { continue } | ||
let isSelfLabel = label.sourceDID == post.author.did | ||
let labeler = preferences.labelers.first { $0.did == label.sourceDID } | ||
guard isSelfLabel || labeler != nil else { continue } | ||
let definition = (isCustomLabelIdentifier(label.value) ? preferences.labelDefinitions.first { | ||
$0.value == label.value && $0.sourceDID == label.sourceDID | ||
} : nil) ?? preferences.labelDefinitions.first { | ||
$0.value == label.value && $0.sourceDID == nil | ||
} | ||
guard let definition else { continue } | ||
guard !(isSelfLabel && definition.noSelf), | ||
!(definition.unauthenticatedOnly && preferences.userDID != nil) else { continue } | ||
let setting: LabelSetting | ||
if !definition.configurable { | ||
setting = definition.defaultSetting | ||
} else if definition.adult && !preferences.adultContentEnabled { | ||
setting = .hide | ||
} else { | ||
setting = labeler?.labels[label.value] ?? preferences.labels[label.value] ?? definition.defaultSetting | ||
} | ||
guard setting != .ignore else { continue } | ||
let labelAction: Action = setting == .hide && !isOwnPost ? .hide : .warn | ||
action = max(action, labelAction) | ||
let noOverride = definition.noOverride || (definition.adult && !preferences.adultContentEnabled) | ||
if labelAction == .hide { contexts[0].filter = true } | ||
let behavior = definition.sourceDID == nil ? definition.warningBehavior : { | ||
switch definition.blur { | ||
case .content: return WarningBehavior.blur | ||
case .media: return WarningBehavior.blurMedia | ||
case .none: return definition.severity == .alert ? WarningBehavior.alert : WarningBehavior.none | ||
} | ||
}() | ||
switch behavior { | ||
case .blur: | ||
contexts[0].blur = true | ||
contexts[1].blur = true | ||
if isAuthorLabel { contexts[3].blur = true; contexts[4].blur = true } | ||
case .blurMedia: | ||
contexts[2].blur = true | ||
if isAuthorLabel { contexts[3].blur = true } | ||
case .alert: | ||
contexts[0].alert = true | ||
contexts[1].alert = true | ||
if isAuthorLabel { contexts[3].alert = true; contexts[4].alert = true } | ||
case .none: | ||
if definition.sourceDID != nil && definition.severity == .inform { | ||
contexts[0].inform = true | ||
contexts[1].inform = true | ||
if isAuthorLabel { contexts[3].inform = true; contexts[4].inform = true } | ||
} | ||
} | ||
if definition.sourceDID != nil { | ||
let targets = isAuthorLabel ? [0, 1, 3, 4] : [0, 1] | ||
for index in targets { | ||
if definition.severity == .alert { contexts[index].alert = true } | ||
if definition.severity == .inform { contexts[index].inform = true } | ||
} | ||
} | ||
if noOverride && behavior == .blur { | ||
contexts[0].noOverride = true | ||
contexts[1].noOverride = true | ||
if isAuthorLabel { contexts[3].noOverride = true; contexts[4].noOverride = true } | ||
} else if noOverride && behavior == .blurMedia { | ||
contexts[2].noOverride = true | ||
if isAuthorLabel { contexts[3].noOverride = true } | ||
} | ||
reasons.append(.label(value: label.value, sourceDID: label.sourceDID, noOverride: noOverride)) | ||
} | ||
return Decision(action: action, reasons: reasons, contentList: contexts[0], contentView: contexts[1], contentMedia: contexts[2], avatar: contexts[3], profileView: contexts[4]) | ||
} | ||
| ||
static func isCustomLabelIdentifier(_ value: String) -> Bool { | ||
!value.isEmpty && value.utf8.allSatisfy { (97...122).contains($0) || $0 == 45 } | ||
} | ||
| ||
private static func matches(_ word: MutedWord, post: Post, now: Date) -> Bool { | ||
guard !word.value.isEmpty, word.expiresAt.map({ $0 > now }) ?? true, | ||
!(word.excludeFollowing && post.author.isFollowing) else { return false } | ||
let value = word.value.lowercased() | ||
// Bluesky treats a content target as also applying to tags. | ||
if !word.targets.isDisjoint(with: [.content, .tag]), | ||
post.tags.contains(where: { $0.lowercased() == value }) { return true } | ||
guard word.targets.contains(.content) else { return false } | ||
return ([post.text] + post.imageAltTexts + post.embeddedTexts).contains { | ||
matchesText(value, text: $0.lowercased(), languages: post.languages) | ||
} | ||
} | ||
| ||
private static func matchesText(_ value: String, text: String, languages: [String]) -> Bool { | ||
let exceptions = ["ja", "zh", "ko", "th", "vi"] | ||
if (value.utf16.count == 1 || languages.first.map(exceptions.contains) == true), text.contains(value) { return true } | ||
if value == text { return true } | ||
let punctuation = CharacterSet.punctuationCharacters | ||
if value.unicodeScalars.contains(where: { punctuation.contains($0) || CharacterSet.whitespacesAndNewlines.contains($0) }), | ||
text.contains(value) { return true } | ||
for part in text.components(separatedBy: .whitespacesAndNewlines) { | ||
if part == value { return true } | ||
let trimmed = part.trimmingCharacters(in: punctuation) | ||
if trimmed == value { return true } | ||
guard value.utf16.count <= trimmed.utf16.count else { continue } | ||
if trimmed.unicodeScalars.contains(where: punctuation.contains) { | ||
// The reference stops checking this muted word when a token contains a slash. | ||
if trimmed.contains("/") { return false } | ||
let parts = trimmed.components(separatedBy: punctuation).filter { !$0.isEmpty } | ||
if parts.joined() == value || parts.contains(value) { return true } | ||
} | ||
} | ||
return false | ||
} | ||
} | ||
Sources/Oldsky/OldskyApp.swift+157−29
| @@ -6,6 +6,10 @@ import SwiftUI | ||
import UniformTypeIdentifiers | ||
import UIKit | ||
| ||
enum BlueskyLinks { | ||
static let moderation = URL(string: "https://bsky.app/moderation")! | ||
} | ||
| ||
enum AppPalette { | ||
private static let background = (red: 0.66, green: 0.25, blue: 0.15) | ||
private static let mark = (red: 0.98, green: 0.89, blue: 0.73) | ||
| @@ -85,6 +89,7 @@ struct OldskyApp: App { | ||
| ||
struct RootView: View { | ||
@EnvironmentObject private var model: AppModel | ||
@Environment(\.scenePhase) private var scenePhase | ||
| ||
var body: some View { | ||
Group { | ||
| @@ -109,6 +114,9 @@ struct RootView: View { | ||
SignedInTabView() | ||
} | ||
} | ||
.onChange(of: scenePhase) { _, phase in | ||
if phase == .active { model.sceneBecameActive() } | ||
} | ||
.alert("Something went wrong", isPresented: Binding( | ||
get: { model.errorMessage != nil }, | ||
set: { if !$0 { model.clearError() } } | ||
| @@ -389,7 +397,7 @@ struct NotificationsView: View { | ||
} | ||
.sheet(item: $selectedNotificationGroup) { group in | ||
NavigationStack { | ||
List(group.notifications.filter { !model.isHidden($0.author.id) && !model.isHidden($0.relatedPost?.author.id) && !model.isHidden($0.parentPost?.author.id) }) { notification in | ||
List(group.notifications.filter { notification in model.visibleNotifications.contains { $0.id == notification.id } }) { notification in | ||
Button { | ||
selectedNotificationGroup = nil | ||
path.append(.profile(notification.author.id)) | ||
| @@ -407,7 +415,10 @@ struct NotificationsView: View { | ||
} | ||
} | ||
.task(id: isActive) { | ||
if isActive { await loadAndMarkNotifications() } | ||
if isActive, model.contentPreferences != nil { await loadAndMarkNotifications() } | ||
} | ||
.onChange(of: model.contentRevision) { _, _ in | ||
if isActive { Task { await loadAndMarkNotifications() } } | ||
} | ||
.safeAreaInset(edge: .top) { | ||
if let readError { | ||
| @@ -424,8 +435,8 @@ struct NotificationsView: View { | ||
| ||
private func loadAndMarkNotifications() async { | ||
let seenAt = Date() | ||
await model.loadNotifications() | ||
guard isActive, !Task.isCancelled, model.notificationsErrorMessage == nil else { return } | ||
let accepted = await model.loadNotifications() | ||
guard accepted, isActive, !Task.isCancelled else { return } | ||
do { | ||
try await model.markNotificationsRead(seenAt: seenAt) | ||
readError = nil | ||
| @@ -440,7 +451,18 @@ struct NotificationsView: View { | ||
| ||
@ViewBuilder | ||
private var content: some View { | ||
if model.isLoadingNotifications && model.visibleNotifications.isEmpty { | ||
if let error = model.contentPreferencesError { | ||
ContentUnavailableView { | ||
Label("Could not load content preferences", systemImage: "exclamationmark.triangle") | ||
} description: { | ||
Text(error) | ||
} actions: { | ||
Button("Retry") { Task { await model.reloadContentPreferences() } } | ||
Link("Manage preferences in Bluesky", destination: BlueskyLinks.moderation) | ||
} | ||
} else if model.contentPreferences == nil { | ||
PostLoadingPlaceholder(label: "Loading content preferences") | ||
} else if model.isLoadingNotifications && model.visibleNotifications.isEmpty { | ||
PostLoadingPlaceholder(label: "Loading notifications") | ||
} else if let error = model.notificationsErrorMessage, model.visibleNotifications.isEmpty { | ||
ContentUnavailableView { | ||
| @@ -459,7 +481,15 @@ struct NotificationsView: View { | ||
VStack(alignment: .leading, spacing: 8) { | ||
Text(error) | ||
.foregroundStyle(.secondary) | ||
Button("Try Again") { Task { await model.retryNotifications() } } | ||
Button("Try Again") { | ||
Task { | ||
if model.retryNotificationsPage { | ||
await model.loadNextNotificationsPage() | ||
} else { | ||
await loadAndMarkNotifications() | ||
} | ||
} | ||
} | ||
} | ||
} | ||
ForEach(NotificationGroup.make(from: model.visibleNotifications, pageStarts: model.notificationPageStarts)) { group in | ||
| @@ -696,7 +726,7 @@ struct NotificationsView: View { | ||
} | ||
} | ||
.listStyle(.plain) | ||
.refreshable { await loadAndMarkNotifications() } | ||
.refreshable { await model.reloadContentPreferences() } | ||
} | ||
} | ||
| ||
| @@ -883,11 +913,23 @@ struct FeedView: View { | ||
.presentationDragIndicator(.visible) | ||
} | ||
.sheet(item: $moderationPost) { post in ModerationControls(author: post.author, post: post) } | ||
.onChange(of: model.contentRevision) { _, _ in Task { await model.loadFeed() } } | ||
} | ||
| ||
@ViewBuilder | ||
private var feedContent: some View { | ||
if model.isLoading && model.posts.isEmpty { | ||
if let error = model.contentPreferencesError { | ||
ContentUnavailableView { | ||
Label("Could not load content preferences", systemImage: "exclamationmark.triangle") | ||
} description: { | ||
Text(error) | ||
} actions: { | ||
Button("Retry") { Task { await model.reloadContentPreferences() } } | ||
Link("Manage preferences in Bluesky", destination: BlueskyLinks.moderation) | ||
} | ||
} else if model.contentPreferences == nil { | ||
PostLoadingPlaceholder(label: "Loading content preferences") | ||
} else if model.isLoading && model.posts.isEmpty { | ||
PostLoadingPlaceholder(label: "Loading Following") | ||
} else if model.posts.isEmpty { | ||
ContentUnavailableView { | ||
| @@ -956,7 +998,7 @@ struct FeedView: View { | ||
} | ||
} | ||
.listStyle(.plain) | ||
.refreshable { await model.loadFeed() } | ||
.refreshable { await model.reloadContentPreferences() } | ||
} | ||
} | ||
| ||
| @@ -1044,18 +1086,21 @@ struct PostDivider: View { | ||
} | ||
| ||
struct RepostAttributionRow: View { | ||
@EnvironmentObject private var model: AppModel | ||
let postID: String | ||
let author: Post.Author | ||
let openProfile: () -> Void | ||
| ||
var body: some View { | ||
Button(action: openProfile) { | ||
Label("Reposted by @\(author.handle)", systemImage: "arrow.2.squarepath") | ||
.font(.subheadline.weight(.medium)) | ||
.foregroundStyle(AppPalette.reply) | ||
if !model.isHidden(author.id), model.contentDecision(author: author)?.action == .allow { | ||
Button(action: openProfile) { | ||
Label("Reposted by @\(author.handle)", systemImage: "arrow.2.squarepath") | ||
.font(.subheadline.weight(.medium)) | ||
.foregroundStyle(AppPalette.reply) | ||
} | ||
.buttonStyle(.plain) | ||
.accessibilityIdentifier("repostAttribution-\(postID)") | ||
} | ||
.buttonStyle(.plain) | ||
.accessibilityIdentifier("repostAttribution-\(postID)") | ||
} | ||
} | ||
| ||
| @@ -1073,8 +1118,9 @@ struct ReplyContextPosts: View { | ||
var body: some View { | ||
if hideReplyContexts, let parentID = post.replyParentURI { | ||
let parent = posts.first { $0.id == parentID } ?? model.post(id: parentID) | ||
let safeParent = parent.flatMap { !model.isHidden($0.author.id) && model.contentDecision(for: $0)?.action == .allow ? $0 : nil } | ||
Button(action: { openPost(parentID) }) { | ||
Label(parent.map { "In reply to \($0.author.name)" } ?? "In reply to a post", systemImage: "arrow.turn.down.right") | ||
Label(safeParent.map { "In reply to \($0.author.name)" } ?? "In reply to a post", systemImage: "arrow.turn.down.right") | ||
.font(.subheadline.weight(.medium)) | ||
.foregroundStyle(AppPalette.reply) | ||
} | ||
| @@ -1085,8 +1131,12 @@ struct ReplyContextPosts: View { | ||
if index > 0 && model.hasMissingReplyContext(between: posts[index - 1], and: contextPost) { | ||
MissingReplyContextRow() | ||
} | ||
contextRow(for: contextPost) | ||
.padding(.bottom, 4) | ||
if !model.isHidden(contextPost.author.id), model.contentDecision(for: contextPost)?.action == .allow { | ||
contextRow(for: contextPost) | ||
.padding(.bottom, 4) | ||
} else { | ||
Text("Reply context hidden by content preferences") | ||
} | ||
} | ||
if let last = posts.last, model.hasMissingReplyContext(between: last, and: post) { | ||
MissingReplyContextRow() | ||
| @@ -1097,7 +1147,9 @@ struct ReplyContextPosts: View { | ||
| ||
private func contextRow(for contextPost: Post) -> some View { | ||
let isRoot = contextPost.id == post.replyRootURI | ||
let parent = posts.first { $0.id == contextPost.replyParentURI } | ||
let parent = posts.first { $0.id == contextPost.replyParentURI }.flatMap { | ||
!model.isHidden($0.author.id) && model.contentDecision(for: $0)?.action == .allow ? $0 : nil | ||
} | ||
return VStack(alignment: .leading, spacing: 8) { | ||
ReplyContextRow( | ||
post: contextPost, | ||
| @@ -1133,6 +1185,8 @@ struct ReplyContextPosts: View { | ||
struct PostRow: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var showingModeration = false | ||
@State private var revealedContent = false | ||
@State private var revealedMedia = false | ||
@Environment(\.accessibilityReduceMotion) private var reduceMotion | ||
let post: Post | ||
let openPost: () -> Void | ||
| @@ -1142,16 +1196,52 @@ struct PostRow: View { | ||
let openComposer: (String?, String?) -> Void | ||
var accessibilityIdentifierPrefix = "" | ||
var openModeration: ((Post) -> Void)? = nil | ||
var moderationContext: ModerationPolicy.Context = .contentList | ||
| ||
private func accessibilityIdentifier(_ identifier: String) -> String { | ||
"\(accessibilityIdentifierPrefix)\(identifier)" | ||
} | ||
| ||
var body: some View { | ||
Group { | ||
if let decision = model.contentDecision(for: post) { | ||
let ui = decision.ui(moderationContext) | ||
if decision.action == .hide { | ||
Text("Post hidden by your content preferences") | ||
} else if ui.blur && (!revealedContent || ui.noOverride) { | ||
VStack(alignment: .leading, spacing: 8) { | ||
Text("Content warning") | ||
if !ui.noOverride { Button("Show post") { revealedContent = true } } | ||
} | ||
} else { | ||
if ui.alert || ui.inform { Text("Content warning").font(.footnote).foregroundStyle(.secondary) } | ||
postContent | ||
} | ||
} else { | ||
VStack(alignment: .leading, spacing: 8) { | ||
Text(model.contentPreferencesError ?? "Loading content preferences") | ||
if model.contentPreferencesError != nil { | ||
Button("Retry") { Task { await model.reloadContentPreferences() } } | ||
Link("Manage preferences in Bluesky", destination: BlueskyLinks.moderation) | ||
} | ||
} | ||
} | ||
} | ||
.onChange(of: post) { _, _ in resetReveals() } | ||
.onChange(of: model.contentDecision(for: post)) { _, _ in resetReveals() } | ||
.onChange(of: model.contentRevision) { _, _ in resetReveals() } | ||
} | ||
| ||
private func resetReveals() { | ||
revealedContent = false | ||
revealedMedia = false | ||
} | ||
| ||
private var postContent: some View { | ||
VStack(alignment: .leading, spacing: 12) { | ||
Button(action: openProfile) { | ||
HStack(spacing: 10) { | ||
AccountAvatar(account: Account(handle: post.author.handle, displayName: post.author.name, id: post.author.id, avatarURL: post.author.avatarURL), size: 40) | ||
AccountAvatar(account: Account(handle: post.author.handle, displayName: post.author.name, id: post.author.id, avatarURL: model.contentDecision(author: post.author)?.ui(.avatar).blur == false ? post.author.avatarURL : nil), size: 40) | ||
VStack(alignment: .leading, spacing: 2) { | ||
Text(post.author.name).fontWeight(.semibold).foregroundStyle(.primary) | ||
Text("@\(post.author.handle)").font(.subheadline).foregroundStyle(.secondary) | ||
| @@ -1178,9 +1268,18 @@ struct PostRow: View { | ||
.externalLinkBrowser { PostTextFacets.openInternalURL($0, openActor: openActor, openPost: openQuotedPost) } | ||
.accessibilityIdentifier(accessibilityIdentifier("postText-\(post.id)")) | ||
| ||
InlineImages(urls: post.imageURLs, descriptions: post.imageDescriptions) | ||
GIFMedia(imageURLs: post.gifURLs, videoURLs: post.inlineGIFVideoURLs, descriptions: post.imageDescriptions) | ||
VideoLinks(urls: post.videoURLs) | ||
if let media = model.contentDecision(for: post)?.ui(.contentMedia), media.blur && (!revealedMedia || media.noOverride) { | ||
if !post.imageURLs.isEmpty || !post.gifURLs.isEmpty || !post.inlineGIFVideoURLs.isEmpty || !post.videoURLs.isEmpty { | ||
VStack(alignment: .leading, spacing: 8) { | ||
Text("Media warning") | ||
if !media.noOverride { Button("Show media") { revealedMedia = true } } | ||
} | ||
} | ||
} else { | ||
InlineImages(urls: post.imageURLs, descriptions: post.imageDescriptions) | ||
GIFMedia(imageURLs: post.gifURLs, videoURLs: post.inlineGIFVideoURLs, descriptions: post.imageDescriptions) | ||
VideoLinks(urls: post.videoURLs) | ||
} | ||
PostLinks(urls: post.links, findPost: model.post, openPost: openQuotedPost) | ||
| ||
if let quote = post.quote { | ||
| @@ -1317,7 +1416,9 @@ private struct PostTimestamp: View { | ||
} | ||
| ||
private struct QuoteContextRow: View { | ||
@EnvironmentObject private var model: AppModel | ||
@AppStorage("hideQuotedPosts") private var hideQuotedPosts = false | ||
@State private var revealedQuote = false | ||
let quote: Post.Quote | ||
let fallbackPost: Post? | ||
var respectsHideSetting = true | ||
| @@ -1330,7 +1431,18 @@ private struct QuoteContextRow: View { | ||
let openPost: () -> Void | ||
| ||
var body: some View { | ||
if respectsHideSetting && hideQuotedPosts { | ||
Group { | ||
if model.isQuoteHidden(quote, fallbackPost: fallbackPost) { | ||
EmptyView() | ||
} else if let decision = model.quoteContentDecision(quote, fallbackPost: fallbackPost), decision.action == .warn && !revealedQuote { | ||
VStack(alignment: .leading, spacing: 8) { | ||
Text("Content warning") | ||
if !decision.reasons.contains(where: { if case .label(_, _, let noOverride) = $0 { return noOverride }; return false }) { | ||
Button("Show post") { revealedQuote = true } | ||
.accessibilityIdentifier("revealQuotedPost-\(quote.postID)") | ||
} | ||
} | ||
} else if respectsHideSetting && hideQuotedPosts { | ||
Button(action: openPost) { | ||
HStack(spacing: 6) { | ||
Image(systemName: "quote.bubble") | ||
| @@ -1349,6 +1461,11 @@ private struct QuoteContextRow: View { | ||
} else { | ||
quotedPost | ||
} | ||
} | ||
.onChange(of: quote) { _, _ in revealedQuote = false } | ||
.onChange(of: fallbackPost) { _, _ in revealedQuote = false } | ||
.onChange(of: model.quoteContentDecision(quote, fallbackPost: fallbackPost)) { _, _ in revealedQuote = false } | ||
.onChange(of: model.contentRevision) { _, _ in revealedQuote = false } | ||
} | ||
| ||
private var quotedPost: some View { | ||
| @@ -1377,7 +1494,7 @@ private struct QuoteContextRow: View { | ||
.fixedSize() | ||
} | ||
if let author, showsAvatar, openProfile == nil { | ||
AccountAvatar(account: Account(handle: author.handle, displayName: author.name, id: author.id, avatarURL: author.avatarURL), size: 24) | ||
AccountAvatar(account: Account(handle: author.handle, displayName: author.name, id: author.id, avatarURL: model.contentDecision(author: author)?.ui(.avatar).blur == false ? author.avatarURL : nil), size: 24) | ||
} | ||
} | ||
.frame(minHeight: openProfile == nil ? 0 : 44) | ||
| @@ -1388,7 +1505,7 @@ private struct QuoteContextRow: View { | ||
.accessibilityIdentifier(accessibilityID) | ||
if let author, showsAvatar, let openProfile { | ||
Button { openProfile(author.id) } label: { | ||
AccountAvatar(account: Account(handle: author.handle, displayName: author.name, id: author.id, avatarURL: author.avatarURL), size: 24) | ||
AccountAvatar(account: Account(handle: author.handle, displayName: author.name, id: author.id, avatarURL: model.contentDecision(author: author)?.ui(.avatar).blur == false ? author.avatarURL : nil), size: 24) | ||
.frame(minWidth: 44, minHeight: 44) | ||
.contentShape(Rectangle()) | ||
} | ||
| @@ -2862,7 +2979,16 @@ struct PostDetailView: View { | ||
| ||
var body: some View { | ||
Group { | ||
if let post = model.post(id: postID), model.isHidden(post.author.id) { | ||
if let error = model.contentPreferencesError { | ||
ContentUnavailableView { | ||
Label("Could not load content preferences", systemImage: "exclamationmark.triangle") | ||
} description: { | ||
Text(error) | ||
} actions: { | ||
Button("Retry") { Task { await model.reloadContentPreferences() } } | ||
Link("Manage preferences in Bluesky", destination: BlueskyLinks.moderation) | ||
} | ||
} else if let post = model.post(id: postID), model.isHidden(post.author.id) { | ||
ContentUnavailableView { | ||
Label("Post hidden", systemImage: "eye.slash") | ||
} description: { | ||
| @@ -2967,7 +3093,8 @@ struct PostDetailView: View { | ||
} | ||
} | ||
.sheet(item: $moderationPost) { post in ModerationControls(author: post.author, post: post) } | ||
.task(id: postID) { await model.loadPost(id: postID) } | ||
.task(id: postID) { if model.contentPreferences != nil { await model.loadPost(id: postID) } } | ||
.onChange(of: model.contentRevision) { _, _ in Task { await model.loadPost(id: postID) } } | ||
.navigationTitle("Post") | ||
.navigationBarTitleDisplayMode(.inline) | ||
.toolbarBackground(.visible, for: .navigationBar) | ||
| @@ -2990,7 +3117,8 @@ struct PostDetailView: View { | ||
openActor: openProfile, | ||
openQuotedPost: openPost, | ||
openComposer: { replyTo, quotePostID in openComposer(replyTo ?? post.id, quotePostID) }, | ||
openModeration: { moderationPost = $0 } | ||
openModeration: { moderationPost = $0 }, | ||
moderationContext: post.id == postID ? .contentView : .contentList | ||
) | ||
} | ||
} | ||
Sources/Oldsky/ProfileView.swift+39−5
| @@ -87,10 +87,17 @@ struct ModerationControls: View { | ||
} | ||
} | ||
| ||
struct ProfileRevealKey: Equatable { | ||
let actorID: String | ||
let decision: ModerationPolicy.Decision? | ||
let contentRevision: UUID | ||
} | ||
| ||
struct ProfileView: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var showingModeration = false | ||
@State private var moderationPost: Post? | ||
@State private var revealedProfile: ProfileRevealKey? | ||
let actorID: String | ||
let openPost: (String) -> Void | ||
let openProfile: (String) -> Void | ||
| @@ -100,19 +107,44 @@ struct ProfileView: View { | ||
private var author: Post.Author? { profile?.author } | ||
private var authorPosts: [Post] { model.posts(for: actorID) } | ||
private var isFollowing: Bool { model.followingActorIDs.contains(actorID) || profile?.isFollowing == true } | ||
private var revealKey: ProfileRevealKey { | ||
ProfileRevealKey(actorID: actorID, decision: author.flatMap { model.contentDecision(author: $0) }, contentRevision: model.contentRevision) | ||
} | ||
private var profileVisible: Bool { | ||
guard let author, let decision = model.contentDecision(author: author), decision.action != .hide else { return false } | ||
let ui = decision.ui(.profileView) | ||
return !ui.blur || (revealedProfile == revealKey && !ui.noOverride) | ||
} | ||
| ||
var body: some View { | ||
List { | ||
VStack(spacing: 0) { | ||
profileHeader | ||
.padding(EdgeInsets(top: 20, leading: 16, bottom: 18, trailing: 16)) | ||
if profileVisible { | ||
if let author, let ui = model.contentDecision(author: author)?.ui(.profileView), ui.alert || ui.inform { | ||
Text("Content warning").font(.footnote).foregroundStyle(.secondary) | ||
} | ||
profileHeader | ||
.padding(EdgeInsets(top: 20, leading: 16, bottom: 18, trailing: 16)) | ||
} else { | ||
Text(model.contentPreferencesError ?? "Profile hidden by content preferences") | ||
.padding() | ||
if let author, let decision = model.contentDecision(author: author), decision.action != .hide, decision.ui(.profileView).blur, !decision.ui(.profileView).noOverride { | ||
Button("Show profile") { revealedProfile = revealKey } | ||
} | ||
if model.contentPreferencesError != nil { | ||
Button("Retry") { Task { await model.reloadContentPreferences() } } | ||
Link("Manage preferences in Bluesky", destination: BlueskyLinks.moderation) | ||
} | ||
} | ||
Divider() | ||
.accessibilityHidden(true) | ||
} | ||
.listRowInsets(EdgeInsets()) | ||
.listRowSeparator(.hidden) | ||
| ||
if model.authorPosts[actorID] == nil, let error = model.profileErrors[actorID] { | ||
if !profileVisible { | ||
EmptyView() | ||
} else if model.authorPosts[actorID] == nil, let error = model.profileErrors[actorID] { | ||
ContentUnavailableView { | ||
Label("Could not load profile posts", systemImage: "exclamationmark.triangle") | ||
} description: { | ||
| @@ -220,7 +252,9 @@ struct ProfileView: View { | ||
if let author { ModerationControls(author: author, post: nil) } | ||
} | ||
.sheet(item: $moderationPost) { post in ModerationControls(author: post.author, post: post) } | ||
.task(id: actorID) { await model.loadProfile(actorID: actorID) } | ||
.onChange(of: revealKey) { _, _ in revealedProfile = nil } | ||
.task(id: actorID) { if model.contentPreferences != nil { await model.loadProfile(actorID: actorID) } } | ||
.onChange(of: model.contentRevision) { _, _ in Task { await model.loadProfile(actorID: actorID) } } | ||
} | ||
| ||
private func profilePostsPlaceholder(label: String, identifier: String, rows: Int) -> some View { | ||
| @@ -330,7 +364,7 @@ struct ProfileView: View { | ||
| ||
@ViewBuilder | ||
private var profileAvatar: some View { | ||
if let url = author?.avatarURL { | ||
if let author, model.contentDecision(author: author)?.ui(.avatar).blur == false, let url = author.avatarURL { | ||
AsyncImage(url: url) { image in | ||
image.resizable().scaledToFill() | ||
} placeholder: { | ||
Tests/OldskyTests/AppModelTests.swift+602−9
611 lines changed: not loaded until asked for.
Tests/OldskyTests/ATProtoServiceTests.swift+183−14
| @@ -26,6 +26,96 @@ private actor WriteDispatchGate { | ||
} | ||
| ||
final class ATProtoServiceTests: XCTestCase { | ||
func testModerationPreferencesReloadAndLabelerHeaders() async throws { | ||
let suite = "ModerationPreferences.\(UUID().uuidString)" | ||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [StubURLProtocol.self] | ||
let session = URLSession(configuration: configuration) | ||
let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) | ||
let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "") | ||
let token = "header.\(payload).signature" | ||
var failDefinitions = false | ||
var omitLabeler = false | ||
var clock = Date(timeIntervalSince1970: 1_700_000_000) | ||
StubURLProtocol.handler = { request in | ||
switch request.url?.path { | ||
case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:reader\"}".utf8)) | ||
case "/did:plc:reader": return (200, Data("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":\"https://reader.example.test\"}]}".utf8)) | ||
case "/xrpc/com.atproto.server.createSession": return (200, Data("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\",\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}".utf8)) | ||
case "/xrpc/app.bsky.actor.getProfile": return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8)) | ||
case "/xrpc/app.bsky.actor.getPreferences": | ||
return (200, Data(""" | ||
{"preferences":[{"$type":"app.bsky.actor.defs#adultContentPref","enabled":true},{"$type":"app.bsky.actor.defs#contentLabelPref","label":"nudity","visibility":"hide"},{"$type":"app.bsky.actor.defs#contentLabelPref","labelerDid":"did:plc:labels","label":"custom","visibility":"warn"},{"$type":"app.bsky.actor.defs#labelersPref","labelers":[{"did":"did:plc:labels"}]},{"$type":"app.bsky.actor.defs#mutedWordsPref","items":[{"value":"spoiler","targets":["content"],"actorTarget":"exclude-following"}]}]} | ||
""".utf8)) | ||
case "/xrpc/app.bsky.labeler.getServices": | ||
if failDefinitions { return (500, Data("{}".utf8)) } | ||
if omitLabeler { return (200, Data("{\"views\":[]}".utf8)) } | ||
return (200, Data(""" | ||
{"views":[{"$type":"app.bsky.labeler.defs#labelerViewDetailed","uri":"at://did:plc:labels/app.bsky.labeler.service/self","cid":"cid","creator":{"did":"did:plc:labels","handle":"labels.example"},"indexedAt":"2024-05-06T12:34:56Z","policies":{"labelValues":["custom"],"labelValueDefinitions":[{"identifier":"custom","severity":"alert","blurs":"content","defaultSetting":"hide","adultOnly":true,"locales":[{"lang":"en","name":"Custom","description":"Custom label"}]}]}},{"$type":"app.bsky.labeler.defs#labelerViewDetailed","uri":"at://did:plc:ar7c4by46qjdydhdevvrndac/app.bsky.labeler.service/self","cid":"cid","creator":{"did":"did:plc:ar7c4by46qjdydhdevvrndac","handle":"moderation.bsky.app"},"indexedAt":"2024-05-06T12:34:56Z","policies":{"labelValues":[],"labelValueDefinitions":[]}}]} | ||
""".utf8)) | ||
case "/xrpc/app.bsky.feed.getTimeline": return (200, Data("{\"feed\":[]}".utf8)) | ||
default: XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")"); return (404, Data("{}".utf8)) | ||
} | ||
} | ||
defer { StubURLProtocol.handler = nil; session.invalidateAndCancel(); defaults.removePersistentDomain(forName: suite) } | ||
let service = ATProtoBlueskyService(defaults: defaults, session: session, now: { clock }) | ||
_ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil) | ||
let preferences = try await service.loadModerationPreferences() | ||
XCTAssertEqual(preferences.userDID, "did:plc:reader") | ||
XCTAssertTrue(preferences.adultContentEnabled) | ||
XCTAssertEqual(preferences.labels["nudity"], .hide) | ||
XCTAssertEqual(preferences.labelers.first { $0.did == "did:plc:labels" }?.labels["custom"], .warn) | ||
XCTAssertTrue(preferences.labelers.contains { $0.did == ModerationPolicy.defaultLabelerDID }) | ||
let custom = preferences.labelDefinitions.first { $0.value == "custom" && $0.sourceDID == "did:plc:labels" } | ||
XCTAssertEqual(custom?.defaultSetting, .hide) | ||
XCTAssertTrue(custom?.adult == true) | ||
XCTAssertEqual(custom?.severity, .alert) | ||
XCTAssertEqual(custom?.blur, .content) | ||
XCTAssertTrue(preferences.labelDefinitions.contains { $0.value == "porn" && $0.adult }) | ||
XCTAssertEqual(preferences.mutedWords.first?.value, "spoiler") | ||
XCTAssertTrue(preferences.mutedWords.first?.excludeFollowing == true) | ||
StubURLProtocol.clearRequests() | ||
_ = try await service.loadFollowingFeed(cursor: nil) | ||
XCTAssertEqual(StubURLProtocol.recordedRequests.last?.value(forHTTPHeaderField: "atproto-accept-labelers"), "did:plc:labels") | ||
failDefinitions = true | ||
clock.addTimeInterval(3599) | ||
let cached = try await service.loadModerationPreferences() | ||
XCTAssertTrue(cached.labelDefinitions.contains { $0.value == "custom" && $0.sourceDID == "did:plc:labels" }) | ||
StubURLProtocol.clearRequests() | ||
_ = try await service.loadFollowingFeed(cursor: nil) | ||
XCTAssertEqual(StubURLProtocol.recordedRequests.last?.value(forHTTPHeaderField: "atproto-accept-labelers"), "did:plc:labels") | ||
clock.addTimeInterval(1) | ||
do { | ||
_ = try await service.loadModerationPreferences() | ||
XCTFail("Expected expired definitions to fail") | ||
} catch ServiceError.labelDefinitionsUnavailable {} | ||
failDefinitions = false | ||
_ = try await service.loadModerationPreferences() | ||
failDefinitions = true | ||
try await service.signOut() | ||
_ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil) | ||
do { | ||
_ = try await service.loadModerationPreferences() | ||
XCTFail("Expected a new session to fetch definitions") | ||
} catch ServiceError.labelDefinitionsUnavailable {} | ||
failDefinitions = false | ||
omitLabeler = true | ||
do { | ||
_ = try await service.loadModerationPreferences() | ||
XCTFail("Expected missing definitions to fail") | ||
} catch ServiceError.labelDefinitionsUnavailable {} | ||
omitLabeler = false | ||
let recovered = try await service.loadModerationPreferences() | ||
XCTAssertEqual(recovered.labels["nudity"], .hide) | ||
XCTAssertEqual(recovered.labelers.first { $0.did == "did:plc:labels" }?.labels["custom"], .warn) | ||
try await service.signOut() | ||
do { _ = try await service.loadModerationPreferences(); XCTFail("Expected sign-in requirement") } catch {} | ||
StubURLProtocol.clearRequests() | ||
_ = try await service.loadProfile(actorID: "did:plc:reader") | ||
XCTAssertNil(StubURLProtocol.recordedRequests.last?.value(forHTTPHeaderField: "atproto-accept-labelers")) | ||
} | ||
| ||
func testModerationRequestsAndFailure() async throws { | ||
let suite = "ModerationTests.\(UUID().uuidString)" | ||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) | ||
| @@ -127,6 +217,29 @@ final class ATProtoServiceTests: XCTestCase { | ||
) | ||
} | ||
| ||
func testMutedQuoteAndAncestorAreNotRestoredFromCachedContent() async throws { | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [StubURLProtocol.self] | ||
let session = URLSession(configuration: configuration) | ||
let selected = "at://did:plc:author/app.bsky.feed.post/selected" | ||
let quoted = "at://did:plc:muted/app.bsky.feed.post/quoted" | ||
func post(_ uri: String, muted: Bool = false) -> [String: Any] { | ||
["uri": uri, "cid": "cid", "author": ["did": "did:plc:author", "handle": "author.example", "viewer": ["muted": muted]], "record": ["text": "text"], "indexedAt": "2024-05-06T12:34:56.123Z"] | ||
} | ||
var selectedPost = post(selected) | ||
selectedPost["embed"] = ["$type": "app.bsky.embed.record#view", "record": ["$type": "app.bsky.embed.record#viewRecord", "uri": quoted, "cid": "cid", "author": ["did": "did:plc:muted", "handle": "muted.example", "viewer": ["muted": true]], "value": ["text": "hidden"], "indexedAt": "2024-05-06T12:34:56.123Z"]] | ||
let grandparent = "at://did:plc:author/app.bsky.feed.post/grandparent" | ||
let parent = "at://did:plc:author/app.bsky.feed.post/parent" | ||
let thread: [String: Any] = ["post": selectedPost, "parent": ["post": post(parent, muted: true), "parent": ["post": post(grandparent)]]] | ||
StubURLProtocol.handler = { _ in (200, try! JSONSerialization.data(withJSONObject: ["thread": thread])) } | ||
defer { StubURLProtocol.handler = nil; session.invalidateAndCancel() } | ||
let service = ATProtoBlueskyService(defaults: .standard, session: session) | ||
let result = try await service.loadThread(uri: selected) | ||
XCTAssertEqual(result.posts.map(\.id), [grandparent, selected]) | ||
XCTAssertEqual(result.mutedPostIDs, [parent]) | ||
XCTAssertNil(result.posts.last?.quote) | ||
} | ||
| ||
func testLoadPostPreservesTextAndMapsOnlyValidFacets() async throws { | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [StubURLProtocol.self] | ||
| @@ -304,6 +417,10 @@ final class ATProtoServiceTests: XCTestCase { | ||
"presentation": "gif" | ||
] | ||
]) | ||
let directExternal = post("direct-external", embed: [ | ||
"$type": "app.bsky.embed.external#view", | ||
"external": ["uri": "https://example.test/article", "title": "Article title", "description": "Article description"] | ||
]) | ||
let facetGIFText = "see animation" | ||
let externalGIF = post("external-gif", embed: [ | ||
"$type": "app.bsky.embed.recordWithMedia#view", | ||
| @@ -320,7 +437,7 @@ final class ATProtoServiceTests: XCTestCase { | ||
embed: ["$type": "app.bsky.embed.images#view", "images": [["thumb": "https://cdn.example.test/photo-thumb.jpg", "fullsize": "https://cdn.example.test/photo.jpg", "alt": "Photo"]]] | ||
) | ||
let responseData = try JSONSerialization.data(withJSONObject: [ | ||
"feed": [attachedImage, attachedVideo, attachedGIFVideo, nestedImage, nestedVideo, nestedGIFVideo, externalGIF, textMedia, duplicateTextImage].map { ["post": $0] } | ||
"feed": [attachedImage, attachedVideo, attachedGIFVideo, nestedImage, nestedVideo, nestedGIFVideo, directExternal, externalGIF, textMedia, duplicateTextImage].map { ["post": $0] } | ||
]) | ||
StubURLProtocol.clearRequests() | ||
StubURLProtocol.handler = { request in | ||
| @@ -336,6 +453,14 @@ final class ATProtoServiceTests: XCTestCase { | ||
let service = ATProtoBlueskyService(defaults: .standard, session: session) | ||
let feed = try await service.loadAuthorPosts(actorID: "did:plc:media", cursor: nil) | ||
let posts = Dictionary(uniqueKeysWithValues: feed.posts.map { ($0.id, $0) }) | ||
let direct = try XCTUnwrap(posts["at://did:plc:media/app.bsky.feed.post/direct-external"]) | ||
XCTAssertEqual(direct.externalTitle, "Article title") | ||
XCTAssertEqual(direct.externalDescription, "Article description") | ||
let nested = try XCTUnwrap(posts["at://did:plc:media/app.bsky.feed.post/external-gif"]) | ||
XCTAssertEqual(nested.externalTitle, "GIF") | ||
XCTAssertEqual(nested.externalDescription, "A person nods") | ||
XCTAssertEqual(nested.quote?.externalTitle, "GIF") | ||
XCTAssertEqual(nested.quote?.externalDescription, "Quoted GIF") | ||
let imageURL = try XCTUnwrap(URL(string: "https://cdn.example.test/photo.jpg")) | ||
let nestedImageURL = try XCTUnwrap(URL(string: "https://cdn.example.test/nested.png")) | ||
let videoURL = try XCTUnwrap(URL(string: "https://video.example.test/playlist.m3u8")) | ||
| @@ -777,7 +902,7 @@ final class ATProtoServiceTests: XCTestCase { | ||
try await service.signOut() | ||
} | ||
| ||
func testNotificationPostHydrationBatchesAtProtocolLimitAndKeepsSuccessfulBatches() async throws { | ||
func testNotificationPostHydrationRejectsFailedAndPartialBatches() async throws { | ||
let suiteName = "OldskyNotificationBatchTests.\(UUID().uuidString)" | ||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) | ||
let configuration = URLSessionConfiguration.ephemeral | ||
| @@ -808,6 +933,10 @@ final class ATProtoServiceTests: XCTestCase { | ||
] | ||
} | ||
var failPostURI: String? = postURI(25) | ||
var omitPostURI: String? | ||
var omitOnlyFromBatch = false | ||
var mutedPostURI: String? | ||
var malformedPostURI: String? | ||
var batchSizes: [Int] = [] | ||
StubURLProtocol.clearRequests() | ||
StubURLProtocol.handler = { request in | ||
| @@ -833,14 +962,16 @@ final class ATProtoServiceTests: XCTestCase { | ||
if let failPostURI, uris.contains(failPostURI) { | ||
return (500, Data("{\"error\":\"Unavailable\"}".utf8)) | ||
} | ||
let posts: [[String: Any]] = uris.enumerated().map { index, uri in | ||
[ | ||
let posts: [[String: Any]] = uris.filter { $0 != omitPostURI || (omitOnlyFromBatch && uris.count == 1) }.enumerated().map { index, uri in | ||
var post: [String: Any] = [ | ||
"uri": uri, | ||
"cid": "post-cid-\(index)", | ||
"author": ["did": "did:plc:reader", "handle": "reader.example", "displayName": "Reader"], | ||
"author": ["did": "did:plc:reader", "handle": "reader.example", "displayName": "Reader", "viewer": ["muted": uri == mutedPostURI]], | ||
"record": ["text": "Hydrated post \(uri)"], | ||
"indexedAt": "2025-01-02T03:04:05.000Z" | ||
] | ||
if uri == malformedPostURI { post.removeValue(forKey: "record") } | ||
return post | ||
} | ||
let response = try! JSONSerialization.data(withJSONObject: ["posts": posts]) | ||
return (200, response) | ||
| @@ -857,15 +988,46 @@ final class ATProtoServiceTests: XCTestCase { | ||
let service = ATProtoBlueskyService(defaults: defaults, session: session) | ||
_ = try await service.signIn(handle: "reader.example", appPassword: "dedicated-app-password", authFactorToken: nil) | ||
| ||
let partiallyHydrated = try await service.loadNotifications(cursor: nil) | ||
XCTAssertEqual(partiallyHydrated.notifications.count, 60) | ||
XCTAssertEqual(batchSizes, [25, 25, 10]) | ||
XCTAssertEqual(partiallyHydrated.notifications.filter { $0.relatedPost != nil }.count, 35) | ||
XCTAssertEqual(partiallyHydrated.notifications.first?.relatedPost?.id, postURI(0)) | ||
XCTAssertNil(partiallyHydrated.notifications.first { $0.postID == postURI(25) }?.relatedPost) | ||
XCTAssertEqual(partiallyHydrated.notifications.first { $0.postID == postURI(50) }?.relatedPost?.id, postURI(50)) | ||
do { | ||
_ = try await service.loadNotifications(cursor: nil) | ||
XCTFail("Expected a failed batch to reject the page") | ||
} catch ServiceError.notificationsUnavailable {} | ||
XCTAssertEqual(batchSizes, [25, 25]) | ||
| ||
failPostURI = nil | ||
omitPostURI = postURI(25) | ||
omitOnlyFromBatch = true | ||
batchSizes = [] | ||
let recovered = try await service.loadNotifications(cursor: nil) | ||
XCTAssertEqual(batchSizes, [25, 25, 1, 10]) | ||
XCTAssertEqual(recovered.notifications.count, 60) | ||
XCTAssertEqual(recovered.notifications.first { $0.postID == postURI(25) }?.relatedPost?.id, postURI(25)) | ||
| ||
malformedPostURI = postURI(25) | ||
do { | ||
_ = try await service.loadNotifications(cursor: nil) | ||
XCTFail("Expected a malformed retry to reject the page") | ||
} catch ServiceError.notificationsUnavailable {} | ||
malformedPostURI = nil | ||
| ||
omitOnlyFromBatch = false | ||
mutedPostURI = postURI(26) | ||
batchSizes = [] | ||
let filtered = try await service.loadNotifications(cursor: nil) | ||
XCTAssertEqual(batchSizes, [25, 25, 1, 10]) | ||
XCTAssertEqual(filtered.notifications.count, 58) | ||
XCTAssertFalse(filtered.notifications.contains { $0.postID == postURI(25) || $0.postID == postURI(26) }) | ||
XCTAssertTrue(filtered.notifications.allSatisfy { $0.relatedPost?.id == $0.postID }) | ||
| ||
omitPostURI = nil | ||
mutedPostURI = nil | ||
malformedPostURI = postURI(25) | ||
do { | ||
_ = try await service.loadNotifications(cursor: nil) | ||
XCTFail("Expected a malformed post to reject the page") | ||
} catch ServiceError.notificationsUnavailable {} | ||
| ||
malformedPostURI = nil | ||
batchSizes = [] | ||
let fullyHydrated = try await service.loadNotifications(cursor: nil) | ||
XCTAssertEqual(batchSizes, [25, 25, 10]) | ||
| @@ -1032,6 +1194,10 @@ final class ATProtoServiceTests: XCTestCase { | ||
let body: [String: Any] = ["feed": [ | ||
["post": post("timeline-repost"), "reason": ["$type": "app.bsky.feed.defs#reasonRepost", "indexedAt": "2024-05-06T12:34:56.123Z", "by": ["did": "did:plc:reader", "handle": "reader.bsky.social"]]], | ||
["post": post("timeline-quote")], | ||
["post": post("muted-post", viewer: ["muted": true])], | ||
["post": post("list-muted-post", viewer: ["mutedByList": ["uri": "at://did:plc:reader/app.bsky.graph.list/muted", "cid": "bafk-list", "name": "Muted accounts", "purpose": "app.bsky.graph.defs#modlist"]])], | ||
["post": post("not-muted-post", viewer: ["muted": false])], | ||
["post": post("muted-repost"), "reply": ["root": post("root"), "parent": post("parent")], "reason": ["$type": "app.bsky.feed.defs#reasonRepost", "indexedAt": "2024-05-06T12:34:56.123Z", "by": ["did": "did:plc:muted", "handle": "muted.example", "viewer": ["muted": true]]]], | ||
["post": post("direct-blocked", viewer: ["blocking": "at://block"])], | ||
["post": post("direct-blocked-by", viewer: ["blockedBy": true])], | ||
["post": post("direct-list-blocked", viewer: ["blockingByList": ["uri": "at://did:plc:reader/app.bsky.graph.list/blocked", "cid": "bafk-list", "name": "Blocked accounts", "purpose": "app.bsky.graph.defs#modlist"]])], | ||
| @@ -1060,7 +1226,7 @@ final class ATProtoServiceTests: XCTestCase { | ||
XCTAssertEqual(request.url?.host, "pds.example.test") | ||
XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer \(token)") | ||
XCTAssertEqual(request.value(forHTTPHeaderField: "atproto-proxy"), "did:web:api.bsky.app#bsky_appview") | ||
return (200, Data(#"{"posts":[{"uri":"at://did:plc:reader/app.bsky.feed.post/selected","cid":"selected-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social","displayName":"Reader","avatar":"https://cdn.bsky.app/img/avatar/reader.jpeg"},"record":{"text":"The post that was liked."},"indexedAt":"2025-01-02T03:04:05.000Z"},{"uri":"at://did:plc:reader/app.bsky.feed.post/parent","cid":"parent-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social","displayName":"Reader"},"record":{"text":"My original post."},"indexedAt":"2025-01-02T03:04:05.000Z"}]}"#.utf8)) | ||
return (200, Data(#"{"posts":[{"uri":"at://did:plc:reader/app.bsky.feed.post/reply-1","cid":"reply-cid","author":{"did":"did:plc:actor","handle":"actor.example","displayName":"Actor"},"record":{"text":"Here is the actual reply."},"indexedAt":"2025-01-02T03:05:05.000Z"},{"uri":"at://did:plc:reader/app.bsky.feed.post/selected","cid":"selected-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social","displayName":"Reader","avatar":"https://cdn.bsky.app/img/avatar/reader.jpeg"},"record":{"text":"The post that was liked."},"indexedAt":"2025-01-02T03:04:05.000Z"},{"uri":"at://did:plc:reader/app.bsky.feed.post/parent","cid":"parent-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social","displayName":"Reader"},"record":{"text":"My original post."},"indexedAt":"2025-01-02T03:04:05.000Z"}]}"#.utf8)) | ||
case "/xrpc/app.bsky.feed.getPostThread": | ||
return (200, Data(#"{"thread":{"parent":{"post":{"uri":"at://did:plc:reader/app.bsky.feed.post/root","cid":"root-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social"},"record":{"text":"Root"},"replyCount":7},"parent":null},"post":{"uri":"at://did:plc:reader/app.bsky.feed.post/selected","cid":"selected-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social"},"record":{"text":"Selected","reply":{"root":{"uri":"at://did:plc:reader/app.bsky.feed.post/root","cid":"root-cid"},"parent":{"uri":"at://did:plc:reader/app.bsky.feed.post/root","cid":"root-cid"}}}},"replies":[{"post":{"uri":"at://did:plc:reader/app.bsky.feed.post/reply","cid":"reply-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social"},"record":{"text":"Reply"}},"replies":[{"post":{"uri":"at://did:plc:reader/app.bsky.feed.post/nested","cid":"nested-cid","author":{"did":"did:plc:reader","handle":"reader.bsky.social"},"record":{"text":"Nested"}},"replies":[]}] }]}}"#.utf8)) | ||
case "/xrpc/com.atproto.repo.uploadBlob": | ||
| @@ -1087,8 +1253,11 @@ final class ATProtoServiceTests: XCTestCase { | ||
XCTAssertEqual(account.displayName, "Reader") | ||
let feed = try await service.loadFollowingFeed(cursor: nil) | ||
XCTAssertEqual(feed.cursor, "next-page") | ||
XCTAssertEqual(feed.posts.map(\.id), ["timeline-repost", "timeline-quote", "visible-reply", "unavailable-parent"]) | ||
XCTAssertEqual(feed.mutedPostIDs, ["muted-post", "list-muted-post"]) | ||
XCTAssertFalse(feed.mutedPostIDs.contains("muted-repost")) | ||
XCTAssertEqual(feed.posts.map(\.id), ["timeline-repost", "timeline-quote", "not-muted-post", "visible-reply", "unavailable-parent"]) | ||
XCTAssertEqual(feed.replyContexts["visible-reply"]?.map(\.id), ["root", "parent"]) | ||
XCTAssertNil(feed.replyContexts["muted-repost"]) | ||
XCTAssertEqual(feed.repostedBy["timeline-repost"]?.id, "did:plc:reader") | ||
XCTAssertNil(feed.repostedBy["timeline-quote"]) | ||
let loadedProfile = try await service.loadProfile(actorID: "did:plc:reader") | ||
Tests/OldskyTests/ModerationPolicyTests.swiftnew+180−0
| @@ -0,0 +1,180 @@ | ||
import Foundation | ||
import XCTest | ||
@testable import Oldsky | ||
| ||
final class ModerationPolicyTests: XCTestCase { | ||
private let now = Date(timeIntervalSince1970: 1_700_000_000) | ||
private var author: ModerationPolicy.Author { .init(did: "did:example:author") } | ||
| ||
func testDefaultLabelerAndBuiltInDefinitions() { | ||
let did = ModerationPolicy.defaultLabelerDID | ||
let preferences = ModerationPolicy.Preferences(labels: ["spam": .warn], labelers: [.init(did: did)], labelDefinitions: ModerationPolicy.builtInDefinitions) | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [.init(value: "spam", sourceDID: did)]) | ||
XCTAssertEqual(evaluate(post, preferences).action, .warn) | ||
let blocked = ModerationPolicy.Post(author: author, text: "", labels: [.init(value: "!hide", sourceDID: did)]) | ||
XCTAssertEqual(evaluate(blocked, preferences).action, .hide) | ||
} | ||
| ||
func testContextDecisionsSeparateMediaAndContent() { | ||
let did = ModerationPolicy.defaultLabelerDID | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [.init(value: "porn", sourceDID: did)]) | ||
let prefs = ModerationPolicy.Preferences(adultContentEnabled: true, labels: ["porn": .warn], labelers: [.init(did: did)], labelDefinitions: ModerationPolicy.builtInDefinitions) | ||
let result = evaluate(post, prefs) | ||
XCTAssertFalse(result.ui(.contentList).filter) | ||
XCTAssertFalse(result.ui(.contentView).blur) | ||
XCTAssertTrue(result.ui(.contentMedia).blur) | ||
XCTAssertFalse(result.ui(.avatar).blur) | ||
} | ||
| ||
func testAuthorMediaWarningDoesNotBlurProfile() { | ||
let did = ModerationPolicy.defaultLabelerDID | ||
let labeledAuthor = ModerationPolicy.Author(did: "did:example:author", labels: [.init(value: "porn", sourceDID: did)]) | ||
let post = ModerationPolicy.Post(author: labeledAuthor, text: "") | ||
let prefs = ModerationPolicy.Preferences(labelers: [.init(did: did)], labelDefinitions: ModerationPolicy.builtInDefinitions) | ||
let result = evaluate(post, prefs) | ||
XCTAssertTrue(result.ui(.avatar).blur) | ||
XCTAssertTrue(result.ui(.avatar).noOverride) | ||
XCTAssertTrue(result.ui(.contentMedia).blur) | ||
XCTAssertFalse(result.ui(.profileView).blur) | ||
XCTAssertFalse(result.ui(.profileView).noOverride) | ||
} | ||
| ||
func testNoOverrideOnlyAppliesToTheMatchingContext() { | ||
let did = ModerationPolicy.defaultLabelerDID | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [ | ||
.init(value: "spam", sourceDID: did), | ||
.init(value: "porn", sourceDID: did) | ||
]) | ||
let prefs = ModerationPolicy.Preferences(labels: ["spam": .warn], labelers: [.init(did: did)], labelDefinitions: ModerationPolicy.builtInDefinitions) | ||
let result = evaluate(post, prefs) | ||
XCTAssertTrue(result.ui(.contentView).blur) | ||
XCTAssertFalse(result.ui(.contentView).noOverride) | ||
XCTAssertTrue(result.ui(.contentMedia).blur) | ||
XCTAssertTrue(result.ui(.contentMedia).noOverride) | ||
XCTAssertTrue(result.ui(.contentList).filter) | ||
} | ||
| ||
func testCustomInformAndMediaBlur() { | ||
let did = "did:example:labeler" | ||
let label = ModerationPolicy.Label(value: "custom", sourceDID: did) | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [label]) | ||
var definition = ModerationPolicy.LabelDefinition(value: "custom", sourceDID: did, defaultSetting: .warn, severity: .inform, blur: .none) | ||
var prefs = ModerationPolicy.Preferences(labelers: [.init(did: did)], labelDefinitions: [definition]) | ||
XCTAssertTrue(evaluate(post, prefs).ui(.contentView).inform) | ||
definition.blur = .media | ||
prefs.labelDefinitions = [definition] | ||
XCTAssertTrue(evaluate(post, prefs).ui(.contentMedia).blur) | ||
XCTAssertFalse(evaluate(post, prefs).ui(.contentView).blur) | ||
} | ||
| ||
func testMutedWordsMatchBoundariesPunctuationAndPhrases() { | ||
let word = ModerationPolicy.MutedWord(value: "cat") | ||
let prefs = ModerationPolicy.Preferences(mutedWords: [word]) | ||
XCTAssertEqual(decide("A CAT!", prefs).action, .hide) | ||
XCTAssertEqual(decide("cat-like", prefs).action, .hide) | ||
XCTAssertEqual(decide("a catalog", prefs).action, .allow) | ||
XCTAssertEqual(decide("a/b cat", prefs).action, .allow) | ||
let phrase = ModerationPolicy.Preferences(mutedWords: [.init(value: "red cat")]) | ||
XCTAssertEqual(decide("a red cat!", phrase).action, .hide) | ||
} | ||
| ||
func testTagsAltTextLanguagesAndSingleCharacters() { | ||
let tagOnly = ModerationPolicy.Preferences(mutedWords: [.init(value: "Swift", targets: [.tag])]) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "swift"), tagOnly).action, .allow) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "", tags: ["SWIFT"]), tagOnly).action, .hide) | ||
let content = ModerationPolicy.Preferences(mutedWords: [.init(value: "cat", targets: [.content])]) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "", tags: ["cat"]), content).action, .hide) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "", imageAltTexts: ["A cat"]), content).action, .hide) | ||
let japanese = ModerationPolicy.Preferences(mutedWords: [.init(value: "東京")]) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "東京都", languages: ["ja"]), japanese).action, .hide) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "東京都"), japanese).action, .allow) | ||
XCTAssertEqual(decide("catalog", .init(mutedWords: [.init(value: "a")])).action, .hide) | ||
} | ||
| ||
func testExpirationFollowingAndOwnPost() { | ||
let expired = ModerationPolicy.MutedWord(value: "cat", expiresAt: now) | ||
XCTAssertEqual(decide("cat", .init(mutedWords: [expired])).action, .allow) | ||
let active = ModerationPolicy.MutedWord(value: "cat", excludeFollowing: true, expiresAt: now.addingTimeInterval(1)) | ||
let prefs = ModerationPolicy.Preferences(mutedWords: [active]) | ||
XCTAssertEqual(decide("cat", prefs).action, .hide) | ||
XCTAssertEqual(evaluate(.init(author: .init(did: "other", isFollowing: true), text: "cat"), prefs).action, .allow) | ||
XCTAssertEqual(evaluate(.init(author: author, text: "cat"), .init(userDID: author.did, mutedWords: [active])).action, .allow) | ||
} | ||
| ||
func testLabelsRequireKnownSourceAndDefinition() { | ||
let label = ModerationPolicy.Label(value: "graphic", sourceDID: "did:labeler") | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [label]) | ||
let def = ModerationPolicy.LabelDefinition(value: "graphic", defaultSetting: .warn) | ||
XCTAssertEqual(evaluate(post, .init(labelDefinitions: [def])).action, .allow) | ||
XCTAssertEqual(evaluate(post, .init(labelers: [.init(did: label.sourceDID)])).action, .allow) | ||
XCTAssertEqual(evaluate(post, .init(labels: ["graphic": .ignore], labelers: [.init(did: label.sourceDID)])).action, .allow) | ||
let prefs = ModerationPolicy.Preferences(labelers: [.init(did: label.sourceDID)], labelDefinitions: [def]) | ||
let decision = evaluate(post, prefs) | ||
XCTAssertEqual(decision.action, .warn) | ||
XCTAssertEqual(decision.reasons, [.label(value: "graphic", sourceDID: label.sourceDID, noOverride: false)]) | ||
} | ||
| ||
func testLabelPrecedenceAdultAndProvenance() { | ||
let label = ModerationPolicy.Label(value: "adult", sourceDID: "did:labeler") | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [label]) | ||
let def = ModerationPolicy.LabelDefinition(value: "adult", defaultSetting: .warn, adult: true) | ||
let labeler = ModerationPolicy.Labeler(did: label.sourceDID, labels: ["adult": .ignore]) | ||
var prefs = ModerationPolicy.Preferences(labels: ["adult": .hide], labelers: [labeler], labelDefinitions: [def]) | ||
let hidden = evaluate(post, prefs) | ||
XCTAssertEqual(hidden.action, .hide) | ||
XCTAssertEqual(hidden.reasons, [.label(value: "adult", sourceDID: label.sourceDID, noOverride: true)]) | ||
prefs.adultContentEnabled = true | ||
XCTAssertEqual(evaluate(post, prefs).action, .allow) | ||
prefs.labelers[0].labels["adult"] = .warn | ||
XCTAssertEqual(evaluate(post, prefs).action, .warn) | ||
} | ||
| ||
func testLabelExpirySelfAndCustomDefinitions() { | ||
let ownLabel = ModerationPolicy.Label(value: "notice", sourceDID: author.did) | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [ownLabel]) | ||
var def = ModerationPolicy.LabelDefinition(value: "notice", defaultSetting: .hide) | ||
XCTAssertEqual(evaluate(post, .init(labelDefinitions: [def])).action, .hide) | ||
def.noSelf = true | ||
XCTAssertEqual(evaluate(post, .init(labelDefinitions: [def])).action, .allow) | ||
def.noSelf = false | ||
XCTAssertEqual(evaluate(post, .init(userDID: author.did, labelDefinitions: [def])).action, .warn) | ||
var expired = ownLabel | ||
expired.expiresAt = now | ||
XCTAssertEqual(evaluate(.init(author: author, text: "", labels: [expired]), .init(labelDefinitions: [def])).action, .allow) | ||
var negated = ownLabel | ||
negated.isNegated = true | ||
XCTAssertEqual(evaluate(.init(author: author, text: "", labels: [negated]), .init(labelDefinitions: [def])).action, .allow) | ||
let otherDefinition = ModerationPolicy.LabelDefinition(value: "notice", sourceDID: "other", defaultSetting: .hide) | ||
XCTAssertEqual(evaluate(post, .init(labelDefinitions: [otherDefinition])).action, .allow) | ||
} | ||
| ||
func testEmbeddedTextContributesToMutedWords() { | ||
let prefs = ModerationPolicy.Preferences(mutedWords: [.init(value: "spoiler")]) | ||
for text in ["quoted spoiler", "image spoiler", "link spoiler"] { | ||
let post = ModerationPolicy.Post(author: author, text: "ordinary", embeddedTexts: [text]) | ||
XCTAssertEqual(evaluate(post, prefs).action, .hide) | ||
} | ||
} | ||
| ||
func testReservedLabelsCannotBeOverridden() { | ||
let did = "did:example:labeler" | ||
let fake = ModerationPolicy.LabelDefinition(value: "!hide", sourceDID: did, defaultSetting: .ignore) | ||
let prefs = ModerationPolicy.Preferences(labelers: [.init(did: did)], labelDefinitions: [fake] + ModerationPolicy.builtInDefinitions) | ||
let post = ModerationPolicy.Post(author: author, text: "", labels: [.init(value: "!hide", sourceDID: did)]) | ||
let decision = evaluate(post, prefs) | ||
XCTAssertEqual(decision.action, .hide) | ||
XCTAssertTrue(decision.contentView.noOverride) | ||
XCTAssertTrue(ModerationPolicy.isCustomLabelIdentifier("custom-label")) | ||
for value in ["", "!hide", "UPPER", "a1", "café"] { | ||
XCTAssertFalse(ModerationPolicy.isCustomLabelIdentifier(value)) | ||
} | ||
} | ||
| ||
private func decide(_ text: String, _ prefs: ModerationPolicy.Preferences) -> ModerationPolicy.Decision { | ||
evaluate(.init(author: author, text: text), prefs) | ||
} | ||
| ||
private func evaluate(_ post: ModerationPolicy.Post, _ prefs: ModerationPolicy.Preferences) -> ModerationPolicy.Decision { | ||
ModerationPolicy.evaluate(post: post, preferences: prefs, now: now) | ||
} | ||
} | ||
Tests/OldskyUITests/OldskyUITests.swift+54−1
| @@ -1,6 +1,58 @@ | ||
import XCTest | ||
| ||
final class OldskyUITests: XCTestCase { | ||
func testMutedWordHidesMatchingPost() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-muted-word"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
XCTAssertTrue(app.buttons["postText-post-2"].waitForExistence(timeout: 5)) | ||
XCTAssertFalse(app.buttons["postText-post-1"].exists) | ||
} | ||
| ||
func testQuotedPostWarningRevealsContent() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-content-warnings"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let reveal = app.buttons["revealQuotedPost-warning-quote"].firstMatch | ||
XCTAssertTrue(reveal.waitForExistence(timeout: 5)) | ||
XCTAssertFalse(app.buttons["quotedPostText-warning-quote"].exists) | ||
reveal.tap() | ||
XCTAssertTrue(app.buttons["quotedPostText-warning-quote"].firstMatch.waitForExistence(timeout: 5)) | ||
} | ||
| ||
func testQuotedPostWarningReturnsAfterRefresh() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-content-warnings"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let reveal = app.buttons["revealQuotedPost-warning-quote"].firstMatch | ||
XCTAssertTrue(reveal.waitForExistence(timeout: 5)) | ||
reveal.tap() | ||
XCTAssertTrue(app.buttons["quotedPostText-warning-quote"].firstMatch.waitForExistence(timeout: 5)) | ||
let feed = app.collectionViews.firstMatch | ||
feed.swipeDown() | ||
let start = feed.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.2)) | ||
let end = feed.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.9)) | ||
start.press(forDuration: 0.1, thenDragTo: end) | ||
XCTAssertTrue(reveal.waitForExistence(timeout: 5)) | ||
XCTAssertFalse(app.buttons["quotedPostText-warning-quote"].exists) | ||
} | ||
| ||
func testNotificationPostWarningRevealsContent() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-content-warnings", "-ui-testing-notification-warning"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
app.tabBars.buttons["Notifications"].tap() | ||
let reveal = app.buttons["revealQuotedPost-post-1"] | ||
XCTAssertTrue(reveal.waitForExistence(timeout: 5)) | ||
XCTAssertFalse(app.buttons["quotedPostText-post-1"].exists) | ||
reveal.tap() | ||
XCTAssertTrue(app.buttons["quotedPostText-post-1"].waitForExistence(timeout: 5)) | ||
} | ||
| ||
func testFeedModerationSheetStaysOpenAfterMute() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing"] | ||
| @@ -806,7 +858,8 @@ final class OldskyUITests: XCTestCase { | ||
XCTAssertTrue(post.waitForExistence(timeout: 5)) | ||
post.tap() | ||
XCTAssertTrue(app.navigationBars["Post"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(app.buttons["Unlike"].firstMatch.exists) | ||
XCTAssertTrue(app.buttons["postText-post-2"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(app.buttons["Unlike"].firstMatch.waitForExistence(timeout: 5)) | ||
app.navigationBars["Post"].buttons.element(boundBy: 0).tap() | ||
XCTAssertTrue(app.staticTexts["profileDisplayName"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(post.isHittable) | ||
README.md+2−0
| @@ -6,6 +6,8 @@ Old Fella is an iPhone app for Bluesky. It keeps the interface small and puts po | ||
| ||
Sign in with an existing Bluesky account and an app password. You can read your Following feed, view profiles and conversations, and see notifications inside the app. You can also write posts and replies, attach images, like and repost, quote posts, and follow accounts. Old Fella does not send push notifications. | ||
| ||
Old Fella has incomplete support for Bluesky content labels and muted words. Do not rely on the app to hide or warn about all content that matches your preferences. | ||
| ||
If a report result is unknown, do not send it again. A second report can create a duplicate. Old Fella blocks another report for that subject during the current session. This protection ends when you sign out or restart the app. | ||
| ||
## Requirements | ||