Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions DockhandMobile.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@
F854ED0C103528EC1A4988AC /* EnvironmentHeaderBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87D71C8FB475456C871903FB /* EnvironmentHeaderBar.swift */; };
A1D4A7E25C0B4F6E9A3C2B11 /* AdaptiveActionGrid.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1D4A7E25C0B4F6E9A3C2B12 /* AdaptiveActionGrid.swift */; };
FE2A71ABBC45203166737B6E /* DockhandService+Decoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6945D3BE7FFCE50A45EE56BC /* DockhandService+Decoding.swift */; };
EA2200000000000000000000 /* ServerSyncRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000000; };
EA2200000000000000000001 /* SyncedServerCredentials.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000001; };
EA2200000000000000000002 /* ServerSyncStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000002; };
EA2200000000000000000003 /* ServerSyncSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000003; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -90,6 +94,10 @@
EF70FDD79036BE973B27B8D1 /* ContainerShellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerShellView.swift; sourceTree = "<group>"; };
F0976C1D3ECF9207F9267361 /* .gitkeep */ = {isa = PBXFileReference; lastKnownFileType = text; name = .gitkeep; path = es.lproj/.gitkeep; sourceTree = "<group>"; };
FAE66F21FC999D77378C2C04 /* ContainerShellStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerShellStore.swift; sourceTree = "<group>"; };
EA1100000000000000000000 /* ServerSyncRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSyncRecord.swift; sourceTree = "<group>"; };
EA1100000000000000000001 /* SyncedServerCredentials.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncedServerCredentials.swift; sourceTree = "<group>"; };
EA1100000000000000000002 /* ServerSyncStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSyncStore.swift; sourceTree = "<group>"; };
EA1100000000000000000003 /* ServerSyncSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSyncSettingsView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -244,6 +252,9 @@
E5A1342B619AADBFCAF7582E /* DockhandService.swift */,
6945D3BE7FFCE50A45EE56BC /* DockhandService+Decoding.swift */,
08E6CB656D0F64ACB6AFBAC0 /* KeychainStore.swift */,
EA1100000000000000000002 /* ServerSyncStore.swift */,
EA1100000000000000000001 /* SyncedServerCredentials.swift */,
EA1100000000000000000000 /* ServerSyncRecord.swift */,
3A1F5D851E40D36A5154376B /* PreferencesStore.swift */,
);
path = Services;
Expand All @@ -264,6 +275,7 @@
children = (
C0A1B2C3D4E5F60718293A4C /* CustomHeadersEditor.swift */,
13E28C30131DD132BCF62665 /* SettingsView.swift */,
EA1100000000000000000003 /* ServerSyncSettingsView.swift */,
);
path = Settings;
sourceTree = "<group>";
Expand Down Expand Up @@ -382,6 +394,10 @@
A814D3A2D9614875BAFF6C4A /* ImagesStore.swift in Sources */,
4866D6323DEB9849B27209D2 /* ImagesView.swift in Sources */,
D259E02834327E2FBF25E5D2 /* KeychainStore.swift in Sources */,
EA2200000000000000000003 /* ServerSyncSettingsView.swift in Sources */,
EA2200000000000000000002 /* ServerSyncStore.swift in Sources */,
EA2200000000000000000001 /* SyncedServerCredentials.swift in Sources */,
EA2200000000000000000000 /* ServerSyncRecord.swift in Sources */,
AB608708755DE5D3031BCBCE /* PreferencesStore.swift in Sources */,
C0A1B2C3D4E5F60718293A4B /* CustomHeadersEditor.swift in Sources */,
B6C034E5D85C2DDB6C9100CC /* SettingsView.swift in Sources */,
Expand Down Expand Up @@ -516,6 +532,7 @@
"CODE_SIGN_IDENTITY" = "iPhone Developer";
"CURRENT_PROJECT_VERSION" = 18;
"DEVELOPMENT_TEAM" = 8DA225EN79;
CODE_SIGN_ENTITLEMENTS = DockhandMobile/DockhandMobile.entitlements;
"GENERATE_INFOPLIST_FILE" = NO;
"INFOPLIST_FILE" = "DockhandMobile/Info.plist";
"LD_RUNPATH_SEARCH_PATHS" = (
Expand All @@ -540,6 +557,7 @@
"CODE_SIGN_IDENTITY" = "iPhone Developer";
"CURRENT_PROJECT_VERSION" = 18;
"DEVELOPMENT_TEAM" = 8DA225EN79;
CODE_SIGN_ENTITLEMENTS = DockhandMobile/DockhandMobile.entitlements;
"GENERATE_INFOPLIST_FILE" = NO;
"INFOPLIST_FILE" = "DockhandMobile/Info.plist";
"LD_RUNPATH_SEARCH_PATHS" = (
Expand Down
69 changes: 60 additions & 9 deletions DockhandMobile/App/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Observation
struct DockhandConnectionScope: Hashable, Sendable {
var profileID: String?
var environmentID: Int?
var revision: Int = 0
}

enum DockhandServerAddress {
Expand Down Expand Up @@ -35,6 +36,9 @@ enum DockhandServerAddress {
@MainActor
@Observable
final class AppModel {
let serverSync = ServerSyncStore()
private var syncConnectionRevision = 0
private var activeSyncPending = false
var serverProfiles: [DockhandServerProfile]
var selectedProfileID: String?
var token: String
Expand Down Expand Up @@ -91,7 +95,8 @@ final class AppModel {
}

var normalizedBaseURL: URL? {
selectedProfile.flatMap { DockhandServerAddress.normalizedURL(from: $0.baseURL) }
guard !serverSync.pendingCredentials.contains(selectedProfileID ?? "") else { return nil }
return selectedProfile.flatMap { DockhandServerAddress.normalizedURL(from: $0.baseURL) }
}

var selectedEnvironment: Components.Schemas.Environment? {
Expand All @@ -103,7 +108,7 @@ final class AppModel {
}

var connectionScopeID: String {
"\(selectedProfileID ?? "none"):\(selectedEnvironmentID ?? -1)"
"\(selectedProfileID ?? "none"):\(selectedEnvironmentID ?? -1):\(syncConnectionRevision)"
}

/// A remembered environment ID alone is not enough: list tasks must restart
Expand All @@ -113,7 +118,7 @@ final class AppModel {
}

var connectionScope: DockhandConnectionScope {
DockhandConnectionScope(profileID: selectedProfileID, environmentID: selectedEnvironmentID)
DockhandConnectionScope(profileID: selectedProfileID, environmentID: selectedEnvironmentID, revision: syncConnectionRevision)
}

/// Builds a service carrying the active profile's token and custom headers.
Expand All @@ -131,49 +136,60 @@ final class AppModel {
}

func bootstrap() async {
serverSync.onChange = { [weak self] in self?.applySyncedServers() }
serverSync.refresh()
await refreshEnvironments(forceEnvironmentReset: false)
}

/// Persists the profile immediately. Reconnecting runs in the background so
/// an unreachable server never blocks the editor.
@discardableResult
func saveServerProfile(
profileID: String?,
name: String,
baseURLText: String,
token: String,
customHeaders: [DockhandCustomHeader] = [],
makeActive: Bool = true
) {
) -> Bool {
let cleanedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
let cleanedURL = baseURLText.trimmingCharacters(in: .whitespacesAndNewlines)
let resolvedName = cleanedName.isEmpty ? cleanedURL : cleanedName

let targetID = profileID ?? UUID().uuidString
let profile = DockhandServerProfile(id: targetID, name: resolvedName, baseURL: cleanedURL)

do {
try KeychainStore.installSyncedCredentials(
SyncedServerCredentials(token: DockhandToken.normalized(token), headers: DockhandCustomHeaderValidator.sanitized(customHeaders)),
profileID: targetID)
} catch {
serverSync.error = String(localized: "Could not save credentials. Unlock your device and try again.")
return false
}

if let index = serverProfiles.firstIndex(where: { $0.id == targetID }) {
serverProfiles[index] = profile
} else {
serverProfiles.append(profile)
}

serverProfiles.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
PreferencesStore.serverProfiles = serverProfiles
KeychainStore.writeToken(token, profileID: targetID)
KeychainStore.writeCustomHeaders(DockhandCustomHeaderValidator.sanitized(customHeaders), profileID: targetID)

serverSync.save(profile, position: serverProfiles.firstIndex(where: { $0.id == targetID }) ?? 0)
if makeActive || selectedProfileID == nil {
Task { await selectServerProfile(targetID, forceEnvironmentReset: true) }
}
return true
}

func deleteServerProfile(_ profileID: String) async {
if let profile = serverProfiles.first(where: { $0.id == profileID }) { serverSync.delete(profile) }
serverProfiles.removeAll { $0.id == profileID }
PreferencesStore.serverProfiles = serverProfiles
PreferencesStore.removeSelectedEnvironmentID(for: profileID)
PreferencesStore.removeCachedDashboardSnapshots(for: profileID)
KeychainStore.deleteToken(profileID: profileID)
KeychainStore.deleteCustomHeaders(profileID: profileID)
KeychainStore.deleteCredentials(profileID: profileID)

if selectedProfileID == profileID {
selectedProfileID = serverProfiles.first?.id
Expand All @@ -188,6 +204,41 @@ final class AppModel {
}
}

func moveServers(from source: IndexSet, to destination: Int) {
guard (0...serverProfiles.count).contains(destination),
source.allSatisfy({ serverProfiles.indices.contains($0) }) else { return }
var reordered = serverProfiles
let moving = source.sorted().map { reordered[$0] }
for index in source.sorted(by: >) { reordered.remove(at: index) }
reordered.insert(contentsOf: moving, at: destination - source.filter { $0 < destination }.count)
serverProfiles = reordered
PreferencesStore.serverProfiles = reordered
serverSync.reorder(reordered)
}

private func applySyncedServers() {
let profiles = PreferencesStore.serverProfiles
let active = profiles.first(where: { $0.id == selectedProfileID }) ?? profiles.first
let pending = serverSync.pendingCredentials.contains(active?.id ?? "")
let newToken = pending ? "" : active.flatMap { KeychainStore.readToken(profileID: $0.id) } ?? ""
let newHeaders = pending ? [] : active.map { KeychainStore.readCustomHeaders(profileID: $0.id) } ?? []
let changed = pending != activeSyncPending || selectedProfile != active || token != newToken || customHeaders != newHeaders || (pending && !environments.isEmpty)
activeSyncPending = pending
serverProfiles = profiles
guard changed else { return }
syncConnectionRevision += 1
environmentsLoadToken = UUID()
selectedProfileID = active?.id
PreferencesStore.selectedProfileID = active?.id
token = newToken
customHeaders = newHeaders
environments = []
selectedEnvironmentID = active.flatMap { PreferencesStore.selectedEnvironmentID(for: $0.id) }
lastHealthStatus = nil
environmentError = nil
Task { await refreshEnvironments(forceEnvironmentReset: false) }
}

func selectServerProfile(_ profileID: String, forceEnvironmentReset: Bool = false) async {
guard selectedProfileID != profileID || forceEnvironmentReset else { return }

Expand Down
8 changes: 8 additions & 0 deletions DockhandMobile/App/DockhandRootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ struct DockhandRootView: View {
}
await appModel.bootstrap()
}
.task(id: scenePhase) {
guard scenePhase == .active else { return }
appModel.serverSync.foregroundRefresh()
while !Task.isCancelled {
appModel.serverSync.refresh()
do { try await Task.sleep(for: .seconds(5)) } catch { break }
}
}
.onChange(of: scenePhase) { _, phase in
guard phase == .active else { return }
Task { await appModel.recoverConnectionIfNeeded() }
Expand Down
6 changes: 6 additions & 0 deletions DockhandMobile/DockhandMobile.entitlements
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.developer.ubiquity-kvstore-identifier</key>
<string>$(TeamIdentifierPrefix)$(CFBundleIdentifier)</string>
</dict></plist>
40 changes: 40 additions & 0 deletions DockhandMobile/Features/Settings/ServerSyncSettingsView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import SwiftUI

struct ServerSyncSettingsView: View {
let appModel: AppModel
@State private var confirmDisable = false

var body: some View {
VStack(alignment: .leading, spacing: 12) {
Toggle(isOn: Binding(get: { appModel.serverSync.enabled }, set: { enabled in
if enabled {
do { try appModel.serverSync.enable() }
catch { appModel.serverSync.error = String(localized: "Could not enable iCloud sync. Check your iCloud account and iCloud Keychain settings, then try again.") }
} else { confirmDisable = true }
})) {
Label(String(localized: "Sync servers with iCloud"), systemImage: "icloud")
}
Text(String(localized: "Sync server addresses, order, tokens and custom headers across your devices. Credentials use iCloud Keychain. Your selected server and environment stay on this device."))
.font(.footnote)
.foregroundStyle(.secondary)
if !appModel.serverSync.pendingCredentials.isEmpty {
Label(String(localized: "Some server credentials are unavailable. Wait for iCloud Keychain or edit the server."), systemImage: "key.icloud")
.font(.footnote)
}
if let error = appModel.serverSync.error {
Text(error).font(.footnote).foregroundStyle(.red)
}
}
.confirmationDialog(String(localized: "Turn off iCloud sync?"), isPresented: $confirmDisable, titleVisibility: .visible) {
Button(String(localized: "Keep servers on this device")) {
appModel.serverSync.disable(removeLocal: false)
}
Button(String(localized: "Remove servers from this device"), role: .destructive) {
appModel.serverSync.disable(removeLocal: true)
}
Button(String(localized: "Cancel"), role: .cancel) {}
} message: {
Text(String(localized: "Choose whether to keep a local copy. Servers in iCloud and on your other devices will be kept."))
}
}
}
24 changes: 22 additions & 2 deletions DockhandMobile/Features/Settings/SettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ struct SettingsList: View {
)
}
}
.onMove { appModel.moveServers(from: $0, to: $1) }
}

Section {
ServerSyncSettingsView(appModel: appModel)
}

Section(String(localized: "About")) {
Expand All @@ -107,6 +112,7 @@ struct SettingsList: View {
}
.navigationTitle(String(localized: "Settings"))
.toolbar {
ToolbarItem(placement: .topBarLeading) { EditButton() }
ToolbarItem(placement: .topBarTrailing) {
Button {
isAddingServer = true
Expand Down Expand Up @@ -210,6 +216,9 @@ struct SettingsView: View {
statusCard(statusMessage)
}

ServerSyncSettingsView(appModel: appModel)
.padding(16)
.glassEffect(.regular, in: .rect(cornerRadius: 22))
aboutCard
}
.padding()
Expand Down Expand Up @@ -512,6 +521,16 @@ struct SettingsView: View {
}
.buttonStyle(.plain)
.frame(maxWidth: .infinity)
.contextMenu {
if let index = appModel.serverProfiles.firstIndex(where: { $0.id == profile.id }) {
Button(String(localized: "Move up"), systemImage: "arrow.up") {
appModel.moveServers(from: IndexSet(integer: index), to: index - 1)
}.disabled(index == 0)
Button(String(localized: "Move down"), systemImage: "arrow.down") {
appModel.moveServers(from: IndexSet(integer: index), to: index + 2)
}.disabled(index == appModel.serverProfiles.count - 1)
}
}
}
}
}
Expand Down Expand Up @@ -973,15 +992,16 @@ private struct ServerProfileDetailView: View {
}

private func saveProfile() {
appModel.saveServerProfile(
let saved = appModel.saveServerProfile(
profileID: profileID,
name: draftName,
baseURLText: draftBaseURL,
token: draftToken,
customHeaders: draftHeaders.headers,
makeActive: true
)
dismiss()
if saved { dismiss() }
else { statusMessage = appModel.serverSync.error }
}

@MainActor
Expand Down
Loading
Loading