1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit
extension ATProtoBlueskyService {
func loadNotifications(cursor: String?) async throws -> NotificationPage {
guard stored != nil else { throw ServiceError.noSession }
let generation = sessionGeneration
let object = try await readObject { try await $0.listNotifications(limit: 50, cursor: cursor) }
guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
guard let allNotificationObjects = object["notifications"] as? [[String: Any]] else {
throw ServiceError.notificationsUnavailable
}
let notificationObjects = allNotificationObjects.filter {
guard let author = $0["author"] as? [String: Any] else { return true }
return !Self.isMuted(author)
}
let postURIs = Set(notificationObjects.flatMap(Self.notificationPostURIs))
let sortedPostURIs = postURIs.sorted()
let batches = stride(from: 0, to: sortedPostURIs.count, by: 25).map { start in
Array(sortedPostURIs[start..<min(start + 25, sortedPostURIs.count)])
}
var hydrated = try await loadNotificationPosts(batches, generation: generation)
let retries = batches.filter { $0.count > 1 }.flatMap { $0 }.filter { !hydrated.returnedURIs.contains($0) }
hydrated.merge(try await loadNotificationPosts(retries.map { [$0] }, generation: generation))
try Task.checkCancellation()
guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
let postsByURI = hydrated.posts
let unavailablePostURIs = hydrated.unavailableURIs.union(postURIs.subtracting(hydrated.returnedURIs))
let notifications = notificationObjects.compactMap {
Self.notification(from: $0, postsByURI: postsByURI, unavailablePostURIs: unavailablePostURIs)
}
return NotificationPage(notifications: notifications, cursor: object["cursor"] as? String)
}
func loadNotificationPosts(_ batches: [[String]], generation: UUID) async throws -> NotificationPosts {
do {
return try await withThrowingTaskGroup(of: NotificationPosts.self) { group in
var pending = batches.makeIterator()
for _ in 0..<Self.notificationPostRequestLimit {
guard let batch = pending.next() else { break }
group.addTask { try await self.loadNotificationPostBatch(batch, generation: generation) }
}
var result = NotificationPosts()
while let batch = try await group.next() {
result.merge(batch)
if let next = pending.next() {
group.addTask { try await self.loadNotificationPostBatch(next, generation: generation) }
}
}
return result
}
} catch {
if NetworkFailure.isCancellation(error) || NetworkFailure.isConnectionFailure(error) { throw error }
throw ServiceError.notificationsUnavailable
}
}
func loadNotificationPostBatch(_ uris: [String], generation: UUID) async throws -> NotificationPosts {
try Task.checkCancellation()
guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
let response = try await readObject { try await $0.getPosts(uris) }
try Task.checkCancellation()
guard generation == sessionGeneration, stored != nil else { throw ServiceError.noSession }
guard let objects = response["posts"] as? [[String: Any]] else { throw ServiceError.notificationsUnavailable }
var result = NotificationPosts()
for object in objects {
guard let uri = object["uri"] as? String, uris.contains(uri), result.returnedURIs.insert(uri).inserted,
let author = object["author"] as? [String: Any],
object["cid"] is String, author["did"] is String, author["handle"] is String,
let record = object["record"] as? [String: Any], record["text"] is String
else {
throw ServiceError.notificationsUnavailable
}
if Self.isMuted(author) || isBlockedPost(object) {
result.unavailableURIs.insert(uri)
} else if let post = mapPost(object) {
result.posts[uri] = post
} else {
throw ServiceError.notificationsUnavailable
}
}
return result
}
func markNotificationsRead(seenAt: Date) async throws {
let client = try await authenticatedClient()
do {
try await client.updateSeen(seenAt: seenAt)
if let id = client.sessionConfiguration?.instanceUUID {
await UserSessionRegistry.shared.removeSession(for: id)
}
} catch {
if let id = client.sessionConfiguration?.instanceUUID {
await UserSessionRegistry.shared.removeSession(for: id)
}
throw error
}
}
private static func notificationPostURIs(_ item: [String: Any]) -> [String] {
let reason = FeedNotification.Reason(rawValue: item["reason"] as? String ?? "") ?? .unknown
let subjectURI = item["reasonSubject"] as? String ?? item["recordSubject"] as? String
if reason == .reply {
let record = item["record"] as? [String: Any]
let reply = record?["reply"] as? [String: Any]
let parent = reply?["parent"] as? [String: Any]
return [item["uri"] as? String, subjectURI, parent?["uri"] as? String].compactMap { $0 }
}
if reason == .mention || reason == .quote {
return [item["uri"] as? String].compactMap { $0 }
}
return [subjectURI].compactMap { $0 }
}
private static func notification(
from item: [String: Any], postsByURI: [String: Post],
unavailablePostURIs: Set<String>
) -> FeedNotification? {
guard let uri = item["uri"] as? String,
let authorObject = item["author"] as? [String: Any],
!Self.isMuted(authorObject),
let did = authorObject["did"] as? String,
let handle = authorObject["handle"] as? String
else { return nil }
let reason = FeedNotification.Reason(rawValue: item["reason"] as? String ?? "") ?? .unknown
let timestamp = Self.notificationDate(item["indexedAt"])
let activityRecord = item["record"] as? [String: Any]
let replyRecord = activityRecord?["reply"] as? [String: Any]
let replyParent = replyRecord?["parent"] as? [String: Any]
let subjectURI =
item["reasonSubject"] as? String
?? item["recordSubject"] as? String
?? replyParent?["uri"] as? String
let postID =
reason == .reply || reason == .mention || reason == .quote
? item["uri"] as? String
: subjectURI
let parentURI = replyParent?["uri"] as? String
guard
Self.hasNotificationPosts(
reason: reason, postID: postID, subjectURI: subjectURI,
parentURI: parentURI,
hydrated: NotificationPosts(posts: postsByURI, unavailableURIs: unavailablePostURIs))
else { return nil }
let relatedPost = postID.flatMap { postsByURI[$0] }
return FeedNotification(
id: uri,
author: Post.Author(
id: did, name: authorObject["displayName"] as? String ?? handle, handle: handle,
avatarURL: Self.url(authorObject["avatar"]),
moderationLabels: Self.moderationLabels(authorObject["labels"]),
isFollowing: (authorObject["viewer"] as? [String: Any])?["following"] != nil,
bio: authorObject["description"] as? String),
reason: reason,
indexedAt: timestamp,
isRead: item["isRead"] as? Bool ?? true,
postID: postID,
relatedPost: relatedPost,
parentPost: reason == .reply ? (replyParent?["uri"] as? String).flatMap { postsByURI[$0] } : nil,
isFollowedBy: (authorObject["viewer"] as? [String: Any])?["followedBy"] is String
)
}
private static func notificationDate(_ value: Any?) -> Date {
let indexedAt = value as? String ?? ""
let fractionalDateFormatter = ISO8601DateFormatter()
fractionalDateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return
fractionalDateFormatter.date(from: indexedAt)
?? ISO8601DateFormatter().date(from: indexedAt)
?? .distantPast
}
private static func hasNotificationPosts(
reason: FeedNotification.Reason, postID: String?, subjectURI: String?,
parentURI: String?, hydrated: NotificationPosts
) -> Bool {
let requiredURIs: [String?] = reason == .reply ? [postID, subjectURI, parentURI] : [postID]
guard !requiredURIs.compactMap({ $0 }).contains(where: { hydrated.unavailableURIs.contains($0) }) else {
return false
}
if [FeedNotification.Reason.reply, .mention, .quote, .like, .repost].contains(reason) {
guard let postID, hydrated.posts[postID] != nil else { return false }
}
if reason == .reply, parentURI == nil { return false }
return true
}
}