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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit
extension ATProtoBlueskyService {
func resolvePostURI(_ uri: String) async throws -> String {
guard uri.hasPrefix("at://"),
let authorityEnd = uri["at://".endIndex...].firstIndex(of: "/")
else { return uri }
let authority = String(uri["at://".endIndex..<authorityEnd])
guard !authority.hasPrefix("did:") else { return uri }
let did = try await resolveDID(for: authority)
return "at://\(did)\(uri[authorityEnd...])"
}
func loadPost(uri: String) async throws -> [Post] {
try await loadThread(uri: uri).posts
}
func loadThread(uri: String) async throws -> ThreadResult {
let resolvedURI = try await resolvePostURI(uri)
async let positions = loadThreadPositions(anchor: resolvedURI)
let object = try await readObject {
try await $0.getPostThread(from: resolvedURI, depth: 1000, parentHeight: 1000)
}
guard let thread = object["thread"] as? [String: Any] else { return ThreadResult(posts: [], mutedPostIDs: []) }
var mutedPostIDs: Set<String> = []
func recordMuted(_ value: [String: Any]) {
guard let post = value["post"] as? [String: Any],
let author = post["author"] as? [String: Any], Self.isMuted(author),
let id = post["uri"] as? String
else { return }
mutedPostIDs.insert(id)
}
var ancestors: [Post] = []
var parent = thread["parent"] as? [String: Any]
while let parentThread = parent {
recordMuted(parentThread)
if let postObject = parentThread["post"] as? [String: Any], let post = mapPost(postObject) {
ancestors.append(post)
}
parent = parentThread["parent"] as? [String: Any]
}
func collectMuted(_ value: [String: Any]) {
recordMuted(value)
for reply in value["replies"] as? [[String: Any]] ?? [] { collectMuted(reply) }
}
collectMuted(thread)
var selectedAndReplies: [Post] = []
appendThread(thread, to: &selectedAndReplies)
guard selectedAndReplies.contains(where: { $0.id == resolvedURI }) else {
return ThreadResult(posts: [], mutedPostIDs: mutedPostIDs)
}
let posts = ancestors.reversed() + selectedAndReplies
let visibleIDs = Set(posts.map(\.id))
return await ThreadResult(
posts: posts, mutedPostIDs: mutedPostIDs, positions: positions.filter { visibleIDs.contains($0.key) })
}
private func loadThreadPositions(anchor: String) async -> [String: ThreadPosition] {
do {
let object = try await readObject { client in
guard let baseURL = URL(string: client.pdsURL),
var url = URLComponents(
url: baseURL.appendingPathComponent("xrpc/app.bsky.unspecced.getPostThreadV2"),
resolvingAgainstBaseURL: false)
else { throw ServiceError.invalidResponse }
url.queryItems = [
URLQueryItem(name: "anchor", value: anchor),
URLQueryItem(name: "below", value: "20")
]
guard let requestURL = url.url else { throw ServiceError.invalidResponse }
return try await client.apiClientService.sendRequest(URLRequest(url: requestURL, timeoutInterval: 4))
}
let items = object["thread"] as? [[String: Any]] ?? []
return items.reduce(into: [:]) { positions, item in
guard let id = item["uri"] as? String, let value = item["value"] as? [String: Any],
value["opThread"] as? Bool == true,
value["hiddenByThreadgate"] as? Bool != true, value["mutedByViewer"] as? Bool != true,
let post = value["post"] as? [String: Any], post["uri"] as? String == id,
let index = value["opThreadPostIndex"] as? Int, let count = value["opThreadPostCount"] as? Int,
let position = ThreadPosition(index: index, count: count)
else { return }
positions[id] = position
}
} catch {
// The thread stays available if the numbering endpoint fails.
return [:]
}
}
func loadProfile(actorID: String) async throws -> Profile? {
let profile = try await readObject { try await $0.getProfile(for: actorID) }
guard let did = profile["did"] as? String, let handle = profile["handle"] as? String else {
throw ServiceError.invalidResponse
}
let viewer = profile["viewer"] as? [String: Any]
let following = viewer?["following"] as? String
let author = Post.Author(
id: did, name: profile["displayName"] as? String ?? handle, handle: handle,
avatarURL: Self.url(profile["avatar"]), moderationLabels: Self.moderationLabels(profile["labels"]),
isFollowing: following != nil)
let links = (profile["links"] as? [[String: Any]] ?? []).compactMap { value -> Profile.Link? in
guard let id = value["uri"] as? String,
let rawURL = value["url"] as? String, let url = URL(string: rawURL),
["http", "https"].contains(url.scheme?.lowercased() ?? ""),
let host = url.host, !host.isEmpty
else { return nil }
let title = (value["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
return Profile.Link(
id: id, title: title.flatMap { $0.isEmpty ? nil : $0 } ?? rawURL,
url: url, moderationLabels: Self.moderationLabels(value["labels"]))
}
return Profile(
author: author, bio: profile["description"] as? String ?? "", location: nil, website: nil,
followerCount: profile["followersCount"] as? Int ?? 0, followingCount: profile["followsCount"] as? Int ?? 0,
isFollowing: following != nil, followURI: following, isFollowedBy: viewer?["followedBy"] is String,
links: links)
}
func loadProfileConnections(actorID: String, kind: ProfileConnectionKind, cursor: String?) async throws
-> ProfileConnectionsPage {
guard stored != nil else { throw ServiceError.noSession }
let object: [String: Any]
let key: String
switch kind {
case .followers:
object = try await readObject { try await $0.getFollowers(by: actorID, cursor: cursor) }
key = "followers"
case .following:
object = try await readObject { try await $0.getFollows(from: actorID, cursor: cursor) }
key = "follows"
}
return ProfileConnectionsPage(
accounts: try accountSummaries(from: object, key: key), cursor: object["cursor"] as? String)
}
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage {
let object = try await readObject {
try await $0.getAuthorFeed(
by: actorID, limit: Self.feedPageSize, cursor: cursor, postFilter: .postsWithReplies,
shouldIncludePins: false)
}
return mapFeedPage(object)
}
func mapFeedPage(_ object: [String: Any], hideBlockedPosts: Bool = false) -> FeedPage {
var contexts: [String: [Post]] = [:]
var repostedBy: [String: Post.Author] = [:]
var mutedPostIDs: Set<String> = []
let posts = (object["feed"] as? [[String: Any]] ?? []).compactMap { item -> Post? in
let reply = item["reply"] as? [String: Any] ?? [:]
for value in [item["post"], reply["root"], reply["parent"]] {
guard let value = value as? [String: Any] else { continue }
let post = value["post"] as? [String: Any] ?? value
guard let author = post["author"] as? [String: Any], Self.isMuted(author),
let id = post["uri"] as? String
else { continue }
mutedPostIDs.insert(id)
}
if hideBlockedPosts && ([item["post"], reply["root"], reply["parent"]].contains { isBlockedPost($0) }) {
return nil
}
guard var post = (item["post"] as? [String: Any]).flatMap(mapPost) else { return nil }
if let author = reply["grandparentAuthor"] as? [String: Any],
let did = author["did"] as? String, let handle = author["handle"] as? String {
post.replyGrandparentAuthor = Post.Author(
id: did, name: author["displayName"] as? String ?? handle, handle: handle,
avatarURL: Self.url(author["avatar"]), moderationLabels: Self.moderationLabels(author["labels"]),
isFollowing: (author["viewer"] as? [String: Any])?["following"] != nil
)
}
if let reason = item["reason"] as? [String: Any],
let author = reason["by"] as? [String: Any], Self.isMuted(author) {
return nil
}
let context = ["root", "parent"].compactMap { key -> Post? in
guard let value = reply[key] as? [String: Any] else { return nil }
return mapPost((value["post"] as? [String: Any]) ?? value)
}
if !context.isEmpty { contexts[post.id] = context }
if let author = repostAuthor(from: item["reason"]) {
repostedBy[post.id] = author
}
return post
}
let visiblePosts = posts.filter { !mutedPostIDs.contains($0.id) }
contexts = contexts.filter { !mutedPostIDs.contains($0.key) }.mapValues {
$0.filter { !mutedPostIDs.contains($0.id) }
}
repostedBy = repostedBy.filter { !mutedPostIDs.contains($0.key) }
return FeedPage(
posts: visiblePosts, cursor: object["cursor"] as? String, replyContexts: contexts, repostedBy: repostedBy,
mutedPostIDs: mutedPostIDs)
}
func isBlockedPost(_ value: Any?) -> Bool {
guard let value = value as? [String: Any] else { return false }
if value["$type"] as? String == "app.bsky.feed.defs#blockedPost" || value["blocked"] as? Bool == true {
return true
}
let post = (value["post"] as? [String: Any]) ?? value
guard let author = post["author"] as? [String: Any],
let viewer = author["viewer"] as? [String: Any]
else { return false }
return viewer["blocking"] is String || viewer["blockedBy"] as? Bool == true
|| viewer["blockingByList"] != nil
}
func repostAuthor(from value: Any?) -> Post.Author? {
guard let reason = value as? [String: Any],
reason["$type"] as? String == "app.bsky.feed.defs#reasonRepost",
let author = reason["by"] as? [String: Any],
let did = author["did"] as? String, let handle = author["handle"] as? String
else { return nil }
return Post.Author(
id: did, name: author["displayName"] as? String ?? handle, handle: handle,
avatarURL: Self.url(author["avatar"]),
moderationLabels: Self.moderationLabels(author["labels"]),
isFollowing: (author["viewer"] as? [String: Any])?["following"] != nil)
}
}