IceCubesApp/Packages/Network/Sources/Network/Client.swift

209 lines
8 KiB
Swift
Raw Normal View History

import Foundation
2022-12-01 08:05:26 +00:00
import Models
2023-01-17 10:36:01 +00:00
import SwiftUI
2022-12-20 14:37:51 +00:00
public class Client: ObservableObject, Equatable {
public static func == (lhs: Client, rhs: Client) -> Bool {
lhs.isAuth == rhs.isAuth &&
2023-01-17 10:36:01 +00:00
lhs.server == rhs.server &&
lhs.oauthToken?.accessToken == rhs.oauthToken?.accessToken
2022-12-20 14:37:51 +00:00
}
2023-01-17 10:36:01 +00:00
public enum Version: String {
2022-12-27 06:51:44 +00:00
case v1, v2
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public enum OauthError: Error {
case missingApp
case invalidRedirectURL
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public var server: String
public let version: Version
2023-01-12 17:25:37 +00:00
public private(set) var connections: Set<String>
private let urlSession: URLSession
private let decoder = JSONDecoder()
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
/// Only used as a transitionary app while in the oauth flow.
2022-12-20 15:08:09 +00:00
private var oauthApp: InstanceApp?
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
private var oauthToken: OauthToken?
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public var isAuth: Bool {
oauthToken != nil
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public init(server: String, version: Version = .v1, oauthToken: OauthToken? = nil) {
self.server = server
self.version = version
2023-01-17 10:36:01 +00:00
urlSession = URLSession.shared
decoder.keyDecodingStrategy = .convertFromSnakeCase
2022-12-01 08:05:26 +00:00
self.oauthToken = oauthToken
2023-01-17 10:36:01 +00:00
connections = Set([server])
}
2023-01-17 10:36:01 +00:00
2023-01-12 17:25:37 +00:00
public func addConnections(_ connections: [String]) {
connections.forEach {
self.connections.insert($0)
}
}
2023-01-17 10:36:01 +00:00
2023-01-12 17:25:37 +00:00
public func hasConnection(with url: URL) -> Bool {
guard let host = url.host(percentEncoded: false) else { return false }
return connections.contains(host)
}
2023-01-17 10:36:01 +00:00
2022-12-27 06:51:44 +00:00
private func makeURL(scheme: String = "https", endpoint: Endpoint, forceVersion: Version? = nil) -> URL {
var components = URLComponents()
components.scheme = scheme
components.host = server
2022-12-01 08:05:26 +00:00
if type(of: endpoint) == Oauth.self {
components.path += "/\(endpoint.path())"
} else {
2022-12-27 06:51:44 +00:00
components.path += "/api/\(forceVersion?.rawValue ?? version.rawValue)/\(endpoint.path())"
2022-12-01 08:05:26 +00:00
}
2022-11-25 11:00:01 +00:00
components.queryItems = endpoint.queryItems()
return components.url!
}
2023-01-17 10:36:01 +00:00
private func makeURLRequest(url: URL, endpoint: Endpoint, httpMethod: String) -> URLRequest {
2022-12-01 08:05:26 +00:00
var request = URLRequest(url: url)
request.httpMethod = httpMethod
if let oauthToken {
request.setValue("Bearer \(oauthToken.accessToken)", forHTTPHeaderField: "Authorization")
}
if let json = endpoint.jsonValue {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
do {
let jsonData = try encoder.encode(json)
request.httpBody = jsonData
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
} catch {
print("Client Error encoding JSON: \(error.localizedDescription)")
}
}
2022-12-01 08:05:26 +00:00
return request
}
2023-01-17 10:36:01 +00:00
private func makeGet(endpoint: Endpoint) -> URLRequest {
let url = makeURL(endpoint: endpoint)
return makeURLRequest(url: url, endpoint: endpoint, httpMethod: "GET")
}
2023-01-17 10:36:01 +00:00
2022-12-27 06:51:44 +00:00
public func get<Entity: Decodable>(endpoint: Endpoint, forceVersion: Version? = nil) async throws -> Entity {
try await makeEntityRequest(endpoint: endpoint, method: "GET", forceVersion: forceVersion)
}
2023-01-17 10:36:01 +00:00
public func getWithLink<Entity: Decodable>(endpoint: Endpoint) async throws -> (Entity, LinkHandler?) {
let (data, httpResponse) = try await urlSession.data(for: makeGet(endpoint: endpoint))
var linkHandler: LinkHandler?
if let response = httpResponse as? HTTPURLResponse,
2023-01-17 10:36:01 +00:00
let link = response.allHeaderFields["Link"] as? String
{
linkHandler = .init(rawLink: link)
}
logResponseOnError(httpResponse: httpResponse, data: data)
return (try decoder.decode(Entity.self, from: data), linkHandler)
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public func post<Entity: Decodable>(endpoint: Endpoint) async throws -> Entity {
2022-12-26 07:24:55 +00:00
try await makeEntityRequest(endpoint: endpoint, method: "POST")
}
2023-01-17 10:36:01 +00:00
public func post(endpoint: Endpoint) async throws -> HTTPURLResponse? {
let url = makeURL(endpoint: endpoint)
let request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: "POST")
let (_, httpResponse) = try await urlSession.data(for: request)
return httpResponse as? HTTPURLResponse
}
2023-01-17 10:36:01 +00:00
2023-01-10 07:24:05 +00:00
public func patch(endpoint: Endpoint) async throws -> HTTPURLResponse? {
let url = makeURL(endpoint: endpoint)
let request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: "PATCH")
2023-01-10 07:24:05 +00:00
let (_, httpResponse) = try await urlSession.data(for: request)
return httpResponse as? HTTPURLResponse
}
2023-01-17 10:36:01 +00:00
2022-12-26 07:24:55 +00:00
public func put<Entity: Decodable>(endpoint: Endpoint) async throws -> Entity {
try await makeEntityRequest(endpoint: endpoint, method: "PUT")
2022-12-01 08:05:26 +00:00
}
2023-01-17 10:36:01 +00:00
public func delete(endpoint: Endpoint) async throws -> HTTPURLResponse? {
let url = makeURL(endpoint: endpoint)
let request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: "DELETE")
let (_, httpResponse) = try await urlSession.data(for: request)
return httpResponse as? HTTPURLResponse
}
2023-01-17 10:36:01 +00:00
2022-12-27 06:51:44 +00:00
private func makeEntityRequest<Entity: Decodable>(endpoint: Endpoint,
method: String,
2023-01-17 10:36:01 +00:00
forceVersion: Version? = nil) async throws -> Entity
{
2022-12-27 06:51:44 +00:00
let url = makeURL(endpoint: endpoint, forceVersion: forceVersion)
let request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: method)
2022-12-26 07:24:55 +00:00
let (data, httpResponse) = try await urlSession.data(for: request)
logResponseOnError(httpResponse: httpResponse, data: data)
return try decoder.decode(Entity.self, from: data)
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public func oauthURL() async throws -> URL {
2022-12-20 15:08:09 +00:00
let app: InstanceApp = try await post(endpoint: Apps.registerApp)
2023-01-17 10:36:01 +00:00
oauthApp = app
2022-12-01 08:05:26 +00:00
return makeURL(endpoint: Oauth.authorize(clientId: app.clientId))
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
public func continueOauthFlow(url: URL) async throws -> OauthToken {
guard let app = oauthApp else {
throw OauthError.missingApp
}
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
2023-01-17 10:36:01 +00:00
let code = components.queryItems?.first(where: { $0.name == "code" })?.value
else {
2022-12-01 08:05:26 +00:00
throw OauthError.invalidRedirectURL
}
let token: OauthToken = try await post(endpoint: Oauth.token(code: code,
clientId: app.clientId,
clientSecret: app.clientSecret))
2023-01-17 10:36:01 +00:00
oauthToken = token
2022-12-01 08:05:26 +00:00
return token
}
2023-01-17 10:36:01 +00:00
public func makeWebSocketTask(endpoint: Endpoint) -> URLSessionWebSocketTask {
let url = makeURL(scheme: "wss", endpoint: endpoint)
let request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: "GET")
return urlSession.webSocketTask(with: request)
}
2023-01-17 10:36:01 +00:00
public func mediaUpload<Entity: Decodable>(endpoint: Endpoint,
version: Version,
method: String,
mimeType: String,
filename: String,
2023-01-17 10:36:01 +00:00
data: Data) async throws -> Entity
{
let url = makeURL(endpoint: endpoint, forceVersion: version)
var request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: method)
2022-12-27 15:16:25 +00:00
let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let httpBody = NSMutableData()
httpBody.append("--\(boundary)\r\n".data(using: .utf8)!)
httpBody.append("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"file.jpg\"\r\n".data(using: .utf8)!)
2022-12-27 15:16:25 +00:00
httpBody.append("Content-Type: \(mimeType)\r\n".data(using: .utf8)!)
httpBody.append("\r\n".data(using: .utf8)!)
httpBody.append(data)
httpBody.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
request.httpBody = httpBody as Data
let (data, httpResponse) = try await urlSession.data(for: request)
logResponseOnError(httpResponse: httpResponse, data: data)
return try decoder.decode(Entity.self, from: data)
2022-12-27 15:16:25 +00:00
}
2023-01-17 10:36:01 +00:00
2022-12-01 08:05:26 +00:00
private func logResponseOnError(httpResponse: URLResponse, data: Data) {
if let httpResponse = httpResponse as? HTTPURLResponse, httpResponse.statusCode > 299 {
print(httpResponse)
print(String(data: data, encoding: .utf8) ?? "")
}
}
}