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
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit
extension ATProtoBlueskyService {
func send(
to url: URL,
method: String,
body: Data?,
contentType: String?,
authenticated: Bool = false,
retried: Bool = false,
proxyService: String? = nil,
authorizationToken: String? = nil,
classifyModerationWrite: Bool = false
) async throws -> (Data, HTTPURLResponse) {
var request = URLRequest(url: url)
request.httpMethod = method
request.httpBody = body
request.timeoutInterval = 30
if url.path == "/xrpc/com.atproto.repo.getRecord" {
request.cachePolicy = .reloadIgnoringLocalCacheData
}
if let contentType { request.setValue(contentType, forHTTPHeaderField: "Content-Type") }
if let proxyService { request.setValue(proxyService, forHTTPHeaderField: "atproto-proxy") }
let generation = sessionGeneration
let requestToken = try await authenticate(
&request, authenticated: authenticated,
authorizationToken: authorizationToken, generation: generation,
classifyModerationWrite: classifyModerationWrite)
if Task.isCancelled {
if classifyModerationWrite { throw ActionNotSentError(underlying: CancellationError()) }
throw CancellationError()
}
let (data, response) = try await session.data(for: request)
guard let http = response as? HTTPURLResponse else { throw ServiceError.invalidResponse }
if http.statusCode == 401, authenticated, !retried, let requestToken {
let token = try await refreshSession(generation: generation, rejectedToken: requestToken)
guard generation == sessionGeneration else { throw ServiceError.noSession }
return try await send(
to: url,
method: method,
body: body,
contentType: contentType,
retried: true,
proxyService: proxyService,
authorizationToken: token,
classifyModerationWrite: classifyModerationWrite
)
}
try validateResponse(data, http: http, classifyModerationWrite: classifyModerationWrite)
return (data, http)
}
private func authenticate(
_ request: inout URLRequest, authenticated: Bool, authorizationToken: String?,
generation: UUID, classifyModerationWrite: Bool
) async throws -> String? {
var requestToken: String?
if let authorizationToken {
request.setValue("Bearer \(authorizationToken)", forHTTPHeaderField: "Authorization")
} else if authenticated {
let token: String
do { token = try await accessToken() } catch {
if classifyModerationWrite { throw ActionNotSentError(underlying: error) }
throw error
}
guard generation == sessionGeneration else {
if classifyModerationWrite {
throw ModerationWriteError.rejected("The request was not sent. Sign in again.")
}
throw ServiceError.noSession
}
requestToken = token
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
return requestToken
}
private func validateResponse(_ data: Data, http: HTTPURLResponse, classifyModerationWrite: Bool) throws {
guard (200..<300).contains(http.statusCode) else {
let body = (try? JSONDecoder().decode(APIErrorBody.self, from: data))
if classifyModerationWrite, http.statusCode == 400, body?.error == "InvalidRequest" {
throw ModerationWriteError.rejected(body?.message ?? "The server rejected the request.")
}
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)).")
}
}
}