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( 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) } }