feat(moderation): add account and post controls
Sources/Oldsky/AppModel.swift+106−7
| @@ -11,6 +11,7 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var isRestoringSession = true | ||
@Published private(set) var isLoadingMore = false | ||
@Published private(set) var isSigningIn = false | ||
@Published private(set) var isSigningOut = false | ||
@Published private(set) var requiresAuthFactorToken = false | ||
@Published private(set) var authFactorErrorMessage: String? | ||
@Published private(set) var isPublishing = false | ||
| @@ -18,6 +19,11 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var loadingProfileIDs: Set<String> = [] | ||
@Published private(set) var errorMessage: String? | ||
@Published private(set) var followingActorIDs: Set<String> = [] | ||
@Published private(set) var moderationStates: [String: ModerationState] = [:] | ||
@Published private(set) var moderationBusy: Set<String> = [] | ||
@Published private(set) var uncertainModerationIDs: [String: Set<ModerationAction>] = [:] | ||
@Published private(set) var moderationError: String? | ||
@Published private(set) var uncertainReports: Set<ReportRetryKey> = [] | ||
@Published private(set) var profiles: [String: Profile] = [:] | ||
@Published private(set) var authorPosts: [String: [Post]] = [:] | ||
@Published private(set) var profileCursors: [String: String] = [:] | ||
| @@ -32,6 +38,7 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var hasMoreNotifications = false | ||
@Published private(set) var notificationsErrorMessage: String? | ||
| ||
private var moderationSession = UUID() | ||
private let service: any BlueskyService | ||
private var cursor: String? | ||
private var notificationsCursor: String? | ||
| @@ -41,8 +48,12 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var failedPostIDs: Set<String> = [] | ||
private var timelinePostIDs: Set<String> = [] | ||
| ||
var visibleNotifications: [FeedNotification] { | ||
notifications.filter { !isHidden($0.author.id) && !isHidden($0.relatedPost?.author.id) && !isHidden($0.parentPost?.author.id) } | ||
} | ||
| ||
var timelinePosts: [Post] { | ||
posts.filter { timelinePostIDs.contains($0.id) } | ||
posts.filter { timelinePostIDs.contains($0.id) && !isHidden($0.author.id) && !isHidden(repostedBy[$0.id]?.id) } | ||
} | ||
| ||
init(service: (any BlueskyService)? = nil) { | ||
| @@ -62,7 +73,13 @@ final class AppModel: ObservableObject { | ||
} | ||
| ||
func signIn(handle: String, appPassword: String, authFactorToken: String? = nil) async { | ||
guard !isSigningIn else { return } | ||
guard !isSigningIn, !isSigningOut else { return } | ||
moderationSession = UUID() | ||
moderationStates = [:] | ||
moderationBusy = [] | ||
uncertainModerationIDs = [:] | ||
uncertainReports = [] | ||
moderationError = nil | ||
isSigningIn = true | ||
errorMessage = nil | ||
authFactorErrorMessage = nil | ||
| @@ -96,8 +113,12 @@ final class AppModel: ObservableObject { | ||
} | ||
| ||
func signOut() async { | ||
guard !isSigningOut else { return } | ||
isSigningOut = true | ||
defer { isSigningOut = false } | ||
do { | ||
try await service.signOut() | ||
moderationSession = UUID() | ||
account = nil | ||
posts = [] | ||
notifications = [] | ||
| @@ -115,6 +136,11 @@ final class AppModel: ObservableObject { | ||
cursor = nil | ||
hasMorePosts = false | ||
followingActorIDs = [] | ||
moderationStates = [:] | ||
moderationBusy = [] | ||
uncertainModerationIDs = [:] | ||
uncertainReports = [] | ||
moderationError = nil | ||
profiles = [:] | ||
authorPosts = [:] | ||
profileCursors = [:] | ||
| @@ -241,6 +267,75 @@ final class AppModel: ObservableObject { | ||
} | ||
} | ||
| ||
func isHidden(_ actorID: String?) -> Bool { | ||
guard let actorID, let state = moderationStates[actorID] else { return false } | ||
return state.isMuted || state.isBlocked | ||
} | ||
| ||
func loadModeration(actorID: String) async -> Bool { | ||
guard account != nil, !isSigningOut, moderationBusy.insert(actorID).inserted else { return false } | ||
let session = moderationSession | ||
defer { if session == moderationSession { moderationBusy.remove(actorID) } } | ||
do { | ||
let state = try await service.moderationState(actorID: actorID) | ||
guard session == moderationSession else { return false } | ||
var merged = state | ||
if let previous = moderationStates[actorID] { | ||
if uncertainModerationIDs[actorID]?.contains(.mute) == true { merged.isMuted = previous.isMuted } | ||
if uncertainModerationIDs[actorID]?.contains(.block) == true { merged.blockURI = previous.blockURI } | ||
} | ||
moderationStates[actorID] = merged | ||
return true | ||
} catch { | ||
if session == moderationSession { moderationError = "Could not load account controls. Try again. \(error.localizedDescription)" } | ||
return false | ||
} | ||
} | ||
| ||
func setModeration(actorID: String, block: Bool) async { | ||
let action: ModerationAction = block ? .block : .mute | ||
guard account != nil, !isSigningOut, uncertainModerationIDs[actorID]?.contains(action) != true, var state = moderationStates[actorID], moderationBusy.insert(actorID).inserted else { return } | ||
let session = moderationSession | ||
defer { if session == moderationSession { moderationBusy.remove(actorID) } } | ||
do { | ||
if block { | ||
state.blockURI = try await service.setBlocked(!state.isBlocked, actorID: actorID, blockURI: state.blockURI) | ||
} else { | ||
try await service.setMuted(!state.isMuted, actorID: actorID) | ||
state.isMuted.toggle() | ||
} | ||
guard session == moderationSession else { return } | ||
moderationStates[actorID] = state | ||
} catch ModerationWriteError.rejected(let message) { | ||
if session == moderationSession { moderationError = "The server rejected the action. \(message)" } | ||
} catch { | ||
if session == moderationSession { | ||
uncertainModerationIDs[actorID, default: []].insert(action) | ||
moderationError = "The action may have succeeded. Check this account in Bluesky before changing it again." | ||
} | ||
} | ||
} | ||
| ||
func submitReport(_ subject: ReportSubject, reason: String) async -> Bool { | ||
let key = "report" | ||
guard account != nil, !isSigningOut, !uncertainReports.contains(subject.retryKey), moderationBusy.insert(key).inserted else { return false } | ||
let session = moderationSession | ||
defer { if session == moderationSession { moderationBusy.remove(key) } } | ||
do { | ||
try await service.report(subject, reason: reason) | ||
return session == moderationSession | ||
} catch ModerationWriteError.rejected(let message) { | ||
if session == moderationSession { moderationError = "The report was not sent. \(message)" } | ||
return false | ||
} catch { | ||
if session == moderationSession { | ||
uncertainReports.insert(subject.retryKey) | ||
moderationError = "The report result is unknown. Sending it again can create a duplicate report." | ||
} | ||
return false | ||
} | ||
} | ||
| ||
func toggleFollow(actorID: String) async { | ||
let newValue = !followingActorIDs.contains(actorID) | ||
do { | ||
| @@ -313,6 +408,10 @@ final class AppModel: ObservableObject { | ||
errorMessage = nil | ||
} | ||
| ||
func clearModerationError() { | ||
moderationError = nil | ||
} | ||
| ||
func post(id: String) -> Post? { | ||
if let post = posts.first(where: { $0.id == id }) { return post } | ||
for key in replyContexts.keys.sorted() { | ||
| @@ -356,7 +455,7 @@ final class AppModel: ObservableObject { | ||
let byID = Dictionary(available.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) | ||
var context: [Post] = [] | ||
for id in [post.replyRootURI, post.replyParentURI].compactMap({ $0 }) where id != post.id { | ||
if let item = byID[id], !context.contains(where: { $0.id == item.id }) { | ||
if let item = byID[id], !isHidden(item.author.id), !context.contains(where: { $0.id == item.id }) { | ||
context.append(item) | ||
} | ||
} | ||
| @@ -383,7 +482,7 @@ final class AppModel: ObservableObject { | ||
ancestors.append(ancestor) | ||
nextID = ancestor.replyParentURI | ||
} | ||
return ancestors.reversed() | ||
return ancestors.reversed().filter { !isHidden($0.author.id) } | ||
} | ||
| ||
func directReplies(to post: Post) -> [Post] { | ||
| @@ -400,7 +499,7 @@ final class AppModel: ObservableObject { | ||
var seen: Set<String> = [] | ||
return candidateIDs.compactMap { id in | ||
guard id != currentPost.id, seen.insert(id).inserted, | ||
let candidate = self.post(id: id) else { return nil } | ||
let candidate = self.post(id: id), !isHidden(candidate.author.id) else { return nil } | ||
if let explicitParentID = candidate.replyParentURI { | ||
return explicitParentID == currentPost.id ? candidate : nil | ||
} | ||
| @@ -418,7 +517,7 @@ final class AppModel: ObservableObject { | ||
let selectedIndex = thread.firstIndex(where: { $0.id == selectedPost.id }) else { | ||
return directReplies(to: selectedPost) | ||
} | ||
return thread.dropFirst(selectedIndex + 1).compactMap { post(id: $0.id) } | ||
return thread.dropFirst(selectedIndex + 1).compactMap { post(id: $0.id) }.filter { !isHidden($0.author.id) } | ||
} | ||
| ||
func loadProfile(actorID: String) async { | ||
| @@ -480,6 +579,6 @@ final class AppModel: ObservableObject { | ||
| ||
func posts(for actorID: String) -> [Post] { | ||
let profilePosts = authorPosts[actorID] ?? posts.filter { $0.author.id == actorID } | ||
return profilePosts.map { post(id: $0.id) ?? $0 } | ||
return profilePosts.map { post(id: $0.id) ?? $0 }.filter { !isHidden($0.author.id) && !isHidden(profileRepostedBy[actorID]?[$0.id]?.id) } | ||
} | ||
} | ||
Sources/Oldsky/BlueskyService.swift+97−10
| @@ -17,6 +17,17 @@ protocol BlueskyService { | ||
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 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? | ||
func report(_ subject: ReportSubject, reason: String) async throws | ||
} | ||
| ||
extension BlueskyService { | ||
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 } | ||
} | ||
| ||
struct MockBlueskyService: BlueskyService { | ||
| @@ -240,6 +251,20 @@ struct MockBlueskyService: BlueskyService { | ||
} | ||
| ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? { following ? "mock-follow-\(actorID)" : nil } | ||
func moderationState(actorID: String) async throws -> ModerationState { | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-moderation-delay") { try await Task.sleep(nanoseconds: 3_000_000_000) } | ||
return ModerationState() | ||
} | ||
func setMuted(_ muted: Bool, actorID: String) async throws { | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-moderation-failure") { throw ServiceError.requestFailed("The account action failed.") } | ||
} | ||
func setBlocked(_ blocked: Bool, actorID: String, blockURI: String?) async throws -> String? { | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-moderation-failure") { throw ServiceError.requestFailed("The account action failed.") } | ||
return blocked ? "mock-block-\(actorID)" : nil | ||
} | ||
func report(_ subject: ReportSubject, reason: String) async throws { | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-moderation-failure") { throw ServiceError.requestFailed("The report failed.") } | ||
} | ||
| ||
private static func mockFacet(in text: String, matching target: String, feature: PostFacet.Feature) -> PostFacet { | ||
guard let range = text.range(of: target) else { | ||
| @@ -542,14 +567,12 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
| ||
func signOut() async throws { | ||
if let sessionID = defaults.string(forKey: sessionDefaultsKey) { | ||
try keychainDelete(account: sessionID) | ||
defaults.removeObject(forKey: sessionDefaultsKey) | ||
} | ||
sessionGeneration = UUID() | ||
refreshTask = nil | ||
guard let sessionID = defaults.string(forKey: sessionDefaultsKey) else { | ||
stored = nil | ||
return | ||
} | ||
try keychainDelete(account: sessionID) | ||
defaults.removeObject(forKey: sessionDefaultsKey) | ||
stored = nil | ||
followRecordURIs.removeAll() | ||
} | ||
| @@ -824,6 +847,57 @@ actor ATProtoBlueskyService: BlueskyService { | ||
return nil | ||
} | ||
| ||
func moderationState(actorID: String) async throws -> ModerationState { | ||
guard stored != nil else { throw ServiceError.noSession } | ||
let object = try await readObject { try await $0.getProfile(for: actorID) } | ||
guard let viewer = object["viewer"] as? [String: Any] else { throw ServiceError.invalidResponse } | ||
return ModerationState(isMuted: viewer["muted"] as? Bool ?? false, blockURI: viewer["blocking"] as? String) | ||
} | ||
| ||
private func moderationRequest(_ method: String, body: [String: Any], proxy: String? = nil) async throws -> [String: Any] { | ||
guard let current = stored else { throw ModerationWriteError.rejected("Sign in again.") } | ||
let url = current.pdsURL.appendingPathComponent("xrpc/\(method)") | ||
let data: Data | ||
do { data = try JSONSerialization.data(withJSONObject: body) } | ||
catch { throw ModerationWriteError.rejected("The request could not be prepared.") } | ||
let (response, _) = try await send(to: url, method: "POST", body: data, contentType: "application/json", authenticated: true, proxyService: proxy, classifyModerationWrite: true) | ||
if response.isEmpty { return [:] } | ||
return try decodeObject(response) | ||
} | ||
| ||
func setMuted(_ muted: Bool, actorID: String) async throws { | ||
let method = muted ? "app.bsky.graph.muteActor" : "app.bsky.graph.unmuteActor" | ||
_ = try await moderationRequest(method, body: ["actor": actorID], proxy: "did:web:api.bsky.app#bsky_appview") | ||
} | ||
| ||
func setBlocked(_ blocked: Bool, actorID: String, blockURI: String?) async throws -> String? { | ||
guard let current = stored else { throw ModerationWriteError.rejected("Sign in again.") } | ||
if blocked { | ||
let record: [String: Any] = ["$type": "app.bsky.graph.block", "subject": actorID, "createdAt": ISO8601DateFormatter().string(from: Date())] | ||
let result = try await moderationRequest("com.atproto.repo.createRecord", body: ["repo": current.did, "collection": "app.bsky.graph.block", "record": record]) | ||
guard let uri = result["uri"] as? String else { throw ServiceError.invalidRecordResponse } | ||
return uri | ||
} | ||
guard let blockURI else { throw ModerationWriteError.rejected("The block record is missing. Reload account controls.") } | ||
let parts = blockURI.split(separator: "/") | ||
guard parts.count == 4, parts[1] == Substring(current.did), parts[2] == "app.bsky.graph.block" else { | ||
throw ModerationWriteError.rejected("The block record is invalid. Reload account controls.") | ||
} | ||
_ = try await moderationRequest("com.atproto.repo.deleteRecord", body: ["repo": current.did, "collection": "app.bsky.graph.block", "rkey": String(parts[3])]) | ||
return nil | ||
} | ||
| ||
func report(_ subject: ReportSubject, reason: String) async throws { | ||
let value: [String: Any] | ||
switch subject { | ||
case .account(let did): value = ["$type": "com.atproto.admin.defs#repoRef", "did": did] | ||
case .post(let uri, let cid): | ||
guard !cid.isEmpty else { throw ModerationWriteError.rejected("This post is missing information needed for a report.") } | ||
value = ["$type": "com.atproto.repo.strongRef", "uri": uri, "cid": cid] | ||
} | ||
_ = try await moderationRequest("com.atproto.moderation.createReport", body: ["reasonType": reason, "subject": value], proxy: "did:plc:ar7c4by46qjdydhdevvrndac#atproto_labeler") | ||
} | ||
| ||
private struct TypedRecord<Record: ATRecordProtocol>: ATRecordProtocol { | ||
static var type: String { Record.type } | ||
let record: Record | ||
| @@ -911,7 +985,8 @@ actor ATProtoBlueskyService: BlueskyService { | ||
authenticated: Bool = false, | ||
retried: Bool = false, | ||
proxyService: String? = nil, | ||
authorizationToken: String? = nil | ||
authorizationToken: String? = nil, | ||
classifyModerationWrite: Bool = false | ||
) async throws -> (Data, HTTPURLResponse) { | ||
var request = URLRequest(url: url) | ||
request.httpMethod = method | ||
| @@ -924,8 +999,16 @@ actor ATProtoBlueskyService: BlueskyService { | ||
if let authorizationToken { | ||
request.setValue("Bearer \(authorizationToken)", forHTTPHeaderField: "Authorization") | ||
} else if authenticated { | ||
let token = try await accessToken() | ||
guard generation == sessionGeneration else { throw ServiceError.noSession } | ||
let token: String | ||
do { token = try await accessToken() } | ||
catch { | ||
if classifyModerationWrite { throw ModerationWriteError.rejected("The request was not sent. Sign in again or try again.") } | ||
throw error | ||
} | ||
guard generation == sessionGeneration else { | ||
if classifyModerationWrite { throw ModerationWriteError.rejected("The request was not sent. Sign in again.") } | ||
throw ServiceError.noSession | ||
} | ||
requestToken = token | ||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | ||
} | ||
| @@ -941,11 +1024,15 @@ actor ATProtoBlueskyService: BlueskyService { | ||
contentType: contentType, | ||
retried: true, | ||
proxyService: proxyService, | ||
authorizationToken: token | ||
authorizationToken: token, | ||
classifyModerationWrite: classifyModerationWrite | ||
) | ||
} | ||
guard (200..<300).contains(http.statusCode) else { | ||
let body = (try? JSONDecoder().decode(APIErrorBody.self, from: data)) | ||
if classifyModerationWrite, http.statusCode == 400, body?.error == "InvalidRequest" { | ||
throw ModerationWriteError.rejected(body?.message ?? "The server rejected the request.") | ||
} | ||
if body?.error == "AuthFactorTokenRequired" { | ||
throw ServiceError.authFactorTokenRequired | ||
} | ||
Sources/Oldsky/Models.swift+31−0
| @@ -211,6 +211,37 @@ struct Account: Equatable { | ||
} | ||
} | ||
| ||
enum ModerationAction: Hashable { | ||
case mute, block | ||
} | ||
| ||
enum ModerationWriteError: Error { | ||
case rejected(String) | ||
} | ||
| ||
struct ModerationState: Equatable { | ||
var isMuted = false | ||
var blockURI: String? = nil | ||
var isBlocked: Bool { blockURI != nil } | ||
} | ||
| ||
enum ReportSubject: Hashable { | ||
case account(String) | ||
case post(uri: String, cid: String) | ||
| ||
var retryKey: ReportRetryKey { | ||
switch self { | ||
case .account(let did): .account(did) | ||
case .post(let uri, _): .post(uri) | ||
} | ||
} | ||
} | ||
| ||
enum ReportRetryKey: Hashable { | ||
case account(String) | ||
case post(String) | ||
} | ||
| ||
struct Profile: Equatable { | ||
let author: Post.Author | ||
let bio: String | ||
Sources/Oldsky/OldskyApp.swift+42−10
| @@ -389,7 +389,7 @@ struct NotificationsView: View { | ||
} | ||
.sheet(item: $selectedNotificationGroup) { group in | ||
NavigationStack { | ||
List(group.notifications) { notification in | ||
List(group.notifications.filter { !model.isHidden($0.author.id) && !model.isHidden($0.relatedPost?.author.id) && !model.isHidden($0.parentPost?.author.id) }) { notification in | ||
Button { | ||
selectedNotificationGroup = nil | ||
path.append(.profile(notification.author.id)) | ||
| @@ -440,9 +440,9 @@ struct NotificationsView: View { | ||
| ||
@ViewBuilder | ||
private var content: some View { | ||
if model.isLoadingNotifications && model.notifications.isEmpty { | ||
if model.isLoadingNotifications && model.visibleNotifications.isEmpty { | ||
PostLoadingPlaceholder(label: "Loading notifications") | ||
} else if let error = model.notificationsErrorMessage, model.notifications.isEmpty { | ||
} else if let error = model.notificationsErrorMessage, model.visibleNotifications.isEmpty { | ||
ContentUnavailableView { | ||
Label("Could not load notifications", systemImage: "bell.slash") | ||
} description: { | ||
| @@ -451,7 +451,7 @@ struct NotificationsView: View { | ||
Button("Try Again") { Task { await loadAndMarkNotifications() } } | ||
.buttonStyle(.borderedProminent) | ||
} | ||
} else if model.notifications.isEmpty { | ||
} else if model.visibleNotifications.isEmpty { | ||
ContentUnavailableView("No notifications yet", systemImage: "bell", description: Text("New activity will appear here.")) | ||
} else { | ||
List { | ||
| @@ -462,7 +462,7 @@ struct NotificationsView: View { | ||
Button("Try Again") { Task { await model.retryNotifications() } } | ||
} | ||
} | ||
ForEach(NotificationGroup.make(from: model.notifications, pageStarts: model.notificationPageStarts)) { group in | ||
ForEach(NotificationGroup.make(from: model.visibleNotifications, pageStarts: model.notificationPageStarts)) { group in | ||
let notification = group.notifications[0] | ||
VStack(spacing: 0) { | ||
if group.notifications.count > 1 { | ||
| @@ -835,6 +835,7 @@ struct FeedView: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var path: [AppRoute] = [] | ||
@State private var composeRequest: ComposeRequest? | ||
@State private var moderationPost: Post? | ||
| ||
var body: some View { | ||
NavigationStack(path: $path) { | ||
| @@ -881,6 +882,7 @@ struct FeedView: View { | ||
.presentationDetents([.large]) | ||
.presentationDragIndicator(.visible) | ||
} | ||
.sheet(item: $moderationPost) { post in ModerationControls(author: post.author, post: post) } | ||
} | ||
| ||
@ViewBuilder | ||
| @@ -965,7 +967,8 @@ struct FeedView: View { | ||
openProfile: { path.append(.profile(post.author.id)) }, | ||
openActor: { path.append(.profile($0)) }, | ||
openQuotedPost: { path.append(.post($0)) }, | ||
openComposer: { reply, quote in showComposer(replyTo: reply, quotePostID: quote) } | ||
openComposer: { reply, quote in showComposer(replyTo: reply, quotePostID: quote) }, | ||
openModeration: { moderationPost = $0 } | ||
) | ||
} | ||
| ||
| @@ -1128,6 +1131,7 @@ struct ReplyContextPosts: View { | ||
| ||
struct PostRow: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var showingModeration = false | ||
@Environment(\.accessibilityReduceMotion) private var reduceMotion | ||
let post: Post | ||
let openPost: () -> Void | ||
| @@ -1136,6 +1140,7 @@ struct PostRow: View { | ||
let openQuotedPost: (String) -> Void | ||
let openComposer: (String?, String?) -> Void | ||
var accessibilityIdentifierPrefix = "" | ||
var openModeration: ((Post) -> Void)? = nil | ||
| ||
private func accessibilityIdentifier(_ identifier: String) -> String { | ||
"\(accessibilityIdentifierPrefix)\(identifier)" | ||
| @@ -1183,7 +1188,7 @@ struct PostRow: View { | ||
} | ||
} | ||
| ||
HStack(spacing: 0) { | ||
HStack(spacing: 8) { | ||
actionButton(title: "\(post.likeCount)", label: post.isLiked ? "Unlike" : "Like", icon: post.isLiked ? "heart.fill" : "heart", tint: post.isLiked ? AppPalette.accent : .secondary, active: post.isLiked) { | ||
Task { await model.toggleLike(postID: post.id) } | ||
} | ||
| @@ -1193,13 +1198,28 @@ struct PostRow: View { | ||
} | ||
.sensoryFeedback(.success, trigger: post.isReposted) { _, reposted in reposted } | ||
actionButton(title: "Reply", label: "Reply", icon: "bubble") { openComposer(post.id, nil) } | ||
.labelStyle(.iconOnly) | ||
.accessibilityIdentifier(accessibilityIdentifier("replyButton")) | ||
actionButton(title: "Quote", label: "Quote", icon: "quote.bubble") { openComposer(nil, post.id) } | ||
.labelStyle(.iconOnly) | ||
.accessibilityIdentifier(accessibilityIdentifier("quoteButton")) | ||
Spacer(minLength: 0) | ||
if post.author.id != model.account?.id { | ||
Button { | ||
if let openModeration { openModeration(post) } else { showingModeration = true } | ||
} label: { | ||
Image(systemName: "ellipsis") | ||
.frame(width: 44, height: 44) | ||
.contentShape(Rectangle()) | ||
} | ||
.accessibilityLabel("Post controls") | ||
.accessibilityIdentifier(accessibilityIdentifier("postControls-\(post.id)")) | ||
} | ||
} | ||
.buttonStyle(.plain) | ||
.foregroundStyle(.secondary) | ||
} | ||
.sheet(isPresented: $showingModeration) { ModerationControls(author: post.author, post: post) } | ||
} | ||
| ||
} | ||
| @@ -1269,7 +1289,7 @@ private extension PostRow { | ||
.symbolEffect(.bounce, value: reduceMotion ? false : active) | ||
.animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: active) | ||
.foregroundStyle(tint) | ||
.frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) | ||
.frame(minWidth: 44, minHeight: 44, alignment: .leading) | ||
.contentShape(Rectangle()) | ||
} | ||
.accessibilityLabel(label) | ||
| @@ -2826,6 +2846,7 @@ final class ThreadScrollViewContainer<Content: View>: UIView { | ||
| ||
struct PostDetailView: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var moderationPost: Post? | ||
let postID: String | ||
let openPost: (String) -> Void | ||
let openProfile: (String) -> Void | ||
| @@ -2833,7 +2854,16 @@ struct PostDetailView: View { | ||
| ||
var body: some View { | ||
Group { | ||
if let post = model.post(id: postID) { | ||
if let post = model.post(id: postID), model.isHidden(post.author.id) { | ||
ContentUnavailableView { | ||
Label("Post hidden", systemImage: "eye.slash") | ||
} description: { | ||
Text("Unmute and unblock this account to see its posts.") | ||
} actions: { | ||
Button("View account controls") { openProfile(post.author.id) } | ||
} | ||
.accessibilityIdentifier("hiddenPost") | ||
} else if let post = model.post(id: postID) { | ||
ThreadScrollView(anchorID: postID) { | ||
VStack(alignment: .leading, spacing: 0) { | ||
ForEach(model.threadAncestors(for: post)) { ancestor in | ||
| @@ -2928,6 +2958,7 @@ struct PostDetailView: View { | ||
ContentUnavailableView("Post not found", systemImage: "text.bubble", description: Text("This post is not available.")) | ||
} | ||
} | ||
.sheet(item: $moderationPost) { post in ModerationControls(author: post.author, post: post) } | ||
.task(id: postID) { await model.loadPost(id: postID) } | ||
.navigationTitle("Post") | ||
.navigationBarTitleDisplayMode(.inline) | ||
| @@ -2950,7 +2981,8 @@ struct PostDetailView: View { | ||
openProfile: { openProfile(post.author.id) }, | ||
openActor: openProfile, | ||
openQuotedPost: openPost, | ||
openComposer: { replyTo, quotePostID in openComposer(replyTo ?? post.id, quotePostID) } | ||
openComposer: { replyTo, quotePostID in openComposer(replyTo ?? post.id, quotePostID) }, | ||
openModeration: { moderationPost = $0 } | ||
) | ||
} | ||
} | ||
Sources/Oldsky/ProfileView.swift+104−1
| @@ -1,7 +1,96 @@ | ||
import SwiftUI | ||
| ||
struct ModerationControls: View { | ||
@EnvironmentObject private var model: AppModel | ||
@Environment(\.dismiss) private var dismiss | ||
let author: Post.Author | ||
let post: Post? | ||
@State private var confirmation: String? | ||
@State private var showingConfirmation = false | ||
@State private var reportSubject: ReportSubject? | ||
@State private var reportReason = "com.atproto.moderation.defs#reasonSpam" | ||
@State private var reportSent = false | ||
@State private var stateLoaded = false | ||
| ||
var body: some View { | ||
NavigationStack { | ||
Form { | ||
if let error = model.moderationError { | ||
Section { | ||
Text(error).accessibilityIdentifier("moderationError") | ||
Button("Dismiss error") { model.clearModerationError() } | ||
} | ||
} | ||
Section("@\(author.handle)") { | ||
if model.moderationBusy.contains(author.id) { | ||
ProgressView("Loading account controls") | ||
} else if stateLoaded, let state = model.moderationStates[author.id] { | ||
if model.uncertainModerationIDs[author.id]?.contains(.mute) == true { | ||
Text("The mute action may have succeeded. Check it in Bluesky.") | ||
} else { | ||
Button(state.isMuted ? "Unmute account" : "Mute account") { confirmation = state.isMuted ? "Unmute" : "Mute"; showingConfirmation = true } | ||
} | ||
if model.uncertainModerationIDs[author.id]?.contains(.block) == true { | ||
Text("The block action may have succeeded. Check it in Bluesky.") | ||
} else { | ||
Button(state.isBlocked ? "Unblock account" : "Block account", role: state.isBlocked ? nil : .destructive) { confirmation = state.isBlocked ? "Unblock" : "Block"; showingConfirmation = true } | ||
} | ||
if model.uncertainModerationIDs[author.id]?.isEmpty == false, let url = URL(string: "https://bsky.app/profile/\(author.id)") { | ||
Link("Open account in Bluesky", destination: url) | ||
} | ||
} else { | ||
Button("Load account controls") { Task { stateLoaded = await model.loadModeration(actorID: author.id) } } | ||
} | ||
Button("Report account") { reportSubject = .account(author.id) } | ||
if let post { Button("Report post") { reportSubject = .post(uri: post.id, cid: post.cid) } } | ||
} | ||
if reportSubject != nil { | ||
Section("Report reason") { | ||
Picker("Reason", selection: $reportReason) { | ||
Text("Spam").tag("com.atproto.moderation.defs#reasonSpam") | ||
Text("Harassment").tag("com.atproto.moderation.defs#reasonRude") | ||
Text("Sexual content").tag("com.atproto.moderation.defs#reasonSexual") | ||
Text("Misleading content").tag("com.atproto.moderation.defs#reasonMisleading") | ||
Text("Other").tag("com.atproto.moderation.defs#reasonOther") | ||
} | ||
if let subject = reportSubject, model.uncertainReports.contains(subject.retryKey) { | ||
Text("The report result is unknown. Sending it again can create a duplicate report.") | ||
} else { | ||
Button("Send report") { confirmation = "Report"; showingConfirmation = true } | ||
} | ||
} | ||
} | ||
} | ||
.disabled(model.moderationBusy.contains("report")) | ||
.navigationTitle("Controls") | ||
.navigationBarTitleDisplayMode(.inline) | ||
.toolbar { Button("Done") { dismiss() } } | ||
.task { model.clearModerationError(); stateLoaded = await model.loadModeration(actorID: author.id) } | ||
.alert("Confirm action", isPresented: $showingConfirmation) { | ||
if let action = confirmation { | ||
Button(action, role: .destructive) { | ||
if action == "Report", let subject = reportSubject { | ||
Task { if await model.submitReport(subject, reason: reportReason) { reportSent = true; reportSubject = nil } } | ||
} else { | ||
Task { await model.setModeration(actorID: author.id, block: action == "Block" || action == "Unblock") } | ||
} | ||
} | ||
} | ||
Button("Cancel", role: .cancel) { confirmation = nil } | ||
} message: { | ||
Text(confirmation == "Report" ? (post != nil && reportSubject == .post(uri: post!.id, cid: post!.cid) ? "Send a report about this post to the moderation service?" : "Send a report about @\(author.handle) to the moderation service?") : "\(confirmation ?? "Change") @\(author.handle)?") | ||
} | ||
.alert("Report sent", isPresented: $reportSent) { | ||
Button("OK", role: .cancel) { reportSent = false } | ||
} message: { Text("The moderation service received your report.") } | ||
} | ||
} | ||
} | ||
| ||
struct ProfileView: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var showingModeration = false | ||
@State private var moderationPost: Post? | ||
let actorID: String | ||
let openPost: (String) -> Void | ||
let openProfile: (String) -> Void | ||
| @@ -39,6 +128,9 @@ struct ProfileView: View { | ||
profilePostsPlaceholder(label: "Loading profile posts", identifier: "profilePostsLoading", rows: 2) | ||
.listRowSeparator(.hidden) | ||
.listRowInsets(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16)) | ||
} else if model.isHidden(author?.id) { | ||
ContentUnavailableView("Posts hidden", systemImage: "eye.slash", description: Text("Unmute and unblock this account to see its posts.")) | ||
.listRowSeparator(.hidden) | ||
} else if authorPosts.isEmpty && model.profileCursors[actorID] == nil { | ||
ContentUnavailableView("No posts yet", systemImage: "text.bubble", description: Text("Posts from this profile will appear here.")) | ||
.accessibilityIdentifier("profilePostsEmpty") | ||
| @@ -69,7 +161,8 @@ struct ProfileView: View { | ||
openProfile: { openProfile(post.author.id) }, | ||
openActor: openProfile, | ||
openQuotedPost: openPost, | ||
openComposer: openComposer | ||
openComposer: openComposer, | ||
openModeration: { moderationPost = $0 } | ||
) | ||
} | ||
.padding(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16)) | ||
| @@ -110,6 +203,12 @@ struct ProfileView: View { | ||
.navigationTitle("Profile") | ||
.navigationBarTitleDisplayMode(.inline) | ||
.toolbar { | ||
if let author, author.id != model.account?.id { | ||
ToolbarItem(placement: .topBarTrailing) { | ||
Button { showingModeration = true } label: { Image(systemName: "ellipsis.circle") } | ||
.accessibilityLabel("Account controls") | ||
} | ||
} | ||
ToolbarItem(placement: .topBarTrailing) { | ||
ShareLink(item: URL(string: "https://bsky.app/profile/\(author?.handle ?? actorID)")!) { | ||
Image(systemName: "square.and.arrow.up") | ||
| @@ -117,6 +216,10 @@ struct ProfileView: View { | ||
.accessibilityLabel("Share profile") | ||
} | ||
} | ||
.sheet(isPresented: $showingModeration) { | ||
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) } | ||
} | ||
| ||
Tests/OldskyTests/AppModelTests.swift+228−0
| @@ -683,6 +683,182 @@ final class AppModelTests: XCTestCase { | ||
XCTAssertEqual(profilePost, sharedPost) | ||
} | ||
| ||
func testModerationUpdatesFeedOnlyAfterSuccess() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
await model.setModeration(actorID: "mae", block: false) | ||
XCTAssertEqual(service.actions, ["mute:true:mae"]) | ||
XCTAssertEqual(model.timelinePosts.map(\.id), ["post-2", "post-3"]) | ||
await model.setModeration(actorID: "mae", block: false) | ||
XCTAssertEqual(model.timelinePosts.map(\.id), ["post-1", "post-2", "post-3"]) | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertTrue(model.moderationStates["mae"]?.isBlocked == true) | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertFalse(model.moderationStates["mae"]?.isBlocked ?? true) | ||
XCTAssertEqual(service.actions.suffix(2), ["block:true:mae", "block:false:mae"]) | ||
} | ||
| ||
func testModerationRefreshAndNotificationFiltering() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.loadNotifications() | ||
_ = await model.loadModeration(actorID: "mae") | ||
await model.setModeration(actorID: "mae", block: false) | ||
XCTAssertFalse(model.visibleNotifications.contains { $0.author.id == "mae" || $0.parentPost?.author.id == "mae" }) | ||
service.state = ModerationState() | ||
_ = await model.loadModeration(actorID: "mae") | ||
XCTAssertFalse(model.isHidden("mae")) | ||
XCTAssertEqual(model.visibleNotifications.count, 3) | ||
} | ||
| ||
func testModerationResultFromSignedOutSessionIsIgnored() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
service.suspendLoad = true | ||
let pending = Task { await model.loadModeration(actorID: "mae") } | ||
while service.pendingLoad == nil { await Task.yield() } | ||
await model.signOut() | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
service.pendingLoad?.resume(returning: ModerationState(isMuted: true)) | ||
_ = await pending.value | ||
XCTAssertNil(model.moderationStates["mae"]) | ||
XCTAssertFalse(model.isHidden("mae")) | ||
} | ||
| ||
func testDelayedSignOutPreventsNewModerationWork() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
service.suspendSignOut = true | ||
let signingOut = Task { await model.signOut() } | ||
while service.pendingSignOut == nil { await Task.yield() } | ||
let loaded = await model.loadModeration(actorID: "alex") | ||
await model.setModeration(actorID: "mae", block: true) | ||
let reported = await model.submitReport(.account("mae"), reason: "reason") | ||
XCTAssertFalse(loaded) | ||
XCTAssertFalse(reported) | ||
XCTAssertTrue(service.actions.isEmpty) | ||
XCTAssertNil(service.reported) | ||
service.pendingSignOut?.resume() | ||
await signingOut.value | ||
XCTAssertNil(model.account) | ||
XCTAssertTrue(model.moderationStates.isEmpty) | ||
XCTAssertTrue(model.moderationBusy.isEmpty) | ||
XCTAssertNil(model.moderationError) | ||
} | ||
| ||
func testFailedSignOutKeepsDelayedBlockSuccess() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
service.suspendBlock = true | ||
let write = Task { await model.setModeration(actorID: "mae", block: true) } | ||
while service.pendingBlock == nil { await Task.yield() } | ||
service.failSignOut = true | ||
await model.signOut() | ||
XCTAssertNotNil(model.account) | ||
XCTAssertTrue(model.moderationBusy.contains("mae")) | ||
service.pendingBlock?.resume(returning: "block-uri") | ||
await write.value | ||
XCTAssertEqual(model.moderationStates["mae"]?.blockURI, "block-uri") | ||
XCTAssertFalse(model.moderationBusy.contains("mae")) | ||
XCTAssertNil(model.uncertainModerationIDs["mae"]) | ||
} | ||
| ||
func testFailedSignOutKeepsDelayedUnknownBlockLocked() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
service.suspendBlock = true | ||
let write = Task { await model.setModeration(actorID: "mae", block: true) } | ||
while service.pendingBlock == nil { await Task.yield() } | ||
service.failSignOut = true | ||
await model.signOut() | ||
service.pendingBlock?.resume(throwing: ServiceError.invalidResponse) | ||
await write.value | ||
XCTAssertNotNil(model.account) | ||
XCTAssertEqual(model.uncertainModerationIDs["mae"], [.block]) | ||
service.suspendBlock = false | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertTrue(service.actions.isEmpty) | ||
} | ||
| ||
func testUncertainBlockCannotBeRepeatedOrClearedByStaleRead() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
service.fail = true | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertEqual(model.uncertainModerationIDs["mae"], [.block]) | ||
service.fail = false | ||
let loaded = await model.loadModeration(actorID: "mae") | ||
XCTAssertTrue(loaded) | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertTrue(service.actions.isEmpty) | ||
await model.setModeration(actorID: "mae", block: false) | ||
XCTAssertEqual(service.actions, ["mute:true:mae"]) | ||
XCTAssertEqual(model.uncertainModerationIDs["mae"], [.block]) | ||
} | ||
| ||
func testRejectedActionCanBeRetried() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
service.reject = true | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertNil(model.uncertainModerationIDs["mae"]) | ||
XCTAssertNotNil(model.moderationError) | ||
service.reject = false | ||
await model.setModeration(actorID: "mae", block: true) | ||
XCTAssertEqual(service.actions, ["block:true:mae"]) | ||
} | ||
| ||
func testRejectedReportShowsNotSent() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
service.reject = true | ||
let sent = await model.submitReport(.account("mae"), reason: "reason") | ||
XCTAssertFalse(sent) | ||
XCTAssertEqual(model.moderationError, "The report was not sent. Rejected") | ||
} | ||
| ||
func testModerationFailuresKeepStateAndReportFailure() async { | ||
let service = ModerationTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
_ = await model.loadModeration(actorID: "mae") | ||
service.fail = true | ||
await model.setModeration(actorID: "mae", block: false) | ||
XCTAssertFalse(model.moderationStates["mae"]?.isMuted ?? true) | ||
XCTAssertEqual(model.uncertainModerationIDs["mae"], [.mute]) | ||
XCTAssertEqual(model.timelinePosts.count, 3) | ||
XCTAssertNotNil(model.moderationError) | ||
let sent = await model.submitReport(.post(uri: "post-1", cid: "cid"), reason: "reason") | ||
XCTAssertFalse(sent) | ||
XCTAssertEqual(model.moderationError, "The report result is unknown. Sending it again can create a duplicate report.") | ||
XCTAssertTrue(model.uncertainReports.contains(.post("post-1"))) | ||
service.fail = false | ||
let duplicate = await model.submitReport(.post(uri: "post-1", cid: "new-cid"), reason: "reason") | ||
XCTAssertFalse(duplicate) | ||
XCTAssertNil(service.reported) | ||
let otherPost = await model.submitReport(.post(uri: "post-2", cid: "other-cid"), reason: "reason") | ||
XCTAssertTrue(otherPost) | ||
XCTAssertEqual(service.reported, .post(uri: "post-2", cid: "other-cid")) | ||
let success = await model.submitReport(.account("mae"), reason: "reason") | ||
XCTAssertTrue(success) | ||
XCTAssertEqual(service.reported, .account("mae")) | ||
} | ||
| ||
func testImageAttachmentKeepsAltTextAndMimeType() throws { | ||
let image = UIGraphicsImageRenderer(size: CGSize(width: 4, height: 4)).image { context in | ||
UIColor.systemRed.setFill() | ||
| @@ -698,6 +874,58 @@ final class AppModelTests: XCTestCase { | ||
} | ||
} | ||
| ||
private final class ModerationTestService: BlueskyService { | ||
private let base = MockBlueskyService() | ||
var fail = false | ||
var reject = false | ||
var actions: [String] = [] | ||
var reported: ReportSubject? | ||
var state = ModerationState() | ||
var suspendLoad = false | ||
var pendingLoad: CheckedContinuation<ModerationState, Never>? | ||
var suspendSignOut = false | ||
var pendingSignOut: CheckedContinuation<Void, Never>? | ||
var failSignOut = false | ||
var suspendBlock = false | ||
var pendingBlock: CheckedContinuation<String?, Error>? | ||
func restoreAccount() async throws -> Account? { nil } | ||
func signIn(handle: String, appPassword: String, authFactorToken: String?) async throws -> Account { try await base.signIn(handle: handle, appPassword: appPassword, authFactorToken: authFactorToken) } | ||
func signOut() async throws { | ||
if suspendSignOut { await withCheckedContinuation { pendingSignOut = $0 } } | ||
if failSignOut { throw ServiceError.invalidResponse } | ||
} | ||
func loadFollowingFeed(cursor: String?) async throws -> FeedPage { try await base.loadFollowingFeed(cursor: cursor) } | ||
func loadNotifications(cursor: String?) async throws -> NotificationPage { try await base.loadNotifications(cursor: cursor) } | ||
func markNotificationsRead(seenAt: Date) async throws {} | ||
func loadPost(uri: String) async throws -> [Post] { try await base.loadPost(uri: uri) } | ||
func loadProfile(actorID: String) async throws -> Profile? { try await base.loadProfile(actorID: actorID) } | ||
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage { try await base.loadAuthorPosts(actorID: actorID, cursor: cursor) } | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { nil } | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { nil } | ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { try await base.publish(text: text, replyTo: replyTo, quotePost: quotePost, images: images) } | ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? { nil } | ||
func moderationState(actorID: String) async throws -> ModerationState { | ||
if suspendLoad { return await withCheckedContinuation { pendingLoad = $0 } } | ||
return state | ||
} | ||
func setMuted(_ muted: Bool, actorID: String) async throws { | ||
if fail { throw ServiceError.invalidResponse } | ||
actions.append("mute:\(muted):\(actorID)") | ||
} | ||
func setBlocked(_ blocked: Bool, actorID: String, blockURI: String?) async throws -> String? { | ||
if suspendBlock { return try await withCheckedThrowingContinuation { pendingBlock = $0 } } | ||
if reject { throw ModerationWriteError.rejected("Rejected") } | ||
if fail { throw ServiceError.invalidResponse } | ||
actions.append("block:\(blocked):\(actorID)") | ||
return blocked ? "block-uri" : nil | ||
} | ||
func report(_ subject: ReportSubject, reason: String) async throws { | ||
if reject { throw ModerationWriteError.rejected("Rejected") } | ||
if fail { throw ServiceError.invalidResponse } | ||
reported = subject | ||
} | ||
} | ||
| ||
private struct ProfilePostTestService: BlueskyService { | ||
let base = MockBlueskyService() | ||
var additionalProfilePost: Post? = nil | ||
Tests/OldskyTests/ATProtoServiceTests.swift+83−0
| @@ -3,6 +3,89 @@ import XCTest | ||
@testable import Oldsky | ||
| ||
final class ATProtoServiceTests: XCTestCase { | ||
func testModerationRequestsAndFailure() async throws { | ||
let suite = "ModerationTests.\(UUID().uuidString)" | ||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [StubURLProtocol.self] | ||
let session = URLSession(configuration: configuration) | ||
StubURLProtocol.clearRequests() | ||
let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) | ||
let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "") | ||
let token = "header.\(payload).signature" | ||
var muteStatus = 200 | ||
StubURLProtocol.handler = { request in | ||
switch request.url?.path { | ||
case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:moderator\"}".utf8)) | ||
case "/did:plc:moderator": return (200, Data("{\"id\":\"did:plc:moderator\",\"service\":[{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":\"https://moderation-pds.example.test\"}]}".utf8)) | ||
case "/xrpc/com.atproto.server.createSession": return (200, Data("{\"handle\":\"moderator.example\",\"did\":\"did:plc:moderator\",\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}".utf8)) | ||
case "/xrpc/app.bsky.actor.getProfile": return (200, Data("{\"did\":\"did:plc:moderator\",\"handle\":\"moderator.example\",\"viewer\":{\"muted\":true,\"blocking\":\"at://did:plc:moderator/app.bsky.graph.block/key\"}}".utf8)) | ||
case "/xrpc/app.bsky.graph.muteActor", "/xrpc/app.bsky.graph.unmuteActor": | ||
XCTAssertEqual(request.value(forHTTPHeaderField: "atproto-proxy"), "did:web:api.bsky.app#bsky_appview") | ||
let body = try! JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as! [String: String] | ||
XCTAssertEqual(body["actor"], "did:plc:target") | ||
return (muteStatus, muteStatus == 200 ? Data() : Data("{\"error\":\"InvalidRequest\",\"message\":\"Rejected\"}".utf8)) | ||
case "/xrpc/com.atproto.repo.createRecord": | ||
let body = try! JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as! [String: Any] | ||
XCTAssertEqual(body["repo"] as? String, "did:plc:moderator") | ||
XCTAssertEqual(body["collection"] as? String, "app.bsky.graph.block") | ||
XCTAssertEqual((body["record"] as? [String: Any])?["subject"] as? String, "did:plc:target") | ||
return (200, Data("{\"uri\":\"at://did:plc:moderator/app.bsky.graph.block/key\",\"cid\":\"cid\"}".utf8)) | ||
case "/xrpc/com.atproto.repo.deleteRecord": | ||
let body = try! JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as! [String: String] | ||
XCTAssertEqual(body["repo"], "did:plc:moderator") | ||
XCTAssertEqual(body["collection"], "app.bsky.graph.block") | ||
XCTAssertEqual(body["rkey"], "key") | ||
return (200, Data("{}".utf8)) | ||
case "/xrpc/com.atproto.moderation.createReport": | ||
XCTAssertEqual(request.value(forHTTPHeaderField: "atproto-proxy"), "did:plc:ar7c4by46qjdydhdevvrndac#atproto_labeler") | ||
let body = try! JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as! [String: Any] | ||
let subject = body["subject"] as! [String: String] | ||
XCTAssertEqual(body["reasonType"] as? String, "com.atproto.moderation.defs#reasonSpam") | ||
if subject["did"] != nil { | ||
XCTAssertEqual(subject["$type"], "com.atproto.admin.defs#repoRef") | ||
XCTAssertEqual(subject["did"], "did:plc:target") | ||
return (200, Data("{}".utf8)) | ||
} | ||
XCTAssertEqual(subject["$type"], "com.atproto.repo.strongRef") | ||
XCTAssertEqual(subject["uri"], "at://did:plc:target/app.bsky.feed.post/key") | ||
XCTAssertEqual(subject["cid"], "cid") | ||
return (400, Data("{\"error\":\"InvalidRequest\",\"message\":\"Report rejected\"}".utf8)) | ||
default: | ||
XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")") | ||
return (404, Data("{\"error\":\"NotFound\"}".utf8)) | ||
} | ||
} | ||
defer { StubURLProtocol.handler = nil; session.invalidateAndCancel(); defaults.removePersistentDomain(forName: suite) } | ||
let service = ATProtoBlueskyService(defaults: defaults, session: session) | ||
_ = try await service.signIn(handle: "moderator.example", appPassword: "test-password", authFactorToken: nil) | ||
let state = try await service.moderationState(actorID: "did:plc:target") | ||
XCTAssertTrue(state.isMuted) | ||
XCTAssertTrue(state.isBlocked) | ||
try await service.setMuted(true, actorID: "did:plc:target") | ||
try await service.setMuted(false, actorID: "did:plc:target") | ||
for status in [499, 408, 429, 400] { | ||
muteStatus = status | ||
do { | ||
try await service.setMuted(true, actorID: "did:plc:target") | ||
XCTFail("Expected status \(status) to fail") | ||
} catch ModerationWriteError.rejected { | ||
XCTAssertEqual(status, 400) | ||
} catch { | ||
XCTAssertNotEqual(status, 400) | ||
} | ||
} | ||
let blockURI = try await service.setBlocked(true, actorID: "did:plc:target", blockURI: nil) | ||
XCTAssertEqual(blockURI, "at://did:plc:moderator/app.bsky.graph.block/key") | ||
_ = try await service.setBlocked(false, actorID: "did:plc:target", blockURI: blockURI) | ||
try await service.report(.account("did:plc:target"), reason: "com.atproto.moderation.defs#reasonSpam") | ||
do { | ||
try await service.report(.post(uri: "at://did:plc:target/app.bsky.feed.post/key", cid: "cid"), reason: "com.atproto.moderation.defs#reasonSpam") | ||
XCTFail("Expected the report to fail") | ||
} catch ModerationWriteError.rejected(let message) { XCTAssertEqual(message, "Report rejected") } | ||
try await service.signOut() | ||
} | ||
| ||
func testEmptyDisplayNamesFallBackToHandle() { | ||
XCTAssertEqual(Post.Author(id: "id", name: "", handle: "person.example").name, "person.example") | ||
XCTAssertEqual(Post.Author(id: "id", name: " \n", handle: "person.example").name, "person.example") | ||
Tests/OldskyUITests/OldskyUITests.swift+117−1
| @@ -1,6 +1,104 @@ | ||
import XCTest | ||
| ||
final class OldskyUITests: XCTestCase { | ||
func testFeedModerationSheetStaysOpenAfterMute() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let controls = app.buttons["postControls-post-1"] | ||
XCTAssertTrue(controls.waitForExistence(timeout: 5)) | ||
let screenshot = XCTAttachment(screenshot: app.screenshot()) | ||
screenshot.name = "Feed action buttons" | ||
screenshot.lifetime = .keepAlways | ||
add(screenshot) | ||
controls.tap() | ||
XCTAssertTrue(app.buttons["Mute account"].waitForExistence(timeout: 5)) | ||
app.buttons["Mute account"].tap() | ||
app.alerts["Confirm action"].buttons["Mute"].tap() | ||
XCTAssertTrue(app.buttons["Unmute account"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(app.buttons["Report account"].exists) | ||
} | ||
| ||
func testProfileModerationSheetStaysOpenAfterBlock() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let profile = app.buttons["profileLink-mae"] | ||
XCTAssertTrue(profile.waitForExistence(timeout: 5)) | ||
profile.tap() | ||
let controls = app.buttons["postControls-post-1"] | ||
XCTAssertTrue(controls.waitForExistence(timeout: 5)) | ||
controls.tap() | ||
XCTAssertTrue(app.buttons["Block account"].waitForExistence(timeout: 5)) | ||
app.buttons["Block account"].tap() | ||
app.alerts["Confirm action"].buttons["Block"].tap() | ||
XCTAssertTrue(app.buttons["Unblock account"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(app.buttons["Report account"].exists) | ||
} | ||
| ||
func testModerationConfirmationAndSelectedPostVisibility() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let post = app.buttons["postText-post-1"] | ||
XCTAssertTrue(post.waitForExistence(timeout: 5)) | ||
post.tap() | ||
app.buttons["postControls-post-1"].firstMatch.tap() | ||
let mute = app.buttons["Mute account"] | ||
XCTAssertTrue(mute.waitForExistence(timeout: 5)) | ||
mute.tap() | ||
app.buttons["Cancel"].tap() | ||
XCTAssertTrue(mute.exists) | ||
mute.tap() | ||
app.buttons["Mute"].tap() | ||
app.buttons["Done"].tap() | ||
XCTAssertTrue(app.descendants(matching: .any)["hiddenPost"].waitForExistence(timeout: 5)) | ||
XCTAssertFalse(app.buttons["postText-post-1"].exists) | ||
app.buttons["View account controls"].tap() | ||
XCTAssertTrue(app.navigationBars["Profile"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(app.buttons["Account controls"].exists) | ||
} | ||
| ||
func testReportAvailableWhileAccountStateLoads() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-moderation-delay"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let post = app.buttons["postText-post-1"] | ||
XCTAssertTrue(post.waitForExistence(timeout: 5)) | ||
post.tap() | ||
app.buttons["postControls-post-1"].firstMatch.tap() | ||
let report = app.buttons["Report account"] | ||
XCTAssertTrue(report.waitForExistence(timeout: 2)) | ||
XCTAssertTrue(report.isEnabled) | ||
report.tap() | ||
XCTAssertTrue(app.buttons["Send report"].exists) | ||
} | ||
| ||
func testModerationFailureKeepsPostVisible() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-moderation-failure"] | ||
app.launch() | ||
app.buttons["demoSignInButton"].tap() | ||
let post = app.buttons["postText-post-1"] | ||
XCTAssertTrue(post.waitForExistence(timeout: 5)) | ||
post.tap() | ||
app.buttons["postControls-post-1"].firstMatch.tap() | ||
let mute = app.buttons["Mute account"] | ||
XCTAssertTrue(mute.waitForExistence(timeout: 5)) | ||
mute.tap() | ||
app.buttons["Mute"].tap() | ||
XCTAssertTrue(app.staticTexts["moderationError"].waitForExistence(timeout: 5)) | ||
app.buttons["Dismiss error"].tap() | ||
XCTAssertFalse(mute.exists) | ||
XCTAssertTrue(app.staticTexts["The mute action may have succeeded. Check it in Bluesky."].exists) | ||
app.buttons["Done"].tap() | ||
XCTAssertTrue(app.buttons["postText-post-1"].exists) | ||
} | ||
| ||
func testDemoSignInAndCreatePost() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing"] | ||
| @@ -664,7 +762,25 @@ final class OldskyUITests: XCTestCase { | ||
XCTAssertTrue(post.isHittable) | ||
app.buttons["Like"].firstMatch.tap() | ||
XCTAssertTrue(app.buttons["Unlike"].firstMatch.waitForExistence(timeout: 5)) | ||
app.buttons["replyButton"].firstMatch.tap() | ||
let reply = app.buttons["replyButton"].firstMatch | ||
let quote = app.buttons["quoteButton"].firstMatch | ||
XCTAssertEqual(reply.label, "Reply") | ||
XCTAssertEqual(quote.label, "Quote") | ||
XCTAssertTrue(reply.isHittable) | ||
XCTAssertTrue(quote.isHittable) | ||
XCTAssertGreaterThanOrEqual(reply.frame.height, 44) | ||
XCTAssertGreaterThanOrEqual(quote.frame.height, 44) | ||
XCTAssertGreaterThanOrEqual(reply.frame.width, 43.9) | ||
XCTAssertGreaterThanOrEqual(quote.frame.width, 43.9) | ||
XCTAssertLessThanOrEqual(quote.frame.minX - reply.frame.maxX, 9) | ||
let controls = app.buttons["postControls-post-1"].firstMatch | ||
XCTAssertGreaterThanOrEqual(controls.frame.width, 44) | ||
XCTAssertGreaterThanOrEqual(controls.frame.height, 44) | ||
XCTAssertGreaterThan(controls.frame.minX, quote.frame.maxX) | ||
reply.tap() | ||
XCTAssertTrue(app.textViews["composeTextField"].waitForExistence(timeout: 5)) | ||
app.buttons["Cancel"].tap() | ||
quote.tap() | ||
XCTAssertTrue(app.textViews["composeTextField"].waitForExistence(timeout: 5)) | ||
app.buttons["Cancel"].tap() | ||
XCTAssertTrue(post.waitForExistence(timeout: 5)) | ||
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. | ||
| ||
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 | ||
| ||
- A Mac with Xcode and the iOS simulator runtime installed. | ||