Compare commits
4 Commits
4efe1a2324
...
562023519a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
562023519a | ||
|
|
c9ebc22551 | ||
|
|
01c8da07e0 | ||
|
|
d3f9126245 |
@@ -9,7 +9,7 @@ import Foundation
|
||||
import Security
|
||||
|
||||
enum KeychainHelper {
|
||||
static func save(apiKey: String, for hostname: String) {
|
||||
static func saveApiKey(_ apiKey: String, for hostname: String) {
|
||||
let data = Data(apiKey.utf8)
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
|
||||
@@ -9,6 +9,7 @@ import Foundation
|
||||
|
||||
enum APIVersion: String, CaseIterable {
|
||||
case v2_12 = "2.12"
|
||||
case v2_13 = "2.13"
|
||||
|
||||
static func from(versionString: String) -> APIVersion? {
|
||||
if let version = APIVersion(rawValue: versionString) {
|
||||
@@ -22,7 +23,8 @@ enum APIVersion: String, CaseIterable {
|
||||
let minor = components[1]
|
||||
|
||||
switch (major, minor) {
|
||||
case (2, 12...): return .v2_12
|
||||
case (2, 12): return .v2_12
|
||||
case (2, 13...): return .v2_13
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
@@ -69,6 +71,8 @@ class APIFactory {
|
||||
switch version {
|
||||
case .v2_12:
|
||||
return AnyServerAPIWrapper(APIv2_12(baseURL: baseURL))
|
||||
case .v2_13:
|
||||
return AnyServerAPIWrapper(APIv2_13(baseURL: baseURL))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +104,7 @@ class APIFactory {
|
||||
}
|
||||
}
|
||||
|
||||
return AnyServerAPIWrapper(APIv2_12(baseURL: baseURL))
|
||||
return AnyServerAPIWrapper(APIv2_13(baseURL: baseURL))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
//
|
||||
// ServerAPI.swift
|
||||
// iKeyMon
|
||||
//
|
||||
// Created by tracer on 06.04.25.
|
||||
//
|
||||
import Foundation
|
||||
|
||||
final class ServerAPI {
|
||||
private let hostname: String
|
||||
private let apiKey: String
|
||||
|
||||
init(hostname: String, apiKey: String) {
|
||||
self.hostname = hostname
|
||||
self.apiKey = apiKey
|
||||
}
|
||||
|
||||
init?(server: Server) {
|
||||
guard let apiKey = KeychainHelper.loadApiKey(for: server.hostname)?.trimmingCharacters(in: .whitespacesAndNewlines) else {
|
||||
return nil
|
||||
}
|
||||
self.hostname = server.hostname
|
||||
self.apiKey = apiKey
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func ping() async -> Bool {
|
||||
guard let url = URL(string: "https://\(hostname)/api/v2/ping") else {
|
||||
print("❌ [ServerAPI] Invalid ping URL for hostname: \(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)
|
||||
|
||||
// Add debug info for comparison with server info request
|
||||
if let httpResponse = response as? HTTPURLResponse {
|
||||
if httpResponse.statusCode != 200 {
|
||||
print("❌ [ServerAPI] Ping HTTP Status: \(httpResponse.statusCode) for \(hostname)")
|
||||
if let responseString = String(data: data, encoding: .utf8) {
|
||||
print("❌ [ServerAPI] Ping error response: \(responseString)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let result = try? JSONDecoder().decode([String: String].self, from: data), result["response"] == "pong" {
|
||||
return true
|
||||
} else {
|
||||
print("❌ [ServerAPI] Ping failed - invalid response for \(hostname)")
|
||||
if let responseString = String(data: data, encoding: .utf8) {
|
||||
print("❌ [ServerAPI] Ping response: \(responseString)")
|
||||
}
|
||||
return false
|
||||
}
|
||||
} catch {
|
||||
print("❌ [ServerAPI] Ping error for \(hostname): \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func fetchServerInfo() async throws -> ServerInfo {
|
||||
print("🔍 [ServerAPI] Starting fetchServerInfo for hostname: \(hostname)")
|
||||
|
||||
guard let url = URL(string: "https://\(hostname)/api/v2/server") else {
|
||||
print("❌ [ServerAPI] Invalid URL for hostname: \(hostname)")
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
|
||||
print("🌐 [ServerAPI] URL created: \(url.absoluteString)")
|
||||
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = "GET"
|
||||
request.setValue(apiKey, forHTTPHeaderField: "X-API-KEY")
|
||||
// Temporarily remove Content-Type to match ping request exactly
|
||||
// request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
request.timeoutInterval = 30
|
||||
|
||||
print("📤 [ServerAPI] Making request with timeout: \(request.timeoutInterval)s")
|
||||
print("📤 [ServerAPI] API Key (first 10 chars): \(String(apiKey.prefix(10)))...")
|
||||
print("📤 [ServerAPI] Request headers: \(request.allHTTPHeaderFields ?? [:])")
|
||||
|
||||
do {
|
||||
let startTime = Date()
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
let endTime = Date()
|
||||
let duration = endTime.timeIntervalSince(startTime)
|
||||
|
||||
print("📥 [ServerAPI] Request completed in \(String(format: "%.2f", duration))s")
|
||||
|
||||
if let httpResponse = response as? HTTPURLResponse {
|
||||
print("📥 [ServerAPI] HTTP Status: \(httpResponse.statusCode)")
|
||||
|
||||
// Handle 401 specifically
|
||||
if httpResponse.statusCode == 401 {
|
||||
print("❌ [ServerAPI] 401 Unauthorized - API key issue!")
|
||||
if let responseString = String(data: data, encoding: .utf8) {
|
||||
print("❌ [ServerAPI] 401 Response body: \(responseString)")
|
||||
}
|
||||
throw URLError(.userAuthenticationRequired)
|
||||
}
|
||||
|
||||
// Handle other non-200 status codes
|
||||
if httpResponse.statusCode != 200 {
|
||||
print("❌ [ServerAPI] Non-200 status code: \(httpResponse.statusCode)")
|
||||
if let responseString = String(data: data, encoding: .utf8) {
|
||||
print("❌ [ServerAPI] Error response body: \(responseString)")
|
||||
}
|
||||
throw URLError(.badServerResponse)
|
||||
}
|
||||
}
|
||||
|
||||
print("📥 [ServerAPI] Data size: \(data.count) bytes")
|
||||
|
||||
print("🔄 [ServerAPI] Decoding response payload...")
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
||||
let decodedResponse = try decoder.decode(ServerResponseEnvelope.self, from: data)
|
||||
let decoded = decodedResponse.toDomain()
|
||||
print("✅ [ServerAPI] JSON decoding successful")
|
||||
|
||||
return decoded
|
||||
} catch let urlError as URLError {
|
||||
print("❌ [ServerAPI] URLError: \(urlError.localizedDescription)")
|
||||
print("❌ [ServerAPI] URLError code: \(urlError.code.rawValue)")
|
||||
throw urlError
|
||||
} catch let decodingError as DecodingError {
|
||||
print("❌ [ServerAPI] Decoding error: \(decodingError)")
|
||||
throw decodingError
|
||||
} catch {
|
||||
print("❌ [ServerAPI] Unexpected error: \(error)")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Response Helpers
|
||||
|
||||
private extension ServerAPI {
|
||||
struct ServerResponseEnvelope: Decodable {
|
||||
let data: ServerData
|
||||
let meta: Meta
|
||||
|
||||
struct Meta: Decodable {
|
||||
let apiVersion: String
|
||||
}
|
||||
}
|
||||
|
||||
struct ServerData: Decodable {
|
||||
struct Port: Decodable {
|
||||
let service: String
|
||||
let status: String
|
||||
let port: Int
|
||||
let proto: String
|
||||
}
|
||||
|
||||
struct Load: Decodable {
|
||||
let minute1: Double
|
||||
let minute5: Double
|
||||
let minute15: Double
|
||||
let percent: Double
|
||||
let cpuCount: Int
|
||||
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
|
||||
}
|
||||
|
||||
struct PHPInterpreter: Decodable {
|
||||
let version: String
|
||||
let path: String?
|
||||
let configFile: String?
|
||||
let extensions: [String]
|
||||
let memoryLimit: String?
|
||||
let maxExecutionTime: String?
|
||||
}
|
||||
|
||||
let hostname: String
|
||||
let ipAddresses: [String]
|
||||
let cpuCores: Int
|
||||
let serverTime: String
|
||||
let uptime: String
|
||||
let processCount: Int
|
||||
let apacheVersion: String
|
||||
let phpVersion: String
|
||||
let mysqlVersion: String?
|
||||
let mariadbVersion: String?
|
||||
let ports: [Port]?
|
||||
let load: Load
|
||||
let memory: Memory
|
||||
let swap: Memory
|
||||
let diskSpace: Disk
|
||||
let panelVersion: String
|
||||
let panelBuild: String
|
||||
let additionalPhpInterpreters: [PHPInterpreter]?
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private extension ServerAPI.ServerResponseEnvelope {
|
||||
func toDomain() -> ServerInfo {
|
||||
ServerInfo(
|
||||
hostname: data.hostname,
|
||||
ipAddresses: data.ipAddresses,
|
||||
cpuCores: data.cpuCores,
|
||||
serverTime: data.serverTime,
|
||||
uptime: data.uptime,
|
||||
processCount: data.processCount,
|
||||
apacheVersion: data.apacheVersion,
|
||||
phpVersion: data.phpVersion,
|
||||
mysqlVersion: data.mysqlVersion,
|
||||
mariadbVersion: data.mariadbVersion,
|
||||
ports: data.ports?.map { ServerInfo.ServicePort(service: $0.service, status: $0.status, port: $0.port, proto: $0.proto) },
|
||||
load: ServerInfo.Load(
|
||||
minute1: data.load.minute1,
|
||||
minute5: data.load.minute5,
|
||||
minute15: data.load.minute15,
|
||||
percent: data.load.percent,
|
||||
cpuCount: data.load.cpuCount,
|
||||
level: data.load.level
|
||||
),
|
||||
memory: ServerInfo.Memory(
|
||||
free: data.memory.free,
|
||||
used: data.memory.used,
|
||||
total: data.memory.total,
|
||||
percent: data.memory.percent
|
||||
),
|
||||
swap: ServerInfo.Memory(
|
||||
free: data.swap.free,
|
||||
used: data.swap.used,
|
||||
total: data.swap.total,
|
||||
percent: data.swap.percent
|
||||
),
|
||||
diskSpace: ServerInfo.DiskSpace(
|
||||
free: data.diskSpace.free,
|
||||
used: data.diskSpace.used,
|
||||
total: data.diskSpace.total,
|
||||
percent: data.diskSpace.percent
|
||||
),
|
||||
panelVersion: data.panelVersion,
|
||||
panelBuild: data.panelBuild,
|
||||
apiVersion: meta.apiVersion,
|
||||
additionalPHPInterpreters: data.additionalPhpInterpreters?.map {
|
||||
ServerInfo.PHPInterpreter(
|
||||
version: $0.version,
|
||||
path: $0.path,
|
||||
configFile: $0.configFile,
|
||||
extensions: $0.extensions,
|
||||
memoryLimit: $0.memoryLimit,
|
||||
maxExecutionTime: $0.maxExecutionTime
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -145,6 +145,7 @@ struct ServerInfo: Codable, Hashable, Equatable {
|
||||
var phpVersion: String
|
||||
var mysqlVersion: String?
|
||||
var mariadbVersion: String?
|
||||
var emailsInQueue: Int?
|
||||
var operatingSystem: OperatingSystem?
|
||||
var ports: [ServicePort]?
|
||||
var load: Load
|
||||
@@ -204,6 +205,7 @@ extension ServerInfo {
|
||||
phpVersion: "8.2.12",
|
||||
mysqlVersion: "8.0.33",
|
||||
mariadbVersion: nil,
|
||||
emailsInQueue: 0,
|
||||
operatingSystem: OperatingSystem(
|
||||
label: "Debian 12.12 (64-bit)",
|
||||
distribution: "Debian",
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
//
|
||||
// ServerTypes_Fixed.swift
|
||||
// iKeyMon
|
||||
//
|
||||
// Fixed server types matching your existing code structure
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Server API Response Types
|
||||
struct ServerAPIResponse<T: Codable>: Codable {
|
||||
let data: T
|
||||
let status: String
|
||||
let timestamp: Date
|
||||
let version: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case data
|
||||
case status
|
||||
case timestamp
|
||||
case version
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Server API Version
|
||||
struct ServerAPIVersion: Codable {
|
||||
let major: Int
|
||||
let minor: Int
|
||||
let patch: Int
|
||||
let string: String
|
||||
|
||||
init(major: Int, minor: Int, patch: Int = 0) {
|
||||
self.major = major
|
||||
self.minor = minor
|
||||
self.patch = patch
|
||||
self.string = "\(major).\(minor).\(patch)"
|
||||
}
|
||||
|
||||
init(from versionString: String) throws {
|
||||
let components = versionString.split(separator: ".").compactMap { Int($0) }
|
||||
guard components.count >= 2 else {
|
||||
throw DecodingError.dataCorrupted(
|
||||
DecodingError.Context(codingPath: [], debugDescription: "Invalid version string format")
|
||||
)
|
||||
}
|
||||
|
||||
self.major = components[0]
|
||||
self.minor = components[1]
|
||||
self.patch = components.count > 2 ? components[2] : 0
|
||||
self.string = versionString
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Server API Response Factory
|
||||
class ServerAPIResponseFactory {
|
||||
static func createResponse<T: Codable>(data: T, status: String = "success") -> ServerAPIResponse<T> {
|
||||
return ServerAPIResponse(
|
||||
data: data,
|
||||
status: status,
|
||||
timestamp: Date(),
|
||||
version: "1.0"
|
||||
)
|
||||
}
|
||||
|
||||
static func createErrorResponse(error: String) -> ServerAPIResponse<String> {
|
||||
return ServerAPIResponse(
|
||||
data: error,
|
||||
status: "error",
|
||||
timestamp: Date(),
|
||||
version: "1.0"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -131,10 +131,10 @@ class APIv2_12: BaseAPIClient, ServerAPIProtocol {
|
||||
typealias UtilizationType = APIv2_12.Utilization
|
||||
|
||||
private enum Endpoint: String {
|
||||
case systemInfo = "/api/v2.12/system/info"
|
||||
case load = "/api/v2.12/metrics/load"
|
||||
case memory = "/api/v2.12/metrics/memory"
|
||||
case utilization = "/api/v2.12/metrics/utilization"
|
||||
case systemInfo = "/api/v2/system/info"
|
||||
case load = "/api/v2/metrics/load"
|
||||
case memory = "/api/v2/metrics/memory"
|
||||
case utilization = "/api/v2/metrics/utilization"
|
||||
|
||||
func url(baseURL: URL) -> URL {
|
||||
return baseURL.appendingPathComponent(self.rawValue)
|
||||
@@ -248,6 +248,7 @@ private extension APIv2_12 {
|
||||
}
|
||||
|
||||
let processCount: Int
|
||||
let emailsInQueue: Int?
|
||||
let load: Load
|
||||
let diskSpace: Disk
|
||||
let memory: Memory
|
||||
@@ -292,6 +293,13 @@ private extension APIv2_12 {
|
||||
case securityUpdateCount = "security_update_count"
|
||||
case rebootRequired = "reboot_required"
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
updateCount = try container.decodeIfPresent(Int.self, forKey: .updateCount) ?? 0
|
||||
securityUpdateCount = try container.decodeIfPresent(Int.self, forKey: .securityUpdateCount) ?? 0
|
||||
rebootRequired = try container.decodeIfPresent(Bool.self, forKey: .rebootRequired) ?? false
|
||||
}
|
||||
}
|
||||
|
||||
let label: String
|
||||
@@ -309,6 +317,16 @@ private extension APIv2_12 {
|
||||
case endOfLife = "end_of_life"
|
||||
case updates
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
label = try container.decodeIfPresent(String.self, forKey: .label) ?? ""
|
||||
distribution = try container.decodeIfPresent(String.self, forKey: .distribution) ?? ""
|
||||
version = try container.decodeIfPresent(String.self, forKey: .version) ?? ""
|
||||
architecture = try container.decodeIfPresent(String.self, forKey: .architecture) ?? ""
|
||||
endOfLife = try container.decodeIfPresent(Bool.self, forKey: .endOfLife) ?? false
|
||||
updates = try container.decodeIfPresent(Updates.self, forKey: .updates)
|
||||
}
|
||||
}
|
||||
|
||||
func toDomain() -> ServerInfo {
|
||||
@@ -328,6 +346,7 @@ private extension APIv2_12 {
|
||||
phpVersion: components.php,
|
||||
mysqlVersion: components.mysql,
|
||||
mariadbVersion: components.mariadb,
|
||||
emailsInQueue: utilization.emailsInQueue,
|
||||
operatingSystem: operatingSystem.map {
|
||||
ServerInfo.OperatingSystem(
|
||||
label: $0.label,
|
||||
|
||||
411
Sources/Model/API/Versions/APIv2_13.swift
Normal file
411
Sources/Model/API/Versions/APIv2_13.swift
Normal file
@@ -0,0 +1,411 @@
|
||||
//
|
||||
// APIv2_13.swift
|
||||
// iKeyMon
|
||||
//
|
||||
// Created by tracer on 13.11.25.
|
||||
//
|
||||
|
||||
|
||||
import Foundation
|
||||
|
||||
extension APIv2_13 {
|
||||
struct Load: Codable {
|
||||
let current: LoadMetrics
|
||||
let historical: [LoadMetrics]
|
||||
|
||||
struct LoadMetrics: Codable {
|
||||
let oneMinute: Double
|
||||
let fiveMinute: Double
|
||||
let fifteenMinute: Double
|
||||
let timestamp: Date
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case oneMinute = "load_1"
|
||||
case fiveMinute = "load_5"
|
||||
case fifteenMinute = "load_15"
|
||||
case timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Memory: Codable {
|
||||
let system: SystemMemory
|
||||
let swap: SwapMemory?
|
||||
|
||||
struct SystemMemory: Codable {
|
||||
let total: Int64
|
||||
let used: Int64
|
||||
let free: Int64
|
||||
let available: Int64
|
||||
let buffers: Int64?
|
||||
let cached: Int64?
|
||||
}
|
||||
|
||||
struct SwapMemory: Codable {
|
||||
let total: Int64
|
||||
let used: Int64
|
||||
let free: Int64
|
||||
}
|
||||
}
|
||||
|
||||
struct Utilization: Codable {
|
||||
let cpu: CPUUtilization
|
||||
let memory: MemoryUtilization
|
||||
let disk: [DiskUtilization]
|
||||
let network: [NetworkUtilization]?
|
||||
|
||||
struct CPUUtilization: Codable {
|
||||
let overall: Double
|
||||
let cores: [Double]
|
||||
let processes: [ProcessInfo]?
|
||||
|
||||
struct ProcessInfo: Codable {
|
||||
let pid: Int
|
||||
let name: String
|
||||
let cpuPercent: Double
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case pid
|
||||
case name
|
||||
case cpuPercent = "cpu_percent"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MemoryUtilization: Codable {
|
||||
let percent: Double
|
||||
let topProcesses: [ProcessMemoryInfo]?
|
||||
|
||||
struct ProcessMemoryInfo: Codable {
|
||||
let pid: Int
|
||||
let name: String
|
||||
let memoryMB: Double
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case pid
|
||||
case name
|
||||
case memoryMB = "memory_mb"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskUtilization: Codable {
|
||||
let device: String
|
||||
let mountpoint: String
|
||||
let usedPercent: Double
|
||||
let totalBytes: Int64
|
||||
let usedBytes: Int64
|
||||
let freeBytes: Int64
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case device
|
||||
case mountpoint
|
||||
case usedPercent = "used_percent"
|
||||
case totalBytes = "total_bytes"
|
||||
case usedBytes = "used_bytes"
|
||||
case freeBytes = "free_bytes"
|
||||
}
|
||||
}
|
||||
|
||||
struct NetworkUtilization: Codable {
|
||||
let interface: String
|
||||
let bytesIn: Int64
|
||||
let bytesOut: Int64
|
||||
let packetsIn: Int64
|
||||
let packetsOut: Int64
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case interface
|
||||
case bytesIn = "bytes_in"
|
||||
case bytesOut = "bytes_out"
|
||||
case packetsIn = "packets_in"
|
||||
case packetsOut = "packets_out"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class APIv2_13: BaseAPIClient, ServerAPIProtocol {
|
||||
typealias LoadType = APIv2_13.Load
|
||||
typealias MemoryType = APIv2_13.Memory
|
||||
typealias UtilizationType = APIv2_13.Utilization
|
||||
|
||||
private enum Endpoint: String {
|
||||
case systemInfo = "/api/v2/system/info"
|
||||
case load = "/api/v2/metrics/load"
|
||||
case memory = "/api/v2/metrics/memory"
|
||||
case utilization = "/api/v2/metrics/utilization"
|
||||
|
||||
func url(baseURL: URL) -> URL {
|
||||
return baseURL.appendingPathComponent(self.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
func fetchSystemInfo() async throws -> SystemInfo {
|
||||
let url = Endpoint.systemInfo.url(baseURL: baseURL)
|
||||
let request = URLRequest(url: url)
|
||||
return try await performRequest(request, responseType: SystemInfo.self)
|
||||
}
|
||||
|
||||
func fetchLoad() async throws -> LoadType {
|
||||
let url = Endpoint.load.url(baseURL: baseURL)
|
||||
var request = URLRequest(url: url)
|
||||
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
return try await performRequest(request, responseType: LoadType.self)
|
||||
}
|
||||
|
||||
func fetchMemory() async throws -> MemoryType {
|
||||
let url = Endpoint.memory.url(baseURL: baseURL)
|
||||
var request = URLRequest(url: url)
|
||||
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
return try await performRequest(request, responseType: MemoryType.self)
|
||||
}
|
||||
|
||||
func fetchUtilization() async throws -> UtilizationType {
|
||||
let url = Endpoint.utilization.url(baseURL: baseURL)
|
||||
var request = URLRequest(url: url)
|
||||
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_13 {
|
||||
struct ServerSummaryEnvelope: Decodable {
|
||||
let meta: Meta
|
||||
let operatingSystem: OperatingSystem?
|
||||
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 emailsInQueue: 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
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case service
|
||||
case status
|
||||
case port
|
||||
case proto = "protocol"
|
||||
}
|
||||
}
|
||||
|
||||
struct AdditionalInterpreter: Decodable {
|
||||
let version: String
|
||||
let path: String?
|
||||
let configFile: String?
|
||||
}
|
||||
|
||||
struct OperatingSystem: Decodable {
|
||||
struct Updates: Decodable {
|
||||
let updateCount: Int
|
||||
let securityUpdateCount: Int
|
||||
let rebootRequired: Bool
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case updateCount = "update_count"
|
||||
case securityUpdateCount = "security_update_count"
|
||||
case rebootRequired = "reboot_required"
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
updateCount = try container.decodeIfPresent(Int.self, forKey: .updateCount) ?? 0
|
||||
securityUpdateCount = try container.decodeIfPresent(Int.self, forKey: .securityUpdateCount) ?? 0
|
||||
rebootRequired = try container.decodeIfPresent(Bool.self, forKey: .rebootRequired) ?? false
|
||||
}
|
||||
}
|
||||
|
||||
let label: String
|
||||
let distribution: String
|
||||
let version: String
|
||||
let architecture: String
|
||||
let endOfLife: Bool
|
||||
let updates: Updates?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case label
|
||||
case distribution
|
||||
case version
|
||||
case architecture
|
||||
case endOfLife = "end_of_life"
|
||||
case updates
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
label = try container.decodeIfPresent(String.self, forKey: .label) ?? ""
|
||||
distribution = try container.decodeIfPresent(String.self, forKey: .distribution) ?? ""
|
||||
version = try container.decodeIfPresent(String.self, forKey: .version) ?? ""
|
||||
architecture = try container.decodeIfPresent(String.self, forKey: .architecture) ?? ""
|
||||
endOfLife = try container.decodeIfPresent(Bool.self, forKey: .endOfLife) ?? false
|
||||
updates = try container.decodeIfPresent(Updates.self, forKey: .updates)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
emailsInQueue: utilization.emailsInQueue,
|
||||
operatingSystem: operatingSystem.map {
|
||||
ServerInfo.OperatingSystem(
|
||||
label: $0.label,
|
||||
distribution: $0.distribution,
|
||||
version: $0.version,
|
||||
architecture: $0.architecture,
|
||||
endOfLife: $0.endOfLife,
|
||||
updates: $0.updates.map {
|
||||
ServerInfo.OperatingSystem.UpdateStatus(
|
||||
updateCount: $0.updateCount,
|
||||
securityUpdateCount: $0.securityUpdateCount,
|
||||
rebootRequired: $0.rebootRequired
|
||||
)
|
||||
}
|
||||
)
|
||||
},
|
||||
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
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,9 +28,10 @@ struct PreferencesView: View {
|
||||
@State private var pingIntervalSlider: Double = 10
|
||||
@State private var refreshIntervalSlider: Double = 60
|
||||
@State private var selection: Tab = .monitor
|
||||
@State private var hoveredTab: Tab?
|
||||
|
||||
private let minimumInterval: Double = 10
|
||||
private let maximumPingInterval: Double = 600
|
||||
private let maximumPingInterval: Double = 60
|
||||
private let maximumRefreshInterval: Double = 600
|
||||
|
||||
var body: some View {
|
||||
@@ -74,13 +75,20 @@ struct PreferencesView: View {
|
||||
Spacer()
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
.padding(.horizontal, 6)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 10, style: .continuous)
|
||||
.fill(selection == tab ? Color.accentColor.opacity(0.25) : Color.clear)
|
||||
)
|
||||
.padding(.horizontal, 10)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.focusable(false)
|
||||
.contentShape(Capsule())
|
||||
.background(
|
||||
Capsule(style: .continuous)
|
||||
.fill(backgroundColor(for: tab))
|
||||
)
|
||||
.foregroundColor(selection == tab ? .white : .primary)
|
||||
.onHover { isHovering in
|
||||
hoveredTab = isHovering ? tab : (hoveredTab == tab ? nil : hoveredTab)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer()
|
||||
@@ -127,6 +135,15 @@ struct PreferencesView: View {
|
||||
storedRefreshInterval = Int(refreshIntervalSlider)
|
||||
}
|
||||
}
|
||||
private func backgroundColor(for tab: Tab) -> Color {
|
||||
if selection == tab {
|
||||
return Color.accentColor
|
||||
}
|
||||
if hoveredTab == tab {
|
||||
return Color.accentColor.opacity(0.2)
|
||||
}
|
||||
return Color.accentColor.opacity(0.08)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MonitorPreferencesView: View {
|
||||
@@ -141,56 +158,20 @@ private struct MonitorPreferencesView: View {
|
||||
let refreshChanged: (Bool) -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Group {
|
||||
Text("Ping interval")
|
||||
.font(.headline)
|
||||
Slider(
|
||||
VStack(alignment: .leading, spacing: 24) {
|
||||
intervalSection(
|
||||
title: "Ping interval",
|
||||
value: $pingIntervalSlider,
|
||||
in: minimumInterval...maximumPingInterval,
|
||||
step: 5
|
||||
) {
|
||||
Text("Ping interval")
|
||||
} minimumValueLabel: {
|
||||
Text("\(Int(minimumInterval))s")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
} maximumValueLabel: {
|
||||
Text("\(Int(maximumPingInterval))s")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
} onEditingChanged: { editing in
|
||||
pingChanged(editing)
|
||||
}
|
||||
Text("Current: \(Int(pingIntervalSlider)) seconds")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
range: minimumInterval...maximumPingInterval,
|
||||
onEditingChanged: pingChanged
|
||||
)
|
||||
|
||||
Group {
|
||||
Text("Refresh interval")
|
||||
.font(.headline)
|
||||
Slider(
|
||||
intervalSection(
|
||||
title: "Refresh interval",
|
||||
value: $refreshIntervalSlider,
|
||||
in: minimumInterval...maximumRefreshInterval,
|
||||
step: 5
|
||||
) {
|
||||
Text("Refresh interval")
|
||||
} minimumValueLabel: {
|
||||
Text("\(Int(minimumInterval))s")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
} maximumValueLabel: {
|
||||
Text("\(Int(maximumRefreshInterval))s")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
} onEditingChanged: { editing in
|
||||
refreshChanged(editing)
|
||||
}
|
||||
Text("Current: \(Int(refreshIntervalSlider)) seconds")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
range: minimumInterval...maximumRefreshInterval,
|
||||
onEditingChanged: refreshChanged
|
||||
)
|
||||
|
||||
Divider()
|
||||
|
||||
@@ -201,6 +182,42 @@ private struct MonitorPreferencesView: View {
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
private func intervalSection(
|
||||
title: String,
|
||||
value: Binding<Double>,
|
||||
range: ClosedRange<Double>,
|
||||
onEditingChanged: @escaping (Bool) -> Void
|
||||
) -> some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
HStack {
|
||||
Text(title)
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(Int(value.wrappedValue)) seconds")
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
Slider(
|
||||
value: value,
|
||||
in: range,
|
||||
step: 5
|
||||
) {
|
||||
Text(title)
|
||||
} minimumValueLabel: {
|
||||
Text("\(Int(range.lowerBound))s")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
} maximumValueLabel: {
|
||||
Text("\(Int(range.upperBound))s")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
} onEditingChanged: { editing in
|
||||
onEditingChanged(editing)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct NotificationsPreferencesView: View {
|
||||
|
||||
@@ -10,16 +10,19 @@ import SwiftUI
|
||||
struct ServerDetailView: View {
|
||||
@Binding var server: Server
|
||||
var isFetching: Bool
|
||||
@AppStorage("showIntervalIndicator") private var showIntervalIndicator: Bool = true
|
||||
|
||||
@State private var progress: Double = 0
|
||||
let timer = Timer.publish(every: 1.0 / 60.0, on: .main, in: .common).autoconnect()
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
if showIntervalIndicator {
|
||||
ProgressView(value: progress)
|
||||
.progressViewStyle(LinearProgressViewStyle())
|
||||
.padding(.horizontal)
|
||||
.frame(height: 2)
|
||||
}
|
||||
|
||||
if server.info == nil {
|
||||
ProgressView("Fetching server info...")
|
||||
@@ -54,6 +57,7 @@ struct ServerDetailView: View {
|
||||
}
|
||||
}
|
||||
.onReceive(timer) { _ in
|
||||
guard showIntervalIndicator else { return }
|
||||
withAnimation(.linear(duration: 1.0 / 60.0)) {
|
||||
progress += 1.0 / (60.0 * 60.0)
|
||||
if progress >= 1 { progress = 0 }
|
||||
|
||||
@@ -185,7 +185,7 @@ struct ServerFormView: View {
|
||||
print("adding server")
|
||||
let newServer = Server(hostname: trimmedHost)
|
||||
servers.append(newServer)
|
||||
KeychainHelper.save(apiKey: trimmedKey, for: trimmedHost)
|
||||
KeychainHelper.saveApiKey(trimmedKey, for: trimmedHost)
|
||||
saveServers()
|
||||
case .edit(let oldServer):
|
||||
if let index = servers.firstIndex(where: { $0.id == oldServer.id }) {
|
||||
@@ -194,7 +194,7 @@ struct ServerFormView: View {
|
||||
if oldHostname != trimmedHost {
|
||||
KeychainHelper.deleteApiKey(for: oldHostname)
|
||||
}
|
||||
KeychainHelper.save(apiKey: trimmedKey, for: trimmedHost)
|
||||
KeychainHelper.saveApiKey(trimmedKey, for: trimmedHost)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,7 @@ struct ServerFormView: View {
|
||||
if oldHostname != hostname {
|
||||
KeychainHelper.deleteApiKey(for: oldHostname)
|
||||
}
|
||||
KeychainHelper.save(apiKey: apiKey, for: hostname)
|
||||
KeychainHelper.saveApiKey(apiKey, for: hostname)
|
||||
saveServers()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,13 @@ struct GeneralView: View {
|
||||
Text("Additional PHP interpreters")
|
||||
} value: {
|
||||
InfoCell(
|
||||
value: server.info?.additionalPHPInterpreters?.map { $0.versionFull } ?? [],
|
||||
value: {
|
||||
let interpreters = server.info?.additionalPHPInterpreters ?? []
|
||||
if interpreters.isEmpty {
|
||||
return ["None"]
|
||||
}
|
||||
return interpreters.map { $0.versionFull }
|
||||
}(),
|
||||
monospaced: true
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user