feat: combine profile, post deletion, and image description changes
Sources/Oldsky/AppModel.swift+166−12
| @@ -11,6 +11,63 @@ struct ComposerDraft { | ||
var attachments: [ImageAttachment] | ||
} | ||
| ||
@MainActor | ||
final class AvatarStore { | ||
private let cache = NSCache<NSURL, UIImage>() | ||
private let session: URLSession | ||
private var requests: [URL: (UUID, Task<UIImage?, Never>)] = [:] | ||
private var generation = UUID() | ||
| ||
init(session: URLSession = { | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.urlCache = nil | ||
return URLSession(configuration: configuration) | ||
}()) { | ||
self.session = session | ||
cache.totalCostLimit = 16 * 1024 * 1024 | ||
cache.countLimit = 200 | ||
} | ||
| ||
func image(for url: URL) async -> UIImage? { | ||
if let image = cache.object(forKey: url as NSURL) { return image } | ||
let currentGeneration = generation | ||
if let request = requests[url] { | ||
let image = await request.1.value | ||
return generation == currentGeneration ? image : nil | ||
} | ||
let id = UUID() | ||
let session = session | ||
let task = Task.detached { () -> UIImage? in | ||
do { | ||
let (data, response) = try await session.data(from: url) | ||
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode), | ||
data.count <= 5 * 1024 * 1024 else { return nil } | ||
return UIImage(data: data) | ||
} catch { | ||
return nil | ||
} | ||
} | ||
requests[url] = (id, task) | ||
let image = await task.value | ||
if requests[url]?.0 == id { | ||
requests[url] = nil | ||
if let image { | ||
let cost = (image.cgImage.map { $0.bytesPerRow * $0.height }) ?? 0 | ||
cache.setObject(image, forKey: url as NSURL, cost: cost) | ||
} | ||
} | ||
return generation == currentGeneration ? image : nil | ||
} | ||
| ||
func clear() { | ||
generation = UUID() | ||
for request in requests.values { request.1.cancel() } | ||
requests.removeAll() | ||
cache.removeAllObjects() | ||
session.configuration.urlCache?.removeAllCachedResponses() | ||
} | ||
} | ||
| ||
@MainActor | ||
final class AppModel: ObservableObject { | ||
@Published private(set) var account: Account? | ||
| @@ -29,6 +86,7 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var publishResultUnknown = false | ||
private var composerDrafts: [ComposerDraftKey: ComposerDraft] = [:] | ||
@Published private(set) var activePostActions: Set<String> = [] | ||
@Published private(set) var deletedPostIDs: Set<String> = [] | ||
@Published private(set) var activeFollowIDs: Set<String> = [] | ||
@Published private(set) var uncertainPostIDs: Set<String> = [] | ||
@Published private(set) var uncertainFollowIDs: Set<String> = [] | ||
| @@ -49,6 +107,7 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var authorPosts: [String: [Post]] = [:] | ||
@Published private(set) var profileCursors: [String: String] = [:] | ||
@Published private(set) var profileErrors: [String: String] = [:] | ||
@Published private(set) var failedProfileRefreshIDs: Set<String> = [] | ||
@Published private(set) var profileRepostedBy: [String: [String: Post.Author]] = [:] | ||
@Published private(set) var loadingMoreProfileIDs: Set<String> = [] | ||
@Published private(set) var hasMorePosts = false | ||
| @@ -63,6 +122,10 @@ final class AppModel: ObservableObject { | ||
private var contentPreferencesRequest = UUID() | ||
@Published private(set) var contentRevision = UUID() | ||
private let service: any BlueskyService | ||
let avatars = AvatarStore() | ||
private var profileLoadedAt: [String: Date] = [:] | ||
private let profileLifetime: TimeInterval = 300 | ||
private let profileLimit = 100 | ||
private var sessionGeneration = UUID() | ||
private var cursor: String? | ||
private var notificationsCursor: String? | ||
| @@ -80,6 +143,36 @@ final class AppModel: ObservableObject { | ||
private var notificationsRequest: UUID? | ||
private var moreNotificationsRequest: UUID? | ||
| ||
private func excludingDeletedQuote(_ post: Post) -> Post { | ||
guard let quote = post.quote, deletedPostIDs.contains(quote.postID) else { return post } | ||
var post = post | ||
post.quote = Post.Quote(postID: quote.postID) | ||
return post | ||
} | ||
| ||
private func excludingDeletedPosts(_ page: FeedPage) -> FeedPage { | ||
FeedPage( | ||
posts: page.posts.filter { !deletedPostIDs.contains($0.id) }.map(excludingDeletedQuote), | ||
cursor: page.cursor, | ||
replyContexts: page.replyContexts.filter { !deletedPostIDs.contains($0.key) }.mapValues { context in | ||
context.filter { !deletedPostIDs.contains($0.id) }.map(excludingDeletedQuote) | ||
}, | ||
repostedBy: page.repostedBy.filter { !deletedPostIDs.contains($0.key) }, | ||
mutedPostIDs: page.mutedPostIDs | ||
) | ||
} | ||
| ||
private func excludingDeletedPosts(_ notifications: [FeedNotification]) -> [FeedNotification] { | ||
notifications.map { notification in | ||
var notification = notification | ||
if let id = notification.relatedPost?.id, deletedPostIDs.contains(id) { notification.relatedPost = nil } | ||
if let id = notification.parentPost?.id, deletedPostIDs.contains(id) { notification.parentPost = nil } | ||
notification.relatedPost = notification.relatedPost.map(excludingDeletedQuote) | ||
notification.parentPost = notification.parentPost.map(excludingDeletedQuote) | ||
return notification | ||
} | ||
} | ||
| ||
private func applyMutedPostIDs(_ ids: Set<String>) { | ||
guard !ids.isEmpty else { return } | ||
contentGeneration = UUID() | ||
| @@ -215,6 +308,7 @@ final class AppModel: ObservableObject { | ||
contentPreferencesError = nil | ||
composerDrafts = [:] | ||
activePostActions = [] | ||
deletedPostIDs = [] | ||
activeFollowIDs = [] | ||
uncertainPostIDs = [] | ||
uncertainFollowIDs = [] | ||
| @@ -281,7 +375,7 @@ final class AppModel: ObservableObject { | ||
if feedRequest == request { feedRequest = nil; isLoading = false } | ||
} | ||
do { | ||
let page = try await service.loadFollowingFeed(cursor: nil) | ||
let page = excludingDeletedPosts(try await service.loadFollowingFeed(cursor: nil)) | ||
guard generation == contentGeneration else { | ||
if feedRequest == request { errorMessage = "Could not load the feed. Try again." } | ||
return | ||
| @@ -315,7 +409,7 @@ final class AppModel: ObservableObject { | ||
if moreFeedRequest == request { moreFeedRequest = nil; isLoadingMore = false } | ||
} | ||
do { | ||
let page = try await service.loadFollowingFeed(cursor: cursor) | ||
let page = excludingDeletedPosts(try await service.loadFollowingFeed(cursor: cursor)) | ||
guard generation == contentGeneration else { return } | ||
applyMutedPostIDs(page.mutedPostIDs) | ||
for post in page.posts { updatePost(post) } | ||
| @@ -335,7 +429,7 @@ final class AppModel: ObservableObject { | ||
} | ||
| ||
func loadPost(id: String) async { | ||
guard loadingPostIDs.insert(id).inserted else { return } | ||
guard !deletedPostIDs.contains(id), loadingPostIDs.insert(id).inserted else { return } | ||
let request = UUID() | ||
postRequests[id] = request | ||
let generation = contentGeneration | ||
| @@ -354,7 +448,7 @@ final class AppModel: ObservableObject { | ||
if postRequests[id] == request { failedPostIDs.insert(id) } | ||
return | ||
} | ||
let loadedPosts = result.posts | ||
let loadedPosts = result.posts.filter { !deletedPostIDs.contains($0.id) }.map(excludingDeletedQuote) | ||
applyMutedPostIDs(result.mutedPostIDs) | ||
for loadedPost in loadedPosts { | ||
updatePost(loadedPost) | ||
| @@ -379,6 +473,30 @@ final class AppModel: ObservableObject { | ||
} | ||
} | ||
| ||
func canDelete(_ post: Post) -> Bool { | ||
account?.id == post.author.id && account != nil && !isSigningOut | ||
} | ||
| ||
func deletePost(id: String) async { | ||
guard let original = post(id: id), canDelete(original), activePostActions.insert(id).inserted else { return } | ||
let generation = sessionGeneration | ||
defer { if generation == sessionGeneration { activePostActions.remove(id) } } | ||
do { | ||
try await service.deletePost(original) | ||
guard generation == sessionGeneration else { return } | ||
contentGeneration = UUID() | ||
deletedPostIDs.insert(id) | ||
removePost(id: id) | ||
} catch { | ||
guard generation == sessionGeneration else { return } | ||
if error is ActionNotSentError || (error as? ServiceError).map({ if case .noSession = $0 { return true }; return false }) == true { | ||
errorMessage = "Could not delete the post. Try again." | ||
} else { | ||
errorMessage = "Could not confirm that the post was deleted. Refresh the feed and try again if it is still there." | ||
} | ||
} | ||
} | ||
| ||
func toggleLike(postID: String) async { | ||
guard account != nil, !isSigningOut, !uncertainPostIDs.contains(postID), let original = post(id: postID), activePostActions.insert(postID).inserted else { return } | ||
let generation = sessionGeneration | ||
| @@ -498,10 +616,13 @@ final class AppModel: ObservableObject { | ||
repostedBy = [:] | ||
threadContexts = [:] | ||
profiles = [:] | ||
profileLoadedAt = [:] | ||
avatars.clear() | ||
authorPosts = [:] | ||
profileCursors = [:] | ||
profileRepostedBy = [:] | ||
profileErrors = [:] | ||
failedProfileRefreshIDs = [] | ||
notifications = [] | ||
notificationPageStarts = [] | ||
notificationsCursor = nil | ||
| @@ -724,7 +845,7 @@ final class AppModel: ObservableObject { | ||
if notificationsRequest == request { notificationsErrorMessage = "Could not load notifications. Try again." } | ||
return false | ||
} | ||
notifications = page.notifications | ||
notifications = excludingDeletedPosts(page.notifications) | ||
notificationPageStarts = Set(page.notifications.prefix(1).map(\.id)) | ||
notificationsCursor = page.cursor | ||
hasMoreNotifications = page.cursor != nil | ||
| @@ -760,7 +881,7 @@ final class AppModel: ObservableObject { | ||
return | ||
} | ||
var seen = Set(notifications.map(\.id)) | ||
let newNotifications = page.notifications.filter { seen.insert($0.id).inserted } | ||
let newNotifications = excludingDeletedPosts(page.notifications).filter { seen.insert($0.id).inserted } | ||
if let first = newNotifications.first { notificationPageStarts.insert(first.id) } | ||
notifications.append(contentsOf: newNotifications) | ||
self.notificationsCursor = page.cursor | ||
| @@ -797,6 +918,9 @@ final class AppModel: ObservableObject { | ||
for key in threadContexts.keys.sorted() { | ||
if let post = threadContexts[key]?.first(where: { $0.id == id }) { return post } | ||
} | ||
for key in authorPosts.keys.sorted() { | ||
if let post = authorPosts[key]?.first(where: { $0.id == id }) { return post } | ||
} | ||
for notification in notifications { | ||
if let post = notification.relatedPost, post.id == id { return post } | ||
if let post = notification.parentPost, post.id == id { return post } | ||
| @@ -824,6 +948,11 @@ final class AppModel: ObservableObject { | ||
if notifications[index].relatedPost?.id == id { notifications[index].relatedPost = nil } | ||
if notifications[index].parentPost?.id == id { notifications[index].parentPost = nil } | ||
} | ||
posts = posts.map(excludingDeletedQuote) | ||
replyContexts = replyContexts.mapValues { $0.map(excludingDeletedQuote) } | ||
threadContexts = threadContexts.mapValues { $0.map(excludingDeletedQuote) } | ||
authorPosts = authorPosts.mapValues { $0.map(excludingDeletedQuote) } | ||
notifications = excludingDeletedPosts(notifications) | ||
} | ||
| ||
private func updatePost(_ post: Post) { | ||
| @@ -917,10 +1046,15 @@ final class AppModel: ObservableObject { | ||
return thread.dropFirst(selectedIndex + 1).compactMap { post(id: $0.id) }.filter { isVisibleInContentList($0) } | ||
} | ||
| ||
func loadProfile(actorID: String) async { | ||
func loadProfile(actorID: String, forceRefresh: Bool = false) async { | ||
guard loadingProfileIDs.insert(actorID).inserted else { return } | ||
let forceRefresh = forceRefresh || failedProfileRefreshIDs.contains(actorID) | ||
let request = UUID() | ||
profileRequests[actorID] = request | ||
if forceRefresh { | ||
moreProfileRequests[actorID] = nil | ||
loadingMoreProfileIDs.remove(actorID) | ||
} | ||
let generation = contentGeneration | ||
defer { | ||
if profileRequests[actorID] == request { | ||
| @@ -931,25 +1065,34 @@ final class AppModel: ObservableObject { | ||
func interrupted() { | ||
if profileRequests[actorID] == request { | ||
profileErrors[actorID] = "The profile could not be loaded. Try again." | ||
failedProfileRefreshIDs.insert(actorID) | ||
} | ||
} | ||
errorMessage = nil | ||
profileErrors[actorID] = nil | ||
do { | ||
if profiles[actorID] == nil { | ||
if forceRefresh || profiles[actorID] == nil || Date().timeIntervalSince(profileLoadedAt[actorID] ?? .distantPast) >= profileLifetime { | ||
guard let profile = try await service.loadProfile(actorID: actorID) else { | ||
guard generation == contentGeneration, profileRequests[actorID] == request else { interrupted(); return } | ||
profileErrors[actorID] = "This profile could not be found." | ||
failedProfileRefreshIDs.insert(actorID) | ||
errorMessage = profileErrors[actorID] | ||
return | ||
} | ||
guard generation == contentGeneration, profileRequests[actorID] == request else { interrupted(); return } | ||
var currentProfile = profile | ||
if let result = followResults[actorID] { currentProfile.isFollowing = result } | ||
profiles[actorID] = currentProfile | ||
profileLoadedAt[actorID] = Date() | ||
if profiles.count > profileLimit, let oldest = profileLoadedAt.min(by: { $0.value < $1.value })?.key { | ||
profiles[oldest] = nil | ||
profileLoadedAt[oldest] = nil | ||
} | ||
if currentProfile.isFollowing { followingActorIDs.insert(actorID) } | ||
else { followingActorIDs.remove(actorID) } | ||
} | ||
if authorPosts[actorID] == nil { | ||
let page = try await service.loadAuthorPosts(actorID: actorID, cursor: nil) | ||
if forceRefresh || authorPosts[actorID] == nil { | ||
let page = excludingDeletedPosts(try await service.loadAuthorPosts(actorID: actorID, cursor: nil)) | ||
guard generation == contentGeneration, profileRequests[actorID] == request else { interrupted(); return } | ||
applyMutedPostIDs(page.mutedPostIDs) | ||
for post in page.posts { updatePost(post) } | ||
| @@ -957,20 +1100,31 @@ final class AppModel: ObservableObject { | ||
profileCursors[actorID] = page.cursor | ||
authorPosts[actorID] = page.posts | ||
replyContexts.merge(page.replyContexts) { _, new in new } | ||
profileRepostedBy[actorID, default: [:]].merge(page.repostedBy) { _, new in new } | ||
profileRepostedBy[actorID] = page.repostedBy | ||
var knownPostIDs = Set(posts.map(\.id)) | ||
posts.append(contentsOf: page.posts.filter { knownPostIDs.insert($0.id).inserted }) | ||
} | ||
profileErrors[actorID] = nil | ||
failedProfileRefreshIDs.remove(actorID) | ||
} catch { | ||
guard generation == contentGeneration, profileRequests[actorID] == request else { interrupted(); return } | ||
profileErrors[actorID] = error.localizedDescription | ||
failedProfileRefreshIDs.insert(actorID) | ||
errorMessage = error.localizedDescription | ||
} | ||
} | ||
| ||
func retryProfilePosts(actorID: String) async { | ||
if failedProfileRefreshIDs.contains(actorID) { | ||
await loadProfile(actorID: actorID, forceRefresh: true) | ||
} else { | ||
await loadNextProfilePage(actorID: actorID) | ||
} | ||
} | ||
| ||
func loadNextProfilePage(actorID: String) async { | ||
guard let cursor = profileCursors[actorID], | ||
!failedProfileRefreshIDs.contains(actorID), | ||
!loadingProfileIDs.contains(actorID), | ||
!loadingMoreProfileIDs.contains(actorID) else { return } | ||
loadingMoreProfileIDs.insert(actorID) | ||
| @@ -985,7 +1139,7 @@ final class AppModel: ObservableObject { | ||
} | ||
} | ||
do { | ||
let page = try await service.loadAuthorPosts(actorID: actorID, cursor: cursor) | ||
let page = excludingDeletedPosts(try await service.loadAuthorPosts(actorID: actorID, cursor: cursor)) | ||
guard generation == contentGeneration, moreProfileRequests[actorID] == request else { return } | ||
applyMutedPostIDs(page.mutedPostIDs) | ||
for post in page.posts { updatePost(post) } | ||
Sources/Oldsky/BlueskyService.swift+23−0
| @@ -16,6 +16,7 @@ protocol BlueskyService { | ||
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 deletePost(_ post: Post) async throws | ||
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 | ||
| @@ -26,6 +27,7 @@ protocol BlueskyService { | ||
} | ||
| ||
extension BlueskyService { | ||
func deletePost(_ post: Post) async throws { throw ServiceError.invalidResponse } | ||
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 } | ||
| @@ -45,6 +47,7 @@ struct MockBlueskyService: BlueskyService { | ||
} | ||
| ||
var failsPublishing = false | ||
var failsDeleting = ProcessInfo.processInfo.arguments.contains("-ui-testing-delete-failure") | ||
var failsMarkingNotificationsRead = false | ||
var requiresAuthFactorToken = false | ||
var restoresAccount = false | ||
| @@ -266,6 +269,11 @@ struct MockBlueskyService: BlueskyService { | ||
return reposted ? "mock-repost-\(post.id)" : nil | ||
} | ||
| ||
func deletePost(_ post: Post) async throws { | ||
guard post.author.id == account.id else { throw ServiceError.invalidResponse } | ||
if failsDeleting { throw ServiceError.requestFailed("Could not delete the post.") } | ||
} | ||
| ||
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.") } | ||
return Post(id: UUID().uuidString, author: Post.Author(id: account.id, name: account.displayName, handle: account.handle), text: text, likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], quote: quotePost.map { Post.Quote(postID: $0.id) }, replyIDs: [], createdAt: Date()) | ||
| @@ -356,6 +364,10 @@ struct MockBlueskyService: BlueskyService { | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-share") { | ||
posts.insert(Post(id: "at://did:plc:sharetest/app.bsky.feed.post/abc123", author: authors[0], text: "A post to share.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []), at: 0) | ||
} | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-own-post") { | ||
let author = Post.Author(id: account.id, name: account.displayName, handle: account.handle) | ||
posts.insert(Post(id: "at://\(account.id)/app.bsky.feed.post/own123", author: author, text: "My post to share and delete.", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []), at: 0) | ||
} | ||
if ProcessInfo.processInfo.arguments.contains("-ui-testing-facets") { | ||
let rootText = "Root context: @alex.example shared https://oldsky.app/post?uri=post-2 and https://example.com/reply." | ||
posts[0].text = rootText | ||
| @@ -1029,6 +1041,17 @@ actor ATProtoBlueskyService: BlueskyService { | ||
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 deletePost(_ post: Post) async throws { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
let parts = post.id.split(separator: "/", omittingEmptySubsequences: false) | ||
guard post.author.id == current.did, parts.count == 5, parts[0] == "at:", parts[1].isEmpty, | ||
parts[2] == Substring(current.did), parts[3] == "app.bsky.feed.post", !parts[4].isEmpty, | ||
!parts[4].contains("?"), !parts[4].contains("#") else { | ||
throw ActionNotSentError(underlying: ServiceError.postReferenceUnavailable) | ||
} | ||
try await deleteRecord(uri: post.id, repository: current.did) | ||
} | ||
| ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
if liked { | ||
Sources/Oldsky/OldskyApp.swift+158−16
| @@ -3,6 +3,7 @@ import Combine | ||
import ImageIO | ||
import PhotosUI | ||
import SwiftUI | ||
import FoundationModels | ||
import UniformTypeIdentifiers | ||
import UIKit | ||
| ||
| @@ -1061,24 +1062,33 @@ struct FeedView: View { | ||
} | ||
| ||
struct AccountAvatar: View { | ||
@EnvironmentObject private var model: AppModel | ||
@State private var image: UIImage? | ||
@State private var imageURL: URL? | ||
let account: Account? | ||
let size: CGFloat | ||
var isDecorative = true | ||
| ||
var body: some View { | ||
Group { | ||
if let url = account?.avatarURL { | ||
AsyncImage(url: url) { image in | ||
image.resizable().scaledToFill() | ||
} placeholder: { | ||
avatarPlaceholder | ||
} | ||
if let image, imageURL == account?.avatarURL { | ||
Image(uiImage: image).resizable().scaledToFill() | ||
} else { | ||
avatarPlaceholder | ||
} | ||
} | ||
.frame(width: size, height: size) | ||
.clipShape(Circle()) | ||
.accessibilityHidden(true) | ||
.accessibilityHidden(isDecorative) | ||
.task(id: account?.avatarURL) { | ||
image = nil | ||
guard let url = account?.avatarURL else { return } | ||
let loaded = await model.avatars.image(for: url) | ||
if !Task.isCancelled { | ||
imageURL = url | ||
image = loaded | ||
} | ||
} | ||
} | ||
| ||
private var avatarPlaceholder: some View { | ||
| @@ -1279,13 +1289,14 @@ struct PostRow: View { | ||
} | ||
| ||
private var postContent: some View { | ||
VStack(alignment: .leading, spacing: 12) { | ||
let author = model.profile(actorID: post.author.id)?.author ?? post.author | ||
return 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: model.contentDecision(author: post.author)?.ui(.avatar).blur == false ? post.author.avatarURL : nil), size: 40) | ||
AccountAvatar(account: Account(handle: author.handle, displayName: author.name, id: author.id, avatarURL: model.contentDecision(author: post.author)?.ui(.avatar).blur == false && model.contentDecision(author: author)?.ui(.avatar).blur == false ? 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) | ||
Text(author.name).fontWeight(.semibold).foregroundStyle(.primary) | ||
Text("@\(author.handle)").font(.subheadline).foregroundStyle(.secondary) | ||
if let date = post.createdAt { | ||
PostTimestamp(date: date) | ||
.frame(maxWidth: .infinity, alignment: .trailing) | ||
| @@ -1370,7 +1381,7 @@ struct PostRow: View { | ||
.accessibilityIdentifier(accessibilityIdentifier("shareButton-\(post.id)")) | ||
} | ||
Spacer(minLength: 0) | ||
if post.author.id != model.account?.id { | ||
if model.canDelete(post) || post.author.id != model.account?.id { | ||
Button { | ||
if let openModeration { openModeration(post) } else { showingModeration = true } | ||
} label: { | ||
| @@ -3141,6 +3152,8 @@ struct PostDetailView: View { | ||
} | ||
.padding(.horizontal, 16) | ||
} | ||
} else if model.deletedPostIDs.contains(postID) { | ||
ContentUnavailableView("Post deleted", systemImage: "text.bubble", description: Text("This post is no longer available.")) | ||
} else if model.failedPostIDs.contains(postID) { | ||
ContentUnavailableView { | ||
Label("Could not load post", systemImage: "text.bubble") | ||
| @@ -3186,6 +3199,12 @@ struct PostDetailView: View { | ||
} | ||
} | ||
| ||
private struct AltTextReview: Identifiable { | ||
let id: UUID | ||
let originalText: String | ||
var draft: String | ||
} | ||
| ||
struct ComposeView: View { | ||
@EnvironmentObject private var model: AppModel | ||
@Environment(\.dismiss) private var dismiss | ||
| @@ -3196,6 +3215,11 @@ struct ComposeView: View { | ||
@State private var attachments: [ImageAttachment] = [] | ||
@State private var isLoadingImages = false | ||
@State private var confirmsMissingAltText = false | ||
@State private var generatingAltText = false | ||
@State private var altTextTask: Task<Void, Never>? | ||
@State private var altTextRequestID: UUID? | ||
@State private var altTextReview: AltTextReview? | ||
@State private var altTextError: String? | ||
@State private var confirmsDiscardUncertainDraft = false | ||
@AppStorage("remindMissingAltText") private var remindMissingAltText = true | ||
@FocusState private var textIsFocused: Bool | ||
| @@ -3259,8 +3283,13 @@ struct ComposeView: View { | ||
} | ||
.accessibilityLabel("Add photos") | ||
.accessibilityIdentifier("addPhotosButton") | ||
.disabled(attachments.count >= 4 || isLoadingImages || model.isPublishing) | ||
.disabled(attachments.count >= 4 || isLoadingImages || model.isPublishing || generatingAltText) | ||
if isLoadingImages { ProgressView().controlSize(.small) } | ||
if generatingAltText { | ||
ProgressView().controlSize(.small).accessibilityLabel("Generating alt text") | ||
Button("Stop generating") { cancelAltTextGeneration() } | ||
.accessibilityIdentifier("stopGeneratingAltTextButton") | ||
} | ||
Spacer() | ||
Text("\(text.count)/\(characterLimit)") | ||
.font(.footnote.monospacedDigit()) | ||
| @@ -3274,7 +3303,7 @@ struct ComposeView: View { | ||
.toolbar { | ||
ToolbarItem(placement: .topBarLeading) { | ||
Button("Cancel", role: .cancel) { dismiss() } | ||
.disabled(model.isPublishing) | ||
.disabled(model.isPublishing || generatingAltText) | ||
.accessibilityIdentifier("cancelComposeButton") | ||
} | ||
ToolbarItem(placement: .topBarTrailing) { | ||
| @@ -3294,10 +3323,47 @@ struct ComposeView: View { | ||
} | ||
} | ||
} | ||
.disabled(!canPublish || model.isPublishing || isLoadingImages || model.uncertainDraftKeys.contains(draftKey)) | ||
.disabled(!canPublish || model.isPublishing || isLoadingImages || generatingAltText || model.uncertainDraftKeys.contains(draftKey)) | ||
.accessibilityIdentifier("publishButton") | ||
} | ||
} | ||
.sheet(item: $altTextReview) { review in | ||
NavigationStack { | ||
VStack(alignment: .leading, spacing: 12) { | ||
Text("Review and edit this description before you use it.") | ||
TextEditor(text: Binding( | ||
get: { altTextReview?.draft ?? "" }, | ||
set: { altTextReview?.draft = $0 } | ||
)) | ||
.accessibilityLabel("Generated alt text") | ||
} | ||
.padding() | ||
.navigationTitle("Review alt text") | ||
.toolbar { | ||
ToolbarItem(placement: .cancellationAction) { | ||
Button("Cancel") { altTextReview = nil } | ||
} | ||
ToolbarItem(placement: .confirmationAction) { | ||
Button("Use text") { | ||
if let current = altTextReview, | ||
let index = attachments.firstIndex(where: { $0.id == current.id }), | ||
attachments[index].altText == current.originalText { | ||
altTextBinding(for: current.id).wrappedValue = current.draft | ||
} | ||
altTextReview = nil | ||
} | ||
} | ||
} | ||
} | ||
} | ||
.alert("Alt text unavailable", isPresented: Binding( | ||
get: { altTextError != nil }, | ||
set: { if !$0 { altTextError = nil } } | ||
)) { | ||
Button("OK", role: .cancel) { altTextError = nil } | ||
} message: { | ||
Text(altTextError ?? "") | ||
} | ||
.alert("Add alt text?", isPresented: $confirmsMissingAltText) { | ||
Button("Keep editing", role: .cancel) {} | ||
Button("Post without alt text") { Task { await publish() } } | ||
| @@ -3337,9 +3403,10 @@ struct ComposeView: View { | ||
textIsFocused = true | ||
} | ||
.onDisappear { | ||
cancelAltTextGeneration() | ||
model.saveComposerDraft(ComposerDraft(text: text, attachments: attachments), for: draftKey) | ||
} | ||
.interactiveDismissDisabled(model.isPublishing) | ||
.interactiveDismissDisabled(model.isPublishing || generatingAltText) | ||
} | ||
| ||
private var canPublish: Bool { | ||
| @@ -3370,10 +3437,17 @@ struct ComposeView: View { | ||
.padding(6) | ||
.accessibilityLabel("Remove image \(index + 1)") | ||
} | ||
Button("Generate alt text") { | ||
startAltTextGeneration(for: attachment) | ||
} | ||
.font(.footnote) | ||
.disabled(generatingAltText) | ||
.accessibilityIdentifier("generateAltText-\(index)") | ||
TextField("Add alt text", text: altTextBinding(for: attachment.id)) | ||
.accessibilityLabel("Alt text for image \(index + 1)") | ||
.font(.footnote) | ||
.textFieldStyle(.roundedBorder) | ||
.accessibilityIdentifier("altText-\(index)") | ||
.frame(width: 132) | ||
} | ||
} | ||
| @@ -3408,6 +3482,74 @@ struct ComposeView: View { | ||
) | ||
} | ||
| ||
@MainActor | ||
private func startAltTextGeneration(for attachment: ImageAttachment) { | ||
guard !generatingAltText else { return } | ||
let requestID = UUID() | ||
altTextRequestID = requestID | ||
generatingAltText = true | ||
altTextTask = Task { await generateAltText(for: attachment, requestID: requestID) } | ||
} | ||
| ||
@MainActor | ||
private func cancelAltTextGeneration() { | ||
altTextRequestID = nil | ||
altTextTask?.cancel() | ||
altTextTask = nil | ||
generatingAltText = false | ||
} | ||
| ||
@MainActor | ||
private func generateAltText(for attachment: ImageAttachment, requestID: UUID) async { | ||
defer { | ||
if altTextRequestID == requestID { | ||
altTextRequestID = nil | ||
altTextTask = nil | ||
generatingAltText = false | ||
} | ||
} | ||
let arguments = ProcessInfo.processInfo.arguments | ||
if arguments.contains("-ui-testing") && arguments.contains("-ui-testing-alt-delayed") { | ||
await Task.detached { try? await Task.sleep(for: .seconds(3)) }.value | ||
guard !Task.isCancelled, altTextRequestID == requestID else { return } | ||
altTextReview = AltTextReview(id: attachment.id, originalText: attachment.altText, draft: "A delayed description") | ||
return | ||
} | ||
if arguments.contains("-ui-testing") && arguments.contains("-ui-testing-alt-success") { | ||
altTextReview = AltTextReview(id: attachment.id, originalText: attachment.altText, draft: "A generated description") | ||
return | ||
} | ||
if arguments.contains("-ui-testing") && arguments.contains("-ui-testing-alt-failure") { | ||
altTextError = "The description could not be generated. Try again or add alt text yourself." | ||
return | ||
} | ||
guard !(arguments.contains("-ui-testing") && arguments.contains("-ui-testing-alt-unavailable")), SystemLanguageModel.default.isAvailable else { | ||
altTextError = "Apple Intelligence is not available. You can add alt text yourself." | ||
return | ||
} | ||
guard let image = UIImage(data: attachment.data) else { | ||
altTextError = "The image could not be read. You can add alt text yourself." | ||
return | ||
} | ||
do { | ||
let session = LanguageModelSession(model: SystemLanguageModel.default) | ||
let response = try await session.respond { | ||
"Write concise alt text describing the visible content of this image. Return only the description." | ||
Attachment(image) | ||
} | ||
guard !Task.isCancelled, altTextRequestID == requestID else { return } | ||
guard !response.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { | ||
altTextError = "No description was generated. You can add alt text yourself." | ||
return | ||
} | ||
guard attachments.contains(where: { $0.id == attachment.id && $0.altText == attachment.altText }) else { return } | ||
altTextReview = AltTextReview(id: attachment.id, originalText: attachment.altText, draft: response.content) | ||
} catch { | ||
guard !Task.isCancelled, altTextRequestID == requestID else { return } | ||
altTextError = "The description could not be generated. Try again or add alt text yourself." | ||
} | ||
} | ||
| ||
private func loadImages(_ items: [PhotosPickerItem]) async { | ||
isLoadingImages = true | ||
defer { isLoadingImages = false } | ||
Sources/Oldsky/ProfileView.swift+66−30
| @@ -11,6 +11,7 @@ struct ModerationControls: View { | ||
@State private var reportReason = "com.atproto.moderation.defs#reasonSpam" | ||
@State private var reportSent = false | ||
@State private var stateLoaded = false | ||
@State private var confirmsDeletion = false | ||
| ||
var body: some View { | ||
NavigationStack { | ||
| @@ -21,28 +22,47 @@ struct ModerationControls: View { | ||
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 let post, author.id == model.account?.id { | ||
Section("@\(author.handle)") { | ||
if let url = post.shareURL { | ||
ShareLink(item: url) { | ||
Label("Share post", systemImage: "square.and.arrow.up") | ||
} | ||
Button { | ||
UIPasteboard.general.url = url | ||
} label: { | ||
Label("Copy link", systemImage: "link") | ||
} | ||
} | ||
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.canDelete(post) { | ||
Button("Delete post", role: .destructive) { confirmsDeletion = true } | ||
.disabled(model.activePostActions.contains(post.id)) | ||
} | ||
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 { | ||
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) } } | ||
} | ||
} 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) } } | ||
} | ||
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") { | ||
| @@ -65,7 +85,23 @@ struct ModerationControls: View { | ||
.navigationTitle("Controls") | ||
.navigationBarTitleDisplayMode(.inline) | ||
.toolbar { Button("Done") { dismiss() } } | ||
.task { model.clearModerationError(); stateLoaded = await model.loadModeration(actorID: author.id) } | ||
.task { | ||
if author.id != model.account?.id { | ||
model.clearModerationError() | ||
stateLoaded = await model.loadModeration(actorID: author.id) | ||
} | ||
} | ||
.alert("Delete this post?", isPresented: $confirmsDeletion) { | ||
Button("Delete post", role: .destructive) { | ||
if let post { | ||
dismiss() | ||
Task { await model.deletePost(id: post.id) } | ||
} | ||
} | ||
Button("Cancel", role: .cancel) {} | ||
} message: { | ||
Text("This cannot be undone.") | ||
} | ||
.alert("Confirm action", isPresented: $showingConfirmation) { | ||
if let action = confirmation { | ||
Button(action, role: .destructive) { | ||
| @@ -163,7 +199,7 @@ struct ProfileView: View { | ||
} 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 { | ||
} else if authorPosts.isEmpty && model.profileCursors[actorID] == nil && model.profileErrors[actorID] == nil { | ||
ContentUnavailableView("No posts yet", systemImage: "text.bubble", description: Text("Posts from this profile will appear here.")) | ||
.accessibilityIdentifier("profilePostsEmpty") | ||
.listRowSeparator(.hidden) | ||
| @@ -204,7 +240,7 @@ struct ProfileView: View { | ||
} | ||
} | ||
| ||
if model.profileCursors[actorID] != nil { | ||
if model.profileCursors[actorID] != nil || (model.authorPosts[actorID] != nil && model.profileErrors[actorID] != nil) { | ||
VStack(spacing: 8) { | ||
if model.loadingMoreProfileIDs.contains(actorID) { | ||
profilePostsPlaceholder(label: "Loading more posts", identifier: "profilePostsMoreLoading", rows: 1) | ||
| @@ -213,7 +249,7 @@ struct ProfileView: View { | ||
.font(.footnote) | ||
.foregroundStyle(.secondary) | ||
Button("Retry loading posts") { | ||
Task { await model.loadNextProfilePage(actorID: actorID) } | ||
Task { await model.retryProfilePosts(actorID: actorID) } | ||
} | ||
.buttonStyle(.bordered) | ||
.accessibilityIdentifier("retryMoreProfilePostsButton") | ||
| @@ -231,6 +267,7 @@ struct ProfileView: View { | ||
} | ||
} | ||
.listStyle(.plain) | ||
.refreshable { await model.loadProfile(actorID: actorID, forceRefresh: true) } | ||
.accessibilityIdentifier("profilePostList") | ||
.navigationTitle("Profile") | ||
.navigationBarTitleDisplayMode(.inline) | ||
| @@ -254,6 +291,11 @@ struct ProfileView: View { | ||
.sheet(item: $moderationPost) { post in ModerationControls(author: post.author, post: post) } | ||
.onChange(of: revealKey) { _, _ in revealedProfile = nil } | ||
.task(id: actorID) { if model.contentPreferences != nil { await model.loadProfile(actorID: actorID) } } | ||
.onAppear { | ||
if profile == nil, model.contentPreferences != nil { | ||
Task { await model.loadProfile(actorID: actorID) } | ||
} | ||
} | ||
.onChange(of: model.contentRevision) { _, _ in Task { await model.loadProfile(actorID: actorID) } } | ||
} | ||
| ||
| @@ -365,14 +407,8 @@ struct ProfileView: View { | ||
@ViewBuilder | ||
private var profileAvatar: some View { | ||
if let author, model.contentDecision(author: author)?.ui(.avatar).blur == false, let url = author.avatarURL { | ||
AsyncImage(url: url) { image in | ||
image.resizable().scaledToFill() | ||
} placeholder: { | ||
avatarPlaceholder | ||
} | ||
.frame(width: 72, height: 72) | ||
.clipShape(Circle()) | ||
.accessibilityLabel("Profile photo") | ||
AccountAvatar(account: Account(handle: author.handle, displayName: author.name, id: author.id, avatarURL: url), size: 72, isDecorative: false) | ||
.accessibilityLabel("Profile photo") | ||
} else { | ||
avatarPlaceholder | ||
.frame(width: 72, height: 72) | ||
Tests/OldskyTests/AppModelTests.swift+234−1
| @@ -21,8 +21,124 @@ final class ImageTestProtocol: URLProtocol { | ||
override func stopLoading() {} | ||
} | ||
| ||
private final class AvatarTestProtocol: URLProtocol { | ||
static let calls = FeedCallCounter() | ||
override class func canInit(with request: URLRequest) -> Bool { true } | ||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } | ||
override func startLoading() { | ||
_ = Self.calls.next() | ||
let url = request.url! | ||
let response = HTTPURLResponse(url: url, statusCode: url.path == "/error" ? 503 : 200, httpVersion: "HTTP/1.1", headerFields: nil)! | ||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) | ||
let data = UIGraphicsImageRenderer(size: CGSize(width: 2, height: 2)).image { _ in UIColor.red.setFill(); UIRectFill(CGRect(x: 0, y: 0, width: 2, height: 2)) }.pngData()! | ||
client?.urlProtocol(self, didLoad: data) | ||
client?.urlProtocolDidFinishLoading(self) | ||
} | ||
override func stopLoading() {} | ||
} | ||
| ||
@MainActor | ||
final class AppModelTests: XCTestCase { | ||
func testDeleteOwnPostAndRejectOtherAuthors() async throws { | ||
let model = AppModel(service: MockBlueskyService()) | ||
await model.signIn(handle: "demo", appPassword: "password") | ||
let other = try XCTUnwrap(model.timelinePosts.first) | ||
XCTAssertFalse(model.canDelete(other)) | ||
await model.deletePost(id: other.id) | ||
XCTAssertNotNil(model.post(id: other.id)) | ||
let published = await model.publish(text: "My post") | ||
XCTAssertTrue(published) | ||
let own = try XCTUnwrap(model.timelinePosts.first) | ||
XCTAssertTrue(model.canDelete(own)) | ||
await model.deletePost(id: own.id) | ||
XCTAssertNil(model.post(id: own.id)) | ||
XCTAssertFalse(model.timelinePosts.contains { $0.id == own.id }) | ||
XCTAssertTrue(model.deletedPostIDs.contains(own.id)) | ||
XCTAssertNil(model.errorMessage) | ||
} | ||
| ||
func testDeleteProfileOnlyOwnPostAfterFeedRefresh() async throws { | ||
let author = Post.Author(id: "demo", name: "Demo Account", handle: "demo.bsky.social") | ||
let own = Post(id: "at://demo/app.bsky.feed.post/profile-only", author: author, text: "My post", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []) | ||
let service = ProfilePostTestService(additionalProfilePost: own, refreshedFeed: FeedPage(posts: [], cursor: nil)) | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo", appPassword: "password") | ||
await model.loadProfile(actorID: "demo") | ||
await model.loadFeed() | ||
XCTAssertTrue(model.posts(for: "demo").contains { $0.id == own.id }) | ||
XCTAssertFalse(model.posts.contains { $0.id == own.id }) | ||
| ||
await model.deletePost(id: own.id) | ||
| ||
XCTAssertTrue(model.deletedPostIDs.contains(own.id)) | ||
XCTAssertNil(model.post(id: own.id)) | ||
XCTAssertFalse(model.posts(for: "demo").contains { $0.id == own.id }) | ||
XCTAssertNil(model.errorMessage) | ||
} | ||
| ||
func testDeletedPostDoesNotReturnInStaleResponses() async throws { | ||
let author = Post.Author(id: "demo", name: "Demo Account", handle: "demo.bsky.social") | ||
let deleted = Post(id: "at://demo/app.bsky.feed.post/deleted", author: author, text: "Deleted", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []) | ||
let other = Post(id: "other-post", author: author, text: "Keep", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], quote: Post.Quote(postID: deleted.id, author: author, text: "Deleted"), replyIDs: []) | ||
let page = FeedPage(posts: [deleted, other], cursor: "next", replyContexts: [other.id: [deleted, other], deleted.id: [deleted]], repostedBy: [deleted.id: author, other.id: author]) | ||
let notification = FeedNotification(id: "notice", author: author, reason: .reply, indexedAt: Date(), isRead: false, postID: other.id, relatedPost: deleted, parentPost: deleted) | ||
var service = ProfilePostTestService() | ||
service.refreshedFeed = page | ||
service.threadResult = ThreadResult(posts: [deleted, other], mutedPostIDs: []) | ||
service.freshProfilePost = deleted | ||
service.profileReplyContexts = page.replyContexts | ||
service.initialRepostedBy = page.repostedBy | ||
service.laterRepostedBy = page.repostedBy | ||
service.staleNotificationPage = NotificationPage(notifications: [notification], cursor: "next") | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo", appPassword: "password") | ||
await model.loadFeed() | ||
XCTAssertNotNil(model.post(id: deleted.id)) | ||
await model.deletePost(id: deleted.id) | ||
XCTAssertTrue(model.deletedPostIDs.contains(deleted.id)) | ||
XCTAssertNil(model.post(id: other.id)?.quote?.text) | ||
XCTAssertEqual(model.post(id: other.id)?.quote?.postID, deleted.id) | ||
| ||
await model.loadFeed() | ||
await model.loadNextPage() | ||
XCTAssertEqual(model.timelinePosts.map(\.id), [other.id]) | ||
XCTAssertNil(model.post(id: deleted.id)) | ||
XCTAssertEqual(model.replyContexts[other.id]?.map(\.id), [other.id]) | ||
XCTAssertNil(model.replyContexts[deleted.id]) | ||
XCTAssertNil(model.repostedBy[deleted.id]) | ||
| ||
await model.loadPost(id: other.id) | ||
await model.loadPost(id: deleted.id) | ||
XCTAssertEqual(model.threadContexts[other.id]?.map(\.id), [other.id]) | ||
XCTAssertFalse(model.failedPostIDs.contains(deleted.id)) | ||
await model.loadProfile(actorID: "mae") | ||
await model.loadNextProfilePage(actorID: "mae") | ||
XCTAssertFalse(model.posts(for: "mae").contains { $0.id == deleted.id }) | ||
_ = await model.loadNotifications() | ||
await model.loadNextNotificationsPage() | ||
XCTAssertNil(model.notifications.first?.relatedPost) | ||
XCTAssertNil(model.notifications.first?.parentPost) | ||
XCTAssertNil(model.post(id: deleted.id)) | ||
XCTAssertNotNil(model.post(id: other.id)) | ||
XCTAssertNil(model.post(id: other.id)?.quote?.text) | ||
XCTAssertEqual(model.post(id: other.id)?.quote?.postID, deleted.id) | ||
} | ||
| ||
func testDeleteFailureKeepsPost() async throws { | ||
var service = MockBlueskyService() | ||
service.failsDeleting = true | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo", appPassword: "password") | ||
let published = await model.publish(text: "My post") | ||
XCTAssertTrue(published) | ||
let own = try XCTUnwrap(model.timelinePosts.first) | ||
await model.deletePost(id: own.id) | ||
XCTAssertNotNil(model.post(id: own.id)) | ||
XCTAssertFalse(model.deletedPostIDs.contains(own.id)) | ||
XCTAssertEqual(model.errorMessage, "Could not confirm that the post was deleted. Refresh the feed and try again if it is still there.") | ||
XCTAssertFalse(model.activePostActions.contains(own.id)) | ||
} | ||
| ||
func testPostShareURLUsesRecordURIAndOpensInApp() { | ||
func post(_ id: String) -> Post { | ||
Post(id: id, author: Post.Author(id: "other", name: "Other", handle: "changed.example"), text: "", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: []) | ||
| @@ -549,6 +665,106 @@ final class AppModelTests: XCTestCase { | ||
XCTAssertEqual(model.threadAncestors(for: selected).map(\.id), ["post-1"]) | ||
} | ||
| ||
func testAvatarRequestsShareAndRetryFailures() async { | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [AvatarTestProtocol.self] | ||
configuration.urlCache = nil | ||
let store = AvatarStore(session: URLSession(configuration: configuration)) | ||
let url = URL(string: "https://example.test/avatar")! | ||
let before = AvatarTestProtocol.calls.count | ||
async let first = store.image(for: url) | ||
async let second = store.image(for: url) | ||
let images = await (first, second) | ||
XCTAssertNotNil(images.0) | ||
XCTAssertNotNil(images.1) | ||
XCTAssertEqual(AvatarTestProtocol.calls.count - before, 1) | ||
let cached = await store.image(for: url) | ||
XCTAssertNotNil(cached) | ||
XCTAssertEqual(AvatarTestProtocol.calls.count - before, 1) | ||
store.clear() | ||
let reloaded = await store.image(for: url) | ||
XCTAssertNotNil(reloaded) | ||
XCTAssertEqual(AvatarTestProtocol.calls.count - before, 2) | ||
let errorURL = URL(string: "https://example.test/error")! | ||
let failed = await store.image(for: errorURL) | ||
let retried = await store.image(for: errorURL) | ||
XCTAssertNil(failed) | ||
XCTAssertNil(retried) | ||
XCTAssertEqual(AvatarTestProtocol.calls.count - before, 4) | ||
} | ||
| ||
func testProfileRequestsShareAndRefresh() async { | ||
let gate = ThreadGate() | ||
let service = ProfilePostTestService(profileGate: gate) | ||
let model = AppModel(service: service) | ||
let first = Task { await model.loadProfile(actorID: "mae") } | ||
await gate.waitUntilStarted() | ||
await model.loadProfile(actorID: "mae") | ||
XCTAssertEqual(service.profileCalls.count, 1) | ||
await gate.release() | ||
await first.value | ||
await model.loadProfile(actorID: "mae") | ||
XCTAssertEqual(service.profileCalls.count, 1) | ||
let refresh = Task { await model.loadProfile(actorID: "mae", forceRefresh: true) } | ||
await gate.waitUntilStarted() | ||
XCTAssertEqual(service.profileCalls.count, 2) | ||
await gate.release() | ||
await refresh.value | ||
} | ||
| ||
func testProfileRefreshReplacesPostsCursorAndReposts() async { | ||
let reposter = Post.Author(id: "reposter", name: "Reposter", handle: "reposter.test") | ||
let service = ProfilePostTestService(emptyProfileFeedAfterFirst: true, initialRepostedBy: ["post-1": reposter]) | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.loadProfile(actorID: "mae") | ||
XCTAssertEqual(model.posts(for: "mae").map(\.id), ["post-1"]) | ||
XCTAssertNotNil(model.profileCursors["mae"]) | ||
XCTAssertEqual(model.profileRepostedBy["mae"]?["post-1"], reposter) | ||
| ||
await model.loadProfile(actorID: "mae", forceRefresh: true) | ||
| ||
XCTAssertTrue(model.posts(for: "mae").isEmpty) | ||
XCTAssertNil(model.profileCursors["mae"]) | ||
XCTAssertTrue(model.profileRepostedBy["mae", default: [:]].isEmpty) | ||
XCTAssertEqual(service.authorProfileCalls.count, 2) | ||
} | ||
| ||
func testRetryFailedProfileRefreshLoadsFirstPageWithExistingCursor() async { | ||
let service = ProfilePostTestService(emptyProfileFeedAfterFirst: true, failSecondProfilePageRequest: true) | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo", appPassword: "password") | ||
await model.loadProfile(actorID: "mae") | ||
XCTAssertNotNil(model.profileCursors["mae"]) | ||
XCTAssertFalse(model.posts(for: "mae").isEmpty) | ||
| ||
await model.loadProfile(actorID: "mae", forceRefresh: true) | ||
XCTAssertNotNil(model.profileErrors["mae"]) | ||
XCTAssertTrue(model.failedProfileRefreshIDs.contains("mae")) | ||
XCTAssertNotNil(model.profileCursors["mae"]) | ||
| ||
await model.retryProfilePosts(actorID: "mae") | ||
XCTAssertEqual(service.authorProfileCalls.count, 3) | ||
XCTAssertNil(model.profileErrors["mae"]) | ||
XCTAssertFalse(model.failedProfileRefreshIDs.contains("mae")) | ||
XCTAssertNil(model.profileCursors["mae"]) | ||
XCTAssertTrue(model.posts(for: "mae").isEmpty) | ||
} | ||
| ||
func testMissingProfileRefreshReportsErrorAndKeepsPosts() async { | ||
let service = ProfilePostTestService(missingProfileAfterFirst: true) | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.loadProfile(actorID: "mae") | ||
let posts = model.posts(for: "mae") | ||
| ||
await model.loadProfile(actorID: "mae", forceRefresh: true) | ||
| ||
XCTAssertEqual(model.posts(for: "mae"), posts) | ||
XCTAssertEqual(model.errorMessage, "This profile could not be found.") | ||
XCTAssertEqual(model.profileErrors["mae"], model.errorMessage) | ||
} | ||
| ||
func testFreshProfilePostReplacesCachedQuote() async { | ||
let base = MockBlueskyService() | ||
var fresh = try! await base.loadFollowingFeed(cursor: nil).posts.first { $0.id == "post-3" }! | ||
| @@ -1617,6 +1833,11 @@ private final class FeedCallCounter: @unchecked Sendable { | ||
calls += 1 | ||
return calls | ||
} | ||
var count: Int { | ||
lock.lock() | ||
defer { lock.unlock() } | ||
return calls | ||
} | ||
} | ||
| ||
@MainActor | ||
| @@ -1771,6 +1992,9 @@ private struct ProfilePostTestService: BlueskyService { | ||
let preferenceCalls = FeedCallCounter() | ||
var additionalProfilePost: Post? = nil | ||
var returnsEmptyProfileFeed = false | ||
var emptyProfileFeedAfterFirst = false | ||
var failSecondProfilePageRequest = false | ||
var missingProfileAfterFirst = false | ||
var profileReplyContexts: [String: [Post]] = [:] | ||
var initialRepostedBy: [String: Post.Author] = [:] | ||
var laterRepostedBy: [String: Post.Author] = [:] | ||
| @@ -1786,7 +2010,10 @@ private struct ProfilePostTestService: BlueskyService { | ||
var overlapGate: OverlapGate? = nil | ||
var notificationGate: ThreadGate? = nil | ||
var notificationOverlapGate: OverlapGate? = nil | ||
var staleNotificationPage: NotificationPage? = nil | ||
let feedCalls = FeedCallCounter() | ||
let profileCalls = FeedCallCounter() | ||
let authorProfileCalls = FeedCallCounter() | ||
| ||
func restoreAccount() async throws -> Account? { try await base.restoreAccount() } | ||
func loadModerationPreferences() async throws -> ModerationPolicy.Preferences { | ||
| @@ -1809,6 +2036,7 @@ private struct ProfilePostTestService: BlueskyService { | ||
func loadNotifications(cursor: String?) async throws -> NotificationPage { | ||
if let notificationGate { await notificationGate.wait() } | ||
if let notificationOverlapGate { await notificationOverlapGate.wait() } | ||
if let staleNotificationPage { return staleNotificationPage } | ||
return try await base.loadNotifications(cursor: cursor) | ||
} | ||
| ||
| @@ -1829,11 +2057,15 @@ private struct ProfilePostTestService: BlueskyService { | ||
return ThreadResult(posts: try await loadPost(uri: uri), mutedPostIDs: []) | ||
} | ||
func loadProfile(actorID: String) async throws -> Profile? { | ||
let call = profileCalls.next() | ||
if let profileGate { await profileGate.wait() } | ||
if missingProfileAfterFirst && call > 1 { return nil } | ||
return try await base.loadProfile(actorID: actorID) | ||
} | ||
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage { | ||
if returnsEmptyProfileFeed { | ||
let call = authorProfileCalls.next() | ||
if failSecondProfilePageRequest && call == 2 { throw URLError(.notConnectedToInternet) } | ||
if returnsEmptyProfileFeed || (emptyProfileFeedAfterFirst && call > 1) { | ||
return FeedPage(posts: [], cursor: nil) | ||
} | ||
let page = try await base.loadAuthorPosts(actorID: actorID, cursor: cursor) | ||
| @@ -1848,6 +2080,7 @@ private struct ProfilePostTestService: BlueskyService { | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { | ||
try await base.toggleRepost(post: post, reposted: reposted) | ||
} | ||
func deletePost(_ post: Post) async throws { try await base.deletePost(post) } | ||
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) | ||
} | ||
Tests/OldskyUITests/OldskyUITests.swift+101−0
| @@ -35,6 +35,84 @@ final class OldskyUITests: XCTestCase { | ||
XCTAssertTrue(app.otherElements["ActivityListView"].waitForExistence(timeout: 5) || app.buttons["Copy"].waitForExistence(timeout: 5)) | ||
} | ||
| ||
func testGeneratedAltTextRequiresReviewAndCanBeEdited() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-signed-in", "-ui-testing-compose-images", "-ui-testing-alt-success"] | ||
app.launch() | ||
XCTAssertTrue(app.buttons["postText-post-1"].waitForExistence(timeout: 10)) | ||
app.tabBars.buttons["New post"].tap() | ||
let field = app.textFields["altText-0"] | ||
XCTAssertTrue(field.waitForExistence(timeout: 5)) | ||
app.buttons["generateAltText-0"].tap() | ||
XCTAssertTrue(app.navigationBars["Review alt text"].waitForExistence(timeout: 5)) | ||
app.navigationBars["Review alt text"].buttons["Cancel"].tap() | ||
XCTAssertEqual(field.value as? String, "A photo") | ||
app.buttons["generateAltText-0"].tap() | ||
let editor = app.textViews["Generated alt text"] | ||
XCTAssertTrue(editor.waitForExistence(timeout: 5)) | ||
editor.tap() | ||
editor.typeText(" edited") | ||
app.buttons["Use text"].tap() | ||
XCTAssertTrue((field.value as? String ?? "").contains("edited")) | ||
} | ||
| ||
func testDelayedAltTextCanBeReviewed() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-signed-in", "-ui-testing-compose-images", "-ui-testing-alt-delayed"] | ||
app.launch() | ||
XCTAssertTrue(app.buttons["postText-post-1"].waitForExistence(timeout: 10)) | ||
app.tabBars.buttons["New post"].tap() | ||
XCTAssertTrue(app.buttons["generateAltText-0"].waitForExistence(timeout: 5)) | ||
app.buttons["generateAltText-0"].tap() | ||
XCTAssertTrue(app.buttons["stopGeneratingAltTextButton"].waitForExistence(timeout: 2)) | ||
XCTAssertFalse(app.buttons["publishButton"].isEnabled) | ||
XCTAssertTrue(app.navigationBars["Review alt text"].waitForExistence(timeout: 10)) | ||
app.buttons["Use text"].tap() | ||
XCTAssertEqual(app.textFields["altText-0"].value as? String, "A delayed description") | ||
} | ||
| ||
func testCancelDelayedAltTextKeepsComposerUsable() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-signed-in", "-ui-testing-compose-images", "-ui-testing-alt-delayed"] | ||
app.launch() | ||
XCTAssertTrue(app.buttons["postText-post-1"].waitForExistence(timeout: 10)) | ||
app.tabBars.buttons["New post"].tap() | ||
XCTAssertTrue(app.buttons["generateAltText-0"].waitForExistence(timeout: 5)) | ||
app.buttons["generateAltText-0"].tap() | ||
let stop = app.buttons["stopGeneratingAltTextButton"] | ||
XCTAssertTrue(stop.waitForExistence(timeout: 2)) | ||
stop.tap() | ||
XCTAssertTrue(app.buttons["publishButton"].isEnabled) | ||
XCTAssertTrue(app.buttons["cancelComposeButton"].isEnabled) | ||
XCTAssertEqual(app.textFields["altText-0"].value as? String, "A photo") | ||
app.buttons["generateAltText-0"].tap() | ||
XCTAssertTrue(stop.waitForExistence(timeout: 2)) | ||
XCTAssertTrue(app.navigationBars["Review alt text"].waitForExistence(timeout: 10)) | ||
XCTAssertFalse(app.alerts["Alt text unavailable"].exists) | ||
app.navigationBars["Review alt text"].buttons["Cancel"].tap() | ||
XCTAssertEqual(app.textFields["altText-0"].value as? String, "A photo") | ||
} | ||
| ||
func testAltTextUnavailableAndFailureKeepManualText() { | ||
for mode in ["-ui-testing-alt-unavailable", "-ui-testing-alt-failure"] { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-signed-in", "-ui-testing-compose-images", mode] | ||
app.launch() | ||
XCTAssertTrue(app.buttons["postText-post-1"].waitForExistence(timeout: 10)) | ||
app.tabBars.buttons["New post"].tap() | ||
let field = app.textFields["altText-0"] | ||
XCTAssertTrue(field.waitForExistence(timeout: 5)) | ||
app.buttons["generateAltText-0"].tap() | ||
let alert = app.alerts["Alt text unavailable"] | ||
XCTAssertTrue(alert.waitForExistence(timeout: 5)) | ||
alert.buttons["OK"].tap() | ||
XCTAssertEqual(field.value as? String, "A photo") | ||
app.buttons["publishButton"].tap() | ||
XCTAssertTrue(app.alerts["Add alt text?"].waitForExistence(timeout: 5)) | ||
app.terminate() | ||
} | ||
} | ||
| ||
func testMissingAltTextReminderAllowsEditingAndPosting() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-signed-in", "-ui-testing-compose-images"] | ||
| @@ -237,6 +315,29 @@ final class OldskyUITests: XCTestCase { | ||
XCTAssertTrue(app.buttons["postText-post-1"].exists) | ||
} | ||
| ||
func testDeletePostRequiresConfirmation() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing", "-ui-testing-signed-in", "-ui-testing-own-post"] | ||
app.launch() | ||
let post = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "My post to share and delete.")).firstMatch | ||
XCTAssertTrue(post.waitForExistence(timeout: 5)) | ||
let controls = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "postControls-")).firstMatch | ||
controls.tap() | ||
XCTAssertTrue(app.navigationBars["Controls"].waitForExistence(timeout: 5)) | ||
XCTAssertTrue(app.buttons["Share post"].exists) | ||
XCTAssertTrue(app.buttons["Copy link"].exists) | ||
XCTAssertFalse(app.buttons["Report post"].exists) | ||
app.buttons["Delete post"].tap() | ||
let alert = app.alerts["Delete this post?"] | ||
XCTAssertTrue(alert.waitForExistence(timeout: 5)) | ||
alert.buttons["Cancel"].tap() | ||
XCTAssertTrue(post.exists) | ||
app.buttons["Delete post"].tap() | ||
XCTAssertTrue(alert.waitForExistence(timeout: 5)) | ||
alert.buttons["Delete post"].tap() | ||
XCTAssertTrue(post.waitForNonExistence(timeout: 5)) | ||
} | ||
| ||
func testDemoSignInAndCreatePost() { | ||
let app = XCUIApplication() | ||
app.launchArguments = ["-ui-testing"] | ||
README.md+4−0
| @@ -8,6 +8,10 @@ Sign in with an existing Bluesky account and an app password. You can read your | ||
| ||
Old Fella reminds you when an image has no alt text by default. You can turn off the reminder in Settings. When the reminder appears, you can return to editing or post without alt text. | ||
| ||
You can ask Apple Intelligence to draft alt text for each image. The image is processed on your device. Review and edit the draft before you choose Use text. Generated descriptions can be wrong or omit details. You can always write alt text yourself. | ||
| ||
This feature needs an iPhone that supports Apple Intelligence, with Apple Intelligence available and enabled. Availability also depends on language and region. Apple lists supported devices and setup requirements in [How to get Apple Intelligence](https://support.apple.com/en-us/121115). Larger images can take longer to process. Apple describes image input in [Analyzing images with multimodal prompting](https://developer.apple.com/documentation/foundationmodels/analyzing-images-with-multimodal-prompting). | ||
| ||
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. | ||