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)).") } } }