Use versioned API client for server summary

This commit is contained in:
Micha
2025-11-16 12:59:05 +01:00
parent d818af18bb
commit df32af064d
7 changed files with 233 additions and 13 deletions

View File

@@ -33,6 +33,7 @@ protocol AnyServerAPI {
func fetchLoadData() async throws -> Any
func fetchMemoryData() async throws -> Any
func fetchUtilizationData() async throws -> Any
func fetchServerSummary(apiKey: String) async throws -> ServerInfo
}
private struct AnyServerAPIWrapper<T: ServerAPIProtocol>: AnyServerAPI {
@@ -57,6 +58,10 @@ private struct AnyServerAPIWrapper<T: ServerAPIProtocol>: AnyServerAPI {
func fetchUtilizationData() async throws -> Any {
return try await wrapped.fetchUtilization()
}
func fetchServerSummary(apiKey: String) async throws -> ServerInfo {
return try await wrapped.fetchServerSummary(apiKey: apiKey)
}
}
class APIFactory {

View File

@@ -17,6 +17,7 @@ protocol ServerAPIProtocol {
func fetchLoad() async throws -> LoadType
func fetchMemory() async throws -> MemoryType
func fetchUtilization() async throws -> UtilizationType
func fetchServerSummary(apiKey: String) async throws -> ServerInfo
}
struct SystemInfo: Codable {

View File

@@ -0,0 +1,34 @@
import Foundation
enum PingService {
static func ping(hostname: String, apiKey: String) async -> Bool {
guard let url = URL(string: "https://\(hostname)/api/v2/ping") else {
print("❌ [PingService] Invalid URL for \(hostname)")
return false
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(apiKey, forHTTPHeaderField: "X-API-KEY")
request.timeoutInterval = 10
do {
let (data, response) = try await URLSession.shared.data(for: request)
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
if let responseString = String(data: data, encoding: .utf8) {
print("❌ [PingService] HTTP \(httpResponse.statusCode): \(responseString)")
}
return false
}
if let result = try? JSONDecoder().decode([String: String].self, from: data), result["response"] == "pong" {
return true
} else {
return false
}
} catch {
print("❌ [PingService] Error pinging \(hostname): \(error)")
return false
}
}
}

View File

@@ -167,4 +167,172 @@ class APIv2_12: BaseAPIClient, ServerAPIProtocol {
request.setValue("application/json", forHTTPHeaderField: "Accept")
return try await performRequest(request, responseType: UtilizationType.self)
}
func fetchServerSummary(apiKey: String) async throws -> ServerInfo {
let summaryURL = baseURL.appendingPathComponent("api/v2/server")
var request = URLRequest(url: summaryURL)
request.httpMethod = "GET"
request.setValue(apiKey, forHTTPHeaderField: "X-API-KEY")
request.timeoutInterval = 30
let (data, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
guard httpResponse.statusCode == 200 else {
throw APIError.httpError(httpResponse.statusCode)
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let envelope = try decoder.decode(ServerSummaryEnvelope.self, from: data)
return envelope.toDomain()
}
}
// MARK: - Server Summary Mapping
private extension APIv2_12 {
struct ServerSummaryEnvelope: Decodable {
let meta: Meta
let utilization: Utilization
let components: Components
let ports: [Port]?
let additionalPhpInterpreters: [AdditionalInterpreter]?
struct Meta: Decodable {
struct Uptime: Decodable {
let days: Int
let hours: Int
let minutes: Int
let seconds: Int
var formatted: String {
"\(days) Days / \(hours) Hours / \(minutes) Minutes / \(seconds) Seconds"
}
}
let hostname: String
let ipAddresses: [String]
let serverTime: String
let uptime: Uptime
let panelVersion: String
let panelBuild: Int
let apiVersion: String
}
struct Utilization: Decodable {
struct Load: Decodable {
let minute1: Double
let minute5: Double
let minute15: Double
let cpuCount: Int
let percent: Double
let level: String
}
struct Memory: Decodable {
let free: Int
let used: Int
let total: Int
let percent: Double
}
struct Disk: Decodable {
let free: Int
let used: Int
let total: Int
let percent: Double
}
let processCount: Int
let load: Load
let diskSpace: Disk
let memory: Memory
let swap: Memory
}
struct Components: Decodable {
let apache: String
let php: String
let mysql: String?
let mariadb: String?
}
struct Port: Decodable {
let service: String
let status: String
let port: Int
let proto: String
}
struct AdditionalInterpreter: Decodable {
let version: String
let path: String?
let configFile: String?
}
func toDomain() -> ServerInfo {
let load = utilization.load
let disk = utilization.diskSpace
let memory = utilization.memory
let swapMemory = utilization.swap
return ServerInfo(
hostname: meta.hostname,
ipAddresses: meta.ipAddresses,
cpuCores: load.cpuCount,
serverTime: meta.serverTime,
uptime: meta.uptime.formatted,
processCount: utilization.processCount,
apacheVersion: components.apache,
phpVersion: components.php,
mysqlVersion: components.mysql,
mariadbVersion: components.mariadb,
ports: ports?.map {
ServerInfo.ServicePort(service: $0.service, status: $0.status, port: $0.port, proto: $0.proto)
},
load: ServerInfo.Load(
minute1: load.minute1,
minute5: load.minute5,
minute15: load.minute15,
percent: load.percent,
cpuCount: load.cpuCount,
level: load.level
),
memory: ServerInfo.Memory(
free: memory.free,
used: memory.used,
total: memory.total,
percent: memory.percent
),
swap: ServerInfo.Memory(
free: swapMemory.free,
used: swapMemory.used,
total: swapMemory.total,
percent: swapMemory.percent
),
diskSpace: ServerInfo.DiskSpace(
free: disk.free,
used: disk.used,
total: disk.total,
percent: disk.percent
),
panelVersion: meta.panelVersion,
panelBuild: String(meta.panelBuild),
apiVersion: meta.apiVersion,
additionalPHPInterpreters: additionalPhpInterpreters?.map {
ServerInfo.PHPInterpreter(
version: $0.version,
path: $0.path,
configFile: $0.configFile,
extensions: [],
memoryLimit: nil,
maxExecutionTime: nil
)
}
)
}
}
}