1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
enum TimelinePolicy {
struct Visibility {
let canShow: (Post) -> Bool
let canShowRepostAuthor: (Post.Author?) -> Bool
let follows: (Post.Author) -> Bool
}
static func filter(
_ feedPosts: [Post],
contexts: [String: [Post]],
reposts: [String: Post.Author],
includeUnfollowedReplies: Bool,
visibility: Visibility
) -> [Post] {
let feedByID = Dictionary(feedPosts.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
var seenThreads: Set<String> = []
return feedPosts.filter { post in
guard visibility.canShow(post), visibility.canShowRepostAuthor(reposts[post.id]) else { return false }
let context = contexts[post.id] ?? []
let ids = [post.replyRootURI, post.replyParentURI].compactMap { $0 }.filter { $0 != post.id }
let related = ids.compactMap { id in context.first { $0.id == id } ?? feedByID[id] }
guard related.allSatisfy({ visibility.canShow($0) }) else { return false }
if !includeUnfollowedReplies && (post.replyRootURI != nil || post.replyParentURI != nil) {
guard visibility.follows(post.author) else { return false }
let authors = related.map(\.author) + [post.replyGrandparentAuthor].compactMap { $0 }
let isSelfThread = authors.allSatisfy { $0.id == post.author.id }
let hasFollowedConnection = authors.contains { $0.id != post.author.id && visibility.follows($0) }
guard isSelfThread || hasFollowedConnection else { return false }
}
return seenThreads.insert(post.replyRootURI ?? post.id).inserted
}
}
}