Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 44cc620d3d | |||
| 08db74f397 | |||
| 9be8d41c94 | |||
| d978c51fbd | |||
| b8f80932ed | |||
| 11815fb807 | |||
| afbb425e3b |
32
CHANGELOG.md
32
CHANGELOG.md
@@ -1,21 +1,43 @@
|
||||
# Changelog
|
||||
|
||||
## 26.1.6
|
||||
## Unreleased (2026-04-21)
|
||||
- Added optional sidebar groups for hosts, including group creation, editing, deletion, and host assignment.
|
||||
- Added grouped host ordering, group reordering via drag and drop, and clearer visual feedback while moving groups.
|
||||
- Improved group header styling to better distinguish groups and ungrouped hosts in the sidebar.
|
||||
- Fixed a launch crash in grouped builds caused by async ping tasks writing back to stale array indexes after the server list changed.
|
||||
|
||||
## 26.1.9 (2026-04-19)
|
||||
- Reduced idle CPU usage and energy impact by changing the interval indicator from a permanent 60 FPS timer to a 1-second update cadence.
|
||||
- Reset the interval indicator cleanly when the refresh interval changes or when the indicator is hidden.
|
||||
|
||||
## 26.1.8 (2026-04-19)
|
||||
- Fixed a crash in `PingService` caused by concurrent mutation of shared ping state from multiple async ping tasks.
|
||||
- Moved ping state tracking and reboot suppression windows into an actor so ping success/failure handling is serialized safely.
|
||||
|
||||
## 26.1.7 (2026-04-19)
|
||||
- Added remote reboot support for hosts running KeyHelp API 2.14 or newer.
|
||||
- Added a dedicated `APIv2_14` client and mapped 2.14+ hosts to it instead of treating them as API 2.13.
|
||||
- Fixed the reboot request to call `/api/v2/server/reboot` with the required JSON confirmation payload.
|
||||
- Changed the reboot confirmation and result UI to non-blocking sheets/banner feedback so failures no longer trap the app in modal dialogs.
|
||||
- Improved API error messages by surfacing the server response body instead of only generic HTTP status codes.
|
||||
- Reduced expected reboot noise by suppressing ping checks for a short grace period after a reboot request.
|
||||
|
||||
## 26.1.6 (2026-04-19)
|
||||
- Publish Gitea releases as stable by default instead of pre-releases.
|
||||
- Update the Homebrew tap automatically after each successful release by rewriting the cask version and DMG checksum, then pushing the tap repo.
|
||||
- Simplified the README for end users by adding clear install options and trimming internal release-engineering details.
|
||||
- Ignore the local `homebrew-tap/` checkout in the main app repository.
|
||||
|
||||
## 26.1.3
|
||||
## 26.1.3 (2026-01-03)
|
||||
- Fixed version handling for changelogs.
|
||||
|
||||
## 26.1.2 (2025-01-03)
|
||||
## 26.1.2 (2026-01-03)
|
||||
- Synced version.json to 26.1.2.
|
||||
|
||||
## 26.1.1 (2025-01-03)
|
||||
## 26.1.1 (2026-01-03)
|
||||
- Fixed changelog extraction in publish script.
|
||||
|
||||
## 26.1.0 (2025-01-03)
|
||||
## 26.1.0 (2026-01-03)
|
||||
- Auto-populate release description from CHANGELOG when publishing to Gitea.
|
||||
|
||||
## Prereleases
|
||||
|
||||
@@ -10,6 +10,7 @@ import Foundation
|
||||
enum APIVersion: String, CaseIterable {
|
||||
case v2_12 = "2.12"
|
||||
case v2_13 = "2.13"
|
||||
case v2_14 = "2.14"
|
||||
|
||||
static func from(versionString: String) -> APIVersion? {
|
||||
if let version = APIVersion(rawValue: versionString) {
|
||||
@@ -24,7 +25,8 @@ enum APIVersion: String, CaseIterable {
|
||||
|
||||
switch (major, minor) {
|
||||
case (2, 12): return .v2_12
|
||||
case (2, 13...): return .v2_13
|
||||
case (2, 13): return .v2_13
|
||||
case (2, 14...): return .v2_14
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
@@ -36,6 +38,7 @@ protocol AnyServerAPI {
|
||||
func fetchMemoryData() async throws -> Any
|
||||
func fetchUtilizationData() async throws -> Any
|
||||
func fetchServerSummary(apiKey: String) async throws -> ServerInfo
|
||||
func restartServer(apiKey: String) async throws
|
||||
}
|
||||
|
||||
private struct AnyServerAPIWrapper<T: ServerAPIProtocol>: AnyServerAPI {
|
||||
@@ -64,6 +67,10 @@ private struct AnyServerAPIWrapper<T: ServerAPIProtocol>: AnyServerAPI {
|
||||
func fetchServerSummary(apiKey: String) async throws -> ServerInfo {
|
||||
return try await wrapped.fetchServerSummary(apiKey: apiKey)
|
||||
}
|
||||
|
||||
func restartServer(apiKey: String) async throws {
|
||||
try await wrapped.restartServer(apiKey: apiKey)
|
||||
}
|
||||
}
|
||||
|
||||
class APIFactory {
|
||||
@@ -73,6 +80,8 @@ class APIFactory {
|
||||
return AnyServerAPIWrapper(APIv2_12(baseURL: baseURL))
|
||||
case .v2_13:
|
||||
return AnyServerAPIWrapper(APIv2_13(baseURL: baseURL))
|
||||
case .v2_14:
|
||||
return AnyServerAPIWrapper(APIv2_14(baseURL: baseURL))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +113,7 @@ class APIFactory {
|
||||
}
|
||||
}
|
||||
|
||||
return AnyServerAPIWrapper(APIv2_13(baseURL: baseURL))
|
||||
return AnyServerAPIWrapper(APIv2_14(baseURL: baseURL))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ protocol ServerAPIProtocol {
|
||||
func fetchMemory() async throws -> MemoryType
|
||||
func fetchUtilization() async throws -> UtilizationType
|
||||
func fetchServerSummary(apiKey: String) async throws -> ServerInfo
|
||||
func restartServer(apiKey: String) async throws
|
||||
}
|
||||
|
||||
struct SystemInfo: Codable {
|
||||
@@ -36,6 +37,15 @@ class BaseAPIClient {
|
||||
}
|
||||
|
||||
func performRequest<T: Codable>(_ request: URLRequest, responseType: T.Type) async throws -> T {
|
||||
let (data, _) = try await performDataRequest(request)
|
||||
return try JSONDecoder().decode(T.self, from: data)
|
||||
}
|
||||
|
||||
func performRequestWithoutBody(_ request: URLRequest) async throws {
|
||||
_ = try await performDataRequest(request)
|
||||
}
|
||||
|
||||
private func performDataRequest(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
|
||||
let (data, response) = try await session.data(for: request)
|
||||
|
||||
guard let httpResponse = response as? HTTPURLResponse else {
|
||||
@@ -43,25 +53,61 @@ class BaseAPIClient {
|
||||
}
|
||||
|
||||
guard 200...299 ~= httpResponse.statusCode else {
|
||||
throw APIError.httpError(httpResponse.statusCode)
|
||||
throw APIError.httpError(
|
||||
httpResponse.statusCode,
|
||||
BaseAPIClient.extractErrorMessage(from: data)
|
||||
)
|
||||
}
|
||||
|
||||
return try JSONDecoder().decode(T.self, from: data)
|
||||
return (data, httpResponse)
|
||||
}
|
||||
|
||||
private static func extractErrorMessage(from data: Data) -> String? {
|
||||
guard !data.isEmpty else { return nil }
|
||||
|
||||
if let envelope = try? JSONDecoder().decode(APIErrorEnvelope.self, from: data) {
|
||||
let parts = [envelope.code, envelope.message]
|
||||
.compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
.filter { !$0.isEmpty }
|
||||
|
||||
if !parts.isEmpty {
|
||||
return parts.joined(separator: " ")
|
||||
}
|
||||
}
|
||||
|
||||
if let text = String(data: data, encoding: .utf8)?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
!text.isEmpty {
|
||||
return text
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
enum APIError: Error, LocalizedError {
|
||||
case invalidURL
|
||||
case invalidResponse
|
||||
case httpError(Int)
|
||||
case httpError(Int, String?)
|
||||
case decodingError(Error)
|
||||
case unsupportedFeature(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidURL: return "Invalid URL"
|
||||
case .invalidResponse: return "Invalid response"
|
||||
case .httpError(let code): return "HTTP Error: \(code)"
|
||||
case .httpError(let code, let message):
|
||||
if let message, !message.isEmpty {
|
||||
return "HTTP Error: \(code)\n\(message)"
|
||||
}
|
||||
return "HTTP Error: \(code)"
|
||||
case .decodingError(let error): return "Decoding error: \(error.localizedDescription)"
|
||||
case .unsupportedFeature(let feature): return "\(feature) is not supported by this host"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct APIErrorEnvelope: Decodable {
|
||||
let code: String?
|
||||
let message: String?
|
||||
}
|
||||
|
||||
@@ -2,9 +2,17 @@ import Foundation
|
||||
import UserNotifications
|
||||
|
||||
enum PingService {
|
||||
private static var previousPingStates: [String: Bool] = [:]
|
||||
private static let stateStore = PingStateStore()
|
||||
|
||||
static func suppressChecks(for hostname: String, duration: TimeInterval) async {
|
||||
await stateStore.suppressChecks(for: hostname, duration: duration)
|
||||
}
|
||||
|
||||
static func ping(hostname: String, apiKey: String, notificationsEnabled: Bool = true) async -> Bool {
|
||||
if await stateStore.shouldSkipPing(for: hostname) {
|
||||
return false
|
||||
}
|
||||
|
||||
guard let url = URL(string: "https://\(hostname)/api/v2/ping") else {
|
||||
print("❌ [PingService] Invalid URL for \(hostname)")
|
||||
return false
|
||||
@@ -18,42 +26,32 @@ enum PingService {
|
||||
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)")
|
||||
}
|
||||
handlePingFailure(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
await handlePingFailure(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
return false
|
||||
}
|
||||
|
||||
if let result = try? JSONDecoder().decode([String: String].self, from: data), result["response"] == "pong" {
|
||||
handlePingSuccess(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
await handlePingSuccess(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
return true
|
||||
} else {
|
||||
handlePingFailure(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
await handlePingFailure(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
return false
|
||||
}
|
||||
} catch {
|
||||
print("❌ [PingService] Error pinging \(hostname): \(error)")
|
||||
handlePingFailure(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
await handlePingFailure(for: hostname, notificationsEnabled: notificationsEnabled)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private static func handlePingSuccess(for hostname: String, notificationsEnabled: Bool) {
|
||||
let wasPreviouslyDown = previousPingStates[hostname] == false
|
||||
previousPingStates[hostname] = true
|
||||
|
||||
if wasPreviouslyDown && notificationsEnabled {
|
||||
sendNotification(title: "Server Online", body: "\(hostname) is now online")
|
||||
private static func handlePingSuccess(for hostname: String, notificationsEnabled: Bool) async {
|
||||
if let notification = await stateStore.recordSuccess(for: hostname, notificationsEnabled: notificationsEnabled) {
|
||||
sendNotification(title: notification.title, body: notification.body)
|
||||
}
|
||||
}
|
||||
|
||||
private static func handlePingFailure(for hostname: String, notificationsEnabled: Bool) {
|
||||
let wasPreviouslyUp = previousPingStates[hostname] != false
|
||||
previousPingStates[hostname] = false
|
||||
|
||||
if wasPreviouslyUp && notificationsEnabled {
|
||||
sendNotification(title: "Server Offline", body: "\(hostname) is offline")
|
||||
private static func handlePingFailure(for hostname: String, notificationsEnabled: Bool) async {
|
||||
if let notification = await stateStore.recordFailure(for: hostname, notificationsEnabled: notificationsEnabled) {
|
||||
sendNotification(title: notification.title, body: notification.body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,3 +65,55 @@ enum PingService {
|
||||
UNUserNotificationCenter.current().add(request)
|
||||
}
|
||||
}
|
||||
|
||||
private actor PingStateStore {
|
||||
private var previousPingStates: [String: Bool] = [:]
|
||||
private var suppressedUntil: [String: Date] = [:]
|
||||
|
||||
func suppressChecks(for hostname: String, duration: TimeInterval) {
|
||||
suppressedUntil[hostname] = Date().addingTimeInterval(duration)
|
||||
previousPingStates[hostname] = false
|
||||
}
|
||||
|
||||
func shouldSkipPing(for hostname: String) -> Bool {
|
||||
if let suppressedUntil = suppressedUntil[hostname], suppressedUntil > Date() {
|
||||
return true
|
||||
}
|
||||
|
||||
suppressedUntil.removeValue(forKey: hostname)
|
||||
return false
|
||||
}
|
||||
|
||||
func recordSuccess(for hostname: String, notificationsEnabled: Bool) -> PingNotification? {
|
||||
let wasPreviouslyDown = previousPingStates[hostname] == false
|
||||
previousPingStates[hostname] = true
|
||||
|
||||
guard wasPreviouslyDown, notificationsEnabled else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return PingNotification(
|
||||
title: "Server Online",
|
||||
body: "\(hostname) is now online"
|
||||
)
|
||||
}
|
||||
|
||||
func recordFailure(for hostname: String, notificationsEnabled: Bool) -> PingNotification? {
|
||||
let wasPreviouslyUp = previousPingStates[hostname] != false
|
||||
previousPingStates[hostname] = false
|
||||
|
||||
guard wasPreviouslyUp, notificationsEnabled else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return PingNotification(
|
||||
title: "Server Offline",
|
||||
body: "\(hostname) is offline"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PingNotification {
|
||||
let title: String
|
||||
let body: String
|
||||
}
|
||||
|
||||
@@ -10,12 +10,14 @@ import Foundation
|
||||
struct Server: Identifiable, Codable, Hashable, Equatable {
|
||||
let id: UUID
|
||||
var hostname: String
|
||||
var groupID: UUID?
|
||||
var info: ServerInfo?
|
||||
var pingable: Bool
|
||||
|
||||
init(id: UUID = UUID(), hostname: String, info: ServerInfo? = nil, pingable: Bool = false) {
|
||||
init(id: UUID = UUID(), hostname: String, groupID: UUID? = nil, info: ServerInfo? = nil, pingable: Bool = false) {
|
||||
self.id = id
|
||||
self.hostname = hostname
|
||||
self.groupID = groupID
|
||||
self.info = info
|
||||
self.pingable = pingable
|
||||
}
|
||||
@@ -23,24 +25,26 @@ struct Server: Identifiable, Codable, Hashable, Equatable {
|
||||
// MARK: - Manual conformance
|
||||
|
||||
static func == (lhs: Server, rhs: Server) -> Bool {
|
||||
lhs.id == rhs.id && lhs.hostname == rhs.hostname && lhs.info == rhs.info && lhs.pingable == rhs.pingable
|
||||
lhs.id == rhs.id && lhs.hostname == rhs.hostname && lhs.groupID == rhs.groupID && lhs.info == rhs.info && lhs.pingable == rhs.pingable
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(id)
|
||||
hasher.combine(hostname)
|
||||
hasher.combine(groupID)
|
||||
hasher.combine(info)
|
||||
hasher.combine(pingable)
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, hostname, info, pingable
|
||||
case id, hostname, groupID, info, pingable
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
id = try container.decode(UUID.self, forKey: .id)
|
||||
hostname = try container.decode(String.self, forKey: .hostname)
|
||||
groupID = try container.decodeIfPresent(UUID.self, forKey: .groupID)
|
||||
info = try container.decodeIfPresent(ServerInfo.self, forKey: .info)
|
||||
pingable = try container.decodeIfPresent(Bool.self, forKey: .pingable) ?? false
|
||||
}
|
||||
@@ -49,6 +53,7 @@ struct Server: Identifiable, Codable, Hashable, Equatable {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(id, forKey: .id)
|
||||
try container.encode(hostname, forKey: .hostname)
|
||||
try container.encodeIfPresent(groupID, forKey: .groupID)
|
||||
try container.encodeIfPresent(info, forKey: .info)
|
||||
try container.encode(pingable, forKey: .pingable)
|
||||
}
|
||||
|
||||
11
Sources/Model/API/ServerGroup.swift
Normal file
11
Sources/Model/API/ServerGroup.swift
Normal file
@@ -0,0 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
struct ServerGroup: Identifiable, Codable, Hashable, Equatable {
|
||||
let id: UUID
|
||||
var name: String
|
||||
|
||||
init(id: UUID = UUID(), name: String) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
@@ -185,6 +185,10 @@ struct ServerInfo: Codable, Hashable, Equatable {
|
||||
].filter { !$0.isEmpty }
|
||||
return components.isEmpty ? nil : components.joined(separator: " • ")
|
||||
}
|
||||
|
||||
var supportsRestartCommand: Bool {
|
||||
ServerInfo.version(apiVersion, isAtLeast: "2.14")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers & Sample Data
|
||||
@@ -226,6 +230,27 @@ extension ServerInfo {
|
||||
return normalized
|
||||
}
|
||||
|
||||
private static func version(_ value: String, isAtLeast minimum: String) -> Bool {
|
||||
let lhs = value
|
||||
.split(separator: ".")
|
||||
.compactMap { Int($0) }
|
||||
let rhs = minimum
|
||||
.split(separator: ".")
|
||||
.compactMap { Int($0) }
|
||||
|
||||
let count = max(lhs.count, rhs.count)
|
||||
for index in 0..<count {
|
||||
let left = index < lhs.count ? lhs[index] : 0
|
||||
let right = index < rhs.count ? rhs[index] : 0
|
||||
|
||||
if left != right {
|
||||
return left > right
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
static let placeholder = ServerInfo(
|
||||
hostname: "preview.example.com",
|
||||
ipAddresses: ["192.168.1.1", "fe80::1"],
|
||||
|
||||
@@ -181,7 +181,7 @@ class APIv2_12: BaseAPIClient, ServerAPIProtocol {
|
||||
}
|
||||
|
||||
guard httpResponse.statusCode == 200 else {
|
||||
throw APIError.httpError(httpResponse.statusCode)
|
||||
throw APIError.httpError(httpResponse.statusCode, nil)
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
@@ -189,6 +189,10 @@ class APIv2_12: BaseAPIClient, ServerAPIProtocol {
|
||||
let envelope = try decoder.decode(ServerSummaryEnvelope.self, from: data)
|
||||
return envelope.toDomain()
|
||||
}
|
||||
|
||||
func restartServer(apiKey: String) async throws {
|
||||
throw APIError.unsupportedFeature("Server reboot")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Server Summary Mapping
|
||||
|
||||
@@ -181,7 +181,7 @@ class APIv2_13: BaseAPIClient, ServerAPIProtocol {
|
||||
}
|
||||
|
||||
guard httpResponse.statusCode == 200 else {
|
||||
throw APIError.httpError(httpResponse.statusCode)
|
||||
throw APIError.httpError(httpResponse.statusCode, nil)
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
@@ -189,6 +189,10 @@ class APIv2_13: BaseAPIClient, ServerAPIProtocol {
|
||||
let envelope = try decoder.decode(ServerSummaryEnvelope.self, from: data)
|
||||
return envelope.toDomain()
|
||||
}
|
||||
|
||||
func restartServer(apiKey: String) async throws {
|
||||
throw APIError.unsupportedFeature("Server reboot")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Server Summary Mapping
|
||||
|
||||
30
Sources/Model/API/Versions/APIv2_14.swift
Normal file
30
Sources/Model/API/Versions/APIv2_14.swift
Normal file
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// APIv2_14.swift
|
||||
// iKeyMon
|
||||
//
|
||||
// Created by tracer on 19.04.26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class APIv2_14: APIv2_13 {
|
||||
private enum Endpoint: String {
|
||||
case serverReboot = "/api/v2/server/reboot"
|
||||
|
||||
func url(baseURL: URL) -> URL {
|
||||
baseURL.appendingPathComponent(rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
override func restartServer(apiKey: String) async throws {
|
||||
var request = URLRequest(url: Endpoint.serverReboot.url(baseURL: baseURL))
|
||||
request.httpMethod = "POST"
|
||||
request.setValue(apiKey, forHTTPHeaderField: "X-API-KEY")
|
||||
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
request.timeoutInterval = 30
|
||||
request.httpBody = #"{"confirm":true}"#.data(using: .utf8)
|
||||
|
||||
try await performRequestWithoutBody(request)
|
||||
}
|
||||
}
|
||||
80
Sources/Views/GroupFormView.swift
Normal file
80
Sources/Views/GroupFormView.swift
Normal file
@@ -0,0 +1,80 @@
|
||||
import SwiftUI
|
||||
|
||||
struct GroupFormView: View {
|
||||
enum Mode {
|
||||
case add
|
||||
case edit(ServerGroup)
|
||||
}
|
||||
|
||||
let mode: Mode
|
||||
@Binding var groups: [ServerGroup]
|
||||
let onSave: () -> Void
|
||||
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var name: String
|
||||
|
||||
init(mode: Mode, groups: Binding<[ServerGroup]>, onSave: @escaping () -> Void) {
|
||||
self.mode = mode
|
||||
self._groups = groups
|
||||
self.onSave = onSave
|
||||
|
||||
switch mode {
|
||||
case .add:
|
||||
self._name = State(initialValue: "")
|
||||
case .edit(let group):
|
||||
self._name = State(initialValue: group.name)
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text(title)
|
||||
.font(.headline)
|
||||
|
||||
TextField("Group name", text: $name)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
|
||||
HStack {
|
||||
Button("Cancel") {
|
||||
dismiss()
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button("Save") {
|
||||
save()
|
||||
}
|
||||
.disabled(trimmedName.isEmpty)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.frame(width: 320)
|
||||
}
|
||||
|
||||
private var title: String {
|
||||
switch mode {
|
||||
case .add:
|
||||
return "Add Group"
|
||||
case .edit:
|
||||
return "Edit Group"
|
||||
}
|
||||
}
|
||||
|
||||
private var trimmedName: String {
|
||||
name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
private func save() {
|
||||
switch mode {
|
||||
case .add:
|
||||
groups.append(ServerGroup(name: trimmedName))
|
||||
case .edit(let group):
|
||||
if let index = groups.firstIndex(where: { $0.id == group.id }) {
|
||||
groups[index].name = trimmedName
|
||||
}
|
||||
}
|
||||
|
||||
onSave()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
@@ -8,16 +8,23 @@
|
||||
import SwiftUI
|
||||
import Combine
|
||||
import UserNotifications
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct MainView: View {
|
||||
|
||||
private static let serverOrderKeyStatic = "serverOrder"
|
||||
private static let storedServersKeyStatic = "storedServers"
|
||||
private static let storedGroupsKeyStatic = "storedGroups"
|
||||
|
||||
@State var showAddServerSheet: Bool = false
|
||||
@State private var showAddGroupSheet: Bool = false
|
||||
@State private var serverBeingEdited: Server?
|
||||
@State private var groupBeingEdited: ServerGroup?
|
||||
@State private var serverToDelete: Server?
|
||||
@State private var groupToDelete: ServerGroup?
|
||||
@State private var showDeleteConfirmation = false
|
||||
@State private var showDeleteGroupConfirmation = false
|
||||
@State private var isFetchingInfo: Bool = false
|
||||
@AppStorage("pingInterval") private var pingInterval: Int = 10
|
||||
@AppStorage("refreshInterval") private var refreshInterval: Int = 60
|
||||
@@ -26,12 +33,16 @@ struct MainView: View {
|
||||
@State private var refreshTimer: Timer.TimerPublisher?
|
||||
@State private var refreshSubscription: AnyCancellable?
|
||||
@State private var pingTimer: Timer?
|
||||
@State private var restartingServerID: UUID?
|
||||
@State private var draggedGroupID: UUID?
|
||||
@State private var groupDropIndicator: GroupDropIndicator?
|
||||
@State private var lastRefreshInterval: Int?
|
||||
@State private var previousServiceStates: [String: String] = [:]
|
||||
private let serverOrderKey = MainView.serverOrderKeyStatic
|
||||
private let storedServersKey = MainView.storedServersKeyStatic
|
||||
private let storedGroupsKey = MainView.storedGroupsKeyStatic
|
||||
|
||||
@State private var servers: [Server] = MainView.loadStoredServers()
|
||||
@State private var groups: [ServerGroup] = MainView.loadStoredGroups()
|
||||
|
||||
// @State private var selectedServer: Server?
|
||||
@State private var selectedServerID: UUID?
|
||||
@@ -39,73 +50,106 @@ struct MainView: View {
|
||||
var body: some View {
|
||||
var mainContent: some View {
|
||||
NavigationSplitView {
|
||||
List(selection: $selectedServerID) {
|
||||
ForEach(servers) { server in
|
||||
HStack {
|
||||
Image(systemName: "dot.circle.fill")
|
||||
.foregroundColor(server.pingable ? .green : .red)
|
||||
Text(server.hostname)
|
||||
ZStack {
|
||||
SidebarMaterialView()
|
||||
|
||||
List(selection: $selectedServerID) {
|
||||
sidebarContent
|
||||
}
|
||||
.tag(server)
|
||||
.contextMenu {
|
||||
Button("Edit") {
|
||||
print("Editing:", server.hostname)
|
||||
serverBeingEdited = server
|
||||
}
|
||||
Divider()
|
||||
Button("Delete", role: .destructive) {
|
||||
serverToDelete = server
|
||||
showDeleteConfirmation = true
|
||||
.listStyle(.sidebar)
|
||||
.scrollContentBackground(.hidden)
|
||||
.background(Color.clear)
|
||||
}
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 0, style: .continuous)
|
||||
.fill(.ultraThinMaterial)
|
||||
)
|
||||
.overlay(alignment: .trailing) {
|
||||
Rectangle()
|
||||
.fill(Color.white.opacity(0.08))
|
||||
.frame(width: 1)
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Menu {
|
||||
Button("Add Host") {
|
||||
showAddServerSheet = true
|
||||
}
|
||||
Button("Add Group") {
|
||||
showAddGroupSheet = true
|
||||
}
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.help("Add Host or Group")
|
||||
}
|
||||
}
|
||||
.onMove(perform: moveServer)
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button(action: { showAddServerSheet = true }) {
|
||||
Image(systemName: "plus")
|
||||
.navigationTitle("Servers")
|
||||
.onChange(of: selectedServerID) {
|
||||
if let selectedServerID {
|
||||
UserDefaults.standard.set(selectedServerID.uuidString, forKey: "selectedServerID")
|
||||
fetchServerInfo(for: selectedServerID)
|
||||
}
|
||||
.help("Add Host")
|
||||
}
|
||||
}
|
||||
.navigationTitle("Servers")
|
||||
.onChange(of: selectedServerID) {
|
||||
if let selectedServerID {
|
||||
UserDefaults.standard.set(selectedServerID.uuidString, forKey: "selectedServerID")
|
||||
fetchServerInfo(for: selectedServerID)
|
||||
} detail: {
|
||||
if let selectedServerID,
|
||||
let index = servers.firstIndex(where: { selectedServerID == $0.id }) {
|
||||
let serverID = servers[index].id
|
||||
ServerDetailView(
|
||||
server: $servers[index],
|
||||
isFetching: isFetchingInfo,
|
||||
canRestart: servers[index].info?.supportsRestartCommand == true,
|
||||
isRestarting: restartingServerID == serverID
|
||||
) {
|
||||
await restartServer(for: serverID)
|
||||
}
|
||||
} else {
|
||||
ContentUnavailableView("No Server Selected", systemImage: "server.rack")
|
||||
}
|
||||
}
|
||||
} detail: {
|
||||
if let selectedServerID,
|
||||
let index = servers.firstIndex(where: { selectedServerID == $0.id }) {
|
||||
ServerDetailView(server: $servers[index], isFetching: isFetchingInfo)
|
||||
} else {
|
||||
ContentUnavailableView("No Server Selected", systemImage: "server.rack")
|
||||
}
|
||||
}
|
||||
}
|
||||
return mainContent
|
||||
.sheet(isPresented: $showAddServerSheet) {
|
||||
ServerFormView(
|
||||
mode: .add,
|
||||
servers: $servers,
|
||||
groups: $groups,
|
||||
dismiss: { showAddServerSheet = false }
|
||||
)
|
||||
}
|
||||
.sheet(isPresented: $showAddGroupSheet) {
|
||||
GroupFormView(mode: .add, groups: $groups) {
|
||||
saveGroups()
|
||||
}
|
||||
}
|
||||
.sheet(item: $serverBeingEdited) { server in
|
||||
ServerFormView(
|
||||
mode: .edit(server),
|
||||
servers: $servers,
|
||||
groups: $groups,
|
||||
dismiss: { serverBeingEdited = nil }
|
||||
)
|
||||
}
|
||||
.sheet(item: $groupBeingEdited) { group in
|
||||
GroupFormView(mode: .edit(group), groups: $groups) {
|
||||
saveGroups()
|
||||
}
|
||||
}
|
||||
.alert("Are you sure you want to delete this server?", isPresented: $showDeleteConfirmation, presenting: serverToDelete) { server in
|
||||
Button("Delete", role: .destructive) {
|
||||
ServerFormView.delete(server: server, from: &servers)
|
||||
saveServers()
|
||||
}
|
||||
Button("Cancel", role: .cancel) {}
|
||||
}
|
||||
.alert("Are you sure you want to delete this group?", isPresented: $showDeleteGroupConfirmation, presenting: groupToDelete) { group in
|
||||
Button("Delete", role: .destructive) {
|
||||
deleteGroup(group)
|
||||
}
|
||||
Button("Cancel", role: .cancel) {}
|
||||
} message: { group in
|
||||
Text("Servers in \(group.name) will remain available and become ungrouped.")
|
||||
}
|
||||
.onAppear {
|
||||
requestNotificationPermissions()
|
||||
|
||||
@@ -140,8 +184,145 @@ struct MainView: View {
|
||||
setupRefreshTimer()
|
||||
}
|
||||
}
|
||||
.onChange(of: groups) { _, _ in
|
||||
saveGroups()
|
||||
}
|
||||
.frame(minWidth: 800, minHeight: 450)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var sidebarContent: some View {
|
||||
if groups.isEmpty {
|
||||
ForEach(servers) { server in
|
||||
sidebarRow(for: server)
|
||||
}
|
||||
.onMove(perform: moveServer)
|
||||
} else {
|
||||
ForEach(groups) { group in
|
||||
Section {
|
||||
ForEach(servers(in: group)) { server in
|
||||
sidebarRow(for: server)
|
||||
}
|
||||
.onMove { source, destination in
|
||||
moveServers(in: group.id, from: source, to: destination)
|
||||
}
|
||||
} header: {
|
||||
groupHeader(for: group)
|
||||
}
|
||||
}
|
||||
|
||||
if !ungroupedServers.isEmpty {
|
||||
Section {
|
||||
ForEach(ungroupedServers) { server in
|
||||
sidebarRow(for: server)
|
||||
}
|
||||
.onMove { source, destination in
|
||||
moveServers(in: nil, from: source, to: destination)
|
||||
}
|
||||
} header: {
|
||||
sidebarSectionHeader("Ungrouped")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func sidebarSectionHeader(_ title: String) -> some View {
|
||||
HStack {
|
||||
Text(title)
|
||||
.font(.system(size: NSFont.systemFontSize + 1, weight: .bold))
|
||||
.foregroundStyle(Color.accentColor)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
|
||||
private func sidebarRow(for server: Server) -> some View {
|
||||
HStack {
|
||||
Image(systemName: "dot.circle.fill")
|
||||
.foregroundColor(server.pingable ? .green : .red)
|
||||
Text(server.hostname)
|
||||
}
|
||||
.tag(server.id)
|
||||
.contextMenu {
|
||||
Button("Edit") {
|
||||
print("Editing:", server.hostname)
|
||||
serverBeingEdited = server
|
||||
}
|
||||
Divider()
|
||||
Button("Delete", role: .destructive) {
|
||||
serverToDelete = server
|
||||
showDeleteConfirmation = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func groupHeader(for group: ServerGroup) -> some View {
|
||||
let activePlacement = groupDropIndicator?.groupID == group.id ? groupDropIndicator?.placement : nil
|
||||
|
||||
return VStack(spacing: 0) {
|
||||
if activePlacement == .before {
|
||||
dropIndicator
|
||||
}
|
||||
|
||||
sidebarSectionHeader(group.name)
|
||||
.contentShape(Rectangle())
|
||||
.background {
|
||||
if activePlacement != nil {
|
||||
RoundedRectangle(cornerRadius: 6, style: .continuous)
|
||||
.fill(Color.accentColor.opacity(0.12))
|
||||
}
|
||||
}
|
||||
|
||||
if activePlacement == .after {
|
||||
dropIndicator
|
||||
}
|
||||
}
|
||||
.onDrag {
|
||||
draggedGroupID = group.id
|
||||
return NSItemProvider(object: group.id.uuidString as NSString)
|
||||
}
|
||||
.onDrop(
|
||||
of: [UTType.text],
|
||||
delegate: GroupDropDelegate(
|
||||
targetGroup: group,
|
||||
groups: $groups,
|
||||
draggedGroupID: $draggedGroupID,
|
||||
indicator: $groupDropIndicator
|
||||
)
|
||||
)
|
||||
.contextMenu {
|
||||
Button("Edit Group") {
|
||||
groupBeingEdited = group
|
||||
}
|
||||
Button("Delete Group", role: .destructive) {
|
||||
groupToDelete = group
|
||||
showDeleteGroupConfirmation = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var dropIndicator: some View {
|
||||
VStack(spacing: 4) {
|
||||
Capsule()
|
||||
.fill(Color.accentColor)
|
||||
.frame(height: 3)
|
||||
.shadow(color: Color.accentColor.opacity(0.25), radius: 1, y: 0)
|
||||
Color.clear
|
||||
.frame(height: 4)
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
|
||||
private var ungroupedServers: [Server] {
|
||||
servers.filter { server in
|
||||
guard let groupID = server.groupID else { return true }
|
||||
return groups.contains(where: { $0.id == groupID }) == false
|
||||
}
|
||||
}
|
||||
|
||||
private func servers(in group: ServerGroup) -> [Server] {
|
||||
servers.filter { $0.groupID == group.id }
|
||||
}
|
||||
|
||||
private func fetchServerInfo(for id: UUID) {
|
||||
guard let server = servers.first(where: { $0.id == id }) else {
|
||||
@@ -214,6 +395,41 @@ struct MainView: View {
|
||||
|
||||
private func moveServer(from source: IndexSet, to destination: Int) {
|
||||
servers.move(fromOffsets: source, toOffset: destination)
|
||||
saveServers()
|
||||
saveServerOrder()
|
||||
}
|
||||
|
||||
private func moveServers(in groupID: UUID?, from source: IndexSet, to destination: Int) {
|
||||
let matchingServers = servers.filter { server in
|
||||
if let groupID {
|
||||
return server.groupID == groupID
|
||||
}
|
||||
return server.groupID == nil || groups.contains(where: { $0.id == server.groupID }) == false
|
||||
}
|
||||
|
||||
var reorderedServers = matchingServers
|
||||
reorderedServers.move(fromOffsets: source, toOffset: destination)
|
||||
|
||||
let replacements = Dictionary(uniqueKeysWithValues: reorderedServers.map { ($0.id, $0) })
|
||||
var reorderedIDs = reorderedServers.map(\.id)
|
||||
|
||||
servers = servers.map { server in
|
||||
let belongsInSection: Bool
|
||||
if let groupID {
|
||||
belongsInSection = server.groupID == groupID
|
||||
} else {
|
||||
belongsInSection = server.groupID == nil || groups.contains(where: { $0.id == server.groupID }) == false
|
||||
}
|
||||
|
||||
guard belongsInSection, let nextID = reorderedIDs.first else {
|
||||
return server
|
||||
}
|
||||
|
||||
reorderedIDs.removeFirst()
|
||||
return replacements[nextID] ?? server
|
||||
}
|
||||
|
||||
saveServers()
|
||||
saveServerOrder()
|
||||
}
|
||||
|
||||
@@ -222,22 +438,47 @@ struct MainView: View {
|
||||
UserDefaults.standard.set(ids, forKey: serverOrderKey)
|
||||
print("💾 [MainView] Saved server order with \(ids.count) entries")
|
||||
}
|
||||
|
||||
private func saveServers() {
|
||||
if let data = try? JSONEncoder().encode(servers) {
|
||||
UserDefaults.standard.set(data, forKey: MainView.storedServersKeyStatic)
|
||||
}
|
||||
}
|
||||
|
||||
private func saveGroups() {
|
||||
if let data = try? JSONEncoder().encode(groups) {
|
||||
UserDefaults.standard.set(data, forKey: storedGroupsKey)
|
||||
}
|
||||
}
|
||||
|
||||
private func deleteGroup(_ group: ServerGroup) {
|
||||
groups.removeAll { $0.id == group.id }
|
||||
for index in servers.indices {
|
||||
if servers[index].groupID == group.id {
|
||||
servers[index].groupID = nil
|
||||
}
|
||||
}
|
||||
saveGroups()
|
||||
saveServers()
|
||||
}
|
||||
|
||||
private struct PingResponse: Codable {
|
||||
let response: String
|
||||
}
|
||||
|
||||
func pingAllServers() {
|
||||
for (index, server) in servers.enumerated() {
|
||||
let pingTargets = servers.map { ($0.id, $0.hostname) }
|
||||
|
||||
for (serverID, hostname) in pingTargets {
|
||||
Task {
|
||||
let apiKey = KeychainHelper.loadApiKey(for: server.hostname)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let pingable = await PingService.ping(hostname: server.hostname, apiKey: apiKey, notificationsEnabled: enableStatusNotifications)
|
||||
let apiKey = KeychainHelper.loadApiKey(for: hostname)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let pingable = await PingService.ping(hostname: hostname, apiKey: apiKey, notificationsEnabled: enableStatusNotifications)
|
||||
await MainActor.run {
|
||||
guard let index = servers.firstIndex(where: { $0.id == serverID }) else {
|
||||
return
|
||||
}
|
||||
servers[index].pingable = pingable
|
||||
}
|
||||
if !pingable {
|
||||
print("📶 [MainView] Ping \(server.hostname): offline")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,6 +534,20 @@ struct MainView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private static func loadStoredGroups() -> [ServerGroup] {
|
||||
let defaults = UserDefaults.standard
|
||||
guard let data = defaults.data(forKey: storedGroupsKeyStatic) else {
|
||||
return []
|
||||
}
|
||||
|
||||
do {
|
||||
return try JSONDecoder().decode([ServerGroup].self, from: data)
|
||||
} catch {
|
||||
print("❌ [MainView] Failed to decode stored groups: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private func requestNotificationPermissions() {
|
||||
Task {
|
||||
do {
|
||||
@@ -332,6 +587,171 @@ struct MainView: View {
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
|
||||
UNUserNotificationCenter.current().add(request)
|
||||
}
|
||||
|
||||
private func restartServer(for id: UUID) async -> ServerActionFeedback {
|
||||
guard let server = servers.first(where: { $0.id == id }) else {
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Failed",
|
||||
message: "The selected server could not be found."
|
||||
)
|
||||
}
|
||||
|
||||
guard server.info?.supportsRestartCommand == true else {
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Unavailable",
|
||||
message: "\(server.hostname) does not support remote reboot via the API."
|
||||
)
|
||||
}
|
||||
|
||||
guard let apiKey = KeychainHelper.loadApiKey(for: server.hostname)?.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
!apiKey.isEmpty else {
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Failed",
|
||||
message: "No API key is configured for \(server.hostname)."
|
||||
)
|
||||
}
|
||||
|
||||
guard let baseURL = URL(string: "https://\(server.hostname)") else {
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Failed",
|
||||
message: "The server URL for \(server.hostname) is invalid."
|
||||
)
|
||||
}
|
||||
|
||||
restartingServerID = id
|
||||
defer { restartingServerID = nil }
|
||||
|
||||
do {
|
||||
let api: AnyServerAPI
|
||||
if let versionString = server.info?.apiVersion,
|
||||
let versionedAPI = APIFactory.createAPI(baseURL: baseURL, versionString: versionString) {
|
||||
api = versionedAPI
|
||||
} else {
|
||||
api = try await APIFactory.detectAndCreateAPI(baseURL: baseURL, apiKey: apiKey)
|
||||
}
|
||||
try await api.restartServer(apiKey: apiKey)
|
||||
await PingService.suppressChecks(for: server.hostname, duration: 90)
|
||||
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Requested",
|
||||
message: "The reboot command was sent to \(server.hostname). The host may become unavailable briefly while it restarts."
|
||||
)
|
||||
} catch let error as URLError where Self.isExpectedRestartDisconnect(error) {
|
||||
await PingService.suppressChecks(for: server.hostname, duration: 90)
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Requested",
|
||||
message: "The reboot command appears to have been accepted by \(server.hostname). The connection dropped while the host was going away, which is expected during a reboot."
|
||||
)
|
||||
} catch APIError.httpError(404, let message) {
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Unavailable",
|
||||
message: message ?? "\(server.hostname) returned 404 for /api/v2/server/reboot."
|
||||
)
|
||||
} catch {
|
||||
return ServerActionFeedback(
|
||||
title: "Reboot Failed",
|
||||
message: error.localizedDescription
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private static func isExpectedRestartDisconnect(_ error: URLError) -> Bool {
|
||||
switch error.code {
|
||||
case .timedOut,
|
||||
.cannotConnectToHost,
|
||||
.networkConnectionLost,
|
||||
.notConnectedToInternet,
|
||||
.cannotFindHost,
|
||||
.dnsLookupFailed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct SidebarMaterialView: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> NSVisualEffectView {
|
||||
let view = NSVisualEffectView()
|
||||
view.blendingMode = .behindWindow
|
||||
view.material = .sidebar
|
||||
view.state = .active
|
||||
return view
|
||||
}
|
||||
|
||||
func updateNSView(_ nsView: NSVisualEffectView, context: Context) {
|
||||
nsView.state = .active
|
||||
}
|
||||
}
|
||||
|
||||
private struct GroupDropDelegate: DropDelegate {
|
||||
enum Placement {
|
||||
case before
|
||||
case after
|
||||
}
|
||||
|
||||
let targetGroup: ServerGroup
|
||||
@Binding var groups: [ServerGroup]
|
||||
@Binding var draggedGroupID: UUID?
|
||||
@Binding var indicator: GroupDropIndicator?
|
||||
|
||||
func dropEntered(info: DropInfo) {
|
||||
updateIndicator(with: info)
|
||||
}
|
||||
|
||||
func dropUpdated(info: DropInfo) -> DropProposal? {
|
||||
updateIndicator(with: info)
|
||||
return DropProposal(operation: .move)
|
||||
}
|
||||
|
||||
func dropExited(info: DropInfo) {
|
||||
indicator = nil
|
||||
}
|
||||
|
||||
func performDrop(info: DropInfo) -> Bool {
|
||||
defer {
|
||||
draggedGroupID = nil
|
||||
indicator = nil
|
||||
}
|
||||
|
||||
guard
|
||||
let draggedGroupID,
|
||||
draggedGroupID != targetGroup.id,
|
||||
let fromIndex = groups.firstIndex(where: { $0.id == draggedGroupID }),
|
||||
let toIndex = groups.firstIndex(where: { $0.id == targetGroup.id })
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
let placement = placement(for: info)
|
||||
let proposedIndex = placement == .after ? toIndex + 1 : toIndex
|
||||
groups.move(
|
||||
fromOffsets: IndexSet(integer: fromIndex),
|
||||
toOffset: proposedIndex > fromIndex ? proposedIndex + 1 : proposedIndex
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
private func updateIndicator(with info: DropInfo) {
|
||||
guard let draggedGroupID, draggedGroupID != targetGroup.id else {
|
||||
indicator = nil
|
||||
return
|
||||
}
|
||||
|
||||
indicator = GroupDropIndicator(
|
||||
groupID: targetGroup.id,
|
||||
placement: placement(for: info)
|
||||
)
|
||||
}
|
||||
|
||||
private func placement(for info: DropInfo) -> Placement {
|
||||
info.location.y > 12 ? .after : .before
|
||||
}
|
||||
}
|
||||
|
||||
private struct GroupDropIndicator: Equatable {
|
||||
let groupID: UUID
|
||||
let placement: GroupDropDelegate.Placement
|
||||
}
|
||||
|
||||
#Preview {
|
||||
|
||||
@@ -7,9 +7,18 @@
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct ServerActionFeedback: Identifiable {
|
||||
let id = UUID()
|
||||
let title: String
|
||||
let message: String
|
||||
}
|
||||
|
||||
struct ServerDetailView: View {
|
||||
@Binding var server: Server
|
||||
var isFetching: Bool
|
||||
var canRestart: Bool = false
|
||||
var isRestarting: Bool = false
|
||||
var onRestart: (() async -> ServerActionFeedback)? = nil
|
||||
@AppStorage("showIntervalIndicator") private var showIntervalIndicator: Bool = true
|
||||
@AppStorage("refreshInterval") private var refreshInterval: Int = 60
|
||||
|
||||
@@ -18,7 +27,9 @@ struct ServerDetailView: View {
|
||||
}
|
||||
|
||||
@State private var progress: Double = 0
|
||||
let timer = Timer.publish(every: 1.0 / 60.0, on: .main, in: .common).autoconnect()
|
||||
@State private var showRestartSheet = false
|
||||
@State private var restartFeedback: ServerActionFeedback?
|
||||
private let indicatorTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
@@ -33,7 +44,13 @@ struct ServerDetailView: View {
|
||||
VStack(spacing: 0) {
|
||||
Spacer().frame(height: 6)
|
||||
TabView {
|
||||
GeneralView(server: resolvedBinding)
|
||||
GeneralView(
|
||||
server: resolvedBinding,
|
||||
canRestart: canRestart,
|
||||
isRestarting: isRestarting
|
||||
) {
|
||||
showRestartSheet = true
|
||||
}
|
||||
.tabItem {
|
||||
Text("General").unredacted()
|
||||
}
|
||||
@@ -57,13 +74,51 @@ struct ServerDetailView: View {
|
||||
}
|
||||
.padding(0)
|
||||
}
|
||||
.onReceive(timer) { _ in
|
||||
.overlay(alignment: .bottomTrailing) {
|
||||
if let feedback = restartFeedback {
|
||||
RestartFeedbackBanner(
|
||||
feedback: feedback,
|
||||
onDismiss: {
|
||||
restartFeedback = nil
|
||||
}
|
||||
)
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
.onReceive(indicatorTimer) { _ in
|
||||
guard showIntervalIndicator else { return }
|
||||
withAnimation(.linear(duration: 1.0 / 60.0)) {
|
||||
progress += 1.0 / (Double(refreshInterval) * 60.0)
|
||||
withAnimation(.linear(duration: 1)) {
|
||||
progress += 1.0 / Double(refreshInterval)
|
||||
if progress >= 1 { progress = 0 }
|
||||
}
|
||||
}
|
||||
.onChange(of: refreshInterval) { _, _ in
|
||||
progress = 0
|
||||
}
|
||||
.onChange(of: showIntervalIndicator) { _, isVisible in
|
||||
if !isVisible {
|
||||
progress = 0
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $showRestartSheet) {
|
||||
RestartConfirmationSheet(
|
||||
hostname: server.hostname,
|
||||
isRestarting: isRestarting,
|
||||
onCancel: {
|
||||
showRestartSheet = false
|
||||
},
|
||||
onConfirm: {
|
||||
guard let onRestart else { return }
|
||||
showRestartSheet = false
|
||||
Task {
|
||||
let feedback = await onRestart()
|
||||
await MainActor.run {
|
||||
restartFeedback = feedback
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private var resolvedBinding: Binding<Server> {
|
||||
@@ -81,7 +136,8 @@ struct ServerDetailView: View {
|
||||
#Preview {
|
||||
ServerDetailView(
|
||||
server: .constant(Server(id: UUID(), hostname: "preview.example.com", info: ServerInfo.placeholder)),
|
||||
isFetching: false
|
||||
isFetching: false,
|
||||
canRestart: true
|
||||
)
|
||||
}
|
||||
|
||||
@@ -97,3 +153,67 @@ private struct LoadingBadge: View {
|
||||
.background(.ultraThinMaterial, in: Capsule())
|
||||
}
|
||||
}
|
||||
|
||||
private struct RestartConfirmationSheet: View {
|
||||
let hostname: String
|
||||
let isRestarting: Bool
|
||||
let onCancel: () -> Void
|
||||
let onConfirm: () -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("Reboot this server?")
|
||||
.font(.title3.weight(.semibold))
|
||||
|
||||
Text("This will send a reboot command to \(hostname).")
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
HStack {
|
||||
Spacer()
|
||||
|
||||
Button("Cancel") {
|
||||
onCancel()
|
||||
}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
.disabled(isRestarting)
|
||||
|
||||
Button("Reboot", role: .destructive) {
|
||||
onConfirm()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(isRestarting)
|
||||
}
|
||||
}
|
||||
.padding(24)
|
||||
.frame(width: 420)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RestartFeedbackBanner: View {
|
||||
let feedback: ServerActionFeedback
|
||||
let onDismiss: () -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text(feedback.title)
|
||||
.font(.headline)
|
||||
|
||||
Text(feedback.message)
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
HStack {
|
||||
Spacer()
|
||||
|
||||
Button("OK") {
|
||||
onDismiss()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 360, alignment: .leading)
|
||||
.padding(24)
|
||||
.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
|
||||
.shadow(radius: 12)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,11 @@ struct ServerFormView: View {
|
||||
var mode: Mode
|
||||
|
||||
@Binding var servers: [Server]
|
||||
@Binding var groups: [ServerGroup]
|
||||
|
||||
@State private var hostname: String
|
||||
@State private var apiKey: String
|
||||
@State private var selectedGroupID: UUID?
|
||||
@State private var connectionOK: Bool = false
|
||||
@State private var testingConnection: Bool = false
|
||||
@State private var connectionError: String = ""
|
||||
@@ -29,25 +31,30 @@ struct ServerFormView: View {
|
||||
init(
|
||||
mode: Mode,
|
||||
servers: Binding<[Server]>,
|
||||
groups: Binding<[ServerGroup]>,
|
||||
dismiss: @escaping () -> Void
|
||||
) {
|
||||
self.mode = mode
|
||||
self._servers = servers
|
||||
self._groups = groups
|
||||
|
||||
switch mode {
|
||||
case .add:
|
||||
self._hostname = State(initialValue: "")
|
||||
self._apiKey = State(initialValue: "")
|
||||
self._selectedGroupID = State(initialValue: nil)
|
||||
case .edit(let server):
|
||||
self._hostname = State(initialValue: server.hostname)
|
||||
self._apiKey = State(initialValue: KeychainHelper.loadApiKey(for: server.hostname) ?? "")
|
||||
self._selectedGroupID = State(initialValue: server.groupID)
|
||||
self._connectionOK = State(initialValue: true)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("Edit Server")
|
||||
Text(modeTitle)
|
||||
.font(.headline)
|
||||
|
||||
TextField("Hostname", text: $hostname)
|
||||
@@ -57,6 +64,14 @@ struct ServerFormView: View {
|
||||
SecureField("API Key", text: $apiKey)
|
||||
.textFieldStyle(RoundedBorderTextFieldStyle())
|
||||
|
||||
Picker("Group", selection: $selectedGroupID) {
|
||||
Text("No Group").tag(nil as UUID?)
|
||||
ForEach(groups) { group in
|
||||
Text(group.name).tag(Optional(group.id))
|
||||
}
|
||||
}
|
||||
.pickerStyle(.menu)
|
||||
|
||||
if !connectionError.isEmpty {
|
||||
Text(connectionError)
|
||||
.foregroundColor(.red)
|
||||
@@ -77,8 +92,6 @@ struct ServerFormView: View {
|
||||
|
||||
Button("Save") {
|
||||
saveServer()
|
||||
updateServer()
|
||||
saveServers()
|
||||
dismiss()
|
||||
}
|
||||
.disabled(hostname.isEmpty || apiKey.isEmpty || !connectionOK)
|
||||
@@ -93,6 +106,8 @@ struct ServerFormView: View {
|
||||
print("serve \(server)")
|
||||
hostname = server.hostname
|
||||
apiKey = KeychainHelper.loadApiKey(for: server.hostname) ?? ""
|
||||
selectedGroupID = server.groupID
|
||||
connectionOK = true
|
||||
print("💡 Loaded server: \(hostname)")
|
||||
}
|
||||
}
|
||||
@@ -205,40 +220,22 @@ struct ServerFormView: View {
|
||||
switch mode {
|
||||
case .add:
|
||||
print("adding server")
|
||||
let newServer = Server(hostname: trimmedHost)
|
||||
let newServer = Server(hostname: trimmedHost, groupID: selectedGroupID)
|
||||
servers.append(newServer)
|
||||
KeychainHelper.saveApiKey(trimmedKey, for: trimmedHost)
|
||||
saveServers()
|
||||
case .edit(let oldServer):
|
||||
if let index = servers.firstIndex(where: { $0.id == oldServer.id }) {
|
||||
let oldHostname = servers[index].hostname
|
||||
servers[index].hostname = trimmedHost
|
||||
servers[index].groupID = selectedGroupID
|
||||
if oldHostname != trimmedHost {
|
||||
KeychainHelper.deleteApiKey(for: oldHostname)
|
||||
}
|
||||
KeychainHelper.saveApiKey(trimmedKey, for: trimmedHost)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func updateServer() {
|
||||
print ("in edit server")
|
||||
guard case let .edit(server) = mode else {
|
||||
return
|
||||
}
|
||||
|
||||
if let index = servers.firstIndex(where: { $0.id == server.id }) {
|
||||
// Only replace hostname if changed
|
||||
let oldHostname = servers[index].hostname
|
||||
servers[index].hostname = hostname
|
||||
|
||||
// Update Keychain
|
||||
if oldHostname != hostname {
|
||||
KeychainHelper.deleteApiKey(for: oldHostname)
|
||||
}
|
||||
KeychainHelper.saveApiKey(apiKey, for: hostname)
|
||||
saveServers()
|
||||
}
|
||||
saveServers()
|
||||
}
|
||||
|
||||
private func saveServers() {
|
||||
@@ -265,6 +262,9 @@ struct ServerFormView: View {
|
||||
servers: .constant([
|
||||
Server(hostname: "example.com")
|
||||
]),
|
||||
groups: .constant([
|
||||
ServerGroup(name: "Production")
|
||||
]),
|
||||
dismiss: {}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import SwiftUI
|
||||
|
||||
struct GeneralView: View {
|
||||
@Binding var server: Server
|
||||
var canRestart: Bool = false
|
||||
var isRestarting: Bool = false
|
||||
var onRestart: (() -> Void)? = nil
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
@@ -117,6 +120,33 @@ struct GeneralView: View {
|
||||
monospaced: true
|
||||
)
|
||||
}
|
||||
|
||||
if canRestart, let onRestart {
|
||||
TableRowView(showDivider: false) {
|
||||
Text("Actions")
|
||||
} value: {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Button(role: .destructive) {
|
||||
onRestart()
|
||||
} label: {
|
||||
if isRestarting {
|
||||
HStack(spacing: 8) {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
Text("Rebooting…")
|
||||
}
|
||||
} else {
|
||||
Label("Reboot Server", systemImage: "arrow.clockwise.circle")
|
||||
}
|
||||
}
|
||||
.disabled(isRestarting)
|
||||
|
||||
Text("Sends a reboot command to the selected host.")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.frame(minHeight: geometry.size.height, alignment: .top)
|
||||
@@ -132,7 +162,7 @@ struct GeneralView: View {
|
||||
@State var previewServer = Server(hostname: "example.com", info: .placeholder)
|
||||
|
||||
var body: some View {
|
||||
GeneralView(server: $previewServer)
|
||||
GeneralView(server: $previewServer, canRestart: true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
30
Sparkle/appcast.xml
vendored
30
Sparkle/appcast.xml
vendored
@@ -3,28 +3,28 @@
|
||||
<channel>
|
||||
<title>iKeyMon</title>
|
||||
<item>
|
||||
<title>26.1.6</title>
|
||||
<pubDate>Sun, 19 Apr 2026 15:26:19 +0200</pubDate>
|
||||
<sparkle:version>175</sparkle:version>
|
||||
<sparkle:shortVersionString>26.1.6</sparkle:shortVersionString>
|
||||
<title>26.1.9</title>
|
||||
<pubDate>Sun, 19 Apr 2026 23:04:07 +0200</pubDate>
|
||||
<sparkle:version>181</sparkle:version>
|
||||
<sparkle:shortVersionString>26.1.9</sparkle:shortVersionString>
|
||||
<sparkle:minimumSystemVersion>15.2</sparkle:minimumSystemVersion>
|
||||
<enclosure url="https://git.24unix.net/tracer/iKeyMon/releases/download/v26.1.6/iKeyMon-26.1.6.zip" length="3063130" type="application/octet-stream" sparkle:edSignature="QPy3zm31ZTXE9grlj7Ul6kEG2t0veODEBjJ/qADM8A88lLJ8V9L4WhNnD8wmM7Urh1O6eZKl1qrCLTk0oo3WBA=="/>
|
||||
<enclosure url="https://git.24unix.net/tracer/iKeyMon/releases/download/v26.1.9/iKeyMon-26.1.9.zip" length="3109488" type="application/octet-stream" sparkle:edSignature="ZV96uUMdYC/X90H3G10FMzmZHKUEWpe1geSe/5IBJ7EOCUmx7Mz352i6VMWumFnCtDD4jHo173W9eySUX9KvDA=="/>
|
||||
</item>
|
||||
<item>
|
||||
<title>26.1.5</title>
|
||||
<pubDate>Sun, 19 Apr 2026 12:09:33 +0200</pubDate>
|
||||
<sparkle:version>173</sparkle:version>
|
||||
<sparkle:shortVersionString>26.1.5</sparkle:shortVersionString>
|
||||
<title>26.1.8</title>
|
||||
<pubDate>Sun, 19 Apr 2026 22:50:15 +0200</pubDate>
|
||||
<sparkle:version>179</sparkle:version>
|
||||
<sparkle:shortVersionString>26.1.8</sparkle:shortVersionString>
|
||||
<sparkle:minimumSystemVersion>15.2</sparkle:minimumSystemVersion>
|
||||
<enclosure url="https://git.24unix.net/tracer/iKeyMon/releases/download/v26.1.5/iKeyMon-26.1.5.zip" length="3065231" type="application/octet-stream" sparkle:edSignature="HVV7iZ4eyJC1VMh2q4GUoAESZnk4HoFU00QlA9qM4X4dJAT5oBEVB55m4wuF4u9iVFAeohkB0vleLlV39mxrBA=="/>
|
||||
<enclosure url="https://git.24unix.net/tracer/iKeyMon/releases/download/v26.1.8/iKeyMon-26.1.8.zip" length="3108005" type="application/octet-stream" sparkle:edSignature="OyoweSuRk5kusKUlqKQudZjrHkw5UPrLkix+ccpKphO1en2XdtQZa61hnA6HwcHM302jb+YlvN8n9f2Zkr9GBg=="/>
|
||||
</item>
|
||||
<item>
|
||||
<title>26.1.3</title>
|
||||
<pubDate>Sun, 19 Apr 2026 11:53:25 +0200</pubDate>
|
||||
<sparkle:version>170</sparkle:version>
|
||||
<sparkle:shortVersionString>26.1.4</sparkle:shortVersionString>
|
||||
<title>26.1.7</title>
|
||||
<pubDate>Sun, 19 Apr 2026 16:54:42 +0200</pubDate>
|
||||
<sparkle:version>177</sparkle:version>
|
||||
<sparkle:shortVersionString>26.1.7</sparkle:shortVersionString>
|
||||
<sparkle:minimumSystemVersion>15.2</sparkle:minimumSystemVersion>
|
||||
<enclosure url="https://git.24unix.net/tracer/iKeyMon/releases/download/v26.1.4/iKeyMon-26.1.4.zip" length="3065263" type="application/octet-stream" sparkle:edSignature="kDxHy5KsxeCYz3N4aIEiZAFnqz6lLg4dHCLG6FL+j37xEpFmZM0lfHL2A15Jg936GeE+iGf6WrQJFInhHAvGDg=="/>
|
||||
<enclosure url="https://git.24unix.net/tracer/iKeyMon/releases/download/v26.1.7/iKeyMon-26.1.7.zip" length="3106520" type="application/octet-stream" sparkle:edSignature="xuNlxCsTtVgroriFU7fphcfHxAEC8cpd6tHnHMXknJ2jvKm27ShQMqjSW2jdqNAz0a0kNtPM8HwTL+e6nvUyCQ=="/>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>
|
||||
@@ -322,7 +322,7 @@
|
||||
CODE_SIGN_ENTITLEMENTS = iKeyMon.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 175;
|
||||
CURRENT_PROJECT_VERSION = 181;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"Preview Content\"";
|
||||
DEVELOPMENT_TEAM = Q5486ZVAFT;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -337,7 +337,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 26.1.6;
|
||||
MARKETING_VERSION = 26.1.9;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.24unix.iKeyMon;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -353,7 +353,7 @@
|
||||
CODE_SIGN_ENTITLEMENTS = iKeyMon.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 175;
|
||||
CURRENT_PROJECT_VERSION = 181;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"Preview Content\"";
|
||||
DEVELOPMENT_TEAM = Q5486ZVAFT;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -368,7 +368,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 26.1.6;
|
||||
MARKETING_VERSION = 26.1.9;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.24unix.iKeyMon;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"marketing_version": "26.1.6"
|
||||
"marketing_version": "26.1.9"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user