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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit
extension ATProtoBlueskyService {
func apiClient(
for url: URL, sessionConfiguration: SessionConfiguration? = nil, capture: ResponseCapture? = nil
) async -> ATProtoKit {
let session = self.session
let executor = ClosureATRequestExecutor { [weak self] original, _ in
var request = Self.preparedRequest(original, configuration: sessionConfiguration)
let isWrite = Self.isRecordOrBookmarkWrite(request)
func dispatch(_ request: URLRequest) async throws -> (Data, URLResponse) {
if let configuration = sessionConfiguration as? LibrarySession {
guard let self else { throw ActionNotSentError(underlying: ServiceError.noSession) }
return try await self.dispatchAuthenticated(request, generation: configuration.generation)
}
return try await session.data(for: request)
}
var (data, response) = try await dispatch(request)
if (response as? HTTPURLResponse)?.statusCode == 401,
let configuration = sessionConfiguration as? LibrarySession, let self {
let token: String
do {
token = try await self.refreshSession(
generation: configuration.generation, rejectedToken: configuration.token)
} catch {
if isWrite { throw ActionNotSentError(underlying: error) }
throw error
}
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
(data, response) = try await dispatch(request)
}
try Self.validateAPIResponse(data, response: response, request: request, isWrite: isWrite)
await capture?.save(data)
return (Self.sdkCompatibleGalleryResponse(data), response)
}
return await ATProtoKit(
sessionConfiguration: sessionConfiguration,
apiClientConfiguration: APIClientConfiguration(responseProvider: executor), pdsURL: url.absoluteString)
}
private static func preparedRequest(_ original: URLRequest, configuration: SessionConfiguration?) -> URLRequest {
var request = original
request.timeoutInterval = min(request.timeoutInterval, 30)
if ["/xrpc/app.bsky.notification.listNotifications", "/xrpc/app.bsky.bookmark.getBookmarks"].contains(
request.url?.path ?? "") {
request.cachePolicy = .reloadIgnoringLocalCacheData
}
if let configuration = configuration as? LibrarySession {
request.setValue("Bearer \(configuration.token)", forHTTPHeaderField: "Authorization")
if request.url?.path.hasPrefix("/xrpc/app.bsky.") == true {
request.setValue("did:web:api.bsky.app#bsky_appview", forHTTPHeaderField: "atproto-proxy")
if request.httpMethod == "GET", let labelers = configuration.labelers {
request.setValue(labelers, forHTTPHeaderField: "atproto-accept-labelers")
}
}
}
return request
}
private static func validateAPIResponse(
_ data: Data, response: URLResponse, request: URLRequest,
isWrite: Bool
) throws {
guard let http = response as? HTTPURLResponse else { throw ServiceError.invalidResponse }
guard (200..<300).contains(http.statusCode) else {
if request.url?.path == "/xrpc/app.bsky.labeler.getServices" {
Logger(subsystem: "com.oldfella.app", category: "moderation").error(
"Definition request returned HTTP \(http.statusCode, privacy: .public)")
}
if http.statusCode == 404, request.url?.path == "/xrpc/app.bsky.feed.getFeed" {
throw CustomFeedError.unavailable
}
let body = try? JSONDecoder().decode(APIErrorBody.self, from: data)
if isWrite,
http.statusCode == 400 && body?.error != nil || http.statusCode == 401 || http.statusCode == 403 {
let error = ServiceError.requestFailed(
body?.message ?? "The server rejected the request (\(http.statusCode)).")
throw ActionNotSentError(underlying: error)
}
if body?.error == "AuthFactorTokenRequired" { throw ServiceError.authFactorTokenRequired }
if let code = body?.error {
throw ServiceError.serverResponse(code: code, message: body?.message ?? code)
}
throw ServiceError.requestFailed(body?.message ?? "The server returned an error (\(http.statusCode)).")
}
}
static func sdkCompatibleGalleryResponse(_ data: Data) -> Data {
guard data.range(of: Data("app.bsky.embed.gallery#view".utf8)) != nil,
let object = try? JSONSerialization.jsonObject(with: data)
else { return data }
func convert(_ value: Any) -> Any {
if let array = value as? [Any] { return array.map(convert) }
guard var dictionary = value as? [String: Any] else { return value }
if dictionary["$type"] as? String == "app.bsky.embed.gallery#view" {
let items = dictionary["items"] as? [[String: Any]] ?? []
let images: [[String: Any]] = items.compactMap { item in
guard item["$type"] as? String == "app.bsky.embed.gallery#viewImage",
let url = item["fullsize"] as? String ?? item["thumbnail"] as? String
else { return nil }
var image: [String: Any] = [
"fullsize": url, "thumb": item["thumbnail"] as? String ?? url,
"alt": item["alt"] as? String ?? ""
]
if let aspectRatio = item["aspectRatio"] { image["aspectRatio"] = aspectRatio }
return image
}
return ["$type": "app.bsky.embed.images#view", "images": images]
}
for (key, item) in dictionary { dictionary[key] = convert(item) }
return dictionary
}
return (try? JSONSerialization.data(withJSONObject: convert(object))) ?? data
}
func dispatchAuthenticated(_ request: URLRequest, generation: UUID) async throws -> (Data, URLResponse) {
let isWrite = Self.isRecordOrBookmarkWrite(request)
if isWrite {
await beforeAuthenticatedDispatch?()
}
guard generation == sessionGeneration, stored != nil,
!usesSharedSession || (try? currentSessionID()) == activeSessionID && activeSessionID != nil
else {
throw ActionNotSentError(underlying: ServiceError.noSession)
}
if isWrite, Task.isCancelled {
throw ActionNotSentError(underlying: CancellationError())
}
return try await session.data(for: request)
}
private static func isRecordOrBookmarkWrite(_ request: URLRequest) -> Bool {
switch request.url?.path {
case "/xrpc/com.atproto.repo.createRecord", "/xrpc/com.atproto.repo.deleteRecord",
"/xrpc/com.atproto.repo.putRecord",
"/xrpc/app.bsky.bookmark.createBookmark", "/xrpc/app.bsky.bookmark.deleteBookmark":
true
default:
false
}
}
func dispatchAuthenticatedUpload(_ request: URLRequest, fileURL: URL, generation: UUID) async throws -> (
Data, URLResponse
) {
guard generation == sessionGeneration, stored != nil,
!usesSharedSession || (try? currentSessionID()) == activeSessionID && activeSessionID != nil
else {
throw ActionNotSentError(underlying: ServiceError.noSession)
}
return try await session.upload(for: request, fromFile: fileURL)
}
func authenticatedClient(capture: ResponseCapture? = nil) async throws -> ATProtoKit {
let generation = sessionGeneration
let token = try await accessToken()
guard generation == sessionGeneration, let current = stored else { throw ServiceError.noSession }
let configuration = LibrarySession(
pdsURL: current.pdsURL, token: token, generation: generation,
labelers: selectedLabelers.isEmpty ? nil : selectedLabelers.joined(separator: ","))
let user = UserSession(
handle: current.handle, sessionDID: current.did, isEmailAuthenticationFactorEnabled: nil, isActive: nil,
status: nil, serviceEndpoint: current.pdsURL)
await UserSessionRegistry.shared.register(configuration.instanceUUID, session: user)
return await apiClient(for: current.pdsURL, sessionConfiguration: configuration, capture: capture)
}
func readObject<T>(
allowUntypedLabelerViews: Bool = false, allowBookmarkDecodingFailure: Bool = false,
_ operation: (ATProtoKit) async throws -> T
) async throws -> [String: Any] {
let capture = ResponseCapture()
let client =
try await stored == nil
? apiClient(for: appViewURL, capture: capture) : authenticatedClient(capture: capture)
do {
_ = try await operation(client)
if let id = client.sessionConfiguration?.instanceUUID {
await UserSessionRegistry.shared.removeSession(for: id)
}
guard let data = await capture.read() else { throw ServiceError.invalidResponse }
return try decodeObject(data)
} catch {
if let id = client.sessionConfiguration?.instanceUUID {
await UserSessionRegistry.shared.removeSession(for: id)
}
if allowBookmarkDecodingFailure, error is DecodingError, let data = await capture.read() {
return try decodeObject(data)
}
if allowUntypedLabelerViews, case DecodingError.keyNotFound(let key, let context) = error,
key.stringValue == "$type", context.codingPath.count == 2,
context.codingPath[0].stringValue == "views", context.codingPath[1].intValue != nil,
let data = await capture.read() {
return try decodeObject(data)
}
throw error
}
}
func resolveDID(for handle: String) async throws -> String {
let client = await apiClient(for: appViewURL)
let result = try await client.resolveHandle(from: handle)
guard result.did.hasPrefix("did:") else { throw ServiceError.identityNotFound }
return result.did
}
func resolvePDSURL(for did: String, fallbackDocument: Any? = nil) async throws -> URL {
let document = try await resolveDIDDocument(for: did) ?? fallbackDocument
guard let pds = Self.pdsURL(from: document) else { throw ServiceError.pdsNotFound }
return pds
}
func resolveDIDDocument(for did: String) async throws -> Any? {
let didDocumentURL: URL?
if did.hasPrefix("did:plc:") {
didDocumentURL = URL(string: "https://plc.directory/\(did)")
} else if did.hasPrefix("did:web:") {
let identifier = String(did.dropFirst("did:web:".count))
let parts = identifier.split(separator: ":").map(String.init)
guard let host = parts.first else { throw ServiceError.invalidDID }
var components = URLComponents()
components.scheme = "https"
components.host = host
let path = parts.dropFirst().joined(separator: "/")
components.path = path.isEmpty ? "/.well-known/did.json" : "/\(path)/did.json"
didDocumentURL = components.url
} else {
throw ServiceError.unsupportedDIDMethod
}
guard let didDocumentURL else { throw ServiceError.invalidDID }
let (data, _) = try await send(to: didDocumentURL, method: "GET", body: nil, contentType: nil)
return try JSONSerialization.jsonObject(with: data)
}
}