diff --git a/.DS_Store b/.DS_Store
index 9aecd8d..3715dd8 100644
Binary files a/.DS_Store and b/.DS_Store differ
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d927013
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+Secrets.xcconfig
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..b31ee30
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,10 @@
+# IPv64.net iOS
+
+## Design rules
+
+- Colour gradient (`setColorGradient`): only on full screens in the navigation stack, never inside a sheet.
+ While a screen presents a sheet, it switches its own gradient off (`setColorGradient(showSheet ? .clear : .orange)`).
+- Copying text: always `Clipboard.copy(_:sensitive:)` (IPv64/Helpers/Clipboard.swift). It vibrates on success; use `sensitive: true` for keys, tokens and update URLs.
+- Destructive items in a `Menu`: always `DestructiveMenuButton` (IPv64/Helpers/DestructiveMenuButton.swift, red icon and text).
+- Expandable sections (statistics, incidents, events, problems, charts, histories): always `HcCollapsibleSection(title:isExpanded:)` (IPv64/Views/Healthcheck/HealthcheckFormFields.swift, header with a chevron that rotates when open), never a hand-rolled header button or a pushed sub-list. Long lists start collapsed.
+- Swipe actions: icon only (`.labelStyle(.iconOnly)`, the title stays for VoiceOver); a delete action is always red (`role: .destructive`, `.tint(.red)`).
diff --git a/Config.xcconfig b/Config.xcconfig
new file mode 100644
index 0000000..f305d3e
--- /dev/null
+++ b/Config.xcconfig
@@ -0,0 +1,4 @@
+// Build settings of the app target. Secrets come from Secrets.xcconfig (git-ignored):
+// SECNTFY_APP_KEY = NTFY-APP-…
+SECNTFY_APP_KEY =
+#include? "Secrets.xcconfig"
diff --git a/HealthcheckIntents/Info.plist b/HealthcheckIntents/Info.plist
deleted file mode 100644
index 8521c02..0000000
--- a/HealthcheckIntents/Info.plist
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
- NSExtension
-
- NSExtensionAttributes
-
- IntentsRestrictedWhileLocked
-
- IntentsRestrictedWhileProtectedDataUnavailable
-
- IntentsSupported
-
- ConfigurationFourIntent
- ConfigurationIntent
-
-
- NSExtensionPointIdentifier
- com.apple.intents-service
- NSExtensionPrincipalClass
- $(PRODUCT_MODULE_NAME).IntentHandler
-
-
-
diff --git a/HealthcheckIntents/IntentHandler.swift b/HealthcheckIntents/IntentHandler.swift
deleted file mode 100644
index 2fc6341..0000000
--- a/HealthcheckIntents/IntentHandler.swift
+++ /dev/null
@@ -1,196 +0,0 @@
-//
-// IntentHandler.swift
-// HealthcheckIntents
-//
-// Created by Sebastian Rank on 27.01.23.
-//
-
-import Intents
-import SwiftUI
-
-class IntentHandler: INExtension, ConfigurationIntentHandling {
-
- func resolveHealthcheckSymbol1(for intent: ConfigurationIntent) async -> HealthcheckSymbolResolutionResult {
- return .success(with: HealthcheckSymbol(identifier: "", display: ""))
- }
-
-
- func provideHealthcheckSymbol1OptionsCollection(for intent: ConfigurationIntent) async throws -> INObjectCollection {
- var symbols:[HealthcheckSymbol] = []
-
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 2)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let shrinkedEventList = hcr.domain.sorted { $0.name > $1.name }
- shrinkedEventList.forEach { health in
- let healthStatus = HealthcheckSymbol(identifier: health.healthtoken, display: health.name)
- healthStatus.events = []
- health.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
-
- symbols.append(healthStatus)
- }
- // Create a collection with the array of characters.
- let collection = INObjectCollection(items: symbols)
- print("Collection")
- // Call the completion handler, passing the collection.
- return collection
- }
-
- func resolveHealthcheckSymbol2(for intent: ConfigurationIntent) async -> HealthcheckSymbolResolutionResult {
- return .success(with: HealthcheckSymbol(identifier: "", display: ""))
- }
-
-
- func provideHealthcheckSymbol2OptionsCollection(for intent: ConfigurationIntent) async throws -> INObjectCollection {
- var symbols:[HealthcheckSymbol] = []
-
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 2)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let shrinkedEventList = hcr.domain.sorted { $0.name > $1.name }
- shrinkedEventList.forEach { health in
- let healthStatus = HealthcheckSymbol(identifier: health.healthtoken, display: health.name)
- healthStatus.events = []
- health.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
-
- symbols.append(healthStatus)
- }
- // Create a collection with the array of characters.
- let collection = INObjectCollection(items: symbols)
- print("Collection")
- // Call the completion handler, passing the collection.
- return collection
- }
-
-}
-
-class IntentFourHandler: INExtension, ConfigurationFourIntentHandling {
-
- func resolveHealthcheckSymbol11(for intent: ConfigurationFourIntent) async -> HealthcheckSymbolResolutionResult {
- return .success(with: HealthcheckSymbol(identifier: "", display: ""))
- }
-
- func provideHealthcheckSymbol11OptionsCollection(for intent: ConfigurationFourIntent) async throws -> INObjectCollection {
- var symbols:[HealthcheckSymbol] = []
-
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 4)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let shrinkedEventList = hcr.domain.sorted { $0.name > $1.name }
- shrinkedEventList.forEach { health in
- let healthStatus = HealthcheckSymbol(identifier: health.healthtoken, display: health.name)
- healthStatus.events = []
- health.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
-
- symbols.append(healthStatus)
- }
- // Create a collection with the array of characters.
- let collection = INObjectCollection(items: symbols)
- print("Collection")
- // Call the completion handler, passing the collection.
- return collection
- }
-
- func resolveHealthcheckSymbol12(for intent: ConfigurationFourIntent) async -> HealthcheckSymbolResolutionResult {
- return .success(with: HealthcheckSymbol(identifier: "", display: ""))
- }
-
-
- func provideHealthcheckSymbol12OptionsCollection(for intent: ConfigurationFourIntent) async throws -> INObjectCollection {
- var symbols:[HealthcheckSymbol] = []
-
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 4)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let shrinkedEventList = hcr.domain.sorted { $0.name > $1.name }
- shrinkedEventList.forEach { health in
- let healthStatus = HealthcheckSymbol(identifier: health.healthtoken, display: health.name)
- healthStatus.events = []
- health.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
-
- symbols.append(healthStatus)
- }
- // Create a collection with the array of characters.
- let collection = INObjectCollection(items: symbols)
- print("Collection")
- // Call the completion handler, passing the collection.
- return collection
- }
-
- func resolveHealthcheckSymbol21(for intent: ConfigurationFourIntent) async -> HealthcheckSymbolResolutionResult {
- return .success(with: HealthcheckSymbol(identifier: "", display: ""))
- }
-
-
- func provideHealthcheckSymbol21OptionsCollection(for intent: ConfigurationFourIntent) async throws -> INObjectCollection {
- var symbols:[HealthcheckSymbol] = []
-
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 4)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let shrinkedEventList = hcr.domain.sorted { $0.name > $1.name }
- shrinkedEventList.forEach { health in
- let healthStatus = HealthcheckSymbol(identifier: health.healthtoken, display: health.name)
- healthStatus.events = []
- health.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
-
- symbols.append(healthStatus)
- }
- // Create a collection with the array of characters.
- let collection = INObjectCollection(items: symbols)
- print("Collection")
- // Call the completion handler, passing the collection.
- return collection
- }
-
- func resolveHealthcheckSymbol22(for intent: ConfigurationFourIntent) async -> HealthcheckSymbolResolutionResult {
- return .success(with: HealthcheckSymbol(identifier: "", display: ""))
- }
-
-
- func provideHealthcheckSymbol22OptionsCollection(for intent: ConfigurationFourIntent) async throws -> INObjectCollection {
- var symbols:[HealthcheckSymbol] = []
-
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 4)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let shrinkedEventList = hcr.domain.sorted { $0.name > $1.name }
- shrinkedEventList.forEach { health in
- let healthStatus = HealthcheckSymbol(identifier: health.healthtoken, display: health.name)
- healthStatus.events = []
- health.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
-
- symbols.append(healthStatus)
- }
- // Create a collection with the array of characters.
- let collection = INObjectCollection(items: symbols)
- print("Collection")
- // Call the completion handler, passing the collection.
- return collection
- }
-
-}
diff --git a/HealthcheckWidget/.DS_Store b/HealthcheckWidget/.DS_Store
deleted file mode 100644
index 6fc56cf..0000000
Binary files a/HealthcheckWidget/.DS_Store and /dev/null differ
diff --git a/HealthcheckWidget/Assets.xcassets/AppIcon.appiconset/Contents.json b/HealthcheckWidget/Assets.xcassets/AppIcon.appiconset/Contents.json
deleted file mode 100644
index 13613e3..0000000
--- a/HealthcheckWidget/Assets.xcassets/AppIcon.appiconset/Contents.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "images" : [
- {
- "idiom" : "universal",
- "platform" : "ios",
- "size" : "1024x1024"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/HealthcheckWidget/HealthcheckWidget.intentdefinition b/HealthcheckWidget/HealthcheckWidget.intentdefinition
deleted file mode 100644
index 6ef7f0c..0000000
--- a/HealthcheckWidget/HealthcheckWidget.intentdefinition
+++ /dev/null
@@ -1,622 +0,0 @@
-
-
-
-
- INEnums
-
- INIntentDefinitionModelVersion
- 1.2
- INIntentDefinitionNamespace
- 88xZPY
- INIntentDefinitionSystemVersion
- 23C5030f
- INIntentDefinitionToolsBuildVersion
- 15A507
- INIntentDefinitionToolsVersion
- 15.0.1
- INIntents
-
-
- INIntentCategory
- information
- INIntentDescriptionID
- tVvJ9c
- INIntentEligibleForWidgets
-
- INIntentIneligibleForSuggestions
-
- INIntentLastParameterTag
- 6
- INIntentName
- Configuration
- INIntentParameters
-
-
- INIntentParameterConfigurable
-
- INIntentParameterCustomDisambiguation
-
- INIntentParameterDisplayName
- Healthcheck 1
- INIntentParameterDisplayNameID
- GTCLgP
- INIntentParameterDisplayPriority
- 1
- INIntentParameterName
- healthcheckSymbol1
- INIntentParameterObjectType
- HealthcheckSymbol
- INIntentParameterObjectTypeNamespace
- 88xZPY
- INIntentParameterPromptDialogs
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Configuration
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Primary
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- There are ${count} options matching ‘${healthcheckSymbol1}’.
- INIntentParameterPromptDialogFormatStringID
- heejvT
- INIntentParameterPromptDialogType
- DisambiguationIntroduction
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- Just to confirm, you wanted ‘${healthcheckSymbol1}’?
- INIntentParameterPromptDialogFormatStringID
- Ekjkf0
- INIntentParameterPromptDialogType
- Confirmation
-
-
- INIntentParameterSupportsDynamicEnumeration
-
- INIntentParameterSupportsResolution
-
- INIntentParameterTag
- 3
- INIntentParameterType
- Object
-
-
- INIntentParameterConfigurable
-
- INIntentParameterCustomDisambiguation
-
- INIntentParameterDisplayName
- Healthcheck 2
- INIntentParameterDisplayNameID
- 1Pknvs
- INIntentParameterDisplayPriority
- 2
- INIntentParameterName
- healthcheckSymbol2
- INIntentParameterObjectType
- HealthcheckSymbol
- INIntentParameterObjectTypeNamespace
- 88xZPY
- INIntentParameterPromptDialogs
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Configuration
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Primary
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- There are ${count} options matching ‘${healthcheckSymbol2}’.
- INIntentParameterPromptDialogFormatStringID
- kmi5xp
- INIntentParameterPromptDialogType
- DisambiguationIntroduction
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- Just to confirm, you wanted ‘${healthcheckSymbol2}’?
- INIntentParameterPromptDialogFormatStringID
- 7XRqtQ
- INIntentParameterPromptDialogType
- Confirmation
-
-
- INIntentParameterSupportsDynamicEnumeration
-
- INIntentParameterSupportsResolution
-
- INIntentParameterTag
- 4
- INIntentParameterType
- Object
-
-
- INIntentResponse
-
- INIntentResponseCodes
-
-
- INIntentResponseCodeName
- success
- INIntentResponseCodeSuccess
-
-
-
- INIntentResponseCodeName
- failure
-
-
-
- INIntentTitle
- Configuration
- INIntentTitleID
- gpCwrM
- INIntentType
- Custom
- INIntentVerb
- View
-
-
- INIntentCategory
- information
- INIntentDescriptionID
- 8wbr0p
- INIntentEligibleForWidgets
-
- INIntentIneligibleForSuggestions
-
- INIntentLastParameterTag
- 8
- INIntentName
- ConfigurationFour
- INIntentParameters
-
-
- INIntentParameterConfigurable
-
- INIntentParameterCustomDisambiguation
-
- INIntentParameterDisplayName
- Healthcheck 11
- INIntentParameterDisplayNameID
- mHBNN8
- INIntentParameterDisplayPriority
- 1
- INIntentParameterName
- healthcheckSymbol11
- INIntentParameterObjectType
- HealthcheckSymbol
- INIntentParameterObjectTypeNamespace
- 88xZPY
- INIntentParameterPromptDialogs
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Configuration
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Primary
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- There are ${count} options matching ‘${healthcheckSymbol11}’.
- INIntentParameterPromptDialogFormatStringID
- wSoKH0
- INIntentParameterPromptDialogType
- DisambiguationIntroduction
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- Just to confirm, you wanted ‘${healthcheckSymbol11}’?
- INIntentParameterPromptDialogFormatStringID
- VvCtzh
- INIntentParameterPromptDialogType
- Confirmation
-
-
- INIntentParameterSupportsDynamicEnumeration
-
- INIntentParameterSupportsResolution
-
- INIntentParameterTag
- 2
- INIntentParameterType
- Object
-
-
- INIntentParameterConfigurable
-
- INIntentParameterCustomDisambiguation
-
- INIntentParameterDisplayName
- Healthcheck 12
- INIntentParameterDisplayNameID
- Cglmh8
- INIntentParameterDisplayPriority
- 2
- INIntentParameterName
- healthcheckSymbol12
- INIntentParameterObjectType
- HealthcheckSymbol
- INIntentParameterObjectTypeNamespace
- 88xZPY
- INIntentParameterPromptDialogs
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Configuration
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Primary
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- There are ${count} options matching ‘${healthcheckSymbol12}’.
- INIntentParameterPromptDialogFormatStringID
- 4eRFjP
- INIntentParameterPromptDialogType
- DisambiguationIntroduction
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- Just to confirm, you wanted ‘${healthcheckSymbol12}’?
- INIntentParameterPromptDialogFormatStringID
- x74QSv
- INIntentParameterPromptDialogType
- Confirmation
-
-
- INIntentParameterSupportsDynamicEnumeration
-
- INIntentParameterSupportsResolution
-
- INIntentParameterTag
- 6
- INIntentParameterType
- Object
-
-
- INIntentParameterConfigurable
-
- INIntentParameterCustomDisambiguation
-
- INIntentParameterDisplayName
- Healthcheck 21
- INIntentParameterDisplayNameID
- dY84q6
- INIntentParameterDisplayPriority
- 3
- INIntentParameterName
- healthcheckSymbol21
- INIntentParameterObjectType
- HealthcheckSymbol
- INIntentParameterObjectTypeNamespace
- 88xZPY
- INIntentParameterPromptDialogs
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Configuration
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Primary
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- There are ${count} options matching ‘${healthcheckSymbol21}’.
- INIntentParameterPromptDialogFormatStringID
- 5644n8
- INIntentParameterPromptDialogType
- DisambiguationIntroduction
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- Just to confirm, you wanted ‘${healthcheckSymbol21}’?
- INIntentParameterPromptDialogFormatStringID
- t3q63i
- INIntentParameterPromptDialogType
- Confirmation
-
-
- INIntentParameterSupportsDynamicEnumeration
-
- INIntentParameterSupportsResolution
-
- INIntentParameterTag
- 7
- INIntentParameterType
- Object
-
-
- INIntentParameterConfigurable
-
- INIntentParameterCustomDisambiguation
-
- INIntentParameterDisplayName
- Healthcheck 22
- INIntentParameterDisplayNameID
- 80skR6
- INIntentParameterDisplayPriority
- 4
- INIntentParameterName
- healthcheckSymbol22
- INIntentParameterObjectType
- HealthcheckSymbol
- INIntentParameterObjectTypeNamespace
- 88xZPY
- INIntentParameterPromptDialogs
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Configuration
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogType
- Primary
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- There are ${count} options matching ‘${healthcheckSymbol22}’.
- INIntentParameterPromptDialogFormatStringID
- UMMJUm
- INIntentParameterPromptDialogType
- DisambiguationIntroduction
-
-
- INIntentParameterPromptDialogCustom
-
- INIntentParameterPromptDialogFormatString
- Just to confirm, you wanted ‘${healthcheckSymbol22}’?
- INIntentParameterPromptDialogFormatStringID
- MIqUFR
- INIntentParameterPromptDialogType
- Confirmation
-
-
- INIntentParameterSupportsDynamicEnumeration
-
- INIntentParameterSupportsResolution
-
- INIntentParameterTag
- 8
- INIntentParameterType
- Object
-
-
- INIntentResponse
-
- INIntentResponseCodes
-
-
- INIntentResponseCodeName
- success
- INIntentResponseCodeSuccess
-
-
-
- INIntentResponseCodeName
- failure
-
-
-
- INIntentTitle
- Configuration Four
- INIntentTitleID
- sIO6Wf
- INIntentType
- Custom
- INIntentVerb
- View
-
-
- INTypes
-
-
- INTypeDisplayName
- Healthcheck Symbol
- INTypeDisplayNameID
- MGuA1W
- INTypeLastPropertyTag
- 106
- INTypeName
- HealthcheckSymbol
- INTypeProperties
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 1
- INTypePropertyName
- identifier
- INTypePropertyTag
- 1
- INTypePropertyType
- String
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 2
- INTypePropertyName
- displayString
- INTypePropertyTag
- 2
- INTypePropertyType
- String
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 3
- INTypePropertyName
- pronunciationHint
- INTypePropertyObjectType
- EventSymbol
- INTypePropertyObjectTypeNamespace
- 88xZPY
- INTypePropertyTag
- 105
- INTypePropertyType
- Object
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 4
- INTypePropertyName
- alternativeSpeakableMatches
- INTypePropertySupportsMultipleValues
-
- INTypePropertyTag
- 4
- INTypePropertyType
- SpeakableString
-
-
- INTypePropertyDisplayName
- Events
- INTypePropertyDisplayNameID
- fwOa2E
- INTypePropertyDisplayPriority
- 5
- INTypePropertyName
- events
- INTypePropertyObjectType
- EventSymbol
- INTypePropertyObjectTypeNamespace
- 88xZPY
- INTypePropertySupportsMultipleValues
-
- INTypePropertyTag
- 106
- INTypePropertyType
- Object
-
-
-
-
- INTypeDisplayName
- Event Symbol
- INTypeDisplayNameID
- jbKSKx
- INTypeLastPropertyTag
- 105
- INTypeName
- EventSymbol
- INTypeProperties
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 1
- INTypePropertyName
- identifier
- INTypePropertyTag
- 1
- INTypePropertyType
- String
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 2
- INTypePropertyName
- displayString
- INTypePropertyTag
- 2
- INTypePropertyType
- String
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 3
- INTypePropertyName
- pronunciationHint
- INTypePropertyTag
- 3
- INTypePropertyType
- String
-
-
- INTypePropertyDefault
-
- INTypePropertyDisplayPriority
- 4
- INTypePropertyName
- alternativeSpeakableMatches
- INTypePropertySupportsMultipleValues
-
- INTypePropertyTag
- 4
- INTypePropertyType
- SpeakableString
-
-
-
-
-
-
diff --git a/HealthcheckWidget/HealthcheckWidget.swift b/HealthcheckWidget/HealthcheckWidget.swift
deleted file mode 100644
index e59c9c7..0000000
--- a/HealthcheckWidget/HealthcheckWidget.swift
+++ /dev/null
@@ -1,512 +0,0 @@
-//
-// HealthcheckWidget.swift
-// HealthcheckWidget
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import WidgetKit
-import SwiftUI
-import Intents
-
-struct Provider: IntentTimelineProvider {
-
- @AppStorage("HealthcheckList") var healthCheckList: String = ""
-
- func placeholder(in context: Context) -> SimpleEntry {
- var count = 2
-
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- }
- let hc = DummyData.HealthcheckListCustom(customCount: count)
- return SimpleEntry(date: Date(), configuration: ConfigurationIntent(), healthcheck: hc)
- }
-
- func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
- var count = 2
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- }
- let hc = DummyData.HealthcheckListCustom(customCount: count)
- let entry = SimpleEntry(date: Date(), configuration: configuration, healthcheck: hc)
- completion(entry)
- }
-
- func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline) -> ()) {
- Task {
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 2)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let sorted = hcr.domain.sorted { $0.name > $1.name }
- let shrinkedEventList = Array(sorted)
- if (configuration.healthcheckSymbol1 != nil) {
- let health = shrinkedEventList.first { $0.healthtoken == configuration.healthcheckSymbol1?.identifier }
- if (health == nil) {
- configuration.healthcheckSymbol1 = nil
- } else {
- let healthStatus = HealthcheckSymbol(identifier: health!.healthtoken, display: health!.name)
- healthStatus.events = []
- health!.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
- configuration.healthcheckSymbol1 = healthStatus
- }
- }
- if (configuration.healthcheckSymbol2 != nil) {
- let health = shrinkedEventList.first { $0.healthtoken == configuration.healthcheckSymbol2?.identifier }
- if (health == nil) {
- configuration.healthcheckSymbol2 = nil
- } else {
- let healthStatus = HealthcheckSymbol(identifier: health!.healthtoken, display: health!.name)
- healthStatus.events = []
- health!.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
- configuration.healthcheckSymbol2 = healthStatus
- }
- }
- let entry = SimpleEntry(date: .now, configuration: configuration, healthcheck: [])
- let timeline = Timeline(entries: [entry], policy: .after(.now.advanced(by: 15 * 60)))
- completion(timeline)
- }
- }
-}
-
-struct ProviderFour: IntentTimelineProvider {
-
- @AppStorage("HealthcheckList") var healthCheckList: String = ""
-
- func placeholder(in context: Context) -> SimpleFourEntry {
- var count = 2
-
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- }
- let hc = DummyData.HealthcheckListCustom(customCount: count)
- return SimpleFourEntry(date: Date(), configuration: ConfigurationFourIntent(), healthcheck: hc)
- }
-
- func getSnapshot(for configuration: ConfigurationFourIntent, in context: Context, completion: @escaping (SimpleFourEntry) -> ()) {
- var count = 2
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- }
- let hc = DummyData.HealthcheckListCustom(customCount: count)
- let entry = SimpleFourEntry(date: Date(), configuration: configuration, healthcheck: hc)
- completion(entry)
- }
-
- func getTimeline(for configuration: ConfigurationFourIntent, in context: Context, completion: @escaping (Timeline) -> ()) {
- Task {
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 4)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
-
- let sorted = hcr.domain.sorted { $0.name > $1.name }
- let shrinkedEventList = Array(sorted)
- if (configuration.healthcheckSymbol11 != nil) {
- let health = shrinkedEventList.first { $0.healthtoken == configuration.healthcheckSymbol11?.identifier }
- if (health == nil) {
- configuration.healthcheckSymbol11 = nil
- } else {
- let healthStatus = HealthcheckSymbol(identifier: health!.healthtoken, display: health!.name)
- healthStatus.events = []
- health!.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
- configuration.healthcheckSymbol11 = healthStatus
- }
- }
- if (configuration.healthcheckSymbol12 != nil) {
- let health = shrinkedEventList.first { $0.healthtoken == configuration.healthcheckSymbol12?.identifier }
- if (health == nil) {
- configuration.healthcheckSymbol12 = nil
- } else {
- let healthStatus = HealthcheckSymbol(identifier: health!.healthtoken, display: health!.name)
- healthStatus.events = []
- health!.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
- configuration.healthcheckSymbol12 = healthStatus
- }
- }
- /*if (configuration.healthcheckSymbol21 != nil) {
- let health = shrinkedEventList.first { $0.healthtoken == configuration.healthcheckSymbol21?.identifier }
- if (health == nil) {
- configuration.healthcheckSymbol21 = nil
- } else {
- let healthStatus = HealthcheckSymbol(identifier: health!.healthtoken, display: health!.name)
- healthStatus.events = []
- health!.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
- configuration.healthcheckSymbol21 = healthStatus
- }
- }
- if (configuration.healthcheckSymbol22 != nil) {
- let health = shrinkedEventList.first { $0.healthtoken == configuration.healthcheckSymbol22?.identifier }
- if (health == nil) {
- configuration.healthcheckSymbol22 = nil
- } else {
- let healthStatus = HealthcheckSymbol(identifier: health!.healthtoken, display: health!.name)
- healthStatus.events = []
- health!.events.forEach { e in
- let event = EventSymbol(identifier: UUID().uuidString, display: e.status!.formatted())
- healthStatus.events?.append(event)
- }
- configuration.healthcheckSymbol22 = healthStatus
- }
- }*/
- let entry = SimpleFourEntry(date: .now, configuration: configuration, healthcheck: [])
- let timeline = Timeline(entries: [entry], policy: .after(.now.advanced(by: 15 * 60)))
- completion(timeline)
- }
- }
-}
-
-struct ProviderStatic: TimelineProvider {
-
- @AppStorage("HealthcheckList") var healthCheckList: String = ""
-
- func placeholder(in context: Context) -> SimpleEntryStatic {
- var count = 2
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- }
- let hc = DummyData.HealthcheckListCustom(customCount: count)
- return SimpleEntryStatic(date: Date(), healthcheck: hc)
- }
-
- func getSnapshot(in context: Context, completion: @escaping (SimpleEntryStatic) -> Void) {
- var count = 2
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 9
- }
- }
- let hc = DummyData.HealthcheckListCustom(customCount: count)
- let entry = SimpleEntryStatic(date: Date(), healthcheck: hc)
- completion(entry)
- }
-
- func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) {
- Task {
- let api = NetworkServices()
- let hcd = DummyData.HealthcheckListCustom(customCount: 2)
- let hcr = await api.GetHealthchecks() ?? HealthCheckResult(domain: hcd)
- var count = 2
- if #available(iOSApplicationExtension 16.0, *) {
- if context.family == .accessoryRectangular {
- count = 1
- } else if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 10
- }
- } else {
- if context.family == .systemSmall {
- count = 2
- } else if context.family == .systemMedium {
- count = 4
- } else {
- count = 10
- }
- }
- let sorted = hcr.domain.prefix(count).sorted { $0.name > $1.name }
- let shrinkedEventList = Array(sorted)
- let entry = SimpleEntryStatic(date: .now, healthcheck: shrinkedEventList)
- let timeline = Timeline(entries: [entry], policy: .after(.now.advanced(by: 15 * 60)))
- completion(timeline)
- }
- }
-}
-
-struct SimpleEntry: TimelineEntry {
- let date: Date
- let configuration: ConfigurationIntent
- let healthcheck: [HealthCheck]
-}
-
-struct SimpleFourEntry: TimelineEntry {
- let date: Date
- let configuration: ConfigurationFourIntent
- let healthcheck: [HealthCheck]
-}
-
-struct SimpleEntryStatic: TimelineEntry {
- let date: Date
- let healthcheck: [HealthCheck]
-}
-
-struct HealthcheckWidgetEntryView : View {
- @Environment(\.widgetFamily) var widgetFamily
-
- var entry: Provider.Entry
-
- var body: some View {
- if #available(iOSApplicationExtension 16.0, *) {
- switch widgetFamily {
- case .systemSmall:
- SmallSizeView(entry: entry)
- .widgetURL(URL(string: "ipv64://tab/2"))
- case .accessoryRectangular:
- AccessoryRectangleView(entry: entry)
- .widgetURL(URL(string: "ipv64://tab/2"))
- default:
- Text("Not implemented!")
- }
- } else {
- // Fallback on earlier versions
- switch widgetFamily {
- case .systemSmall:
- SmallSizeView(entry: entry)
- .widgetURL(URL(string: "ipv64://tab/2"))
- default:
- Text("Not implemented!")
- }
- }
- }
-}
-
-//struct HealthcheckWidgetFourEntryView : View {
-// @Environment(\.widgetFamily) var widgetFamily
-//
-// var entry: ProviderFour.Entry
-//
-// var body: some View {
-// if #available(iOSApplicationExtension 16.0, *) {
-// switch widgetFamily {
-// case .systemMedium:
-// MediumSizeView(entry: entry)
-// .widgetURL(URL(string: "ipv64://tab/2"))
-// default:
-// Text("Not implemented!")
-// }
-// } else {
-// // Fallback on earlier versions
-// switch widgetFamily {
-// case .systemMedium:
-// MediumSizeView(entry: entry)
-// .widgetURL(URL(string: "ipv64://tab/2"))
-// default:
-// Text("Not implemented!")
-// }
-// }
-// }
-//}
-
-struct HealthcheckWidgetStaticEntryView : View {
- @Environment(\.widgetFamily) var widgetFamily
-
- var entry: ProviderStatic.Entry
-
- var body: some View {
- switch widgetFamily {
- case .systemMedium:
- MediumSizeView(entry: entry)
- .widgetURL(URL(string: "ipv64://tab/2"))
- case .systemLarge:
- LargeSizeView(entry: entry)
- .widgetURL(URL(string: "ipv64://tab/2"))
- default:
- Text("Not implemented!")
- }
- }
-}
-
-struct HealthcheckWidget: Widget {
- let kind: String = "HealthcheckWidget"
-
- private var supportedFamilies: [WidgetFamily] {
- if #available(iOSApplicationExtension 16.0, *) {
- return [
- .systemSmall,
- .accessoryRectangular
- ]
- } else {
- return [
- .systemSmall
- ]
- }
- }
-
- var body: some WidgetConfiguration {
- IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
- HealthcheckWidgetEntryView(entry: entry)
- }
- .supportedFamilies(supportedFamilies)
- .configurationDisplayName("Meine Healthchecks")
- .description("Hier werden dir deine Healthchecks angezeigt.")
- .contentMarginsDisabled()
- }
-}
-
-struct HealthcheckWidgetStatic: Widget {
- let kind: String = "HealthcheckWidgetStatic"
-
- private var supportedFamilies: [WidgetFamily] {
- return [
- .systemMedium,
- .systemLarge
- ]
- }
-
- var body: some WidgetConfiguration {
- StaticConfiguration(kind: kind, provider: ProviderStatic()) { entry in
- HealthcheckWidgetStaticEntryView(entry: entry)
- }
- .supportedFamilies(supportedFamilies)
- .configurationDisplayName("Meine Healthchecks")
- .description("Hier werden dir deine Healthchecks angezeigt.")
- .contentMarginsDisabled()
- }
-}
-
-//struct HealthcheckWidgetFour: Widget {
-// let kind: String = "HealthcheckWidgetFour"
-//
-// private var supportedFamilies: [WidgetFamily] {
-// if #available(iOSApplicationExtension 16.0, *) {
-// return [
-// .systemMedium
-// ]
-// } else {
-// return [
-// .systemMedium
-// ]
-// }
-// }
-//
-// var body: some WidgetConfiguration {
-// IntentConfiguration(kind: kind, intent: ConfigurationFourIntent.self, provider: ProviderFour()) { entry in
-// HealthcheckWidgetFourEntryView(entry: entry)
-// }
-// .supportedFamilies(supportedFamilies)
-// .configurationDisplayName("Meine Healthchecks")
-// .description("Hier werden dir deine Healthchecks angezeigt.")
-// .contentMarginsDisabled()
-// }
-//}
-
-extension View {
- func widgetBackground(backgroundView: some View) -> some View {
- if #available(iOSApplicationExtension 17.0, *) {
- return containerBackground(for: .widget) {
- backgroundView
- }
- } else {
- return background(backgroundView)
- }
- }
-}
-
-struct HealthcheckWidget_Previews: PreviewProvider {
- static var previews: some View {
- let hc = DummyData.HealthcheckListCustom(customCount: 4)
- HealthcheckWidgetEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemMedium))
- }
-}
diff --git a/HealthcheckWidget/HealthcheckWidgetBundle.swift b/HealthcheckWidget/HealthcheckWidgetBundle.swift
deleted file mode 100644
index c144550..0000000
--- a/HealthcheckWidget/HealthcheckWidgetBundle.swift
+++ /dev/null
@@ -1,18 +0,0 @@
-//
-// HealthcheckWidgetBundle.swift
-// HealthcheckWidget
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import WidgetKit
-import SwiftUI
-
-@main
-struct HealthcheckWidgetBundle: WidgetBundle {
- var body: some Widget {
- HealthcheckWidget()
-// HealthcheckWidgetFour()
- HealthcheckWidgetStatic()
- }
-}
diff --git a/HealthcheckWidget/HealthcheckWidgetLiveActivity.swift b/HealthcheckWidget/HealthcheckWidgetLiveActivity.swift
deleted file mode 100644
index 85971d6..0000000
--- a/HealthcheckWidget/HealthcheckWidgetLiveActivity.swift
+++ /dev/null
@@ -1,79 +0,0 @@
-//
-// HealthcheckWidgetLiveActivity.swift
-// HealthcheckWidget
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import ActivityKit
-import WidgetKit
-import SwiftUI
-
-struct HealthcheckWidgetAttributes: ActivityAttributes {
- public struct ContentState: Codable, Hashable {
- // Dynamic stateful properties about your activity go here!
- var value: Int
- }
-
- // Fixed non-changing properties about your activity go here!
- var name: String
-}
-
-@available(iOSApplicationExtension 16.1, *)
-struct HealthcheckWidgetLiveActivity: Widget {
- var body: some WidgetConfiguration {
- ActivityConfiguration(for: HealthcheckWidgetAttributes.self) { context in
- // Lock screen/banner UI goes here
- VStack {
- Text("Hello")
- }
- .activityBackgroundTint(Color.cyan)
- .activitySystemActionForegroundColor(Color.black)
-
- } dynamicIsland: { context in
- DynamicIsland {
- // Expanded UI goes here. Compose the expanded UI through
- // various regions, like leading/trailing/center/bottom
- DynamicIslandExpandedRegion(.leading) {
- Text("Leading")
- }
- DynamicIslandExpandedRegion(.trailing) {
- Text("Trailing")
- }
- DynamicIslandExpandedRegion(.bottom) {
- Text("Bottom")
- // more content
- }
- } compactLeading: {
- Text("L")
- } compactTrailing: {
- Text("T")
- } minimal: {
- Text("Min")
- }
- .widgetURL(URL(string: "http://www.apple.com"))
- .keylineTint(Color.red)
- }
- }
-}
-
-@available(iOSApplicationExtension 16.2, *)
-struct HealthcheckWidgetLiveActivity_Previews: PreviewProvider {
- static let attributes = HealthcheckWidgetAttributes(name: "Me")
- static let contentState = HealthcheckWidgetAttributes.ContentState(value: 3)
-
- static var previews: some View {
- attributes
- .previewContext(contentState, viewKind: .dynamicIsland(.compact))
- .previewDisplayName("Island Compact")
- attributes
- .previewContext(contentState, viewKind: .dynamicIsland(.expanded))
- .previewDisplayName("Island Expanded")
- attributes
- .previewContext(contentState, viewKind: .dynamicIsland(.minimal))
- .previewDisplayName("Minimal")
- attributes
- .previewContext(contentState, viewKind: .content)
- .previewDisplayName("Notification")
- }
-}
diff --git a/HealthcheckWidget/Info.plist b/HealthcheckWidget/Info.plist
deleted file mode 100644
index 0f118fb..0000000
--- a/HealthcheckWidget/Info.plist
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
- NSExtension
-
- NSExtensionPointIdentifier
- com.apple.widgetkit-extension
-
-
-
diff --git a/HealthcheckWidget/WidgetSizes/AccessoryInlineView.swift b/HealthcheckWidget/WidgetSizes/AccessoryInlineView.swift
deleted file mode 100644
index ade1d61..0000000
--- a/HealthcheckWidget/WidgetSizes/AccessoryInlineView.swift
+++ /dev/null
@@ -1,91 +0,0 @@
-//
-// SmallSizeView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import Foundation
-import WidgetKit
-import SwiftUI
-
-
-@available(iOSApplicationExtension 16.0, *)
-struct AccessoryRectangleView : View {
- @Environment(\.widgetFamily) var widgetFamily
-
- var entry: Provider.Entry
-
- var body: some View {
- ZStack {
- VStack {
- if (entry.configuration.healthcheckSymbol1 != nil) {
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(entry.configuration.healthcheckSymbol1!.displayString)
- .font(.system(.callout, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, events: entry.configuration.healthcheckSymbol1!.events!)
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5)
- .fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- } else {
- Text("Keine Healthchecks konfiguriert!")
- .font(.system(.callout, design: .rounded))
- }
- }
- .padding(0)
- }
- .privacySensitive()
- .frame(maxHeight: .infinity)
- }
-
- fileprivate func GetLastXMonitorPills(count: Int, events: [EventSymbol]) -> [Color] {
- var colorArr: [Color] = []
- let lastEvents = events.prefix(count)
- print("lastEvents")
- lastEvents.reversed().forEach { event in
- colorArr.append(SetDotColor(statusId: Int(event.displayString) ?? 0))
- }
- return colorArr
- }
-
- fileprivate func SetDotColor(statusId: Int) -> Color {
- if (statusId == StatusTypes.active.statusId) {
- return .white
- }
- if (statusId == StatusTypes.warning.statusId) {
- return .white.opacity(0.6)
- }
- if (statusId == StatusTypes.alarm.statusId) {
- return .white.opacity(0.3)
- }
-
- return .white.opacity(0.1)
- }
-}
-
-@available(iOSApplicationExtension 16.0, *)
-struct AccessoryRectanglePreviews: PreviewProvider {
- static var previews: some View {
- let hc = DummyData.HealthcheckListCustom(customCount: 1)
- AccessoryRectangleView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .accessoryRectangular))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- AccessoryRectangleView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .accessoryRectangular))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
-
diff --git a/HealthcheckWidget/WidgetSizes/LargeSizeView.swift b/HealthcheckWidget/WidgetSizes/LargeSizeView.swift
deleted file mode 100644
index cde1fe3..0000000
--- a/HealthcheckWidget/WidgetSizes/LargeSizeView.swift
+++ /dev/null
@@ -1,139 +0,0 @@
-//
-// LargeSizeView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import Foundation
-import WidgetKit
-import SwiftUI
-
-struct LargeSizeView : View {
- @Environment(\.widgetFamily) var widgetFamily
-
- var entry: ProviderStatic.Entry
-
- var body: some View {
- ZStack {
- HStack {
- let firstColumn = GetColumn(start: 0, end: 4)
- let secondColumn = GetColumn(start: 5, end: 9)
- VStack {
- ForEach(firstColumn, id: \.healthtoken) { it in
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(it.name)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, domain: it).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (firstColumn.count < 5) {
- Spacer()
- }
- }
- .padding(.top, firstColumn.count < 5 ? 4 : 0)
- VStack {
- ForEach(secondColumn, id: \.healthtoken) { it in
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(it.name)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, domain: it).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (secondColumn.count < 5) {
- Spacer()
- }
- }
- .padding(.top, secondColumn.count < 5 ? 4 : 0)
- }
- .padding()
- }
- .frame(maxHeight: .infinity)
- .widgetBackground(backgroundView: Color("circleBG"))
- }
-
- fileprivate func GetLastXMonitorPills(count: Int, domain: HealthCheck) -> [Color] {
-
- let lastEvents = domain.events.prefix(count)
- var colorArr: [Color] = []
-
- lastEvents.forEach { event in
- colorArr.append(SetDotColor(statusId: event.status!))
- }
-
- return colorArr
- }
-
- fileprivate func SetDotColor(statusId: Int) -> Color {
- if (statusId == StatusTypes.active.statusId) {
- return StatusTypes.active.color!
- }
- if (statusId == StatusTypes.warning.statusId) {
- return StatusTypes.warning.color!
- }
- if (statusId == StatusTypes.alarm.statusId) {
- return StatusTypes.alarm.color!
- }
- if (statusId == StatusTypes.pause.statusId) {
- return StatusTypes.pause.color!
- }
-
- return .gray
- }
-
- fileprivate func GetColumn(start: Int, end: Int) -> ArraySlice {
- if (entry.healthcheck.count < start) {
- return []
- } else if (entry.healthcheck.count > end) {
- return entry.healthcheck[start...end]
- } else if (entry.healthcheck.count == 1) {
- return entry.healthcheck[start...start]
- } else if (entry.healthcheck.count == 0) {
- return []
- } else if (entry.healthcheck.count < end) {
- return entry.healthcheck[start...entry.healthcheck.count-1]
- } else {
- return entry.healthcheck[start...end-1]
- }
- }
-}
-
-
-struct LargeSizeViewPreviews: PreviewProvider {
- static var previews: some View {
- let hc = DummyData.HealthcheckListCustom(customCount: 9)
- LargeSizeView(entry: SimpleEntryStatic(date: Date(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemLarge))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- LargeSizeView(entry: SimpleEntryStatic(date: Date(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemLarge))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
-
diff --git a/HealthcheckWidget/WidgetSizes/MediumSizeView.swift b/HealthcheckWidget/WidgetSizes/MediumSizeView.swift
deleted file mode 100644
index e597a9d..0000000
--- a/HealthcheckWidget/WidgetSizes/MediumSizeView.swift
+++ /dev/null
@@ -1,207 +0,0 @@
-//
-// MediumSizeView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import Foundation
-import WidgetKit
-import SwiftUI
-
-struct MediumSizeView : View {
- @Environment(\.widgetFamily) var widgetFamily
-
- var entry: ProviderStatic.Entry
-
- /*
- var body: some View {
- ZStack {
- if (entry.configuration.healthcheckSymbol11 == nil || entry.configuration.healthcheckSymbol12 == nil || entry.configuration.healthcheckSymbol21 == nil || entry.configuration.healthcheckSymbol22 == nil) {
- VStack {
- Text("Keine Healthchecks konfiguriert!")
- .font(.system(.callout, design: .rounded))
- }
- .padding()
- } else {
- /*HStack {
- let firstColumn = GetColumn(start: 0, end: 1)
- let secondColumn = GetColumn(start: 2, end: 3)
- VStack {
- ForEach(firstColumn, id: \.healthtoken) { it in
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(it.name)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, domain: it).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (firstColumn.count == 1) {
- Spacer()
- }
- }
- .padding(.top, firstColumn.count == 1 ? 3 : 0)
- VStack {
- ForEach(secondColumn, id: \.healthtoken) { it in
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(it.name)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, domain: it).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (secondColumn.count == 1) {
- Spacer()
- }
- }
- .padding(.top, secondColumn.count == 1 ? 0 : 0)
- }
- .padding()*/
- }
- }
- .frame(maxHeight: .infinity)
- .widgetBackground(backgroundView: Color("circleBG"))
- }
- */
-
- var body: some View {
- ZStack {
- HStack {
- let firstColumn = GetColumn(start: 0, end: 1)
- let secondColumn = GetColumn(start: 2, end: 3)
- VStack {
- ForEach(firstColumn, id: \.healthtoken) { it in
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(it.name)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, domain: it).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (firstColumn.count == 1) {
- Spacer()
- }
- }
- .padding(.top, firstColumn.count == 1 ? 3 : 0)
- VStack {
- ForEach(secondColumn, id: \.healthtoken) { it in
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(it.name)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, domain: it).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (secondColumn.count == 1) {
- Spacer()
- }
- }
- .padding(.top, secondColumn.count == 1 ? 0 : 0)
- }
- .padding()
- }
- .frame(maxHeight: .infinity)
- .widgetBackground(backgroundView: Color("circleBG"))
- }
-
- fileprivate func GetLastXMonitorPills(count: Int, domain: HealthCheck) -> [Color] {
-
- let lastEvents = domain.events.prefix(count)
- var colorArr: [Color] = []
-
- lastEvents.forEach { event in
- colorArr.append(SetDotColor(statusId: event.status!))
- }
-
- return colorArr
- }
-
- fileprivate func SetDotColor(statusId: Int) -> Color {
- if (statusId == StatusTypes.active.statusId) {
- return StatusTypes.active.color!
- }
- if (statusId == StatusTypes.warning.statusId) {
- return StatusTypes.warning.color!
- }
- if (statusId == StatusTypes.alarm.statusId) {
- return StatusTypes.alarm.color!
- }
- if (statusId == StatusTypes.pause.statusId) {
- return StatusTypes.pause.color!
- }
-
- return .gray
- }
-
- fileprivate func GetColumn(start: Int, end: Int) -> ArraySlice {
- if (entry.healthcheck.count < start) {
- return []
- } else if (entry.healthcheck.count > end) {
- return entry.healthcheck[start...end]
- } else if (entry.healthcheck.count == 1) {
- return entry.healthcheck[start...start]
- } else if (entry.healthcheck.count == 0) {
- return []
- } else {
- return entry.healthcheck[start...end-1]
- }
- }
-}
-
-struct MediumSizeViewPreviews: PreviewProvider {
- static var previews: some View {
- let hc = DummyData.HealthcheckListCustom(customCount: 2)
- MediumSizeView(entry: SimpleEntryStatic(date: Date(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemMedium))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- MediumSizeView(entry: SimpleEntryStatic(date: Date(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemMedium))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
diff --git a/HealthcheckWidget/WidgetSizes/SmallSizeView.swift b/HealthcheckWidget/WidgetSizes/SmallSizeView.swift
deleted file mode 100644
index 75027fc..0000000
--- a/HealthcheckWidget/WidgetSizes/SmallSizeView.swift
+++ /dev/null
@@ -1,111 +0,0 @@
-//
-// SmallSizeView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 20.01.23.
-//
-
-import Foundation
-import WidgetKit
-import SwiftUI
-
-struct SmallSizeView : View {
- @Environment(\.widgetFamily) var widgetFamily
-
- var entry: Provider.Entry
-
- var body: some View {
- ZStack {
- VStack {
- if (entry.configuration.healthcheckSymbol1 != nil || entry.configuration.healthcheckSymbol2 != nil) {
- if (entry.configuration.healthcheckSymbol1 != nil) {
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(entry.configuration.healthcheckSymbol1!.displayString)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, events: entry.configuration.healthcheckSymbol1!.events!)
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- if (entry.configuration.healthcheckSymbol2 != nil) {
- LazyVStack(alignment: .leading, spacing: 0) {
- Text(entry.configuration.healthcheckSymbol2!.displayString)
- .font(.system(.title3, design: .rounded))
- .lineLimit(1)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 12, events: entry.configuration.healthcheckSymbol2!.events!)
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 7, height: 25)
- }
- }
- .padding(.trailing, 5)
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .id(UUID())
- .padding(.bottom, 5)
- }
- } else {
- Text("Keine Healthchecks konfiguriert!")
- .font(.system(.callout, design: .rounded))
- }
- }
- .padding()
- }
- .frame(maxHeight: .infinity)
- .widgetBackground(backgroundView: Color("circleBG"))
- }
-
- fileprivate func GetLastXMonitorPills(count: Int, events: [EventSymbol]) -> [Color] {
- var colorArr: [Color] = []
- let lastEvents = events.prefix(count)
- print("lastEvents")
- lastEvents.reversed().forEach { event in
- colorArr.append(SetDotColor(statusId: Int(event.displayString) ?? 0))
- }
- return colorArr
- }
-
- fileprivate func SetDotColor(statusId: Int) -> Color {
- if (statusId == StatusTypes.active.statusId) {
- return StatusTypes.active.color!
- }
- if (statusId == StatusTypes.warning.statusId) {
- return StatusTypes.warning.color!
- }
- if (statusId == StatusTypes.alarm.statusId) {
- return StatusTypes.alarm.color!
- }
- if (statusId == StatusTypes.pause.statusId) {
- return StatusTypes.pause.color!
- }
-
- return .gray
- }
-}
-
-struct SmallSizeViewPreviews: PreviewProvider {
- static var previews: some View {
- let hc = DummyData.HealthcheckListCustom(customCount: 2)
- SmallSizeView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemSmall))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- SmallSizeView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent(), healthcheck: hc))
- .previewContext(WidgetPreviewContext(family: .systemSmall))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
-
diff --git a/HealthcheckWidgetExtension.entitlements b/HealthcheckWidgetExtension.entitlements
deleted file mode 100644
index 550c609..0000000
--- a/HealthcheckWidgetExtension.entitlements
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
- com.apple.security.application-groups
-
- group.ipv64.net
-
-
-
diff --git a/IPv64-net-Info.plist b/IPv64-net-Info.plist
new file mode 100644
index 0000000..718ac9c
--- /dev/null
+++ b/IPv64-net-Info.plist
@@ -0,0 +1,44 @@
+
+
+
+
+ NSAppTransportSecurity
+
+
+ NSAllowsArbitraryLoads
+
+ NSExceptionDomains
+
+ ipv64.net
+
+ NSIncludesSubdomains
+
+ NSExceptionAllowsInsecureHTTPLoads
+
+
+ secntfy.app
+
+ NSIncludesSubdomains
+
+ NSExceptionAllowsInsecureHTTPLoads
+
+
+
+
+ NSLocalNetworkUsageDescription
+ IPv64.net connects directly to your Node64 nodes in your local network.
+ SECNTFY_APP_KEY
+ $(SECNTFY_APP_KEY)
+ SecureKeychainAccessGroup
+ $(AppIdentifierPrefix)group.ipv64.net
+ UIBackgroundModes
+
+ remote-notification
+
+ UIDesignRequiresCompatibility
+
+
+
diff --git a/IPv64.xcodeproj/project.pbxproj b/IPv64.xcodeproj/project.pbxproj
index ea01a7b..71aed6c 100644
--- a/IPv64.xcodeproj/project.pbxproj
+++ b/IPv64.xcodeproj/project.pbxproj
@@ -3,125 +3,51 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 56;
+ objectVersion = 77;
objects = {
/* Begin PBXBuildFile section */
- 9A0034FC2930F9200065E1F3 /* TabbView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A0034FB2930F9200065E1F3 /* TabbView.swift */; };
- 9A0034FE2930F9460065E1F3 /* ProfilView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A0034FD2930F9460065E1F3 /* ProfilView.swift */; };
- 9A0035002930FD010065E1F3 /* IPView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A0034FF2930FD010065E1F3 /* IPView.swift */; };
- 9A003502293101350065E1F3 /* LogView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A003501293101350065E1F3 /* LogView.swift */; };
- 9A0035042931062B0065E1F3 /* LogItemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A0035032931062B0065E1F3 /* LogItemView.swift */; };
- 9A003506293129930065E1F3 /* AccountView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A003505293129930065E1F3 /* AccountView.swift */; };
- 9A08D1D82979AB47002CF0E8 /* Introspect in Frameworks */ = {isa = PBXBuildFile; productRef = 9A08D1D72979AB47002CF0E8 /* Introspect */; };
- 9A10DBF8298C206D00285C0A /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A10DBF7298C206D00285C0A /* NotificationService.swift */; };
- 9A10DBFC298C206D00285C0A /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 9A10DBF5298C206D00285C0A /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
- 9A10DC00298C285800285C0A /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A10DBF7298C206D00285C0A /* NotificationService.swift */; };
- 9A10DC01298C29C600285C0A /* SetupPrefs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA52918577D009B506D /* SetupPrefs.swift */; };
- 9A154B572989B7600021DD2E /* FirebaseAnalytics in Frameworks */ = {isa = PBXBuildFile; productRef = 9A154B562989B7600021DD2E /* FirebaseAnalytics */; };
- 9A154B592989B7600021DD2E /* FirebaseCrashlytics in Frameworks */ = {isa = PBXBuildFile; productRef = 9A154B582989B7600021DD2E /* FirebaseCrashlytics */; };
- 9A154B5B2989B7600021DD2E /* FirebaseMessaging in Frameworks */ = {isa = PBXBuildFile; productRef = 9A154B5A2989B7600021DD2E /* FirebaseMessaging */; };
- 9A154B5D2989B7EA0021DD2E /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 9A154B5C2989B7EA0021DD2E /* GoogleService-Info.plist */; };
- 9A3313FC29844E4D009E47F5 /* Intents.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A3313FB29844E4D009E47F5 /* Intents.framework */; };
- 9A3313FF29844E4D009E47F5 /* IntentHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A3313FE29844E4D009E47F5 /* IntentHandler.swift */; };
- 9A33140329844E4D009E47F5 /* HealthcheckIntents.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 9A3313FA29844E4D009E47F5 /* HealthcheckIntents.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
- 9A33140729844F1B009E47F5 /* HealthcheckWidget.intentdefinition in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37D9297B26A600FC9B74 /* HealthcheckWidget.intentdefinition */; };
- 9A33140829845032009E47F5 /* IntentHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A3313FE29844E4D009E47F5 /* IntentHandler.swift */; };
- 9A33140929845AF1009E47F5 /* IntentHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A3313FE29844E4D009E47F5 /* IntentHandler.swift */; };
- 9A33140A29845F21009E47F5 /* NetworkServices.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA0291853C9009B506D /* NetworkServices.swift */; };
- 9A33140B29845F41009E47F5 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA329185411009B506D /* Models.swift */; };
- 9A33140C29845F4B009E47F5 /* SetupPrefs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA52918577D009B506D /* SetupPrefs.swift */; };
- 9A5A359E29756EFA006F27EB /* WhatsNewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A5A359C29756EFA006F27EB /* WhatsNewView.swift */; };
- 9A5A359F29756EFA006F27EB /* WhatsNewItemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A5A359D29756EFA006F27EB /* WhatsNewItemView.swift */; };
- 9A6EC81D2A1749AA005C5D5A /* Toast in Frameworks */ = {isa = PBXBuildFile; productRef = 9A6EC81C2A1749AA005C5D5A /* Toast */; };
- 9A8482E82AC603B10072BF45 /* AccountListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A8482E72AC603B10072BF45 /* AccountListView.swift */; };
- 9A8D5BE229196290006B8A74 /* ErrorSheetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A8D5BE129196290006B8A74 /* ErrorSheetView.swift */; };
- 9A8D5BE429197355006B8A74 /* DetailDomainView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A8D5BE329197355006B8A74 /* DetailDomainView.swift */; };
- 9A8D5C0529199141006B8A74 /* HelpView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A8D5C0429199141006B8A74 /* HelpView.swift */; };
- 9AA7B4D22A82BDF900A06B4D /* Tabs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AA7B4D12A82BDF900A06B4D /* Tabs.swift */; };
- 9AA7B4D52A82BF8600A06B4D /* HapticManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AA7B4D32A82BF8600A06B4D /* HapticManager.swift */; };
- 9AA7B4D62A82BF8600A06B4D /* SoundEffectManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AA7B4D42A82BF8600A06B4D /* SoundEffectManager.swift */; };
- 9AA7B4D82A82BFAD00A06B4D /* UserPrefs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AA7B4D72A82BFAD00A06B4D /* UserPrefs.swift */; };
- 9AA7B4DD2A82C66B00A06B4D /* tabSelection_old.wav in Resources */ = {isa = PBXBuildFile; fileRef = 9AA7B4DB2A82C66A00A06B4D /* tabSelection_old.wav */; };
- 9AA7B4DE2A82C66B00A06B4D /* tabSelection.wav in Resources */ = {isa = PBXBuildFile; fileRef = 9AA7B4DC2A82C66B00A06B4D /* tabSelection.wav */; };
- 9AA7B4E12A82C7D400A06B4D /* BlocklistView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AA7B4E02A82C7D400A06B4D /* BlocklistView.swift */; };
- 9AACEB8C291851E1009B506D /* IPv64App.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEB8B291851E1009B506D /* IPv64App.swift */; };
- 9AACEB8E291851E1009B506D /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEB8D291851E1009B506D /* ContentView.swift */; };
- 9AACEB90291851E2009B506D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9AACEB8F291851E2009B506D /* Assets.xcassets */; };
- 9AACEB93291851E2009B506D /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9AACEB92291851E2009B506D /* Preview Assets.xcassets */; };
- 9AACEB98291851E2009B506D /* IPv64.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEB96291851E2009B506D /* IPv64.xcdatamodeld */; };
- 9AACEB9F2918524B009B506D /* LoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEB9E2918524B009B506D /* LoginView.swift */; };
- 9AACEBA1291853C9009B506D /* NetworkServices.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA0291853C9009B506D /* NetworkServices.swift */; };
- 9AACEBA429185411009B506D /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA329185411009B506D /* Models.swift */; };
- 9AACEBA62918577D009B506D /* SetupPrefs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA52918577D009B506D /* SetupPrefs.swift */; };
- 9AACEBA8291857AF009B506D /* SpinnerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA7291857AF009B506D /* SpinnerView.swift */; };
- 9AACEBAA2918609F009B506D /* NewDomainView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA92918609F009B506D /* NewDomainView.swift */; };
- 9AAEF655297F089D00726849 /* Biometrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AAEF654297F089D00726849 /* Biometrics.swift */; };
- 9AAEF657297F0D3800726849 /* LockView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AAEF656297F0D3800726849 /* LockView.swift */; };
- 9AB155C229747DAC0052F21E /* CodeScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AB155C129747DAC0052F21E /* CodeScanner.swift */; };
- 9AB78EB7297740D00047FDFA /* DetailHealthcheckView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AB78EB6297740D00047FDFA /* DetailHealthcheckView.swift */; };
- 9ABB37CF297B26A600FC9B74 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9ABB37CE297B26A600FC9B74 /* WidgetKit.framework */; };
- 9ABB37D1297B26A600FC9B74 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9ABB37D0297B26A600FC9B74 /* SwiftUI.framework */; };
- 9ABB37D4297B26A600FC9B74 /* HealthcheckWidgetBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37D3297B26A600FC9B74 /* HealthcheckWidgetBundle.swift */; };
- 9ABB37D6297B26A600FC9B74 /* HealthcheckWidgetLiveActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37D5297B26A600FC9B74 /* HealthcheckWidgetLiveActivity.swift */; };
- 9ABB37D8297B26A600FC9B74 /* HealthcheckWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37D7297B26A600FC9B74 /* HealthcheckWidget.swift */; };
- 9ABB37DB297B26A700FC9B74 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9ABB37DA297B26A700FC9B74 /* Assets.xcassets */; };
- 9ABB37DD297B26A700FC9B74 /* HealthcheckWidget.intentdefinition in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37D9297B26A600FC9B74 /* HealthcheckWidget.intentdefinition */; };
- 9ABB37DE297B26A700FC9B74 /* HealthcheckWidget.intentdefinition in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37D9297B26A600FC9B74 /* HealthcheckWidget.intentdefinition */; };
- 9ABB37E1297B26A700FC9B74 /* HealthcheckWidgetExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 9ABB37CC297B26A600FC9B74 /* HealthcheckWidgetExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
- 9ABB37EC297B2CD900FC9B74 /* SmallSizeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37E8297B2C1600FC9B74 /* SmallSizeView.swift */; };
- 9ABB37ED297B2CD900FC9B74 /* LargeSizeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37EA297B2C2A00FC9B74 /* LargeSizeView.swift */; };
- 9ABB37EE297B2CD900FC9B74 /* MediumSizeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37E6297B2BFF00FC9B74 /* MediumSizeView.swift */; };
- 9ABB37F0297B314400FC9B74 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA329185411009B506D /* Models.swift */; };
- 9ABB37F1297B380300FC9B74 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9AACEB8F291851E2009B506D /* Assets.xcassets */; };
- 9ABB37F2297B533200FC9B74 /* NetworkServices.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA0291853C9009B506D /* NetworkServices.swift */; };
- 9ABB37F3297B544800FC9B74 /* SetupPrefs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA52918577D009B506D /* SetupPrefs.swift */; };
- 9ABB37F4297B5CB800FC9B74 /* SpinnerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AACEBA7291857AF009B506D /* SpinnerView.swift */; };
- 9ABB37F8297C6BDB00FC9B74 /* EditHealthcheckView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABB37F7297C6BDB00FC9B74 /* EditHealthcheckView.swift */; };
- 9AC2EDEC291ADFAF00140CD9 /* NewDomainDNSView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AC2EDEB291ADFAF00140CD9 /* NewDomainDNSView.swift */; };
- 9AD1D90229B9E26E00DD6057 /* IntegrationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD1D90129B9E26E00DD6057 /* IntegrationView.swift */; };
- 9AD5DF5E2975B5DB007928F6 /* HealthcheckView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD5DF5D2975B5DB007928F6 /* HealthcheckView.swift */; };
- 9AD5DF612975BAC3007928F6 /* HealthcheckStatsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD5DF602975BAC3007928F6 /* HealthcheckStatsView.swift */; };
- 9AD5DF632975BAD7007928F6 /* HealthcheckStatsItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD5DF622975BAD7007928F6 /* HealthcheckStatsItem.swift */; };
- 9AD5DF652975ECC1007928F6 /* NewHealthcheckView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD5DF642975ECC1007928F6 /* NewHealthcheckView.swift */; };
- 9AD7FE3E29B7ED0E001F72B7 /* IntegrationSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD7FE3D29B7ED0E001F72B7 /* IntegrationSelection.swift */; };
- 9AE5E22E298302280019D524 /* AccessoryInlineView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AE5E22D298302280019D524 /* AccessoryInlineView.swift */; };
+ C3D100000000000000000002 /* IPv64NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = C3D100000000000000000001 /* IPv64NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
+ C3D100000000000000000003 /* SecNtfy in Frameworks */ = {isa = PBXBuildFile; productRef = C3D100000000000000000004 /* SecNtfy */; };
+ B1A0000000000000000000A1 /* IPv64 in Frameworks */ = {isa = PBXBuildFile; productRef = B1A0000000000000000000B1 /* IPv64 */; };
+ B1A0000000000000000000A2 /* SecNtfy in Frameworks */ = {isa = PBXBuildFile; productRef = B1A0000000000000000000B2 /* SecNtfy */; };
+ B1A0000000000000000000A3 /* IPv64 in Frameworks */ = {isa = PBXBuildFile; productRef = B1A0000000000000000000B3 /* IPv64 */; };
+ 9A68F3482EBE088C0033CC42 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A0C48022EBA963700BEDFEA /* WidgetKit.framework */; };
+ 9A68F3492EBE088C0033CC42 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A0C48042EBA963700BEDFEA /* SwiftUI.framework */; };
+ 9A68F3562EBE088D0033CC42 /* IPv64WidgetExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 9A68F3472EBE088C0033CC42 /* IPv64WidgetExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
+ 9A68F35C2EBE08C80033CC42 /* SwiftyBeaver in Frameworks */ = {isa = PBXBuildFile; productRef = 9A68F35B2EBE08C80033CC42 /* SwiftyBeaver */; };
+ C3D1000000000000000000A1 /* SwiftyBeaver in Frameworks */ = {isa = PBXBuildFile; productRef = C3D1000000000000000000A2 /* SwiftyBeaver */; };
+ 9A8CA8AF2EA6969D0073978F /* ipv64.icon in Resources */ = {isa = PBXBuildFile; fileRef = 9A8CA8AD2EA6969D0073978F /* ipv64.icon */; };
+ 9A8CA8B02EA6969D0073978F /* ipv64_beta.icon in Resources */ = {isa = PBXBuildFile; fileRef = 9A8CA8AE2EA6969D0073978F /* ipv64_beta.icon */; };
+ 9AD116FC2EBCAC2000EE7E81 /* SwiftyBeaver in Frameworks */ = {isa = PBXBuildFile; productRef = 9AD116FB2EBCAC2000EE7E81 /* SwiftyBeaver */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
- 9A10DBFA298C206D00285C0A /* PBXContainerItemProxy */ = {
+ C3D100000000000000000005 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
- containerPortal = 9AACEB80291851E1009B506D /* Project object */;
+ containerPortal = 9A5178CB2EA3995200731FFB /* Project object */;
proxyType = 1;
- remoteGlobalIDString = 9A10DBF4298C206D00285C0A;
- remoteInfo = NotificationService;
+ remoteGlobalIDString = C3D100000000000000000009;
+ remoteInfo = IPv64NotificationService;
};
- 9A33140129844E4D009E47F5 /* PBXContainerItemProxy */ = {
+ 9A68F3542EBE088D0033CC42 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
- containerPortal = 9AACEB80291851E1009B506D /* Project object */;
+ containerPortal = 9A5178CB2EA3995200731FFB /* Project object */;
proxyType = 1;
- remoteGlobalIDString = 9A3313F929844E4D009E47F5;
- remoteInfo = HealthcheckIntents;
- };
- 9ABB37DF297B26A700FC9B74 /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = 9AACEB80291851E1009B506D /* Project object */;
- proxyType = 1;
- remoteGlobalIDString = 9ABB37CB297B26A600FC9B74;
- remoteInfo = HealthcheckWidgetExtension;
+ remoteGlobalIDString = 9A68F3462EBE088C0033CC42;
+ remoteInfo = IPv64WidgetExtension;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
- 9ABB37E2297B26A700FC9B74 /* Embed Foundation Extensions */ = {
+ 9A0C48152EBA963800BEDFEA /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
- 9ABB37E1297B26A700FC9B74 /* HealthcheckWidgetExtension.appex in Embed Foundation Extensions */,
- 9A10DBFC298C206D00285C0A /* NotificationService.appex in Embed Foundation Extensions */,
- 9A33140329844E4D009E47F5 /* HealthcheckIntents.appex in Embed Foundation Extensions */,
+ 9A68F3562EBE088D0033CC42 /* IPv64WidgetExtension.appex in Embed Foundation Extensions */,
+ C3D100000000000000000002 /* IPv64NotificationService.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
@@ -129,777 +55,416 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
- 9A0034FB2930F9200065E1F3 /* TabbView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabbView.swift; sourceTree = ""; };
- 9A0034FD2930F9460065E1F3 /* ProfilView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfilView.swift; sourceTree = ""; };
- 9A0034FF2930FD010065E1F3 /* IPView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPView.swift; sourceTree = ""; };
- 9A003501293101350065E1F3 /* LogView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogView.swift; sourceTree = ""; };
- 9A0035032931062B0065E1F3 /* LogItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogItemView.swift; sourceTree = ""; };
- 9A003505293129930065E1F3 /* AccountView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountView.swift; sourceTree = ""; };
- 9A10DBF5298C206D00285C0A /* NotificationService.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };
- 9A10DBF7298C206D00285C0A /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = ""; };
- 9A10DBF9298C206D00285C0A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
- 9A10DC02298C2B5E00285C0A /* NotificationService.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = ""; };
- 9A154B5C2989B7EA0021DD2E /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; };
- 9A3313FA29844E4D009E47F5 /* HealthcheckIntents.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HealthcheckIntents.appex; sourceTree = BUILT_PRODUCTS_DIR; };
- 9A3313FB29844E4D009E47F5 /* Intents.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Intents.framework; path = System/Library/Frameworks/Intents.framework; sourceTree = SDKROOT; };
- 9A3313FE29844E4D009E47F5 /* IntentHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntentHandler.swift; sourceTree = ""; };
- 9A33140029844E4D009E47F5 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
- 9A5A359C29756EFA006F27EB /* WhatsNewView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WhatsNewView.swift; sourceTree = ""; };
- 9A5A359D29756EFA006F27EB /* WhatsNewItemView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WhatsNewItemView.swift; sourceTree = ""; };
- 9A8482E72AC603B10072BF45 /* AccountListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountListView.swift; sourceTree = ""; };
- 9A8D5BE129196290006B8A74 /* ErrorSheetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ErrorSheetView.swift; sourceTree = ""; };
- 9A8D5BE329197355006B8A74 /* DetailDomainView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetailDomainView.swift; sourceTree = ""; };
- 9A8D5C0429199141006B8A74 /* HelpView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HelpView.swift; sourceTree = ""; };
- 9AA1F99F29847A5B00170C69 /* HealthcheckIntents.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = HealthcheckIntents.entitlements; sourceTree = ""; };
- 9AA7B4D12A82BDF900A06B4D /* Tabs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Tabs.swift; sourceTree = ""; };
- 9AA7B4D32A82BF8600A06B4D /* HapticManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HapticManager.swift; sourceTree = ""; };
- 9AA7B4D42A82BF8600A06B4D /* SoundEffectManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SoundEffectManager.swift; sourceTree = ""; };
- 9AA7B4D72A82BFAD00A06B4D /* UserPrefs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserPrefs.swift; sourceTree = ""; };
- 9AA7B4DB2A82C66A00A06B4D /* tabSelection_old.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = tabSelection_old.wav; sourceTree = ""; };
- 9AA7B4DC2A82C66B00A06B4D /* tabSelection.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = tabSelection.wav; sourceTree = ""; };
- 9AA7B4E02A82C7D400A06B4D /* BlocklistView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlocklistView.swift; sourceTree = ""; };
- 9AACEB88291851E1009B506D /* IPv64.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = IPv64.app; sourceTree = BUILT_PRODUCTS_DIR; };
- 9AACEB8B291851E1009B506D /* IPv64App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPv64App.swift; sourceTree = ""; };
- 9AACEB8D291851E1009B506D /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; };
- 9AACEB8F291851E2009B506D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
- 9AACEB92291851E2009B506D /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; };
- 9AACEB97291851E2009B506D /* IPv64.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = IPv64.xcdatamodel; sourceTree = ""; };
- 9AACEB9E2918524B009B506D /* LoginView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginView.swift; sourceTree = ""; };
- 9AACEBA0291853C9009B506D /* NetworkServices.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkServices.swift; sourceTree = ""; };
- 9AACEBA329185411009B506D /* Models.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; };
- 9AACEBA52918577D009B506D /* SetupPrefs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SetupPrefs.swift; sourceTree = ""; };
- 9AACEBA7291857AF009B506D /* SpinnerView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SpinnerView.swift; sourceTree = ""; };
- 9AACEBA92918609F009B506D /* NewDomainView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewDomainView.swift; sourceTree = ""; };
- 9AAEF654297F089D00726849 /* Biometrics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Biometrics.swift; sourceTree = ""; };
- 9AAEF656297F0D3800726849 /* LockView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockView.swift; sourceTree = ""; };
- 9AB155C129747DAC0052F21E /* CodeScanner.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CodeScanner.swift; sourceTree = ""; };
- 9AB155C329747F5C0052F21E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
- 9AB78EB6297740D00047FDFA /* DetailHealthcheckView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DetailHealthcheckView.swift; sourceTree = ""; };
- 9ABB37CC297B26A600FC9B74 /* HealthcheckWidgetExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HealthcheckWidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
- 9ABB37CE297B26A600FC9B74 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
- 9ABB37D0297B26A600FC9B74 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
- 9ABB37D3297B26A600FC9B74 /* HealthcheckWidgetBundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthcheckWidgetBundle.swift; sourceTree = ""; };
- 9ABB37D5297B26A600FC9B74 /* HealthcheckWidgetLiveActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthcheckWidgetLiveActivity.swift; sourceTree = ""; };
- 9ABB37D7297B26A600FC9B74 /* HealthcheckWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthcheckWidget.swift; sourceTree = ""; };
- 9ABB37D9297B26A600FC9B74 /* HealthcheckWidget.intentdefinition */ = {isa = PBXFileReference; lastKnownFileType = file.intentdefinition; path = HealthcheckWidget.intentdefinition; sourceTree = ""; };
- 9ABB37DA297B26A700FC9B74 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
- 9ABB37DC297B26A700FC9B74 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
- 9ABB37E6297B2BFF00FC9B74 /* MediumSizeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediumSizeView.swift; sourceTree = ""; };
- 9ABB37E8297B2C1600FC9B74 /* SmallSizeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmallSizeView.swift; sourceTree = ""; };
- 9ABB37EA297B2C2A00FC9B74 /* LargeSizeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LargeSizeView.swift; sourceTree = ""; };
- 9ABB37F5297B659200FC9B74 /* IPv64.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = IPv64.entitlements; sourceTree = ""; };
- 9ABB37F6297B65BF00FC9B74 /* HealthcheckWidgetExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = HealthcheckWidgetExtension.entitlements; sourceTree = ""; };
- 9ABB37F7297C6BDB00FC9B74 /* EditHealthcheckView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EditHealthcheckView.swift; sourceTree = ""; };
- 9AC2EDEB291ADFAF00140CD9 /* NewDomainDNSView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewDomainDNSView.swift; sourceTree = ""; };
- 9AD1D90129B9E26E00DD6057 /* IntegrationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntegrationView.swift; sourceTree = ""; };
- 9AD5DF5D2975B5DB007928F6 /* HealthcheckView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthcheckView.swift; sourceTree = ""; };
- 9AD5DF602975BAC3007928F6 /* HealthcheckStatsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthcheckStatsView.swift; sourceTree = ""; };
- 9AD5DF622975BAD7007928F6 /* HealthcheckStatsItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthcheckStatsItem.swift; sourceTree = ""; };
- 9AD5DF642975ECC1007928F6 /* NewHealthcheckView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewHealthcheckView.swift; sourceTree = ""; };
- 9AD7FE3D29B7ED0E001F72B7 /* IntegrationSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntegrationSelection.swift; sourceTree = ""; };
- 9AE5E22D298302280019D524 /* AccessoryInlineView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccessoryInlineView.swift; sourceTree = ""; };
+ D4E100000000000000000001 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = ""; };
+ C3D100000000000000000001 /* IPv64NotificationService.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = IPv64NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };
+ 9A0C48022EBA963700BEDFEA /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
+ 9A0C48042EBA963700BEDFEA /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
+ 9A2777102EAD457E0025862B /* IPv64-net-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "IPv64-net-Info.plist"; sourceTree = ""; };
+ 9A5178D32EA3995200731FFB /* IPv64.net.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = IPv64.net.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ 9A68F3472EBE088C0033CC42 /* IPv64WidgetExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = IPv64WidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
+ 9A68F35D2EBE08F70033CC42 /* IPv64WidgetExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = IPv64WidgetExtension.entitlements; sourceTree = ""; };
+ 9A8CA8AD2EA6969D0073978F /* ipv64.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = ipv64.icon; sourceTree = ""; };
+ 9A8CA8AE2EA6969D0073978F /* ipv64_beta.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = ipv64_beta.icon; sourceTree = ""; };
/* End PBXFileReference section */
-/* Begin PBXFrameworksBuildPhase section */
- 9A10DBF2298C206D00285C0A /* Frameworks */ = {
- isa = PBXFrameworksBuildPhase;
- buildActionMask = 2147483647;
- files = (
+/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
+ C3D100000000000000000007 /* Exceptions for "IPv64NotificationService" folder in "IPv64NotificationService" target */ = {
+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
+ membershipExceptions = (
+ Info.plist,
+ IPv64NotificationService.entitlements,
+ );
+ target = C3D100000000000000000009 /* IPv64NotificationService */;
+ };
+ 9A68F3572EBE088D0033CC42 /* Exceptions for "IPv64Widget" folder in "IPv64WidgetExtension" target */ = {
+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
+ membershipExceptions = (
+ Info.plist,
+ );
+ target = 9A68F3462EBE088C0033CC42 /* IPv64WidgetExtension */;
+ };
+ 9A68F3622EBE0A370033CC42 /* Exceptions for "IPv64" folder in "IPv64WidgetExtension" target */ = {
+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
+ membershipExceptions = (
+ Helpers/AppConfig.swift,
+ Helpers/Nodes/LocalNodeStore.swift,
+ Helpers/Nodes/LocalNodeURL.swift,
+ Helpers/Nodes/NodeTransport.swift,
+ Helpers/SecureStore.swift,
+ Helpers/WidgetHealthCache.swift,
+ Models/iLogger.swift,
+ );
+ target = 9A68F3462EBE088C0033CC42 /* IPv64WidgetExtension */;
+ };
+ 9A68F36D2EBE0C460033CC42 /* Exceptions for "IPv64Widget" folder in "IPv64.net" target */ = {
+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
+ membershipExceptions = (
+ AppIntent.swift,
+ Service/ApiServiceWidget.swift,
+ Service/HealthCheckEntity.swift,
+ );
+ target = 9A5178D22EA3995200731FFB /* IPv64.net */;
+ };
+/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
+
+/* Begin PBXFileSystemSynchronizedRootGroup section */
+ C3D100000000000000000008 /* IPv64NotificationService */ = {
+ isa = PBXFileSystemSynchronizedRootGroup;
+ exceptions = (
+ C3D100000000000000000007 /* Exceptions for "IPv64NotificationService" folder in "IPv64NotificationService" target */,
);
- runOnlyForDeploymentPostprocessing = 0;
+ path = IPv64NotificationService;
+ sourceTree = "";
};
- 9A3313F729844E4D009E47F5 /* Frameworks */ = {
+ 9A5178D52EA3995200731FFB /* IPv64 */ = {
+ isa = PBXFileSystemSynchronizedRootGroup;
+ exceptions = (
+ 9A68F3622EBE0A370033CC42 /* Exceptions for "IPv64" folder in "IPv64WidgetExtension" target */,
+ );
+ path = IPv64;
+ sourceTree = "";
+ };
+ 9A68F34A2EBE088C0033CC42 /* IPv64Widget */ = {
+ isa = PBXFileSystemSynchronizedRootGroup;
+ exceptions = (
+ 9A68F36D2EBE0C460033CC42 /* Exceptions for "IPv64Widget" folder in "IPv64.net" target */,
+ 9A68F3572EBE088D0033CC42 /* Exceptions for "IPv64Widget" folder in "IPv64WidgetExtension" target */,
+ );
+ path = IPv64Widget;
+ sourceTree = "";
+ };
+/* End PBXFileSystemSynchronizedRootGroup section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ C3D10000000000000000000B /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- 9A3313FC29844E4D009E47F5 /* Intents.framework in Frameworks */,
+ C3D100000000000000000003 /* SecNtfy in Frameworks */,
+ C3D1000000000000000000A1 /* SwiftyBeaver in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- 9AACEB85291851E1009B506D /* Frameworks */ = {
+ 9A5178D02EA3995200731FFB /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- 9A154B5B2989B7600021DD2E /* FirebaseMessaging in Frameworks */,
- 9A154B592989B7600021DD2E /* FirebaseCrashlytics in Frameworks */,
- 9A154B572989B7600021DD2E /* FirebaseAnalytics in Frameworks */,
- 9A6EC81D2A1749AA005C5D5A /* Toast in Frameworks */,
- 9A08D1D82979AB47002CF0E8 /* Introspect in Frameworks */,
+ 9AD116FC2EBCAC2000EE7E81 /* SwiftyBeaver in Frameworks */,
+ B1A0000000000000000000A1 /* IPv64 in Frameworks */,
+ B1A0000000000000000000A2 /* SecNtfy in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- 9ABB37C9297B26A600FC9B74 /* Frameworks */ = {
+ 9A68F3442EBE088C0033CC42 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- 9ABB37D1297B26A600FC9B74 /* SwiftUI.framework in Frameworks */,
- 9ABB37CF297B26A600FC9B74 /* WidgetKit.framework in Frameworks */,
+ 9A68F3492EBE088C0033CC42 /* SwiftUI.framework in Frameworks */,
+ 9A68F3482EBE088C0033CC42 /* WidgetKit.framework in Frameworks */,
+ 9A68F35C2EBE08C80033CC42 /* SwiftyBeaver in Frameworks */,
+ B1A0000000000000000000A3 /* IPv64 in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
- 9A10DBF6298C206D00285C0A /* NotificationService */ = {
- isa = PBXGroup;
- children = (
- 9A10DC02298C2B5E00285C0A /* NotificationService.entitlements */,
- 9A10DBF7298C206D00285C0A /* NotificationService.swift */,
- 9A10DBF9298C206D00285C0A /* Info.plist */,
- );
- path = NotificationService;
- sourceTree = "";
- };
- 9A3313FD29844E4D009E47F5 /* HealthcheckIntents */ = {
- isa = PBXGroup;
- children = (
- 9AA1F99F29847A5B00170C69 /* HealthcheckIntents.entitlements */,
- 9A3313FE29844E4D009E47F5 /* IntentHandler.swift */,
- 9A33140029844E4D009E47F5 /* Info.plist */,
- );
- path = HealthcheckIntents;
- sourceTree = "";
- };
- 9A5A359B29756EFA006F27EB /* WhatsNew */ = {
+ 9A0C48012EBA963700BEDFEA /* Frameworks */ = {
isa = PBXGroup;
children = (
- 9A5A359C29756EFA006F27EB /* WhatsNewView.swift */,
- 9A5A359D29756EFA006F27EB /* WhatsNewItemView.swift */,
- );
- path = WhatsNew;
- sourceTree = "";
- };
- 9A7CDCDB296DEA3900237D5B /* Sheets */ = {
- isa = PBXGroup;
- children = (
- 9AACEBA92918609F009B506D /* NewDomainView.swift */,
- 9AC2EDEB291ADFAF00140CD9 /* NewDomainDNSView.swift */,
- );
- path = Sheets;
- sourceTree = "";
- };
- 9A7CDCDC296DEA5800237D5B /* Domains */ = {
- isa = PBXGroup;
- children = (
- 9A7CDCDB296DEA3900237D5B /* Sheets */,
- 9AACEB8D291851E1009B506D /* ContentView.swift */,
- 9A8D5BE329197355006B8A74 /* DetailDomainView.swift */,
- );
- path = Domains;
- sourceTree = "";
- };
- 9A7CDCDD296DEA6500237D5B /* Account */ = {
- isa = PBXGroup;
- children = (
- 9A7CDCDF296DEBA200237D5B /* Items */,
- 9A0034FD2930F9460065E1F3 /* ProfilView.swift */,
- 9A003501293101350065E1F3 /* LogView.swift */,
- 9A003505293129930065E1F3 /* AccountView.swift */,
- 9A0034FF2930FD010065E1F3 /* IPView.swift */,
- 9A8D5C0429199141006B8A74 /* HelpView.swift */,
- 9A8482E72AC603B10072BF45 /* AccountListView.swift */,
- );
- path = Account;
- sourceTree = "";
- };
- 9A7CDCDE296DEA6F00237D5B /* Main */ = {
- isa = PBXGroup;
- children = (
- 9AA7B4DF2A82C7BD00A06B4D /* Blocklist */,
- 9AD1D90029B9E25C00DD6057 /* Integrations */,
- 9AD5DF5C2975B5C8007928F6 /* Healthcheck */,
- 9A5A359B29756EFA006F27EB /* WhatsNew */,
- 9A7CDCDD296DEA6500237D5B /* Account */,
- 9A7CDCDC296DEA5800237D5B /* Domains */,
- 9A7CDCE0296DEBD400237D5B /* Sheets */,
- 9AACEB9E2918524B009B506D /* LoginView.swift */,
- 9A0034FB2930F9200065E1F3 /* TabbView.swift */,
- 9AA7B4D12A82BDF900A06B4D /* Tabs.swift */,
- 9AAEF656297F0D3800726849 /* LockView.swift */,
- );
- path = Main;
- sourceTree = "";
- };
- 9A7CDCDF296DEBA200237D5B /* Items */ = {
- isa = PBXGroup;
- children = (
- 9A0035032931062B0065E1F3 /* LogItemView.swift */,
- );
- path = Items;
- sourceTree = "";
- };
- 9A7CDCE0296DEBD400237D5B /* Sheets */ = {
- isa = PBXGroup;
- children = (
- 9A8D5BE129196290006B8A74 /* ErrorSheetView.swift */,
- );
- path = Sheets;
- sourceTree = "";
- };
- 9A7CDCE1296DEBE800237D5B /* HelperViews */ = {
- isa = PBXGroup;
- children = (
- 9AB155C129747DAC0052F21E /* CodeScanner.swift */,
- 9AACEBA7291857AF009B506D /* SpinnerView.swift */,
- );
- path = HelperViews;
- sourceTree = "";
- };
- 9A7CDCE2296DEBF700237D5B /* Models&Helpers */ = {
- isa = PBXGroup;
- children = (
- 9AA7B4D72A82BFAD00A06B4D /* UserPrefs.swift */,
- 9AA7B4D32A82BF8600A06B4D /* HapticManager.swift */,
- 9AA7B4D42A82BF8600A06B4D /* SoundEffectManager.swift */,
- 9AAEF654297F089D00726849 /* Biometrics.swift */,
- 9AACEBA52918577D009B506D /* SetupPrefs.swift */,
- 9AACEBA0291853C9009B506D /* NetworkServices.swift */,
- 9AACEBA329185411009B506D /* Models.swift */,
- );
- path = "Models&Helpers";
- sourceTree = "";
- };
- 9AA7B4D92A82C63F00A06B4D /* Env */ = {
- isa = PBXGroup;
- children = (
- 9AA7B4DA2A82C64D00A06B4D /* Sounds */,
- );
- path = Env;
- sourceTree = "";
- };
- 9AA7B4DA2A82C64D00A06B4D /* Sounds */ = {
- isa = PBXGroup;
- children = (
- 9AA7B4DB2A82C66A00A06B4D /* tabSelection_old.wav */,
- 9AA7B4DC2A82C66B00A06B4D /* tabSelection.wav */,
- );
- path = Sounds;
- sourceTree = "";
- };
- 9AA7B4DF2A82C7BD00A06B4D /* Blocklist */ = {
- isa = PBXGroup;
- children = (
- 9AA7B4E02A82C7D400A06B4D /* BlocklistView.swift */,
- );
- path = Blocklist;
- sourceTree = "";
- };
- 9AACEB7F291851E1009B506D = {
- isa = PBXGroup;
- children = (
- 9ABB37F6297B65BF00FC9B74 /* HealthcheckWidgetExtension.entitlements */,
- 9AACEB8A291851E1009B506D /* IPv64 */,
- 9ABB37D2297B26A600FC9B74 /* HealthcheckWidget */,
- 9A3313FD29844E4D009E47F5 /* HealthcheckIntents */,
- 9A10DBF6298C206D00285C0A /* NotificationService */,
- 9ABB37CD297B26A600FC9B74 /* Frameworks */,
- 9AACEB89291851E1009B506D /* Products */,
- );
- sourceTree = "";
- };
- 9AACEB89291851E1009B506D /* Products */ = {
- isa = PBXGroup;
- children = (
- 9AACEB88291851E1009B506D /* IPv64.app */,
- 9ABB37CC297B26A600FC9B74 /* HealthcheckWidgetExtension.appex */,
- 9A3313FA29844E4D009E47F5 /* HealthcheckIntents.appex */,
- 9A10DBF5298C206D00285C0A /* NotificationService.appex */,
- );
- name = Products;
- sourceTree = "";
- };
- 9AACEB8A291851E1009B506D /* IPv64 */ = {
- isa = PBXGroup;
- children = (
- 9AA7B4D92A82C63F00A06B4D /* Env */,
- 9A154B5C2989B7EA0021DD2E /* GoogleService-Info.plist */,
- 9ABB37F5297B659200FC9B74 /* IPv64.entitlements */,
- 9AB155C329747F5C0052F21E /* Info.plist */,
- 9A7CDCE2296DEBF700237D5B /* Models&Helpers */,
- 9A7CDCE1296DEBE800237D5B /* HelperViews */,
- 9A7CDCDE296DEA6F00237D5B /* Main */,
- 9AACEB91291851E2009B506D /* Preview Content */,
- 9AACEB8B291851E1009B506D /* IPv64App.swift */,
- 9AACEB8F291851E2009B506D /* Assets.xcassets */,
- 9AACEB96291851E2009B506D /* IPv64.xcdatamodeld */,
- );
- path = IPv64;
- sourceTree = "";
- };
- 9AACEB91291851E2009B506D /* Preview Content */ = {
- isa = PBXGroup;
- children = (
- 9AACEB92291851E2009B506D /* Preview Assets.xcassets */,
- );
- path = "Preview Content";
- sourceTree = "";
- };
- 9ABB37CD297B26A600FC9B74 /* Frameworks */ = {
- isa = PBXGroup;
- children = (
- 9ABB37CE297B26A600FC9B74 /* WidgetKit.framework */,
- 9ABB37D0297B26A600FC9B74 /* SwiftUI.framework */,
- 9A3313FB29844E4D009E47F5 /* Intents.framework */,
+ 9A0C48022EBA963700BEDFEA /* WidgetKit.framework */,
+ 9A0C48042EBA963700BEDFEA /* SwiftUI.framework */,
);
name = Frameworks;
sourceTree = "";
};
- 9ABB37D2297B26A600FC9B74 /* HealthcheckWidget */ = {
+ 9A5178CA2EA3995200731FFB = {
isa = PBXGroup;
children = (
- 9ABB37EF297B2FEA00FC9B74 /* WidgetSizes */,
- 9ABB37D3297B26A600FC9B74 /* HealthcheckWidgetBundle.swift */,
- 9ABB37D5297B26A600FC9B74 /* HealthcheckWidgetLiveActivity.swift */,
- 9ABB37D7297B26A600FC9B74 /* HealthcheckWidget.swift */,
- 9ABB37D9297B26A600FC9B74 /* HealthcheckWidget.intentdefinition */,
- 9ABB37DA297B26A700FC9B74 /* Assets.xcassets */,
- 9ABB37DC297B26A700FC9B74 /* Info.plist */,
+ D4E100000000000000000001 /* Config.xcconfig */,
+ 9A68F35D2EBE08F70033CC42 /* IPv64WidgetExtension.entitlements */,
+ 9A2777102EAD457E0025862B /* IPv64-net-Info.plist */,
+ 9A8CA8AD2EA6969D0073978F /* ipv64.icon */,
+ 9A8CA8AE2EA6969D0073978F /* ipv64_beta.icon */,
+ 9A5178D52EA3995200731FFB /* IPv64 */,
+ 9A68F34A2EBE088C0033CC42 /* IPv64Widget */,
+ C3D100000000000000000008 /* IPv64NotificationService */,
+ 9A0C48012EBA963700BEDFEA /* Frameworks */,
+ 9A5178D42EA3995200731FFB /* Products */,
);
- path = HealthcheckWidget;
sourceTree = "";
};
- 9ABB37EF297B2FEA00FC9B74 /* WidgetSizes */ = {
+ 9A5178D42EA3995200731FFB /* Products */ = {
isa = PBXGroup;
children = (
- 9AE5E22D298302280019D524 /* AccessoryInlineView.swift */,
- 9ABB37E6297B2BFF00FC9B74 /* MediumSizeView.swift */,
- 9ABB37E8297B2C1600FC9B74 /* SmallSizeView.swift */,
- 9ABB37EA297B2C2A00FC9B74 /* LargeSizeView.swift */,
+ 9A5178D32EA3995200731FFB /* IPv64.net.app */,
+ 9A68F3472EBE088C0033CC42 /* IPv64WidgetExtension.appex */,
+ C3D100000000000000000001 /* IPv64NotificationService.appex */,
);
- path = WidgetSizes;
- sourceTree = "";
- };
- 9AD1D90029B9E25C00DD6057 /* Integrations */ = {
- isa = PBXGroup;
- children = (
- 9AD1D90129B9E26E00DD6057 /* IntegrationView.swift */,
- );
- path = Integrations;
- sourceTree = "";
- };
- 9AD5DF5C2975B5C8007928F6 /* Healthcheck */ = {
- isa = PBXGroup;
- children = (
- 9AD5DF662975ECD3007928F6 /* Sheets */,
- 9AD5DF5F2975B6E3007928F6 /* Items */,
- 9AD5DF5D2975B5DB007928F6 /* HealthcheckView.swift */,
- 9AB78EB6297740D00047FDFA /* DetailHealthcheckView.swift */,
- );
- path = Healthcheck;
- sourceTree = "";
- };
- 9AD5DF5F2975B6E3007928F6 /* Items */ = {
- isa = PBXGroup;
- children = (
- 9AD5DF602975BAC3007928F6 /* HealthcheckStatsView.swift */,
- 9AD5DF622975BAD7007928F6 /* HealthcheckStatsItem.swift */,
- );
- path = Items;
- sourceTree = "";
- };
- 9AD5DF662975ECD3007928F6 /* Sheets */ = {
- isa = PBXGroup;
- children = (
- 9ABB37F7297C6BDB00FC9B74 /* EditHealthcheckView.swift */,
- 9AD5DF642975ECC1007928F6 /* NewHealthcheckView.swift */,
- 9AD7FE3D29B7ED0E001F72B7 /* IntegrationSelection.swift */,
- );
- path = Sheets;
+ name = Products;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
- 9A10DBF4298C206D00285C0A /* NotificationService */ = {
+ C3D100000000000000000009 /* IPv64NotificationService */ = {
isa = PBXNativeTarget;
- buildConfigurationList = 9A10DBFD298C206D00285C0A /* Build configuration list for PBXNativeTarget "NotificationService" */;
+ buildConfigurationList = C3D10000000000000000000F /* Build configuration list for PBXNativeTarget "IPv64NotificationService" */;
buildPhases = (
- 9A10DBF1298C206D00285C0A /* Sources */,
- 9A10DBF2298C206D00285C0A /* Frameworks */,
- 9A10DBF3298C206D00285C0A /* Resources */,
+ C3D10000000000000000000A /* Sources */,
+ C3D10000000000000000000B /* Frameworks */,
+ C3D10000000000000000000C /* Resources */,
);
buildRules = (
);
dependencies = (
);
- name = NotificationService;
- productName = NotificationService;
- productReference = 9A10DBF5298C206D00285C0A /* NotificationService.appex */;
- productType = "com.apple.product-type.app-extension";
- };
- 9A3313F929844E4D009E47F5 /* HealthcheckIntents */ = {
- isa = PBXNativeTarget;
- buildConfigurationList = 9A33140629844E4D009E47F5 /* Build configuration list for PBXNativeTarget "HealthcheckIntents" */;
- buildPhases = (
- 9A3313F629844E4D009E47F5 /* Sources */,
- 9A3313F729844E4D009E47F5 /* Frameworks */,
- 9A3313F829844E4D009E47F5 /* Resources */,
- );
- buildRules = (
+ fileSystemSynchronizedGroups = (
+ C3D100000000000000000008 /* IPv64NotificationService */,
);
- dependencies = (
+ name = IPv64NotificationService;
+ packageProductDependencies = (
+ C3D100000000000000000004 /* SecNtfy */,
+ C3D1000000000000000000A2 /* SwiftyBeaver */,
);
- name = HealthcheckIntents;
- productName = HealthcheckIntents;
- productReference = 9A3313FA29844E4D009E47F5 /* HealthcheckIntents.appex */;
+ productName = IPv64NotificationService;
+ productReference = C3D100000000000000000001 /* IPv64NotificationService.appex */;
productType = "com.apple.product-type.app-extension";
};
- 9AACEB87291851E1009B506D /* IPv64 */ = {
+ 9A5178D22EA3995200731FFB /* IPv64.net */ = {
isa = PBXNativeTarget;
- buildConfigurationList = 9AACEB9B291851E2009B506D /* Build configuration list for PBXNativeTarget "IPv64" */;
+ buildConfigurationList = 9A5178DE2EA3995300731FFB /* Build configuration list for PBXNativeTarget "IPv64.net" */;
buildPhases = (
- 9AACEB84291851E1009B506D /* Sources */,
- 9AACEB85291851E1009B506D /* Frameworks */,
- 9AACEB86291851E1009B506D /* Resources */,
- 9ABB37E2297B26A700FC9B74 /* Embed Foundation Extensions */,
+ 9A5178CF2EA3995200731FFB /* Sources */,
+ 9A5178D02EA3995200731FFB /* Frameworks */,
+ 9A5178D12EA3995200731FFB /* Resources */,
+ 9A0C48152EBA963800BEDFEA /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
- 9ABB37E0297B26A700FC9B74 /* PBXTargetDependency */,
- 9A33140229844E4D009E47F5 /* PBXTargetDependency */,
- 9A10DBFB298C206D00285C0A /* PBXTargetDependency */,
+ 9A68F3552EBE088D0033CC42 /* PBXTargetDependency */,
+ C3D100000000000000000006 /* PBXTargetDependency */,
+ );
+ fileSystemSynchronizedGroups = (
+ 9A5178D52EA3995200731FFB /* IPv64 */,
);
- name = IPv64;
+ name = IPv64.net;
packageProductDependencies = (
- 9A08D1D72979AB47002CF0E8 /* Introspect */,
- 9A154B562989B7600021DD2E /* FirebaseAnalytics */,
- 9A154B582989B7600021DD2E /* FirebaseCrashlytics */,
- 9A154B5A2989B7600021DD2E /* FirebaseMessaging */,
- 9A6EC81C2A1749AA005C5D5A /* Toast */,
+ 9AD116FB2EBCAC2000EE7E81 /* SwiftyBeaver */,
+ B1A0000000000000000000B1 /* IPv64 */,
+ B1A0000000000000000000B2 /* SecNtfy */,
);
productName = IPv64;
- productReference = 9AACEB88291851E1009B506D /* IPv64.app */;
+ productReference = 9A5178D32EA3995200731FFB /* IPv64.net.app */;
productType = "com.apple.product-type.application";
};
- 9ABB37CB297B26A600FC9B74 /* HealthcheckWidgetExtension */ = {
+ 9A68F3462EBE088C0033CC42 /* IPv64WidgetExtension */ = {
isa = PBXNativeTarget;
- buildConfigurationList = 9ABB37E5297B26A700FC9B74 /* Build configuration list for PBXNativeTarget "HealthcheckWidgetExtension" */;
+ buildConfigurationList = 9A68F3582EBE088D0033CC42 /* Build configuration list for PBXNativeTarget "IPv64WidgetExtension" */;
buildPhases = (
- 9ABB37C8297B26A600FC9B74 /* Sources */,
- 9ABB37C9297B26A600FC9B74 /* Frameworks */,
- 9ABB37CA297B26A600FC9B74 /* Resources */,
+ 9A68F3432EBE088C0033CC42 /* Sources */,
+ 9A68F3442EBE088C0033CC42 /* Frameworks */,
+ 9A68F3452EBE088C0033CC42 /* Resources */,
);
buildRules = (
);
dependencies = (
);
- name = HealthcheckWidgetExtension;
- productName = HealthcheckWidgetExtension;
- productReference = 9ABB37CC297B26A600FC9B74 /* HealthcheckWidgetExtension.appex */;
+ fileSystemSynchronizedGroups = (
+ 9A68F34A2EBE088C0033CC42 /* IPv64Widget */,
+ );
+ name = IPv64WidgetExtension;
+ packageProductDependencies = (
+ 9A68F35B2EBE08C80033CC42 /* SwiftyBeaver */,
+ B1A0000000000000000000B3 /* IPv64 */,
+ );
+ productName = IPv64WidgetExtension;
+ productReference = 9A68F3472EBE088C0033CC42 /* IPv64WidgetExtension.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
- 9AACEB80291851E1009B506D /* Project object */ = {
+ 9A5178CB2EA3995200731FFB /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
- LastSwiftUpdateCheck = 1420;
- LastUpgradeCheck = 1500;
+ LastSwiftUpdateCheck = 2610;
+ LastUpgradeCheck = 2610;
TargetAttributes = {
- 9A10DBF4298C206D00285C0A = {
- CreatedOnToolsVersion = 14.2;
- };
- 9A3313F929844E4D009E47F5 = {
- CreatedOnToolsVersion = 14.2;
+ 9A5178D22EA3995200731FFB = {
+ CreatedOnToolsVersion = 26.0.1;
};
- 9AACEB87291851E1009B506D = {
- CreatedOnToolsVersion = 14.1;
+ 9A68F3462EBE088C0033CC42 = {
+ CreatedOnToolsVersion = 26.1;
};
- 9ABB37CB297B26A600FC9B74 = {
- CreatedOnToolsVersion = 14.2;
+ C3D100000000000000000009 = {
+ CreatedOnToolsVersion = 26.1;
};
};
};
- buildConfigurationList = 9AACEB83291851E1009B506D /* Build configuration list for PBXProject "IPv64" */;
- compatibilityVersion = "Xcode 14.0";
- developmentRegion = de;
+ buildConfigurationList = 9A5178CE2EA3995200731FFB /* Build configuration list for PBXProject "IPv64" */;
+ developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
- de,
+ en,
Base,
);
- mainGroup = 9AACEB7F291851E1009B506D;
+ mainGroup = 9A5178CA2EA3995200731FFB;
+ minimizedProjectReferenceProxies = 1;
packageReferences = (
- 9A08D1D62979AB47002CF0E8 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */,
- 9A154B552989B7600021DD2E /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */,
- 9A6EC81B2A1749AA005C5D5A /* XCRemoteSwiftPackageReference "toast-swift" */,
+ 9AD116FA2EBCAC2000EE7E81 /* XCRemoteSwiftPackageReference "SwiftyBeaver" */,
+ B1A0000000000000000000C1 /* XCRemoteSwiftPackageReference "IPv64-SPM" */,
+ B1A0000000000000000000C2 /* XCRemoteSwiftPackageReference "SecNtfy-SPM" */,
);
- productRefGroup = 9AACEB89291851E1009B506D /* Products */;
+ preferredProjectObjectVersion = 77;
+ productRefGroup = 9A5178D42EA3995200731FFB /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
- 9AACEB87291851E1009B506D /* IPv64 */,
- 9ABB37CB297B26A600FC9B74 /* HealthcheckWidgetExtension */,
- 9A3313F929844E4D009E47F5 /* HealthcheckIntents */,
- 9A10DBF4298C206D00285C0A /* NotificationService */,
+ 9A5178D22EA3995200731FFB /* IPv64.net */,
+ 9A68F3462EBE088C0033CC42 /* IPv64WidgetExtension */,
+ C3D100000000000000000009 /* IPv64NotificationService */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
- 9A10DBF3298C206D00285C0A /* Resources */ = {
- isa = PBXResourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
- 9A3313F829844E4D009E47F5 /* Resources */ = {
+ C3D10000000000000000000C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
- 9AACEB86291851E1009B506D /* Resources */ = {
+ 9A5178D12EA3995200731FFB /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 9AACEB93291851E2009B506D /* Preview Assets.xcassets in Resources */,
- 9AACEB90291851E2009B506D /* Assets.xcassets in Resources */,
- 9A154B5D2989B7EA0021DD2E /* GoogleService-Info.plist in Resources */,
- 9AA7B4DD2A82C66B00A06B4D /* tabSelection_old.wav in Resources */,
- 9AA7B4DE2A82C66B00A06B4D /* tabSelection.wav in Resources */,
+ 9A8CA8AF2EA6969D0073978F /* ipv64.icon in Resources */,
+ 9A8CA8B02EA6969D0073978F /* ipv64_beta.icon in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- 9ABB37CA297B26A600FC9B74 /* Resources */ = {
+ 9A68F3452EBE088C0033CC42 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 9ABB37F1297B380300FC9B74 /* Assets.xcassets in Resources */,
- 9ABB37DB297B26A700FC9B74 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
- 9A10DBF1298C206D00285C0A /* Sources */ = {
- isa = PBXSourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 9A10DC01298C29C600285C0A /* SetupPrefs.swift in Sources */,
- 9A10DBF8298C206D00285C0A /* NotificationService.swift in Sources */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
- 9A3313F629844E4D009E47F5 /* Sources */ = {
+ C3D10000000000000000000A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 9A33140A29845F21009E47F5 /* NetworkServices.swift in Sources */,
- 9A33140C29845F4B009E47F5 /* SetupPrefs.swift in Sources */,
- 9A3313FF29844E4D009E47F5 /* IntentHandler.swift in Sources */,
- 9A33140729844F1B009E47F5 /* HealthcheckWidget.intentdefinition in Sources */,
- 9A33140B29845F41009E47F5 /* Models.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- 9AACEB84291851E1009B506D /* Sources */ = {
+ 9A5178CF2EA3995200731FFB /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 9AA7B4E12A82C7D400A06B4D /* BlocklistView.swift in Sources */,
- 9AACEBA1291853C9009B506D /* NetworkServices.swift in Sources */,
- 9A10DC00298C285800285C0A /* NotificationService.swift in Sources */,
- 9A8D5C0529199141006B8A74 /* HelpView.swift in Sources */,
- 9A0034FE2930F9460065E1F3 /* ProfilView.swift in Sources */,
- 9ABB37F8297C6BDB00FC9B74 /* EditHealthcheckView.swift in Sources */,
- 9AA7B4D52A82BF8600A06B4D /* HapticManager.swift in Sources */,
- 9AD5DF612975BAC3007928F6 /* HealthcheckStatsView.swift in Sources */,
- 9AD5DF652975ECC1007928F6 /* NewHealthcheckView.swift in Sources */,
- 9AACEBA8291857AF009B506D /* SpinnerView.swift in Sources */,
- 9AD5DF632975BAD7007928F6 /* HealthcheckStatsItem.swift in Sources */,
- 9A003506293129930065E1F3 /* AccountView.swift in Sources */,
- 9AB155C229747DAC0052F21E /* CodeScanner.swift in Sources */,
- 9AACEB8E291851E1009B506D /* ContentView.swift in Sources */,
- 9AACEB8C291851E1009B506D /* IPv64App.swift in Sources */,
- 9AD1D90229B9E26E00DD6057 /* IntegrationView.swift in Sources */,
- 9AD5DF5E2975B5DB007928F6 /* HealthcheckView.swift in Sources */,
- 9A5A359F29756EFA006F27EB /* WhatsNewItemView.swift in Sources */,
- 9A003502293101350065E1F3 /* LogView.swift in Sources */,
- 9AACEBA62918577D009B506D /* SetupPrefs.swift in Sources */,
- 9AACEB9F2918524B009B506D /* LoginView.swift in Sources */,
- 9AA7B4D62A82BF8600A06B4D /* SoundEffectManager.swift in Sources */,
- 9AB78EB7297740D00047FDFA /* DetailHealthcheckView.swift in Sources */,
- 9AAEF657297F0D3800726849 /* LockView.swift in Sources */,
- 9A8D5BE429197355006B8A74 /* DetailDomainView.swift in Sources */,
- 9AC2EDEC291ADFAF00140CD9 /* NewDomainDNSView.swift in Sources */,
- 9AA7B4D82A82BFAD00A06B4D /* UserPrefs.swift in Sources */,
- 9AA7B4D22A82BDF900A06B4D /* Tabs.swift in Sources */,
- 9A0034FC2930F9200065E1F3 /* TabbView.swift in Sources */,
- 9A8482E82AC603B10072BF45 /* AccountListView.swift in Sources */,
- 9A0035002930FD010065E1F3 /* IPView.swift in Sources */,
- 9A0035042931062B0065E1F3 /* LogItemView.swift in Sources */,
- 9A8D5BE229196290006B8A74 /* ErrorSheetView.swift in Sources */,
- 9AAEF655297F089D00726849 /* Biometrics.swift in Sources */,
- 9ABB37DE297B26A700FC9B74 /* HealthcheckWidget.intentdefinition in Sources */,
- 9A5A359E29756EFA006F27EB /* WhatsNewView.swift in Sources */,
- 9AACEBAA2918609F009B506D /* NewDomainView.swift in Sources */,
- 9AACEB98291851E2009B506D /* IPv64.xcdatamodeld in Sources */,
- 9AD7FE3E29B7ED0E001F72B7 /* IntegrationSelection.swift in Sources */,
- 9A33140929845AF1009E47F5 /* IntentHandler.swift in Sources */,
- 9AACEBA429185411009B506D /* Models.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- 9ABB37C8297B26A600FC9B74 /* Sources */ = {
+ 9A68F3432EBE088C0033CC42 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 9ABB37EC297B2CD900FC9B74 /* SmallSizeView.swift in Sources */,
- 9ABB37D8297B26A600FC9B74 /* HealthcheckWidget.swift in Sources */,
- 9ABB37D4297B26A600FC9B74 /* HealthcheckWidgetBundle.swift in Sources */,
- 9ABB37F2297B533200FC9B74 /* NetworkServices.swift in Sources */,
- 9ABB37F0297B314400FC9B74 /* Models.swift in Sources */,
- 9ABB37ED297B2CD900FC9B74 /* LargeSizeView.swift in Sources */,
- 9A33140829845032009E47F5 /* IntentHandler.swift in Sources */,
- 9ABB37F3297B544800FC9B74 /* SetupPrefs.swift in Sources */,
- 9ABB37D6297B26A600FC9B74 /* HealthcheckWidgetLiveActivity.swift in Sources */,
- 9ABB37EE297B2CD900FC9B74 /* MediumSizeView.swift in Sources */,
- 9ABB37F4297B5CB800FC9B74 /* SpinnerView.swift in Sources */,
- 9AE5E22E298302280019D524 /* AccessoryInlineView.swift in Sources */,
- 9ABB37DD297B26A700FC9B74 /* HealthcheckWidget.intentdefinition in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
- 9A10DBFB298C206D00285C0A /* PBXTargetDependency */ = {
- isa = PBXTargetDependency;
- target = 9A10DBF4298C206D00285C0A /* NotificationService */;
- targetProxy = 9A10DBFA298C206D00285C0A /* PBXContainerItemProxy */;
- };
- 9A33140229844E4D009E47F5 /* PBXTargetDependency */ = {
+ C3D100000000000000000006 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
- target = 9A3313F929844E4D009E47F5 /* HealthcheckIntents */;
- targetProxy = 9A33140129844E4D009E47F5 /* PBXContainerItemProxy */;
+ target = C3D100000000000000000009 /* IPv64NotificationService */;
+ targetProxy = C3D100000000000000000005 /* PBXContainerItemProxy */;
};
- 9ABB37E0297B26A700FC9B74 /* PBXTargetDependency */ = {
+ 9A68F3552EBE088D0033CC42 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
- target = 9ABB37CB297B26A600FC9B74 /* HealthcheckWidgetExtension */;
- targetProxy = 9ABB37DF297B26A700FC9B74 /* PBXContainerItemProxy */;
+ target = 9A68F3462EBE088C0033CC42 /* IPv64WidgetExtension */;
+ targetProxy = 9A68F3542EBE088D0033CC42 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
- 9A10DBFE298C206D00285C0A /* Debug */ = {
+ C3D10000000000000000000D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- CODE_SIGN_ENTITLEMENTS = NotificationService/NotificationService.entitlements;
+ CODE_SIGN_ENTITLEMENTS = IPv64NotificationService/IPv64NotificationService.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
+ CURRENT_PROJECT_VERSION = 45;
DEVELOPMENT_TEAM = 3V2L6G4Y5X;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = NotificationService/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = NotificationService;
+ INFOPLIST_FILE = IPv64NotificationService/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = IPv64NotificationService;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
- IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
- MARKETING_VERSION = 1.2.2;
+ MARKETING_VERSION = 2.2.1;
PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.NotificationService;
PRODUCT_NAME = "$(TARGET_NAME)";
+ SDKROOT = iphoneos;
SKIP_INSTALL = YES;
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
+ SUPPORTS_MACCATALYST = NO;
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
- SWIFT_VERSION = 5.0;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
- 9A10DBFF298C206D00285C0A /* Release */ = {
+ C3D10000000000000000000E /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- CODE_SIGN_ENTITLEMENTS = NotificationService/NotificationService.entitlements;
+ CODE_SIGN_ENTITLEMENTS = IPv64NotificationService/IPv64NotificationService.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
+ CURRENT_PROJECT_VERSION = 45;
DEVELOPMENT_TEAM = 3V2L6G4Y5X;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = NotificationService/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = NotificationService;
+ INFOPLIST_FILE = IPv64NotificationService/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = IPv64NotificationService;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
- IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
- MARKETING_VERSION = 1.2.2;
+ MARKETING_VERSION = 2.2.1;
PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.NotificationService;
PRODUCT_NAME = "$(TARGET_NAME)";
+ SDKROOT = iphoneos;
SKIP_INSTALL = YES;
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
+ SUPPORTS_MACCATALYST = NO;
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
- SWIFT_VERSION = 5.0;
- TARGETED_DEVICE_FAMILY = "1,2";
- };
- name = Release;
- };
- 9A33140429844E4D009E47F5 /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- CODE_SIGN_ENTITLEMENTS = HealthcheckIntents/HealthcheckIntents.entitlements;
- CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
- DEVELOPMENT_TEAM = 3V2L6G4Y5X;
- GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = HealthcheckIntents/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = HealthcheckIntents;
- INFOPLIST_KEY_NSHumanReadableCopyright = "";
- IPHONEOS_DEPLOYMENT_TARGET = 15.0;
- LD_RUNPATH_SEARCH_PATHS = (
- "$(inherited)",
- "@executable_path/Frameworks",
- "@executable_path/../../Frameworks",
- );
- MARKETING_VERSION = 1.2.2;
- PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.HealthcheckIntents;
- PRODUCT_NAME = "$(TARGET_NAME)";
- SKIP_INSTALL = YES;
- SWIFT_EMIT_LOC_STRINGS = YES;
- SWIFT_VERSION = 5.0;
- TARGETED_DEVICE_FAMILY = "1,2";
- };
- name = Debug;
- };
- 9A33140529844E4D009E47F5 /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- CODE_SIGN_ENTITLEMENTS = HealthcheckIntents/HealthcheckIntents.entitlements;
- CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
- DEVELOPMENT_TEAM = 3V2L6G4Y5X;
- GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = HealthcheckIntents/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = HealthcheckIntents;
- INFOPLIST_KEY_NSHumanReadableCopyright = "";
- IPHONEOS_DEPLOYMENT_TARGET = 15.0;
- LD_RUNPATH_SEARCH_PATHS = (
- "$(inherited)",
- "@executable_path/Frameworks",
- "@executable_path/../../Frameworks",
- );
- MARKETING_VERSION = 1.2.2;
- PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.HealthcheckIntents;
- PRODUCT_NAME = "$(TARGET_NAME)";
- SKIP_INSTALL = YES;
- SWIFT_EMIT_LOC_STRINGS = YES;
- SWIFT_VERSION = 5.0;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
- 9AACEB99291851E2009B506D /* Debug */ = {
+ 9A5178DC2EA3995300731FFB /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
@@ -930,10 +495,11 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
+ DEVELOPMENT_TEAM = 3V2L6G4Y5X;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
- GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
@@ -947,20 +513,23 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 16.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 26.0;
+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
- SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
- 9AACEB9A291851E2009B506D /* Release */ = {
+ 9A5178DD2EA3995300731FFB /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
@@ -991,10 +560,11 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ DEVELOPMENT_TEAM = 3V2L6G4Y5X;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
- GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
@@ -1002,194 +572,250 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 16.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 26.0;
+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
- SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
- 9AACEB9C291851E2009B506D /* Debug */ = {
+ 9A5178DF2EA3995300731FFB /* Debug */ = {
isa = XCBuildConfiguration;
+ baseConfigurationReference = D4E100000000000000000001 /* Config.xcconfig */;
buildSettings = {
- ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ ASSETCATALOG_COMPILER_APPICON_NAME = ipv64;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = IPv64/IPv64.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
- DEVELOPMENT_ASSET_PATHS = "\"IPv64/Preview Content\"";
+ CURRENT_PROJECT_VERSION = 45;
DEVELOPMENT_TEAM = 3V2L6G4Y5X;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = IPv64/Info.plist;
+ INFOPLIST_FILE = "IPv64-net-Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = IPv64.net;
- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
- INFOPLIST_KEY_NSCameraUsageDescription = "Die App benötigt diese Berechtigung um den QR Code auszulesen.";
- INFOPLIST_KEY_NSFaceIDUsageDescription = "Die App benötigt diese Berechtigung um die Inhalte freizugeben, wenn aktiviert.";
+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities";
+ INFOPLIST_KEY_NSCameraUsageDescription = "We need camera access to scanthe QR code for the API Key.";
+ INFOPLIST_KEY_NSFaceIDUsageDescription = "Need to unlock the app, when Privacy settings enabled.";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
- INFOPLIST_KEY_UIStatusBarStyle = "";
- INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
- IPHONEOS_DEPLOYMENT_TARGET = 16.0;
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
+ IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
- MARKETING_VERSION = 1.2.2;
+ MARKETING_VERSION = 2.2.1;
PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64;
PRODUCT_NAME = "$(TARGET_NAME)";
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
+ SUPPORTS_MACCATALYST = NO;
+ SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
+ SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
- 9AACEB9D291851E2009B506D /* Release */ = {
+ 9A5178E02EA3995300731FFB /* Release */ = {
isa = XCBuildConfiguration;
+ baseConfigurationReference = D4E100000000000000000001 /* Config.xcconfig */;
buildSettings = {
- ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ ASSETCATALOG_COMPILER_APPICON_NAME = ipv64;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = IPv64/IPv64.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
- DEVELOPMENT_ASSET_PATHS = "\"IPv64/Preview Content\"";
+ CURRENT_PROJECT_VERSION = 45;
DEVELOPMENT_TEAM = 3V2L6G4Y5X;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = IPv64/Info.plist;
+ INFOPLIST_FILE = "IPv64-net-Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = IPv64.net;
- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
- INFOPLIST_KEY_NSCameraUsageDescription = "Die App benötigt diese Berechtigung um den QR Code auszulesen.";
- INFOPLIST_KEY_NSFaceIDUsageDescription = "Die App benötigt diese Berechtigung um die Inhalte freizugeben, wenn aktiviert.";
+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities";
+ INFOPLIST_KEY_NSCameraUsageDescription = "We need camera access to scanthe QR code for the API Key.";
+ INFOPLIST_KEY_NSFaceIDUsageDescription = "Need to unlock the app, when Privacy settings enabled.";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
- INFOPLIST_KEY_UIStatusBarStyle = "";
- INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
- IPHONEOS_DEPLOYMENT_TARGET = 16.0;
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
+ IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
- MARKETING_VERSION = 1.2.2;
+ MARKETING_VERSION = 2.2.1;
PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64;
PRODUCT_NAME = "$(TARGET_NAME)";
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
+ SUPPORTS_MACCATALYST = NO;
+ SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
+ SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
- 9ABB37E3297B26A700FC9B74 /* Debug */ = {
+ 9A68F3592EBE088D0033CC42 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
- CODE_SIGN_ENTITLEMENTS = HealthcheckWidgetExtension.entitlements;
+ CODE_SIGN_ENTITLEMENTS = IPv64WidgetExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
+ CURRENT_PROJECT_VERSION = 45;
DEVELOPMENT_TEAM = 3V2L6G4Y5X;
+ ENABLE_APP_SANDBOX = YES;
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_INCOMING_NETWORK_CONNECTIONS = YES;
+ ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;
+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = NO;
+ ENABLE_RESOURCE_ACCESS_BLUETOOTH = NO;
+ ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
+ ENABLE_RESOURCE_ACCESS_CAMERA = NO;
+ ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
+ ENABLE_RESOURCE_ACCESS_LOCATION = NO;
+ ENABLE_RESOURCE_ACCESS_PRINTING = NO;
+ ENABLE_RESOURCE_ACCESS_USB = NO;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = HealthcheckWidget/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = HealthcheckWidget;
+ INFOPLIST_FILE = IPv64Widget/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = IPv64Widget;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
- IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
- MARKETING_VERSION = 1.2.2;
- PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.HealthcheckWidget;
+ "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ "@executable_path/../../../../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.6;
+ MARKETING_VERSION = 2.2.1;
+ PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.IPv64Widget;
PRODUCT_NAME = "$(TARGET_NAME)";
+ REGISTER_APP_GROUPS = YES;
+ SDKROOT = auto;
SKIP_INSTALL = YES;
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
+ SUPPORTS_MACCATALYST = NO;
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
+ XROS_DEPLOYMENT_TARGET = 26.1;
};
name = Debug;
};
- 9ABB37E4297B26A700FC9B74 /* Release */ = {
+ 9A68F35A2EBE088D0033CC42 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
- CODE_SIGN_ENTITLEMENTS = HealthcheckWidgetExtension.entitlements;
+ CODE_SIGN_ENTITLEMENTS = IPv64WidgetExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 37;
+ CURRENT_PROJECT_VERSION = 45;
DEVELOPMENT_TEAM = 3V2L6G4Y5X;
+ ENABLE_APP_SANDBOX = YES;
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_INCOMING_NETWORK_CONNECTIONS = YES;
+ ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;
+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = NO;
+ ENABLE_RESOURCE_ACCESS_BLUETOOTH = NO;
+ ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
+ ENABLE_RESOURCE_ACCESS_CAMERA = NO;
+ ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
+ ENABLE_RESOURCE_ACCESS_LOCATION = NO;
+ ENABLE_RESOURCE_ACCESS_PRINTING = NO;
+ ENABLE_RESOURCE_ACCESS_USB = NO;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = HealthcheckWidget/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = HealthcheckWidget;
+ INFOPLIST_FILE = IPv64Widget/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = IPv64Widget;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
- IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
- MARKETING_VERSION = 1.2.2;
- PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.HealthcheckWidget;
+ "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ "@executable_path/../../../../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.6;
+ MARKETING_VERSION = 2.2.1;
+ PRODUCT_BUNDLE_IDENTIFIER = de.rpicloud.IPv64.IPv64Widget;
PRODUCT_NAME = "$(TARGET_NAME)";
+ REGISTER_APP_GROUPS = YES;
+ SDKROOT = auto;
SKIP_INSTALL = YES;
+ STRING_CATALOG_GENERATE_SYMBOLS = YES;
+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
+ SUPPORTS_MACCATALYST = NO;
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
+ XROS_DEPLOYMENT_TARGET = 26.1;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
- 9A10DBFD298C206D00285C0A /* Build configuration list for PBXNativeTarget "NotificationService" */ = {
- isa = XCConfigurationList;
- buildConfigurations = (
- 9A10DBFE298C206D00285C0A /* Debug */,
- 9A10DBFF298C206D00285C0A /* Release */,
- );
- defaultConfigurationIsVisible = 0;
- defaultConfigurationName = Release;
- };
- 9A33140629844E4D009E47F5 /* Build configuration list for PBXNativeTarget "HealthcheckIntents" */ = {
+ C3D10000000000000000000F /* Build configuration list for PBXNativeTarget "IPv64NotificationService" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 9A33140429844E4D009E47F5 /* Debug */,
- 9A33140529844E4D009E47F5 /* Release */,
+ C3D10000000000000000000D /* Debug */,
+ C3D10000000000000000000E /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
- 9AACEB83291851E1009B506D /* Build configuration list for PBXProject "IPv64" */ = {
+ 9A5178CE2EA3995200731FFB /* Build configuration list for PBXProject "IPv64" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 9AACEB99291851E2009B506D /* Debug */,
- 9AACEB9A291851E2009B506D /* Release */,
+ 9A5178DC2EA3995300731FFB /* Debug */,
+ 9A5178DD2EA3995300731FFB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
- 9AACEB9B291851E2009B506D /* Build configuration list for PBXNativeTarget "IPv64" */ = {
+ 9A5178DE2EA3995300731FFB /* Build configuration list for PBXNativeTarget "IPv64.net" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 9AACEB9C291851E2009B506D /* Debug */,
- 9AACEB9D291851E2009B506D /* Release */,
+ 9A5178DF2EA3995300731FFB /* Debug */,
+ 9A5178E02EA3995300731FFB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
- 9ABB37E5297B26A700FC9B74 /* Build configuration list for PBXNativeTarget "HealthcheckWidgetExtension" */ = {
+ 9A68F3582EBE088D0033CC42 /* Build configuration list for PBXNativeTarget "IPv64WidgetExtension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 9ABB37E3297B26A700FC9B74 /* Debug */,
- 9ABB37E4297B26A700FC9B74 /* Release */,
+ 9A68F3592EBE088D0033CC42 /* Debug */,
+ 9A68F35A2EBE088D0033CC42 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
@@ -1197,72 +823,69 @@
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
- 9A08D1D62979AB47002CF0E8 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */ = {
+ B1A0000000000000000000C1 /* XCRemoteSwiftPackageReference "IPv64-SPM" */ = {
isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/siteline/SwiftUI-Introspect.git";
+ repositoryURL = "https://github.com/androidseb25/IPv64-SPM";
requirement = {
kind = upToNextMajorVersion;
- minimumVersion = 0.1.4;
+ minimumVersion = 2.2.0;
};
};
- 9A154B552989B7600021DD2E /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = {
+ B1A0000000000000000000C2 /* XCRemoteSwiftPackageReference "SecNtfy-SPM" */ = {
isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/firebase/firebase-ios-sdk";
+ repositoryURL = "https://github.com/SecNtfy/SecNtfy-SPM";
requirement = {
- branch = main;
- kind = branch;
+ kind = upToNextMajorVersion;
+ minimumVersion = 1.3.1;
};
};
- 9A6EC81B2A1749AA005C5D5A /* XCRemoteSwiftPackageReference "toast-swift" */ = {
+ 9AD116FA2EBCAC2000EE7E81 /* XCRemoteSwiftPackageReference "SwiftyBeaver" */ = {
isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/BastiaanJansen/toast-swift";
+ repositoryURL = "https://github.com/SwiftyBeaver/SwiftyBeaver.git";
requirement = {
kind = upToNextMajorVersion;
- minimumVersion = 1.0.0;
+ minimumVersion = 2.1.1;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
- 9A08D1D72979AB47002CF0E8 /* Introspect */ = {
+ C3D100000000000000000004 /* SecNtfy */ = {
isa = XCSwiftPackageProductDependency;
- package = 9A08D1D62979AB47002CF0E8 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */;
- productName = Introspect;
+ package = B1A0000000000000000000C2 /* XCRemoteSwiftPackageReference "SecNtfy-SPM" */;
+ productName = SecNtfy;
};
- 9A154B562989B7600021DD2E /* FirebaseAnalytics */ = {
+ B1A0000000000000000000B1 /* IPv64 */ = {
isa = XCSwiftPackageProductDependency;
- package = 9A154B552989B7600021DD2E /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
- productName = FirebaseAnalytics;
+ package = B1A0000000000000000000C1 /* XCRemoteSwiftPackageReference "IPv64-SPM" */;
+ productName = IPv64;
};
- 9A154B582989B7600021DD2E /* FirebaseCrashlytics */ = {
+ B1A0000000000000000000B2 /* SecNtfy */ = {
isa = XCSwiftPackageProductDependency;
- package = 9A154B552989B7600021DD2E /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
- productName = FirebaseCrashlytics;
+ package = B1A0000000000000000000C2 /* XCRemoteSwiftPackageReference "SecNtfy-SPM" */;
+ productName = SecNtfy;
};
- 9A154B5A2989B7600021DD2E /* FirebaseMessaging */ = {
+ B1A0000000000000000000B3 /* IPv64 */ = {
isa = XCSwiftPackageProductDependency;
- package = 9A154B552989B7600021DD2E /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
- productName = FirebaseMessaging;
+ package = B1A0000000000000000000C1 /* XCRemoteSwiftPackageReference "IPv64-SPM" */;
+ productName = IPv64;
};
- 9A6EC81C2A1749AA005C5D5A /* Toast */ = {
+ 9A68F35B2EBE08C80033CC42 /* SwiftyBeaver */ = {
isa = XCSwiftPackageProductDependency;
- package = 9A6EC81B2A1749AA005C5D5A /* XCRemoteSwiftPackageReference "toast-swift" */;
- productName = Toast;
+ package = 9AD116FA2EBCAC2000EE7E81 /* XCRemoteSwiftPackageReference "SwiftyBeaver" */;
+ productName = SwiftyBeaver;
};
-/* End XCSwiftPackageProductDependency section */
-
-/* Begin XCVersionGroup section */
- 9AACEB96291851E2009B506D /* IPv64.xcdatamodeld */ = {
- isa = XCVersionGroup;
- children = (
- 9AACEB97291851E2009B506D /* IPv64.xcdatamodel */,
- );
- currentVersion = 9AACEB97291851E2009B506D /* IPv64.xcdatamodel */;
- path = IPv64.xcdatamodeld;
- sourceTree = "";
- versionGroupType = wrapper.xcdatamodel;
+ 9AD116FB2EBCAC2000EE7E81 /* SwiftyBeaver */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = 9AD116FA2EBCAC2000EE7E81 /* XCRemoteSwiftPackageReference "SwiftyBeaver" */;
+ productName = SwiftyBeaver;
};
-/* End XCVersionGroup section */
+ C3D1000000000000000000A2 /* SwiftyBeaver */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = 9AD116FA2EBCAC2000EE7E81 /* XCRemoteSwiftPackageReference "SwiftyBeaver" */;
+ productName = SwiftyBeaver;
+ };
+/* End XCSwiftPackageProductDependency section */
};
- rootObject = 9AACEB80291851E1009B506D /* Project object */;
+ rootObject = 9A5178CB2EA3995200731FFB /* Project object */;
}
diff --git a/IPv64.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/IPv64.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
deleted file mode 100644
index 18d9810..0000000
--- a/IPv64.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
- IDEDidComputeMac32BitWarning
-
-
-
diff --git a/IPv64.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/IPv64.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index f1898d6..e2b2801 100644
--- a/IPv64.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/IPv64.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,139 +1,40 @@
{
- "originHash" : "a0d41731ecb092e76a955293f45cb6cc0ed875a448ecf713132d85607ba7596e",
+ "originHash" : "d971f7a8d5672d3eab430a734697ea3e9c9aa59e9a2e2132f3c9b5bf4b950db0",
"pins" : [
{
- "identity" : "abseil-cpp-binary",
+ "identity" : "cryptoswift",
"kind" : "remoteSourceControl",
- "location" : "https://github.com/google/abseil-cpp-binary.git",
+ "location" : "https://github.com/krzyzanowskim/CryptoSwift.git",
"state" : {
- "revision" : "748c7837511d0e6a507737353af268484e1745e2",
- "version" : "1.2024011601.1"
+ "revision" : "f2a627b84c1ff96f21ac2fcb623ab36142dd5512",
+ "version" : "1.10.0"
}
},
{
- "identity" : "app-check",
+ "identity" : "ipv64-spm",
"kind" : "remoteSourceControl",
- "location" : "https://github.com/google/app-check.git",
+ "location" : "https://github.com/androidseb25/IPv64-SPM",
"state" : {
- "revision" : "7d2688de038d5484866d835acb47b379722d610e",
- "version" : "10.19.0"
+ "revision" : "d769b3f19093c6f93926b35264e1f2037b7e169e",
+ "version" : "2.2.0"
}
},
{
- "identity" : "firebase-ios-sdk",
+ "identity" : "secntfy-spm",
"kind" : "remoteSourceControl",
- "location" : "https://github.com/firebase/firebase-ios-sdk",
+ "location" : "https://github.com/SecNtfy/SecNtfy-SPM",
"state" : {
- "branch" : "main",
- "revision" : "c9d013b624a3415192d6644896ecd1856cbbc9e2"
+ "revision" : "5dc9aac55c7b98e7c94da272bac2d80e826555ce",
+ "version" : "1.3.1"
}
},
{
- "identity" : "googleappmeasurement",
+ "identity" : "swiftybeaver",
"kind" : "remoteSourceControl",
- "location" : "https://github.com/google/GoogleAppMeasurement.git",
+ "location" : "https://github.com/SwiftyBeaver/SwiftyBeaver.git",
"state" : {
- "revision" : "51ba746a9d51a4bd0774b68499b0c73ef6e8570d",
- "version" : "10.24.0"
- }
- },
- {
- "identity" : "googledatatransport",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/google/GoogleDataTransport.git",
- "state" : {
- "revision" : "a637d318ae7ae246b02d7305121275bc75ed5565",
- "version" : "9.4.0"
- }
- },
- {
- "identity" : "googleutilities",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/google/GoogleUtilities.git",
- "state" : {
- "revision" : "26c898aed8bed13b8a63057ee26500abbbcb8d55",
- "version" : "7.13.1"
- }
- },
- {
- "identity" : "grpc-binary",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/google/grpc-binary.git",
- "state" : {
- "revision" : "e9fad491d0673bdda7063a0341fb6b47a30c5359",
- "version" : "1.62.2"
- }
- },
- {
- "identity" : "gtm-session-fetcher",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/google/gtm-session-fetcher.git",
- "state" : {
- "revision" : "96d7cc73a71ce950723aa3c50ce4fb275ae180b8",
- "version" : "3.1.0"
- }
- },
- {
- "identity" : "interop-ios-for-google-sdks",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/google/interop-ios-for-google-sdks.git",
- "state" : {
- "revision" : "2d12673670417654f08f5f90fdd62926dc3a2648",
- "version" : "100.0.0"
- }
- },
- {
- "identity" : "leveldb",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/firebase/leveldb.git",
- "state" : {
- "revision" : "0706abcc6b0bd9cedfbb015ba840e4a780b5159b",
- "version" : "1.22.2"
- }
- },
- {
- "identity" : "nanopb",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/firebase/nanopb.git",
- "state" : {
- "revision" : "b7e1104502eca3a213b46303391ca4d3bc8ddec1",
- "version" : "2.30910.0"
- }
- },
- {
- "identity" : "promises",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/google/promises.git",
- "state" : {
- "revision" : "540318ecedd63d883069ae7f1ed811a2df00b6ac",
- "version" : "2.4.0"
- }
- },
- {
- "identity" : "swift-protobuf",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/apple/swift-protobuf.git",
- "state" : {
- "revision" : "ab3a58b7209a17d781c0d1dbb3e1ff3da306bae8",
- "version" : "1.20.3"
- }
- },
- {
- "identity" : "swiftui-introspect",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/siteline/SwiftUI-Introspect.git",
- "state" : {
- "revision" : "121c146fe591b1320238d054ae35c81ffa45f45a",
- "version" : "0.12.0"
- }
- },
- {
- "identity" : "toast-swift",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/BastiaanJansen/toast-swift",
- "state" : {
- "revision" : "bc52aa61d6a372da553d1d59bdd4e56037ae2f14",
- "version" : "1.5.0"
+ "revision" : "8cba041db09596183331d123f337d0eb2e6e8e91",
+ "version" : "2.1.1"
}
}
],
diff --git a/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/IDEFindNavigatorScopes.plist b/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/IDEFindNavigatorScopes.plist
deleted file mode 100644
index 5dd5da8..0000000
--- a/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/IDEFindNavigatorScopes.plist
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/UserInterfaceState.xcuserstate b/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/UserInterfaceState.xcuserstate
index 0887ca0..f3d3f01 100644
Binary files a/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/UserInterfaceState.xcuserstate and b/IPv64.xcodeproj/project.xcworkspace/xcuserdata/sebastianrank.xcuserdatad/UserInterfaceState.xcuserstate differ
diff --git a/IPv64.xcodeproj/xcshareddata/xcodecloud/manifest.json b/IPv64.xcodeproj/xcshareddata/xcodecloud/manifest.json
new file mode 100644
index 0000000..98581ad
--- /dev/null
+++ b/IPv64.xcodeproj/xcshareddata/xcodecloud/manifest.json
@@ -0,0 +1,9 @@
+{
+ "id" : "cfaedaa1-1c07-4954-a29f-ba4cead27d5b",
+ "targets" : [
+ {
+ "id" : "6FACAD94-FD8C-409A-87E3-6BC25F92BB06",
+ "name" : "IPv64"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/IPv64.xcodeproj/xcshareddata/xcschemes/IPv64.xcscheme b/IPv64.xcodeproj/xcshareddata/xcschemes/IPv64.net.xcscheme
similarity index 77%
rename from IPv64.xcodeproj/xcshareddata/xcschemes/IPv64.xcscheme
rename to IPv64.xcodeproj/xcshareddata/xcschemes/IPv64.net.xcscheme
index 5ffc3ae..6b9e922 100644
--- a/IPv64.xcodeproj/xcshareddata/xcschemes/IPv64.xcscheme
+++ b/IPv64.xcodeproj/xcshareddata/xcschemes/IPv64.net.xcscheme
@@ -1,10 +1,11 @@
+ LastUpgradeVersion = "2610"
+ version = "1.7">
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
@@ -26,9 +27,8 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- shouldUseLaunchSchemeArgsEnv = "YES">
-
-
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
@@ -61,9 +61,9 @@
runnableDebuggingMode = "0">
diff --git a/IPv64.xcodeproj/xcshareddata/xcschemes/HealthcheckWidgetExtension.xcscheme b/IPv64.xcodeproj/xcshareddata/xcschemes/IPv64WidgetExtension.xcscheme
similarity index 71%
rename from IPv64.xcodeproj/xcshareddata/xcschemes/HealthcheckWidgetExtension.xcscheme
rename to IPv64.xcodeproj/xcshareddata/xcschemes/IPv64WidgetExtension.xcscheme
index 55a37fc..bc9981f 100644
--- a/IPv64.xcodeproj/xcshareddata/xcschemes/HealthcheckWidgetExtension.xcscheme
+++ b/IPv64.xcodeproj/xcshareddata/xcschemes/IPv64WidgetExtension.xcscheme
@@ -1,11 +1,12 @@
+ version = "2.0">
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
@@ -29,9 +30,9 @@
buildForAnalyzing = "YES">
@@ -41,27 +42,28 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- shouldUseLaunchSchemeArgsEnv = "YES">
-
-
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
+ allowLocationSimulation = "YES"
+ launchAutomaticallySubstyle = "2">
@@ -73,19 +75,15 @@
-
-
diff --git a/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
index 2bec42a..1c23c6b 100644
--- a/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
+++ b/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
@@ -1,22 +1,68 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcschemes/xcschememanagement.plist b/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcschemes/xcschememanagement.plist
index 1fe6387..c683887 100644
--- a/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcschemes/xcschememanagement.plist
+++ b/IPv64.xcodeproj/xcuserdata/sebastianrank.xcuserdatad/xcschemes/xcschememanagement.plist
@@ -4,77 +4,30 @@
SchemeUserState
- HealthcheckIntents.xcscheme_^#shared#^_
+ IPv64.net.xcscheme_^#shared#^_
orderHint
- 2
-
- HealthcheckWidgetExtension.xcscheme_^#shared#^_
-
- orderHint
- 1
+ 0
IPv64.xcscheme_^#shared#^_
orderHint
0
- NotificationService.xcscheme_^#shared#^_
-
- orderHint
- 3
-
- Promises (Playground) 1.xcscheme
-
- isShown
-
- orderHint
- 5
-
- Promises (Playground) 2.xcscheme
-
- isShown
-
- orderHint
- 6
-
- Promises (Playground) 3.xcscheme
-
- isShown
-
- orderHint
- 7
-
- Promises (Playground) 4.xcscheme
-
- isShown
-
- orderHint
- 8
-
- Promises (Playground) 5.xcscheme
-
- isShown
-
- orderHint
- 9
-
- Promises (Playground).xcscheme
+ IPv64WidgetExtension.xcscheme_^#shared#^_
- isShown
-
orderHint
- 4
+ 1
SuppressBuildableAutocreation
- 9AACEB87291851E1009B506D
+ 9A0C47FF2EBA963700BEDFEA
primary
- 9ABB37CB297B26A600FC9B74
+ 9A5178D22EA3995200731FFB
primary
diff --git a/IPv64/.DS_Store b/IPv64/.DS_Store
index fd06470..eb4e04c 100644
Binary files a/IPv64/.DS_Store and b/IPv64/.DS_Store differ
diff --git a/IPv64/Assets.xcassets/.DS_Store b/IPv64/Assets.xcassets/.DS_Store
index 019752d..754d100 100644
Binary files a/IPv64/Assets.xcassets/.DS_Store and b/IPv64/Assets.xcassets/.DS_Store differ
diff --git a/IPv64/Assets.xcassets/AccentColor.colorset/Contents.json b/IPv64/Assets.xcassets/AccentColor.colorset/Contents.json
index d890719..eb87897 100644
--- a/IPv64/Assets.xcassets/AccentColor.colorset/Contents.json
+++ b/IPv64/Assets.xcassets/AccentColor.colorset/Contents.json
@@ -1,33 +1,6 @@
{
"colors" : [
{
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.000",
- "green" : "0.000",
- "red" : "0.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "1.000",
- "green" : "1.000",
- "red" : "1.000"
- }
- },
"idiom" : "universal"
}
],
diff --git a/IPv64/Assets.xcassets/AccountSelectionBG.colorset/Contents.json b/IPv64/Assets.xcassets/AccountSelectionBG.colorset/Contents.json
deleted file mode 100644
index b9bad3a..0000000
--- a/IPv64/Assets.xcassets/AccountSelectionBG.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.900",
- "green" : "0.975",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.004",
- "green" : "0.116",
- "red" : "0.153"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/AppIcon 1.appiconset/1024.png b/IPv64/Assets.xcassets/AppIcon 1.appiconset/1024.png
deleted file mode 100644
index b7ff8ec..0000000
Binary files a/IPv64/Assets.xcassets/AppIcon 1.appiconset/1024.png and /dev/null differ
diff --git a/IPv64/Assets.xcassets/AppIcon 1.appiconset/Contents.json b/IPv64/Assets.xcassets/AppIcon 1.appiconset/Contents.json
deleted file mode 100644
index cff1680..0000000
--- a/IPv64/Assets.xcassets/AppIcon 1.appiconset/Contents.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "images" : [
- {
- "filename" : "1024.png",
- "idiom" : "universal",
- "platform" : "ios",
- "size" : "1024x1024"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/AppIcon.appiconset/Contents.json b/IPv64/Assets.xcassets/AppIcon.appiconset/Contents.json
index 44ac9cc..2305880 100644
--- a/IPv64/Assets.xcassets/AppIcon.appiconset/Contents.json
+++ b/IPv64/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -1,7 +1,28 @@
{
"images" : [
{
- "filename" : "appstore.png",
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "tinted"
+ }
+ ],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
diff --git a/IPv64/Assets.xcassets/AppIcon.appiconset/appstore.png b/IPv64/Assets.xcassets/AppIcon.appiconset/appstore.png
deleted file mode 100644
index 46d9321..0000000
Binary files a/IPv64/Assets.xcassets/AppIcon.appiconset/appstore.png and /dev/null differ
diff --git a/IPv64/Assets.xcassets/Integration Icons/Contents.json b/IPv64/Assets.xcassets/Integration Icons/Contents.json
deleted file mode 100644
index 73c0059..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/Contents.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/discord_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/discord_icon.imageset/Contents.json
deleted file mode 100644
index 8a45823..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/discord_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "icons8-discord.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/gotify_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/gotify_icon.imageset/Contents.json
deleted file mode 100644
index 84f10a6..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/gotify_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "gotify-logo-notification.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/gotify_icon.imageset/gotify-logo-notification.svg b/IPv64/Assets.xcassets/Integration Icons/gotify_icon.imageset/gotify-logo-notification.svg
deleted file mode 100644
index d4c0727..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/gotify_icon.imageset/gotify-logo-notification.svg
+++ /dev/null
@@ -1,228 +0,0 @@
-
-
-
-
diff --git a/IPv64/Assets.xcassets/Integration Icons/matrix_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/matrix_icon.imageset/Contents.json
deleted file mode 100644
index 43e19b8..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/matrix_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "Matrix_icon.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/matrix_icon.imageset/Matrix_icon.svg b/IPv64/Assets.xcassets/Integration Icons/matrix_icon.imageset/Matrix_icon.svg
deleted file mode 100644
index 4e5bfb4..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/matrix_icon.imageset/Matrix_icon.svg
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
diff --git a/IPv64/Assets.xcassets/Integration Icons/ntfy_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/ntfy_icon.imageset/Contents.json
deleted file mode 100644
index 714ae6e..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/ntfy_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "ntfy-svgrepo-com.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/pushover_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/pushover_icon.imageset/Contents.json
deleted file mode 100644
index 94081d1..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/pushover_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "pushover-logo.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/telegram_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/telegram_icon.imageset/Contents.json
deleted file mode 100644
index d4f0ff9..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/telegram_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "icons8-telegram.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/Integration Icons/webhook_icon.imageset/Contents.json b/IPv64/Assets.xcassets/Integration Icons/webhook_icon.imageset/Contents.json
deleted file mode 100644
index 10d81e4..0000000
--- a/IPv64/Assets.xcassets/Integration Icons/webhook_icon.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "icons8-webhook.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/IPv64/Assets.xcassets/SectionBG.colorset/Contents.json b/IPv64/Assets.xcassets/SectionBG.colorset/Contents.json
deleted file mode 100644
index d9716c3..0000000
--- a/IPv64/Assets.xcassets/SectionBG.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "1.000",
- "green" : "1.000",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.161",
- "green" : "0.153",
- "red" : "0.153"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/accountSinceColor.colorset/Contents.json b/IPv64/Assets.xcassets/accountSinceColor.colorset/Contents.json
deleted file mode 100644
index fd9a75f..0000000
--- a/IPv64/Assets.xcassets/accountSinceColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.644",
- "green" : "0.644",
- "red" : "0.644"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.353",
- "green" : "0.353",
- "red" : "0.353"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/ipv64_logo.imageset/Contents.json b/IPv64/Assets.xcassets/appstore.symbolset/Contents.json
similarity index 61%
rename from IPv64/Assets.xcassets/ipv64_logo.imageset/Contents.json
rename to IPv64/Assets.xcassets/appstore.symbolset/Contents.json
index 4e051c8..9d4060e 100644
--- a/IPv64/Assets.xcassets/ipv64_logo.imageset/Contents.json
+++ b/IPv64/Assets.xcassets/appstore.symbolset/Contents.json
@@ -1,12 +1,12 @@
{
- "images" : [
- {
- "filename" : "ipv64_logo.png",
- "idiom" : "universal"
- }
- ],
"info" : {
"author" : "xcode",
"version" : 1
- }
+ },
+ "symbols" : [
+ {
+ "filename" : "appstore.svg",
+ "idiom" : "universal"
+ }
+ ]
}
diff --git a/IPv64/Assets.xcassets/appstore.symbolset/appstore.svg b/IPv64/Assets.xcassets/appstore.symbolset/appstore.svg
new file mode 100644
index 0000000..290ab03
--- /dev/null
+++ b/IPv64/Assets.xcassets/appstore.symbolset/appstore.svg
@@ -0,0 +1,103 @@
+
+
+
+
diff --git a/IPv64/Assets.xcassets/bolt.heart.badge.plus.symbolset/Contents.json b/IPv64/Assets.xcassets/bolt.heart.badge.plus.symbolset/Contents.json
new file mode 100644
index 0000000..b00a564
--- /dev/null
+++ b/IPv64/Assets.xcassets/bolt.heart.badge.plus.symbolset/Contents.json
@@ -0,0 +1,12 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "symbols" : [
+ {
+ "filename" : "bolt.heart.badge.plus.svg",
+ "idiom" : "universal"
+ }
+ ]
+}
diff --git a/IPv64/Assets.xcassets/bolt.heart.badge.plus.symbolset/bolt.heart.badge.plus.svg b/IPv64/Assets.xcassets/bolt.heart.badge.plus.symbolset/bolt.heart.badge.plus.svg
new file mode 100644
index 0000000..35259f9
--- /dev/null
+++ b/IPv64/Assets.xcassets/bolt.heart.badge.plus.symbolset/bolt.heart.badge.plus.svg
@@ -0,0 +1,127 @@
+
+
+
+
diff --git a/IPv64/Assets.xcassets/circleBG.colorset/Contents.json b/IPv64/Assets.xcassets/circleBG.colorset/Contents.json
deleted file mode 100644
index b003672..0000000
--- a/IPv64/Assets.xcassets/circleBG.colorset/Contents.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.957",
- "green" : "0.957",
- "red" : "0.957"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "extended-gray",
- "components" : {
- "alpha" : "1.000",
- "white" : "0.133"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/discord.imageset/Contents.json b/IPv64/Assets.xcassets/discord.imageset/Contents.json
new file mode 100644
index 0000000..036a606
--- /dev/null
+++ b/IPv64/Assets.xcassets/discord.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "discord.svg",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "discord_dark.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/Integration Icons/discord_icon.imageset/icons8-discord.svg b/IPv64/Assets.xcassets/discord.imageset/discord.svg
similarity index 100%
rename from IPv64/Assets.xcassets/Integration Icons/discord_icon.imageset/icons8-discord.svg
rename to IPv64/Assets.xcassets/discord.imageset/discord.svg
diff --git a/IPv64/Assets.xcassets/discord.imageset/discord_dark.svg b/IPv64/Assets.xcassets/discord.imageset/discord_dark.svg
new file mode 100644
index 0000000..9173b58
--- /dev/null
+++ b/IPv64/Assets.xcassets/discord.imageset/discord_dark.svg
@@ -0,0 +1,7 @@
+
+
+
diff --git a/IPv64/Assets.xcassets/gotify.imageset/Contents.json b/IPv64/Assets.xcassets/gotify.imageset/Contents.json
new file mode 100644
index 0000000..b148347
--- /dev/null
+++ b/IPv64/Assets.xcassets/gotify.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "gotify.svg",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "gotify_dark.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/gotify.imageset/gotify.svg b/IPv64/Assets.xcassets/gotify.imageset/gotify.svg
new file mode 100644
index 0000000..26622e7
--- /dev/null
+++ b/IPv64/Assets.xcassets/gotify.imageset/gotify.svg
@@ -0,0 +1,2 @@
+
+
\ No newline at end of file
diff --git a/IPv64/Assets.xcassets/gotify.imageset/gotify_dark.svg b/IPv64/Assets.xcassets/gotify.imageset/gotify_dark.svg
new file mode 100644
index 0000000..27d92c7
--- /dev/null
+++ b/IPv64/Assets.xcassets/gotify.imageset/gotify_dark.svg
@@ -0,0 +1,29 @@
+
+
+
\ No newline at end of file
diff --git a/IPv64/Assets.xcassets/ip64_color.colorset/Contents.json b/IPv64/Assets.xcassets/ip64_color.colorset/Contents.json
deleted file mode 100644
index 6ef924c..0000000
--- a/IPv64/Assets.xcassets/ip64_color.colorset/Contents.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.027",
- "green" : "0.757",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/ipv64_logo.imageset/ipv64_logo.png b/IPv64/Assets.xcassets/ipv64_logo.imageset/ipv64_logo.png
deleted file mode 100644
index cc13588..0000000
Binary files a/IPv64/Assets.xcassets/ipv64_logo.imageset/ipv64_logo.png and /dev/null differ
diff --git a/IPv64/Assets.xcassets/ipv64_logo_new.imageset/Contents.json b/IPv64/Assets.xcassets/ipv64_logo_new.imageset/Contents.json
deleted file mode 100644
index a3d279a..0000000
--- a/IPv64/Assets.xcassets/ipv64_logo_new.imageset/Contents.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "images" : [
- {
- "filename" : "ipv64_logo.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "original"
- }
-}
diff --git a/IPv64/Assets.xcassets/ipv64_logo_new.imageset/ipv64_logo.svg b/IPv64/Assets.xcassets/ipv64_logo_new.imageset/ipv64_logo.svg
deleted file mode 100644
index 625dcb7..0000000
--- a/IPv64/Assets.xcassets/ipv64_logo_new.imageset/ipv64_logo.svg
+++ /dev/null
@@ -1 +0,0 @@
-
\ No newline at end of file
diff --git a/IPv64/Assets.xcassets/lightgray.colorset/Contents.json b/IPv64/Assets.xcassets/lightgray.colorset/Contents.json
deleted file mode 100644
index 2fc7dae..0000000
--- a/IPv64/Assets.xcassets/lightgray.colorset/Contents.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "gray-gamma-22",
- "components" : {
- "alpha" : "1.000",
- "white" : "0.960"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/network.badge.plus.symbolset/Contents.json b/IPv64/Assets.xcassets/network.badge.plus.symbolset/Contents.json
new file mode 100644
index 0000000..3eafea9
--- /dev/null
+++ b/IPv64/Assets.xcassets/network.badge.plus.symbolset/Contents.json
@@ -0,0 +1,12 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "symbols" : [
+ {
+ "filename" : "network.badge.plus.svg",
+ "idiom" : "universal"
+ }
+ ]
+}
diff --git a/IPv64/Assets.xcassets/network.badge.plus.symbolset/network.badge.plus.svg b/IPv64/Assets.xcassets/network.badge.plus.symbolset/network.badge.plus.svg
new file mode 100644
index 0000000..a6da267
--- /dev/null
+++ b/IPv64/Assets.xcassets/network.badge.plus.symbolset/network.badge.plus.svg
@@ -0,0 +1,121 @@
+
+
+
+
diff --git a/IPv64/Assets.xcassets/ntfy.imageset/Contents.json b/IPv64/Assets.xcassets/ntfy.imageset/Contents.json
new file mode 100644
index 0000000..e1f1d2a
--- /dev/null
+++ b/IPv64/Assets.xcassets/ntfy.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "ntfy.svg",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "ntfy_dark.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/Integration Icons/ntfy_icon.imageset/ntfy-svgrepo-com.svg b/IPv64/Assets.xcassets/ntfy.imageset/ntfy.svg
similarity index 100%
rename from IPv64/Assets.xcassets/Integration Icons/ntfy_icon.imageset/ntfy-svgrepo-com.svg
rename to IPv64/Assets.xcassets/ntfy.imageset/ntfy.svg
diff --git a/IPv64/Assets.xcassets/ntfy.imageset/ntfy_dark.svg b/IPv64/Assets.xcassets/ntfy.imageset/ntfy_dark.svg
new file mode 100644
index 0000000..9d6c058
--- /dev/null
+++ b/IPv64/Assets.xcassets/ntfy.imageset/ntfy_dark.svg
@@ -0,0 +1,7 @@
+
+
+
\ No newline at end of file
diff --git a/IPv64/Assets.xcassets/primaryText.colorset/Contents.json b/IPv64/Assets.xcassets/primaryText.colorset/Contents.json
deleted file mode 100644
index d890719..0000000
--- a/IPv64/Assets.xcassets/primaryText.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.000",
- "green" : "0.000",
- "red" : "0.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "1.000",
- "green" : "1.000",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Preview Content/.DS_Store b/IPv64/Assets.xcassets/pushover.imageset/.DS_Store
similarity index 92%
rename from IPv64/Preview Content/.DS_Store
rename to IPv64/Assets.xcassets/pushover.imageset/.DS_Store
index dad7d8a..5008ddf 100644
Binary files a/IPv64/Preview Content/.DS_Store and b/IPv64/Assets.xcassets/pushover.imageset/.DS_Store differ
diff --git a/IPv64/Assets.xcassets/pushover.imageset/Contents.json b/IPv64/Assets.xcassets/pushover.imageset/Contents.json
new file mode 100644
index 0000000..5890f6c
--- /dev/null
+++ b/IPv64/Assets.xcassets/pushover.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "pushover.svg",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "pushover_dark.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/pushover.imageset/pushover.svg b/IPv64/Assets.xcassets/pushover.imageset/pushover.svg
new file mode 100644
index 0000000..643c665
--- /dev/null
+++ b/IPv64/Assets.xcassets/pushover.imageset/pushover.svg
@@ -0,0 +1,8 @@
+
+
+
diff --git a/IPv64/Assets.xcassets/Integration Icons/pushover_icon.imageset/pushover-logo.svg b/IPv64/Assets.xcassets/pushover.imageset/pushover_dark.svg
similarity index 100%
rename from IPv64/Assets.xcassets/Integration Icons/pushover_icon.imageset/pushover-logo.svg
rename to IPv64/Assets.xcassets/pushover.imageset/pushover_dark.svg
diff --git a/IPv64/Assets.xcassets/telegram.imageset/Contents.json b/IPv64/Assets.xcassets/telegram.imageset/Contents.json
new file mode 100644
index 0000000..4f9dd28
--- /dev/null
+++ b/IPv64/Assets.xcassets/telegram.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "telegram.svg",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "telegram_dark.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/Integration Icons/telegram_icon.imageset/icons8-telegram.svg b/IPv64/Assets.xcassets/telegram.imageset/telegram.svg
similarity index 100%
rename from IPv64/Assets.xcassets/Integration Icons/telegram_icon.imageset/icons8-telegram.svg
rename to IPv64/Assets.xcassets/telegram.imageset/telegram.svg
diff --git a/IPv64/Assets.xcassets/telegram.imageset/telegram_dark.svg b/IPv64/Assets.xcassets/telegram.imageset/telegram_dark.svg
new file mode 100644
index 0000000..4a11c8c
--- /dev/null
+++ b/IPv64/Assets.xcassets/telegram.imageset/telegram_dark.svg
@@ -0,0 +1,5 @@
+
+
+
diff --git a/IPv64/Assets.xcassets/textFieldBG.colorset/Contents.json b/IPv64/Assets.xcassets/textFieldBG.colorset/Contents.json
deleted file mode 100644
index 6d99af2..0000000
--- a/IPv64/Assets.xcassets/textFieldBG.colorset/Contents.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "extended-gray",
- "components" : {
- "alpha" : "1.000",
- "white" : "0.920"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "extended-gray",
- "components" : {
- "alpha" : "1.000",
- "white" : "0.133"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Assets.xcassets/v64-logo.imageset/Contents.json b/IPv64/Assets.xcassets/v64-logo.imageset/Contents.json
new file mode 100644
index 0000000..96202e4
--- /dev/null
+++ b/IPv64/Assets.xcassets/v64-logo.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "ipv64-iOS-Default-1024x1024@1x.png",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "ipv64-iOS-Dark-1024x1024@1x.png",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/v64-logo.imageset/ipv64-iOS-Dark-1024x1024@1x.png b/IPv64/Assets.xcassets/v64-logo.imageset/ipv64-iOS-Dark-1024x1024@1x.png
new file mode 100644
index 0000000..75607f3
Binary files /dev/null and b/IPv64/Assets.xcassets/v64-logo.imageset/ipv64-iOS-Dark-1024x1024@1x.png differ
diff --git a/IPv64/Assets.xcassets/v64-logo.imageset/ipv64-iOS-Default-1024x1024@1x.png b/IPv64/Assets.xcassets/v64-logo.imageset/ipv64-iOS-Default-1024x1024@1x.png
new file mode 100644
index 0000000..b4aebf7
Binary files /dev/null and b/IPv64/Assets.xcassets/v64-logo.imageset/ipv64-iOS-Default-1024x1024@1x.png differ
diff --git a/IPv64/Assets.xcassets/webhook.imageset/Contents.json b/IPv64/Assets.xcassets/webhook.imageset/Contents.json
new file mode 100644
index 0000000..2bd922a
--- /dev/null
+++ b/IPv64/Assets.xcassets/webhook.imageset/Contents.json
@@ -0,0 +1,22 @@
+{
+ "images" : [
+ {
+ "filename" : "webhook.svg",
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "webhook_dark.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/IPv64/Assets.xcassets/Integration Icons/webhook_icon.imageset/icons8-webhook.svg b/IPv64/Assets.xcassets/webhook.imageset/webhook.svg
similarity index 100%
rename from IPv64/Assets.xcassets/Integration Icons/webhook_icon.imageset/icons8-webhook.svg
rename to IPv64/Assets.xcassets/webhook.imageset/webhook.svg
diff --git a/IPv64/Assets.xcassets/webhook.imageset/webhook_dark.svg b/IPv64/Assets.xcassets/webhook.imageset/webhook_dark.svg
new file mode 100644
index 0000000..1144f36
--- /dev/null
+++ b/IPv64/Assets.xcassets/webhook.imageset/webhook_dark.svg
@@ -0,0 +1,5 @@
+
+
+
diff --git a/IPv64/ContentView.swift b/IPv64/ContentView.swift
new file mode 100644
index 0000000..45de3f2
--- /dev/null
+++ b/IPv64/ContentView.swift
@@ -0,0 +1,141 @@
+//
+// ContentView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 18.10.25.
+//
+
+import SwiftUI
+import UserNotifications
+
+struct ContentView: View {
+
+ @Environment(\.scenePhase) var scenePhase
+
+ @StateObject var networkMonitor = NetworkMonitor()
+ @EnvironmentObject private var biometrics: Biometrics
+ @StateObject private var userStorage = UserStorage.shared
+ @State private var showWhatsNew = false
+ @State private var activeSheet: ActiveSheet? = nil
+ @Environment(Session.self) private var session
+ @Environment(PushRegistrar.self) private var registrar
+ @Environment(ConnectedNodes.self) private var nodes
+ @State private var showPushSetup = false
+
+ /// After login: sync a changed device token, then open "Push notifications" once per account unless it is
+ /// done or this device already has a channel (Android `MainActivity` + `PushSetupStore.shouldShow`).
+ private func runPushLogic() async {
+ let apiKey = session.apiKey
+ await registrar.ensureAccountId()
+ nodes.syncWithCloud(force: true)
+ _ = try? await registrar.syncTokenIfChanged(channels: nil)
+ guard !Task.isCancelled, PushSetupStore.shouldShow(apiKey: apiKey),
+ let account = PushSetupStore.scope(apiKey: apiKey), registrar.setupTriggeredFor != account else { return }
+ registrar.setupTriggeredFor = account
+ showPushSetup = true
+ }
+
+ var body: some View {
+ ZStack {
+ if (userStorage.ShowWelcomeView) {
+ WelcomeView()
+ } else if !biometrics.isAuthenticated && userStorage.EnableLogscreen {
+ BiometricsLockView()
+ } else if userStorage.ShowLoginView || userStorage.ApiKey.isEmpty {
+ NavigationStack {
+ LoginView()
+ }
+ .appReadableWidth()
+ } else {
+ TabbarView()
+ .id(userStorage.sessionID)
+ .tint(.orange)
+ .task(id: userStorage.ApiKey) { await runPushLogic() }
+ .sheet(isPresented: $showPushSetup, onDismiss: { registrar.setupClosed += 1 }) {
+ NavigationStack { PushSetupView() }.tint(.orange).appReadableWidth()
+ }
+ // Skipped / done in another window: close this window's copy too.
+ .onChange(of: registrar.setupClosed) {
+ if !PushSetupStore.shouldShow(apiKey: session.apiKey) { showPushSetup = false }
+ }
+ .safeAreaInset(edge: .top, spacing: 0) {
+ if !networkMonitor.isConnected {
+ Label("Offline · Showing previously loaded data", systemImage: "wifi.slash")
+ .font(.footnote)
+ .frame(maxWidth: .infinity)
+ .padding(8)
+ .background(.thinMaterial)
+ }
+ }
+ }
+ }
+ .alert("Secure storage unavailable", isPresented: Binding(
+ get: { userStorage.storageError != nil },
+ set: { if !$0 { userStorage.storageError = nil } }
+ )) {
+ Button("OK", role: .cancel) { userStorage.storageError = nil }
+ } message: {
+ Text(userStorage.storageError ?? "")
+ }
+ .onChange(of: scenePhase) { _, newPhase in
+ if newPhase == .active {
+ // Opening the app clears the badge (counter kept by the Notification Service Extension)
+ // and removes its notifications from Notification Center.
+ UserStorage.sharedDefault?.set(0, forKey: "BADGE_COUNT")
+ UNUserNotificationCenter.current().setBadgeCount(0)
+ UNUserNotificationCenter.current().removeAllDeliveredNotifications()
+ userStorage.InAppSwitcher = false
+ // Retries the account id too: the first lookup may have failed offline.
+ Task { await registrar.ensureAccountId(); nodes.syncWithCloud() }
+ } else if newPhase == .inactive {
+ biometrics.isAuthenticated = false
+ userStorage.InAppSwitcher = true
+ } else if newPhase == .background {
+ biometrics.disableFields = false
+ biometrics.isAuthenticated = false
+ userStorage.InAppSwitcher = false
+ }
+ }
+ .onAppear {
+ let bnd = Int(userStorage.LAST_BUILD_NUMBER) ?? 0
+
+ if bnd != Int(Bundle.main.buildNumber) && !userStorage.ShowWelcomeView {
+ withAnimation {
+ showWhatsNew = true
+ activeSheet = .whatsnew
+ }
+ }
+ }
+ // Closed in another window (LAST_BUILD_NUMBER is shared): close this window's copy too.
+ .onChange(of: userStorage.LAST_BUILD_NUMBER) { _, build in
+ if build == Bundle.main.buildNumber {
+ showWhatsNew = false
+ activeSheet = nil
+ }
+ }
+ .sheet(item: $activeSheet) { item in
+ showActiveSheet(item: item)
+ }
+ .screenshotProtected(userStorage.ScreenshotProtection)
+ }
+
+ @ViewBuilder
+ private func showActiveSheet(item: ActiveSheet?) -> some View {
+ switch item {
+ case .whatsnew:
+ if #available(iOS 26.0, *) {
+ WhatsNewView26(activeSheet: $activeSheet, isPresented: $showWhatsNew, isFromSetting: true)
+ .interactiveDismissDisabled(true)
+ } else {
+ WhatsNewView(activeSheet: $activeSheet, isPresented: $showWhatsNew, isFromSetting: true)
+ .interactiveDismissDisabled(true)
+ }
+ default:
+ EmptyView()
+ }
+ }
+}
+
+#Preview {
+ ContentView()
+}
diff --git a/IPv64/Env/Sounds/tabSelection.wav b/IPv64/Env/Sounds/tabSelection.wav
deleted file mode 100644
index 2183344..0000000
Binary files a/IPv64/Env/Sounds/tabSelection.wav and /dev/null differ
diff --git a/IPv64/Env/Sounds/tabSelection_old.wav b/IPv64/Env/Sounds/tabSelection_old.wav
deleted file mode 100644
index dcdb728..0000000
Binary files a/IPv64/Env/Sounds/tabSelection_old.wav and /dev/null differ
diff --git a/IPv64/GoogleService-Info.plist b/IPv64/GoogleService-Info.plist
deleted file mode 100644
index f4eb111..0000000
--- a/IPv64/GoogleService-Info.plist
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
-
- CLIENT_ID
- 245002644962-rrkudf4qu75umfho26b7au5b9i0jl6il.apps.googleusercontent.com
- REVERSED_CLIENT_ID
- com.googleusercontent.apps.245002644962-rrkudf4qu75umfho26b7au5b9i0jl6il
- API_KEY
- AIzaSyBSnFeP9RGUWYK6_oSWclwz-5Wi4Sk1JJg
- GCM_SENDER_ID
- 245002644962
- PLIST_VERSION
- 1
- BUNDLE_ID
- de.rpicloud.IPv64
- PROJECT_ID
- ipv64-b6e12
- STORAGE_BUCKET
- ipv64-b6e12.appspot.com
- IS_ADS_ENABLED
-
- IS_ANALYTICS_ENABLED
-
- IS_APPINVITE_ENABLED
-
- IS_GCM_ENABLED
-
- IS_SIGNIN_ENABLED
-
- GOOGLE_APP_ID
- 1:245002644962:ios:7d77b9a29458c99f451dbb
-
-
\ No newline at end of file
diff --git a/IPv64/HelperViews/CodeScanner.swift b/IPv64/HelperViews/CodeScanner.swift
deleted file mode 100755
index 6569896..0000000
--- a/IPv64/HelperViews/CodeScanner.swift
+++ /dev/null
@@ -1,320 +0,0 @@
-//
-// CodeScannerView.swift
-//
-// Created by Paul Hudson on 10/12/2019.
-// Copyright © 2019 Paul Hudson. All rights reserved.
-//
-
-import AVFoundation
-import SwiftUI
-
-/// A SwiftUI view that is able to scan barcodes, QR codes, and more, and send back what was found.
-/// To use, set `codeTypes` to be an array of things to scan for, e.g. `[.qr]`, and set `completion` to
-/// a closure that will be called when scanning has finished. This will be sent the string that was detected or a `ScanError`.
-/// For testing inside the simulator, set the `simulatedData` property to some test data you want to send back.
-public struct CodeScannerView: UIViewControllerRepresentable {
- public enum ScanError: Error {
- case badInput, badOutput
- }
-
- public enum ScanMode {
- case once, oncePerCode, continuous
- }
-
- public class ScannerCoordinator: NSObject, AVCaptureMetadataOutputObjectsDelegate {
- var parent: CodeScannerView
- var codesFound: Set
- var isFinishScanning = false
- var lastTime = Date(timeIntervalSince1970: 0)
-
- init(parent: CodeScannerView) {
- self.parent = parent
- self.codesFound = Set()
- }
-
- public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
- if let metadataObject = metadataObjects.first {
- guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
- guard let stringValue = readableObject.stringValue else { return }
- guard isFinishScanning == false else { return }
-
- switch self.parent.scanMode {
- case .once:
- found(code: stringValue)
- // make sure we only trigger scan once per use
- isFinishScanning = true
- case .oncePerCode:
- if !codesFound.contains(stringValue) {
- codesFound.insert(stringValue)
- found(code: stringValue)
- }
- case .continuous:
- if isPastScanInterval() {
- found(code: stringValue)
- }
- }
- }
- }
-
- func isPastScanInterval() -> Bool {
- return Date().timeIntervalSince(lastTime) >= self.parent.scanInterval
- }
-
- func found(code: String) {
- lastTime = Date()
- AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
- parent.completion(.success(code))
- }
-
- func didFail(reason: ScanError) {
- parent.completion(.failure(reason))
- }
- }
-
- #if targetEnvironment(simulator)
- public class ScannerViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
- var delegate: ScannerCoordinator?
- override public func loadView() {
- view = UIView()
- view.isUserInteractionEnabled = true
- let label = UILabel()
- label.translatesAutoresizingMaskIntoConstraints = false
- label.numberOfLines = 0
-
- label.text = "Du benutzt einen Simulator!"
- label.textAlignment = .center
- let button = UIButton()
- button.translatesAutoresizingMaskIntoConstraints = false
- button.setTitle("Drücke hier um ein QR-Code einzulesen", for: .normal)
- button.setTitleColor(UIColor.systemBlue, for: .normal)
- button.setTitleColor(UIColor.gray, for: .highlighted)
- button.addTarget(self, action: #selector(self.openGallery), for: .touchUpInside)
-
- let stackView = UIStackView()
- stackView.translatesAutoresizingMaskIntoConstraints = false
- stackView.axis = .vertical
- stackView.spacing = 50
- stackView.addArrangedSubview(label)
- stackView.addArrangedSubview(button)
-
- view.addSubview(stackView)
-
- NSLayoutConstraint.activate([
- button.heightAnchor.constraint(equalToConstant: 50),
- stackView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
- stackView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
- stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
- ])
- }
-
- override public func touchesBegan(_ touches: Set, with event: UIEvent?) {
- guard let simulatedData = delegate?.parent.simulatedData else {
- print("Simulated Data Not Provided!")
- return
- }
-
- delegate?.found(code: simulatedData)
- }
-
- @objc func openGallery(_ sender: UIButton){
- let imagePicker = UIImagePickerController()
- imagePicker.delegate = self
- self.present(imagePicker, animated: true, completion: nil)
- }
-
- public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
- if let qrcodeImg = info[.originalImage] as? UIImage {
- let detector:CIDetector=CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])!
- let ciImage:CIImage=CIImage(image:qrcodeImg)!
- var qrCodeLink=""
-
- let features=detector.features(in: ciImage)
- for feature in features as! [CIQRCodeFeature] {
- qrCodeLink += feature.messageString!
- }
-
- if qrCodeLink=="" {
- delegate?.didFail(reason: .badOutput)
- }else{
- delegate?.found(code: qrCodeLink)
- }
- }
- else{
- print("Something went wrong")
- }
- self.dismiss(animated: true, completion: nil)
- }
- }
- #else
- public class ScannerViewController: UIViewController {
- var captureSession: AVCaptureSession!
- var previewLayer: AVCaptureVideoPreviewLayer!
- var delegate: ScannerCoordinator?
- var metadataOutput: AVCaptureMetadataOutput?
-
- override public func viewDidLoad() {
- super.viewDidLoad()
-
-
- NotificationCenter.default.addObserver(self,
- selector: #selector(updateOrientation),
- name: Notification.Name("UIDeviceOrientationDidChangeNotification"),
- object: nil)
-
- view.backgroundColor = UIColor(named: "Black")
- captureSession = AVCaptureSession()
-
- guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return }
- let videoInput: AVCaptureDeviceInput
-
- do {
- videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
- } catch {
- return
- }
-
- if (captureSession.canAddInput(videoInput)) {
- captureSession.addInput(videoInput)
- } else {
- delegate?.didFail(reason: .badInput)
- return
- }
-
- metadataOutput = AVCaptureMetadataOutput()
-
- if (captureSession.canAddOutput(metadataOutput!)) {
- captureSession.addOutput(metadataOutput!)
-
- metadataOutput!.setMetadataObjectsDelegate(delegate, queue: DispatchQueue.main)
- metadataOutput!.metadataObjectTypes = delegate?.parent.codeTypes
- } else {
- delegate?.didFail(reason: .badOutput)
- return
- }
- }
-
- override public func viewWillLayoutSubviews() {
- previewLayer?.frame = view.layer.bounds
- }
-
- @objc func updateOrientation() {
- guard let orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation else { return }
- guard let connection = captureSession.connections.last, connection.isVideoOrientationSupported else { return }
- connection.videoOrientation = AVCaptureVideoOrientation(rawValue: orientation.rawValue) ?? .portrait
- }
-
- override public func viewDidAppear(_ animated: Bool) {
- super.viewDidAppear(animated)
- updateOrientation()
- }
-
- override public func viewWillAppear(_ animated: Bool) {
- super.viewWillAppear(animated)
-
- if previewLayer == nil {
- previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
- }
- previewLayer.frame = view.layer.bounds
- previewLayer.videoGravity = .resizeAspectFill
- view.layer.addSublayer(previewLayer)
-
- let xPos = (view.frame.size.width / 2) - (200 / 2)
- let yPos = (view.frame.size.height / 2) - (200 / 2)
- let scanRect = CGRect(x: xPos, y: yPos, width: 200, height: 200)
-
- #if DEBUG
- let area = UIView()
- area.frame = scanRect
- area.layer.borderColor = UIColor.red.cgColor
- area.layer.borderWidth = 2.0
- view.addSubview(area)
- view.bringSubviewToFront(area)
- #endif
-
- let substrect = UIView()
- substrect.frame = self.view.bounds
-
- let targetMaskLayer = CAShapeLayer()
- let extendTrans: CGFloat = 50
- let rec = CGRect(x: (scanRect.origin.x - (extendTrans / 2)), y: (scanRect.origin.y - (extendTrans / 2)), width: scanRect.width + extendTrans, height: scanRect.height + extendTrans)
- let square = UIBezierPath(roundedRect: rec, cornerRadius: 45)
-
- let path = UIBezierPath(rect: self.view.bounds)
- path.append(square)
-
- targetMaskLayer.path = path.cgPath
- // Exclude intersected paths
- targetMaskLayer.fillRule = CAShapeLayerFillRule.evenOdd
-
- substrect.layer.mask = targetMaskLayer
- substrect.layer.backgroundColor = UIColor.black.cgColor
- substrect.alpha = 0.35
- substrect.clipsToBounds = true
-
- view.addSubview(substrect)
- view.bringSubviewToFront(substrect)
-
- metadataOutput!.rectOfInterest = previewLayer.metadataOutputRectConverted(fromLayerRect: scanRect)
- captureSession.commitConfiguration()
-
- if (captureSession?.isRunning == false) {
- captureSession.startRunning()
- }
- }
-
- override public func viewDidDisappear(_ animated: Bool) {
- super.viewDidDisappear(animated)
-
- if (captureSession?.isRunning == true) {
- captureSession.stopRunning()
- }
-
- NotificationCenter.default.removeObserver(self)
- }
-
- override public var prefersStatusBarHidden: Bool {
- return true
- }
-
- override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
- return .all
- }
- }
- #endif
-
- public let codeTypes: [AVMetadataObject.ObjectType]
- public let scanMode: ScanMode
- public let scanInterval: Double
- public var simulatedData = ""
- public var completion: (Result) -> Void
-
- public init(codeTypes: [AVMetadataObject.ObjectType], scanMode: ScanMode = .once, scanInterval: Double = 2.0, simulatedData: String = "", completion: @escaping (Result) -> Void) {
- self.codeTypes = codeTypes
- self.scanMode = scanMode
- self.scanInterval = scanInterval
- self.simulatedData = simulatedData
- self.completion = completion
- }
-
- public func makeCoordinator() -> ScannerCoordinator {
- return ScannerCoordinator(parent: self)
- }
-
- public func makeUIViewController(context: Context) -> ScannerViewController {
- let viewController = ScannerViewController()
- viewController.delegate = context.coordinator
- return viewController
- }
-
- public func updateUIViewController(_ uiViewController: ScannerViewController, context: Context) {
-
- }
-}
-
-struct CodeScannerView_Previews: PreviewProvider {
- static var previews: some View {
- CodeScannerView(codeTypes: [.qr]) { result in
- // do nothing
- }
- }
-}
diff --git a/IPv64/Helpers/Adaptive.swift b/IPv64/Helpers/Adaptive.swift
new file mode 100644
index 0000000..f7d9092
--- /dev/null
+++ b/IPv64/Helpers/Adaptive.swift
@@ -0,0 +1,46 @@
+import SwiftUI
+
+extension View {
+ /// iPhone Duo: keeps this screen's bars horizontal (sheet with a single text control Skip/Done).
+ @ViewBuilder
+ func appHorizontalBars() -> some View {
+ if #available(iOS 27.1, *) { toolbarVerticalBehavior(.disabled) } else { self }
+ }
+
+ /// Caps the content at a readable width on wide windows and centres it.
+ /// Narrow windows keep the system margins. Sheets apply it again to measure their own width.
+ func appReadableWidth(_ maxWidth: CGFloat = 720) -> some View {
+ modifier(ReadableWidth(maxWidth: maxWidth))
+ }
+}
+
+private struct ReadableWidth: ViewModifier {
+ let maxWidth: CGFloat
+ /// `nil` = system default margin.
+ @State private var leading: CGFloat?
+ @State private var trailing: CGFloat?
+
+ func body(content: Content) -> some View {
+ content
+ // Scroll content margins don't add to the safe area (the larger one wins), so the inset is included.
+ .contentMargins(.leading, leading, for: .scrollContent)
+ .contentMargins(.trailing, trailing, for: .scrollContent)
+ .onGeometryChange(for: [CGFloat?].self) { proxy in
+ let extra = ((proxy.size.width - maxWidth) / 2).rounded()
+ guard extra > 0 else { return [nil, nil] }
+ return [extra + proxy.safeAreaInsets.leading, extra + proxy.safeAreaInsets.trailing]
+ } action: { margins in
+ leading = margins[0]
+ trailing = margins[1]
+ }
+ }
+}
+
+extension ToolbarContent {
+ /// iPhone Duo: a custom view item (spinner swapped in while loading) joins the vertical bar
+ /// instead of staying horizontal next to the status bar.
+ @ToolbarContentBuilder
+ func appVerticalPreferred() -> some ToolbarContent {
+ if #available(iOS 27.1, *) { axisBehavior(.verticalPreferred) } else { self }
+ }
+}
diff --git a/IPv64/Helpers/AppConfig.swift b/IPv64/Helpers/AppConfig.swift
new file mode 100644
index 0000000..5304e2a
--- /dev/null
+++ b/IPv64/Helpers/AppConfig.swift
@@ -0,0 +1,41 @@
+import Foundation
+import IPv64
+
+/// Shared by the app and the widget extension (target membership exception).
+nonisolated enum AppConfig {
+ static let appGroup = "group.ipv64.net"
+ /// Debug only: `MOCK_API=http://localhost:8064` (environment or launch argument `-MOCK_API …`)
+ /// sends every cloud call to `/api/v2` and SecNtfy to `/secntfy`. Release builds ignore it.
+ static let mockBase: String? = {
+ #if DEBUG
+ let raw = ProcessInfo.processInfo.environment["MOCK_API"] ?? UserDefaults.standard.string(forKey: "MOCK_API")
+ guard var base = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !base.isEmpty else { return nil }
+ while base.hasSuffix("/") { base.removeLast() }
+ return base
+ #else
+ return nil
+ #endif
+ }()
+
+ static var secNtfyURL: String { mockBase.map { $0 + "/secntfy" } ?? "https://api.secntfy.app" }
+
+ /// Cloud API v2 client; `production` is the real host (e.g. ipv4.ipv64.net for my-IP), replaced by the mock.
+ static func cloudClient(apiKey: String?, production: String = "https://ipv64.net/api/v2",
+ timeout: TimeInterval = 30) -> IPv64 {
+ let base = mockBase.map { $0 + "/api/v2" } ?? production
+ return IPv64(configuration: .init(apiKey: apiKey, baseURL: URL(string: base)!, timeoutInterval: timeout))
+ }
+ /// Name in a node's audit log for changes made from this app (`Node64.Configuration.agentActor`).
+ static let nodeAgentActor = "IPv64 iOS"
+ /// WidgetKit kinds of the DNS64 widget and Control (reloaded by the app after pause/resume).
+ static let dns64WidgetKind = "DNS64Widget"
+ static let dns64ControlKind = "DNS64BlockingControl"
+
+ /// iOS SecNtfy app key: Info.plist `SECNTFY_APP_KEY` (file IPv64-net-Info.plist).
+ static var secNtfyAppKey: String {
+ (Bundle.main.object(forInfoDictionaryKey: "SECNTFY_APP_KEY") as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ }
+
+ static var isSecNtfyConfigured: Bool { !secNtfyAppKey.isEmpty }
+}
diff --git a/IPv64/Helpers/Biometrics.swift b/IPv64/Helpers/Biometrics.swift
new file mode 100644
index 0000000..6be6af2
--- /dev/null
+++ b/IPv64/Helpers/Biometrics.swift
@@ -0,0 +1,91 @@
+//
+// Biometrics.swift
+// IPv64
+//
+// Created by Sebastian Rank on 03.11.25.
+//
+
+import Foundation
+import LocalAuthentication
+import Combine
+
+extension Biometrics: @unchecked Sendable {}
+
+class Biometrics: ObservableObject {
+
+ @Published var disableFields: Bool = false
+ @Published var isAuthenticated: Bool = false
+
+ static func GetBiometricSymbol() -> String {
+ _ = checkBiometricType()
+ if (LAContext().biometryType == .faceID) {
+ return "faceid"
+ } else if (LAContext().biometryType == .touchID) {
+ return "touchid"
+ } else {
+ return "lock.circle"
+ }
+ }
+
+ static func GetBiometricText() -> String {
+ _ = checkBiometricType()
+ if (LAContext().biometryType == .faceID) {
+ return "FaceID"
+ } else if (LAContext().biometryType == .touchID) {
+ return "TouchID"
+ } else {
+ return "PIN"
+ }
+ }
+
+ static func checkBiometricType() -> String {
+ let context = LAContext()
+ var error: NSError?
+
+ if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
+ if #available(iOS 11.0, *) {
+ switch context.biometryType {
+ case .none:
+ return "No Biometric Authentication"
+ case .touchID:
+ return "TouchID"
+ case .faceID:
+ return "FaceID"
+ case .opticID:
+ return "OpticID"
+ @unknown default:
+ return "Unknown Biometric Authentication"
+ }
+ } else {
+ return "TouchID available"
+ }
+ } else {
+ return "No Biometric Authentication"
+ }
+ }
+
+ /// One instance for all windows: a second request while the system prompt is up is ignored.
+ private var isEvaluating = false
+
+ func tryToAuthenticatePIN() {
+ guard !isEvaluating else { return }
+ let context = LAContext()
+ var error: NSError?
+ let reason = "Please authenticate to continue with the app."
+
+ guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
+ self.disableFields = false
+ return
+ }
+
+ isEvaluating = true
+ context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { @Sendable success, _ in
+ Task { @MainActor in
+ self.isEvaluating = false
+ // Also after Cancel / failure, otherwise the spinner stays and the button is disabled.
+ self.disableFields = false
+ if success { self.isAuthenticated = true }
+ }
+ }
+ }
+}
diff --git a/IPv64/Helpers/Channels/NotificationSettingsLogic.swift b/IPv64/Helpers/Channels/NotificationSettingsLogic.swift
new file mode 100644
index 0000000..4701256
--- /dev/null
+++ b/IPv64/Helpers/Channels/NotificationSettingsLogic.swift
@@ -0,0 +1,107 @@
+import Foundation
+import IPv64
+
+/// Form state of the notification settings; number fields as text ("" = not set). Android `SettingsForm`.
+nonisolated struct NotificationSettingsForm: Equatable, Sendable {
+ var quietEnabled = false
+ var from = "22:00"
+ var to = "07:00"
+ var days: Set = Set(1...7)
+ var rate = ""
+ var threshold = ""
+ var window = ""
+}
+
+/// Pure logic of `Hc2SettingsView.kt` (spec 04 §7b).
+nonisolated enum NotificationSettingsLogic {
+ static let quietKeys = ["quiet_from", "quiet_to", "quiet_days"]
+
+ /// Flat map: `notify.` or bare ``.
+ static func value(_ map: [String: String], _ key: String) -> String? { map["notify." + key] ?? map[key] }
+
+ /// Parsed form plus the keys the server actually sent.
+ static func parse(_ map: [String: String]) -> (form: NotificationSettingsForm, present: Set) {
+ let defaults = NotificationSettingsForm()
+ var present = Set()
+ func read(_ key: String) -> String? {
+ let v = value(map, key)
+ if v != nil { present.insert(key) }
+ return v
+ }
+ let enabled = read("quiet_enabled").map { ["1", "true", "yes", "on"].contains($0.trimmingCharacters(in: .whitespaces).lowercased()) }
+ let from = normalizeTime(read("quiet_from"))
+ let to = normalizeTime(read("quiet_to"))
+ let days = read("quiet_days").map(parseDays).flatMap { $0.isEmpty ? nil : $0 }
+ func number(_ key: String) -> String { read(key).flatMap { Int($0.trimmingCharacters(in: .whitespaces)) }.map(String.init) ?? "" }
+ let form = NotificationSettingsForm(quietEnabled: enabled ?? defaults.quietEnabled, from: from ?? defaults.from,
+ to: to ?? defaults.to, days: days ?? defaults.days, rate: number("rate_per_hour"),
+ threshold: number("batch_threshold"), window: number("batch_window_seconds"))
+ return (form, present)
+ }
+
+ /// Android `normalizeTimeOfDay`: "22:00", "22:00:00", "2200" → "HH:MM"; invalid → nil.
+ static func normalizeTime(_ text: String?) -> String? {
+ let s = text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ guard !s.isEmpty else { return nil }
+ let parts = s.split(separator: ":", omittingEmptySubsequences: false)
+ let h: Int, m: Int
+ if parts.count >= 2 {
+ guard let hh = Int(parts[0]), let mm = Int(parts[1]) else { return nil }
+ (h, m) = (hh, mm)
+ } else if s.count == 4, s.allSatisfy(\.isNumber), let hh = Int(s.prefix(2)), let mm = Int(s.suffix(2)) {
+ (h, m) = (hh, mm)
+ } else {
+ return nil
+ }
+ guard (0...23).contains(h), (0...59).contains(m) else { return nil }
+ return String(format: "%02d:%02d", h, m)
+ }
+
+ /// "1,2,3" or ranges "1-5"; values 1…7.
+ static func parseDays(_ text: String) -> Set {
+ var result = Set()
+ for part in text.split(separator: ",").map({ $0.trimmingCharacters(in: .whitespaces) }) where !part.isEmpty {
+ if part.contains("-") {
+ let bounds = part.split(separator: "-", maxSplits: 1).map { Int($0.trimmingCharacters(in: .whitespaces)) }
+ if bounds.count == 2, let a = bounds[0], let b = bounds[1], a <= b {
+ result.formUnion((a...b).filter { (1...7).contains($0) })
+ }
+ } else if let day = Int(part), (1...7).contains(day) {
+ result.insert(day)
+ }
+ }
+ return result
+ }
+
+ static func nonNegativeInt(_ text: String) -> Int? {
+ Int(text.trimmingCharacters(in: .whitespaces)).flatMap { $0 >= 0 ? $0 : nil }
+ }
+
+ static func rateOK(_ f: NotificationSettingsForm) -> Bool { f.rate.nonBlank == nil || nonNegativeInt(f.rate) != nil }
+
+ /// Threshold / window may stay blank only when the server had no value.
+ static func requiredNumberOK(_ text: String, baseline: String) -> Bool {
+ text.nonBlank == nil ? baseline.nonBlank == nil : nonNegativeInt(text) != nil
+ }
+
+ static func isValid(_ f: NotificationSettingsForm, base: NotificationSettingsForm) -> Bool {
+ rateOK(f) && requiredNumberOK(f.threshold, baseline: base.threshold)
+ && requiredNumberOK(f.window, baseline: base.window) && (!f.quietEnabled || !f.days.isEmpty)
+ }
+
+ /// PATCH body with the changes only; quiet times/days all sent when enabling and the server lacked any of them.
+ static func update(_ f: NotificationSettingsForm, base b: NotificationSettingsForm, present: Set) -> HC2SettingsInput {
+ let sendQuietAll = f.quietEnabled && quietKeys.contains { !present.contains($0) }
+ let rate = f.rate.nonBlank == nil ? nonNegativeInt(b.rate).map { _ in 0 } : nonNegativeInt(f.rate)
+ let threshold = nonNegativeInt(f.threshold)
+ let window = nonNegativeInt(f.window)
+ return HC2SettingsInput(
+ quietEnabled: f.quietEnabled != b.quietEnabled ? f.quietEnabled : nil,
+ quietFrom: sendQuietAll || f.from != b.from ? f.from : nil,
+ quietTo: sendQuietAll || f.to != b.to ? f.to : nil,
+ quietDays: sendQuietAll || f.days != b.days ? f.days.sorted().map(String.init).joined(separator: ",") : nil,
+ ratePerHour: rate != nonNegativeInt(b.rate) ? rate : nil,
+ batchThreshold: threshold != nonNegativeInt(b.threshold) ? threshold : nil,
+ batchWindowSeconds: window != nonNegativeInt(b.window) ? window : nil)
+ }
+}
diff --git a/IPv64/Helpers/Clipboard.swift b/IPv64/Helpers/Clipboard.swift
new file mode 100644
index 0000000..f4c77af
--- /dev/null
+++ b/IPv64/Helpers/Clipboard.swift
@@ -0,0 +1,15 @@
+import UIKit
+
+/// The one way to copy text in the app: copies and confirms with a success vibration.
+enum Clipboard {
+ /// `sensitive`: stays on this device (no Universal Clipboard) and expires after 2 minutes (keys, update URLs).
+ static func copy(_ text: String, sensitive: Bool = false) {
+ if sensitive {
+ UIPasteboard.general.setItems([["public.utf8-plain-text": text]],
+ options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(120)])
+ } else {
+ UIPasteboard.general.string = text
+ }
+ UINotificationFeedbackGenerator().notificationOccurred(.success)
+ }
+}
diff --git a/IPv64/Helpers/ColorGradient.swift b/IPv64/Helpers/ColorGradient.swift
new file mode 100644
index 0000000..ac9b2ed
--- /dev/null
+++ b/IPv64/Helpers/ColorGradient.swift
@@ -0,0 +1,48 @@
+//
+// ColorGradient.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+
+import SwiftUI
+
+struct ColorGradient: View {
+
+ @Environment(\.colorScheme) var systemColorScheme
+
+ var color: Color
+
+ var body: some View {
+
+ let opacity1: Double = systemColorScheme == .dark ? 0.4 : 0.5
+ let opacity2: Double = systemColorScheme == .dark ? 0.1 : 0.2
+ let opacity3: Double = systemColorScheme == .dark ? 0.05 : 0.05
+ let opacity4: Double = systemColorScheme == .dark ? 0.025 : 0
+ let lastColor: Color = systemColorScheme == .dark ? .clear : .gray.opacity(0.07)
+
+ LinearGradient(
+ colors: [
+ color.opacity(opacity1), // kräftiges Grün
+ color.opacity(opacity2), // kräftiges Grün
+ color.opacity(opacity3), // kräftiges Grün
+ color.opacity(opacity4), // kräftiges Grün
+ lastColor,
+ lastColor,
+ lastColor,
+ lastColor
+ ],
+ startPoint: .top,
+ endPoint: .bottom
+ )
+ .background(lastColor)
+ .ignoresSafeArea()
+ }
+}
+
+#Preview {
+ NavigationStack {
+ WelcomeView()
+ }
+}
diff --git a/IPv64/Helpers/DNS64/DNS64Data.swift b/IPv64/Helpers/DNS64/DNS64Data.swift
new file mode 100644
index 0000000..8b422b1
--- /dev/null
+++ b/IPv64/Helpers/DNS64/DNS64Data.swift
@@ -0,0 +1,65 @@
+import SwiftUI
+import IPv64
+
+/// Failure of one dashboard section: the section shows `text`, the others render normally.
+nonisolated struct DnsSectionError: Error, Sendable { let text: String }
+typealias DnsSec = Result
+
+/// Runs one section request; HTTP 404 becomes "Not available on this node.", else ": ".
+nonisolated func dnsSec(_ operation: @Sendable () async throws -> T) async -> DnsSec {
+ do {
+ return .success(try await operation())
+ } catch {
+ if (error as? Node64Error)?.statusCode == 404 {
+ return .failure(.init(text: String(localized: "Not available on this node.")))
+ }
+ return .failure(.init(text: ErrorText.node(error).titledText))
+ }
+}
+
+/// Everything the dashboard shows for one node and range.
+nonisolated struct DnsData: Sendable {
+ let nodeId: String
+ var blocking: DnsSec
+ var summary: DnsSec
+ var timeline: DnsSec
+ var upstreams: DnsSec
+ var cache: DnsSec
+ var blocked: DnsSec<[Node64.DNS64TopItem]>
+ var allowed: DnsSec<[Node64.DNS64TopItem]>
+ var clients: DnsSec<[Node64.DNS64TopItem]>
+
+ /// All sections in parallel.
+ static func load(nodeId: String, dns: Node64.DNS64, range: Node64.DNS64Range) async -> DnsData {
+ async let status = dnsSec { try await dns.status().blocking }
+ async let summary = dnsSec { try await dns.summary(range: range) }
+ async let timeline = dnsSec { try await dns.timeline(range: range) }
+ async let upstreams = dnsSec { try await dns.upstreams.list() }
+ async let cache = dnsSec { try await dns.cache.get() }
+ async let blocked = dnsSec { try await dns.top(kind: .blocked, range: range, limit: 10) }
+ async let allowed = dnsSec { try await dns.top(kind: .allowed, range: range, limit: 10) }
+ async let clients = dnsSec { try await dns.top(kind: .clients, range: range, limit: 10) }
+ return await DnsData(nodeId: nodeId, blocking: status, summary: summary, timeline: timeline, upstreams: upstreams,
+ cache: cache, blocked: blocked, allowed: allowed, clients: clients)
+ }
+}
+
+enum DnsRange: CaseIterable, Identifiable {
+ case hour, day, week
+ var id: Self { self }
+ var node: Node64.DNS64Range { switch self { case .hour: .lastHour; case .day: .last24Hours; case .week: .last7Days } }
+ var hours: Int { switch self { case .hour: 1; case .day: 24; case .week: 168 } }
+ var label: LocalizedStringKey { switch self { case .hour: "1 h"; case .day: "24 h"; case .week: "7 d" } }
+}
+
+/// Runs a write behind the screen's busy overlay; node errors become an alert.
+@MainActor struct DnsActions {
+ let busy: Binding
+ let error: Binding
+
+ func run(_ operation: () async throws -> Void) async {
+ busy.wrappedValue = true
+ defer { busy.wrappedValue = false }
+ do { try await operation() } catch is CancellationError {} catch { self.error.wrappedValue = .node(error) }
+ }
+}
diff --git a/IPv64/Helpers/DNS64/DNS64Logic.swift b/IPv64/Helpers/DNS64/DNS64Logic.swift
new file mode 100644
index 0000000..f69b6f8
--- /dev/null
+++ b/IPv64/Helpers/DNS64/DNS64Logic.swift
@@ -0,0 +1,112 @@
+import Foundation
+import IPv64
+
+// Pure DNS64 helpers (Android parity). Callable from any isolation.
+
+nonisolated enum Dns64Time { case hm, dayMonth, dayMonthHm }
+
+/// `HH:mm`, `dd.MM.`, `dd.MM. HH:mm` in the device time zone.
+nonisolated func dns64Format(_ date: Date, _ kind: Dns64Time) -> String {
+ let calendar = Calendar(identifier: .gregorian)
+ switch kind {
+ case .hm:
+ return date.formatted(Date.VerbatimFormatStyle(
+ format: "\(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits)",
+ timeZone: .current, calendar: calendar))
+ case .dayMonth:
+ return date.formatted(Date.VerbatimFormatStyle(
+ format: "\(day: .twoDigits).\(month: .twoDigits).", timeZone: .current, calendar: calendar))
+ case .dayMonthHm:
+ return date.formatted(Date.VerbatimFormatStyle(
+ format: "\(day: .twoDigits).\(month: .twoDigits). \(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits)",
+ timeZone: .current, calendar: calendar))
+ }
+}
+
+/// One decimal with a dot, "0" for an empty whole.
+nonisolated func dns64Percent(_ part: Int, of whole: Int) -> String {
+ whole > 0 ? String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), Double(part) * 100 / Double(whole)) : "0"
+}
+
+nonisolated func dns64Ms(_ value: Double?) -> String {
+ value.map { String(format: "%.0f", locale: Locale(identifier: "en_US_POSIX"), $0) } ?? "–"
+}
+
+/// Delay until the next countdown tick: 1 s under 2 minutes, else 30 s.
+nonisolated func dns64CountdownInterval(remaining: TimeInterval) -> Duration {
+ remaining < 120 ? .seconds(1) : .seconds(30)
+}
+
+nonisolated func dns64BlockingTitle(paused: Bool, end: Date?, now: Date) -> String {
+ guard paused else { return String(localized: "Blocking active") }
+ guard let end else { return String(localized: "Paused until resumed") }
+ let remaining = max(end.timeIntervalSince(now), 0)
+ let until = dns64Format(end, .hm)
+ if remaining < 120 { return String(localized: "Paused · \(Int(remaining)) s left (until \(until))") }
+ return String(localized: "Paused · \(Int(remaining / 60) + 1) min left (until \(until))")
+}
+
+// MARK: - Chart
+
+nonisolated struct Dns64Bar: Identifiable, Equatable, Sendable {
+ let index: Int
+ let start: Date?
+ let allowed: Int
+ let blocked: Int
+ var id: Int { index }
+}
+
+/// Timeline buckets to bars; Allowed = max(total - blocked, 0).
+nonisolated func dns64Bars(_ buckets: [Node64.DNS64TimelineBucket]) -> [Dns64Bar] {
+ buckets.enumerated().map { i, b in
+ let blocked = b.blocked ?? 0
+ return Dns64Bar(index: i, start: b.date, allowed: max((b.total ?? 0) - blocked, 0), blocked: blocked)
+ }
+}
+
+// MARK: - Query log
+
+nonisolated enum Dns64LogFilter: String, CaseIterable, Identifiable, Sendable {
+ case all, blocked, allowed
+ var id: String { rawValue }
+ /// Raw status sent to the node (`nil` = all).
+ var rawStatus: String? { self == .all ? nil : rawValue }
+}
+
+/// Chip of a log row from the raw (open) status: blocked red, error orange, allowed/cached green, else gray.
+nonisolated func dns64StatusTag(_ raw: String?) -> ProxyLogic.Tag {
+ switch raw {
+ case "blocked": .init(text: String(localized: "Blocked"), tone: .red)
+ case "error": .init(text: String(localized: "Error"), tone: .orange)
+ case "allowed", "cached": .init(text: raw!.capitalized, tone: .green)
+ case let other: .init(text: other?.nonBlank?.capitalized ?? "–", tone: .gray)
+ }
+}
+
+nonisolated func dns64AllowMessage(reason: String?) -> String {
+ let by = reason?.nonBlank.map { " by \($0)" } ?? ""
+ return String(localized: "Blocked\(by). Allow this domain and its subdomains for all clients?")
+}
+
+nonisolated let dns64BlockMessage = String(localized: "Block this domain and its subdomains for all clients?")
+
+// MARK: - Records
+
+nonisolated let dns64RecordTypes = ["A", "AAAA", "CNAME", "TXT", "MX", "SRV", "PTR", "CAA"]
+
+nonisolated func dns64DigitsOnly(_ text: String) -> String { text.filter { $0.isASCII && $0.isNumber } }
+
+nonisolated func dns64RecordValid(name: String, value: String, ttl: String) -> Bool {
+ name.nonBlank != nil && value.nonBlank != nil && (ttl.isEmpty || Int(ttl) != nil)
+}
+
+/// Edit sends the trimmed text (empty clears), create `nil` when empty.
+nonisolated func dns64Comment(_ text: String, isEdit: Bool) -> String? {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ return isEdit || !trimmed.isEmpty ? trimmed : nil
+}
+
+/// Keeps a flag `nil` while it was never set and is still off; otherwise the toggle value.
+nonisolated func dns64Flag(original: Bool?, toggle: Bool) -> Bool? {
+ original == nil && !toggle ? nil : toggle
+}
diff --git a/IPv64/Helpers/DebugFixtures.swift b/IPv64/Helpers/DebugFixtures.swift
new file mode 100644
index 0000000..12c4797
--- /dev/null
+++ b/IPv64/Helpers/DebugFixtures.swift
@@ -0,0 +1,113 @@
+#if DEBUG
+import Foundation
+import OSLog
+
+/// Opt-in simulator fixtures. Release builds contain neither this transport nor its setup.
+enum DebugFixtures {
+ static func configure() {
+ // `CLEAR_ACCOUNT_IDS=1` (env): forgets remembered account ids, e.g. one taken from the mock server.
+ if ProcessInfo.processInfo.environment["CLEAR_ACCOUNT_IDS"] == "1", let defaults = UserStorage.sharedDefault {
+ for key in defaults.dictionaryRepresentation().keys where key.hasPrefix("HC2_PUSH_SETUP.acct_") {
+ defaults.removeObject(forKey: key)
+ }
+ }
+ seedMockLogin()
+ seedMockNodes()
+ guard ProcessInfo.processInfo.arguments.contains("--fixture-api") else { return }
+ URLProtocol.registerClass(FixtureURLProtocol.self)
+ // A separate non-user key verifies the configured shared Keychain access group.
+ do {
+ let probe = Data("fixture-probe".utf8)
+ try SecureStore.write(probe, account: "FIXTURE_PROBE")
+ guard try SecureStore.read("FIXTURE_PROBE") == probe else { return }
+ try SecureStore.remove("FIXTURE_PROBE")
+ print("FIXTURE: Keychain roundtrip passed")
+ } catch { print("FIXTURE: Keychain roundtrip failed") }
+ if ProcessInfo.processInfo.arguments.contains("--fixture-migration"),
+ (try? SecureStore.readString("API_KEY")) == "",
+ UserStorage.sharedDefault?.object(forKey: "USER_ACCOUNTS") == nil {
+ UserStorage.sharedDefault?.set("fixture-key", forKey: "API_KEY")
+ UserStorage.sharedDefault?.set("fixture-key", forKey: "API_KEY_WIDGET")
+ let user = User(Username: "Fixture account", ApiKey: "fixture-key", Information: "Local test data")
+ UserStorage.sharedDefault?.set(try? JSONEncoder().encode([user]), forKey: "USER_ACCOUNTS")
+ }
+ }
+
+ /// `MOCK_LOGIN=` (env, only together with MOCK_API): logs in like LoginView when no account is stored,
+ /// for simulators that cannot type.
+ private static func seedMockLogin() {
+ guard AppConfig.mockBase != nil, let key = ProcessInfo.processInfo.environment["MOCK_LOGIN"], !key.isEmpty,
+ UserStorage.shared.ApiKey.isEmpty else { return }
+ let storage = UserStorage.shared
+ User(Username: "Mock account", ApiKey: key, Information: "").save()
+ storage.ApiKey = key
+ storage.ApiKeyWidget = key
+ storage.ShowWelcomeView = false
+ storage.ShowLoginView = false
+ }
+
+ /// `MOCK_NODES=nd_a=http://host/node/api,nd_b=…` (env or defaults): direct access to mock nodes
+ /// for the logged-in account, so node screens can be tested where the simulator cannot type.
+ private static func seedMockNodes() {
+ // `MOCK_NODES_CLEAR=nd_a,nd_b` (env): removes seeded mock node access again.
+ for id in (ProcessInfo.processInfo.environment["MOCK_NODES_CLEAR"] ?? "").split(separator: ",") {
+ LocalNodeStore.remove(String(id))
+ }
+ let raw = ProcessInfo.processInfo.environment["MOCK_NODES"] ?? UserDefaults.standard.string(forKey: "MOCK_NODES")
+ guard let raw, let owner = User.empty.current?.uuid, !owner.isEmpty else { return }
+ for pair in raw.split(separator: ",") {
+ let parts = pair.split(separator: "=", maxSplits: 1).map(String.init)
+ guard parts.count == 2 else { continue }
+ try? LocalNodeStore.save(id: parts[0], url: parts[1], key: "node64_mock", owner: owner)
+ }
+ }
+}
+
+nonisolated private final class FixtureURLProtocol: URLProtocol, @unchecked Sendable {
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func startLoading() {
+ let url = request.url!
+ let query = url.query ?? ""
+ let token = request.value(forHTTPHeaderField: "Authorization")
+ let (code, object): (Int, [String: Any])
+ if url.host?.hasPrefix("ipv4.") == true {
+ (code, object) = (200, ["ip": "192.0.2.1", "type": "IPv4"])
+ } else if url.host?.hasPrefix("ipv6.") == true {
+ (code, object) = (200, ["ip": "2001:db8::1", "type": "IPv6"])
+ } else if token != "Bearer fixture-key" {
+ (code, object) = (401, ["status": "401"])
+ } else if query.contains("get_account_info") {
+ var account: [String: Any] = ["account_status": 1, "email": "fixture@example.invalid", "reg_date": "2026-01-01 00:00:00", "update_hash": "fixture", "api_key": "fixture-key", "info": "ok", "status": "200 OK", "get_account_info": "ok"]
+ for key in ["dyndns_updates", "dyndns_subdomains", "owndomains", "healthchecks", "healthchecks_updates", "api_updates", "sms_count", "vpn_limit_reached", "vpn_traffic_input", "vpn_traffic_output"] { account[key] = 1 }
+ var plan: [String: Any] = ["class_name": "Fixture"]
+ for key in ["dyndns_domain_limit", "dyndns_update_limit", "owndomain_limit", "healthcheck_limit", "healthcheck_update_limit", "dyndns_ttl", "api_limit", "sms_limit", "vpn_traffic", "vpn_queue"] { plan[key] = 100 }
+ account["account_class"] = plan
+ (code, object) = (200, account)
+ } else if query.contains("get_domains") {
+ var domains: [String: Any] = [:]
+ for index in 1...100 {
+ domains["server\(index).ipv64.net"] = ["updates": index, "wildcard": 0, "domain_update_hash": "fixture", "records": [["record_id": index, "content": index.isMultiple(of: 2) ? "192.0.2.1" : "192.0.2.2", "type": "A", "ttl": 60, "praefix": "", "last_update": "2026-01-01 00:00:00"]]]
+ }
+ (code, object) = (200, ["status": "200", "subdomains": domains])
+ } else if query.contains("get_healthchecks") {
+ var checks: [String: Any] = ["status": "200", "info": "ok"]
+ for index in 1...100 {
+ checks["check\(index)"] = ["name": "Server \(index)", "healthstatus": (index % 4) + 1, "healthtoken": "fixture-\(index)", "add_time": "2026-01-01 00:00:00", "last_update_time": "2026-01-01 00:00:00", "alarm_time": "2026-01-01 00:15:00", "alarm_down": 1, "alarm_up": 1, "integration_id": "10,21", "alarm_count": 5, "alarm_unit": 1, "grace_count": 1, "grace_unit": 1, "pings_total": index, "type": "push", "events": [["event_time": "2026-01-01 00:00:00", "status": (index % 4) + 1, "text": "Fixture event"]]]
+ }
+ (code, object) = (200, checks)
+ } else if query.contains("get_integrations") {
+ var integrations: [String: Any] = ["status": "200"]
+ for id in [1, 10, 21] {
+ integrations["method\(id)"] = ["integration": "email", "integration_id": id, "integration_name": "Method \(id)", "add_time": "2026-01-01 00:00:00", "last_used": "2026-01-01 00:00:00"]
+ }
+ (code, object) = (200, integrations)
+ } else { (code, object) = (200, ["status": "200", "info": "Fixture response"]) }
+ let data = try! JSONSerialization.data(withJSONObject: object)
+ client?.urlProtocol(self, didReceive: HTTPURLResponse(url: url, statusCode: code, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: data)
+ client?.urlProtocolDidFinishLoading(self)
+ }
+ override func stopLoading() { }
+}
+#endif
diff --git a/IPv64/Helpers/DestructiveMenuButton.swift b/IPv64/Helpers/DestructiveMenuButton.swift
new file mode 100644
index 0000000..8f21820
--- /dev/null
+++ b/IPv64/Helpers/DestructiveMenuButton.swift
@@ -0,0 +1,27 @@
+import SwiftUI
+import UIKit
+
+/// Destructive item of a `Menu`: red text and a red icon. `role: .destructive` alone colours only the text on some
+/// iOS versions; an `.alwaysOriginal` red symbol image is drawn as is by the system menu.
+struct DestructiveMenuButton: View {
+ let title: LocalizedStringKey
+ let systemImage: String
+ let action: () -> Void
+
+ init(_ title: LocalizedStringKey, systemImage: String, action: @escaping () -> Void) {
+ self.title = title
+ self.systemImage = systemImage
+ self.action = action
+ }
+
+ var body: some View {
+ Button(role: .destructive, action: action) {
+ Label {
+ Text(title)
+ } icon: {
+ Image(uiImage: (UIImage(systemName: systemImage) ?? UIImage())
+ .withTintColor(.systemRed, renderingMode: .alwaysOriginal))
+ }
+ }
+ }
+}
diff --git a/IPv64/Helpers/DynDNS/DynDNSLogic.swift b/IPv64/Helpers/DynDNS/DynDNSLogic.swift
new file mode 100644
index 0000000..399b633
--- /dev/null
+++ b/IPv64/Helpers/DynDNS/DynDNSLogic.swift
@@ -0,0 +1,234 @@
+import Foundation
+import IPv64
+
+/// DynDNS list logic (ported from Android 2.1.0): zones, kind filter and the IP status of a domain.
+nonisolated enum DynDNSLogic {
+ static let noIPv4 = "0.0.0.0"
+ static let noIPv6 = "::"
+ static let ownDomain = "Own Domain"
+
+ /// Section order of the list.
+ static let zones = [
+ "ipv64.net", "ipv64.de", "any64.de", "api64.de", "dns64.de", "dyndns64.de", "eth64.de", "dynipv6.de",
+ "home64.de", "iot64.de", "lan64.de", "nas64.de", "root64.de", "route64.de", "srv64.de", "tcp64.de",
+ "udp64.de", "vpn64.de", "wan64.de", ownDomain,
+ ]
+
+ static let newRecordTypes = ["A", "AAAA", "TXT", "MX", "NS", "SRV", "CNAME", "TLSA", "CAA"]
+ static let allRecordTypes = ["A", "AAAA", "CNAME", "MX", "TXT", "NS", "SRV", "TLSA", "CAA"]
+
+ /// A non-blank IP that is not the "no IP" placeholder or loopback, else `nil`.
+ static func knownIp(_ ip: String?) -> String? {
+ guard let ip = ip?.trimmingCharacters(in: .whitespacesAndNewlines), !ip.isEmpty,
+ ip != noIPv4, ip != noIPv6, ip != "::1" else { return nil }
+ return ip
+ }
+
+ static func baseDomain(_ name: String) -> String {
+ let parts = name.split(separator: ".", omittingEmptySubsequences: false)
+ guard parts.count >= 2 else { return ownDomain }
+ let base = parts.suffix(2).joined(separator: ".")
+ return zones.contains(base) ? base : ownDomain
+ }
+
+ static func isOwn(kind: DomainKind?, name: String) -> Bool {
+ (kind ?? (baseDomain(name) == ownDomain ? .own : .dyndns)) == .own
+ }
+
+ enum IpStatus: Sendable { case checking, noIp, unknown, differs, matches }
+
+ static func hasIp(_ detail: DomainDetail?) -> Bool {
+ (detail?.records ?? []).contains { $0.type == .a || $0.type == .aaaa }
+ }
+
+ /// An A record exists, none holds the current IPv4, and IPv4 is not ignored for this domain.
+ static func mismatchV4(_ detail: DomainDetail?, myV4: String) -> Bool {
+ guard let detail, myV4 != noIPv4, detail.ignore != .ipv4 else { return false }
+ let records = (detail.records ?? []).filter { $0.type == .a }
+ return !records.isEmpty && !records.contains { $0.content == myV4 }
+ }
+
+ /// Like `mismatchV4`; a fixed IPv6 prefix means the AAAA records are not the device address.
+ static func mismatchV6(_ detail: DomainDetail?, myV6: String) -> Bool {
+ guard let detail, myV6 != noIPv6, detail.ignore != .ipv6,
+ (detail.ipv6Prefix ?? "").trimmingCharacters(in: .whitespaces).isEmpty else { return false }
+ let records = (detail.records ?? []).filter { $0.type == .aaaa }
+ return !records.isEmpty && !records.contains { $0.content == myV6 }
+ }
+
+ /// `nil` detail = still loading.
+ static func status(_ detail: DomainDetail?, myV4: String, myV6: String) -> IpStatus {
+ guard let detail else { return .checking }
+ if !hasIp(detail) { return .noIp }
+ if myV4 == noIPv4 && myV6 == noIPv6 { return .unknown }
+ return mismatchV4(detail, myV4: myV4) || mismatchV6(detail, myV6: myV6) ? .differs : .matches
+ }
+
+ static func kindLabel(_ kind: DomainKind?) -> String {
+ switch kind {
+ case .dyndns: "DynDNS"
+ case .own: "Own domain"
+ default: "–"
+ }
+ }
+
+ static func ignoreLabel(_ ignore: DomainIgnore?) -> String {
+ switch ignore {
+ case .ipv4: "Ignore IPv4"
+ case .ipv6: "Ignore IPv6"
+ default: "None"
+ }
+ }
+
+ // MARK: Records
+
+ static func isLocked(_ state: RecordState?) -> Bool {
+ guard let state else { return false }
+ return [.cdnRecord, .cdnProxied, .cdnPartial, .failoverRecord, .failoverReplaced].contains(state)
+ }
+
+ static func lockReason(_ state: RecordState?) -> String? {
+ switch state {
+ case .cdnRecord, .cdnProxied, .cdnPartial: "Managed by the CDN. Change it in the CDN settings."
+ case .failoverRecord, .failoverReplaced: "Managed by DNS failover. Change it in the failover policy."
+ default: nil
+ }
+ }
+
+ static func stateLabel(_ state: RecordState?) -> String? {
+ switch state {
+ case .active: "Active"
+ case .inactive: "Inactive"
+ case .cdnRecord: "CDN"
+ case .cdnProxied: "CDN proxied"
+ case .cdnPartial: "CDN partial"
+ case .failoverRecord: "Failover"
+ case .failoverReplaced: "Replaced by failover"
+ default: state?.rawValue
+ }
+ }
+
+ /// Prefix, "@" when empty (the domain itself).
+ static func prefixLabel(_ prefix: String?) -> String {
+ guard let prefix, !prefix.trimmingCharacters(in: .whitespaces).isEmpty, prefix != "@" else { return "@" }
+ return prefix
+ }
+
+ /// Edit form value: "" for the apex.
+ static func editPrefix(_ prefix: String?) -> String {
+ guard let prefix, prefix != "@" else { return "" }
+ return prefix
+ }
+
+ private static func typeOrder(_ type: RecordType?) -> Int {
+ type.flatMap { allRecordTypes.firstIndex(of: $0.rawValue) } ?? allRecordTypes.count
+ }
+
+ /// Sorted by type order then prefix, grouped by type (keeps the sort order).
+ static func groupedRecords(_ records: [Record]) -> [(type: String, records: [Record])] {
+ let sorted = records.sorted {
+ let (a, b) = (typeOrder($0.type), typeOrder($1.type))
+ return a != b ? a < b : prefixLabel($0.prefix) < prefixLabel($1.prefix)
+ }
+ var groups: [(type: String, records: [Record])] = []
+ for record in sorted {
+ let type = record.type?.rawValue ?? "?"
+ if let last = groups.indices.last, groups[last].type == type {
+ groups[last].records.append(record)
+ } else {
+ groups.append((type, [record]))
+ }
+ }
+ return groups
+ }
+
+ // MARK: DynDNS result
+
+ static func outcomeLabel(_ outcome: DynDNSOutcome?) -> String {
+ switch outcome {
+ case .created: "created"
+ case .updated: "updated"
+ case .unchanged: "unchanged"
+ case .ignored: "ignored (domain setting)"
+ case .invalidIP: "invalid IP"
+ case .cnameConflict: "CNAME conflict"
+ case .cdnManaged: "managed by the CDN"
+ default: "unknown"
+ }
+ }
+
+ static func isFailure(_ outcome: DynDNSOutcome?) -> Bool {
+ outcome == .invalidIP || outcome == .cnameConflict || outcome == .cdnManaged
+ }
+
+ // MARK: Validation
+
+ /// Four decimal parts 0...255 without leading zeros, no trimming.
+ static func isIpv4(_ text: String) -> Bool {
+ let parts = text.split(separator: ".", omittingEmptySubsequences: false)
+ return parts.count == 4 && parts.allSatisfy { part in
+ (1...3).contains(part.count) && part.allSatisfy { $0.isASCII && $0.isNumber }
+ && (part.count == 1 || part.first != "0") && Int(part).map { $0 <= 255 } == true
+ }
+ }
+
+ /// Numeric IPv6 only; IPv4-mapped `::ffff:a.b.c.d` is rejected (Android parses it as an IPv4 address).
+ static func isIpv6(_ text: String) -> Bool {
+ guard text.contains(":"), text.count <= 45, !text.contains("%") else { return false }
+ var bytes = in6_addr()
+ guard inet_pton(AF_INET6, text, &bytes) == 1 else { return false }
+ let b = withUnsafeBytes(of: bytes) { Array($0) }
+ let mapped = b[0..<10].allSatisfy { $0 == 0 } && b[10] == 0xff && b[11] == 0xff
+ return !mapped
+ }
+
+ /// Empty is fine; else `addr[/len]` with hex digits and colons, len 1...128.
+ static func isValidIpv6Prefix(_ text: String) -> Bool {
+ guard !text.isEmpty else { return true }
+ let addr = text.prefix { $0 != "/" }
+ let len = text.contains("/") ? text.drop { $0 != "/" }.dropFirst() : ""
+ let addrOk = addr.contains(":") && addr.allSatisfy { $0 == ":" || $0.isHexDigit }
+ let lenOk = len.isEmpty || (len.allSatisfy { $0.isASCII && $0.isNumber } && Int(len).map { (1...128).contains($0) } == true)
+ return addrOk && lenOk
+ }
+
+ /// New domain subdomain: one label, no dots or whitespace.
+ static func isValidSubdomain(_ text: String) -> Bool {
+ !text.isEmpty && !text.contains(".") && !text.contains { $0.isWhitespace }
+ }
+
+ static func updateURL(token: String?) -> String? {
+ token.flatMap { $0.isEmpty ? nil : "https://ipv64.net/nic/update?key=\($0)" }
+ }
+}
+
+nonisolated enum DomainKindFilter: String, CaseIterable, Identifiable, Sendable {
+ case all, dyndns, own
+ var id: Self { self }
+
+ var title: String {
+ switch self {
+ case .all: "All"
+ case .dyndns: "DynDNS"
+ case .own: "Own"
+ }
+ }
+
+ func matches(kind: DomainKind?, name: String) -> Bool {
+ switch self {
+ case .all: true
+ case .dyndns: !DynDNSLogic.isOwn(kind: kind, name: name)
+ case .own: DynDNSLogic.isOwn(kind: kind, name: name)
+ }
+ }
+}
+
+nonisolated extension DynDNSLogic {
+ /// Android `formatGermanTime`: dd.MM.yyyy HH:mm:ss.
+ static func germanTime(_ date: Date?, fallback: String = "–") -> String {
+ guard let date else { return fallback }
+ let formatter = DateFormatter()
+ formatter.dateFormat = "dd.MM.yyyy HH:mm:ss"
+ return formatter.string(from: date)
+ }
+}
diff --git a/IPv64/Helpers/Extensions.swift b/IPv64/Helpers/Extensions.swift
new file mode 100644
index 0000000..ae1057e
--- /dev/null
+++ b/IPv64/Helpers/Extensions.swift
@@ -0,0 +1,125 @@
+//
+// Extensions.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import Foundation
+import SwiftUI
+
+extension View {
+ func showLoading(_ showLoading: Binding) -> some View {
+ modifier(LoadingViewModifier(showLoading: showLoading))
+ }
+
+ @available(iOS 26, *)
+ func setColorGradient(_ color: Color) -> some View {
+ modifier(ColorGradientModifier(color: color))
+ }
+}
+
+extension View {
+ @ViewBuilder
+ func `if`(_ condition: Bool, transform: (Self) -> Content) -> some View {
+ condition ? AnyView(transform(self)) : AnyView(self)
+ }
+}
+
+extension SettingsView {
+ func performLogout() -> Bool {
+ let user = User.empty
+
+ if (user.list.count == 1 || user.list.isEmpty) {
+ UserStorage.shared.clear()
+ } else {
+ user.delete()
+ }
+ return true
+ }
+}
+
+extension Sequence {
+ func sorted(by keyPath: KeyPath) -> [Element] {
+ sorted { ($0[keyPath: keyPath]).lowercased() < ($1[keyPath: keyPath]).lowercased() }
+ }
+}
+
+extension String {
+ func v64domains() -> [String] {
+ return [
+ "ipv64.net",
+ "ipv64.de",
+ "any64.de",
+ "api64.de",
+ "dns64.de",
+ "dyndns64.de",
+ "eth64.de",
+ "dynipv6.de",
+ "home64.de",
+ "iot64.de",
+ "lan64.de",
+ "nas64.de",
+ "root64.de",
+ "route64.de",
+ "srv64.de",
+ "tcp64.de",
+ "udp64.de",
+ "vpn64.de",
+ "wan64.de",
+ "Own Domain"
+ ]
+ }
+
+ func v64DnsRecordTypes() -> [String] {
+ return [
+ "A",
+ "AAAA",
+ "TXT",
+ "MX",
+ "NS",
+ "SRV",
+ "CNAME",
+ "TLSA",
+ "CAA"
+ ]
+ }
+
+ var localized: String {
+ return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
+ }
+}
+
+extension Bundle {
+
+ var appName: String {
+ return infoDictionary?["CFBundleName"] as! String
+ }
+
+ var bundleId: String {
+ return bundleIdentifier!
+ }
+
+ var versionNumber: String {
+ return infoDictionary?["CFBundleShortVersionString"] as! String
+ }
+
+ var buildNumber: String {
+ return infoDictionary?["CFBundleVersion"] as! String
+ }
+
+ var isProduction: Bool {
+#if DEBUG
+ return false
+#else
+ guard let path = self.appStoreReceiptURL?.path else {
+ return true
+ }
+ return !path.contains("sandboxReceipt")
+#endif
+ }
+
+ var isPreview: Bool {
+ return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
+ }
+}
diff --git a/IPv64/Helpers/Healthchecks/HealthcheckFormState.swift b/IPv64/Helpers/Healthchecks/HealthcheckFormState.swift
new file mode 100644
index 0000000..92280e0
--- /dev/null
+++ b/IPv64/Helpers/Healthchecks/HealthcheckFormState.swift
@@ -0,0 +1,354 @@
+import Foundation
+import IPv64
+
+// Form state of the account healthcheck form (spec 02 B4). Pure and nonisolated.
+
+nonisolated struct HealthcheckFormState: Equatable, Sendable {
+ var type: HC2CheckType = .http
+ var name = ""
+ var target = ""
+ var ps = ParamsState.initial(.http)
+ /// Parameters as loaded (dirty check, "was something there" for clearing).
+ var iniPs = ParamsState.initial(.http)
+ var intervalValue = ""
+ var intervalUnit = 1
+ var retryValue = ""
+ var retryUnit = 1
+ var retries = ""
+ var timeout = ""
+ var connectTimeout = ""
+ var stabilize = ""
+ var invert = false
+ var ipMode: HC2IPMode?
+ var locations: [String] = []
+ var policy: HC2Policy?
+ var execSel: HC2Execution = .online
+ var nodeId: String?
+ var notifyDown = true
+ var notifyUp = true
+ var notifyDegraded = false
+ var critical = false
+ var repeatMinutes: Int?
+ var useDefaultChannels = true
+ var channels: Set = []
+ var tags = ""
+ var group = ""
+ var description = ""
+ var createPaused = false
+
+ // MARK: Derived
+
+ var execution: HC2Execution { type == .push ? .online : execSel }
+ var online: Bool { execution == .online }
+ var nodeOnly: Bool { execution == .local }
+ var usesLocations: Bool { execution != .local && type != .push }
+ var policyApplies: Bool { (usesLocations && locations.count > 1) || execution == .both }
+
+ // MARK: Detail → state
+
+ /// `knownChannelIds`: unknown (deleted) channel ids are dropped; none left → default channels.
+ mutating func apply(_ d: HC2CheckDetail, knownChannelIds: Set) {
+ let t = d.type ?? .http
+ type = t
+ name = d.name ?? ""
+ target = d.target ?? ""
+ ps = ParamsState.from(t, d.params)
+ iniPs = ps
+ (intervalValue, intervalUnit) = secondsToDuration(d.intervalSeconds)
+ (retryValue, retryUnit) = secondsToDuration(d.retryIntervalSeconds)
+ retries = d.retries.map(String.init) ?? ""
+ timeout = hcFormatNumber(d.timeoutSeconds)
+ connectTimeout = hcFormatNumber(d.connectTimeoutSeconds)
+ stabilize = d.stabilize.map(String.init) ?? ""
+ invert = d.invert ?? false
+ ipMode = d.ipMode
+ locations = (d.locations ?? []).map(\.rawValue)
+ policy = d.policy
+ execSel = d.execution ?? .online
+ nodeId = d.nodeID?.nonBlank
+ notifyDown = d.notifyDown ?? true
+ notifyUp = d.notifyUp ?? true
+ notifyDegraded = d.notifyDegraded ?? false
+ critical = d.critical ?? false
+ repeatMinutes = d.repeatMinutes
+ let known = Set(d.channels ?? []).intersection(knownChannelIds)
+ channels = known
+ useDefaultChannels = known.isEmpty
+ tags = (d.tags ?? []).joined(separator: ", ")
+ group = d.group ?? ""
+ description = d.description ?? ""
+ }
+
+ // MARK: Validation
+
+ /// Which collapsed section holds the problem.
+ enum FormSection: Sendable { case main, params, execution, advanced, notifications }
+
+ /// First failing rule (spec B4 validation 1–12).
+ func validate(maxLocations: Int?) -> (message: String, section: FormSection)? {
+ if name.nonBlank == nil { return (String(localized: "Please enter a name."), .main) }
+ if type != .push && target.nonBlank == nil { return (String(localized: "Please enter a target."), .main) }
+ if let issue = ps.validateIssue(type, target: target) { return (issue.message, issue.inAdvanced ? .advanced : .params) }
+ let interval = durationToSeconds(intervalValue, unitIdx: intervalUnit)
+ if let interval, interval < 20 { return (String(localized: "Interval must be at least 20 seconds."), .advanced) }
+ let retry = durationToSeconds(retryValue, unitIdx: retryUnit)
+ if let retry, retry < 5 { return (String(localized: "Retry interval must be at least 5 seconds."), .advanced) }
+ if retries.nonBlank != nil, !(Int(retries.hcTrimmed).map { (0...10).contains($0) } ?? false) {
+ return (String(localized: "Retries must be between 0 and 10."), .advanced)
+ }
+ if stabilize.nonBlank != nil, !(Int(stabilize.hcTrimmed).map { (1...20).contains($0) } ?? false) {
+ return (String(localized: "Stabilize must be between 1 and 20."), .advanced)
+ }
+ if timeout.nonBlank != nil, !(Double(timeout.hcTrimmed).map { $0 > 0 } ?? false) {
+ return (String(localized: "Timeout must be greater than 0."), .advanced)
+ }
+ if connectTimeout.nonBlank != nil, !(Double(connectTimeout.hcTrimmed).map { $0 > 0 } ?? false) {
+ return (String(localized: "Connect timeout must be greater than 0."), .advanced)
+ }
+ if usesLocations && type != .push {
+ if locations.isEmpty { return (String(localized: "Select at least one location."), .execution) }
+ if let maxLocations, locations.count > maxLocations {
+ return (String(localized: "Your plan allows up to \(maxLocations) locations per check."), .execution)
+ }
+ }
+ if !online && nodeId == nil { return (String(localized: "Select a node."), .execution) }
+ if !useDefaultChannels && channels.isEmpty {
+ return (String(localized: "Select at least one channel or use the default channels."), .notifications)
+ }
+ return nil
+ }
+
+ // MARK: Requests
+
+ private var trimmedName: String { name.hcTrimmed }
+ private var trimmedTarget: String? { type == .push ? nil : target.hcTrimmed }
+
+ /// Create request (`saveCreate`).
+ func createInput() -> HC2CheckInput {
+ let fields = executionFields(execution, nodeId: nodeId, locations: locations)
+ var input = HC2CheckInput(
+ name: trimmedName, type: type, target: trimmedTarget,
+ params: ps.toParams(type, ini: iniPs),
+ intervalSeconds: durationToSeconds(intervalValue, unitIdx: intervalUnit).flatMap { $0 >= 0 ? $0 : nil },
+ retryIntervalSeconds: durationToSeconds(retryValue, unitIdx: retryUnit).flatMap { $0 >= 0 ? $0 : nil },
+ retries: Int(retries.hcTrimmed), connectTimeoutSeconds: Double(connectTimeout.hcTrimmed),
+ timeoutSeconds: Double(timeout.hcTrimmed), invert: invert, ipMode: ipMode,
+ tags: hcParseTags(tags), group: group.hcTrimmed.nonBlank, description: description.hcTrimmed.nonBlank,
+ paused: createPaused, critical: critical, execution: execution,
+ nodeID: fields.nodeId, nodes: nil,
+ locations: type == .push ? nil : fields.locations.map { $0.map(HC2Location.init(rawValue:)) },
+ policy: policyApplies ? policy : nil,
+ notifyDegraded: notifyDegraded, notifyDown: notifyDown, notifyUp: notifyUp,
+ channels: useDefaultChannels ? [] : channels.sorted(), repeatMinutes: repeatMinutes)
+ input.stabilize = Int(stabilize.hcTrimmed)
+ return input
+ }
+
+ /// Does the edit change execution, node or locations (needs `checks.move`)?
+ func moveNeeded(old: HC2CheckDetail) -> Bool {
+ type != .push && executionMoveNeeded(
+ oldExec: old.execution, oldNodeId: old.nodeID, oldLocations: (old.locations ?? []).map(\.rawValue),
+ exec: execution, nodeId: nodeId, locations: locations)
+ }
+
+ /// Minimal diff against the loaded check (`buildUpdate`). `name`/`type` are always set (GAP: the SPM input
+ /// requires them); `hasChanges` tells whether anything else differs. Never sends execution/locations/node.
+ func updateInput(old: HC2CheckDetail, moveNeeded: Bool) -> (input: HC2CheckInput, hasChanges: Bool) {
+ var changed = false
+ func diff(_ new: T?, _ old: T?) -> T? {
+ guard let new, new != old else { return nil }
+ changed = true
+ return new
+ }
+ func text(_ new: String, _ old: String?) -> String? {
+ let value = new.hcTrimmed
+ if value == (old ?? "").hcTrimmed { return nil }
+ changed = true
+ return value
+ }
+ var input = HC2CheckInput(name: trimmedName, type: old.type ?? type)
+ if trimmedName != (old.name ?? "") { changed = true }
+ if type != .push { input.target = text(target, old.target) }
+ if ps != iniPs {
+ input.params = ps.toParams(type, ini: iniPs)
+ changed = true
+ }
+ input.intervalSeconds = diff(durationToSeconds(intervalValue, unitIdx: intervalUnit), old.intervalSeconds)
+ input.retryIntervalSeconds = diff(durationToSeconds(retryValue, unitIdx: retryUnit), old.retryIntervalSeconds)
+ input.retries = diff(Int(retries.hcTrimmed), old.retries)
+ input.connectTimeoutSeconds = diff(Double(connectTimeout.hcTrimmed), old.connectTimeoutSeconds)
+ input.timeoutSeconds = diff(Double(timeout.hcTrimmed), old.timeoutSeconds)
+ input.stabilize = diff(Int(stabilize.hcTrimmed), old.stabilize)
+ input.invert = diff(invert, old.invert ?? false)
+ input.ipMode = diff(ipMode, old.ipMode)
+ let newTags = hcParseTags(tags)
+ if Set(newTags) != Set(old.tags ?? []) || newTags.count != (old.tags ?? []).count {
+ input.tags = newTags
+ changed = true
+ }
+ input.group = text(group, old.group)
+ input.description = text(description, old.description)
+ let newChannels: [Int] = useDefaultChannels ? [] : channels.sorted()
+ if Set(newChannels) != Set(old.channels ?? []) {
+ input.channels = newChannels
+ changed = true
+ }
+ input.notifyDegraded = diff(notifyDegraded, old.notifyDegraded ?? false)
+ input.notifyDown = diff(notifyDown, old.notifyDown ?? true)
+ input.notifyUp = diff(notifyUp, old.notifyUp ?? true)
+ input.critical = diff(critical, old.critical ?? false)
+ input.repeatMinutes = diff(repeatMinutes, old.repeatMinutes)
+ if policyApplies && !moveNeeded { input.policy = diff(policy, old.policy) }
+ return (input, changed)
+ }
+}
+
+nonisolated extension String {
+ var hcTrimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) }
+}
+
+// MARK: - Helpers (ported from Android 2.1.0 HealthcheckLogic)
+
+nonisolated let healthcheckRepeatOptions: [Int?] = [nil, 0, 5, 10, 15, 30, 60, 120, 360, 720, 1440]
+
+nonisolated extension HC2CheckType {
+ var symbol: String {
+ switch self {
+ case .http: "globe"
+ case .keyword: "text.magnifyingglass"
+ case .json: "curlybraces"
+ case .dns: "network"
+ case .icmp: "dot.radiowaves.left.and.right"
+ case .tcp: "arrow.left.arrow.right"
+ case .port: "point.3.connected.trianglepath.dotted"
+ case .cert: "lock.shield"
+ case .push: "arrow.down.to.line"
+ case .whois: "person.text.rectangle"
+ default: "questionmark.circle"
+ }
+ }
+}
+
+/// Order of the type picker when creating a check.
+nonisolated let healthcheckCreateTypes: [HC2CheckType] = [.http, .keyword, .json, .dns, .icmp, .tcp, .port, .cert, .push, .whois]
+
+nonisolated extension HC2CheckType {
+ /// Placeholder of the target field.
+ var targetHint: String {
+ switch self {
+ case .http, .keyword, .json: "https://example.com/health"
+ case .dns, .whois: "example.com"
+ case .icmp: "example.com or IP address"
+ case .tcp, .port: "host:port"
+ case .cert: "example.com or host:port"
+ default: ""
+ }
+ }
+}
+
+nonisolated let durationUnits: [(name: String, seconds: Int)] = [("seconds", 1), ("minutes", 60), ("hours", 3600), ("days", 86_400)]
+
+/// Seconds → (value, unit index) using the largest unit that divides exactly.
+nonisolated func secondsToDuration(_ seconds: Int?) -> (String, Int) {
+ guard let seconds, seconds > 0 else { return ("", 1) }
+ for idx in durationUnits.indices.reversed() where seconds % durationUnits[idx].seconds == 0 {
+ return (String(seconds / durationUnits[idx].seconds), idx)
+ }
+ return (String(seconds), 0)
+}
+
+/// Blank → `nil` (server default), invalid / out of range → -1.
+nonisolated func durationToSeconds(_ value: String, unitIdx: Int) -> Int? {
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed.isEmpty { return nil }
+ guard let n = Int64(trimmed) else { return -1 }
+ let unit = Int64(durationUnits[min(max(unitIdx, 0), durationUnits.count - 1)].seconds)
+ let (total, overflow) = n.multipliedReportingOverflow(by: unit)
+ return !overflow && total >= 0 && total <= Int64(Int32.max) ? Int(total) : -1
+}
+
+/// Integers without ".0".
+nonisolated func hcFormatNumber(_ value: Double?) -> String {
+ guard let value else { return "" }
+ return value.truncatingRemainder(dividingBy: 1) == 0 ? String(Int64(value)) : String(value)
+}
+
+nonisolated func hcParseTags(_ text: String) -> [String] {
+ var seen = Set()
+ return text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }
+ .filter { !$0.isEmpty && seen.insert($0).inserted }
+}
+
+nonisolated struct ExecutionFields: Equatable, Sendable {
+ var execution: HC2Execution
+ var nodeId: String?
+ var locations: [String]?
+}
+
+/// Online → locations only, node → node only, both → both.
+nonisolated func executionFields(_ execution: HC2Execution, nodeId: String?, locations: [String]) -> ExecutionFields {
+ ExecutionFields(execution: execution,
+ nodeId: execution == .online ? nil : nodeId,
+ locations: execution == .local ? nil : locations)
+}
+
+/// Does the change need `checks.move()`? (a missing old execution counts as online)
+nonisolated func executionMoveNeeded(
+ oldExec: HC2Execution?, oldNodeId: String?, oldLocations: [String],
+ exec: HC2Execution, nodeId: String?, locations: [String]
+) -> Bool {
+ (oldExec ?? .online) != exec
+ || (exec != .online && nodeId != oldNodeId)
+ || (exec != .local && Set(locations) != Set(oldLocations))
+}
+
+nonisolated enum MoveClassification: Equatable, Sendable {
+ case applied
+ case failed(String)
+ case running
+}
+
+nonisolated func classifyTestrun(_ run: HC2Testrun) -> MoveClassification {
+ switch run.status?.rawValue.lowercased() {
+ case "ok": return .applied
+ case "failed": return .failed(testrunFailureMessage(run))
+ case "expired": return .failed(String(localized: "The test run expired before it finished."))
+ default: return .running
+ }
+}
+
+nonisolated func testrunFailureMessage(_ run: HC2Testrun) -> String {
+ let messages = (run.results ?? []).filter { $0.ok != true }.compactMap { result -> String? in
+ guard let message = result.message?.nonBlank else { return nil }
+ return result.source.map { "\($0): \(message)" } ?? message
+ }
+ if !messages.isEmpty { return messages.joined(separator: "\n") }
+ if let error = run.error?.nonBlank { return error }
+ return String(localized: "The test run failed. The change was not applied.")
+}
+
+/// Result of an execution change (`checks.move` + test run).
+enum MoveOutcome: Equatable {
+ case applied
+ case failed(String)
+ case timedOut
+}
+
+/// Starts the move and polls the test run every 2 s for at most 60 s.
+func runHealthcheckMove(api: IPv64, token: String, fields: ExecutionFields) async throws -> MoveOutcome {
+ let run = try await ipv64Retrying {
+ try await api.hc2.checks.move(token, execution: fields.execution, nodeID: fields.nodeId, nodes: nil,
+ locations: fields.locations?.map(HC2Location.init(rawValue:)))
+ }
+ var current = run
+ for _ in 0..<30 {
+ switch classifyTestrun(current) {
+ case .applied: return .applied
+ case .failed(let message): return .failed(message)
+ case .running: break
+ }
+ try await Task.sleep(for: .seconds(2))
+ current = try await api.hc2.checks.testrun(run.id)
+ }
+ return .timedOut
+}
diff --git a/IPv64/Helpers/Healthchecks/HealthcheckFormat.swift b/IPv64/Helpers/Healthchecks/HealthcheckFormat.swift
new file mode 100644
index 0000000..41e7db1
--- /dev/null
+++ b/IPv64/Helpers/Healthchecks/HealthcheckFormat.swift
@@ -0,0 +1,107 @@
+import SwiftUI
+import IPv64
+
+// Texts and small helpers of the healthcheck detail (ported from Android 2.1.0 Formatters / Hc2CheckUi).
+
+nonisolated enum HcFormat {
+ /// Go zero dates (year 0001) and the epoch count as "no date".
+ static func real(_ date: Date?) -> Date? {
+ guard let date, date.timeIntervalSince1970 > 0 else { return nil }
+ return date
+ }
+
+ static func time(_ date: Date?) -> String? {
+ real(date).map { DynDNSLogic.germanTime($0) }
+ }
+
+ static func timeWithRelative(_ date: Date?) -> String? {
+ guard let date = real(date) else { return nil }
+ return "\(DynDNSLogic.germanTime(date)) (\(date.formatted(.relative(presentation: .named))))"
+ }
+
+ static func latency(_ value: Double?) -> String {
+ guard let value else { return "–" }
+ return value.formatted(.number.precision(.fractionLength(0...(value < 10 ? 1 : 0)))) + " ms"
+ }
+
+ static func percent(_ value: Double?) -> String {
+ guard let value else { return "–" }
+ return value.formatted(.number.precision(.fractionLength(0...2))) + " %"
+ }
+
+ static func duration(seconds: Int) -> String {
+ if seconds <= 0 { return "0 s" }
+ var rest = seconds
+ var parts: [String] = []
+ for (size, name) in [(86_400, "d"), (3600, "h"), (60, "min"), (1, "s")] where parts.count < 2 {
+ let n = rest / size
+ if n > 0 {
+ parts.append("\(n) \(name)")
+ rest -= n * size
+ }
+ }
+ return parts.joined(separator: " ")
+ }
+
+ static func seconds(_ value: Double) -> String { duration(seconds: Int(value.rounded())) }
+
+ static func repeatMinutes(_ minutes: Int) -> String {
+ minutes <= 0 ? String(localized: "Off") : duration(seconds: minutes * 60)
+ }
+
+ static func yesNo(_ value: Bool?) -> String? {
+ value.map { $0 ? String(localized: "Yes") : String(localized: "No") }
+ }
+
+ /// Event kind title: "_" becomes a space, first letter uppercased; blank gives the fallback.
+ static func eventTitle(kind: String?, fallback: String) -> String {
+ guard let kind = kind?.nonBlank else { return fallback }
+ let text = kind.replacingOccurrences(of: "_", with: " ")
+ return text.prefix(1).uppercased() + text.dropFirst()
+ }
+
+ static func eventState(kind: String?, to: String?) -> Hc2StateUi {
+ switch kind?.lowercased() {
+ case "down", "reminder": .down
+ case "up", "degraded_end", "flapping_end": .up
+ case "degraded": .degraded
+ case "flapping_start": .flapping
+ default: Hc2StateUi.from(state: to.flatMap { HC2CheckState(rawValue: $0.lowercased()) }, paused: false)
+ }
+ }
+
+ /// Channel name, else type label, else type, else `Channel #id`.
+ static func channelName(_ channel: HC2Channel) -> String {
+ channel.name?.trimmingCharacters(in: .whitespaces).nonBlank ?? channel.typeLabel?.nonBlank
+ ?? channel.type?.rawValue.nonBlank ?? String(localized: "Channel #\(channel.id)")
+ }
+
+ /// Command output as text (JSON string or JSON-encoded), trimmed, first 400 characters.
+ static func commandOutput(_ output: JSONValue?) -> String? {
+ guard let output, output != .null else { return nil }
+ let text = output.stringValue ?? (try? JSONEncoder().encode(output)).map { String(decoding: $0, as: UTF8.self) } ?? ""
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? nil : String(trimmed.prefix(400))
+ }
+
+ /// Only http(s) targets of http, keyword and json checks can be opened.
+ static func browserURL(type: HC2CheckType?, target: String?) -> URL? {
+ guard let type, [.http, .keyword, .json].contains(type),
+ let target, target.lowercased().hasPrefix("http") else { return nil }
+ return URL(string: target)
+ }
+}
+
+nonisolated extension Hc2StateUi {
+ static func from(state: HC2CheckState?, paused: Bool?) -> Hc2StateUi {
+ if paused == true { return .paused }
+ switch state {
+ case .up: return .up
+ case .down: return .down
+ case .degraded: return .degraded
+ case .flapping: return .flapping
+ case .paused: return .paused
+ default: return .pending
+ }
+ }
+}
diff --git a/IPv64/Helpers/Healthchecks/HealthcheckLogic.swift b/IPv64/Helpers/Healthchecks/HealthcheckLogic.swift
new file mode 100644
index 0000000..ac4e04a
--- /dev/null
+++ b/IPv64/Helpers/Healthchecks/HealthcheckLogic.swift
@@ -0,0 +1,97 @@
+import SwiftUI
+import IPv64
+
+// Healthchecks 2.0 list logic (ported from Android 2.1.0: Hc2CheckUi.kt, HealthcheckView.kt).
+
+nonisolated extension HC2CheckType {
+ /// Readable type name.
+ var label: String {
+ switch self {
+ case .http: "HTTP(S)"
+ case .keyword: "Keyword"
+ case .json: "JSON"
+ case .dns: "DNS"
+ case .icmp: "Ping (ICMP)"
+ case .tcp: "TCP"
+ case .port: "Port"
+ case .cert: "Certificate"
+ case .push: "Push"
+ case .whois: "WHOIS"
+ default: "Unknown"
+ }
+ }
+}
+
+/// Displayed state of a check; `paused` wins over the measured state.
+nonisolated enum Hc2StateUi: Sendable {
+ case up, down, degraded, flapping, paused, pending
+
+ static func from(_ check: HC2Check) -> Hc2StateUi { from(state: check.state?.state, paused: check.paused) }
+
+ var label: String {
+ switch self {
+ case .up: "Up"
+ case .down: "Down"
+ case .degraded: "Degraded"
+ case .flapping: "Flapping"
+ case .paused: "Paused"
+ case .pending: "Pending"
+ }
+ }
+
+ var color: Color {
+ switch self {
+ case .up: .green
+ case .down: .red
+ case .degraded, .flapping: .orange
+ case .paused: .teal
+ case .pending: .gray
+ }
+ }
+}
+
+nonisolated enum HcStatusFilter: CaseIterable, Hashable, Sendable {
+ case all, up, degraded, down, paused
+
+ var label: String {
+ switch self {
+ case .all: "All"
+ case .up: "Up"
+ case .degraded: "Degraded"
+ case .down: "Down"
+ case .paused: "Paused"
+ }
+ }
+
+ func matches(_ state: Hc2StateUi) -> Bool {
+ switch (self, state) {
+ case (.all, _), (.up, .up), (.degraded, .degraded), (.degraded, .flapping), (.down, .down), (.paused, .paused):
+ true
+ default:
+ false
+ }
+ }
+}
+
+/// Where a check runs; the filter is only offered when some check runs on a node.
+nonisolated enum HcExecFilter: CaseIterable, Hashable, Sendable {
+ case all, online, node, both
+
+ var label: String {
+ switch self {
+ case .all: "All"
+ case .online: "Online"
+ case .node: "Node"
+ case .both: "Both"
+ }
+ }
+
+ func matches(_ execution: HC2Execution?) -> Bool {
+ switch self {
+ case .all: true
+ case .online: (execution ?? .online) == .online
+ case .node: execution == .local
+ case .both: execution == .both
+ }
+ }
+}
diff --git a/IPv64/Helpers/Healthchecks/HealthcheckParamsState.swift b/IPv64/Helpers/Healthchecks/HealthcheckParamsState.swift
new file mode 100644
index 0000000..0d75b2f
--- /dev/null
+++ b/IPv64/Helpers/Healthchecks/HealthcheckParamsState.swift
@@ -0,0 +1,295 @@
+import Foundation
+import IPv64
+
+// Type-dependent parameters of the account check form (spec 02 B5; Android `ParamsState`).
+// Everything is text so input stays verbatim. Pure and nonisolated.
+
+nonisolated struct HeaderRow: Hashable, Identifiable, Sendable {
+ var id = UUID()
+ var key = ""
+ var value = ""
+}
+
+nonisolated struct JsonRuleRow: Hashable, Identifiable, Sendable {
+ var id = UUID()
+ var path = ""
+ var op: HC2JSONRuleOperator = .eq
+ var value = ""
+}
+
+nonisolated extension HC2JSONRuleOperator {
+ var needsValue: Bool { self != .exists && self != .notExists }
+}
+
+nonisolated let jsonRuleOperators: [HC2JSONRuleOperator] = [
+ .eq, .ne, .lt, .le, .gt, .ge, .contains, .notContains, .regex, .exists, .notExists,
+]
+
+nonisolated let dnsRecordTypes: [HC2DNSRecordType] = [.a, .aaaa, .cname, .mx, .txt, .ns, .srv, .caa, .ptr, .soa]
+
+nonisolated let httpMethods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
+
+nonisolated struct ParamsState: Equatable, Sendable {
+ // http / keyword / json
+ var method = "GET"
+ var acceptStatus = ""
+ var followRedirects = true
+ var maxRedirects = ""
+ var keyword = ""
+ var keywordAbsent = false
+ var basicUser = ""
+ var basicPassword = ""
+ var headers: [HeaderRow] = []
+ var body = ""
+ var insecureTls = false
+ var certMinDays = ""
+ // json
+ var jsonRules: [JsonRuleRow] = []
+ var jsonAny = false
+ // dns
+ var recordType: HC2DNSRecordType = .a
+ var resolver: HC2DNSResolver = .system
+ var server = ""
+ var values = ""
+ var dnssec = false
+ var minTtl = ""
+ // dns / tcp / port
+ var expect = ""
+ // icmp
+ var count = ""
+ var maxLossPercent = ""
+ var maxLatencyMs = ""
+ // tcp / port / cert
+ var port = ""
+ var send = ""
+ var tls = false
+ // cert
+ var minDays = ""
+ var serverName = ""
+ var skipChain = false
+ var skipHostname = false
+ // push
+ var periodValue = ""
+ var periodUnit = 1
+ var graceValue = ""
+ var graceUnit = 1
+
+ static func initial(_ type: HC2CheckType) -> ParamsState {
+ switch type {
+ case .dns: ParamsState(expect: "any")
+ case .port: ParamsState(expect: "open")
+ default: ParamsState()
+ }
+ }
+
+ /// Loaded parameters → form state; passwords never come back.
+ static func from(_ type: HC2CheckType, _ p: HC2CheckParams?) -> ParamsState {
+ var s = initial(type)
+ guard let p else { return s }
+ let (pv, pu) = secondsToDuration(p.periodSeconds)
+ let (gv, gu) = secondsToDuration(p.graceSeconds)
+ s.method = p.method?.nonBlank ?? s.method
+ s.acceptStatus = p.acceptStatus ?? ""
+ s.followRedirects = p.followRedirects ?? s.followRedirects
+ s.maxRedirects = p.maxRedirects.map(String.init) ?? ""
+ s.keyword = p.keyword ?? ""
+ s.keywordAbsent = p.keywordAbsent ?? false
+ s.basicUser = p.basicUser ?? ""
+ s.basicPassword = ""
+ s.headers = (p.headers ?? [:]).sorted { $0.key < $1.key }.map { HeaderRow(key: $0.key, value: $0.value) }
+ s.body = p.body ?? ""
+ s.insecureTls = p.insecureTLS ?? false
+ s.certMinDays = p.certMinDays.map(String.init) ?? ""
+ s.jsonRules = (p.jsonRules ?? []).map { JsonRuleRow(path: $0.path, op: $0.op, value: $0.value ?? "") }
+ s.jsonAny = p.jsonAny ?? false
+ s.recordType = p.recordType ?? s.recordType
+ s.resolver = p.resolver ?? s.resolver
+ s.server = p.server ?? ""
+ s.values = (p.values ?? []).joined(separator: "\n")
+ s.dnssec = p.dnssec ?? false
+ s.minTtl = p.minTTL.map(String.init) ?? ""
+ s.expect = p.expect?.nonBlank ?? s.expect
+ s.count = p.count.map(String.init) ?? ""
+ s.maxLossPercent = p.maxLossPercent.map(String.init) ?? ""
+ s.maxLatencyMs = p.maxLatencyMS.map(String.init) ?? ""
+ s.port = p.port.map(String.init) ?? ""
+ s.send = p.send ?? ""
+ s.tls = p.tls ?? false
+ s.minDays = p.minDays.map(String.init) ?? ""
+ s.serverName = p.serverName ?? ""
+ s.skipChain = p.skipChain ?? false
+ s.skipHostname = p.skipHostname ?? false
+ s.periodValue = pv
+ s.periodUnit = pu
+ s.graceValue = gv
+ s.graceUnit = gu
+ return s
+ }
+
+ // MARK: Request mapping
+
+ /// Non-blank → trimmed; else "" when something was there before (clears); else not sent.
+ private static func txt(_ cur: String, _ ini: String) -> String? {
+ cur.nonBlank.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } ?? (ini.nonBlank != nil ? "" : nil)
+ }
+
+ private static func int(_ s: String) -> Int? { Int(s.trimmingCharacters(in: .whitespaces)) }
+
+ /// Parameters for the request. Password and headers are only sent when changed.
+ func toParams(_ type: HC2CheckType, ini: ParamsState) -> HC2CheckParams? {
+ switch type {
+ case .http, .keyword, .json:
+ HC2CheckParams(
+ method: method.trimmingCharacters(in: .whitespaces).nonBlank,
+ acceptStatus: Self.txt(acceptStatus, ini.acceptStatus),
+ followRedirects: followRedirects,
+ maxRedirects: Self.int(maxRedirects),
+ keyword: type == .keyword ? keyword.trimmingCharacters(in: .whitespacesAndNewlines) : nil,
+ keywordAbsent: type == .keyword ? keywordAbsent : nil,
+ basicUser: Self.txt(basicUser, ini.basicUser),
+ basicPassword: basicPassword.isEmpty ? nil : basicPassword,
+ headers: headersForRequest(ini),
+ body: Self.txt(body, ini.body),
+ insecureTLS: insecureTls,
+ certMinDays: Self.int(certMinDays),
+ jsonRules: type == .json ? jsonRules.map {
+ HC2CheckParams.JSONRule(path: $0.path.trimmingCharacters(in: .whitespaces), op: $0.op,
+ value: $0.op.needsValue ? $0.value : nil)
+ } : nil,
+ jsonAny: type == .json ? jsonAny : nil)
+ case .dns:
+ HC2CheckParams(
+ expect: expect.nonBlank,
+ recordType: recordType, resolver: resolver,
+ server: resolver == .server ? server.trimmingCharacters(in: .whitespaces) : nil,
+ values: ["contains", "equals", "regex"].contains(expect)
+ ? values.split(whereSeparator: \.isNewline)
+ .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } : nil,
+ dnssec: dnssec, minTTL: Self.int(minTtl))
+ case .icmp:
+ HC2CheckParams(count: Self.int(count), maxLossPercent: Self.int(maxLossPercent),
+ maxLatencyMS: Self.int(maxLatencyMs))
+ case .tcp:
+ HC2CheckParams(port: Self.int(port), send: Self.txt(send, ini.send),
+ expect: Self.txt(expect, ini.expect), tls: tls)
+ case .port:
+ HC2CheckParams(port: Self.int(port), expect: expect.nonBlank)
+ case .cert:
+ HC2CheckParams(port: Self.int(port), minDays: Self.int(minDays),
+ serverName: Self.txt(serverName, ini.serverName),
+ skipChain: skipChain, skipHostname: skipHostname)
+ case .push:
+ HC2CheckParams(
+ periodSeconds: durationToSeconds(periodValue, unitIdx: periodUnit).flatMap { $0 >= 0 ? $0 : nil },
+ graceSeconds: durationToSeconds(graceValue, unitIdx: graceUnit).flatMap { $0 >= 0 ? $0 : nil })
+ default:
+ nil
+ }
+ }
+
+ /// Headers only when changed (nil = server keeps them); unchanged masked placeholders are left out.
+ func headersForRequest(_ ini: ParamsState) -> [String: String]? {
+ let old = ini.headers.headerMap
+ let now = headers.headerMap
+ if now == old { return nil }
+ return now.filter { !(old[$0.key] == $0.value && $0.value.looksMasked) }
+ }
+
+ /// Headers were changed although unchanged masked values are still in the list.
+ func headersNeedReentry(_ ini: ParamsState) -> Bool {
+ let old = ini.headers.headerMap
+ let now = headers.headerMap
+ return now != old && now.contains { old[$0.key] == $0.value && $0.value.looksMasked }
+ }
+
+ // MARK: Validation
+
+ private static func inRange(_ s: String, _ range: ClosedRange) -> Bool {
+ s.nonBlank == nil || (int(s).map(range.contains) ?? false)
+ }
+
+ /// Error text + whether the field is in the collapsed "Advanced" section.
+ func validateIssue(_ type: HC2CheckType, target: String) -> (message: String, inAdvanced: Bool)? {
+ switch type {
+ case .http, .keyword, .json:
+ if followRedirects && !Self.inRange(maxRedirects, 0...50) {
+ return (String(localized: "Max redirects must be a number between 0 and 50."), true)
+ }
+ if !Self.inRange(certMinDays, 0...3650) {
+ return (String(localized: "Certificate minimum days must be between 0 and 3650."), true)
+ }
+ if headers.contains(where: { $0.key.nonBlank == nil && $0.value.nonBlank != nil }) {
+ return (String(localized: "Every header needs a name."), true)
+ }
+ if type == .keyword && keyword.nonBlank == nil { return (String(localized: "Please enter a keyword."), false) }
+ if type == .json {
+ if jsonRules.isEmpty { return (String(localized: "Add at least one JSON rule."), false) }
+ if jsonRules.count > 10 { return (String(localized: "At most 10 JSON rules are allowed."), false) }
+ if jsonRules.contains(where: { $0.path.nonBlank == nil }) {
+ return (String(localized: "Every JSON rule needs a path."), false)
+ }
+ if jsonRules.contains(where: { $0.op.needsValue && $0.value.nonBlank == nil }) {
+ return (String(localized: "Every JSON rule except exists / not exists needs a value."), false)
+ }
+ }
+ case .dns:
+ if resolver == .server && server.nonBlank == nil { return (String(localized: "Please enter a DNS server."), true) }
+ if !Self.inRange(minTtl, 0...Int(Int32.max)) {
+ return (String(localized: "Minimum TTL must be a number of 0 or more."), true)
+ }
+ if ["contains", "equals", "regex"].contains(expect) && values.nonBlank == nil {
+ return (String(localized: "Please enter the expected value(s)."), true)
+ }
+ case .icmp:
+ if !Self.inRange(count, 1...20) { return (String(localized: "Packet count must be between 1 and 20."), true) }
+ if !Self.inRange(maxLossPercent, 0...100) {
+ return (String(localized: "Max packet loss must be between 0 and 100."), true)
+ }
+ if !Self.inRange(maxLatencyMs, 0...Int(Int32.max)) {
+ return (String(localized: "Max latency must be a number of 0 or more."), true)
+ }
+ case .tcp, .port:
+ if !Self.inRange(port, 1...65535) { return (String(localized: "Port must be between 1 and 65535."), false) }
+ if port.nonBlank == nil && !target.contains(":") {
+ return (String(localized: "Please enter a port or use host:port as target."), false)
+ }
+ case .cert:
+ if !Self.inRange(port, 1...65535) { return (String(localized: "Port must be between 1 and 65535."), true) }
+ if !Self.inRange(minDays, 0...3650) { return (String(localized: "Minimum days must be between 0 and 3650."), true) }
+ case .push:
+ if durationToSeconds(periodValue, unitIdx: periodUnit) == -1 {
+ return (String(localized: "Expected interval is not a valid number."), false)
+ }
+ if durationToSeconds(graceValue, unitIdx: graceUnit) == -1 {
+ return (String(localized: "Grace period is not a valid number."), false)
+ }
+ default:
+ break
+ }
+ return nil
+ }
+}
+
+nonisolated extension HC2CheckType {
+ /// Types with core parameters shown in the main form.
+ var hasEssentialParams: Bool { [.keyword, .json, .dns, .tcp, .port, .push].contains(self) }
+ /// Types with fine options (inside "Advanced").
+ var hasAdvancedParams: Bool { ![.whois, .push].contains(self) }
+}
+
+private nonisolated extension [HeaderRow] {
+ var headerMap: [String: String] {
+ var map: [String: String] = [:]
+ for row in self where row.key.nonBlank != nil {
+ map[row.key.trimmingCharacters(in: .whitespaces)] = row.value
+ }
+ return map
+ }
+}
+
+private nonisolated extension String {
+ var looksMasked: Bool {
+ hasPrefix("…")
+ || (count >= 3 && (allSatisfy { "*•●".contains($0) } || lowercased() == "" || lowercased() == "[redacted]"))
+ }
+}
diff --git a/IPv64/Helpers/Healthchecks/Monitor64Logic.swift b/IPv64/Helpers/Healthchecks/Monitor64Logic.swift
new file mode 100644
index 0000000..471ef95
--- /dev/null
+++ b/IPv64/Helpers/Healthchecks/Monitor64Logic.swift
@@ -0,0 +1,164 @@
+import SwiftUI
+import IPv64
+
+// Monitor64 hosts of connected nodes in the Healthchecks tab (Android 2.2.0). Pure and nonisolated.
+
+/// Pushed from the list.
+struct Monitor64HostRoute: Hashable {
+ let nodeId: String
+ let uid: String
+}
+
+/// Where "+" creates the new healthcheck.
+enum HealthcheckTarget: Hashable {
+ case account
+ case nodeCheck(String)
+ case monitor64Host(String)
+}
+
+/// Monitor64 hosts of one node in the list; no entry = module off or node not reachable.
+nonisolated struct Monitor64ListData: Sendable {
+ var hosts: [Node64.Monitor64OverviewHost] = []
+ /// Set when Monitor64 answered with an error other than 404.
+ var error: String?
+}
+
+/// 404 means the module is off (or the host is gone).
+nonisolated func isNodeNotFound(_ error: any Error) -> Bool {
+ guard let error = error as? Node64Error else { return false }
+ switch error {
+ case .api(let e): return e.status == 404
+ case .httpStatus(let code, _): return code == 404
+ default: return false
+ }
+}
+
+/// Displayed state of a host or problem: text and colour; `paused` wins.
+nonisolated struct Monitor64Display: Sendable {
+ let label: String
+ let color: Color
+
+ static func host(view: String?, paused: Bool?) -> Monitor64Display {
+ if paused == true { return Monitor64Display(label: "Paused", color: .gray) }
+ switch view {
+ case "ok": return Monitor64Display(label: "OK", color: .green)
+ case "warn": return Monitor64Display(label: "Warning", color: .orange)
+ case "crit": return Monitor64Display(label: "Critical", color: .red)
+ case "unreachable": return Monitor64Display(label: "Unreachable", color: .red)
+ case "maintenance": return Monitor64Display(label: "Maintenance", color: .gray)
+ default: return Monitor64Display(label: "Unknown", color: .gray)
+ }
+ }
+
+ static func service(_ state: String?) -> Monitor64Display {
+ switch state {
+ case "ok": Monitor64Display(label: "OK", color: .green)
+ case "warn": Monitor64Display(label: "Warning", color: .orange)
+ case "crit": Monitor64Display(label: "Critical", color: .red)
+ default: Monitor64Display(label: "Unknown", color: .gray)
+ }
+ }
+
+ /// ok = Up, warn = Degraded, crit/unreachable = Down, paused/maintenance = Paused.
+ func matches(_ filter: HcStatusFilter) -> Bool {
+ switch filter {
+ case .all: true
+ case .up: label == "OK"
+ case .degraded: label == "Warning"
+ case .down: label == "Critical" || label == "Unreachable"
+ case .paused: label == "Paused" || label == "Maintenance"
+ }
+ }
+}
+
+nonisolated extension Node64.Monitor64OverviewHost {
+ var display: Monitor64Display { .host(view: view?.rawValue, paused: paused) }
+}
+
+nonisolated extension String {
+ /// The node sends untranslated keys ("i18n:monitor64.svc.fs?name=%2F"): last key part plus parameter values ("fs /").
+ var m64Text: String {
+ guard let regex = try? NSRegularExpression(pattern: #"i18n:([\w.\-]+)(?:\?([^\s]*))?"#) else { return self }
+ let result = NSMutableString(string: self)
+ for match in regex.matches(in: self, range: NSRange(startIndex..., in: self)).reversed() {
+ func group(_ i: Int) -> String {
+ Range(match.range(at: i), in: self).map { String(self[$0]) } ?? ""
+ }
+ let word = (group(1).split(separator: ".").last.map(String.init) ?? group(1)).replacingOccurrences(of: "_", with: " ")
+ let values = group(2).split(separator: "&", omittingEmptySubsequences: false).compactMap { part -> String? in
+ guard let eq = part.firstIndex(of: "=") else { return nil }
+ let value = String(part[part.index(after: eq)...])
+ return value.isEmpty ? nil : (value.removingPercentEncoding ?? value)
+ }
+ result.replaceCharacters(in: match.range, with: values.isEmpty ? word : "\(word) \(values.joined(separator: " / "))")
+ }
+ return result as String
+ }
+}
+
+nonisolated let monitor64HostKinds: [Node64.Monitor64HostKind] = [
+ .unspecified, .linuxAgent, .windows, .freebsd, .ssh, .pve, .pbs, .docker, .truenas, .unraid, .server, .ups, .prom, .snmp, .nas,
+]
+
+nonisolated let monitor64AccessTypes: [Node64.Monitor64AccessType] = [
+ .agent, .ssh, .pve, .pbs, .docker, .prom, .nut, .truenas, .unraid, .redfish, .snmp,
+]
+
+nonisolated extension Node64.Monitor64HostKind {
+ var label: String { self == .unspecified ? "None" : rawValue }
+}
+
+/// Access form fields. The server checks strictly "only fields of the access type", so only non-empty fields are sent.
+nonisolated struct Monitor64AccessDraft: Hashable, Sendable {
+ /// Existing access; `nil` = new.
+ var uid: String?
+ /// `nil` = no access (creating a host).
+ var type: Node64.Monitor64AccessType?
+ var port = ""
+ var user = ""
+ var url = ""
+ var tokenId = ""
+ /// Write-only.
+ var secret = ""
+ var enabled = true
+ /// Config as loaded: the PUT replaces it, so fields not shown here must be kept.
+ var base: Node64.Monitor64AccessConfig?
+ /// Confirmed fingerprint: hostkey for SSH, else `config.pin`.
+ var fingerprint: String?
+
+ init(uid: String? = nil, type: Node64.Monitor64AccessType? = nil) {
+ self.uid = uid
+ self.type = type
+ }
+
+ init(_ a: Node64.Monitor64AccessState) {
+ uid = a.uid
+ type = a.type ?? .agent
+ port = a.config?.port.flatMap { $0 > 0 ? String($0) : nil } ?? ""
+ user = a.config?.user ?? ""
+ url = a.config?.url ?? ""
+ tokenId = a.config?.tokenID ?? ""
+ enabled = a.enabled != false
+ base = a.config ?? Node64.Monitor64AccessConfig()
+ }
+
+ /// Changing the target invalidates a test and a confirmed fingerprint.
+ var targetKey: String { [type?.rawValue ?? "", port, user, url, tokenId, secret].joined(separator: "\u{1}") }
+
+ func input() -> Node64.Monitor64AccessInput? {
+ guard let type else { return nil }
+ let ssh = type == .ssh
+ var config = base ?? Node64.Monitor64AccessConfig()
+ config.port = Int(port.hcTrimmed)
+ config.user = user.nonBlank?.hcTrimmed
+ config.url = url.nonBlank?.hcTrimmed
+ config.tokenID = tokenId.nonBlank?.hcTrimmed
+ if !ssh, let fingerprint { config.pin = fingerprint }
+ return Node64.Monitor64AccessInput(
+ type: type,
+ config: base != nil || config != Node64.Monitor64AccessConfig() ? config : nil,
+ secret: secret.isEmpty ? nil : secret,
+ hostkey: ssh ? fingerprint : nil,
+ enabled: uid == nil ? nil : enabled)
+ }
+}
diff --git a/IPv64/Helpers/Healthchecks/NodeCheckLogic.swift b/IPv64/Helpers/Healthchecks/NodeCheckLogic.swift
new file mode 100644
index 0000000..432e5f4
--- /dev/null
+++ b/IPv64/Helpers/Healthchecks/NodeCheckLogic.swift
@@ -0,0 +1,180 @@
+import Foundation
+import IPv64
+
+// Logic of the node healthchecks (Node64 `hc.checks`; Android 2.1.0). Pure and nonisolated.
+
+/// Node64 type order of the form (docker and proxmox no longer exist since 2.x).
+nonisolated let nodeCheckTypes: [Node64.CheckType] = [.http, .keyword, .json, .dns, .icmp, .tcp, .port, .cert, .whois, .push]
+
+nonisolated extension Node64.CheckType {
+ /// The same type as account check (labels, symbols and hints are shared).
+ var hc2: HC2CheckType { HC2CheckType(rawValue: rawValue) }
+ var label: String { hc2.label }
+}
+
+/// Node64 timestamps are ISO 8601 strings; Go zero dates are removed later by `HcFormat.real`.
+nonisolated func nodeDate(_ iso: String?) -> Date? {
+ guard let iso = iso?.trimmingCharacters(in: .whitespaces), !iso.isEmpty else { return nil }
+ return (try? Date(iso, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)))
+ ?? (try? Date(iso, strategy: Date.ISO8601FormatStyle()))
+}
+
+nonisolated extension Node64.Check {
+ var uiState: Hc2StateUi {
+ Hc2StateUi.from(state: state?.state.map { HC2CheckState(rawValue: $0.rawValue) }, paused: paused)
+ }
+
+ /// `owner != online && owner != other` (nil, "self" and unknown count as owned by the node).
+ var isNodeOwned: Bool { owner != .online && owner != .other }
+}
+
+/// State of the healthchecks module of a node.
+nonisolated enum NodeChecksModule: Sendable { case on, off, missing }
+
+nonisolated func nodeChecksModule(_ modules: [Node64.ModuleStatus]?) -> NodeChecksModule {
+ guard let modules, !modules.isEmpty else { return .on }
+ guard let module = modules.first(where: { ["checks", "healthchecks"].contains($0.name.lowercased()) }) else { return .missing }
+ return module.enabled == false ? .off : .on
+}
+
+/// Stored result of one connected node in the list.
+nonisolated struct NodeChecksData: Sendable {
+ var module: NodeChecksModule
+ var checks: [Node64.Check] = []
+ /// Set when the node could not be reached.
+ var error: String?
+
+ /// Checks owned by the node itself (others belong to the account).
+ var owned: [Node64.Check] { checks.filter(\.isNodeOwned) }
+}
+
+/// Pushed from the list.
+struct NodeCheckRoute: Hashable {
+ let nodeId: String
+ let token: String
+}
+
+/// Form state of the node check sheet. Pure and nonisolated.
+nonisolated struct NodeCheckFormState: Equatable, Sendable {
+ var type: Node64.CheckType = .http
+ var name = ""
+ var target = ""
+ var keyword = ""
+ var port = ""
+ var recordType: HC2DNSRecordType = .a
+ var intervalValue = ""
+ var intervalUnit = 1
+ var retryValue = ""
+ var retryUnit = 1
+ var retries = ""
+ var timeout = ""
+ var connectTimeout = ""
+ var stabilize = ""
+ var invert = false
+ var ipMode: Node64.CheckIPMode?
+ var notifyDown = true
+ var notifyUp = true
+ var notifyDegraded = false
+ var critical = false
+ var repeatMinutes: Int?
+ var tags = ""
+ var group = ""
+ var description = ""
+ var createPaused = false
+ /// Loaded check (edit); `nil` when creating.
+ var base: Node64.Check?
+
+ var editing: Bool { base != nil }
+
+ mutating func apply(_ c: Node64.Check) {
+ base = c
+ name = c.name ?? ""
+ type = c.type ?? .http
+ target = c.target ?? ""
+ keyword = c.params?["keyword"]?.stringValue ?? ""
+ port = c.params?["port"].flatMap { $0.intValue.map(String.init) ?? $0.stringValue } ?? ""
+ recordType = c.params?["record_type"]?.stringValue.map(HC2DNSRecordType.init(rawValue:)) ?? .a
+ (intervalValue, intervalUnit) = secondsToDuration(c.intervalSeconds)
+ (retryValue, retryUnit) = secondsToDuration(c.retryIntervalSeconds)
+ retries = c.retries.map(String.init) ?? ""
+ timeout = hcFormatNumber(c.timeoutSeconds)
+ connectTimeout = hcFormatNumber(c.connectTimeoutSeconds)
+ stabilize = c.stabilize.map(String.init) ?? ""
+ invert = c.invert ?? false
+ ipMode = c.ipMode
+ notifyDown = c.notifyDown ?? true
+ notifyUp = c.notifyUp ?? true
+ notifyDegraded = c.notifyDegraded ?? false
+ critical = c.critical ?? false
+ repeatMinutes = c.repeatMinutes
+ tags = (c.tags ?? []).joined(separator: ", ")
+ group = c.group ?? ""
+ description = c.description ?? ""
+ }
+
+ /// First failing rule, `nil` when the form can be saved.
+ func validate() -> String? {
+ if name.nonBlank == nil { return String(localized: "Please enter a name.") }
+ if type != .push && target.nonBlank == nil { return String(localized: "Please enter a target.") }
+ if type == .keyword && keyword.nonBlank == nil { return String(localized: "Please enter a keyword.") }
+ if (type == .tcp || type == .port || type == .cert), port.nonBlank != nil, Int(port.hcTrimmed) == nil {
+ return String(localized: "Port must be a number.")
+ }
+ if durationToSeconds(intervalValue, unitIdx: intervalUnit) == -1 || durationToSeconds(retryValue, unitIdx: retryUnit) == -1 {
+ return String(localized: "Interval is not valid.")
+ }
+ if retries.nonBlank != nil, !(Int(retries.hcTrimmed).map { (0...10).contains($0) } ?? false) {
+ return String(localized: "Retries must be between 0 and 10.")
+ }
+ if stabilize.nonBlank != nil, !(Int(stabilize.hcTrimmed).map { (1...20).contains($0) } ?? false) {
+ return String(localized: "Stabilize must be between 1 and 20.")
+ }
+ if timeout.nonBlank != nil, !(Double(timeout.hcTrimmed).map { $0 > 0 } ?? false) {
+ return String(localized: "Timeout must be greater than 0.")
+ }
+ if connectTimeout.nonBlank != nil, !(Double(connectTimeout.hcTrimmed).map { $0 > 0 } ?? false) {
+ return String(localized: "Connect timeout must be greater than 0.")
+ }
+ return nil
+ }
+
+ /// Request. The update (PUT) is built from the loaded check: name, type and target are always sent,
+ /// the description is sent as text (nil would clear it), everything not in the form keeps its value.
+ func input() -> Node64.CheckInput {
+ var params = base?.params ?? [:]
+ switch type {
+ case .keyword: params["keyword"] = keyword.nonBlank.map { .string($0.hcTrimmed) }
+ case .tcp, .port, .cert: params["port"] = Int(port.hcTrimmed).map { .number(Double($0)) }
+ case .dns: params["record_type"] = .string(recordType.rawValue)
+ default: break
+ }
+ let seconds: (String, Int) -> Int? = { durationToSeconds($0, unitIdx: $1).flatMap { $0 >= 0 ? $0 : nil } }
+ return Node64.CheckInput(
+ name: name.hcTrimmed, type: type,
+ target: type == .push ? (editing ? "" : nil) : target.hcTrimmed,
+ params: params.isEmpty ? nil : params,
+ intervalSeconds: seconds(intervalValue, intervalUnit) ?? base?.intervalSeconds,
+ retryIntervalSeconds: seconds(retryValue, retryUnit) ?? base?.retryIntervalSeconds,
+ retries: Int(retries.hcTrimmed) ?? base?.retries,
+ connectTimeoutSeconds: Double(connectTimeout.hcTrimmed) ?? base?.connectTimeoutSeconds,
+ timeoutSeconds: Double(timeout.hcTrimmed) ?? base?.timeoutSeconds,
+ invert: invert,
+ stabilize: Int(stabilize.hcTrimmed) ?? base?.stabilize,
+ ipMode: ipMode ?? base?.ipMode,
+ tags: hcParseTags(tags),
+ description: editing ? description.hcTrimmed : description.hcTrimmed.nonBlank,
+ paused: editing ? base?.paused : createPaused,
+ parent: base?.parent,
+ critical: critical,
+ execution: base?.execution,
+ policy: base?.policy,
+ locations: base?.locations.flatMap { $0.isEmpty ? nil : $0 },
+ notifyDegraded: notifyDegraded,
+ notifyDown: notifyDown,
+ notifyUp: notifyUp,
+ channels: base?.channels.flatMap { $0.isEmpty ? nil : $0 },
+ repeatMinutes: repeatMinutes ?? base?.repeatMinutes,
+ group: editing ? group.hcTrimmed : group.hcTrimmed.nonBlank,
+ nodes: base?.nodes.flatMap { $0.isEmpty ? nil : $0 })
+ }
+}
diff --git a/IPv64/Helpers/LoadingView.swift b/IPv64/Helpers/LoadingView.swift
new file mode 100644
index 0000000..f26211b
--- /dev/null
+++ b/IPv64/Helpers/LoadingView.swift
@@ -0,0 +1,40 @@
+//
+// LoadingView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+
+import SwiftUI
+
+struct LoadingView: View {
+
+ @State var blurRadius = CGFloat(5)
+ @State var bgOpacity = CGFloat(0.9)
+ @State var spinnerColor: UIColor = .systemOrange
+ @State var message: String = "Loading..."
+
+ var body: some View {
+ VStack {
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(.gray.opacity(bgOpacity))
+ .blur(radius: blurRadius, opaque: false)
+ .overlay {
+ VStack {
+ Spinner(isAnimating: true, style: .large, color: spinnerColor)
+ Text(message)
+ .fontDesign(.rounded)
+ .font(.title3)
+ .fontWeight(.medium)
+ .padding(.top, 5)
+ }
+ }
+ }
+}
+
+#Preview {
+ WelcomeView()
+ .showLoading(.constant(true))
+}
diff --git a/IPv64/Helpers/More/MoreLogic.swift b/IPv64/Helpers/More/MoreLogic.swift
new file mode 100644
index 0000000..7c42468
--- /dev/null
+++ b/IPv64/Helpers/More/MoreLogic.swift
@@ -0,0 +1,131 @@
+import Foundation
+import CryptoKit
+import IPv64
+
+/// Pure helpers of the security screens . Callable from any isolation.
+nonisolated enum MoreLogic {
+ /// Android `countryFlag`: two ASCII letters → regional indicator pair, anything else unchanged.
+ static func countryFlag(_ code: String?) -> String? {
+ guard let code else { return nil }
+ let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
+ let scalars = Array(trimmed.unicodeScalars)
+ guard scalars.count == 2, scalars.allSatisfy({ $0.value >= 65 && $0.value <= 90 }) else { return code }
+ var flag = ""
+ for scalar in scalars {
+ flag.unicodeScalars.append(Unicode.Scalar(0x1F1E6 + scalar.value - 65)!)
+ }
+ return flag
+ }
+
+ // MARK: Password check (SHA-1 k-anonymity)
+
+ /// 40 uppercase hex characters of SHA-1(UTF-8 password).
+ static func sha1Hex(_ password: String) -> String {
+ Insecure.SHA1.hash(data: Data(password.utf8)).map { String(format: "%02X", $0) }.joined()
+ }
+
+ /// Only `prefix` (5 chars) ever leaves the device.
+ static func prefixAndSuffix(_ password: String) -> (prefix: String, suffix: String) {
+ let hash = sha1Hex(password)
+ return (String(hash.prefix(5)), String(hash.dropFirst(5)))
+ }
+
+ /// Count of the line with our suffix (case-insensitive), 0 if absent.
+ static func count(forSuffix suffix: String, in entries: [(suffix: String, count: Int)]) -> Int {
+ let wanted = suffix.uppercased()
+ return entries.first { $0.suffix.uppercased() == wanted }?.count ?? 0
+ }
+
+ // MARK: IP input
+
+ static func normalizeIpInput(_ raw: String) -> String {
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed.count > 2, trimmed.hasPrefix("["), trimmed.hasSuffix("]") {
+ return String(trimmed.dropFirst().dropLast())
+ }
+ return trimmed
+ }
+
+ static func isValidIPv4(_ text: String) -> Bool {
+ let parts = text.split(separator: ".", omittingEmptySubsequences: false)
+ guard parts.count == 4 else { return false }
+ return parts.allSatisfy { part in
+ guard (1...3).contains(part.count), part.allSatisfy({ $0.isASCII && $0.isNumber }) else { return false }
+ if part.count > 1, part.hasPrefix("0") { return false }
+ return Int(part).map { $0 <= 255 } ?? false
+ }
+ }
+
+ static func isValidIPv6(_ text: String) -> Bool {
+ guard text.contains(":"), !text.contains(":::"), !text.contains("%") else { return false }
+ let halves = text.components(separatedBy: "::")
+ guard halves.count <= 2 else { return false }
+ func groups(_ part: String) -> [String] { part.isEmpty ? [] : part.components(separatedBy: ":") }
+ let head = groups(halves[0])
+ let tail = halves.count == 2 ? groups(halves[1]) : []
+ let all = head + tail
+ var count = 0
+ for (index, group) in all.enumerated() {
+ if index == all.count - 1, group.contains(".") {
+ guard isValidIPv4(group) else { return false }
+ count += 2
+ } else {
+ guard (1...4).contains(group.count), group.allSatisfy({ $0.isHexDigit && $0.isASCII }) else { return false }
+ count += 1
+ }
+ }
+ return halves.count == 2 ? count <= 7 : count == 8
+ }
+
+ static func isValidIP(_ text: String) -> Bool { isValidIPv4(text) || isValidIPv6(text) }
+
+ // MARK: Formatting
+
+ static func prettyKey(_ key: String) -> String { key.replacingOccurrences(of: "_", with: " ") }
+
+ /// First 8 characters + "…" when longer; "–" when missing.
+ static func sensorTitle(_ id: String?) -> String {
+ guard let id, !id.isEmpty else { return "–" }
+ return id.count > 8 ? String(id.prefix(8)) + "…" : id
+ }
+
+ /// Fraction of nodes running the honeypot module (0 when no nodes).
+ static func honeypotShare(modules: [[String]]) -> (active: Int, total: Int, fraction: Double) {
+ let active = modules.filter { $0.contains { $0.lowercased() == "honeypot" } }.count
+ return (active, modules.count, modules.isEmpty ? 0 : Double(active) / Double(modules.count))
+ }
+
+ static func listURL(base: String) -> String? {
+ let trimmed = base.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ var base = trimmed
+ while base.hasSuffix("/") { base.removeLast() }
+ return base + "/ipv64_blocklist_v64.txt"
+ }
+}
+
+/// Texts of the API key list and the create sheet.
+nonisolated enum ApiKeyText {
+ static func subtitle(_ key: APIKey, current: Bool) -> String {
+ var lines: [String] = []
+ if let hint = key.tokenHint?.nonBlank { lines.append(hint) }
+ if let created = HcFormat.time(key.createdAt) { lines.append(String(localized: "Created \(created)")) }
+ if let expires = HcFormat.time(key.expiresAt) {
+ lines.append(String(localized: "Expires \(expires)"))
+ } else {
+ lines.append(String(localized: "Never expires"))
+ }
+ lines.append(String(localized: "\(key.uses ?? 0) calls"))
+ if current { lines.append(String(localized: "This app uses this key and cannot delete it.")) }
+ return lines.joined(separator: "\n")
+ }
+
+ /// Validity choices (seconds, 0 = unlimited).
+ static let validity: [(label: String, seconds: Int)] = [
+ (String(localized: "Unlimited"), 0), (String(localized: "1 day"), 86_400),
+ (String(localized: "7 days"), 7 * 86_400), (String(localized: "30 days"), 30 * 86_400),
+ (String(localized: "90 days"), 90 * 86_400), (String(localized: "1 year"), 31_536_000),
+ ]
+ static let defaultValidity = 30 * 86_400
+ static let nameLimit = 64
+}
diff --git a/IPv64/Helpers/NetworkMonitor.swift b/IPv64/Helpers/NetworkMonitor.swift
new file mode 100644
index 0000000..65d4ca7
--- /dev/null
+++ b/IPv64/Helpers/NetworkMonitor.swift
@@ -0,0 +1,37 @@
+//
+// NetworkMonitor.swift
+// IPv64
+//
+// Created by Sebastian Rank on 03.11.25.
+//
+
+import Foundation
+import Network
+import Combine
+
+@MainActor
+class NetworkMonitor: ObservableObject {
+
+ @Published private(set) var isConnected: Bool
+
+ private let networkMonitor: NWPathMonitor
+ private let workerQueue: DispatchQueue
+
+ init() {
+ self.networkMonitor = NWPathMonitor()
+ self.workerQueue = DispatchQueue(label: "Monitor")
+ self.isConnected = false
+
+ networkMonitor.pathUpdateHandler = { [weak self] path in
+ guard let self = self else { return }
+ Task { @MainActor in
+ let connected = path.status == .satisfied
+ if self.isConnected != connected { self.isConnected = connected }
+ }
+ }
+ networkMonitor.start(queue: workerQueue)
+ }
+
+ deinit { networkMonitor.cancel() }
+}
+
diff --git a/IPv64/Helpers/Nodes/ConnectedNodes.swift b/IPv64/Helpers/Nodes/ConnectedNodes.swift
new file mode 100644
index 0000000..2dffdb2
--- /dev/null
+++ b/IPv64/Helpers/Nodes/ConnectedNodes.swift
@@ -0,0 +1,113 @@
+import Foundation
+import Observation
+import IPv64
+
+/// Nodes of the active account with stored direct access (Android `ConnectedNodes`).
+/// Drives the CDN64/Proxy64 tab and the DNS64 tab. Injected with `.environment(nodes)`.
+@Observable
+final class ConnectedNodes {
+ /// Sorted node ids with stored access for the active account.
+ private(set) var ids: [String] = []
+ /// Subset whose last known status has the proxy module enabled.
+ private(set) var proxyIds: [String] = []
+ /// Subset whose last known status has DNS64 enabled.
+ private(set) var dnsIds: [String] = []
+ /// Installed Node64 version per node id from the last status call (direct connections show it in the list).
+ private(set) var versions: [String: String] = [:]
+
+ var proxyActive: Bool { !proxyIds.isEmpty }
+
+ init() { refresh() }
+
+ /// `LocalNodeStore` owner of the active account (`User.uuid`, "" when none).
+ var owner: String { User.empty.current?.uuid ?? "" }
+
+ /// Stored access of a node of the active account.
+ func access(for nodeId: String) -> LocalNodeStore.Access? { LocalNodeStore.get(nodeId, owner: owner) }
+
+ /// Node64 client for a connected node, `nil` without stored access.
+ func client(for nodeId: String) -> Node64? { access(for: nodeId).flatMap(NodeClientFactory.client(for:)) }
+
+ /// Display name: stored name, else "Node …" + last 4 chars.
+ func name(of nodeId: String) -> String { NodesLogic.nodeName(LocalNodeStore.name(nodeId), nodeId: nodeId) }
+
+ /// Stable ipv64.net account id that scopes the iCloud node sync; `nil` while sync is off or the id is
+ /// not known yet (`PushRegistrar.ensureAccountId`) — never the per-device `User.uuid`.
+ private var syncAccount: Int? {
+ guard NodeSyncStore.isEnabled, !owner.isEmpty,
+ let keyHash = PushSetupStore.keyHash(apiKey: UserStorage.shared.ApiKey) else { return nil }
+ return PushSetupStore.accountId(keyHash: keyHash)
+ }
+
+ /// Writes a saved or renamed access to the iCloud Keychain.
+ func push(_ nodeId: String) {
+ guard let account = syncAccount else { return }
+ NodeSyncStore.push(nodeId, account: account, owner: owner)
+ }
+
+ /// "Forget access": removes it here and on the user's other devices. Without a known account id yet,
+ /// the deletion waits in `pendingDeletes` for the next sync.
+ func forget(_ nodeId: String) {
+ LocalNodeStore.remove(nodeId)
+ if let account = syncAccount, NodeSyncStore.delete(nodeId, account: account) { return }
+ // Queued even if never synced here: another device may already have pushed it.
+ if let scope = pendingScope { pendingDeletes.append("\(scope)|\(nodeId)") }
+ }
+
+ /// Pending deletes are tied to the API key they were made with, so another account never applies them.
+ private var pendingScope: String? { PushSetupStore.keyHash(apiKey: UserStorage.shared.ApiKey) }
+
+ private var pendingDeletes: [String] {
+ get { UserDefaults(suiteName: AppConfig.appGroup)?.stringArray(forKey: "NODE64_SYNC_PENDING_DELETE") ?? [] }
+ set { UserDefaults(suiteName: AppConfig.appGroup)?.set(newValue, forKey: "NODE64_SYNC_PENDING_DELETE") }
+ }
+
+ /// Writes the deletion markers queued for the current account; failed ones stay queued.
+ private func flushPendingDeletes(account: Int) {
+ guard let scope = pendingScope else { return }
+ pendingDeletes = pendingDeletes.filter { item in
+ let parts = item.split(separator: "|", maxSplits: 1).map(String.init)
+ guard parts.count == 2, parts[0] == scope else { return true }
+ return !NodeSyncStore.delete(parts[1], account: account)
+ }
+ }
+ @ObservationIgnored private var lastSync: Date?
+
+ /// Two-way iCloud sync, then re-reads the store. Without `force`, at most every 30 s (every activation
+ /// calls it, also after Face ID or Control Center).
+ func syncWithCloud(force: Bool = false) {
+ guard let account = syncAccount else { return }
+ if !force, let lastSync, Date.now.timeIntervalSince(lastSync) < 30 { return }
+ lastSync = .now
+ flushPendingDeletes(account: account)
+ NodeSyncStore.sync(account: account, owner: owner)
+ refresh()
+ }
+
+ /// Re-reads the store (no network); arrays change only when their content does.
+ func refresh() {
+ let list = LocalNodeStore.list(owner: owner)
+ let proxy = list.filter(LocalNodeStore.proxyActive)
+ let dns = list.filter(LocalNodeStore.dnsActive)
+ if list != ids { ids = list }
+ if proxy != proxyIds { proxyIds = proxy }
+ if dns != dnsIds { dnsIds = dns }
+ }
+
+ /// Asks every connected node for its modules in parallel; unreachable nodes keep their last state.
+ func refreshModules() async {
+ let clients = ids.compactMap { id in client(for: id).map { (id, $0) } }
+ let found = await withTaskGroup(of: (String, String?).self) { group in
+ for (id, client) in clients {
+ group.addTask {
+ guard let status = try? await client.node.status() else { return (id, nil) }
+ if let modules = status.modules { LocalNodeStore.saveModules(id, modules: modules) }
+ return (id, status.node?.version?.nonBlank)
+ }
+ }
+ return await group.reduce(into: [String: String]()) { if let v = $1.1 { $0[$1.0] = v } }
+ }
+ versions.merge(found) { $1 }
+ refresh()
+ }
+}
diff --git a/IPv64/Helpers/Nodes/LocalNodeStore.swift b/IPv64/Helpers/Nodes/LocalNodeStore.swift
new file mode 100644
index 0000000..ccbf441
--- /dev/null
+++ b/IPv64/Helpers/Nodes/LocalNodeStore.swift
@@ -0,0 +1,104 @@
+import Foundation
+import IPv64
+
+/// Direct node access stored on this device (Android `LocalNodeStore`, prefs `NODE64_LOCAL`).
+/// Metadata (`.url/.owner/.name/.proxy/.dns/.synced`) lives in the app-group UserDefaults under the prefix
+/// `NODE64_LOCAL.`; the node API key lives in the Keychain (`NODE64_KEY.`). Owner = the account's `User.uuid`.
+nonisolated enum LocalNodeStore {
+ struct Access: Hashable, Sendable {
+ let url: String
+ let key: String
+ }
+
+ private static let prefix = "NODE64_LOCAL."
+ /// Test seam: an isolated suite replaces the app-group defaults.
+ nonisolated(unsafe) static var overrideDefaults: UserDefaults?
+ private static var defaults: UserDefaults { overrideDefaults ?? UserDefaults(suiteName: AppConfig.appGroup) ?? .standard }
+ private static func key(_ id: String, _ field: String) -> String { "\(prefix)\(id).\(field)" }
+ private static func secretAccount(_ id: String) -> String { "NODE64_KEY.\(id)" }
+
+ /// URL + key for a node of `owner`, `nil` if none is stored or it belongs to another account.
+ static func get(_ id: String, owner: String) -> Access? {
+ guard !owner.isEmpty, defaults.string(forKey: key(id, "owner")) == owner,
+ let url = defaults.string(forKey: key(id, "url")),
+ let apiKey = try? SecureStore.readString(secretAccount(id)), !apiKey.isEmpty else { return nil }
+ return Access(url: url, key: apiKey)
+ }
+
+ static func name(_ id: String) -> String? { defaults.string(forKey: key(id, "name")) }
+
+ static func setName(_ id: String, _ name: String) {
+ defaults.set(name, forKey: key(id, "name"))
+ defaults.set(true, forKey: key(id, "dirty"))
+ }
+
+ /// Account owning the stored access of `id` (one entry per node id on this device).
+ static func owner(_ id: String) -> String? { defaults.string(forKey: key(id, "owner")) }
+
+ /// Stored URL without reading the Keychain (list rows).
+ static func url(_ id: String) -> String? { defaults.string(forKey: key(id, "url")) }
+
+ /// Sorted node ids of `owner` that have a stored URL.
+ static func list(owner: String) -> [String] {
+ let all = defaults.dictionaryRepresentation().reduce(into: [String: Any]()) { result, entry in
+ if entry.key.hasPrefix(prefix) { result[String(entry.key.dropFirst(prefix.count))] = entry.value }
+ }
+ return localNodeIds(all, owner: owner)
+ }
+
+ /// Android `localNodeIds(all, owner)` on the un-prefixed key map. Pure.
+ static func localNodeIds(_ all: [String: Any], owner: String) -> [String] {
+ all.keys
+ .filter { $0.hasSuffix(".url") }
+ .map { String($0.dropLast(4)) }
+ .filter { all["\($0).owner"] as? String == owner }
+ .sorted()
+ }
+
+ /// Saves (or replaces) the access; `.name` is only written when non-nil.
+ static func save(id: String, url: String, key apiKey: String, owner: String, name: String? = nil) throws {
+ try SecureStore.write(Data(apiKey.utf8), account: secretAccount(id))
+ defaults.set(url, forKey: key(id, "url"))
+ defaults.set(owner, forKey: key(id, "owner"))
+ if let name { defaults.set(name, forKey: key(id, "name")) }
+ // Changed here: wins over the iCloud copy on the next sync (also when saved offline).
+ defaults.set(true, forKey: key(id, "dirty"))
+ }
+
+ /// Set once the access was written to or imported from the iCloud Keychain (`NodeSyncStore`).
+ static func isSynced(_ id: String) -> Bool { defaults.bool(forKey: key(id, "synced")) }
+ /// Saved or renamed here and not yet written to the iCloud Keychain.
+ static func isDirty(_ id: String) -> Bool { defaults.bool(forKey: key(id, "dirty")) }
+ static func markSynced(_ id: String) {
+ defaults.set(true, forKey: key(id, "synced"))
+ defaults.removeObject(forKey: key(id, "dirty"))
+ }
+
+ static func proxyActive(_ id: String) -> Bool { defaults.bool(forKey: key(id, "proxy")) }
+ static func dnsActive(_ id: String) -> Bool { defaults.bool(forKey: key(id, "dns")) }
+
+ /// Android `isProxyModule`.
+ static func isProxyModule(_ name: String) -> Bool { ["cdn64", "proxy64", "proxy"].contains(name.lowercased()) }
+
+ /// Persists the proxy / DNS64 module flags from `node.status().modules`; writes only on change.
+ static func saveModules(_ id: String, modules: [Node64.ModuleStatus]) {
+ let proxy = modules.contains { isProxyModule($0.name) && $0.enabled == true }
+ let dns = modules.contains { $0.name.lowercased() == "dns64" && $0.enabled == true }
+ guard proxy != proxyActive(id) || dns != dnsActive(id) else { return }
+ defaults.set(proxy, forKey: key(id, "proxy"))
+ defaults.set(dns, forKey: key(id, "dns"))
+ }
+
+ static func remove(_ id: String) {
+ for field in ["url", "owner", "name", "proxy", "dns", "synced", "dirty"] { defaults.removeObject(forKey: key(id, field)) }
+ try? SecureStore.remove(secretAccount(id))
+ }
+
+ /// Deletes every node access of an account (account removed from this app).
+ static func removeOwner(_ owner: String) {
+ for (fullKey, value) in defaults.dictionaryRepresentation()
+ where fullKey.hasPrefix(prefix) && fullKey.hasSuffix(".owner") && value as? String == owner {
+ remove(String(fullKey.dropFirst(prefix.count).dropLast(".owner".count)))
+ }
+ }
+}
diff --git a/IPv64/Helpers/Nodes/LocalNodeURL.swift b/IPv64/Helpers/Nodes/LocalNodeURL.swift
new file mode 100644
index 0000000..ef3aa5c
--- /dev/null
+++ b/IPv64/Helpers/Nodes/LocalNodeURL.swift
@@ -0,0 +1,201 @@
+import Foundation
+import Darwin
+
+/// A parsed IP address (from a literal or from `getaddrinfo`).
+nonisolated enum IPAddressBytes: Equatable, Sendable {
+ case v4([UInt8])
+ case v6([UInt8])
+}
+
+/// Android LocalNodeSupport.kt (spec 01 §5.1–5.6). Pure functions, never perform DNS.
+nonisolated enum LocalNodeURL {
+ static let defaultNodePort = 8080
+ static let localSuffixes = [".local", ".lan", ".home.arpa", ".internal", ".fritz.box", ".home", ".localdomain"]
+
+ /// Form message for an input that `normalizeLocalNodeUrl` rejects.
+ static func invalidInputMessage(_ input: String) -> String {
+ if input.trimmingCharacters(in: .whitespaces).lowercased().hasPrefix("http://") {
+ return String(localized: "Enter a valid address. HTTP works with an IP address (e.g. 192.168.1.10 or a public IP) or a local name.")
+ }
+ return String(localized: "Enter a valid address, e.g. http://192.168.1.10:8080/api")
+ }
+
+ // MARK: 5.2 – 5.5
+
+ /// `^\d{1,3}(\.\d{1,3}){3}$` (matches "999.1.1.1" too, like Android).
+ static func isIPv4Literal(_ host: String) -> Bool {
+ let parts = host.split(separator: ".", omittingEmptySubsequences: false)
+ return parts.count == 4 && parts.allSatisfy { (1...3).contains($0.count) && $0.allSatisfy(\.isASCIIDigit) }
+ }
+
+ /// Host as OkHttp reports it (IPv6 without brackets).
+ static func isIpHost(_ host: String) -> Bool { host.contains(":") || isIPv4Literal(host) }
+
+ /// Loopback, link-local, IPv4 private ranges, IPv6 ULA (fc00::/7). IPv4-mapped IPv6 is judged as IPv4.
+ static func isLocalAddress(_ address: IPAddressBytes) -> Bool {
+ switch address {
+ case .v4(let b):
+ guard b.count == 4 else { return false }
+ return b[0] == 127
+ || (b[0] == 169 && b[1] == 254)
+ || b[0] == 10
+ || (b[0] == 172 && (16...31).contains(b[1]))
+ || (b[0] == 192 && b[1] == 168)
+ case .v6(let b):
+ guard b.count == 16 else { return false }
+ if b[0..<10].allSatisfy({ $0 == 0 }) && b[10] == 0xFF && b[11] == 0xFF {
+ return isLocalAddress(.v4(Array(b[12..<16])))
+ }
+ let loopback = b[0..<15].allSatisfy { $0 == 0 } && b[15] == 1
+ let linkLocal = b[0] == 0xFE && (b[1] & 0xC0) == 0x80
+ return loopback || linkLocal || (b[0] & 0xFE) == 0xFC
+ }
+ }
+
+ /// Parses an IP literal with `inet_pton` (no DNS). Invalid octets (> 255) → nil.
+ static func parseLiteral(_ host: String) -> IPAddressBytes? {
+ var v4 = in_addr()
+ if inet_pton(AF_INET, host, &v4) == 1 {
+ return .v4(withUnsafeBytes(of: &v4) { Array($0) })
+ }
+ var v6 = in6_addr()
+ if inet_pton(AF_INET6, host, &v6) == 1 {
+ return .v6(withUnsafeBytes(of: &v6) { Array($0) })
+ }
+ return nil
+ }
+
+ static func isLocalHost(_ host: String) -> Bool {
+ var h = host.lowercased()
+ if h.hasPrefix("[") { h.removeFirst() }
+ if h.hasSuffix("]") { h.removeLast() }
+ if h.contains(":") || isIPv4Literal(h) {
+ guard let address = parseLiteral(h) else { return false }
+ return isLocalAddress(address)
+ }
+ if h.allSatisfy({ $0.isASCIIDigit || $0 == "." }) { return false }
+ var name = Substring(h)
+ while name.hasSuffix(".") { name.removeLast() }
+ return !name.contains(".") || localSuffixes.contains { name.hasSuffix($0) }
+ }
+
+ /// Drives the red "unencrypted over the internet" warning.
+ static func isPublicHttp(_ url: String) -> Bool {
+ guard let parsed = ParsedURL(url) else { return false }
+ return parsed.scheme == "http" && !isLocalHost(parsed.host)
+ }
+
+ /// Host of a stored node URL (direct node row subtitle).
+ static func host(of url: String) -> String? { ParsedURL(url)?.displayHost }
+
+ // MARK: 5.6
+
+ /// Android `normalizeLocalNodeUrl`: e.g. "192.168.1.10" → "http://192.168.1.10:8080/api",
+ /// "node.example.com" → "https://node.example.com/api". `nil` = invalid.
+ static func normalizeLocalNodeUrl(_ input: String) -> String? {
+ let raw = input.trimmingCharacters(in: .whitespacesAndNewlines)
+ if raw.isEmpty { return nil }
+ let hasScheme = raw.contains("://")
+ guard var url = ParsedURL(hasScheme ? raw : "http://" + raw) else { return nil }
+ let local = isLocalHost(url.host)
+ let ip = isIpHost(url.host)
+ if !hasScheme {
+ let beforePath = raw.split(separator: "/", maxSplits: 1, omittingEmptySubsequences: false).first ?? ""
+ let afterBracket = beforePath.split(separator: "]", omittingEmptySubsequences: false).last ?? ""
+ let explicitPort = afterBracket.contains(":")
+ if local || ip {
+ if !explicitPort { url.port = defaultNodePort }
+ } else {
+ url.scheme = "https"
+ }
+ }
+ let numeric = url.host.allSatisfy { $0.isASCIIDigit || $0 == "." }
+ if url.scheme == "http" && numeric && !isIpHost(url.host) { return nil }
+ var path = Substring(url.path)
+ while path.hasSuffix("/") { path.removeLast() }
+ url.path = path.isEmpty ? "/api" : String(path)
+ return url.string
+ }
+}
+
+/// Minimal URL parser with OkHttp `toHttpUrlOrNull` semantics (scheme http/https, userinfo dropped,
+/// lowercase host, canonical IPv6, default port dropped, query/fragment dropped).
+nonisolated struct ParsedURL: Equatable, Sendable {
+ var scheme: String
+ /// Lowercase; IPv6 without brackets, canonical (`fd00::1`).
+ var host: String
+ /// `nil` = default port of the scheme.
+ var port: Int?
+ /// Encoded path, starts with "/" or is empty.
+ var path: String
+
+ init?(_ string: String) {
+ guard let schemeEnd = string.range(of: "://") else { return nil }
+ let scheme = string[..\"{}`")
+ guard !host.isEmpty, host.unicodeScalars.allSatisfy({ $0.isASCII && $0.value > 0x20 && $0.value < 0x7F }),
+ !host.contains(where: invalid.contains) else { return nil }
+ }
+ let defaultPort = scheme == "https" ? 443 : 80
+ var port: Int?
+ if let portText {
+ guard let value = Int(portText), portText.allSatisfy(\.isASCIIDigit), (1...65535).contains(value) else { return nil }
+ port = value == defaultPort ? nil : value
+ }
+ var path = rawPath
+ if !path.contains("%") {
+ path = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? path
+ }
+ self.scheme = scheme
+ self.host = host
+ self.port = port
+ self.path = path
+ }
+
+ var displayHost: String { host.contains(":") ? "[\(host)]" : host }
+
+ var string: String {
+ let defaultPort = scheme == "https" ? 443 : 80
+ let portPart = port.map { $0 == defaultPort ? "" : ":\($0)" } ?? ""
+ return "\(scheme)://\(displayHost)\(portPart)\(path)"
+ }
+
+ private static func canonicalIPv6(_ literal: String) -> String? {
+ var address = in6_addr()
+ guard inet_pton(AF_INET6, literal, &address) == 1 else { return nil }
+ var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
+ guard inet_ntop(AF_INET6, &address, &buffer, socklen_t(buffer.count)) != nil else { return nil }
+ return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)
+ }
+}
+
+private extension Character {
+ nonisolated var isASCIIDigit: Bool { isASCII && isNumber }
+}
diff --git a/IPv64/Helpers/Nodes/NodeErrorText.swift b/IPv64/Helpers/Nodes/NodeErrorText.swift
new file mode 100644
index 0000000..c29c3b5
--- /dev/null
+++ b/IPv64/Helpers/Nodes/NodeErrorText.swift
@@ -0,0 +1,68 @@
+import Foundation
+import IPv64
+
+nonisolated extension ErrorText {
+ /// Android `localNodeError(e)`: title + text for errors of direct node access.
+ static func node(_ error: any Error) -> ErrorText {
+ if let error = error as? Node64Error {
+ switch error {
+ case .httpStatus(401, let body) where String(decoding: body, as: UTF8.self).contains("/.node64/login"):
+ return ErrorText(
+ title: String(localized: "Address is sign-in protected"),
+ message: String(localized: "PROXY64 asks for a sign-in on this address, so the API key never reaches the node. Use the node's local IP, or give the path /api its own open access list in the PROXY64 host (the node's API key still protects it)."))
+ case .api(let e):
+ return nodeStatusError(status: e.status, nodeError: e.error)
+ case .httpStatus(let code, _):
+ return nodeStatusError(status: code, nodeError: nil)
+ case .decoding:
+ return ErrorText(
+ title: String(localized: "Unexpected response"),
+ message: String(localized: "The address answered, but not like a Node64 API. Check the URL (it usually ends in /api)."))
+ default:
+ break
+ }
+ }
+ if error is NodeTransportError {
+ return ErrorText(
+ title: String(localized: "Not a local address"),
+ message: String(localized: "Over http:// a name must resolve to an address in your local network. Use the node's IP address or its https:// address."))
+ }
+ if let urlError = error as? URLError {
+ switch urlError.code {
+ case .appTransportSecurityRequiresSecureConnection:
+ return ErrorText(
+ title: String(localized: "Unencrypted connection blocked"),
+ message: String(localized: "HTTP is only allowed for IP addresses and local names (e.g. nas.local). Use https:// for a domain."))
+ case .serverCertificateUntrusted, .secureConnectionFailed, .serverCertificateHasBadDate,
+ .serverCertificateHasUnknownRoot, .serverCertificateNotYetValid, .clientCertificateRejected:
+ return ErrorText(
+ title: String(localized: "Certificate not trusted"),
+ message: String(localized: "The node's HTTPS certificate is not trusted by this device. Use the node's local http:// address or a valid certificate."))
+ default:
+ break
+ }
+ }
+ return ErrorText(
+ title: String(localized: "Node not reachable"),
+ message: String(localized: "Could not reach the node. Is your phone on the same network as the node?"))
+ }
+
+ private static func nodeStatusError(status: Int, nodeError: String?) -> ErrorText {
+ switch status {
+ case 401, 403:
+ var lines = [String(localized: "The node rejected the API key (HTTP \(status)).")]
+ if let nodeError { lines.append(String(localized: "Node: \(nodeError)")) }
+ lines.append(String(localized: "Create a key in the node's web interface on the API tab."))
+ return ErrorText(title: String(localized: "API key rejected"), message: lines.joined(separator: "\n"))
+ case 404:
+ return ErrorText(title: String(localized: "Not a Node64 API"),
+ message: String(localized: "Not a Node64 API — does the URL end in /api?"))
+ default:
+ return ErrorText(title: String(localized: "Node error"),
+ message: nodeError ?? String(localized: "The node answered with HTTP \(status)."))
+ }
+ }
+
+ /// Android `": "` inline form used by the node sheets.
+ var titledText: String { "\(title): \(message)" }
+}
diff --git a/IPv64/Helpers/Nodes/NodeSyncPlan.swift b/IPv64/Helpers/Nodes/NodeSyncPlan.swift
new file mode 100644
index 0000000..dcccb78
--- /dev/null
+++ b/IPv64/Helpers/Nodes/NodeSyncPlan.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+/// Pure merge rules of the iCloud node sync (`NodeSyncStore`), kept free of storage so they can be checked alone.
+nonisolated enum NodeSyncPlan {
+ struct Entry: Codable, Equatable, Sendable {
+ var url: String
+ var key: String
+ var name: String?
+ var updatedAt: Date
+ /// Deletion marker ("Forget access" on one device): removes the access on the others.
+ var deleted: Bool?
+ }
+
+ /// Pure merge. Local changes (`dirty`) and access missing in iCloud are pushed; iCloud access that is
+ /// missing or different here is imported (skipping ids stored for another account on this device);
+ /// local access with a deletion marker is removed unless it was changed here since.
+ static func plan(local: [String: Entry], synced: [String: Entry], dirty: Set, otherOwner: Set)
+ -> (push: [String], upsert: [String: Entry], remove: [String], inSync: [String]) {
+ let push = local.keys.filter { dirty.contains($0) || synced[$0] == nil }.sorted()
+ let remove = local.keys.filter { !dirty.contains($0) && synced[$0]?.deleted == true }.sorted()
+ let upsert = synced.filter { id, entry in
+ guard entry.deleted != true, !dirty.contains(id), !otherOwner.contains(id) else { return false }
+ guard let mine = local[id] else { return true }
+ return mine.url != entry.url || mine.key != entry.key || (entry.name != nil && mine.name != entry.name)
+ }
+ let inSync = local.keys.filter { !push.contains($0) && !remove.contains($0) && upsert[$0] == nil }.sorted()
+ return (push, upsert, remove, inSync)
+ }
+}
diff --git a/IPv64/Helpers/Nodes/NodeSyncStore.swift b/IPv64/Helpers/Nodes/NodeSyncStore.swift
new file mode 100644
index 0000000..9db9ee3
--- /dev/null
+++ b/IPv64/Helpers/Nodes/NodeSyncStore.swift
@@ -0,0 +1,101 @@
+import Foundation
+import Security
+
+/// Direct node access synced across the user's devices through the iCloud Keychain.
+/// One synchronizable generic password per node (service `net.ipv64.nodesync`, account `.`,
+/// value JSON `Entry`), scoped by the stable ipv64.net account id. `LocalNodeStore` stays the source the app reads.
+nonisolated enum NodeSyncStore {
+ typealias Entry = NodeSyncPlan.Entry
+
+ /// App-group defaults key of the "Sync with iCloud" setting (default on).
+ static let enabledKey = "NODE64_SYNC_ICLOUD"
+ static var isEnabled: Bool {
+ UserDefaults(suiteName: AppConfig.appGroup)?.object(forKey: enabledKey) as? Bool ?? true
+ }
+
+ private static func query() throws -> [String: Any] {
+ try [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: "net.ipv64.nodesync",
+ kSecAttrAccessGroup as String: SecureStore.accessGroup()]
+ }
+
+ /// Writes the stored access of `id` to the iCloud Keychain and marks it as synced.
+ static func push(_ id: String, account: Int, owner: String) {
+ guard let access = LocalNodeStore.get(id, owner: owner), !isDebugMock(access.key) else { return }
+ let entry = Entry(url: access.url, key: access.key, name: LocalNodeStore.name(id), updatedAt: .now)
+ if write(entry, id: id, account: account) { LocalNodeStore.markSynced(id) }
+ }
+
+ /// "Forget access": replaces the synced access of `id` with a deletion marker, so it is removed on all
+ /// devices but a keychain that is merely missing items (iCloud Keychain reset) never removes anything.
+ @discardableResult
+ static func delete(_ id: String, account: Int) -> Bool {
+ write(Entry(url: "", key: "", name: nil, updatedAt: .now, deleted: true), id: id, account: account)
+ }
+
+ private static func write(_ entry: Entry, id: String, account: Int) -> Bool {
+ guard let data = try? JSONEncoder().encode(entry), var request = try? query() else { return false }
+ request[kSecAttrAccount as String] = "\(account).\(id)"
+ request[kSecAttrSynchronizable as String] = true
+ // Synced items cannot be ThisDeviceOnly.
+ let attributes: [String: Any] = [kSecValueData as String: data,
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock]
+ var status = SecItemUpdate(request as CFDictionary, attributes as CFDictionary)
+ if status == errSecItemNotFound {
+ status = SecItemAdd(request.merging(attributes) { _, new in new } as CFDictionary, nil)
+ }
+ return status == errSecSuccess
+ }
+
+ /// Synced entries of `account` by node id; `nil` when the Keychain cannot be read (then nothing may be removed).
+ static func entries(account: Int) -> [String: Entry]? {
+ guard var request = try? query() else { return nil }
+ request[kSecAttrSynchronizable as String] = kSecAttrSynchronizableAny
+ request[kSecReturnAttributes as String] = true
+ request[kSecReturnData as String] = true
+ request[kSecMatchLimit as String] = kSecMatchLimitAll
+ var result: CFTypeRef?
+ let status = SecItemCopyMatching(request as CFDictionary, &result)
+ if status == errSecItemNotFound { return [:] }
+ guard status == errSecSuccess, let items = result as? [[String: Any]] else { return nil }
+ let prefix = "\(account)."
+ return items.reduce(into: [:]) { entries, item in
+ guard let name = item[kSecAttrAccount as String] as? String, name.hasPrefix(prefix),
+ let data = item[kSecValueData as String] as? Data,
+ let entry = try? JSONDecoder().decode(Entry.self, from: data),
+ entry.deleted == true || (!entry.url.isEmpty && NodesLogic.isValidApiKey(entry.key)) else { return }
+ entries[String(name.dropFirst(prefix.count))] = entry
+ }
+ }
+
+ /// Two-way sync of `account`: uploads access changed here or missing in iCloud, imports access from
+ /// other devices and removes access forgotten on another device.
+ static func sync(account: Int, owner: String) {
+ guard let synced = entries(account: account) else { return }
+ let ids = LocalNodeStore.list(owner: owner)
+ let local = ids.reduce(into: [String: Entry]()) { local, id in
+ guard let access = LocalNodeStore.get(id, owner: owner) else { return }
+ local[id] = Entry(url: access.url, key: access.key, name: LocalNodeStore.name(id), updatedAt: .distantPast)
+ }
+ let otherOwner = Set(synced.keys.filter { id in LocalNodeStore.owner(id).map { $0 != owner } ?? false })
+ let changes = NodeSyncPlan.plan(local: local, synced: synced, dirty: Set(ids.filter(LocalNodeStore.isDirty)),
+ otherOwner: otherOwner)
+ changes.push.forEach { push($0, account: account, owner: owner) }
+ for (id, entry) in changes.upsert {
+ guard (try? LocalNodeStore.save(id: id, url: entry.url, key: entry.key, owner: owner, name: entry.name)) != nil else { continue }
+ LocalNodeStore.markSynced(id)
+ }
+ changes.remove.forEach(LocalNodeStore.remove)
+ changes.inSync.forEach(LocalNodeStore.markSynced)
+ }
+
+
+ /// DEBUG mock nodes (`DebugFixtures`, key "node64_mock") never leave the device.
+ private static func isDebugMock(_ key: String) -> Bool {
+ #if DEBUG
+ return key == "node64_mock"
+ #else
+ return false
+ #endif
+ }
+}
diff --git a/IPv64/Helpers/Nodes/NodeTransport.swift b/IPv64/Helpers/Nodes/NodeTransport.swift
new file mode 100644
index 0000000..abff902
--- /dev/null
+++ b/IPv64/Helpers/Nodes/NodeTransport.swift
@@ -0,0 +1,124 @@
+import Foundation
+import Darwin
+import IPv64
+
+/// Thrown when an `http://` node name does not resolve to local addresses only (→ "Not a local address").
+nonisolated struct NodeTransportError: Error, Sendable {
+ let host: String
+}
+
+/// Hardened transport for direct node access (Android `localBaseClient`/`localHttpClient`, spec 01 §5.9):
+/// no redirects; for `http://` no proxy, and a host name must resolve (getaddrinfo) to local addresses only,
+/// then the request goes to that IP literal with the original `Host` header (prevents DNS rebinding).
+/// Timeouts: 15 s per request (set by `Node64.Configuration.timeoutInterval`), 5 s idle on the session.
+/// shortcut: URLSession has no separate connect timeout; the 5 s idle timeout is the closest equivalent.
+nonisolated final class NodeTransport: IPv64Transport {
+ private let session: URLSession
+
+ init(plainHTTP: Bool) {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 5
+ configuration.timeoutIntervalForResource = 60
+ configuration.waitsForConnectivity = false
+ configuration.urlCache = nil
+ configuration.httpCookieStorage = nil
+ if plainHTTP {
+ configuration.connectionProxyDictionary = [kCFNetworkProxiesHTTPEnable as String: false]
+ }
+ session = URLSession(configuration: configuration, delegate: NoRedirectDelegate(), delegateQueue: nil)
+ }
+
+ deinit { session.finishTasksAndInvalidate() }
+
+ @concurrent
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ if let url = request.url, url.scheme?.lowercased() == "http",
+ let host = url.host(percentEncoded: false), !LocalNodeURL.isIpHost(host) {
+ let addresses = try Self.resolve(host)
+ guard !addresses.isEmpty, addresses.allSatisfy(LocalNodeURL.isLocalAddress) else {
+ throw NodeTransportError(host: host)
+ }
+ // Like OkHttp: try every resolved address until one accepts the connection.
+ var lastError: any Error = NodeTransportError(host: host)
+ for address in addresses {
+ var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
+ components?.host = Self.literal(address)
+ guard let pinned = components?.url else { continue }
+ var pinnedRequest = request
+ pinnedRequest.url = pinned
+ pinnedRequest.setValue(url.port.map { "\(host):\($0)" } ?? host, forHTTPHeaderField: "Host")
+ do {
+ return try await perform(pinnedRequest)
+ } catch let error as URLError where error.code == .cannotConnectToHost || error.code == .timedOut {
+ lastError = error
+ }
+ }
+ throw lastError
+ }
+ return try await perform(request)
+ }
+
+ private func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ let (data, response) = try await session.data(for: request)
+ guard let http = response as? HTTPURLResponse else { throw IPv64Error.invalidResponse }
+ return (data, http)
+ }
+
+ /// Blocking system lookup; only called from the concurrent `send`.
+ private static func resolve(_ host: String) throws -> [IPAddressBytes] {
+ var hints = addrinfo()
+ hints.ai_family = AF_UNSPEC
+ hints.ai_socktype = SOCK_STREAM
+ var result: UnsafeMutablePointer?
+ guard getaddrinfo(host, nil, &hints, &result) == 0, let head = result else { throw URLError(.cannotFindHost) }
+ defer { freeaddrinfo(head) }
+ var addresses: [IPAddressBytes] = []
+ for info in sequence(first: head, next: { $0.pointee.ai_next }) {
+ guard let sa = info.pointee.ai_addr else { continue }
+ switch Int32(sa.pointee.sa_family) {
+ case AF_INET:
+ var addr = sa.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr }
+ addresses.append(.v4(withUnsafeBytes(of: &addr) { Array($0) }))
+ case AF_INET6:
+ var addr = sa.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { $0.pointee.sin6_addr }
+ addresses.append(.v6(withUnsafeBytes(of: &addr) { Array($0) }))
+ default:
+ continue
+ }
+ }
+ return addresses
+ }
+
+ private static func literal(_ address: IPAddressBytes) -> String {
+ switch address {
+ case .v4(let b):
+ return b.map(String.init).joined(separator: ".")
+ case .v6(var b):
+ var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
+ _ = inet_ntop(AF_INET6, &b, &buffer, socklen_t(buffer.count))
+ return "[" + String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) + "]"
+ }
+ }
+}
+
+/// Refuses every redirect (Android `followRedirects = false`); the 3xx answer is returned as is.
+private nonisolated final class NoRedirectDelegate: NSObject, URLSessionTaskDelegate, Sendable {
+ // The async variant of this delegate method crashes the Swift 6.4 compiler (ObjC thunk); keep the handler form.
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
+ completionHandler(nil)
+ }
+}
+
+/// Android `localNodeClient(url, key)`: one cheap Node64 client per call, agent actor "IPv64 iOS".
+nonisolated enum NodeClientFactory {
+ static func client(url: String, key: String) -> Node64? {
+ guard let baseURL = URL(string: url) else { return nil }
+ let plainHTTP = baseURL.scheme?.lowercased() == "http"
+ return Node64(
+ configuration: .init(baseURL: baseURL, apiKey: key, agentActor: AppConfig.nodeAgentActor, timeoutInterval: 15),
+ transport: NodeTransport(plainHTTP: plainHTTP))
+ }
+
+ static func client(for access: LocalNodeStore.Access) -> Node64? { client(url: access.url, key: access.key) }
+}
diff --git a/IPv64/Helpers/Nodes/NodesLogic.swift b/IPv64/Helpers/Nodes/NodesLogic.swift
new file mode 100644
index 0000000..30db341
--- /dev/null
+++ b/IPv64/Helpers/Nodes/NodesLogic.swift
@@ -0,0 +1,250 @@
+import Foundation
+import IPv64
+
+/// Pure logic of the node screens (Android NodeSupport.kt, NodeLocalView.kt).
+nonisolated enum NodesLogic {
+ /// Stored / cloud name, else "Node …" + last 4 characters of the id.
+ static func nodeName(_ name: String?, nodeId: String) -> String {
+ name?.nonBlank ?? "Node …" + String(nodeId.suffix(4))
+ }
+
+ /// Remote management label (`off`/`read`/`full`/nil).
+ static func remoteLabel(_ remote: String?) -> String {
+ switch remote {
+ case "off": String(localized: "Off")
+ case "read": String(localized: "Read only")
+ case "full": String(localized: "Full")
+ default: String(localized: "Unknown")
+ }
+ }
+
+ /// Cloud row meta line: location, "v"+version, "seen …" joined " · ", `nil` when all are missing.
+ static func cloudMeta(location: String?, version: String?, lastSeen: Date?) -> String? {
+ let parts = [
+ location?.nonBlank,
+ version?.nonBlank.map { "v" + $0 },
+ lastSeen.map { String(localized: "seen \($0.formatted(.relative(presentation: .named)))") },
+ ].compactMap { $0 }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ /// "Remote: Full" plus " · N conflict(s)".
+ static func remoteLine(_ remote: String?, conflicts: Int?) -> String {
+ var line = String(localized: "Remote: \(remoteLabel(remote))")
+ let count = conflicts ?? 0
+ if count > 0 {
+ line += " · " + (count == 1 ? String(localized: "1 conflict") : String(localized: "\(count) conflicts"))
+ }
+ return line
+ }
+
+ /// Direct node row subtitle: host of the stored URL, else the URL.
+ static func directSubtitle(url: String?) -> String {
+ guard let url else { return "" }
+ return LocalNodeURL.host(of: url) ?? url
+ }
+
+ /// Android: every character of the key must be printable ASCII (`!`…`~`).
+ static func isValidApiKey(_ key: String) -> Bool {
+ key.unicodeScalars.allSatisfy { (0x21...0x7E).contains($0.value) }
+ }
+
+ /// Live warning under the form: none, orange (http on the local network) or red (http over the internet).
+ enum InsecureWarning: Equatable, Sendable { case none, local, internet }
+
+ static func insecureWarning(for address: String) -> InsecureWarning {
+ guard let url = LocalNodeURL.normalizeLocalNodeUrl(address), url.hasPrefix("http://") else { return .none }
+ return LocalNodeURL.isPublicHttp(url) ? .internet : .local
+ }
+
+ static func remoteDescription(_ remote: String) -> String {
+ switch remote {
+ case "off": String(localized: "Remote management is off.")
+ case "read": String(localized: "Read access, the node does not accept commands.")
+ default: String(localized: "Commands from ipv64.net (run check, repair, pause, resume) are accepted.")
+ }
+ }
+
+ // MARK: Link code
+
+ /// Letters/digits, uppercased, max 8 (raw value of the "Code" field).
+ static func rawLinkCode(_ input: String) -> String {
+ String(input.filter { $0.isASCII && ($0.isLetter || $0.isNumber) }.uppercased().prefix(8))
+ }
+
+ /// "ABCD-EFGH" display mask of a raw code.
+ static func maskedLinkCode(_ raw: String) -> String {
+ raw.count > 4 ? raw.prefix(4) + "-" + raw.dropFirst(4) : raw
+ }
+
+ // MARK: Live state
+
+ enum LiveState: Equatable, Sendable {
+ case connecting, paused, offline, live
+
+ static func from(lastOk: Date?, active: Bool, failing: Bool) -> LiveState {
+ if lastOk == nil { return .connecting }
+ if !active { return .paused }
+ return failing ? .offline : .live
+ }
+ }
+
+ /// "Updated just now" / "Updated 12 s ago".
+ static func updatedText(since lastOk: Date, now: Date = .now) -> String {
+ let seconds = Int(now.timeIntervalSince(lastOk))
+ return seconds < 2 ? String(localized: "Updated just now")
+ : String(localized: "Updated \(HcFormat.duration(seconds: seconds)) ago")
+ }
+
+ /// HTTP 401/403 of the node (shown as the "rejected" line in the header).
+ static func isAuthRejection(_ error: any Error) -> Bool {
+ guard let error = error as? Node64Error else { return false }
+ return error.statusCode == 401 || error.statusCode == 403
+ }
+
+ // MARK: Logs
+
+ /// One parsed logfmt line; missing fields are `nil`.
+ struct LogEntry: Equatable, Sendable {
+ var time: String?
+ var level: String?
+ var module: String?
+ var msg: String?
+ }
+
+ /// logfmt (`time=… level=INFO msg="a b"`): quoted values with `\"`, `\\`, `\n`, `\t`, `\r`; the first duplicate
+ /// key wins; `nil` = not logfmt (a word without "=", or neither `level` nor `msg`).
+ static func parseLogLine(_ line: String) -> LogEntry? {
+ let chars = Array(line)
+ var fields: [String: String] = [:]
+ var i = 0
+ let n = chars.count
+ while i < n {
+ while i < n && chars[i].isWhitespace { i += 1 }
+ if i >= n { break }
+ let keyStart = i
+ while i < n && chars[i] != "=" && !chars[i].isWhitespace { i += 1 }
+ guard i < n, chars[i] == "=", i != keyStart else { return nil }
+ let key = String(chars[keyStart.. String? {
+ guard let iso = iso?.trimmingCharacters(in: .whitespaces), !iso.isEmpty else { return nil }
+ let date = (try? Date(iso, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)))
+ ?? (try? Date(iso, strategy: Date.ISO8601FormatStyle()))
+ return date.map { $0.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits).second(.twoDigits)) }
+ }
+
+ /// One log element → text: string → itself; object with `msg` → logfmt of the present keys; else JSON.
+ static func logText(_ element: JSONValue) -> String {
+ if case .string(let s) = element { return s }
+ if case .object(let object) = element, object["msg"] != nil {
+ return ["time", "level", "module", "msg"].compactMap { key in
+ object[key].map { "\(key)=\"\(escapeLogfmt(jsonString($0)))\"" }
+ }.joined(separator: " ")
+ }
+ return jsonString(element)
+ }
+
+ static func jsonString(_ value: JSONValue) -> String {
+ switch value {
+ case .string(let s): return s
+ case .null: return "null"
+ case .bool(let b): return b ? "true" : "false"
+ case .number(let d): return d == d.rounded() && abs(d) < 1e15 ? String(Int(d)) : String(d)
+ default:
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
+ return (try? encoder.encode(value)).flatMap { String(data: $0, encoding: .utf8) } ?? ""
+ }
+ }
+
+ private static func escapeLogfmt(_ s: String) -> String {
+ s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
+ .replacingOccurrences(of: "\n", with: "\\n")
+ }
+
+ // MARK: Commands
+
+ static func commandLabel(_ name: String?) -> String {
+ switch name {
+ case "run_check": String(localized: "Run check")
+ case "repair": String(localized: "Repair")
+ case "pause": String(localized: "Pause check")
+ case "resume": String(localized: "Resume check")
+ case "resolve_conflict": String(localized: "Resolve conflict")
+ case let other?: other
+ case nil: String(localized: "Command")
+ }
+ }
+
+ /// Command history args text: check name / "Conflict #id" / "keep side".
+ static func commandArgsText(_ args: JSONValue?, checkName: (String) -> String) -> String? {
+ guard case .object(let object)? = args else { return nil }
+ var parts: [String] = []
+ if let token = object["token"].map(jsonString) { parts.append(checkName(token)) }
+ if let id = object["id"].map(jsonString) { parts.append("Conflict #\(id)") }
+ if let keep = object["keep"].map(jsonString) { parts.append("keep \(keep)") }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ /// Unlink result: "N checks continued as online checks, N checks deleted. The node keeps running standalone."
+ static func unlinkSummary(kept: Int, deleted: Int) -> String {
+ var parts: [String] = []
+ if kept > 0 {
+ parts.append(kept == 1 ? String(localized: "1 check continued as online check")
+ : String(localized: "\(kept) checks continued as online checks"))
+ }
+ if deleted > 0 {
+ parts.append(deleted == 1 ? String(localized: "1 check deleted") : String(localized: "\(deleted) checks deleted"))
+ }
+ let counts = parts.joined(separator: ", ")
+ return counts.isEmpty ? String(localized: "The node keeps running standalone.")
+ : String(localized: "\(counts). The node keeps running standalone.")
+ }
+
+ // MARK: Module screens
+
+ /// ISO-3166 alpha-2 → flag emoji, `nil` if not two letters.
+ static func countryFlag(_ code: String?) -> String? {
+ guard let code = code?.uppercased(), code.count == 2, code.allSatisfy({ $0.isASCII && $0.isLetter }) else { return nil }
+ return String(String.UnicodeScalarView(code.unicodeScalars.compactMap { Unicode.Scalar(127_397 + $0.value) }))
+ }
+
+ /// DNS64 blocked share: below 10 one decimal, else whole percent; "–" without queries.
+ static func blockedPercent(total: Int, blocked: Int) -> String {
+ guard total > 0 else { return "–" }
+ let p = Double(blocked) * 100 / Double(total)
+ return p < 10 ? p.formatted(.number.precision(.fractionLength(1))) + " %" : "\(Int(p)) %"
+ }
+}
diff --git a/IPv64/Helpers/Proxy/ProxyHostForm.swift b/IPv64/Helpers/Proxy/ProxyHostForm.swift
new file mode 100644
index 0000000..1d494b8
--- /dev/null
+++ b/IPv64/Helpers/Proxy/ProxyHostForm.swift
@@ -0,0 +1,120 @@
+import Foundation
+import IPv64
+
+/// Editable state of the proxy host editor.
+struct ProxyHostForm: Equatable {
+ var kind: Node64.ProxyHostKind = .proxy
+ var names = ""
+ var enabled = true
+ var scheme: Node64.ProxyHostScheme = .http
+ var host = ""
+ var port = "80"
+ var websockets = false
+ var blockExploits = false
+ var cacheAssets = false
+ var forceSSL = false
+ var http2 = false
+ var http3 = false
+ var hsts = false
+ var hstsSubdomains = false
+ var verifyTarget = false
+ var minTLS: Node64.ProxyHostMinTLS?
+ var accessListID = 0
+ var certID = 0
+ var redirectTarget = ""
+ var redirectScheme: Node64.ProxyHostRedirectScheme = .auto
+ var redirectCode = 301
+ var preservePath = true
+ var statusPageID = ""
+
+ static let redirectCodes = [300, 301, 302, 303, 307, 308]
+
+ init() {}
+
+ init(host h: Node64.ProxyHost) {
+ kind = h.kind ?? .proxy
+ names = (h.names ?? []).joined(separator: "\n")
+ enabled = h.enabled != false
+ scheme = h.scheme ?? .http
+ host = h.targetHost ?? ""
+ port = h.targetPort.map(String.init) ?? ""
+ websockets = h.websockets == true
+ blockExploits = h.blockExploits == true
+ cacheAssets = h.cacheAssets == true
+ forceSSL = h.forceSSL == true
+ http2 = h.http2 == true
+ http3 = h.http3 == true
+ hsts = h.hsts == true
+ hstsSubdomains = h.hstsSubdomains == true
+ verifyTarget = h.verifyTarget == true
+ minTLS = h.minTLS
+ accessListID = h.accessListID ?? 0
+ certID = h.certID ?? 0
+ redirectTarget = h.redirectTarget ?? ""
+ redirectScheme = h.redirectScheme ?? .auto
+ redirectCode = h.redirectCode ?? 301
+ preservePath = h.preservePath != false
+ statusPageID = (h.statusPageID ?? 0) > 0 ? String(h.statusPageID ?? 0) : ""
+ }
+
+ var isProxy: Bool { kind == .proxy }
+ var isRedirect: Bool { kind == .redirect }
+ var isPassthrough: Bool { kind == .passthrough }
+ var isStatus: Bool { kind == .status }
+ /// Host and port of the target: proxy and TLS passthrough.
+ var hasTarget: Bool { isProxy || isPassthrough }
+ /// Options and advanced settings: proxy and redirect. Kinds `dead` and `stream` have no target and only edit names.
+ var editable: Bool { isProxy || isRedirect }
+ var pageID: Int? { Int(statusPageID.trimmingCharacters(in: .whitespaces)).flatMap { $0 > 0 ? $0 : nil } }
+ var firstName: String { ProxyLogic.parseNames(names).first ?? "" }
+
+ /// Validation message per section.
+ struct Errors: Equatable {
+ var names: String?
+ var target: String?
+ var redirect: String?
+ /// First message in screen order (shown in the alert).
+ var first: String? { names ?? target ?? redirect }
+ }
+
+ var errors: Errors {
+ var e = Errors()
+ if ProxyLogic.parseNames(names).isEmpty { e.names = String(localized: "Enter at least one domain name.") }
+ if isStatus, pageID == nil { e.target = String(localized: "Enter the status page ID (greater than 0).") }
+ if hasTarget {
+ if host.trimmingCharacters(in: .whitespaces).isEmpty {
+ e.target = String(localized: "Enter the target host.")
+ } else if ProxyLogic.parsePort(port) == nil {
+ e.target = String(localized: "The port must be between 1 and 65535.")
+ }
+ }
+ if isRedirect, redirectTarget.trimmingCharacters(in: .whitespaces).isEmpty {
+ e.redirect = String(localized: "Enter the redirect target.")
+ }
+ return e
+ }
+
+ /// `nil` fields are not sent; `enabled`/`kind` only on create.
+ func input(create: Bool) -> Node64.ProxyHostInput {
+ let nameList = ProxyLogic.parseNames(names)
+ if isPassthrough {
+ return Node64.ProxyHostInput(kind: create ? kind : nil, names: nameList, enabled: create ? enabled : nil,
+ targetHost: host.trimmingCharacters(in: .whitespaces), targetPort: ProxyLogic.parsePort(port))
+ }
+ if isStatus {
+ return Node64.ProxyHostInput(kind: create ? kind : nil, names: nameList, enabled: create ? enabled : nil, statusPageID: pageID)
+ }
+ guard editable else { return Node64.ProxyHostInput(names: nameList) }
+ return Node64.ProxyHostInput(
+ kind: create ? kind : nil, names: nameList, enabled: create ? enabled : nil,
+ scheme: isProxy ? scheme : nil, targetHost: isProxy ? host.trimmingCharacters(in: .whitespaces) : nil,
+ targetPort: isProxy ? ProxyLogic.parsePort(port) : nil,
+ websockets: isProxy ? websockets : nil, blockExploits: isProxy ? blockExploits : nil,
+ cacheAssets: isProxy ? cacheAssets : nil, certID: certID, forceSSL: forceSSL,
+ http2: http2, http3: http3, hsts: hsts, hstsSubdomains: hstsSubdomains, minTLS: minTLS,
+ verifyTarget: isProxy ? verifyTarget : nil,
+ redirectTarget: isRedirect ? redirectTarget.trimmingCharacters(in: .whitespaces) : nil,
+ redirectScheme: isRedirect ? redirectScheme : nil, redirectCode: isRedirect ? redirectCode : nil,
+ preservePath: isRedirect ? preservePath : nil, accessListID: accessListID)
+ }
+}
diff --git a/IPv64/Helpers/Proxy/ProxyLogic.swift b/IPv64/Helpers/Proxy/ProxyLogic.swift
new file mode 100644
index 0000000..ab8e27f
--- /dev/null
+++ b/IPv64/Helpers/Proxy/ProxyLogic.swift
@@ -0,0 +1,126 @@
+import Foundation
+
+/// Pure texts of the Proxy64 screens (Android ProxyHostRow / CDN64 stats).
+nonisolated enum ProxyLogic {
+ enum Tone { case gray, green, orange, red }
+ struct Tag: Equatable { var text: String; var tone: Tone }
+
+ /// Limit 0 or missing = unlimited (`nil`).
+ static func limit(_ value: T?) -> T? { value.flatMap { $0 > 0 ? $0 : nil } }
+
+ static func modeShort(_ mode: Int?) -> String { mode.map { "Mode \($0)" } ?? "Mode ?" }
+
+ static func reachTag(enabled: Bool?, state: String?, ms: Int?) -> Tag {
+ let base: (String, Tone) = switch (enabled == false, state) {
+ case (true, _): (String(localized: "Disabled"), .gray)
+ case (_, "up"): (String(localized: "Up"), .green)
+ case (_, "slow"): (String(localized: "Slow"), .orange)
+ case (_, "down"): (String(localized: "Down"), .red)
+ default: (String(localized: "Enabled"), .gray)
+ }
+ return Tag(text: base.0 + (ms.map { " · \($0) ms" } ?? ""), tone: base.1)
+ }
+
+ static func sslTag(state: String?, daysLeft: Int?) -> Tag? {
+ switch state {
+ case "ok", "soon":
+ let days = daysLeft.map { String(localized: "SSL \($0) days") } ?? String(localized: "SSL ok")
+ return Tag(text: days, tone: state == "soon" || (daysLeft ?? 99) < 14 ? .orange : .green)
+ case "expired": return Tag(text: String(localized: "SSL expired"), tone: .red)
+ case "missing": return Tag(text: String(localized: "SSL missing"), tone: .red)
+ case "http": return Tag(text: "HTTP", tone: .gray)
+ default: return nil
+ }
+ }
+
+ static func cdnTag(mode: Int?, edgeCount: Int, up: Int) -> Tag {
+ Tag(text: "CDN64 · \(modeShort(mode))" + (edgeCount > 0 ? " · " + String(localized: "\(up)/\(edgeCount) servers") : ""),
+ tone: edgeCount > 0 && up == 0 ? .red : .green)
+ }
+
+ /// Options as one line, e.g. "WS · Cache · HTTPS forced".
+ static func optionsLine(websockets: Bool?, blockExploits: Bool?, cacheAssets: Bool?, forceSSL: Bool?,
+ http2: Bool?, http3: Bool?, hsts: Bool?, accessListID: Int?) -> String? {
+ let list = [websockets == true ? "WS" : nil, blockExploits == true ? "Exploits" : nil,
+ cacheAssets == true ? "Cache" : nil, forceSSL == true ? "HTTPS forced" : nil,
+ http2 == true ? "H2" : nil, http3 == true ? "H3" : nil, hsts == true ? "HSTS" : nil,
+ (accessListID ?? 0) > 0 ? String(localized: "Not public") : nil].compactMap { $0 }
+ return list.isEmpty ? nil : list.joined(separator: " · ")
+ }
+
+ /// `kind → target`; blank parts dropped.
+ static func hostSubtitle(kind: String?, scheme: String?, targetHost: String?, targetPort: Int?,
+ redirectTarget: String?) -> String {
+ let target = targetHost.map { host in
+ (scheme.map { "\($0)://" } ?? "") + (targetPort.map { "\(host):\($0)" } ?? host)
+ }
+ return [kind, redirectTarget ?? target].compactMap { $0 }
+ .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }.joined(separator: " → ")
+ }
+
+ static func counterLine(requests: Int?, errors: Int?, blocked: Int?) -> String? {
+ guard let requests else { return nil }
+ var text = String(localized: "\(requests) requests")
+ if let errors, errors > 0 { text += " · " + String(localized: "\(errors) errors") }
+ if let blocked, blocked > 0 { text += " · " + String(localized: "\(blocked) blocked") }
+ return text
+ }
+
+ static func serversText(connected: Int, total: Int) -> String {
+ total == 0 ? String(localized: "No CDN64 servers") : String(localized: "Servers: \(connected) of \(total) connected")
+ }
+
+ // MARK: Host editor
+
+ static func parseNames(_ text: String) -> [String] {
+ text.split(whereSeparator: { $0 == "\n" || $0 == "," })
+ .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ }
+
+ static func parsePort(_ text: String) -> Int? {
+ Int(text.trimmingCharacters(in: .whitespaces)).flatMap { (1...65535).contains($0) ? $0 : nil }
+ }
+
+ // MARK: CDN64 modes
+
+ static func cdnModeTitle(_ mode: Int) -> String {
+ switch mode {
+ case 1: String(localized: "Pass through (default)")
+ case 2: String(localized: "Terminate on the servers")
+ case 3: String(localized: "Without Node64")
+ default: modeShort(mode)
+ }
+ }
+
+ static func cdnModeDescription(_ mode: Int) -> String {
+ switch mode {
+ case 1: String(localized: "The servers only pass the encrypted connection through; it is decrypted in your node. The right choice for almost everything.")
+ case 2: String(localized: "The servers decrypt (own certificate) and filter there: blocklists, limits, HTTP/3. Good for small uploads. Not with TLS passthrough.")
+ case 3: String(localized: "The servers go directly to your target without a tunnel — it must be reachable from the internet. Set up on the website:")
+ default: ""
+ }
+ }
+
+ /// Android `enableCdn64`: error text of the first failed name, else `nil`.
+ static func firstEnableError(_ results: [(name: String?, failed: Bool, error: String?, code: String?)]) -> String? {
+ results.first(where: \.failed).map { [$0.name, $0.error ?? $0.code].compactMap { $0 }.joined(separator: ": ") }
+ }
+
+ static var noNodeError: ErrorText {
+ ErrorText(title: String(localized: "No node reachable"),
+ message: String(localized: "No node with Proxy64 is reachable. Check the connection under More → Nodes."))
+ }
+
+ // MARK: Numbers
+
+ static func megabytes(_ mb: Double) -> String {
+ if mb >= 1024 * 1024 { return String(format: "%.1f TB", locale: .current, mb / (1024 * 1024)) }
+ if mb >= 1024 { return String(format: "%.2f GB", locale: .current, mb / 1024) }
+ return String(format: "%.1f MB", locale: .current, mb)
+ }
+
+ static func fraction(used: Double?, limit: Int?) -> Double? {
+ guard let limit, limit > 0 else { return nil }
+ return min(max((used ?? 0) / Double(limit), 0), 1)
+ }
+}
diff --git a/IPv64/Helpers/Proxy/ProxyNodes.swift b/IPv64/Helpers/Proxy/ProxyNodes.swift
new file mode 100644
index 0000000..3440344
--- /dev/null
+++ b/IPv64/Helpers/Proxy/ProxyNodes.swift
@@ -0,0 +1,93 @@
+import Foundation
+import IPv64
+
+/// Proxy hosts and CDN64 status of one connected proxy node (Android `NodeHosts` / `NodeOnline`).
+struct ProxyNodeData: Identifiable {
+ let id: String
+ let name: String
+ var hosts: [Node64.ProxyHost] = []
+ var online: Node64.CDNOnlineStatus?
+ /// Set when the node does not answer.
+ var error: ErrorText?
+
+ /// Hosts of a reachable node that are not in CDN64 yet.
+ var cdnChoices: [CdnHostChoice] {
+ guard error == nil else { return [] }
+ let used = cdn
+ return hosts.filter { used[$0.id] == nil }.map {
+ CdnHostChoice(nodeId: id, nodeName: name, hostId: $0.id,
+ label: ($0.names ?? []).joined(separator: ", ").nonBlank ?? "#\($0.id)")
+ }
+ }
+
+ /// CDN64 names by host id.
+ var cdn: [Int: Node64.CDNOnlineName] {
+ Dictionary((online?.names ?? []).compactMap { n in n.hostID.map { ($0, n) } }, uniquingKeysWith: { a, _ in a })
+ }
+}
+
+extension ProxyNodeData {
+ /// Loads one node (`withHosts: false`: CDN64 status only, its error counts); a failure stays in `error`.
+ nonisolated static func load(id: String, name: String, client: Node64?, withHosts: Bool) async -> ProxyNodeData {
+ var data = ProxyNodeData(id: id, name: name)
+ guard let client else {
+ data.error = ErrorText(title: String(localized: "Node not reachable"),
+ message: String(localized: "No access saved for this node."))
+ return data
+ }
+ do {
+ if withHosts {
+ data.hosts = try await client.proxy64.hosts.list()
+ // CDN64 is optional: a node without tunnel answers with an error.
+ data.online = try? await client.proxy64.online.status()
+ } else {
+ data.online = try await client.proxy64.online.status()
+ }
+ } catch {
+ data.error = ErrorText.node(error)
+ }
+ return data
+ }
+}
+
+/// One proxy host that can still get CDN64.
+struct CdnHostChoice: Identifiable, Hashable {
+ let nodeId: String
+ let nodeName: String
+ let hostId: Int
+ let label: String
+ var id: String { "\(nodeId)/\(hostId)" }
+}
+
+extension ConnectedNodes {
+ /// Every proxy node in parallel; a failing node affects only itself.
+ func loadProxyNodes(withHosts: Bool) async -> [ProxyNodeData] {
+ let jobs = proxyIds.map { ($0, name(of: $0), client(for: $0)) }
+ return await withTaskGroup(of: (Int, ProxyNodeData).self) { group in
+ for (index, job) in jobs.enumerated() {
+ group.addTask { (index, await ProxyNodeData.load(id: job.0, name: job.1, client: job.2, withHosts: withHosts)) }
+ }
+ var result: [(Int, ProxyNodeData)] = []
+ for await item in group { result.append(item) }
+ return result.sorted { $0.0 < $1.0 }.map(\.1)
+ }
+ }
+
+ func loadProxyNode(_ id: String, withHosts: Bool) async -> ProxyNodeData {
+ await ProxyNodeData.load(id: id, name: name(of: id), client: client(for: id), withHosts: withHosts)
+ }
+
+ /// Enables CDN64 for a host; returns an error to show (also a partly failed name), `nil` on success.
+ func enableCdn64(_ choice: CdnHostChoice, mode: Int, healthcheck: Bool) async -> ErrorText? {
+ guard let client = client(for: choice.nodeId) else {
+ return ErrorText(title: String(localized: "No access"), message: String(localized: "No access saved for this node."))
+ }
+ do {
+ let result = try await client.proxy64.online.enable(host: choice.hostId, mode: mode, healthcheck: healthcheck)
+ return ProxyLogic.firstEnableError((result.results ?? []).map { ($0.name, $0.result == .error, $0.error, $0.code) })
+ .map { ErrorText(title: "CDN64", message: $0) }
+ } catch {
+ return ErrorText.node(error)
+ }
+ }
+}
diff --git a/IPv64/Helpers/Push/AppDelegate.swift b/IPv64/Helpers/Push/AppDelegate.swift
new file mode 100644
index 0000000..011d536
--- /dev/null
+++ b/IPv64/Helpers/Push/AppDelegate.swift
@@ -0,0 +1,41 @@
+import UIKit
+import UserNotifications
+import SwiftyBeaver
+
+/// APNs registration (spec 01 §9): the token goes to SecNtfy via `PushRegistrar` on every launch.
+final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
+ /// Set by `IPv64App` once the scene is up; a token that arrived earlier is handed over then.
+ var registrar: PushRegistrar? {
+ didSet { deliverPendingToken() }
+ }
+ private var pendingToken: String?
+
+ func application(_ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
+ _ = iLogger.shared // log file destination (System Logs)
+ UNUserNotificationCenter.current().delegate = self
+ application.registerForRemoteNotifications() // no prompt; the permission is asked in Push setup step 1
+ return true
+ }
+
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
+ pendingToken = deviceToken.map { String(format: "%02x", $0) }.joined()
+ deliverPendingToken()
+ }
+
+ func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {
+ iLogger.log.warning("APNs registration failed: \(error.localizedDescription)")
+ }
+
+ private func deliverPendingToken() {
+ guard let registrar, let token = pendingToken else { return }
+ pendingToken = nil
+ Task { await registrar.apnsTokenReceived(token) }
+ }
+
+ /// Show pushes while the app is open (the Notification Service Extension already decrypted them).
+ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
+ willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
+ [.banner, .list, .sound]
+ }
+}
diff --git a/IPv64/Helpers/Push/PushLogic.swift b/IPv64/Helpers/Push/PushLogic.swift
new file mode 100644
index 0000000..a9040d4
--- /dev/null
+++ b/IPv64/Helpers/Push/PushLogic.swift
@@ -0,0 +1,221 @@
+import Foundation
+import IPv64
+
+/// Pure channel helpers (Android `ChannelFieldViews.kt`, `ChannelItemView.kt`, `PushChannelRegistrar.kt`), spec 04 §5–7.
+nonisolated enum ChannelLogic {
+ /// Android `parseChannelBool`: "true", "1", "yes", "on".
+ static func parseBool(_ raw: String?) -> Bool {
+ ["true", "1", "yes", "on"].contains(raw?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "")
+ }
+
+ /// Lower-cased field kind, missing = "text".
+ static func kindKey(_ field: HC2ChannelType.Field) -> String {
+ let kind = field.kind?.rawValue.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? ""
+ return kind.isEmpty ? "text" : kind
+ }
+
+ /// Secret field (never returned by the server).
+ static func isSecret(_ field: HC2ChannelType.Field) -> Bool {
+ field.secret == true || kindKey(field) == "password"
+ }
+
+ /// Android `toChannelFieldText`.
+ static func text(_ value: JSONValue?) -> String {
+ switch value {
+ case nil, .null?: ""
+ case .string(let s)?: s
+ case .bool(let b)?: b ? "true" : "false"
+ case .number(let n)?: n.rounded() == n && abs(n) < 1e15 ? String(Int64(n)) : String(n)
+ case let other?: (try? String(decoding: JSONEncoder().encode(other), as: UTF8.self)) ?? ""
+ }
+ }
+
+ /// Android `toConfigValue`: bool → JSON bool, number → integer, double or string, else string.
+ static func configValue(_ field: HC2ChannelType.Field, _ raw: String) -> JSONValue {
+ switch kindKey(field) {
+ case "bool": return .bool(parseBool(raw))
+ case "number":
+ let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if let int = Int64(text) { return .number(Double(int)) }
+ if let double = Double(text) { return .number(double) }
+ return .string(text)
+ default: return .string(raw)
+ }
+ }
+
+ /// Android `initialChannelFieldValue`.
+ static func initialValue(_ field: HC2ChannelType.Field, config: [String: JSONValue]?, isEdit: Bool) -> String {
+ guard let key = field.key else { return "" }
+ let isBool = kindKey(field) == "bool"
+ if isSecret(field) { return isEdit ? "" : field.default ?? "" }
+ if isEdit {
+ if let existing = config?[key], existing != .null {
+ return isBool ? String(parseBool(text(existing))) : text(existing)
+ }
+ return isBool ? String(parseBool(field.default)) : ""
+ }
+ return isBool ? String(parseBool(field.default)) : field.default ?? ""
+ }
+
+ /// Passwords, multi-line and secret values are sent unchanged, everything else trimmed.
+ private static func normalized(_ field: HC2ChannelType.Field, _ raw: String) -> String {
+ let kind = kindKey(field)
+ return kind == "password" || kind == "textarea" || isSecret(field)
+ ? raw : raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ /// Android `buildChannelConfig`. New: blank optional fields omitted. Edit: starts from `base` (unknown keys kept),
+ /// secrets only when typed (`touched`) and non-blank, a cleared non-secret field is sent as "", `keepKeys` untouched.
+ static func buildConfig(fields: [HC2ChannelType.Field], values: [String: String], touched: Set,
+ base: [String: JSONValue]?, isEdit: Bool, keepKeys: Set = []) -> [String: JSONValue] {
+ var map = isEdit ? base ?? [:] : [:]
+ for field in fields {
+ guard let key = field.key?.nonBlank, !keepKeys.contains(key) else { continue }
+ let text = normalized(field, values[key] ?? "")
+ let blank = text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ if kindKey(field) == "bool" {
+ map[key] = configValue(field, text)
+ } else if isSecret(field) {
+ if !blank && (!isEdit || touched.contains(key)) { map[key] = configValue(field, text) } else { map[key] = nil }
+ } else if blank {
+ if isEdit && !self.text(base?[key]).isEmpty { map[key] = .string("") }
+ } else {
+ map[key] = configValue(field, text)
+ }
+ }
+ return map
+ }
+
+ /// Android `channelFieldError` (`nil` = valid).
+ static func fieldError(_ field: HC2ChannelType.Field, value: String, required: Bool) -> String? {
+ if kindKey(field) == "bool" { return nil }
+ let text = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ if text.isEmpty { return required ? String(localized: "Required") : nil }
+ if kindKey(field) == "number" && Double(text) == nil { return String(localized: "Must be a number") }
+ return nil
+ }
+
+ /// Android `channelTestResultMessage` (title, text).
+ static func testResultMessage(_ result: HC2ChannelTestResult) -> (title: String, message: String) {
+ if result.sent == true {
+ return (String(localized: "Test sent"), String(localized: "The test notification was sent."))
+ }
+ if result.queuedAtNode == true {
+ return (String(localized: "Test queued"), String(localized: "The test notification was queued at the node."))
+ }
+ return (String(localized: "Test not sent"),
+ String(localized: "The server did not send the test notification. Please check the channel settings."))
+ }
+
+ /// Android `displayName`: name → typeLabel → type → "Channel #".
+ static func displayName(_ channel: HC2Channel) -> String {
+ channel.name?.nonBlank ?? channel.typeLabel?.nonBlank ?? channel.type?.rawValue.nonBlank
+ ?? String(localized: "Channel #\(channel.id)")
+ }
+
+ /// Android `isAwaitingVerification`; without types the mail/SMS types need verification.
+ static func isAwaitingVerification(_ channel: HC2Channel, types: [HC2ChannelType]?) -> Bool {
+ guard channel.verified != true else { return false }
+ if let types {
+ return types.first { $0.type == channel.type }?.needsVerification == true
+ }
+ return channel.type == .ipv64Mail || channel.type == .ipv64SMS
+ }
+
+ /// Type icon (spec 04 §5).
+ static func systemImage(type: String?) -> String {
+ switch type?.lowercased() {
+ case "ipv64_mail", "smtp", "email", "mail": "at"
+ case "ipv64_sms", "sms": "message"
+ case "app": "iphone"
+ case "telegram": "paperplane.circle"
+ case "discord": "bubble.left.and.bubble.right"
+ case "ntfy", "secntfy": "bell.and.waves.left.and.right"
+ case "gotify": "bell.badge"
+ case "pushover": "bell.circle"
+ case "webhook": "arrow.triangle.branch"
+ case "slack", "teams", "matrix": "puzzlepiece.extension"
+ case nil, "": "questionmark.square.dashed"
+ default: "bell.badge"
+ }
+ }
+
+ /// Android `systemChannelLang()`.
+ static var systemLanguage: HC2ChannelLanguage {
+ Locale.current.language.languageCode?.identifier == "de" ? .de : .en
+ }
+}
+
+/// Pure helpers of the hc2 "app" channel of this device (Android `PushChannelRegistrar`).
+nonisolated enum PushTokenLogic {
+ static let fallbackTokenKey = "device_token"
+
+ static func appType(_ types: [HC2ChannelType]?) -> HC2ChannelType? {
+ types?.first { $0.type == .app }
+ }
+
+ /// Android `resolveAppTokenKey`.
+ static func resolveTokenKey(_ appType: HC2ChannelType?) -> String? {
+ let fields = (appType?.fields ?? []).filter { $0.key?.nonBlank != nil }
+ let keys = fields.compactMap(\.key)
+ for preferred in ["device_token", "devicetoken", "token", "ntfy_token"] {
+ if let key = keys.first(where: { $0.lowercased() == preferred }) { return key }
+ }
+ if let key = keys.first(where: { $0.lowercased().contains("token") }) { return key }
+ let textual = fields.filter {
+ $0.required == true && ["text", "password", "textarea"].contains(ChannelLogic.kindKey($0))
+ }
+ return textual.count == 1 ? textual[0].key : nil
+ }
+
+ /// Android `tokenKeyFor(channel, appType)`.
+ static func tokenKey(for channel: HC2Channel, appType: HC2ChannelType?) -> String {
+ resolveTokenKey(appType)
+ ?? channel.secretsSet?.first { $0.lowercased().contains("token") }
+ ?? channel.config?.keys.sorted().first { $0.lowercased().contains("token") }
+ ?? fallbackTokenKey
+ }
+
+ /// The non-secret config holds the token (SHA-256 fingerprint of a string value; `key` first, then any value).
+ static func configHoldsToken(_ channel: HC2Channel, key: String?, token: String) -> Bool {
+ guard let config = channel.config else { return false }
+ let fp = PushSetupStore.fingerprint(token)
+ func matches(_ value: JSONValue?) -> Bool {
+ guard case .string(let s)? = value else { return false }
+ let trimmed = s.trimmingCharacters(in: .whitespacesAndNewlines)
+ return !trimmed.isEmpty && PushSetupStore.fingerprint(trimmed) == fp
+ }
+ if let key, matches(config.first(where: { $0.key.lowercased() == key.lowercased() })?.value) { return true }
+ return config.values.contains(where: matches)
+ }
+
+ /// Existing config without the token key (case-insensitive) plus `key: token`.
+ static func configWithToken(_ existing: [String: JSONValue]?, key: String, token: String) -> [String: JSONValue] {
+ var map = (existing ?? [:]).filter { $0.key.lowercased() != key.lowercased() }
+ map[key] = .string(token)
+ return map
+ }
+
+ /// Android `findThisDeviceChannel`: stored id first, else an app channel whose config holds the token.
+ static func findThisDevice(_ channels: [HC2Channel], storedId: Int?, key: String?, token: String?) -> HC2Channel? {
+ let apps = channels.filter { $0.type == .app }
+ if let storedId, let match = apps.first(where: { $0.id == storedId }) { return match }
+ guard let token = token?.nonBlank else { return nil }
+ return apps.first { configHoldsToken($0, key: key, token: token) }
+ }
+
+ /// The server kept the token key (`secrets_set` or `config`, case-insensitive).
+ static func holdsTokenKey(_ channel: HC2Channel, key: String) -> Bool {
+ let keys = (channel.secretsSet ?? []) + (channel.config.map { Array($0.keys) } ?? [])
+ return keys.contains { $0.lowercased() == key.lowercased() }
+ }
+
+ /// Existing app channels, names equal to the typed or default device name first (Android candidate order).
+ static func sortedCandidates(_ apps: [HC2Channel], names: [String]) -> [HC2Channel] {
+ let wanted = Set(names.map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() })
+ func preferred(_ c: HC2Channel) -> Bool {
+ wanted.contains((c.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased())
+ }
+ return apps.filter(preferred) + apps.filter { !preferred($0) }
+ }
+}
diff --git a/IPv64/Helpers/Push/PushRegistrar.swift b/IPv64/Helpers/Push/PushRegistrar.swift
new file mode 100644
index 0000000..227f0ef
--- /dev/null
+++ b/IPv64/Helpers/Push/PushRegistrar.swift
@@ -0,0 +1,285 @@
+import Foundation
+import IPv64
+import Observation
+import SecNtfy
+import SwiftyBeaver
+import UIKit
+
+/// Android `PushRegistrationException`: shown as a message dialog (title + text, never the token).
+nonisolated struct PushRegistrationError: Error, Sendable {
+ let title: String
+ let message: String
+
+ static var tokenUnavailable: Self {
+ Self(title: String(localized: "Device token unavailable"),
+ message: String(localized: "This device could not be registered for push notifications (Apple Push Notification service or the push service is not reachable). Please check your internet connection and try again later."))
+ }
+
+ static var notSupported: Self {
+ Self(title: String(localized: "Not supported"),
+ message: String(localized: "Push notifications to the IPv64 app are not supported by the server yet. You can skip this step."))
+ }
+
+ static var channelNotFound: Self {
+ Self(title: String(localized: "Channel not found"),
+ message: String(localized: "The selected channel no longer exists."))
+ }
+
+ static func unknownFormat(_ message: String) -> Self {
+ Self(title: String(localized: "Unknown app channel format"), message: message)
+ }
+}
+
+/// Settings of this device's channel (Android `DeviceChannelSettings`).
+struct DeviceChannelSettings {
+ var name: String
+ var isDefault: Bool
+ var notifyDown: Bool
+ var notifyUp: Bool
+ var lang: HC2ChannelLanguage
+}
+
+enum DeviceRegistration {
+ case registered(HC2Channel, reused: Bool)
+ /// No match, `createNew == false` and the account already has app channels.
+ case existingCandidates([HC2Channel])
+}
+
+/// SecNtfy device token + hc2 "app" channel of this device (Android `SecNtfyHelper` + `PushChannelRegistrar`,
+/// spec 01 §9, 04 §7). One instance, injected with `.environment(registrar)`.
+@Observable
+final class PushRegistrar {
+ private let session: Session
+ /// `apiUrl|appKey` the SDK was configured with (Android: init once per process unless they change).
+ @ObservationIgnored private var configuredFor: String?
+ /// Last device registration; a new one waits for it (Android serialises with a mutex).
+ @ObservationIgnored private var registration: Task?
+ /// Account scope the push setup sheet was opened for in this app run, shared by all windows
+ /// so only one window opens it (Android `MainActivity`: once per account and app start).
+ @ObservationIgnored var setupTriggeredFor: String?
+ /// Bumped when a window closes the setup sheet; other windows close theirs once `PushSetupStore.shouldShow` is false.
+ var setupClosed = 0
+
+ init(session: Session) {
+ self.session = session
+ }
+
+ // MARK: - SecNtfy
+
+ private var appKey: String {
+ AppConfig.secNtfyAppKey
+ }
+
+ /// The App Group keeps the key pair and device token so the Notification Service Extension can decrypt.
+ private func configureSecNtfy(force: Bool) {
+ let url = AppConfig.secNtfyURL
+ let key = appKey
+ guard force || configuredFor != url + "|" + key else { return }
+ SecNtfySwifty.shared.initialize(apiUrl: url, bundleGroup: AppConfig.appGroup)
+ if !key.isEmpty { SecNtfySwifty.shared.configure(apiKey: key) }
+ configuredFor = url + "|" + key
+ }
+
+ /// GAP (SecNtfy SDK): no public accessor for the stored device token, so the App Group key is read directly.
+ private var storedToken: String? {
+ UserDefaults(suiteName: AppConfig.appGroup)?.string(forKey: "NTFY_DEVICE_TOKEN")?.nonBlank
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ }
+
+ /// APNs token from the app delegate (every launch): register at SecNtfy, then update the device channel.
+ func apnsTokenReceived(_ hex: String) async {
+ SecNtfySwifty.shared.setApnsToken(apnsToken: hex)
+ guard await registerDevice() != nil else { return }
+ _ = try? await syncTokenIfChanged(channels: nil)
+ }
+
+ /// Android `registerDevice()`: SecNtfy device token or `nil` (not configured / not reachable).
+ @discardableResult
+ func registerDevice() async -> String? {
+ let previous = registration
+ let task = Task { [weak self] () -> String? in
+ _ = await previous?.value
+ return await self?.performRegistration()
+ }
+ registration = task
+ let token = await task.value
+ if registration == task { registration = nil }
+ return token
+ }
+
+ private func performRegistration() async -> String? {
+ guard !appKey.isEmpty else { return nil }
+ configureSecNtfy(force: false)
+ for attempt in 0..<2 {
+ let result = await SecNtfySwifty.shared.getNtfyToken()
+ if let token = result.token?.nonBlank { return token.trimmingCharacters(in: .whitespacesAndNewlines) }
+ iLogger.log.warning("SecNtfy registration failed: \(result.error?.localizedDescription ?? "no token")")
+ // GAP (SecNtfy SDK): NtfyError is internal, ConfigurationChanged / NoDevice cannot be told apart → reconfigure, retry once.
+ if attempt == 0 { configureSecNtfy(force: true) }
+ }
+ return nil
+ }
+
+ /// Android `ntfyToken()`: stored token, else a fresh registration.
+ private func ntfyToken() async -> String? {
+ if let storedToken { return storedToken }
+ return await registerDevice()
+ }
+
+ // MARK: - Account / channel
+
+ /// Remembers the stable account id for the active API key (`account.me().id`) once per key.
+ /// API and network errors are ignored (retried on a later trigger).
+ func ensureAccountId() async {
+ guard let keyHash = PushSetupStore.keyHash(apiKey: session.apiKey),
+ PushSetupStore.accountId(keyHash: keyHash) == nil else { return }
+ let client = session.api // captured before the request so an account switch cannot mix them up
+ guard let me = try? await ipv64Retrying({ try await client.account.me() }) else { return }
+ PushSetupStore.rememberAccountId(keyHash: keyHash, accountId: me.id)
+ }
+
+ /// Android `syncTokenIfChanged(channels?)`: puts a changed token on the stored device channel.
+ /// Without `channels` and an unchanged token nothing is requested. Returns `true` if a request updated it.
+ @discardableResult
+ func syncTokenIfChanged(channels: [HC2Channel]? = nil) async throws -> Bool {
+ let apiKey = session.apiKey
+ let client = session.api
+ guard let storedId = PushSetupStore.channelId(apiKey: apiKey) else { return false }
+ let token = storedToken
+ let fp = token.map(PushSetupStore.fingerprint)
+ let upToDate = token == nil || fp == PushSetupStore.tokenFingerprint(apiKey: apiKey)
+ if channels == nil && upToDate { return false }
+ var channel = channels?.first { $0.id == storedId && $0.type == .app }
+ if channel == nil {
+ channel = try await ipv64Retrying { try await client.hc2.channels.list() }
+ .first { $0.id == storedId && $0.type == .app }
+ }
+ guard let channel else {
+ PushSetupStore.clearChannel(apiKey: apiKey)
+ return false
+ }
+ guard !upToDate, let token else { return false }
+ let types = try? await ipv64Retrying { try await client.hc2.channels.types() }
+ let key = PushTokenLogic.tokenKey(for: channel, appType: PushTokenLogic.appType(types))
+ if PushTokenLogic.configHoldsToken(channel, key: key, token: token) {
+ PushSetupStore.setChannel(apiKey: apiKey, id: storedId, tokenFingerprint: fp)
+ return false
+ }
+ let input = HC2ChannelInput(name: channel.name ?? ChannelLogic.displayName(channel),
+ config: PushTokenLogic.configWithToken(channel.config, key: key, token: token))
+ _ = try await ipv64Retrying { try await client.hc2.channels.update(storedId, input) }
+ PushSetupStore.setChannel(apiKey: apiKey, id: storedId, tokenFingerprint: fp)
+ return true
+ }
+
+ /// Android `detectThisDevice`: stored channel, else token match (then remembered).
+ func detectThisDevice(_ channels: [HC2Channel], types: [HC2ChannelType]?) -> HC2Channel? {
+ let apiKey = session.apiKey
+ let storedId = PushSetupStore.channelId(apiKey: apiKey)
+ let token = storedToken
+ let key = PushTokenLogic.resolveTokenKey(PushTokenLogic.appType(types))
+ guard let found = PushTokenLogic.findThisDevice(channels, storedId: storedId, key: key, token: token) else { return nil }
+ if found.id != storedId, let token {
+ PushSetupStore.setChannel(apiKey: apiKey, id: found.id, tokenFingerprint: PushSetupStore.fingerprint(token))
+ }
+ return found
+ }
+
+ /// Android `registerThisDevice` (spec 04 §7 steps 1–9).
+ func registerThisDevice(_ settings: DeviceChannelSettings, adoptChannelId: Int? = nil,
+ createNew: Bool = false) async throws -> DeviceRegistration {
+ guard let token = await ntfyToken() else { throw PushRegistrationError.tokenUnavailable }
+ await ensureAccountId()
+ let apiKey = session.apiKey
+ let client = session.api
+ let types = try await ipv64Retrying { try await client.hc2.channels.types() }
+ guard let appType = PushTokenLogic.appType(types) else { throw PushRegistrationError.notSupported }
+ let resolvedKey = PushTokenLogic.resolveTokenKey(appType)
+ let key = resolvedKey ?? PushTokenLogic.fallbackTokenKey
+ let channels = try await ipv64Retrying { try await client.hc2.channels.list() }
+ let apps = channels.filter { $0.type == .app }
+ let storedId = PushSetupStore.channelId(apiKey: apiKey)
+ let target = Target(apiKey: apiKey, client: client, key: key, token: token)
+
+ if let adoptChannelId {
+ guard let channel = channels.first(where: { $0.id == adoptChannelId }) else {
+ throw PushRegistrationError.channelNotFound
+ }
+ return .registered(try await applyToExisting(channel, settings, target, setToken: true), reused: true)
+ }
+ if let existing = PushTokenLogic.findThisDevice(channels, storedId: storedId, key: key, token: token) {
+ let knownFp = existing.id == storedId ? PushSetupStore.tokenFingerprint(apiKey: apiKey) : nil
+ let outdated = !PushTokenLogic.configHoldsToken(existing, key: key, token: token)
+ && knownFp != PushSetupStore.fingerprint(token)
+ return .registered(try await applyToExisting(existing, settings, target, setToken: outdated), reused: true)
+ }
+ if !createNew && !apps.isEmpty {
+ return .existingCandidates(PushTokenLogic.sortedCandidates(apps, names: [settings.name, Self.defaultDeviceName]))
+ }
+ return .registered(try await create(settings, appType: appType, resolvedKey: resolvedKey, target), reused: false)
+ }
+
+ private struct Target {
+ let apiKey: String
+ let client: IPv64
+ let key: String
+ let token: String
+ }
+
+ private func create(_ settings: DeviceChannelSettings, appType: HC2ChannelType, resolvedKey: String?,
+ _ target: Target) async throws -> HC2Channel {
+ var config: [String: JSONValue] = [target.key: .string(target.token)]
+ for field in appType.fields ?? [] where field.required == true {
+ guard let fieldKey = field.key?.nonBlank, fieldKey.lowercased() != target.key.lowercased() else { continue }
+ guard let value = field.default else {
+ let label = field.label?.nonBlank ?? fieldKey
+ throw PushRegistrationError.unknownFormat(String(localized: "The server requires the setting \"\(label)\" for app channels. Please add this device at ipv64.net."))
+ }
+ config[fieldKey] = ChannelLogic.configValue(field, value)
+ }
+ let input = HC2ChannelInput(name: settings.name, type: .app, config: config, enabled: true,
+ default: settings.isDefault, lang: settings.lang,
+ notifyDown: settings.notifyDown, notifyUp: settings.notifyUp)
+ let client = target.client
+ // Android "no id returned": HC2Channel.id is non-optional, a body without id fails decoding instead.
+ let created = try await ipv64Retrying { try await client.hc2.channels.create(input) }
+ PushSetupStore.setChannel(apiKey: target.apiKey, id: created.id, tokenFingerprint: PushSetupStore.fingerprint(target.token))
+ if PushTokenLogic.holdsTokenKey(created, key: target.key) { return created }
+ guard let reloaded = try? await ipv64Retrying({ try await client.hc2.channels.get(created.id) }) else { return created }
+ if !PushTokenLogic.holdsTokenKey(reloaded, key: target.key) && resolvedKey == nil {
+ PushSetupStore.clearChannel(apiKey: target.apiKey)
+ // Not cancellable (Android NonCancellable): the guessed channel must not stay behind.
+ await Task { try? await client.hc2.channels.delete(created.id) }.value
+ throw PushRegistrationError.unknownFormat(String(localized: "The server describes app channels in a format this app version does not know. Please update the app or add this device at ipv64.net."))
+ }
+ return reloaded
+ }
+
+ /// Android `applyToExisting`: one PATCH with the differences only (never un-defaults), then remember id + fingerprint.
+ private func applyToExisting(_ channel: HC2Channel, _ settings: DeviceChannelSettings, _ target: Target,
+ setToken: Bool) async throws -> HC2Channel {
+ let name = settings.name.trimmingCharacters(in: .whitespacesAndNewlines)
+ let newName = !name.isEmpty && name != channel.name ? name : nil
+ let config = setToken ? PushTokenLogic.configWithToken(channel.config, key: target.key, token: target.token) : nil
+ let enabled: Bool? = channel.enabled == false ? true : nil
+ let isDefault: Bool? = settings.isDefault && channel.default != true ? true : nil
+ let down: Bool? = settings.notifyDown != channel.notifyDown ? settings.notifyDown : nil
+ let up: Bool? = settings.notifyUp != channel.notifyUp ? settings.notifyUp : nil
+ var result = channel
+ if newName != nil || config != nil || enabled != nil || isDefault != nil || down != nil || up != nil {
+ // GAP-7: HC2ChannelInput.name is non-optional, so the PATCH always carries the (unchanged) name.
+ let input = HC2ChannelInput(name: newName ?? channel.name ?? ChannelLogic.displayName(channel), config: config,
+ enabled: enabled, default: isDefault, notifyDown: down, notifyUp: up)
+ let client = target.client
+ result = try await ipv64Retrying { try await client.hc2.channels.update(channel.id, input) }
+ }
+ PushSetupStore.setChannel(apiKey: target.apiKey, id: channel.id, tokenFingerprint: PushSetupStore.fingerprint(target.token))
+ return result
+ }
+
+ /// Channel name: the model name from the SecNtfy package (e.g. "iPhone 15 Pro Max"), as SecNtfy names the device.
+ static var defaultDeviceName: String {
+ let model = UIDevice.current.type
+ return model == .unrecognized ? UIDevice.current.name : model.rawValue
+ }
+}
diff --git a/IPv64/Helpers/Push/PushSetupStore.swift b/IPv64/Helpers/Push/PushSetupStore.swift
new file mode 100644
index 0000000..a66ed92
--- /dev/null
+++ b/IPv64/Helpers/Push/PushSetupStore.swift
@@ -0,0 +1,95 @@
+import Foundation
+import CryptoKit
+
+/// Device-local push setup state (Android `PushSetupStore`, prefs `HC2_PUSH_SETUP`, spec 01 §2.4 / 04 §7.3).
+/// Keys (app-group UserDefaults, prefix `HC2_PUSH_SETUP.`): `done_` Bool, `channel_` Int,
+/// `tokenfp_` String, `acct_` Int. Scope = `"a" + sha256("account:")[:16]` once the
+/// account id is known, else the key hash `sha256(trim(apiKey))[:16]`. The token itself is never stored.
+nonisolated enum PushSetupStore {
+ private static let prefix = "HC2_PUSH_SETUP."
+ /// Test seam: an isolated suite replaces the app-group defaults.
+ nonisolated(unsafe) static var overrideDefaults: UserDefaults?
+ private static var defaults: UserDefaults { overrideDefaults ?? UserDefaults(suiteName: AppConfig.appGroup) ?? .standard }
+
+ static func sha256Hex(_ text: String) -> String {
+ SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// Fingerprint of a (trimmed) device token.
+ static func fingerprint(_ token: String) -> String {
+ sha256Hex(token.trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+
+ /// `nil` when logged out.
+ static func keyHash(apiKey: String) -> String? {
+ let key = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !key.isEmpty else { return nil }
+ // DEBUG mock server: its own namespace, so mock account ids never stick to a real API key.
+ let scoped = AppConfig.mockBase.map { "\(key)|\($0)" } ?? key
+ return String(sha256Hex(scoped).prefix(16))
+ }
+
+ static func accountScope(accountId: Int) -> String { "a" + sha256Hex("account:\(accountId)").prefix(16) }
+
+ static func accountId(keyHash: String) -> Int? {
+ defaults.object(forKey: prefix + "acct_" + keyHash) as? Int
+ }
+
+ /// Current scope (Android `accountHash()`), `nil` when logged out.
+ static func scope(apiKey: String) -> String? {
+ guard let keyHash = keyHash(apiKey: apiKey) else { return nil }
+ return accountId(keyHash: keyHash).map(accountScope) ?? keyHash
+ }
+
+ /// Android `shouldShow()`: logged in, not done, no device channel stored, SecNtfy configured.
+ static func shouldShow(apiKey: String) -> Bool {
+ guard let scope = scope(apiKey: apiKey) else { return false }
+ return !defaults.bool(forKey: prefix + "done_" + scope)
+ && defaults.object(forKey: prefix + "channel_" + scope) == nil
+ && AppConfig.isSecNtfyConfigured
+ }
+
+ static func markDone(apiKey: String) {
+ guard let scope = scope(apiKey: apiKey) else { return }
+ defaults.set(true, forKey: prefix + "done_" + scope)
+ }
+
+ /// Stored hc2 channel id of this device.
+ static func channelId(apiKey: String) -> Int? {
+ scope(apiKey: apiKey).flatMap { defaults.object(forKey: prefix + "channel_" + $0) as? Int }
+ }
+
+ static func tokenFingerprint(apiKey: String) -> String? {
+ scope(apiKey: apiKey).flatMap { defaults.string(forKey: prefix + "tokenfp_" + $0) }
+ }
+
+ static func setChannel(apiKey: String, id: Int, tokenFingerprint: String?) {
+ guard let scope = scope(apiKey: apiKey) else { return }
+ defaults.set(id, forKey: prefix + "channel_" + scope)
+ if let tokenFingerprint {
+ defaults.set(tokenFingerprint, forKey: prefix + "tokenfp_" + scope)
+ } else {
+ defaults.removeObject(forKey: prefix + "tokenfp_" + scope)
+ }
+ }
+
+ static func clearChannel(apiKey: String) {
+ guard let scope = scope(apiKey: apiKey) else { return }
+ defaults.removeObject(forKey: prefix + "channel_" + scope)
+ defaults.removeObject(forKey: prefix + "tokenfp_" + scope)
+ }
+
+ /// Remembers the account id of a key hash and migrates key-hash-scoped entries to the account scope
+ /// (existing account values win; channel + fingerprint only if the account scope has no channel).
+ static func rememberAccountId(keyHash: String, accountId: Int) {
+ let account = accountScope(accountId: accountId)
+ let d = defaults
+ if d.object(forKey: prefix + "channel_" + account) == nil, let channel = d.object(forKey: prefix + "channel_" + keyHash) {
+ d.set(channel, forKey: prefix + "channel_" + account)
+ if let fp = d.string(forKey: prefix + "tokenfp_" + keyHash) { d.set(fp, forKey: prefix + "tokenfp_" + account) }
+ }
+ if d.bool(forKey: prefix + "done_" + keyHash) { d.set(true, forKey: prefix + "done_" + account) }
+ for field in ["done_", "channel_", "tokenfp_"] { d.removeObject(forKey: prefix + field + keyHash) }
+ d.set(accountId, forKey: prefix + "acct_" + keyHash)
+ }
+}
diff --git a/IPv64/Helpers/Push/PushSupport.swift b/IPv64/Helpers/Push/PushSupport.swift
new file mode 100644
index 0000000..e8b1fe5
--- /dev/null
+++ b/IPv64/Helpers/Push/PushSupport.swift
@@ -0,0 +1,75 @@
+import SwiftUI
+import IPv64
+
+/// What the push code needs from the app: the active account's API client and a few helpers (configuration: `AppConfig`).
+
+/// API v2 client of the active account (IPv64-SPM).
+@Observable
+final class Session {
+ var apiKey: String { UserStorage.shared.ApiKey.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var api: IPv64 { AppConfig.cloudClient(apiKey: apiKey) }
+
+ enum IPFamilyChoice { case v4, v6 }
+
+ /// Public IPv4 / IPv6 of this device (`meta.ip()` on ipv4./ipv6.ipv64.net), `nil` if the family is unreachable.
+ func myIP(_ family: IPFamilyChoice) async -> String? {
+ let host = family == .v4 ? "https://ipv4.ipv64.net/api/v2" : "https://ipv6.ipv64.net/api/v2"
+ let client = AppConfig.cloudClient(apiKey: nil, production: host, timeout: 5)
+ guard let result = try? await client.meta.ip() else { return nil }
+ if let reported = result.family, reported != (family == .v4 ? .ipv4 : .ipv6) { return nil }
+ return result.ip?.trimmingCharacters(in: .whitespacesAndNewlines).nonBlank
+ }
+}
+
+/// On a 429 with a short `retryAfter` wait and run once more (Android `ipv64Retrying`).
+func ipv64Retrying(_ operation: () async throws -> T) async throws -> T {
+ do {
+ return try await operation()
+ } catch let error as IPv64Error {
+ var wait = 3
+ if case .api(let problem) = error, let seconds = problem.retryAfter { wait = seconds }
+ guard error.statusCode == 429, wait <= 5 else { throw error }
+ try await Task.sleep(for: .seconds(max(wait, 1)))
+ return try await operation()
+ }
+}
+
+nonisolated struct ErrorText: Identifiable, Sendable {
+ let id = UUID()
+ var title: String
+ var message: String
+
+ init(title: String, message: String) {
+ self.title = title
+ self.message = message
+ }
+
+ /// Shows the server's detail text instead of a generic connection error.
+ init(_ error: any Error) {
+ title = String(localized: "Error")
+ if case .api(let problem)? = error as? IPv64Error {
+ message = problem.detail
+ } else {
+ message = error.localizedDescription
+ }
+ }
+}
+
+extension View {
+ func errorAlert(_ error: Binding) -> some View {
+ alert(error.wrappedValue?.title ?? "", isPresented: Binding(
+ get: { error.wrappedValue != nil }, set: { if !$0 { error.wrappedValue = nil } }
+ )) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(error.wrappedValue?.message ?? "")
+ }
+ }
+}
+
+extension String {
+ /// `nil` for empty or whitespace-only text.
+ nonisolated var nonBlank: String? {
+ trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : self
+ }
+}
diff --git a/IPv64/Helpers/ScreenshotProtection.swift b/IPv64/Helpers/ScreenshotProtection.swift
new file mode 100644
index 0000000..0c3fc31
--- /dev/null
+++ b/IPv64/Helpers/ScreenshotProtection.swift
@@ -0,0 +1,83 @@
+import SwiftUI
+import UIKit
+
+/// Screenshot protection (More → App), like Android's FLAG_SECURE: screenshots and recordings show the app black,
+/// and while the screen is recorded/mirrored or the app is inactive (app switcher snapshot) an opaque cover is shown.
+private struct ScreenshotProtection: ViewModifier {
+ let enabled: Bool
+ @Environment(\.scenePhase) private var scenePhase
+ @State private var captured = false
+
+ func body(content: Content) -> some View {
+ content
+ .overlay {
+ if enabled && (captured || scenePhase != .active) {
+ ZStack {
+ Color(.systemBackground)
+ VStack(spacing: 12) {
+ Image(systemName: "eye.slash").font(.largeTitle)
+ Text("Screenshot protection is on")
+ .font(.headline)
+ Text("You can turn it off under More → App → Screenshot protection.")
+ .font(.footnote)
+ .multilineTextAlignment(.center)
+ }
+ .foregroundStyle(.secondary)
+ .padding(32)
+ }
+ .ignoresSafeArea()
+ }
+ }
+ .onAppear(perform: refresh)
+ .onChange(of: enabled, initial: true) { ScreenshotShield.apply(enabled) }
+ .onChange(of: scenePhase) { if scenePhase == .active { ScreenshotShield.apply(enabled) } }
+ .onReceive(NotificationCenter.default.publisher(for: UIScreen.capturedDidChangeNotification)) { _ in refresh() }
+ }
+
+ private func refresh() {
+ captured = UIApplication.shared.connectedScenes
+ .compactMap { ($0 as? UIWindowScene)?.screen }
+ .contains { $0.isCaptured }
+ }
+}
+
+/// Hangs each window's layer into the secure layer of a password field, which iOS leaves out of screenshots and
+/// recordings (same setup as ScreenProtectorKit: iOS 17+ uses the field's last sublayer). Touches and layout are
+/// unaffected (only the layer moves, the view tree stays). Installed once per window; on/off only flips
+/// `isSecureTextEntry`, so the layer tree is never rebuilt while the app runs.
+/// shortcut: relies on UITextField's private layer layout; check after each major iOS update.
+@MainActor private enum ScreenshotShield {
+ private static var fields: [ObjectIdentifier: UITextField] = [:]
+
+ static func apply(_ on: Bool) {
+ let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows)
+ for window in windows {
+ if let field = fields[ObjectIdentifier(window)] {
+ field.isSecureTextEntry = on
+ } else if on {
+ install(window)
+ }
+ }
+ }
+
+ private static func install(_ window: UIWindow) {
+ guard let superlayer = window.layer.superlayer else { return }
+ let field = UITextField()
+ field.isSecureTextEntry = true
+ field.isUserInteractionEnabled = false
+ // Zero-size field at the window origin: the window layer is positioned in the field's coordinates, so any
+ // offset of the field (e.g. centring it) shifts the whole app on screen.
+ window.addSubview(field)
+ guard let secure = field.layer.sublayers?.last else {
+ field.removeFromSuperview()
+ return
+ }
+ superlayer.addSublayer(field.layer)
+ secure.addSublayer(window.layer)
+ fields[ObjectIdentifier(window)] = field
+ }
+}
+
+extension View {
+ func screenshotProtected(_ enabled: Bool) -> some View { modifier(ScreenshotProtection(enabled: enabled)) }
+}
diff --git a/IPv64/Helpers/SecureStore.swift b/IPv64/Helpers/SecureStore.swift
new file mode 100644
index 0000000..73f431c
--- /dev/null
+++ b/IPv64/Helpers/SecureStore.swift
@@ -0,0 +1,62 @@
+import Foundation
+import Security
+
+/// Shared by the app and widget; never falls back to plaintext storage.
+nonisolated enum SecureStore {
+ static func accessGroup() throws -> String {
+ guard let group = Bundle.main.object(forInfoDictionaryKey: "SecureKeychainAccessGroup") as? String,
+ !group.isEmpty, !group.contains("$(") else {
+ throw StoreError.configuration
+ }
+ return group
+ }
+
+ private static func query(_ account: String) throws -> [String: Any] {
+ try [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: "net.ipv64.credentials",
+ kSecAttrAccount as String: account,
+ kSecAttrAccessGroup as String: accessGroup()]
+ }
+
+ static func read(_ account: String) throws -> Data? {
+ var request = try query(account)
+ request[kSecReturnData as String] = true
+ request[kSecMatchLimit as String] = kSecMatchLimitOne
+ var result: CFTypeRef?
+ let status = SecItemCopyMatching(request as CFDictionary, &result)
+ if status == errSecItemNotFound { return nil }
+ guard status == errSecSuccess else { throw StoreError.status(status) }
+ return result as? Data
+ }
+
+ static func readString(_ account: String) throws -> String {
+ String(data: try read(account) ?? Data(), encoding: .utf8) ?? ""
+ }
+
+ static func write(_ data: Data, account: String) throws {
+ let request = try query(account)
+ let attributes: [String: Any] = [
+ kSecValueData as String: data,
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ ]
+ let status = SecItemUpdate(request as CFDictionary, attributes as CFDictionary)
+ if status == errSecItemNotFound {
+ let addStatus = SecItemAdd(request.merging(attributes) { _, new in new } as CFDictionary, nil)
+ guard addStatus == errSecSuccess else { throw StoreError.status(addStatus) }
+ } else if status != errSecSuccess {
+ throw StoreError.status(status)
+ }
+ }
+
+ static func remove(_ account: String) throws {
+ let status = SecItemDelete(try query(account) as CFDictionary)
+ guard status == errSecSuccess || status == errSecItemNotFound else { throw StoreError.status(status) }
+ }
+
+ enum StoreError: LocalizedError {
+ case configuration, status(OSStatus)
+ var errorDescription: String? {
+ "Your credentials could not be accessed securely. Unlock your device and try again."
+ }
+ }
+}
diff --git a/IPv64/Helpers/SharedExtensions.swift b/IPv64/Helpers/SharedExtensions.swift
new file mode 100644
index 0000000..e89f491
--- /dev/null
+++ b/IPv64/Helpers/SharedExtensions.swift
@@ -0,0 +1,17 @@
+//
+// SharedExtensions.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 04.11.25.
+//
+
+import Foundation
+
+extension DateFormatter {
+ nonisolated static let db: DateFormatter = {
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "de_DE")
+ f.dateFormat = "yyyy-MM-dd HH:mm:ss"
+ return f
+ }()
+}
diff --git a/IPv64/HelperViews/SpinnerView.swift b/IPv64/Helpers/Spinner.swift
similarity index 89%
rename from IPv64/HelperViews/SpinnerView.swift
rename to IPv64/Helpers/Spinner.swift
index ee4da7d..5e69619 100644
--- a/IPv64/HelperViews/SpinnerView.swift
+++ b/IPv64/Helpers/Spinner.swift
@@ -1,24 +1,25 @@
//
-// SpinnerView.swift
+// Spinner.swift
// IPv64
//
-// Created by Sebastian Rank on 06.11.22.
+// Created by Sebastian Rank on 20.10.25.
//
+
import SwiftUI
struct Spinner: UIViewRepresentable {
let isAnimating: Bool
let style: UIActivityIndicatorView.Style
let color: UIColor
-
+
func makeUIView(context: UIViewRepresentableContext) -> UIActivityIndicatorView {
let spinner = UIActivityIndicatorView(style: style)
spinner.hidesWhenStopped = true
spinner.color = color
return spinner
}
-
+
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
diff --git a/IPv64/Helpers/Tips.swift b/IPv64/Helpers/Tips.swift
new file mode 100644
index 0000000..451262b
--- /dev/null
+++ b/IPv64/Helpers/Tips.swift
@@ -0,0 +1,21 @@
+//
+// Tips.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 30.10.25.
+//
+
+
+import TipKit
+
+struct HcActionTip: Tip {
+ var title: Text {
+ Text("Swipe for action")
+ }
+ var message: Text? {
+ Text("Swipe on a Healthcheck to do delete or start/pause the Healthcheck")
+ }
+ var image: Image? {
+ Image(systemName: "appwindow.swipe.rectangle")
+ }
+}
diff --git a/IPv64/Helpers/UserStorage.swift b/IPv64/Helpers/UserStorage.swift
new file mode 100644
index 0000000..37272ad
--- /dev/null
+++ b/IPv64/Helpers/UserStorage.swift
@@ -0,0 +1,203 @@
+//
+// UserStorage.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import Foundation
+import Combine
+import SwiftUI
+import WidgetKit
+
+
+
+@MainActor
+public class UserStorage: ObservableObject {
+ class Storage {
+
+ @AppStorage("SHOW_WELCOME_VIEW", store: UserStorage.sharedDefault) var ShowWelcomeView: Bool = true
+ @AppStorage("SHOW_LOGIN_VIEW", store: UserStorage.sharedDefault) var ShowLoginView: Bool = false
+ @AppStorage("ENABLLE_LOCKSCREEN", store: UserStorage.sharedDefault) var EnableLogscreen: Bool = false
+ @AppStorage("SCREENSHOT_PROTECTION", store: UserStorage.sharedDefault) var ScreenshotProtection: Bool = true
+ @AppStorage("IS_INIT_DOMAIN", store: UserStorage.sharedDefault) var IsInitDomain: Bool = false
+ @AppStorage("IN_APP_SWITCHER", store: UserStorage.sharedDefault) var InAppSwitcher: Bool = false
+ @AppStorage("LAST_BUILD_NUMBER", store: UserStorage.sharedDefault) var LAST_BUILD_NUMBER: String = ""
+
+ init() { }
+ }
+
+
+ public static let shared = UserStorage()
+ nonisolated(unsafe) public static let sharedDefault = UserDefaults(suiteName: "group.ipv64.net")
+ private let storage = Storage()
+ @Published var storageError: String?
+ @Published private(set) var sessionID = UUID()
+ private var cachedUsers: [User]?
+ private var isRestoringAfterStorageFailure = false
+ private var isInitializing = true
+
+ var users: [User] {
+ if let cachedUsers { return cachedUsers }
+ var users = (try? JSONDecoder().decode([User].self, from: UserAccounts)) ?? []
+ var needsMigration = false
+ for index in users.indices where users[index].uuid == nil {
+ users[index].uuid = UUID().uuidString
+ needsMigration = true
+ }
+ if needsMigration, let data = try? JSONEncoder().encode(users) { UserAccounts = data }
+ cachedUsers = users
+ return users
+ }
+
+ @Published public var ShowWelcomeView: Bool = true {
+ didSet {
+ storage.ShowWelcomeView = ShowWelcomeView
+ }
+ }
+
+ @Published public var ShowLoginView: Bool = false {
+ didSet {
+ storage.ShowLoginView = ShowLoginView
+ }
+ }
+
+ @Published public var EnableLogscreen: Bool = false {
+ didSet {
+ storage.EnableLogscreen = EnableLogscreen
+ }
+ }
+
+ @Published public var ScreenshotProtection: Bool = true {
+ didSet {
+ storage.ScreenshotProtection = ScreenshotProtection
+ }
+ }
+
+ @Published public var IsInitDomain: Bool = true {
+ didSet {
+ storage.IsInitDomain = IsInitDomain
+ }
+ }
+
+ @Published public var InAppSwitcher: Bool = false {
+ didSet {
+ storage.InAppSwitcher = InAppSwitcher
+ }
+ }
+
+ @Published public var ApiKey: String = "" {
+ didSet {
+ guard ApiKey != oldValue else { return }
+ guard !isRestoringAfterStorageFailure else { return }
+ do {
+ if ApiKey.isEmpty {
+ try SecureStore.remove("API_KEY")
+ } else {
+ try SecureStore.write(ApiKey.data(using: .utf8)!, account: "API_KEY")
+ }
+ UserStorage.sharedDefault?.removeObject(forKey: "API_KEY")
+ sessionID = UUID()
+ } catch {
+ isRestoringAfterStorageFailure = true
+ ApiKey = oldValue
+ isRestoringAfterStorageFailure = false
+ storageError = error.localizedDescription
+ }
+ }
+ }
+
+ @Published public var ApiKeyWidget: String = "" {
+ didSet {
+ guard ApiKeyWidget != oldValue else { return }
+ guard !isRestoringAfterStorageFailure else { return }
+ do {
+ if ApiKeyWidget.isEmpty {
+ try SecureStore.remove("API_KEY_WIDGET")
+ } else {
+ try SecureStore.write(ApiKeyWidget.data(using: .utf8)!, account: "API_KEY_WIDGET")
+ }
+ UserStorage.sharedDefault?.removeObject(forKey: "API_KEY_WIDGET")
+ if !isInitializing {
+ WidgetHealthCacheStore.invalidate()
+ WidgetCenter.shared.reloadAllTimelines()
+ }
+ } catch {
+ isRestoringAfterStorageFailure = true
+ ApiKeyWidget = oldValue
+ isRestoringAfterStorageFailure = false
+ storageError = error.localizedDescription
+ }
+ }
+ }
+
+ @Published public var UserAccounts: Data = "".data(using: .utf8)! {
+ didSet {
+ guard UserAccounts != oldValue else { return }
+ guard !isRestoringAfterStorageFailure else { return }
+ do {
+ try SecureStore.write(UserAccounts, account: "USER_ACCOUNTS")
+ UserStorage.sharedDefault?.removeObject(forKey: "USER_ACCOUNTS")
+ cachedUsers = nil
+ } catch {
+ isRestoringAfterStorageFailure = true
+ UserAccounts = oldValue
+ isRestoringAfterStorageFailure = false
+ storageError = error.localizedDescription
+ }
+ }
+ }
+
+ @Published public var LAST_BUILD_NUMBER: String = "" {
+ didSet {
+ storage.LAST_BUILD_NUMBER = LAST_BUILD_NUMBER
+ }
+ }
+
+ private init() {
+ // Remove legacy values only after each secure write has succeeded.
+ do {
+ for key in ["API_KEY", "API_KEY_WIDGET", "USER_ACCOUNTS"] {
+ let legacy: Data?
+ if key == "USER_ACCOUNTS" {
+ legacy = Self.sharedDefault?.data(forKey: key)
+ } else {
+ legacy = Self.sharedDefault?.string(forKey: key)?.data(using: .utf8)
+ }
+ if let legacy {
+ if try SecureStore.read(key) == nil {
+ try SecureStore.write(legacy, account: key)
+ }
+ Self.sharedDefault?.removeObject(forKey: key)
+ }
+ }
+ ApiKey = try SecureStore.readString("API_KEY")
+ ApiKeyWidget = try SecureStore.readString("API_KEY_WIDGET")
+ UserAccounts = try SecureStore.read("USER_ACCOUNTS") ?? Data()
+ } catch {
+ storageError = error.localizedDescription
+ }
+
+ ShowWelcomeView = storage.ShowWelcomeView
+ ShowLoginView = storage.ShowLoginView
+ EnableLogscreen = storage.EnableLogscreen
+ ScreenshotProtection = storage.ScreenshotProtection
+ IsInitDomain = storage.IsInitDomain
+ InAppSwitcher = storage.InAppSwitcher
+ LAST_BUILD_NUMBER = storage.LAST_BUILD_NUMBER
+ isInitializing = false
+ }
+
+ public func clear() {
+ users.compactMap(\.uuid).forEach(LocalNodeStore.removeOwner)
+ ShowWelcomeView = true
+ ShowLoginView = false
+ EnableLogscreen = false
+ InAppSwitcher = false
+ IsInitDomain = true
+ ApiKey = ""
+ ApiKeyWidget = ""
+ UserAccounts = "".data(using: .utf8)!
+ LAST_BUILD_NUMBER = ""
+ }
+}
diff --git a/IPv64/Helpers/ViewModifiers.swift b/IPv64/Helpers/ViewModifiers.swift
new file mode 100644
index 0000000..9ef350c
--- /dev/null
+++ b/IPv64/Helpers/ViewModifiers.swift
@@ -0,0 +1,34 @@
+//
+// ViewModifiers.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import Foundation
+import SwiftUI
+
+struct LoadingViewModifier: ViewModifier {
+ @Binding var showLoading: Bool
+
+ func body(content: Content) -> some View {
+ content
+ .overlay {
+ if showLoading {
+ LoadingView(blurRadius: 0, bgOpacity: 0.4)
+ .zIndex(10)
+ }
+ }
+ .allowsHitTesting(true)
+ }
+}
+
+struct ColorGradientModifier: ViewModifier {
+ var color: Color
+
+ func body(content: Content) -> some View {
+ content
+ .scrollContentBackground(.hidden)
+ .background(ColorGradient(color: color))
+ }
+}
diff --git a/IPv64/Helpers/WidgetHealthCache.swift b/IPv64/Helpers/WidgetHealthCache.swift
new file mode 100644
index 0000000..9b68244
--- /dev/null
+++ b/IPv64/Helpers/WidgetHealthCache.swift
@@ -0,0 +1,33 @@
+import Foundation
+import CryptoKit
+
+/// What the widget needs of a healthchecks 2.0 check: name plus the state history (newest first, raw `HC2CheckState` values).
+nonisolated struct WidgetCheck: Codable, Hashable, Sendable {
+ let token: String
+ let name: String
+ let states: [String]
+}
+
+nonisolated struct WidgetHealthCachePayload: Codable, Sendable {
+ let account: String
+ let checks: [WidgetCheck]
+ let updatedAt: Date
+}
+
+nonisolated enum WidgetHealthCacheStore {
+ static let suiteName = "group.ipv64.net"
+ static let cacheKey = "HealthCheckCache_Data_v2"
+ static let revisionKey = "HealthCheckCache_Revision"
+
+ static func accountFingerprint() -> String? {
+ guard let key = try? SecureStore.readString("API_KEY_WIDGET"), !key.isEmpty else { return nil }
+ return SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined()
+ }
+
+ static func invalidate() {
+ guard let defaults = UserDefaults(suiteName: suiteName) else { return }
+ defaults.removeObject(forKey: cacheKey)
+ defaults.removeObject(forKey: "HealthCheckCache_Data_v1")
+ defaults.set(UUID().uuidString, forKey: revisionKey)
+ }
+}
diff --git a/IPv64/IPv64.entitlements b/IPv64/IPv64.entitlements
index 373c646..1cf783e 100644
--- a/IPv64/IPv64.entitlements
+++ b/IPv64/IPv64.entitlements
@@ -4,6 +4,8 @@
aps-environment
development
+ keychain-access-groups
+ $(AppIdentifierPrefix)group.ipv64.net
com.apple.security.application-groups
group.ipv64.net
diff --git a/IPv64/IPv64.xcdatamodeld/.xccurrentversion b/IPv64/IPv64.xcdatamodeld/.xccurrentversion
deleted file mode 100644
index edc1a0a..0000000
--- a/IPv64/IPv64.xcdatamodeld/.xccurrentversion
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
- _XCCurrentVersionName
- IPv64.xcdatamodel
-
-
diff --git a/IPv64/IPv64.xcdatamodeld/IPv64.xcdatamodel/contents b/IPv64/IPv64.xcdatamodeld/IPv64.xcdatamodel/contents
deleted file mode 100644
index 9ed2921..0000000
--- a/IPv64/IPv64.xcdatamodeld/IPv64.xcdatamodel/contents
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/IPv64/IPv64App.swift b/IPv64/IPv64App.swift
index 5b9502d..8e47935 100644
--- a/IPv64/IPv64App.swift
+++ b/IPv64/IPv64App.swift
@@ -2,170 +2,71 @@
// IPv64App.swift
// IPv64
//
-// Created by Sebastian Rank on 06.11.22.
+// Created by Sebastian Rank on 18.10.25.
//
import SwiftUI
-import Firebase
-import UserNotifications
-import FirebaseMessaging
-
-
-class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
- let gcmMessageIDKey = "gcm.message_id"
-
- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
- FirebaseApp.configure()
- // [START set_messaging_delegate]
- Messaging.messaging().delegate = self
- // [END set_messaging_delegate]
- // Register for remote notifications. This shows a permission dialog on first run, to
- // show the dialog at a more appropriate time move this registration accordingly.
- // [START register_for_notifications]
- if #available(iOS 10.0, *) {
- // For iOS 10 display notification (sent via APNS)
- UNUserNotificationCenter.current().delegate = self
- let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
- UNUserNotificationCenter.current().requestAuthorization(
- options: authOptions,
- completionHandler: {_, _ in })
- } else {
- let settings: UIUserNotificationSettings =
- UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
- application.registerUserNotificationSettings(settings)
- }
-
- application.registerForRemoteNotifications()
-
- // [END register_for_notifications]
- return true
- }
-
- // MARK: UISceneSession Lifecycle
- func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
- // Called when a new scene session is being created.
- // Use this method to select a configuration to create the new scene with.
- return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
- }
-
- func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) {
- // Called when the user discards a scene session.
- // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
- // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
- }
-
- // [START receive_message]
- func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
- // If you are receiving a notification message while your app is in the background,
- // this callback will not be fired till the user taps on the notification launching the application.
- // TODO: Handle data of notification
- // With swizzling disabled you must let Messaging know about the message, for Analytics
- // Messaging.messaging().appDidReceiveMessage(userInfo)
- // Print message ID.
- if let messageID = userInfo[gcmMessageIDKey] {
- print("Message ID: \(messageID)")
- }
-
- // Print full message.
- print(userInfo)
- //print(userInfo["gcm.notification.fcm_options"])
- }
-
- func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
- fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
- // If you are receiving a notification message while your app is in the background,
- // this callback will not be fired till the user taps on the notification launching the application.
- // TODO: Handle data of notification
- // With swizzling disabled you must let Messaging know about the message, for Analytics
- // Messaging.messaging().appDidReceiveMessage(userInfo)
- // Print message ID.
- if let messageID = userInfo[gcmMessageIDKey] {
- print("Message ID: \(messageID)")
- }
-
- // Print full message.
- print(userInfo)
-
- completionHandler(UIBackgroundFetchResult.newData)
- }
- // [END receive_message]
- func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
- print("Unable to register for remote notifications: \(error.localizedDescription)")
- }
-
- // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
- // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
- // the FCM registration token.
- func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
- print("APNs token retrieved: \(deviceToken)")
-
- // With swizzling disabled you must set the APNs token here.
- Messaging.messaging().apnsToken = deviceToken
- }
-}
-
+import TipKit
@main
struct IPv64App: App {
- @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
- @AppStorage("BIOMETRIC_ENABLED") var isBiometricEnabled: Bool = false
- @State var isBio = false
-
+ @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
+ @State private var session: Session
+ @State private var registrar: PushRegistrar
+ @State private var nodes: ConnectedNodes
+ /// App-wide so unlocking once unlocks every window (iPad multi-window).
+ @StateObject private var biometrics = Biometrics()
+
init() {
- var titleFont = UIFont.preferredFont(forTextStyle: .largeTitle) /// the default large title font
- titleFont = UIFont(
- descriptor:
- titleFont.fontDescriptor
- .withDesign(.rounded)? /// make rounded
- .withSymbolicTraits(.traitBold) /// make bold
- ??
- titleFont.fontDescriptor, /// return the normal title if customization failed
- size: titleFont.pointSize
- )
+ #if DEBUG
+ DebugFixtures.configure() // before ConnectedNodes reads the stored node access
+ #endif
+ let session = Session()
+ _session = State(initialValue: session)
+ _registrar = State(initialValue: PushRegistrar(session: session))
+ _nodes = State(initialValue: ConnectedNodes())
- var smallTitleFont = UIFont.preferredFont(forTextStyle: .body) /// the default large title font
- smallTitleFont = UIFont(
- descriptor:
- smallTitleFont.fontDescriptor
- .withDesign(.rounded)? /// make rounded
- .withSymbolicTraits(.traitBold) /// make bold
- ??
- smallTitleFont.fontDescriptor, /// return the normal title if customization failed
- size: smallTitleFont.pointSize
- )
+ /// Load and configure the state of all the tips of the app
+ try? Tips.configure()
- /// set the rounded font
- UINavigationBar.appearance().largeTitleTextAttributes = [.font: titleFont]
- UINavigationBar.appearance().titleTextAttributes = [.font : smallTitleFont]
+ let appearance = UINavigationBarAppearance()
+ appearance.configureWithDefaultBackground()
- var lastBuildNumber = SetupPrefs.readPreference(mKey: "LASTBUILDNUMBER", mDefaultValue: "0") as! String
- var token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- let lastBuildNumberStandart = SetupPrefs.readPreferenceStandard(mKey: "LASTBUILDNUMBER", mDefaultValue: "0") as! String
- let tokenStandart = SetupPrefs.readPreferenceStandard(mKey: "APIKEY", mDefaultValue: "") as! String
+ // Large Title (z. B. auf Listenansichten)
+ let largeDesc = UIFontDescriptor
+ .preferredFontDescriptor(withTextStyle: .largeTitle)
+ .withDesign(.rounded) ?? UIFontDescriptor.preferredFontDescriptor(withTextStyle: .largeTitle)
+ appearance.largeTitleTextAttributes = [
+ .font: UIFont(descriptor: largeDesc, size: 0) // 0 = system size aus Descriptor (Dynamic Type)
+ ]
- if (token.isEmpty) {
- token = tokenStandart
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: token)
- }
- if (lastBuildNumber.isEmpty || lastBuildNumber == "0") {
- lastBuildNumber = lastBuildNumberStandart
- SetupPrefs.setPreference(mKey: "LASTBUILDNUMBER", mValue: lastBuildNumber)
+ // Inline Title (z. B. Detailansichten)
+ let inlineDesc = UIFontDescriptor
+ .preferredFontDescriptor(withTextStyle: .headline)
+ .withDesign(.rounded) ?? UIFontDescriptor.preferredFontDescriptor(withTextStyle: .headline)
+ appearance.titleTextAttributes = [
+ .font: UIFont(descriptor: inlineDesc, size: 0)
+ ]
+
+ UINavigationBar.appearance().standardAppearance = appearance
+ UINavigationBar.appearance().scrollEdgeAppearance = appearance
+ UINavigationBar.appearance().compactAppearance = appearance
+ UserStorage.shared.IsInitDomain = true
+
+ if (UserStorage.shared.ApiKeyWidget.count == 0 && !User.empty.list.isEmpty) {
+ UserStorage.shared.ApiKeyWidget = User.empty.list.first!.ApiKey
}
}
var body: some Scene {
WindowGroup {
- let apikey = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
-
- if (apikey.count == 0) {
- LoginView()
- } else {
- if isBiometricEnabled {
- LockView()
- } else {
- TabbView(showDomains: .constant(true))
- }
- }
+ ContentView()
+ .fontDesign(.rounded)
+ .environment(session)
+ .environment(registrar)
+ .environment(nodes)
+ .environmentObject(biometrics)
+ .task { appDelegate.registrar = registrar }
}
}
}
diff --git a/IPv64/Info.plist b/IPv64/Info.plist
deleted file mode 100644
index 38c511a..0000000
--- a/IPv64/Info.plist
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
- CFBundleURLTypes
-
-
- CFBundleTypeRole
- Editor
- CFBundleURLName
- openWidget
- CFBundleURLSchemes
-
- ipv64
-
-
-
- NSUserActivityTypes
-
- ConfigurationFourIntent
- ConfigurationIntent
-
- UIBackgroundModes
-
- fetch
- remote-notification
-
-
-
diff --git a/IPv64/Main/.DS_Store b/IPv64/Main/.DS_Store
deleted file mode 100644
index d177b01..0000000
Binary files a/IPv64/Main/.DS_Store and /dev/null differ
diff --git a/IPv64/Main/Account/.DS_Store b/IPv64/Main/Account/.DS_Store
deleted file mode 100644
index ac44236..0000000
Binary files a/IPv64/Main/Account/.DS_Store and /dev/null differ
diff --git a/IPv64/Main/Account/AccountListView.swift b/IPv64/Main/Account/AccountListView.swift
deleted file mode 100644
index a1913a3..0000000
--- a/IPv64/Main/Account/AccountListView.swift
+++ /dev/null
@@ -1,177 +0,0 @@
-//
-// AccountListView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 28.09.23.
-//
-
-import SwiftUI
-
-struct AccountListView: View {
- @AppStorage("AccountList") var accountListJson: String = ""
- @AppStorage("DomainResult") var listOfDomainsString: String = ""
- @AppStorage("IntegrationList") var integrationListS: String = ""
- @AppStorage("HealthcheckList") var healthCheckList: String = ""
-
- @Environment(\.presentationMode) var presentationMode
-
- @Binding var isBottomSheetVisible: Bool
- @Binding var accountList: [Account]
- @Binding var newAccountB: Bool
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State private var selectedAccount: Account? = nil
- @State private var deleteAccount: Bool = false
-
- fileprivate func deleteAccountDialog() {
- errorTyp = ErrorTypes.deleteAccount
- activeSheet = .error
- print(errorTyp)
- }
-
- var body: some View {
- VStack {
- Form {
- Section("Deine Accounts") {
- ForEach(accountList, id: \.ApiKey) { acc in
- let dateDate = dateDBFormatter.date(from: acc.Since ?? "0001-01-01 00:00:00")
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- Button(action: {
- let beforeAccInt = accountList.firstIndex { $0.Active == true }
- if (beforeAccInt! > -1) {
- accountList[beforeAccInt!].Active = false
- }
- let currentAccInd = accountList.firstIndex { $0.ApiKey == acc.ApiKey }
- if (currentAccInd! > -1) {
- accountList[currentAccInd!].Active = true
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: accountList[currentAccInd!].ApiKey)
- }
- do {
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(accountList)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountListJson = json!
- } catch let error {
- print(error)
- }
- listOfDomainsString = ""
- integrationListS = ""
- healthCheckList = ""
- presentationMode.wrappedValue.dismiss()
- }) {
- HStack {
- Image(systemName: acc.Active! ? "checkmark.circle.fill" : "circle")
- .resizable()
- .scaledToFit()
- .foregroundStyle(Color("ip64_color"))
- .frame(width: 22, height: 22)
- .padding(.trailing)
- VStack(alignment: .leading) {
- Text(acc.AccountName!)
- .foregroundStyle(Color("primaryText"))
- Text(dateString)
- .font(.system(.subheadline, design: .rounded))
- .foregroundColor(Color("accountSinceColor"))
- }
-
- }
- }
- .listRowBackground(acc.Active! ? Color("AccountSelectionBG") : Color("SectionBG"))
- .swipeActions(edge: .trailing) {
- if (!acc.Active!) {
- Button(role: .destructive, action: {
- print("delete")
- selectedAccount = acc
- deleteAccountDialog()
- }) {
- Label("Löschen", systemImage: "trash")
- }
- .tint(.red)
- }
- }
- }
- }
- Button(action: {
- withAnimation {
- newAccountB = true
- isBottomSheetVisible = false
-// presentationMode.wrappedValue.dismiss()
- }
- }) {
- HStack {
- Image(systemName: "plus.circle")
- .resizable()
- .scaledToFit()
- .foregroundStyle(Color("ip64_color"))
- .frame(width: 32, height: 32)
- .padding(.trailing)
- VStack(alignment: .leading) {
- Text("Neuen Account hinzufügen")
- .foregroundStyle(Color("primaryText"))
- }
-
- }
- .padding(.vertical, 10)
- }
- }
- .scrollIndicators(.hidden)
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: $deleteAccount)
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountListJson.data(using: .utf8)
- var accountList = try jsonDecoder.decode([Account].self, from: jsonData!)
-
- if (deleteAccount) {
- print(selectedAccount)
- let indSel = accountList.firstIndex { $0.ApiKey == selectedAccount?.ApiKey }
- print(indSel)
- if indSel! > -1 {
- accountList.remove(at: indSel!)
- }
- self.accountList = accountList
-
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(accountList)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountListJson = json!
- }
- } catch let error {
- print(error)
- }
- }
- default:
- EmptyView()
- }
- }
-
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .medium
- formatter.timeStyle = .none
- formatter.locale = Locale(identifier: "de_DE")
- return formatter
- }()
-
- private let dateDBFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
- return formatter
- }()
-}
-
-#Preview {
- AccountListView(isBottomSheetVisible: .constant(false), accountList: .constant([]), newAccountB: .constant(false))
-}
diff --git a/IPv64/Main/Account/AccountView.swift b/IPv64/Main/Account/AccountView.swift
deleted file mode 100644
index 3c206cd..0000000
--- a/IPv64/Main/Account/AccountView.swift
+++ /dev/null
@@ -1,290 +0,0 @@
-//
-// AccountView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 25.11.22.
-//
-
-import SwiftUI
-import Toast
-
-struct AccountView: View {
-
- @AppStorage("AccountInfos") var accountInfosJson: String = ""
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State var accountInfos: AccountInfo = AccountInfo()
- @State var showDynHash = false
- @State var showApiKey = false
- @State var showDevToken = false
-
- var body: some View {
- ZStack {
- VStack {
- let dateDate = dateDBFormatter.date(from: accountInfos.reg_date ?? "0001-01-01 00:00:00")
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- let apiLimit = thousendSeperator.string(from: (accountInfos.account_class?.api_limit! ?? Int(0 as NSNumber)) as NSNumber)
- let apiUpdates = thousendSeperator.string(from: (accountInfos.api_updates ?? Int(0 as NSNumber)) as NSNumber)
- Form {
- Section("") {
- Group {
- HStack {
- Text("Account Status")
- Spacer()
- Text("Aktiviert")
- .foregroundColor(.green)
- }
- HStack {
- Text("Account Klasse")
- Spacer()
- Text(accountInfos.account_class?.class_name ?? "")
- .foregroundColor(.yellow)
- }
- HStack {
- Text("E-Mail")
- Spacer()
- Text(accountInfos.email ?? "")
- .foregroundColor(.gray)
- }
- HStack {
- Text("Registriert seit")
- Spacer()
- Text(dateString)
- .foregroundColor(.gray)
- }
- }
- Group {
- let subDom = accountInfos.dyndns_subdomains ?? 0
- let subDomMax = accountInfos.account_class?.dyndns_domain_limit ?? 0
- HStack {
- Text("Dyn Domains")
- Spacer()
- Text("\(subDom) / \(subDomMax)")
- .foregroundColor(GetColor(cur: subDom, max: subDomMax))
- }
- let mDomains = accountInfos.owndomains ?? 0
- let mDomainsMax = accountInfos.account_class?.owndomain_limit ?? 0
- HStack {
- Text("Domains")
- Spacer()
- Text("\(mDomains) / \(mDomainsMax)")
- .foregroundColor(GetColor(cur: mDomains, max: mDomainsMax))
- }
- let dynUp = accountInfos.dyndns_updates ?? 0
- let dynUpMax = accountInfos.account_class?.dyndns_update_limit ?? 0
- HStack {
- Text("DynDNS Update Limit / 24h")
- Spacer()
- Text("\(dynUp) / \(dynUpMax)")
- .foregroundColor(GetColor(cur: dynUp, max: dynUpMax))
- }
- }
- Group {
- let health = accountInfos.healthchecks ?? 0
- let healthMax = accountInfos.account_class?.healthcheck_limit ?? 0
- HStack {
- Text("Healthchecks")
- Spacer()
- Text("\(health) / \(healthMax)")
- .foregroundColor(GetColor(cur: health, max: healthMax))
- }
- let healthup = accountInfos.healthchecks_updates ?? 0
- let healthupMax = accountInfos.account_class?.healthcheck_update_limit ?? 0
- HStack {
- Text("Healthcheck Updates")
- Spacer()
- Text("\(healthup) / \(healthupMax)")
- .foregroundColor(GetColor(cur: healthup, max: healthupMax))
- }
- HStack {
- Text("API Limit / 24h")
- Spacer()
- Text("\(apiUpdates ?? "0") / \((apiLimit == "0" ? "∞" : apiLimit) ?? "0")")
- .foregroundColor(GetColor(cur: accountInfos.api_updates ?? 0, max: accountInfos.account_class?.api_limit ?? 0))
- }
- let sms = accountInfos.sms_count ?? 0
- let smsMax = accountInfos.account_class?.sms_limit ?? 0
- HStack {
- Text("SMS Limit")
- Spacer()
- Text("\(sms) / \(smsMax)")
- .foregroundColor(GetColor(cur: sms, max: smsMax))
- }
- }
- Group {
- Button(action: {
- withAnimation {
- showDynHash.toggle()
- }
- }) {
- HStack {
- if (showDynHash) {
- Text(accountInfos.update_hash ?? "HASH")
- .multilineTextAlignment(.trailing)
- .foregroundColor(.gray)
- } else {
- Text("DynDNS Updatehash")
- Spacer()
- Text("••••••")
- .foregroundColor(.gray)
- }
- }
- }
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "Kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = accountInfos.update_hash ?? "HASH"
- }) {
- Label("Kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- .tint(Color("primaryText"))
- Button(action: {
- withAnimation {
- showApiKey.toggle()
- }
- }) {
- HStack {
- if (showApiKey) {
- Text(accountInfos.api_key ?? "API KEY")
- .multilineTextAlignment(.trailing)
- .foregroundColor(.gray)
- } else {
- Text("API Key")
- Spacer()
- Text("••••••")
- .foregroundColor(.gray)
- }
- }
- }
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "Kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = accountInfos.api_key ?? "API KEY"
- }) {
- Label("Kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- .tint(Color("primaryText"))
- }
- }
- }
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
-
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- .onAppear {
- GetAccountInfos()
- }
- .navigationTitle("Account Status")
- }
-
- fileprivate func GetAccountInfos() {
- Task {
- accountInfos = await api.GetAccountStatus() ?? AccountInfo()
- let status = accountInfos.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && accountInfos.email == nil) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(accountInfos)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountInfosJson = json!
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (errorTyp?.status == 401) {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- } else {
- GetAccountInfos()
- }
- }
- default:
- EmptyView()
- }
- }
-
- fileprivate func GetColor(cur: Int, max: Int) -> Color {
-
- if (cur == max) {
- return .red
- }
-
- return .green
- }
-
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .medium
- formatter.timeStyle = .none
- formatter.locale = Locale(identifier: "de_DE")
- return formatter
- }()
-
- private let dateDBFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
- return formatter
- }()
-
- private let thousendSeperator: NumberFormatter = {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.groupingSeparator = "."
- return formatter
- }()
-}
-
-struct AccountView_Previews: PreviewProvider {
- static var previews: some View {
- AccountView()
- }
-}
diff --git a/IPv64/Main/Account/HelpView.swift b/IPv64/Main/Account/HelpView.swift
deleted file mode 100644
index 24939d2..0000000
--- a/IPv64/Main/Account/HelpView.swift
+++ /dev/null
@@ -1,86 +0,0 @@
-//
-// HelpView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 07.11.22.
-//
-
-import SwiftUI
-
-struct HelpView: View {
- @Environment(\.openURL) var openURL
-
- @ObservedObject var api: NetworkServices = NetworkServices()
-
- var body: some View {
- VStack {
- Form() {
- Section("Hilfe") {
- HStack(alignment: .center) {
- Image(systemName: "circle.fill")
- .resizable()
- .scaledToFill()
- .foregroundColor(.red)
- .frame(width: 8, height: 8)
- Text("A-Record stimmt nicht überein!")
- }
- .frame(alignment: .center)
- HStack(alignment: .center) {
- Image(systemName: "circle.fill")
- .resizable()
- .scaledToFill()
- .foregroundColor(.green)
- .frame(width: 8, height: 8)
- Text("A-Record stimmt überein!")
- }
- .frame(alignment: .center)
- }
- Section("Was ist IPv64.net?") {
- Text("**IPv64** ist natürlich kein neues Internet-Protokoll (64), sondern einfach eine deduplizierte Kurzform von IPv6 und IPv4. Auf der Seite von IPv64 findest du einen **Dynamischen DNS** Dienst (DynDNS) und viele weitere nützliche Tools für dein tägliches Interneterlebnis. \n\nMit dem **dynamischen DNS Dienst** von IPv64 kannst du dir kostenfreie Subdomains registrieren und nutzen. Das Update der Domain übernimmt voll automatisch dein eigener Router oder alternative Hardware / Software. \n\nÜber den Youtube Kanal RaspberryPi Cloud wirst du ganz sicher noch viel mehr über die Welt der IT kennenlernen dürfen.")
- Button(action: {
- openURL(URL(string: "https://www.youtube.com/c/RaspberryPiCloud")!)
- }) {
- HStack {
- Image(systemName: "play.rectangle.fill")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(.red)
- Text("YouTube")
- .foregroundColor(.red)
- }
- }
- }
- Section("Kontakt") {
- Text("Ein Produkt der Prox IT UG (haftungsbeschränkt). \n\n**Angaben gemäß § 5 TMG**\nProx IT UG (haftungsbeschränkt)\nAm Eisenstein 10\n45470 Mülheim an der Ruhr\n\n**Vertreten durch**\nDennis Schröder (Geschäftsführer)\n\nRegistergericht: Amtsgericht Duisburg\nRegisternummer: HRB 35106")
- Button(action: {
- openURL(URL(string: "mailto:info@ipv64.net")!)
- }) {
- HStack {
- Image(systemName: "envelope.fill")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- Text("info@ipv64.net")
- .tint(Color("primaryText"))
- }
- }
- .foregroundColor(Color("primaryText"))
- }
- Section("Über diese App ") {
- Text("Diese App ist mithilfe der Community von RaspberryPi Cloud entstanden. \nAlle Rechte vorbehalten, bei Dennis Schröder.")
- HStack {
- Text("Version")
- Spacer()
- Text(Bundle.main.versionNumber)
- .foregroundColor(.gray)
- }
- }
- }
- .navigationTitle("Über")
- }
- }
-}
-
-struct HelpView_Previews: PreviewProvider {
- static var previews: some View {
- HelpView()
- }
-}
diff --git a/IPv64/Main/Account/IPView.swift b/IPv64/Main/Account/IPView.swift
deleted file mode 100644
index 5bd37b5..0000000
--- a/IPv64/Main/Account/IPView.swift
+++ /dev/null
@@ -1,91 +0,0 @@
-//
-// IPView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 25.11.22.
-//
-
-import SwiftUI
-import Toast
-
-struct IPView: View {
-
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var myIP: MyIP = MyIP(ip: "")
- @State var myIPV6: MyIP = MyIP(ip: "")
-
- var body: some View {
-
- Form {
- Section("IPv4") {
- if (myIP.ip?.count == 0) {
- Spinner(isAnimating: true, style: .medium, color: .white)
- } else {
- Text(myIP.ip!)
- .lineLimit(1)
- .minimumScaleFactor(0.01)
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "IPv4 kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = myIP.ip! ?? "0.0.0.0"
- }) {
- Label("IPv4 kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- }
- }
- Section("IPv6") {
- if (myIPV6.ip?.count == 0) {
- Spinner(isAnimating: true, style: .medium, color: .white)
- } else {
- Text(myIPV6.ip!)
- .lineLimit(1)
- .minimumScaleFactor(0.01)
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "IPv6 kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = myIPV6.ip! ?? "0.0.0.0"
- }) {
- Label("IPv6 kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- }
- }
- }
- .onAppear {
- Task {
- myIP = await api.GetMyIP() ?? MyIP(ip: "0.0.0.0")
- myIPV6 = await api.GetMyIPV6() ?? MyIP(ip: "0.0.0.0")
- }
- }
- .navigationTitle("Meine IP")
- }
-}
-
-struct IPView_Previews: PreviewProvider {
- static var previews: some View {
- IPView()
- }
-}
diff --git a/IPv64/Main/Account/Items/LogItemView.swift b/IPv64/Main/Account/Items/LogItemView.swift
deleted file mode 100644
index ccf84fd..0000000
--- a/IPv64/Main/Account/Items/LogItemView.swift
+++ /dev/null
@@ -1,71 +0,0 @@
-//
-// LogItemView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 25.11.22.
-//
-
-import SwiftUI
-
-struct LogItemView: View {
-
- @State var log: MyLogs
-
- var body: some View {
- let dateDate = dateDBFormatter.date(from: log.time!)
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- Button(action: {
- print(log)
- withAnimation {
- log.expandLog.toggle()
- }
- }) {
- VStack {
- HStack {
- Text(log.subdomain!)
- .font(.system(.caption, design: .rounded))
- Spacer()
- Text(dateString)
- .font(.system(.caption, design: .rounded))
- }
- .padding(.bottom, 2)
- VStack(alignment: .leading, spacing: 0) {
- Text(log.header!)
- .font(.system(.headline, design: .rounded))
- .padding(.bottom, 2)
- .frame(maxWidth: .infinity, alignment: .leading)
- if (log.expandLog) {
- Text(log.content!)
- .multilineTextAlignment(.leading)
- .frame(maxWidth: .infinity, alignment: .leading)
- } else {
- Text(log.content!)
- .lineLimit(1)
- .multilineTextAlignment(.leading)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- }
- }
- .foregroundStyle(Color("primaryText"))
- }
- }
-
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .medium
- formatter.timeStyle = .medium
- formatter.locale = Locale(identifier: "de_DE")
- return formatter
- }()
-
- private let dateDBFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
- return formatter
- }()
-}
-
-#Preview {
- LogItemView(log: MyLogs(subdomain: "mesr.ipv64.net", time: "2022-11-25 15:12:16", header: "Record hinzugefügt", content: "DNS Record (A) für mesr.ipv64.net hinzugefügt. jhasiufjajsdnjcn ijsidncdnsciun "))
-}
diff --git a/IPv64/Main/Account/LogView.swift b/IPv64/Main/Account/LogView.swift
deleted file mode 100644
index ae4774e..0000000
--- a/IPv64/Main/Account/LogView.swift
+++ /dev/null
@@ -1,99 +0,0 @@
-//
-// LogView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 25.11.22.
-//
-
-import SwiftUI
-
-struct LogView: View {
-
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var myLogs: [MyLogs] = []
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State private var showAllLogs = false
- @State private var btnTxt = ""
- @State private var myCustomLogs: [MyLogs] = []
-
- var body: some View {
- ZStack {
- VStack {
- Form {
- Section("Letzten \(myCustomLogs.count) Logs") {
- ForEach(myCustomLogs, id: \.id) { log in
- LogItemView(log: log)
- }
- }
-
- Button(action: {
- withAnimation {
- showAllLogs.toggle()
- editLogs()
- }
- }) {
- Text(btnTxt)
- .font(.system(.callout, design: .rounded))
- .textCase(.uppercase)
- .foregroundColor(Color("ip64_color"))
- }
- }
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
-
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- .onAppear {
- GetLogs()
- }
- .navigationTitle("Logs")
- }
-
- fileprivate func editLogs() {
- if (showAllLogs) {
- btnTxt = "Zeige 10 Logs an"
- myCustomLogs = myLogs
- } else {
- btnTxt = "Zeige \(myLogs.count) Logs an"
- myCustomLogs = Array(myLogs.prefix(10))
- }
- }
-
- fileprivate func GetLogs() {
- Task {
- myLogs = await api.GetLogs()?.logs ?? Logs(logs: []).logs!
- editLogs()
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (errorTyp?.status == 401) {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- } else {
- GetLogs()
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-#Preview {
- LogView()
-}
diff --git a/IPv64/Main/Account/ProfilView.swift b/IPv64/Main/Account/ProfilView.swift
deleted file mode 100644
index 718dcf9..0000000
--- a/IPv64/Main/Account/ProfilView.swift
+++ /dev/null
@@ -1,231 +0,0 @@
-//
-// ProfilView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 25.11.22.
-//
-
-import SwiftUI
-import Introspect
-
-struct ProfilView: View {
-
- @AppStorage("NEW_ACCOUNT") var newAccount = false
- @AppStorage("AccountInfos") var accountInfos: String = ""
- @AppStorage("DomainResult") var listOfDomainsString: String = ""
- @AppStorage("BIOMETRIC_ENABLED") var isBiometricEnabled: Bool = false
- @AppStorage("ENABLE_NAV_SOUND") var enableNavSound: Bool = true
- @AppStorage("IntegrationList") var integrationListS: String = ""
- @AppStorage("HealthcheckList") var healthCheckList: String = ""
- @AppStorage("current_Tab") var selectedTab: Tab = .domains
- @AppStorage("AccountList") var accountListJson: String = ""
-
- @Environment(\.openURL) var openURL
-
- @Binding var popToRootTab: Tab
- @State var showLoginView = false
- @State var enableBio = false
- @State var enableNavSou = true
- @State var accountList: [Account] = []
- @State var activeAccount: Account = Account()
-
- @State private var loadUser = false
- @State private var isBottomSheetVisible = false
- @State private var newAccountB = false
-
- @ObservedObject private var bio = Biometrics()
-
- var body: some View {
- ZStack {
- VStack {
- NavigationView {
- Form {
- Section {
- Button(action: {
- withAnimation {
- self.isBottomSheetVisible.toggle()
- }
- }) {
- let dateDate = dateDBFormatter.date(from: activeAccount.Since ?? "0001-01-01 00:00:00")
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- HStack {
- VStack {
- Image(systemName: "person.circle")
- .resizable()
- .scaledToFill()
- .frame(width: 50, height: 50)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .frame(width: 50, height: 50)
- .cornerRadius(50)
- VStack {
- Text(activeAccount.AccountName ?? "")
- .font(.system(.headline, design: .rounded))
- .frame(maxWidth: .infinity, alignment: .leading)
- Text(dateString)
- .font(.system(.subheadline, design: .rounded))
- .foregroundColor(Color("accountSinceColor"))
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- .padding(.leading)
- }
- .redacted(reason: loadUser ? .placeholder : .init())
- }
- }
- Section("Allgemein") {
- NavigationLink("Account Status", destination: AccountView())
- NavigationLink("Logs", destination: LogView())
- NavigationLink("Meine IP", destination: IPView())
- Button(action: { withAnimation { enableNavSou.toggle() } }) {
- HStack {
- Text("Tabsound")
- Spacer()
- Toggle("", isOn: $enableNavSou)
- .labelsHidden()
- .tint(Color("ip64_color"))
- .onChange(of: enableNavSou) { isSoundEnabled in
- withAnimation {
- enableNavSound = isSoundEnabled
- }
- }
- }
- }
- .tint(Color("primaryText"))
- }
- Section("Sicherheit") {
- Button(action: { withAnimation { enableBio.toggle() } }) {
- HStack {
- Text("Bildschirmsperre \(enableBio ? "deaktivieren" : "aktivieren")")
- Spacer()
- Toggle("", isOn: $enableBio)
- .labelsHidden()
- .tint(Color("ip64_color"))
- .onChange(of: enableBio) { isBio in
- withAnimation {
- isBiometricEnabled = isBio
- }
- }
- }
- }
- .tint(Color("primaryText"))
- }
- Section("Sonstiges") {
- NavigationLink("Über", destination: HelpView())
- Button(action: {
- openURL(URL(string: "https://www.youtube.com/c/RaspberryPiCloud")!)
- }) {
- Text("YouTube")
- }
- .tint(Color("primaryText"))
- Button(action: {
- openURL(URL(string: "https://discord.gg/rpicloud")!)
- }) {
- Text("Discord")
- }
- .tint(Color("primaryText"))
- }
- Section {
- Button(action: {
- let apikey = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var delAccountInd = accountList.firstIndex(where: { $0.ApiKey! == apikey})
-
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- SetupPrefs.setPreference(mKey: "LASTBUILDNUMBER", mValue: "0")
- SetupPrefs.setPreference(mKey: "DEVICETOKEN", mValue: "")
- accountInfos = ""
- listOfDomainsString = ""
- isBiometricEnabled = false
- integrationListS = ""
- healthCheckList = ""
- selectedTab = .domains
- withAnimation {
- showLoginView.toggle()
- }
- }) {
- Text("Logout")
- .foregroundColor(.red)
- }
- }
- .listRowBackground(Color.red.opacity(0.15))
- }
- .navigationTitle(Tab.profile.labelName)
- .onAppear {
- newAccount = false
- enableBio = isBiometricEnabled
- enableNavSou = enableNavSound
- loadUser = true
- if (!accountListJson.isEmpty) {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountListJson.data(using: .utf8)
- accountList = try jsonDecoder.decode([Account].self, from: jsonData!)
- activeAccount = accountList.first { $0.Active == true}!
- } catch {
- print("ERROR \(error.localizedDescription)")
- }
- loadUser = false
- } else {
- activeAccount = Account(ApiKey: "", AccountName: "Need to be Init!", DeviceToken: "", Since: "", Active: true)
- loadUser = false
- }
- }
- }
- .introspectNavigationController { navigationController in
- navigationController.splitViewController?.preferredPrimaryColumnWidthFraction = 1
- navigationController.splitViewController?.maximumPrimaryColumnWidth = 400
- }
- .accentColor(Color("AccentColor"))
- }
- .fullScreenCover(isPresented: $showLoginView) {
- LoginView()
- }.sheet(isPresented: $isBottomSheetVisible) {
- AccountListView(isBottomSheetVisible: $isBottomSheetVisible, accountList: $accountList, newAccountB: $newAccountB)
- .onDisappear {
- if (!accountListJson.isEmpty) {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountListJson.data(using: .utf8)
- accountList = try jsonDecoder.decode([Account].self, from: jsonData!)
- activeAccount = accountList.first { $0.Active == true}!
- print(accountList)
- print(activeAccount)
- } catch {
- print("ERROR \(error.localizedDescription)")
- }
- newAccount = newAccountB
- if (newAccount) {
- showLoginView = true
- }
- loadUser = false
- } else {
- activeAccount = Account(ApiKey: "", AccountName: "Need to be Init!", DeviceToken: "", Since: "", Active: true)
- loadUser = false
- }
- }
- .presentationDetents([.fraction(0.25), .medium])
- .presentationDragIndicator(.hidden)
- }
- }
- }
-
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .medium
- formatter.timeStyle = .none
- formatter.locale = Locale(identifier: "de_DE")
- return formatter
- }()
-
- private let dateDBFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
- return formatter
- }()
-}
-
-
-#Preview {
- ProfilView(popToRootTab: .constant(.other))
-}
diff --git a/IPv64/Main/Blocklist/BlocklistView.swift b/IPv64/Main/Blocklist/BlocklistView.swift
deleted file mode 100644
index 6162d5c..0000000
--- a/IPv64/Main/Blocklist/BlocklistView.swift
+++ /dev/null
@@ -1,168 +0,0 @@
-//
-// BlocklistView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 08.08.23.
-//
-
-import SwiftUI
-
-struct BlocklistView: View {
-
- @Binding var popToRootTab: Tab
-
- @ObservedObject var api: NetworkServices = NetworkServices()
-
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
-
- @State private var blockerNodeList: BlockerNodeResults = .empty
- @State private var selectedBlockerNodeId = ""
- @State private var badIp = ""
- @State private var badPort = ""
- @State private var badInfo = ""
- @State private var badCategory = 0
- @State private var showLoginView = false
-
- var body: some View {
- NavigationView {
- ZStack {
- VStack {
- Form {
- Section("IP - Adresse Reporten") {
- Picker(selection: $selectedBlockerNodeId, label: Text("Blocker Node*")
- .font(.system(.callout))
- .padding(.horizontal, 5)) {
- ForEach(blockerNodeList.blockers, id: \.blocker_id) { b in
- let name = b.name!
- let blocker_id = b.blocker_id!
- Text(name)
- .tag(blocker_id)
- .id(blocker_id)
- }
- }
- TextField("IP Adresse*", text: $badIp)
- TextField("Port", text: $badPort)
- Picker(selection: $badCategory, label: Text("Kategorie*")
- .font(.system(.callout))
- .padding(.horizontal, 5)) {
- ForEach(0 ..< badNodeCategory.count) {
- Text(badNodeCategory[$0].text!)
- .tag(badNodeCategory[$0].id! - 1)
- }
- }
- TextField("Information", text: $badInfo)
- }
-
- Text("* benötigte Informationen")
- .bold()
- }
- }
- .tint(Color("ip64_color"))
- .navigationTitle(Tab.blocklist.labelName)
- .toolbar {
- ToolbarItem {
- Button(action: {
- if (badIp.count > 0) {
- let poisonedIp = PoisonedIP(blocker_id: selectedBlockerNodeId, report_ip: badIp, port: badPort, category: "\(badCategory+1)", info: badInfo)
- Task {
- let res = await api.PostPoisonedIP(poisonedIp: poisonedIp)
- print(res)
- if (res?.info == "success") {
- activeSheet = .error
- errorTyp = ErrorTypes.poisonedIpSuccesfully
- if (!blockerNodeList.blockers.isEmpty) {
- selectedBlockerNodeId = blockerNodeList.blockers[0].blocker_id!
- }
- badIp = ""
- badPort = ""
- badCategory = 0
- badInfo = ""
- } else if (res?.info == "error") {
- activeSheet = .error
- errorTyp = ErrorTypes.poisonedIpError
- } else if (res?.info == "Updateintervall overcommited") {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- }
- }
- }
- }) {
- Image(systemName: "paperplane")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
-// if api.isLoading {
-// VStack() {
-// Spinner(isAnimating: true, style: .large, color: .white)
-// }
-// .frame(maxWidth: .infinity, maxHeight: .infinity)
-// .background(Color.black.opacity(0.3).ignoresSafeArea())
-// }
- }
- .onAppear {
- loadBlockerNodes()
- }
- .fullScreenCover(isPresented: $showLoginView) {
- LoginView()
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- }
- }
-
- fileprivate func loadBlockerNodes() {
- Task {
- let response = await api.GetBlockerNodes()
- let status = response?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && response?.blockers == nil) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- blockerNodeList = response!
- if (!blockerNodeList.blockers.isEmpty) {
- selectedBlockerNodeId = blockerNodeList.blockers[0].blocker_id!
- }
- print(selectedBlockerNodeId)
- print(response)
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (errorTyp?.status == 401) {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- withAnimation {
- showLoginView.toggle()
- }
- } else {
- loadBlockerNodes()
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-#Preview {
- BlocklistView(popToRootTab: .constant(.other))
-}
diff --git a/IPv64/Main/Domains/.DS_Store b/IPv64/Main/Domains/.DS_Store
deleted file mode 100644
index ab3b92d..0000000
Binary files a/IPv64/Main/Domains/.DS_Store and /dev/null differ
diff --git a/IPv64/Main/Domains/ContentView.swift b/IPv64/Main/Domains/ContentView.swift
deleted file mode 100644
index 97aee59..0000000
--- a/IPv64/Main/Domains/ContentView.swift
+++ /dev/null
@@ -1,328 +0,0 @@
-//
-// ContentView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 06.11.22.
-//
-
-import SwiftUI
-import CoreData
-import Introspect
-import Toast
-
-struct ContentView: View {
-
- @AppStorage("AccountInfos") var accountInfos: String = ""
- @AppStorage("DomainResult") var listOfDomainsString: String = ""
-
- @Environment(\.presentationMode) var presentationMode
-
- @Binding var popToRootTab: Tab
-
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var myIP: MyIP = MyIP(ip: "")
- @State var myIPV6: MyIP = MyIP(ip: "")
- @State var listOfDomains: DomainResult = DomainResult()
- @State var listDomains: [DomainItems] = []
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State var showSheet = false
- @State var delDomain = ""
- @State var deleteThisDomain = false
- @State var deleteThisDNSRecord: Bool = false
- @State var showLoginView = false
- @State private var isNewItem = false
-
- fileprivate func loadAccountInfos() {
- Task {
- do {
- let response = await api.GetAccountStatus()
- if (response == nil) {
- throw NetworkError.NoNetworkConnection
- }
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(response)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountInfos = json!
- } catch let error {
- print(error)
- activeSheet = .error
- errorTyp = ErrorTypes.websiteRequestError
- }
- }
- }
-
- fileprivate func loadDomains(isRefresh: Bool) {
- do {
- api.isLoading = true
- if (isRefresh || listOfDomainsString.isEmpty) {
- Task {
- let response = await api.GetDomains()
- let status = response?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && response?.subdomains == nil) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- listOfDomains = response!
- }
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(response)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- listOfDomainsString = json!
- //loadAccountInfos()
- prepareToNormalList()
- }
- } else {
- let jsonDecoder = JSONDecoder()
- let jsonData = listOfDomainsString.data(using: .utf8)
- listOfDomains = try jsonDecoder.decode(DomainResult.self, from: jsonData!)
-
- prepareToNormalList()
- }
- } catch let error {
- print(error)
- activeSheet = .error
- errorTyp = ErrorTypes.websiteRequestError
- }
- loadIpAddress()
- }
-
- fileprivate func prepareToNormalList() {
- listDomains = []
- listOfDomains.subdomains?.forEach { domain in
- var isDomaindAdded = false
- dynDomainList.forEach { dynDomain in
- if (domain.key.contains(dynDomain)) {
- var domInd = listDomains.firstIndex(where: { $0.name == dynDomain })
- if (domInd == nil) {
- var domval: Domain = domain.value
- domval.name = domain.key
- var dom = DomainItems(name: dynDomain, list: [domval])
- listDomains.append(dom)
- } else {
- var domval: Domain = domain.value
- domval.name = domain.key
- listDomains[domInd!].list?.append(domval)
- }
- isDomaindAdded = true
- }
- }
- if (!isDomaindAdded) {
- var domInd = listDomains.firstIndex(where: { $0.name == "Eigene Domains" })
- if (domInd == nil) {
- var domval: Domain = domain.value
- domval.name = domain.key
- var dom = DomainItems(name: "Eigene Domains", list: [domval])
- listDomains.append(dom)
- } else {
- var domval: Domain = domain.value
- domval.name = domain.key
- listDomains[domInd!].list?.append(domval)
- }
- }
- }
- }
-
- fileprivate func loadIpAddress() {
- api.isLoading = true
- Task {
- myIP = await api.GetMyIP() ?? MyIP(ip: "0.0.0.0")
- myIPV6 = await api.GetMyIPV6() ?? MyIP(ip: "0.0.0.0")
- }
- }
-
- fileprivate func SetDotColor(domain: Domain) -> Color {
- let firstRec = domain.records?.first(where: { $0.type == "A" })
- if (firstRec?.content == myIP.ip) {
- return .green
- }
-
- return .red
- }
-
- fileprivate func deleteDomain() {
- errorTyp = ErrorTypes.delete
- activeSheet = .error
- print(errorTyp)
- }
-
- fileprivate func DomainViews() -> some View {
- return VStack {
- ZStack {
- NavigationView {
- VStack {
- Form {
- if (listOfDomains.subdomains == nil) {
- Section("Domainen") {
- Text("Keine Daten gefunden!")
- }
- } else {
- let sortedList = listDomains.sorted { $0.name!.lowercased() < $1.name!.lowercased() }
- ForEach(sortedList, id: \.id) { domain in
-
- let sorted = Array(domain.list!.sorted { $0.name.lowercased() < $1.name.lowercased() })
- Section(domain.name!) {
- ForEach(sorted, id: \.id) { dom in
- NavigationLink(destination: DetailDomainView(domainName: dom.name, domain: dom, myIp: myIP, deleteThisDNSRecord: $deleteThisDNSRecord ).onDisappear {
- if (deleteThisDNSRecord) {
- deleteThisDNSRecord = false
- presentationMode.wrappedValue.dismiss()
- loadDomains(isRefresh: true)
- }
- }) {
- HStack(alignment: .center) {
- Image(systemName: "circle.fill")
- .resizable()
- .scaledToFill()
- .foregroundColor(SetDotColor(domain: dom))
- .frame(width: 8, height: 8)
- Text(dom.name)
- }
- .frame(alignment: .center)
- }
- .swipeActions(edge: .trailing) {
- Button(role: .destructive, action: {
- delDomain = dom.name
- deleteDomain()
- }) {
- Label("Löschen", systemImage: "trash")
- }
- }
- .tint(.red)
- }
- }
- }
- }
- }
- }
- .frame(maxWidth: .infinity)
- .refreshable {
- loadDomains(isRefresh: true)
- }
- .toolbar {
- ToolbarItem(placement: .navigationBarTrailing) {
- Button(action: {
- withAnimation {
- activeSheet = .add
- }
- }) {
- Image(systemName: "plus.circle")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- .navigationTitle(Tab.domains.labelName)
- }
- .introspectNavigationController { navigationController in
- navigationController.splitViewController?.preferredPrimaryColumnWidthFraction = 1
- navigationController.splitViewController?.maximumPrimaryColumnWidth = 400
- }
- .accentColor(Color("AccentColor"))
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- }
- }
-
- var body: some View {
- VStack {
- DomainViews()
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .onAppear {
- loadDomains(isRefresh: false)
- }
- .fullScreenCover(isPresented: $showLoginView) {
- LoginView()
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .add:
- NewDomainView(newItem: $isNewItem)
- .onDisappear {
- if (isNewItem) {
- isNewItem = false
- listOfDomainsString = ""
- loadDomains(isRefresh: true)
- }
- }
- case .help:
- HelpView()
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: $deleteThisDomain)
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (deleteThisDomain) {
- Task {
- let res = await api.DeleteDomain(domain: delDomain)
- let status = res?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429")) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- let toast = Toast.default(
- image: GetUIImage(imageName: "checkmark.circle", color: UIColor.systemGreen, hierarichal: true),
- title: "Erfolgreich gelöscht!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- }
-
- loadDomains(isRefresh: true)
- }
- } else {
- if (errorTyp?.status == 401) {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- withAnimation {
- showLoginView.toggle()
- }
- } else {
- loadDomains(isRefresh: false)
- }
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-struct ContentView_Previews: PreviewProvider {
- static var previews: some View {
- ContentView(popToRootTab: .constant(.other))
- }
-}
diff --git a/IPv64/Main/Domains/DetailDomainView.swift b/IPv64/Main/Domains/DetailDomainView.swift
deleted file mode 100644
index c308d02..0000000
--- a/IPv64/Main/Domains/DetailDomainView.swift
+++ /dev/null
@@ -1,374 +0,0 @@
-//
-// DetailDomainView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 07.11.22.
-//
-
-import SwiftUI
-import Toast
-
-struct DetailDomainView: View {
-
- @AppStorage("AccountInfos") var accountInfosJson: String = ""
- @Environment(\.presentationMode) var presentationMode
-
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State var domainName: String
- @State var domain: Domain
- @State var myIp: MyIP
- @State var showingPopover = false
- @State var popOverValue = ""
- @State var isFromDNSRecord = false
- @State var accountInfos = AccountInfo()
-
- @State var delDNSRecord: RecordInfos? = nil
- @Binding var deleteThisDNSRecord: Bool
-
- fileprivate func deleteDNSRecord() {
- errorTyp = ErrorTypes.deleteDNSRecord
- activeSheet = .error
- }
-
- fileprivate func CheckIfIpCorrect() -> Bool {
- let firstRec = domain.records?.first(where: { $0.type == "A" })
- if (firstRec?.content != myIp.ip) {
- return false
- }
- return true
- }
-
- fileprivate func loadAccountInfos() {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountInfosJson.data(using: .utf8)
- accountInfos = try jsonDecoder.decode(AccountInfo.self, from: jsonData!)
- } catch let error {
- print(error)
- }
- }
-
- fileprivate func GetAccountUpdateUrl() -> String {
- return "https://ipv64.net/update.php?key=" + accountInfos.update_hash! + "&domain=" + domainName
- }
-
- fileprivate func GetDomainUpdateUrl() -> String {
- return "https://ipv64.net/update.php?key=" + domain.domain_update_hash!
- }
-
- var body: some View {
- ZStack {
- Form {
- if (!CheckIfIpCorrect()) {
- Section("Hinweis") {
- Text("Dein A-Record stimmt mit deiner aktuellen IP nicht überein! Dies kann an einer Aktiven Mobilfunkverbindung hängen oder an die IP ist eine Serveradresse.")
- .font(.system(.callout))
- Button(action: {
- Task {
- do {
- if (accountInfos.update_hash == nil) {
- print("updatehash == nil");
- return
- }
- let result = try await api.UpdateDomainIp(updateKey: accountInfos.update_hash!, domain: domainName)
- if (result == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (result?.info == "Update Cooldown - 10sec") {
- activeSheet = .error
- errorTyp = ErrorTypes.updateCoolDown
- return
- }
- withAnimation {
- deleteThisDNSRecord = true
- presentationMode.wrappedValue.dismiss()
- }
- } catch let error {
- print(error)
- activeSheet = .error
- errorTyp = ErrorTypes.websiteRequestError
- }
- }
- print("Aktualisiere A-Record")
- }) {
- Text("A-Record aktualisieren?")
- .foregroundColor(.blue)
- .font(.system(.callout))
- }
- }
- }
- Section("Allgemein") {
- HStack {
- Text("Wildcard:")
- Spacer()
- Text(domain.wildcard! == 1 ? "ja" : "nein")
- .foregroundColor(.gray)
- }
- HStack {
- Text("Updates:")
- Spacer()
- Text("\(domain.updates!)")
- .foregroundColor(.gray)
- }
- HStack {
- Text("Account Update URL:")
- Spacer()
- Text(GetAccountUpdateUrl())
- .foregroundColor(.gray)
- .lineLimit(1)
- }
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "Kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = GetAccountUpdateUrl()
- }) {
- Label("Kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- HStack {
- Text("Domain Update URL:")
- Spacer()
- Text(GetDomainUpdateUrl())
- .foregroundColor(.gray)
- .lineLimit(1)
- }
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "Kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = GetDomainUpdateUrl()
- }) {
- Label("Kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- }
-
- ForEach(domain.records!.sorted { $0.type!.lowercased() < $1.type!.lowercased() }, id: \.record_id) { record in
- let dateDate = dateDBFormatter.date(from: record.last_update!)
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- let ttlState = thousendSeperator.string(from: record.ttl! as NSNumber)
-
- RecordItemView(record: record, ttlState: ttlState!, dateString: dateString)
- .swipeActions(edge: .trailing) {
- Button(role: .destructive, action: {
- delDNSRecord = record
- deleteDNSRecord()
- }) {
- Label("Löschen", systemImage: "trash")
- }
- .tint(.red)
- }
- }
- }
- .onAppear {
- loadAccountInfos()
- }
- .navigationTitle(domainName)
- .toolbar {
- ToolbarItem {
- Button(action: {
- activeSheet = .adddns
- }) {
- Image(systemName: "square.and.pencil")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- }
-
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .medium
- formatter.timeStyle = .medium
- formatter.locale = Locale(identifier: "de_DE")
- return formatter
- }()
-
- private let dateDBFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
- return formatter
- }()
-
- private let thousendSeperator: NumberFormatter = {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.groupingSeparator = "."
- return formatter
- }()
-
- struct RecordItemView : View {
-
- @State var record: RecordInfos
- @State var ttlState: String
- @State var dateString: String
-
- var body: some View {
- Section("\(record.type!)") {
- HStack {
- Text("Präfix:")
- Spacer()
- Text(record.praefix!.count == 0 ? "---" : record.praefix!)
- .foregroundColor(.gray)
- }
- HStack {
- Text("TTL:")
- Spacer()
- Text(ttlState)
- .foregroundColor(.gray)
- }
- HStack {
- Text("Typ:")
- Spacer()
- Text(record.type!)
- .foregroundColor(.gray)
- }
- HStack {
- Text("Wert:")
- Spacer()
- Text(record.content!)
- .lineLimit(1)
- .multilineTextAlignment(.trailing)
- .foregroundColor(.gray)
- }
- HStack {
- Text("letzte Änderung:")
- Spacer()
- Text(dateString)
- .foregroundColor(.gray)
- }
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .adddns:
- NewDomainDNSView(isSaved: $isFromDNSRecord, domainName: domainName).onDisappear {
- if (isFromDNSRecord) {
- deleteThisDNSRecord = true
- self.presentationMode.wrappedValue.dismiss()
- }
- }
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: $deleteThisDNSRecord)
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (deleteThisDNSRecord) {
- Task {
- let res = await api.DeleteDNSRecord(recordId: (delDNSRecord?.record_id)!)
-
- let status = res?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429")) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- let toast = Toast.default(
- image: GetUIImage(imageName: "checkmark.circle", color: UIColor.systemGreen, hierarichal: true),
- title: "Erfolgreich gelöscht!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- }
-
-
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-struct DetailDomainView_Previews: PreviewProvider {
- static var previews: some View {
- NavigationView {
- DetailDomainView(domainName: "sebhaha.ipv64.de", domain: Domain(
- updates: 0,
- wildcard: 1,
- records: [
- RecordInfos(
- record_id: 4900,
- content: "2a02:26f7:ec48:6609:0:a054:3b9d:dcc4",
- ttl: 3600,
- type: "AAAA",
- praefix: "",
- last_update: "2022-10-28 21:57:34"
- )
- ]
- ), myIp: MyIP(ip: "0.0.0.0"), deleteThisDNSRecord: .constant(false))
- }.preferredColorScheme(.light)
-
- NavigationView {
- DetailDomainView(domainName: "sebhaha.ipv64.de", domain: Domain(
- updates: 0,
- wildcard: 1,
- records: [
- RecordInfos(
- record_id: 4900,
- content: "2a02:26f7:ec48:6609:0:a054:3b9d:dcc4",
- ttl: 3600,
- type: "AAAA",
- praefix: "",
- last_update: "2022-10-28 21:57:34"
- )
- ]
- ), myIp: MyIP(ip: "0.0.0.0"), deleteThisDNSRecord: .constant(false))
- }.preferredColorScheme(.dark)
- }
-}
diff --git a/IPv64/Main/Domains/Sheets/NewDomainDNSView.swift b/IPv64/Main/Domains/Sheets/NewDomainDNSView.swift
deleted file mode 100644
index 1dc6779..0000000
--- a/IPv64/Main/Domains/Sheets/NewDomainDNSView.swift
+++ /dev/null
@@ -1,121 +0,0 @@
-//
-// NewDomainDNSView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 08.11.22.
-//
-
-import SwiftUI
-
-struct NewDomainDNSView: View {
-
- @Environment(\.presentationMode) var presentationMode
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = nil
-
- @Binding var isSaved: Bool
- @State var domainName: String
-
- @State var praefix: String = ""
- @State var content: String = ""
- @State var selectedTyp: Int = 0
-
- var typeList = [
- "A",
- "AAAA",
- "TXT",
- "MX",
- "NS",
- "SRV",
- "CNAME",
- "TLSA",
- "CAA"
- ]
-
- var body: some View {
- NavigationView {
- ZStack {
- VStack {
- Form {
- Section("Benötigte Informationen") {
- TextField("Präfix", text: $praefix)
- Picker(selection: $selectedTyp, label: Text("Typ")
- .font(.system(.callout))
- .padding(.horizontal, 5)) {
- ForEach(0 ..< typeList.count) {
- Text(self.typeList[$0])
- .tag(self.typeList[$0])
- }
- }
- TextField("Wert", text: $content)
- }
- }
- }
- .navigationTitle("Neuer DNS-Record")
- .toolbar {
- ToolbarItem {
- Button(action: {
- if (content.count > 0) {
- let _praefix = praefix.trimmingCharacters(in: .whitespaces)
- let _content = content.trimmingCharacters(in: .whitespaces)
- Task {
- let res = await api.PostDNSRecord(domain: domainName, praefix: _praefix, typ: typeList[selectedTyp], content: _content)
- if (res?.info == "success") {
- activeSheet = .error
- errorTyp = ErrorTypes.dnsRecordSuccesfullyCreated
- } else if (res?.info == "error") {
- activeSheet = .error
- errorTyp = ErrorTypes.domainNotAvailable
- } else if (res?.info == "Updateintervall overcommited") {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- }
- }
- }
- }) {
- Image(systemName: "paperplane")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .onDisappear {
- if (self.errorTyp!.status == 201) {
- withAnimation {
- isSaved = true
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-struct NewDomainDNSView_Previews: PreviewProvider {
- static var previews: some View {
- NewDomainDNSView(isSaved: .constant(false), domainName: "seb.nas64.de")
- }
-}
diff --git a/IPv64/Main/Domains/Sheets/NewDomainView.swift b/IPv64/Main/Domains/Sheets/NewDomainView.swift
deleted file mode 100644
index fb07cbf..0000000
--- a/IPv64/Main/Domains/Sheets/NewDomainView.swift
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// NewDomainView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 06.11.22.
-//
-
-import SwiftUI
-
-struct NewDomainView: View {
-
- @Environment(\.presentationMode) var presentationMode
- @Binding var newItem: Bool
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = nil
- @State var showSheet = false
-
- @State var domain: String = ""
- @State private var selectedDomain = 0
- @State var domainError: String = ""
-
- var body: some View {
- NavigationView {
- ZStack {
- VStack {
- Form {
- Section("Benötigte Informationen") {
- TextField("zB.: Heimserver01", text: $domain)
- Picker(selection: $selectedDomain, label: Text("Domain")
- .font(.system(.callout))
- .padding(.horizontal, 5)) {
- ForEach(0 ..< dynDomainList.count) {
- Text(dynDomainList[$0])
- .tag(dynDomainList[$0])
- }
- }
- }
- }
- }
- .navigationTitle("Neue Domain")
- .toolbar {
- ToolbarItem {
- Button(action: {
- if (domain.count > 0) {
- var domainReg = domain.trimmingCharacters(in: .whitespaces) + "." + dynDomainList[selectedDomain]
- //loadDomains()
- Task {
- let res = await api.PostDomain(domain: domainReg)
- if (res?.info == "success") {
- activeSheet = .error
- errorTyp = ErrorTypes.domainCreatedSuccesfully
- newItem = true
- } else if (res?.info == "error") {
- activeSheet = .error
- errorTyp = ErrorTypes.domainNotAvailable
- } else if (res?.info == "Updateintervall overcommited") {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- }
- }
- }
- }) {
- Image(systemName: "paperplane")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .add:
- EmptyView()
- case .detail:
- EmptyView()
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(true)
- .onDisappear {
- if (self.errorTyp!.status == 201) {
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-struct NewDomainView_Previews: PreviewProvider {
- static var previews: some View {
- NewDomainView(newItem: .constant(false))
- }
-}
diff --git a/IPv64/Main/Healthcheck/.DS_Store b/IPv64/Main/Healthcheck/.DS_Store
deleted file mode 100644
index f7d0ba4..0000000
Binary files a/IPv64/Main/Healthcheck/.DS_Store and /dev/null differ
diff --git a/IPv64/Main/Healthcheck/DetailHealthcheckView.swift b/IPv64/Main/Healthcheck/DetailHealthcheckView.swift
deleted file mode 100644
index fd416f2..0000000
--- a/IPv64/Main/Healthcheck/DetailHealthcheckView.swift
+++ /dev/null
@@ -1,406 +0,0 @@
-//
-// DetailHealthcheckView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 17.01.23.
-//
-
-import SwiftUI
-import Charts
-import Toast
-
-struct DetailHealthcheckView: View {
-
- @Environment(\.presentationMode) var presentationMode
- @AppStorage("IntegrationList") var integrationListS: String = ""
-
- @State var healthcheck: HealthCheck?
- @Binding var isEdit: Bool
-
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State var healthcheckStatus: HealthcheckStatisticsResult = HealthcheckStatisticsResult()
-
- @State var updatedItem = false
-
- @State var pillCount = 15
-
- @State var selectedPos: String? = nil
-
- fileprivate func GetIntegrationCount() -> String {
- if (healthcheck!.integration_id == "0") {
- return "0"
- }
-
- return "\(healthcheck!.integration_id.split(separator: ",").count)"
- }
-
- fileprivate func SetDotColor(statusId: Int) -> Color {
- if (statusId == StatusTypes.active.statusId) {
- return StatusTypes.active.color!
- }
- if (statusId == StatusTypes.warning.statusId) {
- return StatusTypes.warning.color!
- }
- if (statusId == StatusTypes.alarm.statusId) {
- return StatusTypes.alarm.color!
- }
- if (statusId == StatusTypes.pause.statusId) {
- return StatusTypes.pause.color!
- }
-
- return .gray
- }
-
- fileprivate func GetLastXMonitorPills(count: Int, domain: HealthCheck) -> [Color] {
- let lastEvents = domain.events.prefix(count)
- var colorArr: [Color] = []
- lastEvents.forEach { event in
- colorArr.append(SetDotColor(statusId: event.status!))
- }
-
- return colorArr
- }
-
- fileprivate func GetLastXMonitor(count: Int, domain: HealthCheck) -> [HealthEvents] {
- let lastEvents = domain.events.prefix(count)
- var healthArr: [HealthEvents] = []
- lastEvents.forEach { event in
- healthArr.append(event)
- }
-
- return healthArr
- }
-
- fileprivate func GetUnit(unitId: Int) -> String {
- if (unitId == AlarmUnitTypes.minutes.id) {
- return AlarmUnitTypes.minutes.text!
- } else if (unitId == AlarmUnitTypes.stunden.id) {
- return AlarmUnitTypes.stunden.text!
- } else {
- return AlarmUnitTypes.tage.text!
- }
- }
-
- fileprivate func GetHealthUpdateUrl() -> String {
- return "https://ipv64.net/health.php?token=" + (healthcheck?.healthtoken)!
- }
-
- var body: some View {
- ZStack {
- GeometryReader { geo in
- let countPills = geo.size.width / 17
- VStack { }
- .onAppear {
- pillCount = Int(countPills)
- if (healthcheck?.type != "health") {
- Task {
- healthcheckStatus = await api.GetHealthcheckStatistics(healthtoken: healthcheck!.healthtoken) ?? HealthcheckStatisticsResult()
- print("STATSRES")
- print(healthcheckStatus)
- }
- }
- }
- }
- Form {
- HStack {
- Spacer()
- HStack(spacing: 6) {
- let lastXPills = GetLastXMonitorPills(count: Int(pillCount), domain: healthcheck!).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 9, height: 40)
- }
- }
- Spacer()
- }
- .frame(height: 60)
- .listStyle(.plain)
- .listRowInsets(EdgeInsets(top: 15, leading: 0, bottom: 0, trailing: 0))
- .listRowBackground(Color.clear)
- .id(UUID())
- Section("Healthcheck Einstellungen") {
- HStack {
- Text("Zeitraum")
- Spacer()
- Text("\(healthcheck!.alarm_count) \(GetUnit(unitId: healthcheck!.alarm_unit))")
- .foregroundColor(.gray)
- }
- HStack {
- Text("Karenzzeit")
- Spacer()
- Text("\(healthcheck!.grace_count) \(GetUnit(unitId: healthcheck!.grace_unit))")
- .foregroundColor(.gray)
- }
- HStack {
- Text("Benachrichtungsmethode/n")
- Spacer()
- Text(GetIntegrationCount())
- .foregroundColor(.gray)
- }
- HStack {
- Text("Benachrichtung bei DOWN")
- Spacer()
- Text(healthcheck!.alarm_down != 0 ? "aktiv" : "deaktiviert")
- .foregroundColor(.gray)
- }
- .foregroundColor(.red)
- HStack {
- Text("Benachrichtung bei UP")
- Spacer()
- Text(healthcheck!.alarm_up != 0 ? "aktiv" : "deaktiviert")
- .foregroundColor(.gray)
- }
- .foregroundColor(.green)
- let dateDateCreated = dateDBFormatter.date(from: (healthcheck?.add_time)!)
- let dateCreatedString = itemFormatter.string(from: dateDateCreated ?? Date())
- HStack {
- Text("erstellt am")
- Spacer()
- Text(dateCreatedString)
- .foregroundColor(.gray)
- }
- HStack {
- Text("Health Update URL:")
- Spacer()
- Text(GetHealthUpdateUrl())
- .foregroundColor(.gray)
- .lineLimit(1)
- }
- .swipeActions(edge: .trailing) {
- Button(role: .none, action: {
- let toast = Toast.default(
- image: GetUIImage(imageName: "doc.on.doc", color: UIColor.systemBlue, hierarichal: true),
- title: "Kopiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- UIPasteboard.general.string = GetHealthUpdateUrl()
- }) {
- Label("Kopieren", systemImage: "doc.on.doc")
- }
- .tint(.blue)
- }
- }
- if (healthcheck?.type != "health") {
- Section("Latenzen") {
- if #available(iOS 16.0, *) {
- if (healthcheckStatus.statistics != nil) {
- let gradient = Gradient(colors: [Color("ip64_color"), Color("ip64_color").opacity(0)])
- let statKey = Array(healthcheckStatus.statistics!)[0]
- let stats = Array(statKey.value.reversed().prefix(pillCount).reversed())
- VStack(alignment: .leading, spacing: 4) {
- if (selectedPos != nil) {
- let item = stats.first(where: { $0.id.uuidString == selectedPos })
- let dateDate = dateDBTFormatter.date(from: item?.time ?? "2001-01-01")
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- Text("Datum: \(dateString)")
- .font(.system(.headline, design: .rounded))
- Text("Latenz: \(item?.latency ?? 0, specifier: "%.2f") ms")
- .font(.system(.footnote, design: .rounded))
- }
- Chart(stats, id: \.id) {
- if (selectedPos != nil && $0.id.uuidString == selectedPos) {
- RuleMark(x: .value("Now", $0.id.uuidString))
- .foregroundStyle(Color.secondary)
- .accessibilityHidden(true)
- PointMark(
- x: .value("ID", $0.id.uuidString),
- y: .value("Value", $0.latency)
- )
- .symbolSize(CGSize(width: 8, height: 8))
- .foregroundStyle(Color.white)
- .accessibilityHidden(true)
- }
- LineMark(
- x: .value("ID", $0.id.uuidString),
- y: .value("Value", $0.latency)
- )
- .interpolationMethod(.catmullRom)
- .foregroundStyle(Color("ip64_color"))
- AreaMark(
- x: .value("ID", $0.id.uuidString),
- y: .value("Value", $0.latency)
- )
- .interpolationMethod(.catmullRom)
- .foregroundStyle(gradient)
- }
- .chartOverlay { proxy in
- GeometryReader { geo in
- Rectangle()
- .fill(Color.clear)
- .contentShape(Rectangle())
- .gesture(DragGesture(minimumDistance: 0)
- .onChanged { value in
- // find start and end positions of the drag
-
- let start = geo[proxy.plotAreaFrame].origin.x
- let xCurrent = value.location.x - start
- // map those positions to X-axis values in the chart
- if let posId: String = proxy.value(atX: xCurrent) {
- selectedPos = posId
- }
- }
- .onEnded { value in
- // find start and end positions of the drag
-
- let start = geo[proxy.plotAreaFrame].origin.x
- let xCurrent = value.location.x - start
- // map those positions to X-axis values in the chart
- if let posId: String = proxy.value(atX: xCurrent) {
- selectedPos = posId
- }
- })
- }
- }
- .chartXAxis(.hidden)
- .frame(height: 250)
- .padding(.vertical)
- .onAppear {
- selectedPos = stats[0].id.uuidString ?? ""
- }
-
- }
- } else {
- VStack {
- Spinner(isAnimating: true, style: .medium, color: .white)
- }.frame(maxWidth: .infinity, maxHeight: .infinity)
- }
- }
- else {
- Text("Latenzen sind erst unter iOS 16 mit der Apple Chart Bibliothek verfügbar!")
- }
- }
- }
-
- Section("Logs") {
- let list = GetLastXMonitor(count: Int(pillCount), domain: healthcheck!)
- ForEach(list, id:\.event_time) { event in
- LazyVStack {
- let dateDate = dateDBFormatter.date(from: event.event_time!)
- let dateString = itemFormatter.string(from: dateDate ?? Date())
- HStack {
- Image(systemName: "circle.fill")
- .resizable()
- .scaledToFill()
- .foregroundColor(SetDotColor(statusId: event.status!))
- .frame(width: 8, height: 8)
- VStack(alignment: .leading, spacing: 5) {
- Text(dateString)
- .multilineTextAlignment(.leading)
- .font(.system(.callout, design: .rounded))
- Text(event.text!)
- .multilineTextAlignment(.leading)
- .font(.system(.caption2, design: .rounded))
- }
- .padding(.leading, 5)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- }
- }
- }
- }
- .navigationTitle((healthcheck?.name)!)
- .toolbar {
- ToolbarItem {
- Button(action: {
- activeSheet = .edit
- }) {
- Image(systemName: "square.and.pencil")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .edit:
- EditHealthcheckView(healthcheck: healthcheck!, updatedItem: $updatedItem)
- .onDisappear {
- if (updatedItem) {
- isEdit = true
- updatedItem = false
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- /*.onDisappear {
- if (deleteThisDNSRecord) {
- Task {
- print(deleteDNSRecord)
- let res = await api.DeleteDNSRecord(recordId: (delDNSRecord?.record_id)!)
- print(res)
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- }*/
- default:
- EmptyView()
- }
- }
-
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .medium
- formatter.timeStyle = .medium
- formatter.locale = Locale(identifier: "de_DE")
- return formatter
- }()
-
- private let dateDBFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
- return formatter
- }()
-
- private let dateDBTFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "de_DE")
- formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
- return formatter
- }()
-}
-
-struct DetailHealthcheckView_Previews: PreviewProvider {
- static var previews: some View {
- let hcd = DummyData.Healthcheck
- NavigationView {
- DetailHealthcheckView(healthcheck: hcd, isEdit: .constant(false))
- }
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- NavigationView {
- DetailHealthcheckView(healthcheck: hcd, isEdit: .constant(false))
- }
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
diff --git a/IPv64/Main/Healthcheck/HealthcheckView.swift b/IPv64/Main/Healthcheck/HealthcheckView.swift
deleted file mode 100644
index b108b72..0000000
--- a/IPv64/Main/Healthcheck/HealthcheckView.swift
+++ /dev/null
@@ -1,383 +0,0 @@
-//
-// HealthcheckView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 16.01.23.
-//
-
-import SwiftUI
-import Introspect
-import Toast
-
-struct HealthcheckView: View {
-
- @AppStorage("AccountInfos") var accountInfos: String = ""
- @AppStorage("HealthcheckList") var healthCheckList: String = ""
- @AppStorage("IntegrationList") var integrationListS: String = ""
- @ObservedObject var api: NetworkServices = NetworkServices()
-
- @Binding var popToRootTab: Tab
-
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State var showSheet = false
- @State var deleteThisHealth = false
- @State var healthcheckList: HealthCheckResult? = nil
- @State var integrationList: IntegrationResult? = nil
-
- @State var activeCount = 0
- @State var warningCount = 0
- @State var alarmCount = 0
- @State var pausedCount = 0
-
- @State var deleteHealth = ""
- @State var startPauseHealthToken = ""
-
- @State private var refeshUUID = UUID()
- @State private var isNewItem = false
- @State private var isEdit = false
-
- fileprivate func loadAccountInfos() {
- Task {
- do {
- let response = await api.GetAccountStatus()
- if (response == nil) {
- throw NetworkError.NoNetworkConnection
- }
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(response)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountInfos = json!
- } catch let error {
- print(error)
- activeSheet = .error
- errorTyp = ErrorTypes.websiteRequestError
- }
- }
- }
-
- fileprivate func SetDotColor(statusId: Int) -> Color {
- if (statusId == StatusTypes.active.statusId) {
- return StatusTypes.active.color!
- }
- if (statusId == StatusTypes.warning.statusId) {
- return StatusTypes.warning.color!
- }
- if (statusId == StatusTypes.alarm.statusId) {
- return StatusTypes.alarm.color!
- }
- if (statusId == StatusTypes.pause.statusId) {
- return StatusTypes.pause.color!
- }
-
- return .gray
- }
-
- fileprivate func deleteHealthcheck() {
- errorTyp = ErrorTypes.deletehealth
- activeSheet = .error
- print(errorTyp)
- }
-
- fileprivate func startPauseHealthCheck(isPause: Bool) {
- Task {
- if (isPause) {
- let res = await api.PostPauseHealth(healthtoken: startPauseHealthToken)
- startPauseHealthToken = ""
-
- let toast = Toast.default(
- image: GetUIImage(imageName: "pause.circle", color: UIColor.systemCyan, hierarichal: true),
- title: "Erfolgreich pausiert!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
-
- } else {
- let res = await api.PostStartHealth(healthtoken: startPauseHealthToken)
- startPauseHealthToken = ""
-
- let toast = Toast.default(
- image: GetUIImage(imageName: "play.circle", color: UIColor.systemGreen, hierarichal: true),
- title: "Erfolgreich gestartet!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- }
- GetHealthChecks()
- }
- }
-
- var body: some View {
- ZStack {
- NavigationView {
- VStack {
- Form {
- HealthcheckStatsView(activeCount: $activeCount, warningCount: $warningCount, alarmCount: $alarmCount, pausedCount: $pausedCount)
- .listStyle(.plain)
- .listRowInsets(EdgeInsets(top: -15, leading: -15, bottom: -15, trailing: -15))
- .listRowBackground(Color.clear)
-
- Section {
- if (healthcheckList?.domain.count == 0) {
- Text("Keine Daten gefunden!")
- } else {
- ForEach((healthcheckList?.domain.sorted { $0.name.lowercased() < $1.name.lowercased() }) ?? [], id: \.name) { hcd in
- NavigationLink(destination: DetailHealthcheckView(healthcheck: hcd, isEdit: $isEdit).onDisappear {
- if (isEdit) {
- isEdit = false
- GetHealthChecks()
- }
- }) {
- LazyVStack {
- HStack {
- Image(systemName: "circle.fill")
- .resizable()
- .scaledToFill()
- .foregroundColor(SetDotColor(statusId: hcd.healthstatus))
- .frame(width: 8, height: 8)
- Text(hcd.name)
- Spacer()
- HStack(spacing: 4) {
- let lastXPills = GetLastXMonitorPills(count: 10, domain: hcd).reversed()
- ForEach(lastXPills, id:\.self) { color in
- RoundedRectangle(cornerRadius: 5).fill(color)
- .frame(width: 5, height: 20)
- }
- }
- .padding(.trailing, 5)
- }
- .id(UUID())
- }
- }
- .swipeActions(edge: .trailing) {
- Button(role: .destructive, action: {
- deleteHealth = hcd.healthtoken
- deleteHealthcheck()
- }) {
- Label("Löschen", systemImage: "trash")
- }
- .tint(.red)
- if (hcd.healthstatus != StatusTypes.pause.statusId) {
- Button(role: .destructive, action: {
- startPauseHealthToken = hcd.healthtoken
- startPauseHealthCheck(isPause: true)
- }) {
- Label("Pause", systemImage: "pause.circle")
- }
- .tint(.teal)
- }
- if (hcd.healthstatus == StatusTypes.pause.statusId) {
- Button(role: .destructive, action: {
- startPauseHealthToken = hcd.healthtoken
- startPauseHealthCheck(isPause: false)
- }) {
- Label("Start", systemImage: "play.circle")
- }
- .tint(.green)
- }
- }
- }
- }
- }
- }
- }
- .toolbar {
- ToolbarItem(placement: .navigationBarTrailing) {
- Button(action: {
- withAnimation {
- activeSheet = .add
- }
- }) {
- Image(systemName: "plus.circle")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- .navigationTitle(Tab.healthchecks.labelName)
- .refreshable {
- GetHealthChecks()
- }
- }
- .introspectNavigationController { navigationController in
- navigationController.splitViewController?.preferredPrimaryColumnWidthFraction = 1
- navigationController.splitViewController?.maximumPrimaryColumnWidth = 400
- }
- .id(refeshUUID)
- .accentColor(Color("AccentColor"))
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
-
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- .onAppear {
- GetHealthChecks()
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .add:
- NewHealthcheckView(newItem: $isNewItem)
- .onDisappear {
- if (isNewItem) {
- isNewItem = false
- GetHealthChecks()
- }
- }
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: $deleteThisHealth)
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (deleteThisHealth) {
- Task {
- refeshUUID = UUID()
- let res = await api.DeleteHealth(health: deleteHealth)
-
- let status = res?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429")) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- let toast = Toast.default(
- image: GetUIImage(imageName: "checkmark.circle", color: UIColor.systemGreen, hierarichal: true),
- title: "Erfolgreich gelöscht!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
- }
-
- GetHealthChecks()
- }
- } else {
- if (errorTyp?.status == 401) {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- } else {
- GetHealthChecks()
- }
- }
- }
- default:
- EmptyView()
- }
- }
-
- fileprivate func GetHealthChecks() {
- api.isLoading = true
- Task {
- activeCount = 0
- warningCount = 0
- alarmCount = 0
- pausedCount = 0
- healthcheckList = await api.GetHealthchecks()
- let status = healthcheckList?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && healthcheckList?.domain.count == 0) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- if (healthcheckList != nil) {
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(healthcheckList)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- healthCheckList = json!
- Array((healthcheckList?.domain.sorted { $0.name.lowercased() < $1.name.lowercased() })!).forEach { hcd in
- if (hcd.healthstatus == StatusTypes.active.statusId) {
- activeCount += 1
- } else if (hcd.healthstatus == StatusTypes.warning.statusId) {
- warningCount += 1
- } else if (hcd.healthstatus == StatusTypes.alarm.statusId) {
- alarmCount += 1
- } else if (hcd.healthstatus == StatusTypes.pause.statusId) {
- pausedCount += 1
- }
- }
- }
- if (integrationListS.isEmpty) {
- GetIntegrations()
- }
- }
- }
- }
-
- fileprivate func GetIntegrations() {
- Task {
- integrationList = await api.GetIntegrations()
- let status = integrationList?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && integrationList?.integration.count == 0) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- if (integrationList != nil) {
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(integrationList?.integration)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- integrationListS = json!
- }
- }
- }
- }
-
- fileprivate func GetLastXMonitorPills(count: Int, domain: HealthCheck) -> [Color] {
-
- let lastEvents = domain.events.prefix(count)
- var colorArr: [Color] = []
-
- lastEvents.forEach { event in
- colorArr.append(SetDotColor(statusId: event.status!))
- }
-
- return colorArr
- }
-}
-
-#Preview {
- HealthcheckView(popToRootTab: .constant(.other))
-}
diff --git a/IPv64/Main/Healthcheck/Items/HealthcheckStatsItem.swift b/IPv64/Main/Healthcheck/Items/HealthcheckStatsItem.swift
deleted file mode 100644
index 791d6a5..0000000
--- a/IPv64/Main/Healthcheck/Items/HealthcheckStatsItem.swift
+++ /dev/null
@@ -1,52 +0,0 @@
-//
-// HealthcheckStatsItem.swift
-// IPv64
-//
-// Created by Sebastian Rank on 16.01.23.
-//
-
-import SwiftUI
-
-struct HealthcheckStatsItem: View {
-
- @State var statusType: StatusTyp
- @Binding var count: Int
-
- var body: some View {
- VStack {
- VStack {
- HStack(alignment: .top) {
- VStack(alignment: .leading, spacing: 8) {
- Text(statusType.name!)
- .bold()
- .lineLimit(1)
- .font(.system(.title2, design: .rounded))
- Text("\(count)")
- .font(.system(.title, design: .rounded))
- }
- Spacer()
- Image(systemName: statusType.icon!)
- .resizable()
- .scaledToFit()
- .frame(width: 25, height: 25)
- .offset(y: statusType.statusId == 4 ? -5 : 0)
- }
- .foregroundColor(.white)
- .padding()
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(RoundedRectangle(cornerRadius: 16).fill(statusType.color!))
- }
- }
-}
-
-struct HealthcheckStatsItem_Previews: PreviewProvider {
- static var previews: some View {
- HealthcheckStatsItem(statusType: StatusTypes.pause, count: .constant(20))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- HealthcheckStatsItem(statusType: StatusTypes.pause, count: .constant(20))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
diff --git a/IPv64/Main/Healthcheck/Items/HealthcheckStatsView.swift b/IPv64/Main/Healthcheck/Items/HealthcheckStatsView.swift
deleted file mode 100644
index ad4985d..0000000
--- a/IPv64/Main/Healthcheck/Items/HealthcheckStatsView.swift
+++ /dev/null
@@ -1,41 +0,0 @@
-//
-// HealthcheckStatsView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 16.01.23.
-//
-
-import SwiftUI
-
-struct HealthcheckStatsView: View {
-
- @Binding var activeCount: Int
- @Binding var warningCount: Int
- @Binding var alarmCount: Int
- @Binding var pausedCount: Int
-
- @State var columnsGrid: [GridItem] = Array(repeating: GridItem(.flexible(), spacing: 10), count: 2)
-
- var body: some View {
- VStack {
- LazyVGrid(columns: columnsGrid, spacing: 10) {
- HealthcheckStatsItem(statusType: StatusTypes.active, count: $activeCount)
- HealthcheckStatsItem(statusType: StatusTypes.warning, count: $warningCount)
- HealthcheckStatsItem(statusType: StatusTypes.alarm, count: $alarmCount)
- HealthcheckStatsItem(statusType: StatusTypes.pause, count: $pausedCount)
- }
- .padding()
- }
- }
-}
-
-struct HealthcheckStatsView_Previews: PreviewProvider {
- static var previews: some View {
- HealthcheckStatsView(activeCount: .constant(2), warningCount: .constant(0), alarmCount: .constant(3), pausedCount: .constant(1))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- HealthcheckStatsView(activeCount: .constant(2), warningCount: .constant(0), alarmCount: .constant(3), pausedCount: .constant(1))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
diff --git a/IPv64/Main/Healthcheck/Sheets/EditHealthcheckView.swift b/IPv64/Main/Healthcheck/Sheets/EditHealthcheckView.swift
deleted file mode 100644
index 2e9ccc5..0000000
--- a/IPv64/Main/Healthcheck/Sheets/EditHealthcheckView.swift
+++ /dev/null
@@ -1,190 +0,0 @@
-//
-// EditHealthcheckView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 21.01.23.
-//
-
-import SwiftUI
-
-struct EditHealthcheckView: View {
-
- @Environment(\.presentationMode) var presentationMode
- @AppStorage("IntegrationList") var integrationListS: String = ""
-
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = nil
- @State var showSheet = false
- @State var healthcheck: HealthCheck
- @Binding var updatedItem: Bool
- @State var alarmCount = 0.0
- @State var graceCount = 0.0
- @State var notifyDown = false
- @State var notifyUp = false
- @State var integrationIds = ""
-
- @State var integrationList: [Integration] = []
-
- var AlarmUnitList: [AlarmUnit] = [
- AlarmUnitTypes.minutes,
- AlarmUnitTypes.stunden,
- AlarmUnitTypes.tage
- ]
-
- fileprivate func GetUnit(unit: Int) -> String {
- if (unit == AlarmUnitTypes.minutes.id) {
- return AlarmUnitTypes.minutes.text!
- } else if (unit == AlarmUnitTypes.stunden.id) {
- return AlarmUnitTypes.stunden.text!
- } else {
- return AlarmUnitTypes.tage.text!
- }
- }
-
- var body: some View {
- ZStack {
- NavigationView {
- VStack {
- Form {
- Section("Name") {
- TextField("Healthcheck #002", text: $healthcheck.name)
- }
- Section("Zeitraum") {
- Text("\(Int(alarmCount)) \(GetUnit(unit: healthcheck.alarm_unit))")
- Slider(value: $alarmCount, in: 1...60, step: 1.0)
- Picker(selection: $healthcheck.alarm_unit, label: Text("Zeitraum")) {
- ForEach(0 ..< AlarmUnitList.count) {
- Text(AlarmUnitList[$0].text!)
- .tag(AlarmUnitList[$0].id!)
- }
- }
- }
- Section("Karenzzeit") {
- Text("\(Int(graceCount)) \(GetUnit(unit: healthcheck.grace_unit))")
- Slider(value: $graceCount, in: 1...60, step: 1.0)
- Picker(selection: $healthcheck.grace_unit, label: Text("Zeitraum")) {
- ForEach(0 ..< AlarmUnitList.count) {
- Text(AlarmUnitList[$0].text!)
- .tag(AlarmUnitList[$0].id!)
- }
- }
- }
- Section("Benachrichtigung") {
- /*let intList = integrationList
- Picker(selection: $integrationId, label: Text("Benachrichtungsmethode")) {
- ForEach(0 ..< intList.count) {
- Text(intList[$0].integration_name!)
- .tag(intList[$0].integration_id)
- }
- }*/
- Button(action: {
- withAnimation {
- activeSheet = .integrationselection
- }
- }) {
- Text("Benachrichtigungsmethoden")
- }
- Toggle(isOn: $notifyDown) {
- Text("Benachrichtung bei DOWN")
- }.tint(.red)
- Toggle(isOn: $notifyUp) {
- Text("Benachrichtung bei UP")
- }.tint(.green)
- }
- }
- }
- .navigationTitle("Bearbeiten")
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- .toolbar {
- ToolbarItem {
- Button(action: {
- if (healthcheck.name.count > 0) {
- Task {
- healthcheck.alarm_count = Int(alarmCount)
- healthcheck.grace_count = Int(graceCount)
- healthcheck.alarm_down = notifyDown ? 1 : 0
- healthcheck.alarm_up = notifyUp ? 1 : 0
- let res = await api.PostEditHealthcheck(healthcheck: healthcheck, integrationId: integrationIds)
- withAnimation {
- if (res?.info == "success") {
- activeSheet = .error
- errorTyp = ErrorTypes.healthcheckUpdatedSuccesfully
- updatedItem = true
- } else if (res?.info == "error") {
- activeSheet = .error
- } else if (res?.info == "Updateintervall overcommited") {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- }
- }
- }
- }
- }) {
- Image(systemName: "paperplane")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- }
- .onAppear {
- alarmCount = Double(healthcheck.alarm_count)
- graceCount = Double(healthcheck.grace_count)
- notifyUp = healthcheck.alarm_up == 1
- notifyDown = healthcheck.alarm_down == 1
- integrationIds = healthcheck.integration_id.replacingOccurrences(of: ",", with: "_")
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = integrationListS.data(using: .utf8)
- integrationList = try jsonDecoder.decode([Integration].self, from: jsonData!)
- } catch {
- print("ERROR \(error.localizedDescription)")
- }
- }
- .tint(Color("ip64_color"))
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- }
-
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(true)
- .onDisappear {
- if (self.errorTyp!.status == 201) {
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- case .integrationselection:
- IntegrationSelection(integrationIds: $integrationIds)
- default:
- EmptyView()
- }
- }
-}
-
-struct EditHealthcheckView_Previews: PreviewProvider {
- static var previews: some View {
- EditHealthcheckView(healthcheck: DummyData.Healthcheck, updatedItem: .constant(false))
- .preferredColorScheme(.light)
- .previewDisplayName("Light Mode")
- EditHealthcheckView(healthcheck: DummyData.Healthcheck, updatedItem: .constant(false))
- .preferredColorScheme(.dark)
- .previewDisplayName("Dark Mode")
- }
-}
diff --git a/IPv64/Main/Healthcheck/Sheets/IntegrationSelection.swift b/IPv64/Main/Healthcheck/Sheets/IntegrationSelection.swift
deleted file mode 100644
index d10bbb2..0000000
--- a/IPv64/Main/Healthcheck/Sheets/IntegrationSelection.swift
+++ /dev/null
@@ -1,64 +0,0 @@
-//
-// IntegrationSelection.swift
-// IPv64
-//
-// Created by Sebastian Rank on 07.03.23.
-//
-
-import SwiftUI
-
-struct IntegrationSelection: View {
- @Environment(\.presentationMode) var presentationMode
- @AppStorage("IntegrationList") var integrationListS: String = ""
- @Binding var integrationIds: String
- @State var integrationList: [Integration] = []
- @State private var selection = Set()
- @State var editMode: EditMode = .active
-
- var body: some View {
- NavigationView {
- List(integrationList, id: \.integration_id, selection: $selection) { i in
- Text(i.integration_name!.replacingOccurrences(of: """, with: "\""))
- }
- .navigationTitle("Benachrichten auf")
- .environment(\.editMode, self.$editMode)
- .onAppear {
- var splitSel = integrationIds.split(separator: "_")
- splitSel.forEach { i in
- if (Int(i)! != 0) {
- selection.insert(Int(i)!)
- }
- }
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = integrationListS.data(using: .utf8)
- integrationList = try jsonDecoder.decode([Integration].self, from: jsonData!).sorted { $0.integration_name!.lowercased() < $1.integration_name!.lowercased()
- }
- } catch {
- print("ERROR \(error.localizedDescription)")
- }
- }
- .toolbar {
- Button(action: {
- withAnimation {
- integrationIds = selection.compactMap { $0.description }
- .joined(separator: "_")
- if (integrationIds.count == 0) {
- integrationIds = "0"
- }
- print(integrationIds)
- presentationMode.wrappedValue.dismiss()
- }
- }) {
- Text("Speichern")
- }
- }
- }
- }
-}
-
-struct IntegrationSelection_Previews: PreviewProvider {
- static var previews: some View {
- IntegrationSelection(integrationIds: .constant(""))
- }
-}
diff --git a/IPv64/Main/Healthcheck/Sheets/NewHealthcheckView.swift b/IPv64/Main/Healthcheck/Sheets/NewHealthcheckView.swift
deleted file mode 100644
index 1e1cf7c..0000000
--- a/IPv64/Main/Healthcheck/Sheets/NewHealthcheckView.swift
+++ /dev/null
@@ -1,127 +0,0 @@
-//
-// NewHealthcheckView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 16.01.23.
-//
-
-import SwiftUI
-
-struct NewHealthcheckView: View {
-
- @Environment(\.presentationMode) var presentationMode
- @Binding var newItem: Bool
- @ObservedObject var api: NetworkServices = NetworkServices()
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = nil
- @State var showSheet = false
- @State var healthName = ""
- @State var healthAlarmCount = 30.0
- @State var healthAlarmUnit = 1
-
- var AlarmUnitList: [AlarmUnit] = [
- AlarmUnitTypes.minutes,
- AlarmUnitTypes.stunden,
- AlarmUnitTypes.tage
- ]
-
- fileprivate func GetUnit() -> String {
- if (healthAlarmUnit == AlarmUnitTypes.minutes.id) {
- return AlarmUnitTypes.minutes.text!
- } else if (healthAlarmUnit == AlarmUnitTypes.stunden.id) {
- return AlarmUnitTypes.stunden.text!
- } else {
- return AlarmUnitTypes.tage.text!
- }
- }
-
- var body: some View {
- ZStack {
- NavigationView {
- VStack {
- Form {
- Section("Benötigte Informationen") {
- TextField("Healthcheck #002", text: $healthName)
- Text("\(Int(healthAlarmCount)) \(GetUnit())")
- Slider(value: $healthAlarmCount, in: 1...60, step: 1.0)
- Picker(selection: $healthAlarmUnit, label: Text("Zeitraum")
- .font(.system(.callout))
- .padding(.horizontal, 5)) {
- ForEach(0 ..< AlarmUnitList.count) {
- Text(AlarmUnitList[$0].text!)
- .tag(AlarmUnitList[$0].id!)
- }
- }
- }
- }
- }
- .navigationTitle("Neuer Healthcheck")
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- .toolbar {
- ToolbarItem {
- Button(action: {
- if (healthName.count > 0) {
- Task {
- let res = await api.PostHealth(add_healthcheck: healthName, alarm_count: Int(healthAlarmCount), alarm_unit: healthAlarmUnit)
- if (res?.info == "success") {
- activeSheet = .error
- errorTyp = ErrorTypes.healthcheckCreatedSuccesfully
- newItem = true
- } else if (res?.info == "error") {
- activeSheet = .error
- } else if (res?.info == "Updateintervall overcommited") {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- }
- }
- }
- }) {
- Image(systemName: "paperplane")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- .foregroundColor(.black)
- }
- }
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- }
- }
-
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .add:
- EmptyView()
- case .detail:
- EmptyView()
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(true)
- .onDisappear {
- if (self.errorTyp!.status == 201) {
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }
- }
- default:
- EmptyView()
- }
- }
-}
-
-struct NewHealthcheckView_Previews: PreviewProvider {
- static var previews: some View {
- NewHealthcheckView(newItem: .constant(false))
- }
-}
diff --git a/IPv64/Main/Integrations/IntegrationView.swift b/IPv64/Main/Integrations/IntegrationView.swift
deleted file mode 100644
index a6be9eb..0000000
--- a/IPv64/Main/Integrations/IntegrationView.swift
+++ /dev/null
@@ -1,264 +0,0 @@
-//
-// IntegrationView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 09.03.23.
-//
-
-import SwiftUI
-import Introspect
-import Toast
-
-struct IntegrationView: View {
-
- @AppStorage("AccountInfos") var accountInfos: String = ""
- @AppStorage("IntegrationList") var integrationListS: String = ""
- @ObservedObject var api: NetworkServices = NetworkServices()
-
- @Binding var popToRootTab: Tab
-
- @State var deleteThisIntegration = false
- @State var activeSheet: ActiveSheet? = nil
- @State var errorTyp: ErrorTyp? = .none
- @State var integrationList: IntegrationResult? = nil
-
- @State var deleteIntegrationId = 0
-
- fileprivate func deleteIntegrationDialog() {
- errorTyp = ErrorTypes.deleteIntegration
- activeSheet = .error
- print(errorTyp)
- }
-
- var body: some View {
- ZStack {
- NavigationView {
- VStack {
- Form {
- Section("Integrations") {
- if (integrationList == nil) {
- Text("Keine Daten gefunden!")
- } else {
- ForEach(GetSortedIntegrationList(), id: \.i_uuid) { ig in
- LazyVStack {
- HStack {
- GetSystemImage(ig: ig.integration!)
- Text(ig.integration_name!.replacingOccurrences(of: """, with: "\""))
- Spacer()
- }
- .id(UUID())
- }
- .swipeActions(edge: .trailing) {
- Button(role: .destructive, action: {
- deleteIntegrationId = ig.integration_id
- deleteIntegrationDialog()
- }) {
- Label("Löschen", systemImage: "trash")
- }
- .tint(.red)
- }
- }
- }
- }
- }
- }
- .navigationTitle(Tab.integrations.labelName)
- .refreshable {
- GetIntegrations()
- }
- }
- .introspectNavigationController { navigationController in
- navigationController.splitViewController?.preferredPrimaryColumnWidthFraction = 1
- navigationController.splitViewController?.maximumPrimaryColumnWidth = 400
- }
- .accentColor(Color("AccentColor"))
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
-
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- .onAppear {
- GetIntegrations()
- }
- }
-
- @ViewBuilder
- func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: $deleteThisIntegration)
- .interactiveDismissDisabled(errorTyp?.status == 202 ? false : true)
- .onDisappear {
- if (deleteThisIntegration) {
- Task {
- let res = await api.DeleteIntegration(integration_id: deleteIntegrationId)
-
-
- let toast = Toast.default(
- image: GetUIImage(imageName: "checkmark.circle", color: UIColor.systemGreen, hierarichal: true),
- title: "Erfolgreich gelöscht!", config: .init(
- direction: .top,
- autoHide: true,
- enablePanToClose: false,
- displayTime: 4,
- enteringAnimation: .fade(alphaValue: 0.5),
- exitingAnimation: .slide(x: 0, y: -100))
- )
- toast.show(haptic: .success)
-
- GetIntegrations()
- }
- } else {
- if (errorTyp?.status == 401) {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: "")
- } else {
- GetIntegrations()
- }
- }
- }
- default:
- EmptyView()
- }
- }
-
- fileprivate func GetSortedIntegrationList() -> [Integration] {
- var igList = (integrationList?.integration.sorted { ($0.integration_name?.lowercased())! < ($1.integration_name?.lowercased())! }) ?? []
- print(igList)
- return igList
- }
-
- @ViewBuilder
- fileprivate func GetSystemImage(ig: String) -> some View {
- switch ig {
- case "mobil":
- Image(systemName: "ipad.and.iphone")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "email":
- Image(systemName: "mail")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "sms":
- Image(systemName: "message.badge")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "discord":
- Image("discord_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "telegram":
- Image("telegram_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "webhook":
- Image("webhook_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "gotify":
- Image("gotify_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "pushover":
- Image("pushover_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "ntfy":
- Image("ntfy_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- case "matrix":
- Image("matrix_icon")
- .resizable()
- .scaledToFill()
- .frame(width: 25, height: 25)
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- default:
- Image(systemName: "questionmark.square.dashed")
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("primaryText"))
- }
- }
-
- fileprivate func GetIntegrations() {
- Task {
- integrationList = await api.GetIntegrations()
- let status = integrationList?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && integrationList?.integration.count == 0) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- if (integrationList != nil) {
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(integrationList?.integration)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- integrationListS = json!
- }
- }
- }
- }
-
- fileprivate func DeleteIntegration(integration_id: Int) {
- Task {
- let result = await api.DeleteIntegration(integration_id: integration_id)
- let status = integrationList?.status
- if (status == nil) {
- throw NetworkError.NoNetworkConnection
- }
- if (status!.contains("429") && integrationList?.integration.count == 0) {
- activeSheet = .error
- errorTyp = ErrorTypes.tooManyRequests
- } else if (status!.contains("401")) {
- activeSheet = .error
- errorTyp = ErrorTypes.unauthorized
- } else {
- activeSheet = nil
- errorTyp = nil
- if (integrationList != nil) {
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(integrationList?.integration)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- integrationListS = json!
- }
- }
- }
-
- }
-}
-
-#Preview {
- IntegrationView(popToRootTab: .constant(.other))
-}
diff --git a/IPv64/Main/LockView.swift b/IPv64/Main/LockView.swift
deleted file mode 100644
index 0488fad..0000000
--- a/IPv64/Main/LockView.swift
+++ /dev/null
@@ -1,104 +0,0 @@
-//
-// LockView.swift
-// Tokey
-//
-// Created by Sebastian Rank on 05.04.22.
-//
-
-import SwiftUI
-
-struct LockView: View {
-
- @State var showDomains = false
- @State private var frameWidth: CGFloat = .infinity
- @ObservedObject private var bio = Biometrics()
-
- var body: some View {
- ZStack {
- if !showDomains {
- VStack(alignment: .center) {
- Image(systemName: "lock.shield")
- .resizable()
- .scaledToFit()
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(Color("ip64_color"))
- .frame(width: 75, height: 75, alignment: .center)
- .padding(.bottom, 25)
- Text("Bitte verwende FaceID/TouchID um IPv64.net zu entsperren")
- .font(.system(.callout, design: .rounded))
- .foregroundColor(Color("primaryText"))
- .padding(.bottom)
- .multilineTextAlignment(.center)
- .frame(maxWidth: .infinity, alignment: .center)
- HStack {
- Button(action: {
- withAnimation {
- bio.disableFields = true
- bio.tryToAuthenticate()
- }
- }) {
- ZStack {
- if bio.disableFields {
- Spinner(isAnimating: true, style: .large, color: UIColor.white)
- } else {
- HStack {
- Image(systemName: Biometrics.GetBiometricSymbol())
- .resizable()
- .symbolRenderingMode(.hierarchical)
- .scaledToFit()
- .frame(width: 24, height: 24, alignment: .center)
- .padding(.trailing, 10)
- Text("Entsperren")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- }
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color.white)
- .background(Color("ip64_color")).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- }
- .frame(maxWidth: .infinity, maxHeight: 55)
- .background(Color("ip64_color")).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .buttonStyle(PlainButtonStyle())
- .disabled(bio.disableFields)
- .padding(EdgeInsets(top: 10, leading: 0, bottom: 0, trailing: 0))
- }
- }
- .padding(16)
- .onAppear {
- frameWidth = Functions.getOrientationWidth()
- bio.reset()
- bio.tryToAuthenticate()
- }
- .onChange(of: bio.isAuthenticated) { value in
- withAnimation {
- if bio.isAuthenticated {
- showDomains = true
- let generator = UINotificationFeedbackGenerator()
- generator.notificationOccurred(.success)
- }
- }
- }
- .frame(maxWidth: frameWidth, maxHeight: .infinity)
- } else {
- TabbView(showDomains: $showDomains)
- }
- }
- .onRotate { _ in
- frameWidth = Functions.getOrientationWidth()
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- }
-}
-
-struct LockView_Previews: PreviewProvider {
- static var previews: some View {
- LockView()
- .preferredColorScheme(.light)
- LockView()
- .preferredColorScheme(.dark)
- }
-}
diff --git a/IPv64/Main/LoginView.swift b/IPv64/Main/LoginView.swift
deleted file mode 100644
index 981eac3..0000000
--- a/IPv64/Main/LoginView.swift
+++ /dev/null
@@ -1,261 +0,0 @@
-//
-// LoginView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 06.11.22.
-//
-
-import SwiftUI
-
-struct LoginView: View {
-
- @AppStorage("NEW_ACCOUNT") var newAccount = false
- @AppStorage("AccountInfos") var accountInfosJson: String = ""
- @AppStorage("AccountList") var accountListJson: String = ""
-
- @ObservedObject var api: NetworkServices = NetworkServices()
-
- @State var actionSheet: ActiveSheet?
- @State var errorTyp: ErrorTyp? = nil
- @State var username = ""
- @State var apiKey = ""
- @State private var errorMsg = ""
- @State var showMainView = false
- @State var loginFailed = false
- @State var accountInfos = AccountInfo()
- @State private var accountList: [Account] = []
-
- var body: some View {
- GeometryReader { geometry in
- if (!showMainView) {
- ZStack {
- ScrollView {
- VStack {
- Image("ipv64_logo_new")
- .resizable()
- .scaledToFit()
- .frame(height: 60)
- .padding()
- .background(RoundedRectangle(cornerRadius: 12).fill(Color("lightgray")))
- .padding(.bottom, 20)
-
- Button(action: {
- withAnimation {
- actionSheet = .qrcode
- }
- }) {
- Text("Login mit QR Code")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color.white)
- .background(Color("ip64_color")).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .padding(.vertical)
-
- HStack {
- VStack {}
- .frame(maxWidth: .infinity, maxHeight: 1)
- .background(Color.gray)
- .padding(.trailing, 16)
- Text("ODER")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- VStack {}
- .frame(maxWidth: .infinity, maxHeight: 1)
- .background(Color.gray)
- .padding(.trailing, 16)
- }
- .padding(.horizontal, 16)
-
- TextField("API - Key", text: $apiKey)
- .font(.system(.body, design: .rounded))
- .padding(EdgeInsets(top: 20.5, leading: 16, bottom: 20.5, trailing: 0))
- .background(Color("textFieldBG")).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- .padding(.top, 6)
- .tint(Color("ip64_color"))
-
- Button(action: {
- withAnimation {
- if (newAccount) {
- addNewAccount()
- } else {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: apiKey)
- showMainView.toggle()
- }
- }
- }) {
- Text("Login mit API Key")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color.white)
- .background(Color("ip64_color")).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .padding(.vertical)
-
- if (loginFailed) {
- if #available(iOS 16.0, *) {
- Text("Login fehlgeschlagen!\n\(errorMsg)")
- .font(.system(.body, design: .rounded, weight: .bold))
- .foregroundColor(.red)
- } else {
- Text("Login fehlgeschlagen!\n\(errorMsg)")
- .font(.system(.body, design: .rounded).bold())
- .foregroundColor(.red)
- }
- }
- }
- .padding()
- .frame(width: UIDevice.isIPhone ? geometry.size.width : geometry.size.width / 1.75, height: geometry.size.height)
- }
- .frame(maxWidth: .infinity)
- .sheet(item: $actionSheet) { item in
- showActiveSheet(item: item)
- }
- .onAppear {
- if (!accountListJson.isEmpty) {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountListJson.data(using: .utf8)
- accountList = try jsonDecoder.decode([Account].self, from: jsonData!)
- print(accountList)
- } catch {
- print("ERROR \(error.localizedDescription)")
- }
- }
- }
- if api.isLoading {
- VStack() {
- Spinner(isAnimating: true, style: .large, color: .white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.black.opacity(0.3).ignoresSafeArea())
- }
- }
- } else {
- TabbView(showDomains: .constant(true))
- }
- }
- }
-
- @ViewBuilder
- private func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .qrcode:
- CodeScannerView(codeTypes: [.qr], simulatedData: "", completion: self.handleScan).edgesIgnoringSafeArea(.bottom)
- case .error:
- ErrorSheetView(errorTyp: $errorTyp, deleteThisDomain: .constant(false))
- .interactiveDismissDisabled(true)
- .onDisappear {
- if (self.errorTyp!.status == 201) {
- withAnimation {
- errorTyp = nil
- actionSheet = nil
- newAccount = false
- showMainView.toggle()
- apiKey = ""
- }
- }
- }
- default:
- EmptyView()
- }
- }
-
- private func addNewAccount() {
- if (apiKey.isEmpty) {
- return;
- }
-
- let accountInd = accountList.firstIndex { $0.ApiKey == apiKey }
- if (accountInd != nil && accountInd != -1) {
- errorTyp = ErrorTypes.accountFound
- actionSheet = .error
- } else {
- Task {
- do {
- await getAccountInfos()
-
- if (accountInfos.api_key == nil) {
- errorTyp = ErrorTypes.accountNotFound
- actionSheet = .error
- } else {
-
- let sdtoken = SetupPrefs.readPreference(mKey: "DEVICETOKEN", mDefaultValue: "") as! String
-
- let result = await api.PostAddIntegration(integrationType: "mobil", dtoken: sdtoken, dName: UIDevice().type.rawValue, apiKey: apiKey)
-
- print(result)
-
- let account = Account(ApiKey: apiKey, AccountName: accountInfos.email, DeviceToken: sdtoken, Since: accountInfos.reg_date, Active: false)
-
- accountList.append(account)
-
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(accountList)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountListJson = json!
-
- actionSheet = .error
- errorTyp = ErrorTypes.accountSuccessfullyAdded
- }
- } catch let error {
- print(error)
- }
- }
- }
- }
-
- private func handleScan(result: Result) {
- switch result {
- case .success(let data): do {
- apiKey = data
- loginFailed = false
- if (newAccount) {
- addNewAccount()
- } else {
- SetupPrefs.setPreference(mKey: "APIKEY", mValue: apiKey)
- showMainView.toggle()
- withAnimation {
- self.actionSheet = nil
- }
- }
- } case .failure(let error): do {
- errorMsg = error.localizedDescription
- loginFailed = true
- withAnimation {
- self.actionSheet = nil
- }
- }}
- }
-
- fileprivate func loadAccountInfos() {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountInfosJson.data(using: .utf8)
- accountInfos = try jsonDecoder.decode(AccountInfo.self, from: jsonData!)
- } catch let error {
- print(error)
- }
- }
-
- fileprivate func getAccountInfos() async {
- accountInfos = await api.GetAccountStatus(apiKey: apiKey) ?? AccountInfo()
- print(accountInfos)
- }
-}
-
-struct LoginView_Previews: PreviewProvider {
- static var previews: some View {
- LoginView()
- .preferredColorScheme(.dark)
- LoginView()
- .preferredColorScheme(.light)
- }
-}
diff --git a/IPv64/Main/Sheets/ErrorSheetView.swift b/IPv64/Main/Sheets/ErrorSheetView.swift
deleted file mode 100644
index 544eb5f..0000000
--- a/IPv64/Main/Sheets/ErrorSheetView.swift
+++ /dev/null
@@ -1,170 +0,0 @@
-//
-// ErrorSheetView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 07.11.22.
-//
-
-import SwiftUI
-
-struct ErrorSheetView: View {
- @Environment(\.presentationMode) var presentationMode
-
- @Binding var errorTyp: ErrorTyp?
- @Binding var deleteThisDomain: Bool
-
- @State var timeRemaining = 10
- let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
-
- var body: some View {
- NavigationView {
- VStack {
- Spacer()
- let icon = errorTyp!.icon!
-
- if (icon.contains(";")) {
- let splittetIcons = icon.split(separator: ";")
- ZStack {
- ZStack {
- Circle()
- .fill(Color("circleBG"))
- .frame(height: 220)
- Circle()
- .fill(Color("circleBG"))
- .frame(height: 75)
- .offset(x: 75, y: 55)
- }
- Image(systemName: String(splittetIcons[0]))
- .resizable()
- .scaledToFit()
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(errorTyp!.iconColor!)
- .frame(height: 115)
- .padding(25)
- Image(systemName: String(splittetIcons[1]))
- .resizable()
- .scaledToFit()
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(errorTyp!.iconColor!)
- .frame(height: 45)
- .padding()
- .offset(x: 70, y: 50)
-
- }
- } else {
- ZStack {
- ZStack {
- Circle()
- .fill(Color("circleBG"))
- .frame(height: 220)
- }
- Image(systemName: icon)
- .resizable()
- .scaledToFit()
- .symbolRenderingMode(.hierarchical)
- .foregroundColor(errorTyp!.iconColor!)
- .frame(height: 100)
- .padding(25)
-
- }
- }
- Spacer()
- VStack {
- Text(errorTyp!.errorTitle!)
- .multilineTextAlignment(.center)
- .font(.system(.title3, design: .rounded).bold())
- Text(errorTyp!.errorDescription!)
- .font(.system(.callout, design: .rounded))
- .multilineTextAlignment(.center)
- .padding()
- }
-
- Spacer()
-
- if (errorTyp!.status! == 429) {
- Button(action: {
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }) {
- Text(timeRemaining > 0 ? "Schließen (\(timeRemaining))" : "Schließen")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color.white)
- .background(Color("ip64_color")).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .disabled(timeRemaining > 0)
- .padding()
- } else if (errorTyp!.status! == 202) {
- Button(action: {
- withAnimation {
- deleteThisDomain = true
- presentationMode.wrappedValue.dismiss()
- }
- }) {
- Text("Wirklich löschen?")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color.white)
- .background(.red).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .padding([.horizontal, .top])
-
- Button(action: {
- withAnimation {
- presentationMode.wrappedValue.dismiss()
- }
- }) {
- Text("Abbrechen")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color("AccentColor"))
- .background(.gray.opacity(0.2)).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .padding([.horizontal, .bottom])
- } else {
- Button(action: {
- withAnimation {
- deleteThisDomain = false
- presentationMode.wrappedValue.dismiss()
- }
- }) {
- Text("Schließen")
- .font(.system(.callout, design: .rounded))
- .fontWeight(.bold)
- .textCase(.uppercase)
- .frame(minWidth: 0, maxWidth: .infinity)
- .padding(16)
- .foregroundColor(Color.white)
- .background(errorTyp!.iconColor!).clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .padding()
- }
- }
- .navigationTitle(errorTyp!.navigationTitle!)
- .navigationBarTitleDisplayMode(.inline)
- .onReceive(timer) { _ in
- if timeRemaining > 0 {
- timeRemaining -= 1
- } else {
- timer.upstream.connect().cancel()
- }
- }
- }
- }
-}
-
-struct ErrorSheetView_Previews: PreviewProvider {
- static var previews: some View {
- ErrorSheetView(errorTyp: .constant(ErrorTypes.unauthorized), deleteThisDomain: .constant(false))
- }
-}
diff --git a/IPv64/Main/TabbView.swift b/IPv64/Main/TabbView.swift
deleted file mode 100644
index 37159d2..0000000
--- a/IPv64/Main/TabbView.swift
+++ /dev/null
@@ -1,239 +0,0 @@
-//
-// TabView.swift
-// IPv64
-//
-// Created by Sebastian Rank on 25.11.22.
-//
-
-import SwiftUI
-import FirebaseMessaging
-
-struct TabbView: View {
-
- @AppStorage("BIOMETRIC_ENABLED") var isBiometricEnabled: Bool = false
- @AppStorage("AccountInfos") var accountInfosJson: String = ""
- @AppStorage("AccountList") var accountListJson: String = ""
- @AppStorage("ENABLE_NAV_SOUND") var enableNavSound: Bool = true
- @AppStorage("DomainResult") var listOfDomainsString: String = ""
- @AppStorage("current_Tab") var selectedTab: Tab = .domains
-
- @Binding var showDomains: Bool
-
- @ObservedObject var api: NetworkServices = NetworkServices()
-
- @State var activeSheet: ActiveSheet? = nil
- @State var accountInfos = AccountInfo()
-
- @State private var popToRootTab: Tab = .other
- @State private var showPlaceholder = false
- @State private var showWhatsNew = false
- @State private var accountList: [Account] = []
-
- private var availableTabs: [Tab] {
- Tab.tabList()
- }
-
- var body: some View {
- tabBarView
- }
-
- @ViewBuilder
- private func showActiveSheet(item: ActiveSheet?) -> some View {
- switch item {
- case .whatsnew:
- WhatsNewView(activeSheet: $activeSheet, isPresented: $showWhatsNew)
- default:
- EmptyView()
- }
- }
-
- private func sendFCMToken() {
- Messaging.messaging().isAutoInitEnabled = true
- Messaging.messaging().token { token, error in
- if let error = error {
- print("Error fetching FCM registration token: \(error)")
- } else if let token = token {
- print("FCM registration token: \(token)")
- print(UIDevice().type.rawValue)
- let os = ProcessInfo().operatingSystemVersion
- let sdtoken = SetupPrefs.readPreference(mKey: "DEVICETOKEN", mDefaultValue: "") as! String
- if (sdtoken != token) {
- Task {
- let api = NetworkServices()
- let result = await api.PostAddIntegration(integrationType: "mobil", dtoken: token, dName: UIDevice().type.rawValue)
- SetupPrefs.setPreference(mKey: "DEVICETOKEN", mValue: token)
- }
- }
- }
- }
- }
-
-
-
- private var tabBarView: some View {
- TabView(selection: .init(get: {
- selectedTab
- }, set: { newTab in
- Task {
- if newTab == selectedTab {
- /// Stupid hack to trigger onChange binding in tab views.
- popToRootTab = .other
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
- popToRootTab = selectedTab
- }
- }
-
- selectedTab = newTab
- if (enableNavSound) {
- await HapticManager.shared.fireHaptic(of: .tabSelection)
- await SoundEffectManager.shared.playSound(of: .tabSelection)
- }
- }
-
- })) {
- ForEach(availableTabs) { tab in
- tab.makeContentView(popToRootTab: $popToRootTab)
- .redacted(reason: showPlaceholder ? .placeholder : .init())
- .tabItem {
- tab.label
- .labelStyle(TitleAndIconLabelStyle())
- }
- .tag(tab)
- }
- }
- .tint(Color("ip64_color"))
- .sheet(item: $activeSheet) { item in
- showActiveSheet(item: item)
- }
- .onAppear {
- let tabBarAppearance = UITabBarAppearance()
- tabBarAppearance.configureWithDefaultBackground()
- UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
-
- UIApplication.shared.applicationIconBadgeNumber = 0
- SetupPrefs.setPreference(mKey: "BADGE_COUNT", mValue: 0)
-
- if (accountListJson.isEmpty) {
- Task {
- await createAccountList()
- }
- }
-
- var lastBuildNumber = SetupPrefs.readPreference(mKey: "LASTBUILDNUMBER", mDefaultValue: "0") as! String
- var token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- if Int(lastBuildNumber) != Int(Bundle.main.buildNumber) && !token.isEmpty {
- withAnimation {
- showWhatsNew = true
- activeSheet = .whatsnew
- }
- }
-
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
- sendFCMToken()
- }
- }
- .onOpenURL { url in
- print("URL")
- guard url.scheme == "ipv64", url.host == "tab", let tabId = Int(url.pathComponents[1])
- else {
- print("issue")
- return
- }
-
- var tab: Tab = .other
-
- if (tabId == 1) {
- tab = .domains
- } else if (tabId == 2) {
- tab = .healthchecks
- } else if (tabId == 3) {
- tab = .integrations
- } else if (tabId == 4) {
- tab = .profile
- }
-
- selectedTab = tab
- }
- .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
- print("Moving to the background! didBecomeActiveNotification")
- withAnimation {
- showPlaceholder = false
- }
- }
- .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
- print("Moving to the background! willResignActiveNotification")
- withAnimation {
- if (isBiometricEnabled) {
- showPlaceholder = true
- }
- }
- }
- .onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)) { _ in
- print("Moving to the background! willTerminateNotification")
- }
- .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
- print("Moving to the background! willEnterForegroundNotification")
- withAnimation {
- showPlaceholder = false
- showDomains = false
-
- UIApplication.shared.applicationIconBadgeNumber = 0
- SetupPrefs.setPreference(mKey: "BADGE_COUNT", mValue: 0)
- }
- }
- .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
- withAnimation {
- // if UIDevice.current.userInterfaceIdiom == .pad {
- /*DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
- _ = Functions().getGridCount(width: geo!.size.width, gridItem: $columnsGrid)
- }*/
- // }
- }
- }
- }
-
- fileprivate func createAccountList() async {
- loadAccountInfos()
- if (!accountInfosJson.isEmpty) {
- do {
- let apikey = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- let sdtoken = SetupPrefs.readPreference(mKey: "DEVICETOKEN", mDefaultValue: "") as! String
-
- let account = Account(ApiKey: apikey, AccountName: accountInfos.email, DeviceToken: sdtoken, Since: accountInfos.reg_date, Active: true)
-
- accountList.append(account)
-
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(accountList)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountListJson = json!
- } catch let error {
- print(error)
- }
- } else {
- Task {
- accountInfos = await api.GetAccountStatus() ?? AccountInfo()
- print(accountInfos)
- let jsonEncoder = JSONEncoder()
- let jsonData = try jsonEncoder.encode(accountInfos)
- let json = String(data: jsonData, encoding: String.Encoding.utf8)
- accountInfosJson = json!
- await createAccountList()
- }
- }
- }
-
- fileprivate func loadAccountInfos() {
- do {
- let jsonDecoder = JSONDecoder()
- let jsonData = accountInfosJson.data(using: .utf8)
- accountInfos = try jsonDecoder.decode(AccountInfo.self, from: jsonData!)
- } catch let error {
- print(error)
- }
- }
-}
-
-#Preview {
- TabbView(showDomains: .constant(true))
-}
diff --git a/IPv64/Main/Tabs.swift b/IPv64/Main/Tabs.swift
deleted file mode 100644
index cca7b8a..0000000
--- a/IPv64/Main/Tabs.swift
+++ /dev/null
@@ -1,95 +0,0 @@
-//
-// Tabs.swift
-// IPv64
-//
-// Created by Sebastian Rank on 08.08.23.
-//
-
-import SwiftUI
-
-enum Tab: Int, Identifiable, Hashable {
- case domains, healthchecks, integrations, profile, blocklist, other
-
- var id: Int {
- rawValue
- }
-
- static func tabList() -> [Tab] {
- // if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac {
- // return [.timeline, .trending, .federated, .local, .notifications, .mentions, .explore, .messages, .settings]
- // } else {
- // return [.timeline, .notifications, .explore, .messages, .profile]
- // }
- return [.domains, .healthchecks, .integrations, .blocklist, .profile]
- }
-
- @ViewBuilder
- func makeContentView(popToRootTab: Binding) -> some View {
- switch self {
- case .domains:
- ContentView(popToRootTab: popToRootTab)
- case .healthchecks:
- HealthcheckView(popToRootTab: popToRootTab)
- case .integrations:
- IntegrationView(popToRootTab: popToRootTab)
- case .profile:
- ProfilView(popToRootTab: popToRootTab)
- case .blocklist:
- BlocklistView(popToRootTab: popToRootTab)
- case .other:
- EmptyView()
- }
- }
-
- @ViewBuilder
- var label: some View {
- switch self {
- case .domains:
- Label(labelName, systemImage: iconName)
- case .healthchecks:
- Label(labelName, systemImage: iconName)
- case .integrations:
- Label(labelName, systemImage: iconName)
- case .profile:
- Label(labelName, systemImage: iconName)
- case .blocklist:
- Label(labelName, systemImage: iconName)
- case .other:
- EmptyView()
- }
- }
-
- var iconName: String {
- switch self {
- case .domains:
- return "network"
- case .healthchecks:
- return "bolt.heart"
- case .integrations:
- return "bell.and.waveform"
- case .profile:
- return "person.circle"
- case .blocklist:
- return "shield.lefthalf.filled"
- case .other:
- return ""
- }
- }
-
- var labelName: String {
- switch self {
- case .domains:
- return "Domains"
- case .healthchecks:
- return "Health"
- case .integrations:
- return "Mitteilungen"
- case .profile:
- return "Account"
- case .blocklist:
- return "Blocklist"
- case .other:
- return ""
- }
- }
-}
diff --git a/IPv64/Main/WhatsNew/WhatsNewItemView.swift b/IPv64/Main/WhatsNew/WhatsNewItemView.swift
deleted file mode 100644
index 4b0a512..0000000
--- a/IPv64/Main/WhatsNew/WhatsNewItemView.swift
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// WhatsNewItemView.swift
-// Treibholz
-//
-// Created by Sebastian Rank on 16.02.22.
-//
-
-import SwiftUI
-
-struct WhatsNewItemView: View {
-
- @State var whatsNewItem: WhatsNewObj
-
- var body: some View {
- VStack(alignment: .leading) {
- HStack(alignment: .top) {
- Image(systemName: whatsNewItem.imageName)
- .resizable()
- .scaledToFit()
- .frame(width: 30, height: 30)
- .symbolRenderingMode(.hierarchical)
- .padding(.horizontal)
- .foregroundColor(Color("ip64_color"))
- VStack(alignment: .leading, spacing: 5) {
- Text(whatsNewItem.title)
- .font(.system(.headline, design: .rounded))
- .fontWeight(.bold)
- Text(whatsNewItem.subtitle)
- .font(.system(.footnote, design: .rounded))
- .foregroundColor(Color("primaryText"))
- }
- .padding(.trailing)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- .padding(.horizontal)
- .padding(.bottom)
- .frame(maxWidth: .infinity)
- }
- }
-}
-
-struct WhatsNewItemView_Previews: PreviewProvider {
- static var previews: some View {
- WhatsNewItemView(whatsNewItem: WhatsNewObj(imageName: "sparkles", title: "Was ist Neu?", subtitle: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren"))
- }
-}
diff --git a/IPv64/Main/WhatsNew/WhatsNewView.swift b/IPv64/Main/WhatsNew/WhatsNewView.swift
deleted file mode 100644
index 42bd3fd..0000000
--- a/IPv64/Main/WhatsNew/WhatsNewView.swift
+++ /dev/null
@@ -1,67 +0,0 @@
-//
-// WhatsNewView.swift
-// Treibholz
-//
-// Created by Sebastian Rank on 16.02.22.
-//
-
-import SwiftUI
-
-struct WhatsNewView: View {
- @Binding var activeSheet: ActiveSheet?
- @Binding var isPresented: Bool
- var isFromSetting = false
-
- var whatsNewList = [
- WhatsNewObj(imageName: "ant.circle", title: "Fehlerbehebung", subtitle: "Es wurden in diesem Update ein Paar Fehler behoben, die zur Steigerung der Performance und der Nutzbarkeit dienen"),
- WhatsNewObj(imageName: "person.circle", title: "Multi-User Support", subtitle: "Ihr könnt jetzt mehr als 1 Account in der App hinterlegen um Private & Firmenaccount über ein Gerät zuverwalten!"),
- WhatsNewObj(imageName: "switch.2", title: "Toggle hinzugefügt", subtitle: "Es wurde ein neuer Toggle Switch hinzugefügt der den Tabsound in der Navigationleiste steuert!")
- ]
-
- var body: some View {
- VStack {
- VStack {
- Text("Was ist neu in")
- .font(.system(.largeTitle, design: .rounded))
- .fontWeight(.bold)
- .frame(maxWidth: .infinity, alignment: .center)
- Text("v\(Bundle.main.versionNumber)?")
- .font(.system(.largeTitle, design: .rounded))
- .fontWeight(.bold)
- .frame(maxWidth: .infinity, alignment: .center)
- }
- .padding(.vertical, 27.5)
-
- Spacer()
-
- ScrollView {
- ForEach(whatsNewList, id: \.id) { item in
- WhatsNewItemView(whatsNewItem: item)
- }
- }
-
- Button(action: {
- withAnimation {
- let buildNumber = Bundle.main.buildNumber
- SetupPrefs.setPreference(mKey: "LASTBUILDNUMBER", mValue: buildNumber)
- activeSheet = nil
- }
- }) {
- Text(isFromSetting ? "Schließen" : "Fortfahren").font(.headline)
- .foregroundColor(.white)
- .padding()
- .frame(maxWidth: .infinity, minHeight: 50, idealHeight: 50, maxHeight: 50, alignment: .center)
- .background(Color("ip64_color"))
- .cornerRadius(16.0)
- }
- .padding(.horizontal, 27.5)
- .padding(.bottom, UIDevice.isIPad ? 27.5 : 8)
- }.interactiveDismissDisabled(!isFromSetting)
- }
-}
-
-struct WhatsNewView_Previews: PreviewProvider {
- static var previews: some View {
- WhatsNewView(activeSheet: .constant(nil), isPresented: .constant(false))
- }
-}
diff --git a/IPv64/Models&Helpers/Biometrics.swift b/IPv64/Models&Helpers/Biometrics.swift
deleted file mode 100644
index 65975cc..0000000
--- a/IPv64/Models&Helpers/Biometrics.swift
+++ /dev/null
@@ -1,113 +0,0 @@
-//
-// Biometrics.swift
-//
-//
-// Created by Sebastian Rank on 05.04.22.
-//
-
-import Foundation
-import LocalAuthentication
-
-class Biometrics: ObservableObject {
-
- @Published var isAuthenticated = false
- @Published var disableFields = true
- @Published private(set) var error: Error?
-
- static func GetBiometricSymbol() -> String {
- if (LAContext().biometryType == .faceID) {
- return "faceid"
- } else if (LAContext().biometryType == .touchID) {
- return "touchid"
- } else {
- return "lock.circle"
- }
- }
-
- static func GetBiometricText() -> String {
- if (LAContext().biometryType == .faceID) {
- return "FaceID"
- } else if (LAContext().biometryType == .touchID) {
- return "TouchID"
- } else {
- return "PIN"
- }
- }
-
- func reset() {
- isAuthenticated = false
- disableFields = true
- }
-
- func tryToAuthenticate(isIntro: Bool = false) {
- let context = LAContext()
- var error: NSError?
- let reason = "Bitte authentifiziere dich, um mit der App fortzufahren."
-
- guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
- print("No Biometric Sensor Has Been Detected. This device does not support FaceID/TouchID.")
- self.disableFields = false
- tryToAuthenticatePIN()
- return
- }
-
- context.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: { (success, error) -> Void in
- DispatchQueue.main.async {
- self.error = error
- if success {
- print("FaceID/TouchID. You are a device owner!")
- self.isAuthenticated = true
- } else {
- print(error!)
- // Check if there is an error
- if let errorObj = error as? LAError {
- print("Error took place. \(errorObj.localizedDescription)")
- if errorObj.code == .userCancel {
- self.isAuthenticated = false
- self.disableFields = false
- }
- if errorObj.code == .userFallback {
- self.tryToAuthenticatePIN()
- }
- }
- }
- }
- })
- }
-
- func tryToAuthenticatePIN() {
- let context = LAContext()
- var error: NSError?
- let reason = "Bitte authentifiziere dich, um mit der App fortzufahren."
-
- guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
- print("No Biometric Sensor Has Been Detected. This device does not support FaceID/TouchID.")
- self.disableFields = false
- return
- }
-
- context.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: reason, reply: { (success, error) -> Void in
- DispatchQueue.main.async {
- self.error = error
- if success {
- print("FaceID/TouchID. You are a device owner!")
- self.isAuthenticated = true
- } else {
- print(error!)
- // Check if there is an error
- if let errorObj = error as? LAError {
- print("Error took place. \(errorObj.localizedDescription)")
- if errorObj.code == .userCancel {
- self.isAuthenticated = false
- self.disableFields = false
- }
- if errorObj.code == .userFallback {
- self.isAuthenticated = false
- self.disableFields = false
- }
- }
- }
- }
- })
- }
-}
diff --git a/IPv64/Models&Helpers/HapticManager.swift b/IPv64/Models&Helpers/HapticManager.swift
deleted file mode 100644
index 0c5fd3a..0000000
--- a/IPv64/Models&Helpers/HapticManager.swift
+++ /dev/null
@@ -1,57 +0,0 @@
-import CoreHaptics
-import UIKit
-
-public class HapticManager {
- public static let shared: HapticManager = .init()
-
- public enum HapticType {
- case buttonPress
- case dataRefresh(intensity: CGFloat)
- case notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
- case tabSelection
- case timeline
- }
-
- private let selectionGenerator = UISelectionFeedbackGenerator()
- private let impactGenerator = UIImpactFeedbackGenerator(style: .heavy)
- private let notificationGenerator = UINotificationFeedbackGenerator()
-
- private let userPrefs = UserPrefs.shared
-
- private init() {
- selectionGenerator.prepare()
- impactGenerator.prepare()
- }
-
- @MainActor
- public func fireHaptic(of type: HapticType) {
- guard supportsHaptics else { return }
-
- switch type {
- case .buttonPress:
- if userPrefs.hapticButtonPressEnabled {
- impactGenerator.impactOccurred()
- }
- case let .dataRefresh(intensity):
- if userPrefs.hapticTimelineEnabled {
- impactGenerator.impactOccurred(intensity: intensity)
- }
- case let .notification(type):
- if userPrefs.hapticButtonPressEnabled {
- notificationGenerator.notificationOccurred(type)
- }
- case .tabSelection:
- if userPrefs.hapticTabSelectionEnabled {
- selectionGenerator.selectionChanged()
- }
- case .timeline:
- if userPrefs.hapticTimelineEnabled {
- selectionGenerator.selectionChanged()
- }
- }
- }
-
- public var supportsHaptics: Bool {
- CHHapticEngine.capabilitiesForHardware().supportsHaptics
- }
-}
diff --git a/IPv64/Models&Helpers/Models.swift b/IPv64/Models&Helpers/Models.swift
deleted file mode 100644
index 50582a8..0000000
--- a/IPv64/Models&Helpers/Models.swift
+++ /dev/null
@@ -1,1419 +0,0 @@
-//
-// Models.swift
-// IPv64
-//
-// Created by Sebastian Rank on 06.11.22.
-//
-
-import Foundation
-import SwiftUI
-
-enum NetworkError: Error {
- case NoNetworkConnection
-}
-
-struct DomainResult : Codable {
- var subdomains: [String: Domain]?
- var info: String?
- var status: String?
- var add_domain: String?
-
- enum CodingKeys: String, CodingKey {
- case subdomains = "subdomains"
- case info = "info"
- case status = "status"
- case add_domain = "add_domain"
- }
-}
-
-struct DomainItems : Codable {
- var id = UUID()
- var name: String?
- var list: [Domain]?
-
- enum CodingKeys: String, CodingKey {
- case id = "id"
- case name = "name"
- case list = "list"
- }
-}
-
-struct AddDomainResult : Codable {
- var info: String?
- var status: String?
- var add_domain: String?
-
- enum CodingKeys: String, CodingKey {
- case info = "info"
- case status = "status"
- case add_domain = "add_domain"
- }
-}
-
-struct Domain : Codable {
- var id = UUID()
- var name: String = ""
- var updates: Int?
- var wildcard: Int?
- var domain_update_hash: String?
- var records: [RecordInfos]?
-
- enum CodingKeys: String, CodingKey {
- case updates = "updates"
- case wildcard = "wildcard"
- case domain_update_hash = "domain_update_hash"
- case records = "records"
- }
-}
-
-struct RecordInfos: Codable {
- var record_id: Int?
- var content: String?
- var ttl: Int?
- var type: String?
- var praefix: String?
- var last_update: String?
-
- enum CodingKeys: String, CodingKey {
- case record_id = "record_id"
- case content = "content"
- case ttl = "ttl"
- case type = "type"
- case praefix = "praefix"
- case last_update = "last_update"
- }
-}
-
-struct MyIP: Codable {
- var ip: String?
-
- enum CodingKeys: String, CodingKey {
- case ip = "ip"
- }
-}
-
-struct MyLogs: Codable {
- var id: UUID = UUID()
- var subdomain: String?
- var time: String?
- var header: String?
- var content: String?
- var expandLog: Bool = false
-
- enum CodingKeys: String, CodingKey {
- case subdomain = "subdomain"
- case time = "time"
- case header = "header"
- case content = "content"
- }
-}
-
-struct Logs: Codable {
- var logs: [MyLogs]?
-
- enum CodingKeys: String, CodingKey {
- case logs = "logs"
- }
-}
-
-struct AccountInfo: Codable {
- var email: String? = ""
- var account_status: Int? = 0
- var reg_date: String? = "2022-01-01 00:00:00"
- var update_hash: String? = ""
- var api_key: String? = ""
- var dyndns_updates: Int? = 0
- var dyndns_subdomains: Int? = 0
- var owndomains: Int? = 0
- var healthchecks: Int? = 0
- var healthchecks_updates: Int? = 0
- var api_updates: Int? = 0
- var sms_count: Int? = 0
- var account_class: AccountClass? = AccountClass()
- var devicetoken: String? = ""
- var info: String? = ""
- var status: String? = ""
- var get_account_info: String? = ""
-
- enum CodingKeys: String, CodingKey {
- case email = "email"
- case account_status = "account_status"
- case reg_date = "reg_date"
- case update_hash = "update_hash"
- case api_key = "api_key"
- case dyndns_updates = "dyndns_updates"
- case dyndns_subdomains = "dyndns_subdomains"
- case owndomains = "owndomains"
- case healthchecks = "healthchecks"
- case healthchecks_updates = "healthchecks_updates"
- case api_updates = "api_updates"
- case sms_count = "sms_count"
- case account_class = "account_class"
- case devicetoken = "devicetoken"
- case info = "info"
- case status = "status"
- case get_account_info = "get_account_info"
- }
-}
-
-struct AccountClass: Codable {
- var class_name: String? = ""
- var dyndns_domain_limit: Int? = 0
- var dyndns_update_limit: Int? = 0
- var owndomain_limit: Int? = 0
- var healthcheck_limit: Int? = 0
- var healthcheck_update_limit: Int? = 0
- var dyndns_ttl: Int? = 0
- var api_limit: Int? = 0
- var sms_limit: Int? = 0
-
- enum CodingKeys: String, CodingKey {
- case class_name = "class_name"
- case dyndns_domain_limit = "dyndns_domain_limit"
- case dyndns_update_limit = "dyndns_update_limit"
- case owndomain_limit = "owndomain_limit"
- case healthcheck_limit = "healthcheck_limit"
- case healthcheck_update_limit = "healthcheck_update_limit"
- case dyndns_ttl = "dyndns_ttl"
- case api_limit = "api_limit"
- case sms_limit = "sms_limit"
- }
-}
-
-struct Account: Codable {
- var ApiKey: String?
- var AccountName: String?
- var DeviceToken: String?
- var Since: String?
- var Active: Bool?
-
- enum CodingKeys: String, CodingKey {
- case ApiKey = "ApiKey"
- case AccountName = "AccountName"
- case DeviceToken = "DeviceToken"
- case Since = "Since"
- case Active = "Active"
- }
-}
-
-struct HealthCheckResult: Codable {
-
- var domain: [HealthCheck] = []
- var info: String?
- var status: String?
- var get_account_info: String?
-
- // Define DynamicCodingKeys type needed for creating
- // decoding container from JSONDecoder
- private struct DynamicCodingKeys: CodingKey {
- // Use for string-keyed dictionary
- var stringValue: String
- init?(stringValue: String) {
- self.stringValue = stringValue
- }
-
- // Use for integer-keyed dictionary
- var intValue: Int?
- init?(intValue: Int) {
- // We are not using this, thus just return nil
- return nil
- }
-
- }
-
- init(from decoder: Decoder) throws {
-
- // 1
- // Create a decoding container using DynamicCodingKeys
- // The container will contain all the JSON first level key
- let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
-
- var tempArray = [HealthCheck]()
-
- // 2
- // Loop through each key (healthcheck Domain) in container
- for key in container.allKeys {
- // Decode healthchecks using key & keep decoded healthcheck object in tempArray
- if (key.stringValue == "info") {
- info = try container.decode(String.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- } else if (key.stringValue == "status") {
- status = try container.decode(String.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- } else if (key.stringValue == "get_account_info") {
- get_account_info = try container.decode(String.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- } else {
- let decodedObject = try container.decode(HealthCheck.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- tempArray.append(decodedObject)
- }
- }
-
- // 3
- // Finish decoding all HealthCheck objects. Thus assign tempArray to array.
- domain = tempArray
- }
-
- init(domain: [HealthCheck] = [], info: String = "", status: String = "", get_account_info: String = "") {
- self.domain = domain
- self.info = info
- self.status = status
- self.get_account_info = get_account_info
- }
-}
-
-struct HealthCheck: Codable {
- // healthstatus == 1 = Active; 2 = Paused; 3 = Warning; 4 = Alarm;
- var name: String = ""
- var healthstatus: Int = 0
- var healthtoken: String = ""
- var add_time: String? = ""
- var last_update_time: String? = ""
- var alarm_time: String? = ""
- var alarm_down: Int = 0
- var alarm_up: Int = 0
- var integration_id: String = "0"
- var alarm_count: Int = 0
- var alarm_unit: Int = 0
- var grace_count: Int = 0
- var grace_unit: Int = 0
- var pings_total: Int = 0
- var type: String = ""
- var events: [HealthEvents] = []
-
- // 1
- // Define healthcheck Domain
- var keyInd: String = ""
-
- // 2
- // Define coding key for decoding use
- enum CodingKeys: String, CodingKey {
- case name = "name"
- case healthstatus = "healthstatus"
- case healthtoken = "healthtoken"
- case add_time = "add_time"
- case last_update_time = "last_update_time"
- case alarm_time = "alarm_time"
- case alarm_down = "alarm_down"
- case alarm_up = "alarm_up"
- case integration_id = "integration_id"
- case alarm_count = "alarm_count"
- case alarm_unit = "alarm_unit"
- case grace_count = "grace_count"
- case grace_unit = "grace_unit"
- case pings_total = "pings_total"
- case type = "type"
- case keyInd = "keyInd"
- case events = "events"
- }
-
- init(from decoder: Decoder) throws {
-
- let container = try decoder.container(keyedBy: CodingKeys.self)
-
- // 3
- // Decode
- name = try container.decode(String.self, forKey: CodingKeys.name)
- healthstatus = try container.decode(Int.self, forKey: CodingKeys.healthstatus)
- healthtoken = try container.decode(String.self, forKey: CodingKeys.healthtoken)
- add_time = try container.decode(String.self, forKey: CodingKeys.add_time)
- last_update_time = try container.decode(String.self, forKey: CodingKeys.last_update_time)
- alarm_time = try container.decode(String.self, forKey: CodingKeys.alarm_time)
- alarm_down = try container.decode(Int.self, forKey: CodingKeys.alarm_down)
- alarm_up = try container.decode(Int.self, forKey: CodingKeys.alarm_up)
- integration_id = try container.decode(String.self, forKey: CodingKeys.integration_id)
- alarm_count = try container.decode(Int.self, forKey: CodingKeys.alarm_count)
- alarm_unit = try container.decode(Int.self, forKey: CodingKeys.alarm_unit)
- grace_count = try container.decode(Int.self, forKey: CodingKeys.grace_count)
- grace_unit = try container.decode(Int.self, forKey: CodingKeys.grace_unit)
- pings_total = try container.decode(Int.self, forKey: CodingKeys.pings_total)
- type = try container.decode(String.self, forKey: CodingKeys.type)
- events = try container.decode([HealthEvents].self, forKey: CodingKeys.events)
-
- // 4
- // Extract healthcheckDomain from coding path
- if (container.codingPath.first!.stringValue != nil) {
- keyInd = container.codingPath.first!.stringValue
- }
- }
-
- init(name: String = "", healthstatus: Int = 0, healthtoken: String = "", add_time: String? = "", last_update_time: String? = "", alarm_time: String? = "", alarm_down: Int = 0, alarm_up: Int = 0, integration_id: String = "0", alarm_count: Int = 0, alarm_unit: Int = 0, grace_count: Int = 0, grace_unit: Int = 0, pings_total: Int = 0, type: String = "", events: [HealthEvents] = []) {
- self.name = name
- self.healthstatus = healthstatus
- self.healthtoken = healthtoken
- self.add_time = add_time
- self.last_update_time = last_update_time
- self.alarm_time = alarm_time
- self.alarm_down = alarm_down
- self.alarm_up = alarm_up
- self.integration_id = integration_id
- self.alarm_count = alarm_count
- self.alarm_unit = alarm_unit
- self.grace_count = grace_count
- self.grace_unit = grace_unit
- self.pings_total = pings_total
- self.type = type
- self.events = events
- }
-}
-
-struct HealthEvents: Codable {
- var event_time: String?
- var status: Int?
- var text: String?
-
- enum CodingKeys: String, CodingKey {
- case event_time = "event_time"
- case status = "status"
- case text = "text"
- }
-}
-
-struct StatusTyp {
- var statusId: Int?
- var name: String?
- var icon: String?
- var color: Color?
-
- enum CodingKeys: String, CodingKey {
- case statusId = "statusId"
- case name = "name"
- case icon = "icon"
- case color = "color"
- }
-}
-
-struct IntegrationResult: Codable {
-
- var integration: [Integration] = []
- var service: String?
- var info: String?
- var status: String?
- var get_account_info: String?
-
- // Define DynamicCodingKeys type needed for creating
- // decoding container from JSONDecoder
- private struct DynamicCodingKeys: CodingKey {
- // Use for string-keyed dictionary
- var stringValue: String
- init?(stringValue: String) {
- self.stringValue = stringValue
- }
-
- // Use for integer-keyed dictionary
- var intValue: Int?
- init?(intValue: Int) {
- // We are not using this, thus just return nil
- return nil
- }
-
- }
-
- init(from decoder: Decoder) throws {
-
- // 1
- // Create a decoding container using DynamicCodingKeys
- // The container will contain all the JSON first level key
- let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
-
- var tempArray = [Integration]()
-
- // 2
- // Loop through each key (healthcheck Domain) in container
- for key in container.allKeys {
- // Decode healthchecks using key & keep decoded healthcheck object in tempArray
- if (key.stringValue == "info") {
- info = try container.decode(String.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- } else if (key.stringValue == "status") {
- status = try container.decode(String.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- } else if (key.stringValue == "get_account_info") {
- get_account_info = try container.decode(String.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- } else {
- let decodedObject = try container.decode(Integration.self, forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
- tempArray.append(decodedObject)
- }
- }
-
- // 3
- // Finish decoding all HealthCheck objects. Thus assign tempArray to array.
- integration = tempArray
- }
-
- init(integration: [Integration] = [], info: String = "", status: String = "", get_account_info: String = "") {
- self.integration = integration
- self.info = info
- self.status = status
- self.get_account_info = get_account_info
- }
-}
-
-struct Integration: Codable, Hashable {
- var i_uuid = UUID()
- var integration: String?
- var integration_id: Int = 0
- var integration_name: String?
- var add_time: String?
- var last_used: String?
-
- enum CodingKeys: String, CodingKey {
- case integration = "integration"
- case integration_id = "integration_id"
- case integration_name = "integration_name"
- case add_time = "add_time"
- case last_used = "last_used"
- }
-
- init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- do {
- // 3
- // Decode
- integration = try container.decode(String.self, forKey: CodingKeys.integration)
- integration_id = try container.decode(Int.self, forKey: CodingKeys.integration_id)
- integration_name = try container.decode(String.self, forKey: CodingKeys.integration_name)
- add_time = try container.decode(String.self, forKey: CodingKeys.add_time)
- last_used = try container.decode(String.self, forKey: CodingKeys.last_used)
-
- // 4
- // Extract healthcheckDomain from coding path
- //keyInd = container.codingPath.first!.stringValue
- } catch {
- print(error)
- }
- }
-}
-
-struct HealthcheckStatisticsResult: Codable {
- var info: String = ""
- var status: String = ""
- var get_account_info: String = ""
- var statistics: [String: [HealthcheckStatistics]]?
-
- enum CodingKeys: String, CodingKey {
- case info = "info"
- case status = "status"
- case get_account_info = "get_account_info"
- case statistics = "statistics"
- }
-}
-
-struct HealthcheckStatistics: Codable {
- var id = UUID()
- var time: String = ""
- var measurement: String = ""
- var latency: Double = 0.0
-
- enum CodingKeys: String, CodingKey {
- case time = "time"
- case measurement = "measurement"
- case latency = "latency"
- }
-}
-
-struct BlockerNode : Codable {
- var blocker_id: String?
- var name: String?
- var last_contact: String?
- var reported_ips_count: Int?
- var blocked_with_help: Int?
- var status: Int?
-
- enum CodingKeys: String, CodingKey {
- case blocker_id = "blocker_id"
- case name = "name"
- case last_contact = "last_contact"
- case reported_ips_count = "reported_ips_count"
- case blocked_with_help = "blocked_with_help"
- case status = "status"
- }
-}
-
-struct BlockerNodeResults : Codable {
- var blockers: [BlockerNode] = []
- var info: String?
- var status: String?
- var get_blocker: String?
-
- enum CodingKeys: String, CodingKey {
- case blockers = "blockers"
- case info = "info"
- case status = "status"
- case get_blocker = "get_blocker"
- }
-
- static var empty: BlockerNodeResults { return BlockerNodeResults(blockers: [], info: "", status: "", get_blocker: "") }
-}
-
-struct PoisonedIP : Codable {
- var blocker_id: String
- var report_ip: String
- var port: String?
- var category: String?
- var info: String?
-
- enum CodingKeys: String, CodingKey {
- case blocker_id = "blocker_id"
- case report_ip = "report_ip"
- case port = "port"
- case category = "category"
- case info = "info"
- }
-
- static var empty: PoisonedIP { return PoisonedIP(blocker_id: "", report_ip: "", port: "", category: "", info: "") }
-}
-
-struct PoisonedIPResult : Codable {
- var info: String?
- var status: String?
- var report_ip: String?
-
- enum CodingKeys: String, CodingKey {
- case info = "info"
- case status = "status"
- case report_ip = "report_ip"
- }
-}
-
-struct AlarmUnit: Codable {
- var id: Int?
- var text: String?
-
- enum CodingKeys: String, CodingKey {
- case id = "id"
- case text = "text"
- }
-}
-
-struct AlarmUnitTypes {
- static var minutes: AlarmUnit {
- AlarmUnit(id: 1, text: "Minuten")
- }
- static var stunden: AlarmUnit {
- AlarmUnit(id: 2, text: "Stunden")
- }
- static var tage: AlarmUnit {
- AlarmUnit(id: 3, text: "Tage")
- }
-}
-
-struct StatusTypes {
- static var active: StatusTyp {
- StatusTyp(statusId: 1, name: "Aktiv", icon: "checkmark.circle", color: .green)
- }
- static var pause: StatusTyp {
- StatusTyp(statusId: 2, name: "Pause", icon: "pause.circle", color: .teal)
- }
- static var warning: StatusTyp {
- StatusTyp(statusId: 3, name: "Warnung", icon: "exclamationmark.triangle.fill", color: .orange)
- }
- static var alarm: StatusTyp {
- StatusTyp(statusId: 4, name: "Alarm", icon: "light.beacon.max.fill", color: .red)
- }
-}
-
-struct ErrorTyp: Codable {
- var icon: String?
- var iconColor: Color?
- var navigationTitle: String?
- var errorTitle: String?
- var errorDescription: String?
- var status: Int?
-
- enum CodingKeys: String, CodingKey {
- case icon = "icon"
- case navigationTitle = "navigationTitle"
- case errorTitle = "errorTitle"
- case errorDescription = "errorDescription"
- case status = "status"
- }
-}
-
-struct ErrorTypes {
- static var tooManyRequests: ErrorTyp {
- ErrorTyp(
- icon: "bolt.horizontal.icloud.fill;exclamationmark.arrow.triangle.2.circlepath",
- iconColor: .orange,
- navigationTitle: "Information",
- errorTitle: "Zu Viele Aktualisierungen!",
- errorDescription: "Du hast dein Limit von 5 API-Anfragen innerhalb der erlaubten 10 Sek. überschritten.",
- status: 429
- )
- }
-
- static var updateCoolDown: ErrorTyp {
- ErrorTyp(
- icon: "bolt.horizontal.icloud.fill;exclamationmark.arrow.triangle.2.circlepath",
- iconColor: .orange,
- navigationTitle: "Information",
- errorTitle: "Zu Viele Aktualisierungen!",
- errorDescription: "Die A-Record Aktualisierung kann nur alle 10 Sek. ausgeführt werden!",
- status: 429
- )
- }
-
- static var domainNotAvailable: ErrorTyp {
- ErrorTyp(
- icon: "xmark.icloud.fill",
- iconColor: .red,
- navigationTitle: "Fehler",
- errorTitle: "Domaine nicht verfügbar!",
- errorDescription: "Deine ausgewählte Domaine ist bereits vergeben!",
- status: 403
- )
- }
-
- static var domainCreatedSuccesfully: ErrorTyp {
- ErrorTyp(
- icon: "checkmark.icloud.fill",
- iconColor: .green,
- navigationTitle: "Erfolgreich",
- errorTitle: "Domaine wurde erfolgreich reserviert!",
- errorDescription: "Deine ausgewählte Domaine wurde erfolgreich, bei uns im System, für dich reserviert!",
- status: 201
- )
- }
-
- static var poisonedIpSuccesfully: ErrorTyp {
- ErrorTyp(
- icon: "checkmark.icloud.fill",
- iconColor: .green,
- navigationTitle: "Erfolgreich",
- errorTitle: "Bösartige IP wurde erfolgreich gemeldet!",
- errorDescription: "Deine Bösartige IP wurde erfolgreich, bei uns im System gemeldet!",
- status: 201
- )
- }
-
- static var poisonedIpError: ErrorTyp {
- ErrorTyp(
- icon: "xmark.icloud.fill",
- iconColor: .red,
- navigationTitle: "Fehler",
- errorTitle: "Fehlerhafte IP!",
- errorDescription: "Deine übergebene bösartige IP ist nicht korrekt!",
- status: 403
- )
- }
-
- static var delete: ErrorTyp {
- ErrorTyp(
- icon: "trash.fill",
- iconColor: .red,
- navigationTitle: "Wirklick löschen?",
- errorTitle: "Willst du wirklich die Domain löschen?",
- errorDescription: "Deine Domaine wird mit allen bekannten DNS-Records unverzüglich gelöscht.",
- status: 202
- )
- }
-
- static var deletehealth: ErrorTyp {
- ErrorTyp(
- icon: "trash.fill",
- iconColor: .red,
- navigationTitle: "Wirklick löschen?",
- errorTitle: "Willst du wirklich den Healthcheck löschen?",
- errorDescription: "Dein Healthcheck wird mit allen dazugehörigen Events unverzüglich gelöscht.",
- status: 202
- )
- }
-
- static var deleteIntegration: ErrorTyp {
- ErrorTyp(
- icon: "trash.fill",
- iconColor: .red,
- navigationTitle: "Wirklick löschen?",
- errorTitle: "Willst du wirklich die Integration löschen?",
- errorDescription: "Deine Integration wird aus allen Healthchecks gelöscht.",
- status: 202
- )
- }
-
- static var dnsRecordSuccesfullyCreated: ErrorTyp {
- ErrorTyp(
- icon: "checkmark.icloud.fill",
- iconColor: .green,
- navigationTitle: "Erfolgreich",
- errorTitle: "DNS-Record wurde erfolgreich erstellt!",
- errorDescription: "Dein DNS-Record wurde erfolgreich im System erstellt!",
- status: 201
- )
- }
-
- static var deleteDNSRecord: ErrorTyp {
- ErrorTyp(
- icon: "trash.fill",
- iconColor: .red,
- navigationTitle: "Wirklick löschen?",
- errorTitle: "Willst du wirklich den\nDNS-Record löschen?",
- errorDescription: "Dein DNS-Record wird mit sofortiger Wirkung aus deiner Domain gelöscht.",
- status: 202
- )
- }
-
- static var unauthorized: ErrorTyp {
- ErrorTyp(
- icon: "xmark.shield.fill",
- iconColor: .red,
- navigationTitle: "Fehlgeschlagen",
- errorTitle: "Authorisierung fehlgeschlagen!",
- errorDescription: "Deine Authorisierung am Server ist fehlgeschlagen, bitte melde dich erneut an.",
- status: 401
- )
- }
-
- static var websiteRequestError: ErrorTyp {
- ErrorTyp(
- icon: "bolt.horizontal.icloud.fill;exclamationmark.arrow.triangle.2.circlepath",
- iconColor: .red,
- navigationTitle: "Fehlgeschlagen",
- errorTitle: "Verbindung zum Server fehlgeschlagen!",
- errorDescription: "Es konnte keine Verbindung zum Server hergestellt werden!",
- status: 500
- )
- }
-
- static var healthcheckCreatedSuccesfully: ErrorTyp {
- ErrorTyp(
- icon: "waveform.path.ecg",
- iconColor: .green,
- navigationTitle: "Erfolgreich",
- errorTitle: "Healthcheck wurde erfolgreich erstellt!",
- errorDescription: "Dein neuer Healthcheck ist nun online!",
- status: 201
- )
- }
-
- static var healthcheckUpdatedSuccesfully: ErrorTyp {
- ErrorTyp(
- icon: "waveform.path.ecg",
- iconColor: .green,
- navigationTitle: "Erfolgreich",
- errorTitle: "Healthcheck erfolgreich aktualisiert!",
- errorDescription: "Dein Healthcheck wurde erfolgreich aktualisiert!",
- status: 201
- )
- }
-
- static var accountSuccessfullyAdded: ErrorTyp {
- ErrorTyp(
- icon: "person.crop.circle.badge.checkmark",
- iconColor: .green,
- navigationTitle: "Erfolgreich",
- errorTitle: "Account erfolgreich hinzugefügt!",
- errorDescription: "",
- status: 201
- )
- }
-
- static var accountFound: ErrorTyp {
- ErrorTyp(
- icon: "person.crop.circle.badge.exclamationmark",
- iconColor: .orange,
- navigationTitle: "Achtung",
- errorTitle: "Account wurde bereits hinzugefügt!",
- errorDescription: "Dein API-Key ist bereits mit einem Account in der App verknüpft.",
- status: 201
- )
- }
-
- static var accountNotFound: ErrorTyp {
- ErrorTyp(
- icon: "person.crop.circle.badge.questionmark",
- iconColor: .red,
- navigationTitle: "Fehler!",
- errorTitle: "API-Key nicht gefunden!",
- errorDescription: "Bist du dir sicher das der API-Key korrekt geschrieben ist?",
- status: 401
- )
- }
-
- static var deleteAccount: ErrorTyp {
- ErrorTyp(
- icon: "trash.fill",
- iconColor: .red,
- navigationTitle: "Wirklick löschen?",
- errorTitle: "Willst du wirklich den\nAccount löschen?",
- errorDescription: "Dein Account wird mit sofortiger Wirkung aus der App gelöscht.",
- status: 202
- )
- }
-}
-
-public var dynDomainList = [
- "ipv64.net",
- "ipv64.de",
- "any64.de",
- "eth64.de",
- "home64.de",
- "iot64.de",
- "lan64.de",
- "nas64.de",
- "srv64.de",
- "tcp64.de",
- "udp64.de",
- "vpn64.de",
- "wan64.de"
-]
-
-public var badNodeCategory: [BadNodeCategory] = [
- BadNodeCategory(id: 1, text: "SSH"),
- BadNodeCategory(id: 2, text: "HTTP/S"),
- BadNodeCategory(id: 3, text: "Mail"),
- BadNodeCategory(id: 4, text: "FTP"),
- BadNodeCategory(id: 5, text: "ICMP"),
- BadNodeCategory(id: 6, text: "DoS"),
- BadNodeCategory(id: 7, text: "DDoS"),
- BadNodeCategory(id: 8, text: "Flooding"),
- BadNodeCategory(id: 9, text: "Web"),
- BadNodeCategory(id: 10, text: "Malware"),
- BadNodeCategory(id: 11, text: "Bots"),
- BadNodeCategory(id: 12, text: "TCP"),
- BadNodeCategory(id: 13, text: "UDP"),
-]
-
-public struct BadNodeCategory: Codable {
- var id: Int?
- var text: String?
-
- enum CodingKeys: String, CodingKey {
- case id = "id"
- case text = "text"
- }
-}
-
-struct WhatsNewObj : Codable {
- var id = UUID()
- var imageName: String
- var title: String
- var subtitle: String
-
- enum CodingKeys: String, CodingKey {
- case imageName = "imageName"
- case title = "title"
- case subtitle = "subtitle"
- }
-
- init(imageName: String = "", title: String = "", subtitle: String = "") {
- self.imageName = imageName
- self.title = title
- self.subtitle = subtitle
- }
-}
-
-extension UIDevice {
- static var isIPad: Bool {
- UIDevice.current.userInterfaceIdiom == .pad
- }
-
- static var isIPhone: Bool {
- UIDevice.current.userInterfaceIdiom == .phone
- }
-}
-
-
-enum ActiveSheet: Identifiable {
- case detail, add, adddns, help, error, qrcode, whatsnew, edit, integrationselection
-
- var id: Int {
- hashValue
- }
-}
-
-extension Bundle {
-
- var appName: String {
- return infoDictionary?["CFBundleName"] as! String
- }
-
- var bundleId: String {
- return bundleIdentifier!
- }
-
- var versionNumber: String {
- return infoDictionary?["CFBundleShortVersionString"] as! String
- }
-
- var buildNumber: String {
- return infoDictionary?["CFBundleVersion"] as! String
- }
-
-}
-
-struct MyNavigation: View where Content: View {
- @ViewBuilder var content: () -> Content
-
- var body: some View {
- if #available(iOS 16, *) {
- NavigationStack(root: content)
- } else {
- NavigationView(content: content)
- }
- }
-}
-
-struct DummyData {
- static var Healthcheck = HealthCheck(
- name: "Healthcheck Test",
- healthstatus: 3,
- healthtoken: "123456789abcdefghijklmnop",
- add_time: "2023-01-01 00:00:00",
- last_update_time: "2023-01-01 00:00:00",
- alarm_time: "2023-01-01 00:00:00",
- alarm_down: 0,
- alarm_up: 0,
- integration_id: "0",
- alarm_count: 1,
- alarm_unit: 1,
- grace_count: 1,
- grace_unit: 1,
- pings_total: 1,
- events: [
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 1,
- text: "123456789"
- ),
- HealthEvents(
- event_time: "2023-01-01 01:00:00",
- status: 4,
- text: "WARNING: Zeitlimit erreicht, Karenzzeit hat begonnen."
- ),
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 3,
- text: "123456789"
- ),
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 0,
- text: "GET Request von 194.126.177.83 -- Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Safari/605.1.15"
- ),
- HealthEvents(
- event_time: "2023-01-01 00:00:00",
- status: 1,
- text: Optional("Healthcheck Einstellungen übernommen.")
- ),
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 4,
- text: "123456789"
- ),
- HealthEvents(
- event_time: "2023-01-01 01:00:00",
- status: 3,
- text: "WARNING: Zeitlimit erreicht, Karenzzeit hat begonnen."
- ),
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 0,
- text: "123456789"
- ),
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 1,
- text: "GET Request von 194.126.177.83 -- Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Safari/605.1.15"
- ),
- HealthEvents(
- event_time: "2023-01-01 00:00:00",
- status: 4,
- text: Optional("Healthcheck Einstellungen übernommen.")
- ),
- HealthEvents(
- event_time: "2023-01-01 00:45:00",
- status: 3,
- text: "123456789"
- )
- ]
- )
-
- static func HealthcheckListCustom(customCount: Int) -> [HealthCheck] {
- var list: [HealthCheck] = []
- for i in 0.. CGFloat {
-
- if !UIDevice.isIPad {
- return .infinity
- }
-
- if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight {
- return UIScreen.main.bounds.width / 2.3
- } else {
- return UIScreen.main.bounds.width / 1
- }
- }
-}
-
-// Our custom view modifier to track rotation and
-// call our action
-struct DeviceRotationViewModifier: ViewModifier {
- let action: (UIDeviceOrientation) -> Void
-
- func body(content: Content) -> some View {
- content
- .onAppear()
- .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
- action(UIDevice.current.orientation)
- }
- }
-}
-
-// A View wrapper to make the modifier easier to use
-extension View {
- func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
- self.modifier(DeviceRotationViewModifier(action: action))
- }
-}
-
-public enum Model : String {
-
- //Simulator
- case simulator = "simulator/sandbox",
-
- //iPod
- iPod1 = "iPod 1",
- iPod2 = "iPod 2",
- iPod3 = "iPod 3",
- iPod4 = "iPod 4",
- iPod5 = "iPod 5",
- iPod6 = "iPod 6",
- iPod7 = "iPod 7",
-
- //iPad
- iPad2 = "iPad 2",
- iPad3 = "iPad 3",
- iPad4 = "iPad 4",
- iPadAir = "iPad Air ",
- iPadAir2 = "iPad Air 2",
- iPadAir3 = "iPad Air 3",
- iPadAir4 = "iPad Air 4",
- iPadAir5 = "iPad Air 5",
- iPad5 = "iPad 5", //iPad 2017
- iPad6 = "iPad 6", //iPad 2018
- iPad7 = "iPad 7", //iPad 2019
- iPad8 = "iPad 8", //iPad 2020
- iPad9 = "iPad 9", //iPad 2021
- iPad10 = "iPad 10", //iPad 2022
-
- //iPad Mini
- iPadMini = "iPad Mini",
- iPadMini2 = "iPad Mini 2",
- iPadMini3 = "iPad Mini 3",
- iPadMini4 = "iPad Mini 4",
- iPadMini5 = "iPad Mini 5",
- iPadMini6 = "iPad Mini 6",
-
- //iPad Pro
- iPadPro9_7 = "iPad Pro 9.7\"",
- iPadPro10_5 = "iPad Pro 10.5\"",
- iPadPro11 = "iPad Pro 11\"",
- iPadPro2_11 = "iPad Pro 11\" 2nd gen",
- iPadPro3_11 = "iPad Pro 11\" 3rd gen",
- iPadPro12_9 = "iPad Pro 12.9\"",
- iPadPro2_12_9 = "iPad Pro 2 12.9\"",
- iPadPro3_12_9 = "iPad Pro 3 12.9\"",
- iPadPro4_12_9 = "iPad Pro 4 12.9\"",
- iPadPro5_12_9 = "iPad Pro 5 12.9\"",
-
- //iPhone
- iPhone4 = "iPhone 4",
- iPhone4S = "iPhone 4S",
- iPhone5 = "iPhone 5",
- iPhone5S = "iPhone 5S",
- iPhone5C = "iPhone 5C",
- iPhone6 = "iPhone 6",
- iPhone6Plus = "iPhone 6 Plus",
- iPhone6S = "iPhone 6S",
- iPhone6SPlus = "iPhone 6S Plus",
- iPhoneSE = "iPhone SE",
- iPhone7 = "iPhone 7",
- iPhone7Plus = "iPhone 7 Plus",
- iPhone8 = "iPhone 8",
- iPhone8Plus = "iPhone 8 Plus",
- iPhoneX = "iPhone X",
- iPhoneXS = "iPhone XS",
- iPhoneXSMax = "iPhone XS Max",
- iPhoneXR = "iPhone XR",
- iPhone11 = "iPhone 11",
- iPhone11Pro = "iPhone 11 Pro",
- iPhone11ProMax = "iPhone 11 Pro Max",
- iPhoneSE2 = "iPhone SE 2nd gen",
- iPhone12Mini = "iPhone 12 Mini",
- iPhone12 = "iPhone 12",
- iPhone12Pro = "iPhone 12 Pro",
- iPhone12ProMax = "iPhone 12 Pro Max",
- iPhone13Mini = "iPhone 13 Mini",
- iPhone13 = "iPhone 13",
- iPhone13Pro = "iPhone 13 Pro",
- iPhone13ProMax = "iPhone 13 Pro Max",
- iPhoneSE3 = "iPhone SE 3nd gen",
- iPhone14 = "iPhone 14",
- iPhone14Plus = "iPhone 14 Plus",
- iPhone14Pro = "iPhone 14 Pro",
- iPhone14ProMax = "iPhone 14 Pro Max",
- iPhone15 = "iPhone 15",
- iPhone15Plus = "iPhone 15 Plus",
- iPhone15Pro = "iPhone 15 Pro",
- iPhone15ProMax = "iPhone 15 Pro Max",
-
- // Apple Watch
- AppleWatch1 = "Apple Watch 1gen",
- AppleWatchS1 = "Apple Watch Series 1",
- AppleWatchS2 = "Apple Watch Series 2",
- AppleWatchS3 = "Apple Watch Series 3",
- AppleWatchS4 = "Apple Watch Series 4",
- AppleWatchS5 = "Apple Watch Series 5",
- AppleWatchSE = "Apple Watch Special Edition",
- AppleWatchS6 = "Apple Watch Series 6",
- AppleWatchS7 = "Apple Watch Series 7",
-
- //Apple TV
- AppleTV1 = "Apple TV 1gen",
- AppleTV2 = "Apple TV 2gen",
- AppleTV3 = "Apple TV 3gen",
- AppleTV4 = "Apple TV 4gen",
- AppleTV_4K = "Apple TV 4K",
- AppleTV2_4K = "Apple TV 4K 2gen",
-
- unrecognized = "?unrecognized?"
-}
-
-// #-#-#-#-#-#-#-#-#-#-#-#-#
-// MARK: UIDevice extensions
-// #-#-#-#-#-#-#-#-#-#-#-#-#
-
-public extension UIDevice {
-
- var type: Model {
- var systemInfo = utsname()
- uname(&systemInfo)
- let modelCode = withUnsafePointer(to: &systemInfo.machine) {
- $0.withMemoryRebound(to: CChar.self, capacity: 1) {
- ptr in String.init(validatingUTF8: ptr)
- }
- }
-
- let modelMap : [String: Model] = [
-
- //Simulator
- "i386" : .simulator,
- "x86_64" : .simulator,
-
- //iPod
- "iPod1,1" : .iPod1,
- "iPod2,1" : .iPod2,
- "iPod3,1" : .iPod3,
- "iPod4,1" : .iPod4,
- "iPod5,1" : .iPod5,
- "iPod7,1" : .iPod6,
- "iPod9,1" : .iPod7,
-
- //iPad
- "iPad2,1" : .iPad2,
- "iPad2,2" : .iPad2,
- "iPad2,3" : .iPad2,
- "iPad2,4" : .iPad2,
- "iPad3,1" : .iPad3,
- "iPad3,2" : .iPad3,
- "iPad3,3" : .iPad3,
- "iPad3,4" : .iPad4,
- "iPad3,5" : .iPad4,
- "iPad3,6" : .iPad4,
- "iPad6,11" : .iPad5, //iPad 2017
- "iPad6,12" : .iPad5,
- "iPad7,5" : .iPad6, //iPad 2018
- "iPad7,6" : .iPad6,
- "iPad7,11" : .iPad7, //iPad 2019
- "iPad7,12" : .iPad7,
- "iPad11,6" : .iPad8, //iPad 2020
- "iPad11,7" : .iPad8,
- "iPad12,1" : .iPad9, //iPad 2021
- "iPad12,2" : .iPad9,
- "iPad13,18" : .iPad10,
- "iPad13,19" : .iPad10,
-
- //iPad Mini
- "iPad2,5" : .iPadMini,
- "iPad2,6" : .iPadMini,
- "iPad2,7" : .iPadMini,
- "iPad4,4" : .iPadMini2,
- "iPad4,5" : .iPadMini2,
- "iPad4,6" : .iPadMini2,
- "iPad4,7" : .iPadMini3,
- "iPad4,8" : .iPadMini3,
- "iPad4,9" : .iPadMini3,
- "iPad5,1" : .iPadMini4,
- "iPad5,2" : .iPadMini4,
- "iPad11,1" : .iPadMini5,
- "iPad11,2" : .iPadMini5,
- "iPad14,1" : .iPadMini6,
- "iPad14,2" : .iPadMini6,
-
- //iPad Pro
- "iPad6,3" : .iPadPro9_7,
- "iPad6,4" : .iPadPro9_7,
- "iPad7,3" : .iPadPro10_5,
- "iPad7,4" : .iPadPro10_5,
- "iPad6,7" : .iPadPro12_9,
- "iPad6,8" : .iPadPro12_9,
- "iPad7,1" : .iPadPro2_12_9,
- "iPad7,2" : .iPadPro2_12_9,
- "iPad8,1" : .iPadPro11,
- "iPad8,2" : .iPadPro11,
- "iPad8,3" : .iPadPro11,
- "iPad8,4" : .iPadPro11,
- "iPad8,9" : .iPadPro2_11,
- "iPad8,10" : .iPadPro2_11,
- "iPad13,4" : .iPadPro3_11,
- "iPad13,5" : .iPadPro3_11,
- "iPad13,6" : .iPadPro3_11,
- "iPad13,7" : .iPadPro3_11,
- "iPad8,5" : .iPadPro3_12_9,
- "iPad8,6" : .iPadPro3_12_9,
- "iPad8,7" : .iPadPro3_12_9,
- "iPad8,8" : .iPadPro3_12_9,
- "iPad8,11" : .iPadPro4_12_9,
- "iPad8,12" : .iPadPro4_12_9,
- "iPad13,8" : .iPadPro5_12_9,
- "iPad13,9" : .iPadPro5_12_9,
- "iPad13,10" : .iPadPro5_12_9,
- "iPad13,11" : .iPadPro5_12_9,
-
- //iPad Air
- "iPad4,1" : .iPadAir,
- "iPad4,2" : .iPadAir,
- "iPad4,3" : .iPadAir,
- "iPad5,3" : .iPadAir2,
- "iPad5,4" : .iPadAir2,
- "iPad11,3" : .iPadAir3,
- "iPad11,4" : .iPadAir3,
- "iPad13,1" : .iPadAir4,
- "iPad13,2" : .iPadAir4,
- "iPad13,16" : .iPadAir5,
- "iPad13,17" : .iPadAir5,
-
- //iPhone
- "iPhone3,1" : .iPhone4,
- "iPhone3,2" : .iPhone4,
- "iPhone3,3" : .iPhone4,
- "iPhone4,1" : .iPhone4S,
- "iPhone5,1" : .iPhone5,
- "iPhone5,2" : .iPhone5,
- "iPhone5,3" : .iPhone5C,
- "iPhone5,4" : .iPhone5C,
- "iPhone6,1" : .iPhone5S,
- "iPhone6,2" : .iPhone5S,
- "iPhone7,1" : .iPhone6Plus,
- "iPhone7,2" : .iPhone6,
- "iPhone8,1" : .iPhone6S,
- "iPhone8,2" : .iPhone6SPlus,
- "iPhone8,4" : .iPhoneSE,
- "iPhone9,1" : .iPhone7,
- "iPhone9,3" : .iPhone7,
- "iPhone9,2" : .iPhone7Plus,
- "iPhone9,4" : .iPhone7Plus,
- "iPhone10,1" : .iPhone8,
- "iPhone10,4" : .iPhone8,
- "iPhone10,2" : .iPhone8Plus,
- "iPhone10,5" : .iPhone8Plus,
- "iPhone10,3" : .iPhoneX,
- "iPhone10,6" : .iPhoneX,
- "iPhone11,2" : .iPhoneXS,
- "iPhone11,4" : .iPhoneXSMax,
- "iPhone11,6" : .iPhoneXSMax,
- "iPhone11,8" : .iPhoneXR,
- "iPhone12,1" : .iPhone11,
- "iPhone12,3" : .iPhone11Pro,
- "iPhone12,5" : .iPhone11ProMax,
- "iPhone12,8" : .iPhoneSE2,
- "iPhone13,1" : .iPhone12Mini,
- "iPhone13,2" : .iPhone12,
- "iPhone13,3" : .iPhone12Pro,
- "iPhone13,4" : .iPhone12ProMax,
- "iPhone14,4" : .iPhone13Mini,
- "iPhone14,5" : .iPhone13,
- "iPhone14,2" : .iPhone13Pro,
- "iPhone14,3" : .iPhone13ProMax,
- "iPhone14,6" : .iPhoneSE3,
- "iPhone14,7" : .iPhone14,
- "iPhone14,8" : .iPhone14Plus,
- "iPhone15,2" : .iPhone14Pro,
- "iPhone15,3" : .iPhone14ProMax,
- "iPhone15,4" : .iPhone15,
- "iPhone15,5" : .iPhone15Plus,
- "iPhone16,1" : .iPhone15Pro,
- "iPhone16,2" : .iPhone15ProMax,
-
- // Apple Watch
- "Watch1,1" : .AppleWatch1,
- "Watch1,2" : .AppleWatch1,
- "Watch2,6" : .AppleWatchS1,
- "Watch2,7" : .AppleWatchS1,
- "Watch2,3" : .AppleWatchS2,
- "Watch2,4" : .AppleWatchS2,
- "Watch3,1" : .AppleWatchS3,
- "Watch3,2" : .AppleWatchS3,
- "Watch3,3" : .AppleWatchS3,
- "Watch3,4" : .AppleWatchS3,
- "Watch4,1" : .AppleWatchS4,
- "Watch4,2" : .AppleWatchS4,
- "Watch4,3" : .AppleWatchS4,
- "Watch4,4" : .AppleWatchS4,
- "Watch5,1" : .AppleWatchS5,
- "Watch5,2" : .AppleWatchS5,
- "Watch5,3" : .AppleWatchS5,
- "Watch5,4" : .AppleWatchS5,
- "Watch5,9" : .AppleWatchSE,
- "Watch5,10" : .AppleWatchSE,
- "Watch5,11" : .AppleWatchSE,
- "Watch5,12" : .AppleWatchSE,
- "Watch6,1" : .AppleWatchS6,
- "Watch6,2" : .AppleWatchS6,
- "Watch6,3" : .AppleWatchS6,
- "Watch6,4" : .AppleWatchS6,
- "Watch6,6" : .AppleWatchS7,
- "Watch6,7" : .AppleWatchS7,
- "Watch6,8" : .AppleWatchS7,
- "Watch6,9" : .AppleWatchS7,
-
- //Apple TV
- "AppleTV1,1" : .AppleTV1,
- "AppleTV2,1" : .AppleTV2,
- "AppleTV3,1" : .AppleTV3,
- "AppleTV3,2" : .AppleTV3,
- "AppleTV5,3" : .AppleTV4,
- "AppleTV6,2" : .AppleTV_4K,
- "AppleTV11,1" : .AppleTV2_4K
- ]
-
- guard let mcode = modelCode, let map = String(validatingUTF8: mcode), let model = modelMap[map] else { return Model.unrecognized }
- if model == .simulator {
- if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
- if let simMap = String(validatingUTF8: simModelCode), let simModel = modelMap[simMap] {
- return simModel
- }
- }
- }
- return model
- }
-}
-
-
-
-func GetUIImage(imageName: String, color: UIColor, hierarichal: Bool) -> UIImage {
- var image = UIImage(systemName: imageName)?.withTintColor(color)
-
- if (hierarichal) {
- let config = UIImage.SymbolConfiguration(hierarchicalColor: color)
- image = UIImage(systemName: imageName, withConfiguration: config)
- }
-
- return image!
-}
diff --git a/IPv64/Models&Helpers/NetworkServices.swift b/IPv64/Models&Helpers/NetworkServices.swift
deleted file mode 100644
index 8bba079..0000000
--- a/IPv64/Models&Helpers/NetworkServices.swift
+++ /dev/null
@@ -1,756 +0,0 @@
-//
-// NetworkServices.swift
-// IPv64
-//
-// Created by Sebastian Rank on 06.11.22.
-//
-
-
-import Foundation
-import UIKit
-
-class NetworkServices: ObservableObject {
-
- @Published var isLoading = false
- let JsonEncoder = JSONEncoder()
- let JsonDecoder = JSONDecoder()
-
- let apiUrl = "https://ipv64.net/api.php"
-
- init() { }
-
- @MainActor
- func GetDomains() async -> DomainResult? {
- let urlString = "\(apiUrl)?get_domains"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(DomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetDomains", error)
- return nil
- }
- }
-
- @MainActor
- func GetLogs() async -> Logs? {
- let urlString = "\(apiUrl)?get_logs"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(Logs.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetLogs", error)
- return nil
- }
- }
-
- @MainActor
- func GetAccountStatus(apiKey: String = "") async -> AccountInfo? {
- let urlString = "\(apiUrl)?get_account_info"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = apiKey.count == 0 ? SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String : apiKey
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AccountInfo.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetLogs", error)
- return nil
- }
- }
-
- @MainActor
- func GetMyIP() async -> MyIP? {
- let urlString = "https://ipv4.ipv64.net/update.php?howismyip"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let _ = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(MyIP.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetMyIP", error)
- return nil
- }
- }
-
- @MainActor
- func GetMyIPV6() async -> MyIP? {
- let urlString = "https://ipv6.ipv64.net/update.php?howismyip"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let _ = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(MyIP.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetMyIP", error)
- return nil
- }
- }
-
-
- @MainActor func PostDomain(domain: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "add_domain=\(domain)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
- @MainActor func DeleteDomain(domain: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "DELETE"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "del_domain=\(domain)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
-
- @MainActor func PostDNSRecord(domain: String, praefix: String, typ: String, content: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "add_record=\(domain)&praefix=\(praefix)&type=\(typ)&content=\(content)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
- @MainActor func DeleteDNSRecord(recordId: Int) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "DELETE"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "del_record=\(recordId)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
- @MainActor
- func UpdateDomainIp(updateKey: String, domain: String) async -> AddDomainResult? {
-
- let urlString = "https://ipv4.ipv64.net/update.php?key=\(updateKey)&domain=\(domain)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
-
- @MainActor
- func GetHealthchecks() async -> HealthCheckResult? {
- let urlString = "\(apiUrl)?get_healthchecks&events"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(HealthCheckResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetHealthchecks", error)
- return nil
- }
- }
-
- @MainActor func PostHealth(add_healthcheck: String, alarm_count: Int, alarm_unit: Int) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "add_healthcheck=\(add_healthcheck)&alarm_count=\(alarm_count)&alarm_unit=\(alarm_unit)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to PostHealth", error)
- return nil
- }
- }
-
-
- @MainActor func PostPauseHealth(healthtoken: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "pause_healthcheck=\(healthtoken)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to PostPauseHealth", error)
- return nil
- }
- }
-
-
- @MainActor func PostStartHealth(healthtoken: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "start_healthcheck=\(healthtoken)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to PostPauseHealth", error)
- return nil
- }
- }
-
-
- @MainActor func DeleteHealth(health: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "DELETE"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "del_healthcheck=\(health)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
- @MainActor
- func GetIntegrations() async -> IntegrationResult? {
- let urlString = "\(apiUrl)?get_integrations"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(IntegrationResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetIntegrations", error)
- return nil
- }
- }
-
-
- @MainActor func PostEditHealthcheck(healthcheck: HealthCheck, integrationId: String) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let body = "edit_healthcheck=\(healthcheck.healthtoken)&healthcheck_name=\(healthcheck.name)&alarm_count=\(healthcheck.alarm_count)&alarm_unit=\(healthcheck.alarm_unit)&integration=\(integrationId)&grace_count=\(healthcheck.grace_count)&grace_unit=\(healthcheck.grace_unit)&alarm_down=\(healthcheck.alarm_down)&alarm_up=\(healthcheck.alarm_up)"
-
- request.httpBody = body.data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to PostEditHealthcheck", error)
- return nil
- }
- }
-
-
- @MainActor func PostAddIntegration(integrationType: String, dtoken: String, dName: String, apiKey: String = "") async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = apiKey.count == 0 ? SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String : apiKey
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let body = "add_integration=\(integrationType)&integration_name=\(dName)&devicetoken=\(dtoken)"
-
- request.httpBody = body.data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to PostDeviceToken", error)
- return nil
- }
- }
-
-
-
- @MainActor
- func GetHealthcheckStatistics(healthtoken: String) async -> HealthcheckStatisticsResult? {
- let urlString = "\(apiUrl)?get_healthcheck_statistics&healthtoken=\(healthtoken)"
-
- isLoading = false
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(HealthcheckStatisticsResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetHealthcheckStatistics", error)
- return nil
- }
- }
-
- @MainActor func DeleteIntegration(integration_id: Int) async -> AddDomainResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "DELETE"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- request.httpBody = "del_integration=\(integration_id)".data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(AddDomainResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to Post Domain", error)
- return nil
- }
- }
-
- @MainActor
- func GetBlockerNodes() async -> BlockerNodeResults? {
- let urlString = "\(apiUrl)?get_blockers"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(BlockerNodeResults.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to GetBlockerNodes", error)
- return nil
- }
- }
-
-
- @MainActor func PostPoisonedIP(poisonedIp: PoisonedIP) async -> PoisonedIPResult? {
- let urlString = "\(apiUrl)"
-
- isLoading = true
-
- guard let url = URL(string: urlString) else {
- isLoading = false
- return nil
- }
-
- do {
- let token = SetupPrefs.readPreference(mKey: "APIKEY", mDefaultValue: "") as! String
- var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
- request.httpMethod = "POST"
- //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
- request.setValue("Authorization: Bearer \(token)", forHTTPHeaderField: "Authorization")
- JsonEncoder.outputFormatting = .prettyPrinted
-
- let body = "blocker_id=\(poisonedIp.blocker_id)&report_ip=\(poisonedIp.report_ip)&port=\(poisonedIp.port!)&category=\(poisonedIp.category!)&info=\(poisonedIp.info!)"
-
- request.httpBody = body.data(using: .utf8)
-
- let (data, _) = try await URLSession.shared.data(for: request)
-
- let result = try JsonDecoder.decode(PoisonedIPResult.self, from: data)
- isLoading = false
- return result
- } catch let error {
- isLoading = false
- print("Failed to PostPoisonedIP", error)
- return nil
- }
- }
-}
diff --git a/IPv64/Models&Helpers/SetupPrefs.swift b/IPv64/Models&Helpers/SetupPrefs.swift
deleted file mode 100755
index 2083614..0000000
--- a/IPv64/Models&Helpers/SetupPrefs.swift
+++ /dev/null
@@ -1,53 +0,0 @@
-//
-// SetupPrefs.swift
-// IPv64
-//
-// Created by Sebastian Rank on 06.11.22.
-//
-
-import Foundation
-
-class SetupPrefs {
-
- static let preferences = UserDefaults(suiteName:"group.ipv64.net")
- static let preferencesStandard = UserDefaults.standard
-
- static func setPreference(mKey: String, mValue: Any) {
- preferences!.set(mValue, forKey: mKey)
- preferences!.synchronize()
- }
-
- static func readPreference(mKey: String, mDefaultValue: Any) -> Any {
- if preferences!.object(forKey: mKey) == nil {
- return mDefaultValue;
- } else {
- return preferences!.object(forKey: mKey) as Any
- }
- }
-
- static func readPreferenceStandard(mKey: String, mDefaultValue: Any) -> Any {
- if preferencesStandard.object(forKey: mKey) == nil {
- return mDefaultValue;
- } else {
- return preferencesStandard.object(forKey: mKey) as Any
- }
- }
-
- static func getArray(mKey: String, mType: String) -> Any {
- if mType.contains("string") {
- return preferences!.stringArray(forKey: mKey) ?? [String]()
- } else if mType.contains("int") {
- return preferences!.array(forKey: mKey) as? [Int] ?? [Int]()
- } else if mType.contains("date") {
- return preferences!.array(forKey: mKey) as? [Bool] ?? [Bool]()
- } else if mType.contains("bool") {
- return preferences!.array(forKey: mKey) as? [Date] ?? [Date]()
- } else {
- return []
- }
- }
-
- static func deletePreference(mKey: String) {
- preferences!.removeObject(forKey: mKey)
- }
-}
diff --git a/IPv64/Models&Helpers/SoundEffectManager.swift b/IPv64/Models&Helpers/SoundEffectManager.swift
deleted file mode 100644
index 05313c2..0000000
--- a/IPv64/Models&Helpers/SoundEffectManager.swift
+++ /dev/null
@@ -1,32 +0,0 @@
-import AVKit
-import CoreHaptics
-import UIKit
-
-public class SoundEffectManager {
- public static let shared: SoundEffectManager = .init()
-
- public enum SoundEffect: String {
- case pull, refresh
- case tootSent
- case tabSelection
- case bookmark, boost, favorite, share
- }
-
- private let userPrefs = UserPrefs.shared
-
- private var currentPlayer: AVAudioPlayer?
-
- private init() {}
-
- @MainActor
- public func playSound(of type: SoundEffect) {
- guard userPrefs.soundEffectEnabled else { return }
- if let url = Bundle.main.url(forResource: type.rawValue, withExtension: "wav") {
- try? AVAudioSession.sharedInstance().setCategory(.ambient)
- try? AVAudioSession.sharedInstance().setActive(true)
- currentPlayer = try? .init(contentsOf: url)
- currentPlayer?.prepareToPlay()
- currentPlayer?.play()
- }
- }
-}
diff --git a/IPv64/Models&Helpers/UserPrefs.swift b/IPv64/Models&Helpers/UserPrefs.swift
deleted file mode 100644
index c8bc321..0000000
--- a/IPv64/Models&Helpers/UserPrefs.swift
+++ /dev/null
@@ -1,18 +0,0 @@
-import Combine
-import Foundation
-import Network
-import SwiftUI
-
-@MainActor
-public class UserPrefs: ObservableObject {
-
-// public static let groupContainer = "group.sr.angelninde"
-// public static let sharedDefault = UserDefaults(suiteName: groupContainer)
- public static let shared = UserPrefs()
-
- @AppStorage("haptic_tab") public var hapticTabSelectionEnabled = true
- @AppStorage("haptic_timeline") public var hapticTimelineEnabled = true
- @AppStorage("haptic_button_press") public var hapticButtonPressEnabled = true
- @AppStorage("sound_effect_enabled") public var soundEffectEnabled = true
-
-}
diff --git a/IPv64/Models/Enum.swift b/IPv64/Models/Enum.swift
new file mode 100644
index 0000000..ab39d9b
--- /dev/null
+++ b/IPv64/Models/Enum.swift
@@ -0,0 +1,115 @@
+//
+// Enum.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import Foundation
+import AVFoundation
+import SwiftUI
+
+enum CameraPermission {
+ case authorized, denied, notDetermined, restricted
+
+ static func status() -> CameraPermission {
+ switch AVCaptureDevice.authorizationStatus(for: .video) {
+ case .authorized: return .authorized
+ case .denied: return .denied
+ case .notDetermined: return .notDetermined
+ case .restricted: return .restricted
+ @unknown default: return .denied
+ }
+ }
+
+ static func request() async -> CameraPermission {
+ await withCheckedContinuation { cont in
+ AVCaptureDevice.requestAccess(for: .video) { granted in
+ cont.resume(returning: granted ? .authorized : .denied)
+ }
+ }
+ }
+}
+
+enum AlertType: Int, Identifiable {
+ case logout, logoutSuccess, apiError, apiSuccess, apiSuccessDelete, apiSuccessUpdate, updateAlert, deleteDNSAlert, deleteDomainAlert, deleteHc, other
+
+ public var id: Int {
+ rawValue
+ }
+
+ public var uuidString: String {
+ UUID().uuidString
+ }
+}
+
+nonisolated enum Unit: Int, Identifiable {
+ case minute, hour, day, unknown
+
+ var id: Int {
+ switch self {
+ case .minute: return 1
+ case .hour: return 2
+ case .day: return 3
+ default: return 0
+ }
+ }
+
+ var label: String {
+ switch self {
+ case .minute: return "Minute/s"
+ case .hour: return "Hour/s"
+ case .day: return "Day/s"
+ default: return ""
+ }
+ }
+
+ var list: [Unit] {
+ [.minute, .hour, .day]
+ }
+}
+
+nonisolated enum Status: Int, Identifiable {
+
+ case active, pause, warning, alarm, unknown
+
+ var id: Int {
+ switch self {
+ case .active: return 1
+ case .pause: return 2
+ case .warning: return 3
+ case .alarm: return 4
+ default: return 0
+ }
+ }
+
+ var label: String {
+ switch self {
+ case .active: return "Active"
+ case .pause: return "Pause"
+ case .warning: return "Warning"
+ case .alarm: return "Alarm"
+ default: return ""
+ }
+ }
+
+ var iconName: String {
+ switch self {
+ case .active: return "checkmark.circle"
+ case .pause: return "pause.circle"
+ case .warning: return "exclamationmark.triangle.fill"
+ case .alarm: return "light.beacon.max.fill"
+ default: return ""
+ }
+ }
+
+ var color: Color {
+ switch self {
+ case .active: return .green
+ case .pause: return .teal
+ case .warning: return .orange
+ case .alarm: return .red
+ case .unknown: return .gray
+ }
+ }
+}
diff --git a/IPv64/Models/Tabs.swift b/IPv64/Models/Tabs.swift
new file mode 100644
index 0000000..ecdf7d3
--- /dev/null
+++ b/IPv64/Models/Tabs.swift
@@ -0,0 +1,153 @@
+//
+// Tabs.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+
+import Foundation
+import SwiftUI
+
+public enum Tabs: Int, Identifiable, Hashable, Decodable, Encodable {
+
+ // New cases go last: the raw value is persisted in CURRENT_TAB.
+ case domain, healthcheck, notification, settings, account, log, myip, about, syslog, other, cdn, proxy64, dns64
+
+ public var id: Int {
+ rawValue
+ }
+
+ public var uuidString: String {
+ UUID().uuidString
+ }
+
+ /// Tab bar as in Android 2.1.0 (`Tabs.tabList`): Proxy64 replaces CDN64 and DNS64 appears only while a
+ /// connected node has that module active. `.settings` is the More tab.
+ static func tabList(proxyActive: Bool, dnsActive: Bool) -> [Tabs] {
+ var list: [Tabs] = [.domain, .healthcheck, proxyActive ? .proxy64 : .cdn]
+ if dnsActive { list.append(.dns64) }
+ return list + [.settings]
+ }
+
+ @MainActor @ViewBuilder
+ func makeContentView(popToRootTab: Binding) -> some View {
+ switch self {
+ case .domain:
+ DomainView(popToRootTab: popToRootTab)
+ case .healthcheck:
+ HealthcheckView(popToRootTab: popToRootTab)
+ case .notification:
+ ChannelsView()
+ case .settings:
+ SettingsView(popToRootTab: popToRootTab)
+ case .account:
+ AccountView(popToRootTab: popToRootTab)
+ case .log:
+ LogView(popToRootTab: popToRootTab)
+ case .syslog:
+ LoggerView(popToRootTab: popToRootTab, showToolbar: false)
+ case .myip:
+ ThreatLookupView()
+ case .about:
+ AboutView(popToRootTab: popToRootTab)
+ case .cdn:
+ CdnView(popToRootTab: popToRootTab)
+ case .proxy64:
+ ProxyView(popToRootTab: popToRootTab)
+ case .dns64:
+ NodeDnsView(popToRootTab: popToRootTab)
+ default:
+ EmptyView()
+ }
+ }
+
+ var labelNew: String {
+ switch self {
+ case .domain:
+ return "DynDNS"
+ case .healthcheck:
+ return "Healthchecks"
+ case .notification:
+ return "Channels"
+ case .settings:
+ return "More"
+ case .cdn:
+ return "CDN64"
+ case .proxy64:
+ return "Proxy64"
+ case .dns64:
+ return "DNS64"
+ case .account:
+ return "Account"
+ case .log:
+ return "Logs"
+ case .syslog:
+ return "System Logs"
+ case .myip:
+ return "IP lookup & My IP"
+ case .about:
+ return "About"
+ default:
+ return ""
+ }
+ }
+
+ var route: String {
+ switch self {
+ case .account:
+ return "settings.account"
+ case .log:
+ return "settings.log"
+ case .myip:
+ return "settings.myip"
+ case .about:
+ return "settings.about"
+ case .notification:
+ return "settings.notification"
+ case .syslog:
+ return "settings.syslog"
+ default:
+ return ""
+ }
+ }
+
+ @ViewBuilder
+ var label: some View {
+ switch self {
+ case .domain:
+ Label("DynDNS", systemImage: iconName)
+ case .healthcheck:
+ Label("Healthcheck", systemImage: iconName)
+ case .notification:
+ Label("Notification", systemImage: iconName)
+ case .settings:
+ Label("Settings", systemImage: iconName)
+ default:
+ EmptyView()
+ }
+ }
+
+ var iconName: String {
+ switch self {
+ case .domain:
+ return "network"
+ case .healthcheck:
+ return "bolt.heart"
+ case .notification:
+ return "bell.badge"
+ case .settings:
+ return "ellipsis"
+ case .cdn:
+ return "cloud"
+ case .proxy64:
+ return "arrow.left.arrow.right"
+ case .dns64:
+ return "server.rack"
+ case .account:
+ return "person.circle"
+ default:
+ return "app.dashed"
+ }
+ }
+}
diff --git a/IPv64/Models/User.swift b/IPv64/Models/User.swift
new file mode 100644
index 0000000..14f48aa
--- /dev/null
+++ b/IPv64/Models/User.swift
@@ -0,0 +1,96 @@
+//
+// User.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 22.10.25.
+//
+
+import Foundation
+
+struct User: Codable {
+ var uuid: String? = UUID().uuidString
+ var Username: String // E-Mail
+ var ApiKey: String
+ var Information: String
+
+ enum CodingKeys: String, CodingKey {
+ case uuid = "uuid"
+ case Username = "Username"
+ case ApiKey = "ApiKey"
+ case Information = "Information"
+ }
+
+ static let empty = User(Username: "", ApiKey: "", Information: "")
+
+ var current: User? {
+ guard !self.list.isEmpty else { return nil }
+ guard var user = self.list.first(where: { $0.ApiKey == UserStorage.shared.ApiKey }) else {
+ return nil
+ }
+
+ if user.Information.isEmpty {
+ user.Information = "No Information"
+ }
+
+ return user
+ }
+
+ var list: [User] { UserStorage.shared.users }
+
+ func save() {
+ var userList = self.list
+ userList.append(self)
+
+ do {
+ let data = try JSONEncoder().encode(userList)
+ UserStorage.shared.UserAccounts = data
+ } catch {
+ print("Error encoding data: \(error)")
+ }
+ }
+
+ func saveList(_ list: [User]) {
+ do {
+ let data = try JSONEncoder().encode(list)
+ UserStorage.shared.UserAccounts = data
+ } catch {
+ print("Error encoding data: \(error)")
+ }
+ }
+
+ func update() {
+ var userList = self.list
+ let index = userList.firstIndex(where: { $0.uuid == self.uuid})
+ if (index != nil) {
+ userList[index!] = self
+
+ do {
+ let data = try JSONEncoder().encode(userList)
+ UserStorage.shared.UserAccounts = data
+ } catch {
+ print("Error encoding data: \(error)")
+ }
+ }
+ }
+
+ func delete() {
+ var userList = self.list
+ let removedKey = UserStorage.shared.ApiKey
+ let removedOwners = userList.filter { $0.ApiKey == removedKey }.compactMap(\.uuid)
+ userList.removeAll(where: { $0.ApiKey == removedKey })
+
+ do {
+ let data = try JSONEncoder().encode(userList)
+ UserStorage.shared.UserAccounts = data
+ guard UserStorage.shared.UserAccounts == data else { return }
+ removedOwners.forEach(LocalNodeStore.removeOwner)
+ UserStorage.shared.ApiKey = userList.first?.ApiKey ?? ""
+ if UserStorage.shared.ApiKeyWidget == removedKey {
+ UserStorage.shared.ApiKeyWidget = userList.first?.ApiKey ?? ""
+ Task { _ = try? await ClearHealthCheckCacheIntent().perform() }
+ }
+ } catch {
+ print("Error encoding data: \(error)")
+ }
+ }
+}
diff --git a/IPv64/Models/WhatsNew.swift b/IPv64/Models/WhatsNew.swift
new file mode 100644
index 0000000..d639f3e
--- /dev/null
+++ b/IPv64/Models/WhatsNew.swift
@@ -0,0 +1,48 @@
+//
+// WhatsNew.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 13.02.26.
+//
+
+import Foundation
+import Combine
+
+struct WhatsNew : Codable {
+ var id = UUID()
+ var imageName: String
+ var title: String
+ var subtitle: String
+ var assetIcon: Bool
+
+ enum CodingKeys: String, CodingKey {
+ case imageName = "imageName"
+ case title = "title"
+ case subtitle = "subtitle"
+ case assetIcon = "assetIcon"
+ }
+
+ init(imageName: String = "", title: String = "", subtitle: String = "", assetIcon: Bool = false) {
+ self.imageName = imageName
+ self.title = title
+ self.subtitle = subtitle
+ self.assetIcon = assetIcon
+ }
+}
+
+extension WhatsNew {
+ /// Entries of the current version (shared by WhatsNewView and WhatsNewView26).
+ static var current: [WhatsNew] {
+ [
+ WhatsNew(imageName: "ladybug", title: "Bug fixes".localized, subtitle: "Scanning the API key QR code when adding an account works again, and an invalid key now shows an error message after the scan.".localized),
+ ]
+ }
+}
+
+enum ActiveSheet: Identifiable {
+ case whatsnew
+
+ var id: Int {
+ hashValue
+ }
+}
diff --git a/IPv64/Models/iLogger.swift b/IPv64/Models/iLogger.swift
new file mode 100644
index 0000000..f1b93c5
--- /dev/null
+++ b/IPv64/Models/iLogger.swift
@@ -0,0 +1,122 @@
+//
+// Logger.swift
+// iGotify
+//
+// Created by Sebastian Rank on 23.01.24.
+//
+
+import Foundation
+@preconcurrency import SwiftyBeaver
+
+public struct iLogger: Sendable {
+
+ public static let log = SwiftyBeaver.self
+ private var file: FileDestination? = nil
+ static let shared = iLogger()
+
+ init() {
+
+ let console = ConsoleDestination() // log to Xcode Console
+ file = FileDestination() // log to default swiftybeaver.log file
+ file!.logFileURL = defaultLogFileURL()
+ console.format = "$DHH:mm:ss$d $L $M"
+ // add the destinations to SwiftyBeaver
+ iLogger.log.addDestination(console)
+ iLogger.log.addDestination(file!)
+ rotateLogFileIfNeeded()
+ iLogger.log.info("♻️ - Initialize iLogger")
+ }
+
+ func defaultLogFileURL() -> URL {
+ let _ = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
+ let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.ipv64.net")
+ let logFileURL = container!.appendingPathComponent("app_\(formatDateToYYYYMMDD(date: Date()))_latest.log")
+ return logFileURL
+ }
+
+ @MainActor
+ static func getLogFileURL(log: String) -> URL {
+ let _ = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
+ let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.ipv64.net")
+ let logFileURL = container!.appendingPathComponent(log)
+ return logFileURL
+ }
+
+ @MainActor
+ static func defaultLogPath() -> String {
+ let _ = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
+ let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.ipv64.net")
+ return container?.path() ?? ""
+ }
+
+ // Function to rotate the log file if it exceeds the maximum size
+ func rotateLogFileIfNeeded() {
+ guard let logFileURL = file!.logFileURL else {
+ return
+ }
+
+ do {
+ let fileSize = try FileManager.default.attributesOfItem(atPath: logFileURL.path)[.size] as? NSNumber
+ let maxSize = NSNumber(value: 1024 * 1024)
+
+ if let fileSize = fileSize, fileSize.int64Value > maxSize.int64Value {
+ // Rotate the log file by renaming the current file
+ let rotatedLogFileURL = logFileURL.deletingLastPathComponent().appendingPathComponent("app_\(formatDateToYYYYMMDD(date: Date())).log")
+ try FileManager.default.moveItem(at: logFileURL, to: rotatedLogFileURL)
+
+ // Create a new empty log file
+ FileManager.default.createFile(atPath: logFileURL.path, contents: nil, attributes: nil)
+ }
+ } catch {
+ print("Error rotating log file: \(error)")
+ }
+ }
+
+ func formatDateToYYYYMMDD(date: Date) -> String {
+ let dateFormatter = DateFormatter()
+ dateFormatter.dateFormat = "yyyyMMdd"
+ let formattedDate = dateFormatter.string(from: date)
+ return formattedDate
+ }
+
+ public static func readLogFile(log: String) async -> String {
+ let logFileURL = await getLogFileURL(log: log)
+
+ do {
+ // let logContent = try String(contentsOf: logFileURL)
+ var logContent = ""
+ for try await line in logFileURL.lines {
+ logContent.append("\n\n\(line.replacingOccurrences(of: "\n", with: "\n \n", options: .regularExpression))")
+ }
+ //print("Log File Content:\n\(logContent)")
+ return logContent
+ } catch {
+ //print("Error reading log file: \(error)")
+ return "Error reading log file: \(error)"
+ }
+ }
+
+ public static func getFileList() async -> [String] {
+ let containerPath = await defaultLogPath()
+ if (containerPath.isEmpty) {
+ return []
+ }
+ do {
+ let fileList = try FileManager.default.contentsOfDirectory(atPath: containerPath).filter({ $0.contains(".log") })
+ return fileList.sorted().reversed()
+ } catch _ { }
+ return []
+ }
+
+ public static func removeLogFile(file: String) async -> Bool {
+ let logFileUrl = await getLogFileURL(log: file)
+
+ do {
+ try FileManager.default.removeItem(at: logFileUrl)
+ return true
+ } catch _ {
+
+ }
+ return false
+ }
+}
diff --git a/IPv64/Preview Content/Preview Assets.xcassets/Contents.json b/IPv64/Preview Content/Preview Assets.xcassets/Contents.json
deleted file mode 100644
index 73c0059..0000000
--- a/IPv64/Preview Content/Preview Assets.xcassets/Contents.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/IPv64/Views/.DS_Store b/IPv64/Views/.DS_Store
new file mode 100644
index 0000000..1548042
Binary files /dev/null and b/IPv64/Views/.DS_Store differ
diff --git a/IPv64/Views/CDN/CdnView.swift b/IPv64/Views/CDN/CdnView.swift
new file mode 100644
index 0000000..a86ee22
--- /dev/null
+++ b/IPv64/Views/CDN/CdnView.swift
@@ -0,0 +1,124 @@
+import SwiftUI
+import IPv64
+
+/// CDN64: the CDN64 names of every connected proxy node. Tab root without a proxy node explains how to get one;
+/// pushed from Proxy64 otherwise. "+" enables CDN64 for a proxy host.
+struct CdnView: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ @Binding var popToRootTab: Tabs
+ @State private var nodeData: [ProxyNodeData]?
+ @State private var enableChoices: [CdnHostChoice]?
+ @State private var error: ErrorText?
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(enableChoices != nil ? .clear : .orange)
+ } else { content }
+ }
+
+ private var content: some View {
+ Group {
+ if nodes.proxyIds.isEmpty {
+ ContentUnavailableView {
+ Label("CDN64 needs a node", systemImage: "cloud")
+ } description: {
+ Text("CDN64 runs on a Node64 with the Proxy64 module. Connect one under More → Nodes.")
+ }
+ } else {
+ List {
+ ForEach(nodeData ?? []) { data in
+ CdnNodeSection(node: data) { id in Task { await reload(node: id) } }
+ }
+ }
+ .overlay { if nodeData == nil { ProgressView("Loading CDN64…") } }
+ .refreshable { await load() }
+ .task(id: nodes.proxyIds) { await load() }
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { enable() } label: { Label("Enable CDN64 for a proxy host", systemImage: "plus") }
+ .disabled(nodeData == nil)
+ }
+ }
+ .sheet(isPresented: Binding(get: { enableChoices != nil }, set: { if !$0 { enableChoices = nil } })) {
+ CdnEnableFlow(choices: enableChoices ?? []) { choice, mode, healthcheck in
+ if let failure = await nodes.enableCdn64(choice, mode: mode, healthcheck: healthcheck) { error = failure }
+ await reload(node: choice.nodeId)
+ }
+ }
+ .errorAlert($error)
+ }
+ }
+ .navigationTitle(Tabs.cdn.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private func enable() {
+ let choices = (nodeData ?? []).flatMap(\.cdnChoices)
+ if (nodeData ?? []).allSatisfy({ $0.error != nil }) {
+ error = ProxyLogic.noNodeError
+ } else {
+ enableChoices = choices
+ }
+ }
+
+ private func load() async {
+ let loaded = await nodes.loadProxyNodes(withHosts: true)
+ if !Task.isCancelled { nodeData = loaded }
+ }
+
+ private func reload(node id: String) async {
+ let fresh = await nodes.loadProxyNode(id, withHosts: true)
+ if let index = nodeData?.firstIndex(where: { $0.id == id }) { nodeData?[index] = fresh } else { await load() }
+ }
+}
+
+/// CDN64 names of one proxy node: server count, sync error and the names with their mode; a name opens its host.
+private struct CdnNodeSection: View {
+ let node: ProxyNodeData
+ let onChanged: (String) -> Void
+
+ var body: some View {
+ Section(node.name) {
+ if let error = node.error {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: error.title)
+ Text(verbatim: error.message).font(.subheadline).foregroundStyle(.secondary)
+ Text("Check the connection under More → Nodes.").font(.subheadline).foregroundStyle(.secondary)
+ }
+ } else if let status = node.online {
+ let edges = status.edges ?? []
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: ProxyLogic.serversText(connected: edges.filter { $0.connected == true }.count, total: edges.count))
+ if let sync = status.syncError?.nonBlank { Text(verbatim: sync).font(.subheadline).foregroundStyle(.secondary) }
+ }
+ ForEach(Array((status.names ?? []).enumerated()), id: \.offset) { _, name in
+ if let hostID = name.hostID {
+ NavigationLink {
+ ProxyHostEditView(route: ProxyHostRoute(nodeId: node.id, hostId: hostID)) { onChanged(node.id) }
+ } label: { nameRow(name) }
+ } else {
+ nameRow(name)
+ }
+ }
+ if (status.names ?? []).isEmpty {
+ Text("No names in CDN64 yet.").foregroundStyle(.secondary)
+ }
+ } else {
+ Text("CDN64 status not available.").foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ private func nameRow(_ name: Node64.CDNOnlineName) -> some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: name.name?.nonBlank ?? "–").font(.headline).lineLimit(1)
+ if let check = name.check?.nonBlank {
+ Text("Check: \(check)").font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ ProxyTag(tag: ProxyLogic.Tag(text: ProxyLogic.modeShort(name.mode), tone: .gray))
+ }
+ }
+}
diff --git a/IPv64/Views/Channels/ChannelFieldViews.swift b/IPv64/Views/Channels/ChannelFieldViews.swift
new file mode 100644
index 0000000..b6de724
--- /dev/null
+++ b/IPv64/Views/Channels/ChannelFieldViews.swift
@@ -0,0 +1,112 @@
+import SwiftUI
+import IPv64
+
+/// "General" section of the channel form.
+struct ChannelGeneralSection: View {
+ @Binding var name: String
+ @Binding var enabled: Bool
+ @Binding var isDefault: Bool
+ @Binding var notifyDown: Bool
+ @Binding var notifyUp: Bool
+ @Binding var lang: HC2ChannelLanguage
+ let showValidation: Bool
+
+ var body: some View {
+ Section {
+ VStack(alignment: .leading, spacing: 4) {
+ TextField("Name", text: $name)
+ if showValidation && name.nonBlank == nil {
+ Text("Required").font(.caption).foregroundStyle(.red)
+ }
+ }
+ Toggle("Enabled", isOn: $enabled)
+ Toggle(isOn: $isDefault) {
+ Text("Default channel")
+ Text("Checks without explicit channels notify default channels.")
+ }
+ Toggle("Notify when a check goes down", isOn: $notifyDown)
+ Toggle("Notify when a check recovers", isOn: $notifyUp)
+ Picker("Language", selection: $lang) {
+ Text(verbatim: "English").tag(HC2ChannelLanguage.en)
+ Text(verbatim: "Deutsch").tag(HC2ChannelLanguage.de)
+ }
+ } header: {
+ Text("General")
+ }
+ }
+}
+
+/// One dynamic config field of the channel type.
+struct ChannelFieldRow: View {
+ let field: HC2ChannelType.Field
+ @Binding var value: String
+ let required: Bool
+ let error: String?
+ let secretIsSet: Bool
+
+ @State private var revealed = false
+
+ private var kind: String { ChannelLogic.kindKey(field) }
+ private var label: String { (field.label?.nonBlank ?? field.key ?? "") + (required ? " *" : "") }
+
+ var body: some View {
+ switch kind {
+ case "bool":
+ Toggle(isOn: Binding(get: { ChannelLogic.parseBool(value) }, set: { value = String($0) })) {
+ Text(verbatim: label)
+ }
+ case "select":
+ Picker(selection: $value) {
+ if !required { Text(verbatim: "–").tag("") }
+ ForEach((field.options ?? []).filter { !$0.isEmpty }, id: \.self) { Text(verbatim: $0).tag($0) }
+ } label: {
+ Text(verbatim: label)
+ }
+ .foregroundStyle(error == nil ? Color.primary : Color.red)
+ default:
+ VStack(alignment: .leading, spacing: 4) {
+ input
+ if let error { Text(verbatim: error).font(.caption).foregroundStyle(.red) }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var input: some View {
+ if ChannelLogic.isSecret(field) {
+ HStack {
+ Group {
+ if revealed {
+ TextField(label, text: $value, prompt: prompt)
+ } else {
+ SecureField(label, text: $value, prompt: prompt)
+ }
+ }
+ .textContentType(.password)
+ Button(revealed ? "Hide" : "Show", systemImage: revealed ? "eye.slash" : "eye") { revealed.toggle() }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.borderless)
+ }
+ .autocorrectionDisabled()
+ .textInputAutocapitalization(.never)
+ } else if kind == "textarea" {
+ TextField(label, text: $value, axis: .vertical).lineLimit(3...)
+ } else {
+ TextField(label, text: $value)
+ .keyboardType(keyboard)
+ .autocorrectionDisabled()
+ .textInputAutocapitalization(.never)
+ }
+ }
+
+ private var prompt: Text? { secretIsSet ? Text("Set – leave empty to keep") : Text(verbatim: label) }
+
+ private var keyboard: UIKeyboardType {
+ switch kind {
+ case "url": .URL
+ case "email": .emailAddress
+ case "number": .decimalPad
+ default: .default
+ }
+ }
+}
diff --git a/IPv64/Views/Channels/ChannelFormSheet.swift b/IPv64/Views/Channels/ChannelFormSheet.swift
new file mode 100644
index 0000000..8b15dff
--- /dev/null
+++ b/IPv64/Views/Channels/ChannelFormSheet.swift
@@ -0,0 +1,393 @@
+import SwiftUI
+import IPv64
+
+/// Channel setup (`channelId == nil`: type picker + fields) or edit, shown as a sheet.
+struct ChannelFormSheet: View {
+ let channelId: Int?
+ /// The list must reload (created, changed, deleted, verified).
+ let onChanged: () -> Void
+ /// "IPv64 App (this device)" was picked: the caller replaces this sheet with the push setup.
+ let onPush: () -> Void
+
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var types: [HC2ChannelType] = []
+ @State private var type: HC2ChannelType?
+ @State private var channel: HC2Channel?
+ @State private var loaded = false
+ @State private var name = ""
+ @State private var enabled = true
+ @State private var isDefault = false
+ @State private var notifyDown = true
+ @State private var notifyUp = true
+ @State private var lang = ChannelLogic.systemLanguage
+ @State private var values: [String: String] = [:]
+ @State private var touched: Set = []
+ @State private var showValidation = false
+ @State private var verifiedNow = false
+ @State private var isBusy = false
+ @State private var error: ErrorText?
+ @State private var loadError: ErrorText?
+ @State private var message: FormMessage?
+ @State private var confirmDelete = false
+ @State private var verify: VerifyTarget?
+ @State private var savedPrompt: VerifyTarget?
+
+ private var isEdit: Bool { channelId != nil }
+ private var isThisDevice: Bool { channel != nil && channel?.id == PushSetupStore.channelId(apiKey: session.apiKey) }
+ private var awaitingVerification: Bool {
+ guard let channel, !verifiedNow else { return false }
+ return ChannelLogic.isAwaitingVerification(channel, types: type.map { [$0] })
+ }
+
+ /// The token field of an edited app channel stays hidden and unchanged.
+ private var keepKeys: Set {
+ guard let channel, channel.type == .app else { return [] }
+ return [PushTokenLogic.tokenKey(for: channel, appType: type)]
+ }
+
+ private var fields: [HC2ChannelType.Field] {
+ (type?.fields ?? []).filter { $0.key?.nonBlank != nil && !keepKeys.contains($0.key ?? "") }
+ }
+
+ private var secrets: Set { Set(channel?.secretsSet ?? []) }
+
+ private func required(_ field: HC2ChannelType.Field) -> Bool {
+ field.required == true && !(isEdit && secrets.contains(field.key ?? ""))
+ }
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ if loaded { form } else if loadError == nil { ProgressView() }
+ }
+ .navigationTitle(isEdit ? "Edit channel" : "New channel")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel", systemImage: "xmark") { dismiss() }.disabled(isBusy)
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if isBusy {
+ ProgressView()
+ } else {
+ Button(isEdit ? "Save" : "Create", systemImage: "checkmark", action: save).disabled(!loaded || type == nil && !isEdit)
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ .interactiveDismissDisabled(isBusy)
+ .task { await load() }
+ .errorAlert($error)
+ .alert(Text(verbatim: loadError?.title ?? ""), isPresented: isPresented($loadError), presenting: loadError) { _ in
+ Button("Cancel", role: .cancel) { dismiss() }
+ Button("Retry") { Task { await load() } }
+ } message: { Text(verbatim: $0.message) }
+ .alert(Text(verbatim: message?.title ?? ""), isPresented: isPresented($message), presenting: message) { msg in
+ Button("OK", role: .cancel) { if msg.closeAfter { close() } }
+ } message: { Text(verbatim: $0.text) }
+ .alert("Channel saved", isPresented: isPresented($savedPrompt), presenting: savedPrompt) { target in
+ Button("Later", role: .cancel) { close() }
+ Button("Send test") { sendTest(id: target.id, closeAfter: true) }
+ } message: { Text("Send a test notification to “\($0.name)” now?") }
+ .alert("Delete channel?", isPresented: $confirmDelete) {
+ Button("Delete", role: .destructive) { if let channel { delete(channel.id) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { Text(deleteText) }
+ .sheet(item: $verify) { target in
+ ChannelVerifySheet(channelId: target.id, name: target.name,
+ onVerified: { verified(target) },
+ onLater: { if target.justCreated { close() } })
+ }
+ }
+
+ private var form: some View {
+ Form {
+ if awaitingVerification, let channel {
+ Section {
+ Text("Not verified").font(.headline).foregroundStyle(.orange)
+ Text("This channel won't receive notifications and can't be tested until it is verified.")
+ Button("Verify now", systemImage: "checkmark.shield") {
+ verify = VerifyTarget(id: channel.id, name: ChannelLogic.displayName(channel), justCreated: false)
+ }
+ }
+ }
+ typeSection
+ ChannelGeneralSection(name: $name, enabled: $enabled, isDefault: $isDefault, notifyDown: $notifyDown,
+ notifyUp: $notifyUp, lang: $lang, showValidation: showValidation)
+ fieldsSection
+ if isEdit, let channel {
+ Section {
+ Button("Send test", systemImage: "paperplane") { sendTest(id: channel.id, closeAfter: false) }
+ .disabled(awaitingVerification)
+ }
+ Section {
+ Button("Delete channel", systemImage: "trash", role: .destructive) { confirmDelete = true }
+ .disabled(isThisDevice)
+ } footer: {
+ if isThisDevice { Text("This device's push channel can't be deleted.") }
+ }
+ }
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .disabled(isBusy)
+ }
+
+ @ViewBuilder
+ private var typeSection: some View {
+ Section {
+ if isEdit {
+ LabeledContent("Type") {
+ HStack(spacing: 6) {
+ Image(systemName: ChannelLogic.systemImage(type: channel?.type?.rawValue)).foregroundStyle(.tint)
+ Text(verbatim: (channel?.typeLabel ?? channel?.type?.rawValue ?? "")
+ + (isThisDevice ? " · " + String(localized: "This device") : ""))
+ }
+ }
+ } else {
+ Picker("Type", selection: $type) {
+ ForEach(types, id: \.self) { entry in
+ Label {
+ if entry.type == .app {
+ Text("IPv64 App (this device)")
+ } else {
+ Text(verbatim: entry.label?.nonBlank ?? entry.type?.rawValue ?? "")
+ }
+ } icon: {
+ Image(systemName: ChannelLogic.systemImage(type: entry.type?.rawValue))
+ }
+ .tag(Optional(entry))
+ }
+ }
+ .pickerStyle(.navigationLink)
+ .onChange(of: type) { old, new in typeChanged(from: old, to: new) }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var fieldsSection: some View {
+ if isEdit && type == nil {
+ Section(channel?.typeLabel ?? String(localized: "Settings")) {
+ Text("The settings of this channel type can only be changed at ipv64.net.")
+ }
+ } else if !fields.isEmpty || type?.needsVerification == true {
+ Section {
+ ForEach(fields, id: \.self) { field in
+ let key = field.key ?? ""
+ ChannelFieldRow(field: field, value: binding(key), required: required(field),
+ error: showValidation ? ChannelLogic.fieldError(field, value: values[key] ?? "", required: required(field)) : nil,
+ secretIsSet: isEdit && secrets.contains(key))
+ }
+ } header: {
+ Text(verbatim: type?.label?.nonBlank ?? channel?.typeLabel ?? String(localized: "Settings"))
+ } footer: {
+ if !isEdit && type?.needsVerification == true {
+ Text("After creating the channel, a verification code will be sent to confirm it.")
+ }
+ }
+ }
+ }
+
+ private var deleteText: String {
+ guard let channel else { return "" }
+ return String(localized: "“\(ChannelLogic.displayName(channel))” will be deleted. Checks using only this channel will notify default channels instead.")
+ }
+
+ private func binding(_ key: String) -> Binding {
+ Binding(get: { values[key] ?? "" }, set: { values[key] = $0; touched.insert(key) })
+ }
+
+ private func isPresented(_ value: Binding) -> Binding {
+ Binding(get: { value.wrappedValue != nil }, set: { if !$0 { value.wrappedValue = nil } })
+ }
+
+ private func close() {
+ onChanged()
+ dismiss()
+ }
+}
+
+// MARK: - Loading and actions
+
+private extension ChannelFormSheet {
+ func load() async {
+ loadError = nil
+ let client = session.api
+ do {
+ if let channelId {
+ let types = try? await ipv64Retrying { try await client.hc2.channels.types() }
+ let channel = try await ipv64Retrying { try await client.hc2.channels.get(channelId) }
+ apply(channel, type: types?.first { $0.type == channel.type })
+ } else {
+ guard !loaded else { return }
+ types = try await ipv64Retrying { try await client.hc2.channels.types() }
+ let first = types.first { $0.type != .app } ?? types.first
+ type = first
+ resetFields(for: first, replacing: nil)
+ loaded = true
+ }
+ } catch is CancellationError {
+ } catch {
+ loadError = ErrorText(error)
+ }
+ }
+
+ func apply(_ channel: HC2Channel, type: HC2ChannelType?) {
+ self.channel = channel
+ self.type = type
+ name = channel.name ?? ""
+ enabled = channel.enabled ?? true
+ isDefault = channel.default ?? false
+ notifyDown = channel.notifyDown ?? true
+ notifyUp = channel.notifyUp ?? true
+ if let lang = channel.lang, lang == .de || lang == .en { self.lang = lang }
+ for field in type?.fields ?? [] {
+ if let key = field.key { values[key] = ChannelLogic.initialValue(field, config: channel.config, isEdit: true) }
+ }
+ loaded = true
+ }
+
+ func typeChanged(from old: HC2ChannelType?, to new: HC2ChannelType?) {
+ if new?.type == .app {
+ onPush()
+ } else {
+ resetFields(for: new, replacing: old)
+ }
+ }
+
+ /// New type: its defaults; the name follows the type as long as the user did not type their own.
+ func resetFields(for type: HC2ChannelType?, replacing old: HC2ChannelType?) {
+ if name.isEmpty || name == old?.label { name = type?.label ?? "" }
+ values = [:]
+ touched = []
+ showValidation = false
+ for field in type?.fields ?? [] {
+ if let key = field.key { values[key] = ChannelLogic.initialValue(field, config: nil, isEdit: false) }
+ }
+ }
+
+ func save() {
+ showValidation = true
+ let invalid = fields.contains {
+ ChannelLogic.fieldError($0, value: values[$0.key ?? ""] ?? "", required: required($0)) != nil
+ }
+ guard let trimmed = name.nonBlank?.trimmingCharacters(in: .whitespacesAndNewlines), !invalid else { return }
+ let config = ChannelLogic.buildConfig(fields: fields, values: values, touched: touched,
+ base: channel?.config, isEdit: isEdit, keepKeys: keepKeys)
+ if let channelId {
+ update(channelId, name: trimmed, config: config)
+ } else if let type {
+ create(type, name: trimmed, config: config)
+ }
+ }
+
+ func create(_ type: HC2ChannelType, name: String, config: [String: JSONValue]) {
+ let input = HC2ChannelInput(name: name, type: type.type, config: config, enabled: enabled, default: isDefault,
+ lang: lang, notifyDown: notifyDown, notifyUp: notifyUp)
+ let client = session.api
+ Task {
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ let created = try await ipv64Retrying { try await client.hc2.channels.create(input) }
+ onChanged()
+ let target = VerifyTarget(id: created.id, name: ChannelLogic.displayName(created), justCreated: true)
+ if ChannelLogic.isAwaitingVerification(created, types: [type]) {
+ verify = target
+ } else {
+ savedPrompt = target
+ }
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+
+ /// Only changed fields (the name is always carried); nothing changed closes without a request.
+ func update(_ id: Int, name: String, config: [String: JSONValue]) {
+ guard let base = channel else { return }
+ let baseLang = base.lang == .de || base.lang == .en ? base.lang : ChannelLogic.systemLanguage
+ let input = HC2ChannelInput(
+ name: name,
+ config: config != (base.config ?? [:]) ? config : nil,
+ enabled: enabled != (base.enabled ?? true) ? enabled : nil,
+ default: isDefault != (base.default ?? false) ? isDefault : nil,
+ lang: lang != baseLang ? lang : nil,
+ notifyDown: notifyDown != (base.notifyDown ?? true) ? notifyDown : nil,
+ notifyUp: notifyUp != (base.notifyUp ?? true) ? notifyUp : nil)
+ guard name != (base.name ?? "") || input.config != nil || input.enabled != nil || input.default != nil
+ || input.lang != nil || input.notifyDown != nil || input.notifyUp != nil else {
+ dismiss()
+ return
+ }
+ let client = session.api
+ Task {
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ _ = try await ipv64Retrying { try await client.hc2.channels.update(id, input) }
+ close()
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+
+ func sendTest(id: Int, closeAfter: Bool) {
+ let client = session.api
+ Task {
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ let result = try await ipv64Retrying { try await client.hc2.channels.sendTest(id) }
+ let text = ChannelLogic.testResultMessage(result)
+ message = FormMessage(title: text.title, text: text.message, closeAfter: closeAfter)
+ } catch {
+ let text = ErrorText(error)
+ message = FormMessage(title: text.title, text: text.message, closeAfter: closeAfter)
+ }
+ }
+ }
+
+ func delete(_ id: Int) {
+ let client = session.api
+ let apiKey = session.apiKey
+ Task {
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ try await ipv64Retrying { try await client.hc2.channels.delete(id) }
+ if PushSetupStore.channelId(apiKey: apiKey) == id { PushSetupStore.clearChannel(apiKey: apiKey) }
+ close()
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+
+ func verified(_ target: VerifyTarget) {
+ if target.justCreated {
+ savedPrompt = target
+ } else {
+ verifiedNow = true
+ onChanged()
+ }
+ }
+}
+
+private struct VerifyTarget: Identifiable {
+ let id: Int
+ let name: String
+ let justCreated: Bool
+}
+
+private struct FormMessage: Identifiable {
+ let id = UUID()
+ let title: String
+ let text: String
+ let closeAfter: Bool
+}
diff --git a/IPv64/Views/Channels/ChannelVerifySheet.swift b/IPv64/Views/Channels/ChannelVerifySheet.swift
new file mode 100644
index 0000000..76007ec
--- /dev/null
+++ b/IPv64/Views/Channels/ChannelVerifySheet.swift
@@ -0,0 +1,142 @@
+import SwiftUI
+import IPv64
+
+/// "Verify channel": send a 6-digit code, enter it. Never swipe-dismissible; closes via "Later" or a successful verification.
+struct ChannelVerifySheet: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ let channelId: Int
+ let name: String
+ let onVerified: () -> Void
+ /// "Later" (e.g. closes the setup sheet after a create).
+ var onLater: () -> Void = {}
+
+ @State private var codeSent = false
+ @State private var code = ""
+ @State private var isBusy = false
+ @State private var errorText: String?
+ @State private var infoText: String?
+ @State private var countdown = 0
+ @State private var sendCount = 0
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ Section {
+ content
+ } footer: {
+ VStack(alignment: .leading, spacing: 4) {
+ if let infoText { Text(verbatim: infoText) }
+ if let errorText { Text(verbatim: errorText).foregroundStyle(.red) }
+ }
+ }
+ }
+ .navigationTitle("Verify channel")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Later", systemImage: "clock") {
+ dismiss()
+ onLater()
+ }
+ .disabled(isBusy)
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if isBusy {
+ ProgressView()
+ } else if !codeSent {
+ Button("Send code", systemImage: "paperplane", action: sendCode)
+ } else {
+ Button("Verify", systemImage: "checkmark", action: verify).disabled(code.count != 6)
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ .interactiveDismissDisabled()
+ .appReadableWidth()
+ .presentationDetents([.medium, .large])
+ .task(id: sendCount) { await runCountdown() }
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ if !codeSent {
+ Text("A 6-digit code will be sent to “\(name)”.")
+ Text("You can request up to 5 codes per hour. Each code is valid for 15 minutes.")
+ .font(.footnote).foregroundStyle(.secondary)
+ } else {
+ Text("Enter the 6-digit code sent to “\(name)”.")
+ TextField("Code", text: $code)
+ .keyboardType(.numberPad)
+ .textContentType(.oneTimeCode)
+ .font(.title3.monospacedDigit())
+ .foregroundStyle(errorText == nil ? Color.primary : Color.red)
+ .onChange(of: code) { _, new in
+ let digits = String(new.filter(\.isNumber).prefix(6))
+ if digits != new { code = digits }
+ errorText = nil
+ }
+ Button(action: sendCode) {
+ countdown > 0 ? Text("Resend code (\(countdown) s)") : Text("Resend code")
+ }
+ .disabled(isBusy || countdown > 0)
+ Text("Up to 5 codes per hour, valid for 15 minutes.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ }
+
+ private func runCountdown() async {
+ guard sendCount > 0 else { return }
+ countdown = 60
+ while countdown > 0 {
+ do { try await Task.sleep(for: .seconds(1)) } catch { return }
+ countdown -= 1
+ }
+ }
+
+ /// Without auto-retry: a 429 has a meaning here.
+ private func sendCode() {
+ guard !isBusy else { return }
+ let client = session.api
+ let wasSent = codeSent
+ Task {
+ isBusy = true
+ errorText = nil
+ infoText = nil
+ defer { isBusy = false }
+ do {
+ _ = try await client.hc2.channels.sendVerificationCode(channelId)
+ if wasSent { infoText = String(localized: "A new code has been sent.") }
+ codeSent = true
+ sendCount += 1
+ } catch let error as IPv64Error where error.statusCode == 429 {
+ errorText = String(localized: "Too many codes requested, try again later.")
+ } catch {
+ errorText = ErrorText(error).message
+ }
+ }
+ }
+
+ private func verify() {
+ guard !isBusy, code.count == 6 else { return }
+ let client = session.api
+ let code = code
+ Task {
+ isBusy = true
+ errorText = nil
+ defer { isBusy = false }
+ do {
+ _ = try await client.hc2.channels.verify(channelId, code: code)
+ dismiss()
+ onVerified()
+ } catch let error as IPv64Error where error.statusCode == 429 {
+ errorText = String(localized: "Too many attempts, try again later.")
+ } catch let error as IPv64Error where error.statusCode == 422 || error.code == "invalid_code" {
+ errorText = String(localized: "Invalid or expired code.")
+ } catch {
+ errorText = ErrorText(error).message
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/Channels/ChannelsView.swift b/IPv64/Views/Channels/ChannelsView.swift
new file mode 100644
index 0000000..79176db
--- /dev/null
+++ b/IPv64/Views/Channels/ChannelsView.swift
@@ -0,0 +1,252 @@
+import SwiftUI
+import IPv64
+
+/// Channels (pushed from More): permission banner, "This device", all channels. Setup and edit are sheets.
+struct ChannelsView: View {
+ @Environment(Session.self) private var session
+ @Environment(PushRegistrar.self) private var registrar
+
+ @State private var channels: [HC2Channel]?
+ @State private var types: [HC2ChannelType]?
+ @State private var deviceChannelId: Int?
+ @State private var permission = NotificationPermission.unknown
+ @State private var sheet: ChannelSheet?
+ @State private var confirmDelete: HC2Channel?
+ @State private var isBusy = false
+ @State private var error: ErrorText?
+ @State private var message: ErrorText?
+
+ enum ChannelSheet: Identifiable {
+ case new, push
+ case edit(Int)
+ case verify(HC2Channel)
+
+ var id: String {
+ switch self {
+ case .new: "new"
+ case .push: "push"
+ case .edit(let id): "edit\(id)"
+ case .verify(let channel): "verify\(channel.id)"
+ }
+ }
+ }
+
+ private var deviceChannel: HC2Channel? { channels?.first { $0.id == deviceChannelId } }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView.setColorGradient(sheet != nil || confirmDelete != nil ? .clear : .orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ List {
+ if permission == .canRequest || permission == .denied {
+ Section {
+ Label("Notifications are disabled", systemImage: "bell.slash").font(.headline).foregroundStyle(.orange)
+ NotificationPermissionActions(permission: $permission)
+ }
+ }
+ if let channels {
+ deviceSection(hasDefault: channels.contains { $0.default == true })
+ Section {
+ ForEach(channels) { channel in
+ // No outer Button: the "Not verified" tag is a button of its own.
+ ChannelRow(channel: channel, isThisDevice: channel.id == deviceChannelId,
+ awaitingVerification: ChannelLogic.isAwaitingVerification(channel, types: types),
+ onVerify: { sheet = .verify(channel) })
+ .contentShape(Rectangle())
+ .onTapGesture { sheet = .edit(channel.id) }
+ .accessibilityAddTraits(.isButton)
+ // This device's push channel can't be deleted here (it would silently stop its pushes).
+ .swipeActions {
+ if channel.id != deviceChannelId {
+ Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = channel }
+ .labelStyle(.iconOnly)
+ .tint(.red)
+ }
+ }
+ }
+ } header: {
+ Text("Channels")
+ } footer: {
+ if channels.isEmpty { Text("No channels yet. Tap + to add one.") }
+ }
+ }
+ }
+ .overlay {
+ if channels == nil || isBusy { ProgressView() }
+ }
+ .navigationTitle("Channels")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Add channel", systemImage: "plus") { sheet = .new }.disabled(channels == nil)
+ }
+ }
+ .refreshable { await load() }
+ .trackingNotificationPermission($permission)
+ .task { await load() }
+ .errorAlert($error)
+ .errorAlert($message)
+ .alert("Delete channel?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),
+ presenting: confirmDelete) { channel in
+ Button("Delete", role: .destructive) { delete(channel) }
+ Button("Cancel", role: .cancel) {}
+ } message: { channel in
+ Text(deleteText(channel))
+ }
+ .sheet(item: $sheet) { sheet in
+ switch sheet {
+ case .new:
+ ChannelFormSheet(channelId: nil, onChanged: reload, onPush: { self.sheet = .push })
+ case .edit(let id):
+ ChannelFormSheet(channelId: id, onChanged: reload, onPush: { self.sheet = .push })
+ case .push:
+ NavigationStack { PushSetupView() }.tint(.orange).appReadableWidth()
+ .onDisappear(perform: reload)
+ case .verify(let channel):
+ ChannelVerifySheet(channelId: channel.id, name: ChannelLogic.displayName(channel), onVerified: reload)
+ }
+ }
+ }
+
+ private func deviceSection(hasDefault: Bool) -> some View {
+ Section {
+ if let channel = deviceChannel {
+ Button { sheet = .edit(channel.id) } label: {
+ LabeledContent {
+ if channel.enabled == false { ChannelTag(text: "Disabled", color: .gray) }
+ } label: {
+ Label(ChannelLogic.displayName(channel), systemImage: "iphone")
+ }
+ }
+ .tint(.primary)
+ Button("Send test", systemImage: "paperplane", action: sendTest)
+ } else {
+ Label {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Push notifications")
+ Text("Receive healthcheck alerts as push notifications on this device.")
+ .font(.subheadline).foregroundStyle(.secondary)
+ }
+ } icon: { Image(systemName: "iphone") }
+ Button("Set up push notifications", systemImage: "bell.badge") { sheet = .push }
+ }
+ } header: {
+ Text("This device")
+ } footer: {
+ if !hasDefault { Text("No default channel set. Checks without explicit channels notify default channels.") }
+ }
+ }
+
+ private func reload() { Task { await load() } }
+
+ /// Account id, channels, types (failure tolerated), token sync (errors ignored), this device's channel.
+ private func load() async {
+ await registrar.ensureAccountId()
+ let client = session.api
+ do {
+ let list = try await ipv64Retrying { try await client.hc2.channels.list() }
+ let types = try? await ipv64Retrying { try await client.hc2.channels.types() }
+ _ = try? await registrar.syncTokenIfChanged(channels: list)
+ deviceChannelId = registrar.detectThisDevice(list, types: types)?.id
+ self.types = types
+ channels = list
+ } catch is CancellationError {
+ } catch let error as URLError where error.code == .cancelled {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func sendTest() {
+ guard let id = deviceChannelId else { return }
+ let client = session.api
+ Task {
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ let result = try await ipv64Retrying { try await client.hc2.channels.sendTest(id) }
+ let text = ChannelLogic.testResultMessage(result)
+ message = ErrorText(title: text.title, message: text.message)
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+
+ private func deleteText(_ channel: HC2Channel) -> String {
+ String(localized: "“\(ChannelLogic.displayName(channel))” will be deleted. Checks using only this channel will notify default channels instead.")
+ }
+
+ private func delete(_ channel: HC2Channel) {
+ let client = session.api
+ let apiKey = session.apiKey
+ Task {
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ try await ipv64Retrying { try await client.hc2.channels.delete(channel.id) }
+ if PushSetupStore.channelId(apiKey: apiKey) == channel.id { PushSetupStore.clearChannel(apiKey: apiKey) }
+ await load()
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+}
+
+/// Compact row: name, type · target, trailing tags, last error.
+private struct ChannelRow: View {
+ let channel: HC2Channel
+ let isThisDevice: Bool
+ let awaitingVerification: Bool
+ let onVerify: () -> Void
+
+ /// Type label plus the first readable target of the (non-secret) config.
+ private var subtitle: String {
+ let type = channel.typeLabel?.nonBlank ?? channel.type?.rawValue ?? ""
+ let target = ["email", "address", "phone", "number", "to", "url", "host", "chat_id", "topic", "channel"]
+ .lazy.compactMap { key in channel.config?.first { $0.key.lowercased() == key }.flatMap { ChannelLogic.text($0.value).nonBlank } }
+ .first
+ return [type.nonBlank, target?.trimmingCharacters(in: .whitespacesAndNewlines)].compactMap { $0 }.joined(separator: " · ")
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: ChannelLogic.displayName(channel)).font(.headline).lineLimit(1)
+ if !subtitle.isEmpty {
+ Text(verbatim: subtitle).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ VStack(alignment: .trailing, spacing: 4) {
+ if isThisDevice { ChannelTag(text: "This device", color: .orange) }
+ if channel.default == true { ChannelTag(text: "Default", color: .blue) }
+ if channel.enabled == false { ChannelTag(text: "Disabled", color: .gray) }
+ if awaitingVerification {
+ Button(action: onVerify) { ChannelTag(text: "Not verified", color: .orange) }
+ .buttonStyle(.borderless)
+ .accessibilityHint(Text("Verify channel"))
+ }
+ }
+ }
+ if let error = channel.lastError?.nonBlank {
+ Text(verbatim: error.trimmingCharacters(in: .whitespacesAndNewlines))
+ .font(.footnote).foregroundStyle(.red).lineLimit(2)
+ }
+ }
+ }
+}
+
+struct ChannelTag: View {
+ let text: LocalizedStringKey
+ let color: Color
+
+ var body: some View { HealthcheckTag(text: text, color: color) }
+}
diff --git a/IPv64/Views/Channels/NotificationSettingsView.swift b/IPv64/Views/Channels/NotificationSettingsView.swift
new file mode 100644
index 0000000..10971b6
--- /dev/null
+++ b/IPv64/Views/Channels/NotificationSettingsView.swift
@@ -0,0 +1,219 @@
+import SwiftUI
+import IPv64
+
+/// Notification settings (pushed from More): quiet hours, rate limit and batching. PATCH sends changes only.
+struct NotificationSettingsView: View {
+ @Environment(Session.self) private var session
+
+ @State private var baseline: NotificationSettingsForm?
+ @State private var present: Set = []
+ @State private var form = NotificationSettingsForm()
+ @State private var isSaving = false
+ @State private var error: ErrorText?
+
+ private var changed: Bool { baseline != nil && form != baseline }
+ private var valid: Bool { baseline.map { NotificationSettingsLogic.isValid(form, base: $0) } ?? false }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ formView.setColorGradient(.orange)
+ } else {
+ formView
+ }
+ }
+
+ private var formView: some View {
+ Form {
+ if let baseline {
+ QuietHoursSection(form: $form)
+ Section {
+ NumberSettingRow(label: "Notifications per hour", text: $form.rate,
+ supporting: "0 = unlimited", isError: !NotificationSettingsLogic.rateOK(form))
+ requiredRow("Batch threshold", text: $form.threshold, baseline: baseline.threshold,
+ supporting: "From this many notifications they are combined into one.")
+ requiredRow("Batch window (seconds)", text: $form.window, baseline: baseline.window,
+ supporting: "Time span in which notifications are counted.")
+ } header: {
+ Text("Rate limit and batching")
+ }
+ }
+ }
+ .overlay {
+ if baseline == nil && error == nil { ProgressView() }
+ }
+ .navigationTitle("Notification settings")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if changed {
+ ToolbarItem(placement: .topBarTrailing) {
+ if isSaving {
+ ProgressView()
+ } else {
+ Button("Save", systemImage: "checkmark", action: save).disabled(!valid)
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .disabled(isSaving)
+ .refreshable { await load(pull: true) }
+ .task { await load(pull: false) }
+ .errorAlert($error)
+ }
+
+ private func requiredRow(_ label: LocalizedStringKey, text: Binding, baseline: String,
+ supporting: LocalizedStringKey) -> some View {
+ let ok = NotificationSettingsLogic.requiredNumberOK(text.wrappedValue, baseline: baseline)
+ return NumberSettingRow(label: label, text: text,
+ supporting: ok ? supporting : "Enter a whole number (cannot be empty).", isError: !ok)
+ }
+
+ /// Pull-to-refresh discards edits; the first load fills the form.
+ private func load(pull: Bool) async {
+ let client = session.api
+ do {
+ let parsed = NotificationSettingsLogic.parse(try await ipv64Retrying { try await client.hc2.settings() })
+ if pull || baseline == nil { form = parsed.form }
+ baseline = parsed.form
+ present = parsed.present
+ } catch is CancellationError {
+ } catch let error as URLError where error.code == .cancelled {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func save() {
+ guard let base = baseline, valid else { return }
+ let f = form
+ let update = NotificationSettingsLogic.update(f, base: base, present: present)
+ guard update != HC2SettingsInput() else {
+ baseline = f // nothing to send (e.g. only an empty field without a server value)
+ return
+ }
+ let client = session.api
+ Task {
+ isSaving = true
+ defer { isSaving = false }
+ do {
+ let result = NotificationSettingsLogic.parse(try await ipv64Retrying { try await client.hc2.updateSettings(update) })
+ if result.present.isEmpty {
+ baseline = f
+ present.formUnion(NotificationSettingsLogic.quietKeys)
+ } else {
+ baseline = result.form
+ present.formUnion(result.present)
+ form = result.form
+ }
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+}
+
+private struct QuietHoursSection: View {
+ @Binding var form: NotificationSettingsForm
+
+ var body: some View {
+ Section {
+ Toggle(isOn: $form.quietEnabled) {
+ Text("Enable quiet hours")
+ Text("Notifications are held back during these hours.")
+ }
+ if form.quietEnabled {
+ TimeOfDayRow(label: "From", value: $form.from)
+ TimeOfDayRow(label: "To", value: $form.to)
+ DayChips(days: $form.days)
+ }
+ } header: {
+ Text("Quiet hours")
+ } footer: {
+ if form.quietEnabled {
+ if form.days.isEmpty {
+ Text("Select at least one day.").foregroundStyle(.red)
+ } else {
+ Text("Times use the server's time zone.")
+ }
+ }
+ }
+ }
+}
+
+/// "HH:mm" (24 h) via the system time picker.
+private struct TimeOfDayRow: View {
+ let label: LocalizedStringKey
+ @Binding var value: String
+
+ private var date: Binding {
+ Binding {
+ let parts = value.split(separator: ":").compactMap { Int($0) }
+ return Calendar.current.date(bySettingHour: parts.first ?? 0, minute: parts.count > 1 ? parts[1] : 0,
+ second: 0, of: .now) ?? .now
+ } set: { new in
+ let c = Calendar.current.dateComponents([.hour, .minute], from: new)
+ value = String(format: "%02d:%02d", c.hour ?? 0, c.minute ?? 0)
+ }
+ }
+
+ var body: some View {
+ DatePicker(label, selection: date, displayedComponents: .hourAndMinute)
+ .environment(\.locale, Locale(identifier: "de_DE")) // 24 h like Android's picker
+ }
+}
+
+/// Mon…Sun toggles (several days at once, so buttons instead of a segmented picker).
+private struct DayChips: View {
+ @Binding var days: Set
+
+ private static let labels: [LocalizedStringKey] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+
+ var body: some View {
+ // Scrolls only when the seven buttons don't fit (narrow width, large Dynamic Type).
+ ViewThatFits(in: .horizontal) {
+ chips
+ ScrollView(.horizontal, showsIndicators: false) { chips }
+ }
+ }
+
+ private var chips: some View {
+ HStack(spacing: 6) {
+ ForEach(0..<7, id: \.self) { index in
+ let day = index + 1
+ let selected = days.contains(day)
+ Button {
+ if selected { days.remove(day) } else { days.insert(day) }
+ } label: {
+ Text(Self.labels[index]).font(.subheadline)
+ }
+ .buttonStyle(.bordered)
+ .tint(selected ? .orange : .gray)
+ .controlSize(.small)
+ .accessibilityAddTraits(selected ? .isSelected : [])
+ }
+ }
+ .padding(.vertical, 2)
+ }
+}
+
+private struct NumberSettingRow: View {
+ let label: LocalizedStringKey
+ @Binding var text: String
+ let supporting: LocalizedStringKey
+ let isError: Bool
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ LabeledContent(label) {
+ TextField(label, text: $text)
+ .keyboardType(.numberPad)
+ .multilineTextAlignment(.trailing)
+ .onChange(of: text) { _, new in
+ let digits = new.filter(\.isNumber)
+ if digits != new { text = digits }
+ }
+ }
+ Text(supporting).font(.caption).foregroundStyle(isError ? Color.red : Color.secondary)
+ }
+ }
+}
diff --git a/IPv64/Views/DNS64/NodeDnsBlockingSection.swift b/IPv64/Views/DNS64/NodeDnsBlockingSection.swift
new file mode 100644
index 0000000..2d6a65c
--- /dev/null
+++ b/IPv64/Views/DNS64/NodeDnsBlockingSection.swift
@@ -0,0 +1,99 @@
+import SwiftUI
+import WidgetKit
+import IPv64
+
+/// Blocking card: state, countdown, pause durations, resume. An unreachable node shows only the error.
+struct NodeDnsBlockingSection: View {
+ let blocking: DnsSec
+ let dns: Node64.DNS64
+ let actions: DnsActions
+ let onChange: (Node64.DNS64Blocking) -> Void
+ let onExpired: () -> Void
+
+ @State private var now = Date()
+ /// End of a pause started in this session (kept until resumed).
+ @State private var localEnd: Date?
+ @State private var choosing = false
+
+ private struct Choice: Identifiable {
+ let minutes: Int
+ let label: String
+ var id: Int { minutes }
+ }
+
+ private static let choices = [
+ Choice(minutes: 5, label: String(localized: "For 5 minutes")), Choice(minutes: 15, label: String(localized: "For 15 minutes")),
+ Choice(minutes: 30, label: String(localized: "For 30 minutes")), Choice(minutes: 60, label: String(localized: "For 1 hour")),
+ Choice(minutes: 0, label: String(localized: "Until resumed")),
+ ]
+
+ private var current: Node64.DNS64Blocking? { (try? blocking.get()) ?? nil }
+ private var paused: Bool { current?.paused == true }
+
+ private var end: Date? {
+ guard paused, current?.untilResumed != true else { return nil }
+ return HcFormat.real(current?.pausedUntil) ?? localEnd
+ }
+
+ var body: some View {
+ Section("Blocking") {
+ switch blocking {
+ case .failure(let failure):
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: failure.text).foregroundStyle(.red)
+ Text("Check the connection under More → Nodes.").font(.subheadline).foregroundStyle(.secondary)
+ }
+ case .success:
+ LabeledContent {
+ ProxyTag(tag: .init(text: paused ? String(localized: "Paused") : String(localized: "Active"),
+ tone: paused ? .orange : .green))
+ } label: {
+ Text(verbatim: dns64BlockingTitle(paused: paused, end: end, now: now))
+ }
+ if paused {
+ Button("Resume", systemImage: "play.fill") {
+ Task { await actions.run { onChange(try await dns.resume()) } }
+ }
+ } else {
+ // One centred alert with the durations; picking one is the confirmation.
+ Button("Pause blocking", systemImage: "pause.fill") { choosing = true }
+ .background {
+ // Alert buttons take the presenter's tint: neutral durations, so Cancel stands apart.
+ Color.clear
+ .alert("Pause blocking?", isPresented: $choosing) {
+ ForEach(Self.choices) { choice in
+ Button(choice.label) { pause(choice) }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Ads and trackers will not be blocked while paused.")
+ }
+ .tint(.primary)
+ }
+ }
+ }
+ }
+ .task(id: end) { await countdown() }
+ .onChange(of: paused) {
+ if !paused { localEnd = nil }
+ WidgetCenter.shared.reloadTimelines(ofKind: AppConfig.dns64WidgetKind)
+ ControlCenter.shared.reloadControls(ofKind: AppConfig.dns64ControlKind)
+ }
+ }
+
+ private func pause(_ choice: Choice) {
+ localEnd = choice.minutes > 0 ? .now.addingTimeInterval(Double(choice.minutes) * 60) : nil
+ Task { await actions.run { onChange(try await dns.pause(minutes: choice.minutes)) } }
+ }
+
+ /// Ticks every 30 s (1 s under 2 minutes) while a pause end is known; reloads once on expiry.
+ private func countdown() async {
+ guard let end else { return }
+ while !Task.isCancelled {
+ now = .now
+ let remaining = end.timeIntervalSince(now)
+ if remaining <= 0 { onExpired(); return }
+ do { try await Task.sleep(for: dns64CountdownInterval(remaining: remaining)) } catch { return }
+ }
+ }
+}
diff --git a/IPv64/Views/DNS64/NodeDnsLogView.swift b/IPv64/Views/DNS64/NodeDnsLogView.swift
new file mode 100644
index 0000000..c95588e
--- /dev/null
+++ b/IPv64/Views/DNS64/NodeDnsLogView.swift
@@ -0,0 +1,140 @@
+import SwiftUI
+import IPv64
+
+/// Query log: live polling every 3 s while the screen is visible and the app active.
+struct NodeDnsLogView: View {
+ let nodeId: String
+
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.scenePhase) private var scenePhase
+
+ @State private var rows: [Node64.DNS64LogRow] = []
+ @State private var loaded = false
+ @State private var pollError: String?
+ @State private var live = true
+ @State private var query = ""
+ @State private var filter: Dns64LogFilter = .all
+ /// Tapped row: a blocked one can be allowed, any other one blocked.
+ @State private var selected: Node64.DNS64LogRow?
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ private struct PollKey: Equatable {
+ var active: Bool, live: Bool, filter: Dns64LogFilter, query: String
+ }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(.orange)
+ } else { content }
+ }
+
+ private var content: some View {
+ List {
+ Section {
+ Picker("Status", selection: $filter) {
+ Text("All").tag(Dns64LogFilter.all)
+ Text("Blocked").tag(Dns64LogFilter.blocked)
+ Text("Allowed").tag(Dns64LogFilter.allowed)
+ }
+ .pickerStyle(.segmented)
+ .listRowBackground(Color.clear)
+ .listRowInsets(EdgeInsets())
+ }
+ if let pollError {
+ Section { Text(verbatim: pollError).foregroundStyle(.red) }
+ } else if !loaded {
+ HStack { Spacer(); ProgressView(); Spacer() }.listRowBackground(Color.clear)
+ } else if rows.isEmpty {
+ Section { Text("No queries.").foregroundStyle(.secondary) }
+ }
+ Section {
+ ForEach(rows.indices, id: \.self) { logRow(rows[$0]) }
+ }
+ }
+ .navigationTitle("Query log")
+ .navigationBarTitleDisplayMode(.inline)
+ .searchable(text: $query, prompt: "Domain or client")
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ Button(live ? "Pause live update" : "Resume live update", systemImage: live ? "pause.fill" : "play.fill") {
+ live.toggle()
+ }
+ }
+ }
+ .showLoading($busy)
+ .errorAlert($error)
+ .alert(selected?.domain ?? "", isPresented: Binding(get: { selected != nil }, set: { if !$0 { selected = nil } }),
+ presenting: selected) { row in
+ if isBlocked(row) {
+ Button("Allow this domain") { change(row, block: false) }
+ } else {
+ Button("Block this domain", role: .destructive) { change(row, block: true) }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: { row in
+ Text(isBlocked(row) ? dns64AllowMessage(reason: row.reason) : dns64BlockMessage)
+ }
+ .task(id: PollKey(active: scenePhase == .active, live: live, filter: filter, query: query)) { await poll() }
+ }
+
+ private func isBlocked(_ row: Node64.DNS64LogRow) -> Bool { row.status?.rawValue == "blocked" }
+
+ @ViewBuilder private func logRow(_ row: Node64.DNS64LogRow) -> some View {
+ if row.domain != nil {
+ Button { selected = row } label: { rowContent(row) }.buttonStyle(.plain)
+ } else {
+ rowContent(row)
+ }
+ }
+
+ private func rowContent(_ row: Node64.DNS64LogRow) -> some View {
+ let who = row.clientName?.nonBlank ?? row.client ?? "–"
+ let time = row.date?.formatted(date: .omitted, time: .standard) ?? "–"
+ let detail = [who, row.qtype, time].compactMap { $0 }.joined(separator: " · ")
+ return HStack(alignment: .top, spacing: 8) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: row.domain ?? "–").font(.headline).lineLimit(2)
+ Text(verbatim: detail).font(.footnote).foregroundStyle(.secondary).lineLimit(2)
+ }
+ Spacer(minLength: 8)
+ ProxyTag(tag: dns64StatusTag(row.status?.rawValue))
+ }
+ .contentShape(Rectangle())
+ }
+
+ /// Polls every 3 s while `live`, one fetch otherwise; 300 ms debounce for a typed query.
+ private func poll() async {
+ guard scenePhase == .active, let dns = nodes.client(for: nodeId)?.dns64 else { return }
+ let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ let status = filter.rawStatus.map { Node64.DNS64QueryStatus(rawValue: $0) }
+ do {
+ if !text.isEmpty { try await Task.sleep(for: .milliseconds(300)) }
+ repeat {
+ do {
+ rows = try await dns.log(status: status, query: text.isEmpty ? nil : text, limit: 100).rows ?? []
+ pollError = nil
+ } catch {
+ try Task.checkCancellation()
+ pollError = ErrorText.node(error).titledText
+ }
+ loaded = true
+ guard live else { return }
+ try await Task.sleep(for: .seconds(3))
+ } while true
+ } catch {
+ return
+ }
+ }
+
+ private func change(_ row: Node64.DNS64LogRow, block: Bool) {
+ guard let domain = row.domain, let dns = nodes.client(for: nodeId)?.dns64 else { return }
+ Task {
+ busy = true
+ defer { busy = false }
+ do {
+ if block { _ = try await dns.denylist.add(domain) } else { _ = try await dns.allowlist.add(domain) }
+ } catch { self.error = .node(error) }
+ }
+ }
+}
diff --git a/IPv64/Views/DNS64/NodeDnsMetricsSections.swift b/IPv64/Views/DNS64/NodeDnsMetricsSections.swift
new file mode 100644
index 0000000..3e433b1
--- /dev/null
+++ b/IPv64/Views/DNS64/NodeDnsMetricsSections.swift
@@ -0,0 +1,294 @@
+import SwiftUI
+import Charts
+import IPv64
+
+/// KPI tiles, chart, upstreams, cache and top lists. Failed or empty sections stay hidden (failures show their text).
+struct NodeDnsMetricsSections: View {
+ let data: DnsData
+ @Binding var range: DnsRange
+ let dns: Node64.DNS64
+ let actions: DnsActions
+ let onCache: (DnsSec) -> Void
+
+ @State private var confirmFlush = false
+
+ var body: some View {
+ kpiSection
+ chartSection
+ upstreamsSection
+ cacheSection
+ topSection("Top blocked domains", data.blocked) { $0.name ?? "–" }
+ topSection("Top queried domains", data.allowed) { $0.name ?? "–" }
+ topSection("Top clients", data.clients) { $0.hostname?.nonBlank ?? $0.name ?? "–" }
+ }
+
+ @ViewBuilder private func failed(_ title: LocalizedStringKey, _ failure: DnsSectionError) -> some View {
+ Section(title) { Text(verbatim: failure.text).foregroundStyle(.red) }
+ }
+
+ // MARK: KPI
+
+ @ViewBuilder private var kpiSection: some View {
+ switch data.summary {
+ case .failure(let failure):
+ failed("Overview", failure)
+ case .success(let summary):
+ let s = summary.summary
+ let total = s?.total ?? 0, blocked = s?.blocked ?? 0, cached = s?.cached ?? 0
+ // One list section like the Fitness/Health summaries: values in two columns, no separate cards.
+ Section {
+ Grid(alignment: .topLeading, horizontalSpacing: 16, verticalSpacing: 12) {
+ GridRow {
+ DnsKpiTile("Queries", total.formatted(), caption: String(localized: "≈ \((total / range.hours).formatted()) per hour"))
+ DnsKpiTile("Blocked", blocked.formatted(), caption: String(localized: "\(dns64Percent(blocked, of: total)) % of queries"))
+ }
+ Divider()
+ GridRow {
+ DnsKpiTile("From cache", cached.formatted(), caption: String(localized: "\(dns64Percent(cached, of: total)) % answered instantly"))
+ DnsKpiTile("Clients", (s?.clients ?? 0).formatted(), caption: nil)
+ }
+ Divider()
+ GridRow {
+ DnsKpiTile("Ø Upstream", s?.avgUpstreamMs.map { "\(dns64Ms($0)) ms" } ?? "–", caption: nil)
+ DnsKpiTile("Blocklists", (summary.blocklistSize ?? 0).formatted(), caption: String(localized: "domains"))
+ }
+ }
+ .padding(.vertical, 4)
+ } header: {
+ // The period applies to the overview, the chart and the top lists.
+ HStack {
+ Text("Overview")
+ Spacer()
+ Picker("Period", selection: $range) {
+ ForEach(DnsRange.allCases) { Text($0.label).tag($0) }
+ }
+ .pickerStyle(.menu)
+ .textCase(nil)
+ .font(.subheadline)
+ }
+ }
+ }
+ }
+
+ // MARK: Chart
+
+ @ViewBuilder private var chartSection: some View {
+ switch data.timeline {
+ case .failure(let failure):
+ failed("Queries over time", failure)
+ case .success(let value):
+ let bars = dns64Bars(value.buckets ?? [])
+ if !bars.isEmpty { Section("Queries over time") { DnsQueriesChart(bars: bars, range: range) } }
+ }
+ }
+
+ // MARK: Upstreams
+
+ @ViewBuilder private var upstreamsSection: some View {
+ switch data.upstreams {
+ case .failure(let failure):
+ failed("Upstream servers", failure)
+ case .success(let value):
+ let servers = value.servers ?? []
+ if !servers.isEmpty {
+ let wins = servers.reduce(0) { $0 + ($1.wins ?? 0) }
+ Section("Upstream servers") {
+ if let mode = value.mode { Text("Mode: \(mode.rawValue)").foregroundStyle(.secondary) }
+ ForEach(servers) { upstreamRow($0, totalWins: wins) }
+ }
+ }
+ }
+ }
+
+ private func upstreamRow(_ s: Node64.DNS64UpstreamStats, totalWins: Int) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(alignment: .firstTextBaseline) {
+ Text(verbatim: s.name ?? s.url ?? "–").font(.headline).lineLimit(2)
+ Spacer(minLength: 8)
+ ProxyTag(tag: .init(text: s.healthy == true ? String(localized: "Healthy") : String(localized: "Unhealthy"),
+ tone: s.healthy == true ? .green : .red))
+ if s.active == true { ProxyTag(tag: .init(text: String(localized: "Active"), tone: .green)) }
+ }
+ Text("Ø \(dns64Ms(s.avgMs)) ms · \((s.requests ?? 0).formatted()) queries · \(s.errors ?? 0) errors")
+ .font(.footnote).foregroundStyle(.secondary)
+ ProgressView(value: totalWins > 0 ? Double(s.wins ?? 0) / Double(totalWins) : 0).tint(.orange)
+ if let error = s.lastError?.nonBlank { Text(verbatim: error).font(.footnote).foregroundStyle(.red) }
+ }
+ }
+
+ // MARK: Cache
+
+ @ViewBuilder private var cacheSection: some View {
+ switch data.cache {
+ case .failure(let failure):
+ failed("DNS cache", failure)
+ case .success(let c):
+ let hits = c.hits ?? 0
+ let lookups = hits + (c.misses ?? 0)
+ Section("DNS cache") {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Hit rate \(dns64Percent(hits, of: lookups)) %")
+ ProgressView(value: lookups > 0 ? Double(hits) / Double(lookups) : 0).tint(.orange)
+ }
+ LabeledContent("Entries", value: String(localized: "\((c.entries ?? 0).formatted()) of \((c.max ?? 0).formatted())"))
+ LabeledContent("Stale served", value: (c.staleServed ?? 0).formatted())
+ LabeledContent("Refreshed in background", value: (c.refreshed ?? 0).formatted())
+ Button("Flush cache", systemImage: "trash", role: .destructive) { confirmFlush = true }
+ .alert("Flush cache", isPresented: $confirmFlush) {
+ Button("Flush", role: .destructive) { flush() }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Remove all cached DNS answers on this node? The next queries are answered by the upstream servers.")
+ }
+ }
+ }
+ }
+
+ private func flush() {
+ Task {
+ await actions.run {
+ _ = try await dns.cache.flush()
+ onCache(await dnsSec { try await dns.cache.get() })
+ }
+ }
+ }
+
+ // MARK: Top lists
+
+ @ViewBuilder private func topSection(_ title: LocalizedStringKey, _ items: DnsSec<[Node64.DNS64TopItem]>,
+ label: @escaping (Node64.DNS64TopItem) -> String) -> some View {
+ switch items {
+ case .failure(let failure):
+ failed(title, failure)
+ case .success(let list) where !list.isEmpty:
+ let maxValue = list.compactMap(\.count).max() ?? 0
+ Section(title) {
+ ForEach(list.indices, id: \.self) { i in
+ let count = list[i].count ?? 0
+ ModuleRankRow(label: label(list[i]), value: count, detail: count.formatted(), maxValue: maxValue, mono: true)
+ }
+ }
+ case .success:
+ EmptyView()
+ }
+ }
+}
+
+/// KPI tile with a prominent number; stretches to the (equal) height of its grid row.
+private struct DnsKpiTile: View {
+ let label: LocalizedStringKey
+ let value: String
+ let caption: String?
+
+ init(_ label: LocalizedStringKey, _ value: String, caption: String?) {
+ self.label = label
+ self.value = value
+ self.caption = caption
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(label).font(.subheadline).foregroundStyle(.secondary)
+ Text(verbatim: value).font(.system(.title2, design: .rounded).weight(.bold)).lineLimit(1).minimumScaleFactor(0.6)
+ .fixedSize(horizontal: false, vertical: true)
+ if let caption {
+ Text(verbatim: caption).font(.caption).foregroundStyle(.secondary).lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true) // wrap and grow the row instead of shrinking the value
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Stacked Allowed/Blocked bars on a time axis; touching a bar shows its time and counts above the chart.
+/// Each bar spans its bucket (start → next start), so the width is right for any bucket size.
+private struct DnsQueriesChart: View {
+ let bars: [Dns64Bar]
+ let range: DnsRange
+ @State private var rawSelection: Date?
+
+ private struct Span: Identifiable {
+ let bar: Dns64Bar
+ let start: Date
+ let end: Date
+ var id: Int { bar.index }
+ }
+
+ /// Bars with a time; the last bucket gets the same length as the one before.
+ private var spans: [Span] {
+ let dated = bars.compactMap { bar in bar.start.map { (bar, $0) } }
+ return dated.indices.map { i in
+ let (bar, start) = dated[i]
+ let step = i + 1 < dated.count ? dated[i + 1].1.timeIntervalSince(start)
+ : (i > 0 ? start.timeIntervalSince(dated[i - 1].1) : 3600)
+ return Span(bar: bar, start: start, end: start.addingTimeInterval(step * 0.85))
+ }
+ }
+
+ private var maxValue: Int { max(bars.map { $0.allowed + $0.blocked }.max() ?? 0, 1) }
+
+ private var selected: Span? {
+ guard let raw = rawSelection else { return nil }
+ return spans.first { raw >= $0.start && raw < $0.end }
+ ?? spans.min { abs($0.start.timeIntervalSince(raw)) < abs($1.start.timeIntervalSince(raw)) }
+ }
+
+ private var header: Text {
+ guard let span = selected else { return Text("Touch the chart for values") }
+ let when = dns64Format(span.start, .dayMonthHm)
+ return Text("\(when) Allowed: \(span.bar.allowed.formatted()) Blocked: \(span.bar.blocked.formatted())")
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ header.font(.caption).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.8)
+ Chart(spans) { span in
+ RectangleMark(xStart: .value("Start", span.start), xEnd: .value("End", span.end),
+ yStart: .value("Queries", 0), yEnd: .value("Queries", span.bar.allowed))
+ .foregroundStyle(Color.green.opacity(opacity(span)))
+ RectangleMark(xStart: .value("Start", span.start), xEnd: .value("End", span.end),
+ yStart: .value("Queries", span.bar.allowed),
+ yEnd: .value("Queries", span.bar.allowed + span.bar.blocked))
+ .foregroundStyle(Color.red.opacity(opacity(span)))
+ }
+ .chartYScale(domain: 0...maxValue)
+ .chartXSelection(value: $rawSelection)
+ .chartXAxis {
+ AxisMarks(values: .automatic(desiredCount: 4)) { value in
+ AxisGridLine().foregroundStyle(.secondary.opacity(0.2))
+ AxisValueLabel {
+ if let date = value.as(Date.self) {
+ Text(verbatim: dns64Format(date, range == .week ? .dayMonth : .hm))
+ }
+ }
+ }
+ }
+ .chartYAxis {
+ AxisMarks(values: .automatic(desiredCount: 3)) {
+ AxisGridLine().foregroundStyle(.secondary.opacity(0.2))
+ AxisValueLabel()
+ }
+ }
+ .frame(height: 160)
+ .accessibilityLabel("Stacked bar chart with \(bars.count) bars, maximum \(maxValue.formatted())")
+ HStack(spacing: 12) {
+ legend("Allowed", .green)
+ legend("Blocked", .red)
+ Spacer()
+ Text("max \(maxValue.formatted())")
+ }
+ .font(.caption2).foregroundStyle(.secondary)
+ }
+ .onChange(of: bars) { rawSelection = nil }
+ }
+
+ private func opacity(_ span: Span) -> Double { selected == nil || selected?.id == span.id ? 1 : 0.35 }
+
+ private func legend(_ text: LocalizedStringKey, _ color: Color) -> some View {
+ HStack(spacing: 4) {
+ RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 8, height: 8)
+ Text(text)
+ }
+ }
+}
diff --git a/IPv64/Views/DNS64/NodeDnsRecordSheet.swift b/IPv64/Views/DNS64/NodeDnsRecordSheet.swift
new file mode 100644
index 0000000..1c4d769
--- /dev/null
+++ b/IPv64/Views/DNS64/NodeDnsRecordSheet.swift
@@ -0,0 +1,98 @@
+import SwiftUI
+import IPv64
+
+/// Create/edit form of a local DNS record. The sheet closes after a successful save or delete.
+struct NodeDnsRecordSheet: View {
+ let record: Node64.DNS64Record?
+ let onSave: (Node64.DNS64RecordInput) async throws -> Void
+ let onDelete: () async throws -> Void
+
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var name = ""
+ @State private var type = "A"
+ @State private var value = ""
+ @State private var ttl = ""
+ @State private var comment = ""
+ @State private var noPTR = false
+ @State private var localOnly = false
+ @State private var busy = false
+ @State private var confirmDelete = false
+ @State private var error: ErrorText?
+
+ private var types: [String] {
+ dns64RecordTypes.contains(type) ? dns64RecordTypes : dns64RecordTypes + [type]
+ }
+
+ var body: some View {
+ DynDNSSheet(title: record == nil ? "New record" : "Edit record", confirmLabel: "Save",
+ confirmEnabled: dns64RecordValid(name: name, value: value, ttl: ttl), isBusy: busy,
+ onConfirm: { run { try await onSave(input) } }) {
+ Section {
+ TextField("Name", text: $name).textInputAutocapitalization(.never).autocorrectionDisabled()
+ Picker("Type", selection: $type) {
+ ForEach(types, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ TextField("Value", text: $value).textInputAutocapitalization(.never).autocorrectionDisabled()
+ TextField("TTL (seconds, optional)", text: $ttl).keyboardType(.numberPad)
+ TextField("Comment (optional)", text: $comment)
+ }
+ Section {
+ if type == "A" || type == "AAAA" { Toggle("No reverse lookup (PTR)", isOn: $noPTR) }
+ Toggle("Only this node", isOn: $localOnly)
+ } footer: {
+ Text("Only this node: the record is never synced in a cluster.")
+ }
+ if record != nil {
+ Section {
+ Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = true }
+ .disabled(busy)
+ }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.medium, .large])
+ .onAppear(perform: fill)
+ .onChange(of: ttl) { ttl = dns64DigitsOnly(ttl) }
+ .alert("Delete record", isPresented: $confirmDelete) {
+ Button("Delete", role: .destructive) { run { try await onDelete() } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Delete \(name) (\(type))?")
+ }
+ .errorAlert($error)
+ }
+
+ private var input: Node64.DNS64RecordInput {
+ Node64.DNS64RecordInput(
+ name: name.trimmingCharacters(in: .whitespacesAndNewlines),
+ type: Node64.DNS64RecordType(rawValue: type),
+ value: value.trimmingCharacters(in: .whitespacesAndNewlines),
+ ttl: Int(ttl),
+ comment: dns64Comment(comment, isEdit: record != nil),
+ noPTR: dns64Flag(original: record?.noPTR, toggle: noPTR),
+ localOnly: dns64Flag(original: record?.localOnly, toggle: localOnly))
+ }
+
+ private func fill() {
+ guard let record else { return }
+ name = record.name
+ type = record.type.rawValue
+ value = record.value
+ ttl = record.ttl.map(String.init) ?? ""
+ comment = record.comment ?? ""
+ noPTR = record.noPTR ?? false
+ localOnly = record.localOnly ?? false
+ }
+
+ private func run(_ operation: @escaping () async throws -> Void) {
+ Task {
+ busy = true
+ defer { busy = false }
+ do {
+ try await operation()
+ dismiss()
+ } catch { self.error = .node(error) }
+ }
+ }
+}
diff --git a/IPv64/Views/DNS64/NodeDnsRecordsView.swift b/IPv64/Views/DNS64/NodeDnsRecordsView.swift
new file mode 100644
index 0000000..4227ac6
--- /dev/null
+++ b/IPv64/Views/DNS64/NodeDnsRecordsView.swift
@@ -0,0 +1,138 @@
+import SwiftUI
+import IPv64
+
+/// Local DNS records of a node: enable toggle, create/edit sheet, swipe to delete.
+struct NodeDnsRecordsView: View {
+ let nodeId: String
+
+ @Environment(ConnectedNodes.self) private var nodes
+
+ @State private var records: [Node64.DNS64Record]?
+ @State private var sheet: RecordSheet?
+ @State private var toDelete: Node64.DNS64Record?
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ enum RecordSheet: Identifiable {
+ case new
+ case edit(Node64.DNS64Record)
+ var id: Int { if case .edit(let r) = self { r.id } else { -1 } }
+ }
+
+ private var dns: Node64.DNS64? { nodes.client(for: nodeId)?.dns64 }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(sheet != nil ? .clear : .orange)
+ } else { content }
+ }
+
+ private var content: some View {
+ Group {
+ if dns == nil {
+ ContentUnavailableView("No direct connection to this node.", systemImage: "network.slash")
+ } else if let records {
+ list(records)
+ } else {
+ ProgressView()
+ }
+ }
+ .navigationTitle("Local DNS records")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if dns != nil {
+ ToolbarItem(placement: .primaryAction) {
+ Button("Add record", systemImage: "plus") { sheet = .new }
+ }
+ }
+ }
+ .sheet(item: $sheet) { item in
+ switch item {
+ case .new:
+ NodeDnsRecordSheet(record: nil, onSave: { try await save($0, id: nil) }, onDelete: {})
+ case .edit(let r):
+ NodeDnsRecordSheet(record: r, onSave: { try await save($0, id: r.id) }, onDelete: { try await delete(r) })
+ }
+ }
+ .alert("Delete record", isPresented: Binding(get: { toDelete != nil }, set: { if !$0 { toDelete = nil } }),
+ presenting: toDelete) { r in
+ Button("Delete", role: .destructive) { act { try await delete(r) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { r in
+ Text("Delete \(r.name) (\(r.type.rawValue))?")
+ }
+ .showLoading($busy)
+ .errorAlert($error)
+ .task { await reload() }
+ }
+
+ private func list(_ records: [Node64.DNS64Record]) -> some View {
+ List {
+ if records.isEmpty {
+ ContentUnavailableView("No local DNS records yet.", systemImage: "list.bullet")
+ .listRowBackground(Color.clear)
+ }
+ ForEach(records) { record in
+ HStack {
+ Button { sheet = .edit(record) } label: { row(record) }.buttonStyle(.plain)
+ Toggle("Enabled", isOn: Binding(get: { record.enabled != false }, set: { toggle(record, $0) }))
+ .labelsHidden()
+ .disabled(busy)
+ }
+ .swipeActions(edge: .trailing) {
+ Button("Delete", systemImage: "trash", role: .destructive) { toDelete = record }
+ .labelStyle(.iconOnly)
+ .tint(.red)
+ }
+ }
+ }
+ .refreshable { await reload() }
+ }
+
+ private func row(_ r: Node64.DNS64Record) -> some View {
+ var sub = "\(r.type.rawValue) · \(r.value) · TTL \(r.ttl.map(String.init) ?? "–")"
+ if let comment = r.comment?.nonBlank { sub += "\n" + comment }
+ return VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: r.name.nonBlank ?? "–").font(.headline)
+ Text(verbatim: sub).font(.footnote.monospaced()).foregroundStyle(.secondary).lineLimit(3)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+
+ private func reload() async {
+ guard let dns else { return }
+ do { records = try await dns.records.list() } catch is CancellationError {} catch {
+ if !Task.isCancelled { self.error = .node(error) }
+ if records == nil { records = [] }
+ }
+ }
+
+ /// Spinner, call, then reload the list.
+ private func act(_ operation: @escaping () async throws -> Void) {
+ Task {
+ busy = true
+ do { try await operation() } catch { self.error = .node(error) }
+ await reload()
+ busy = false
+ }
+ }
+
+ private func toggle(_ r: Node64.DNS64Record, _ on: Bool) {
+ guard let dns else { return }
+ act { on ? try await dns.records.enable(r.id) : try await dns.records.disable(r.id) }
+ }
+
+ /// Used by the sheet, which shows the error itself and stays open on failure.
+ private func save(_ input: Node64.DNS64RecordInput, id: Int?) async throws {
+ guard let dns else { return }
+ if let id { _ = try await dns.records.update(id, input) } else { _ = try await dns.records.create(input) }
+ await reload()
+ }
+
+ private func delete(_ r: Node64.DNS64Record) async throws {
+ guard let dns else { return }
+ try await dns.records.delete(r.id)
+ await reload()
+ }
+}
diff --git a/IPv64/Views/DNS64/NodeDnsView.swift b/IPv64/Views/DNS64/NodeDnsView.swift
new file mode 100644
index 0000000..c515a18
--- /dev/null
+++ b/IPv64/Views/DNS64/NodeDnsView.swift
@@ -0,0 +1,97 @@
+import SwiftUI
+import IPv64
+
+/// DNS64 tab root: blocking, metrics and entries to the query log and local records of one connected node.
+struct NodeDnsView: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.scenePhase) private var scenePhase
+ @Binding var popToRootTab: Tabs
+
+ @State private var picked: String?
+ @State private var range: DnsRange = .day
+ @State private var data: DnsData?
+ @State private var resumeToken = 0
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ private struct LoadKey: Equatable { var id: String?; var range: DnsRange; var resume: Int }
+
+ private var currentId: String? {
+ picked.flatMap { nodes.dnsIds.contains($0) ? $0 : nil } ?? nodes.dnsIds.first
+ }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(.orange)
+ } else { content }
+ }
+
+ private var content: some View {
+ Group {
+ if let id = currentId {
+ dashboard(id)
+ } else {
+ ContentUnavailableView("No connected node has DNS64 enabled.", systemImage: "server.rack")
+ }
+ }
+ .navigationTitle(Tabs.dns64.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if nodes.dnsIds.count > 1, let id = currentId {
+ ToolbarItem(placement: .topBarTrailing) {
+ // Title + icon so the item can join the vertical bar on iPhone Duo.
+ Menu {
+ Picker("Node", selection: Binding(get: { id }, set: { picked = $0 })) {
+ ForEach(nodes.dnsIds, id: \.self) { Text(verbatim: nodes.name(of: $0)).tag($0) }
+ }
+ } label: {
+ Label(nodes.name(of: id), systemImage: "point.3.connected.trianglepath.dotted")
+ }
+ }
+ }
+ }
+ .showLoading($busy)
+ .errorAlert($error)
+ .task(id: LoadKey(id: currentId, range: range, resume: resumeToken)) { await load() }
+ .onChange(of: scenePhase) { old, new in if new == .active && old != .active { resumeToken += 1 } }
+ }
+
+ private func dashboard(_ id: String) -> some View {
+ let dns = nodes.client(for: id)?.dns64
+ return List {
+ if dns == nil {
+ ContentUnavailableView("No direct connection to this node.", systemImage: "network.slash")
+ .listRowBackground(Color.clear)
+ } else if let data, data.nodeId == id, let dns {
+ let actions = DnsActions(busy: $busy, error: $error)
+ NodeDnsBlockingSection(blocking: data.blocking, dns: dns, actions: actions,
+ onChange: { self.data?.blocking = .success($0) },
+ onExpired: { resumeToken += 1 })
+ if case .success = data.blocking {
+ Section {
+ NavigationLink {
+ NodeDnsLogView(nodeId: id)
+ } label: { Label("Query log", systemImage: "list.bullet.rectangle") }
+ NavigationLink {
+ NodeDnsRecordsView(nodeId: id)
+ } label: { Label("Local DNS records", systemImage: "externaldrive.connected.to.line.below") }
+ }
+ NodeDnsMetricsSections(data: data, range: $range, dns: dns, actions: actions,
+ onCache: { self.data?.cache = $0 })
+ }
+ } else {
+ HStack { Spacer(); ProgressView(); Spacer() }.listRowBackground(Color.clear)
+ }
+ }
+ .refreshable { await load() }
+ }
+
+ /// Loads every section; a node change clears the old data first.
+ private func load() async {
+ guard let id = currentId else { return }
+ if data?.nodeId != id { data = nil }
+ guard let dns = nodes.client(for: id)?.dns64 else { return }
+ let result = await DnsData.load(nodeId: id, dns: dns, range: range.node)
+ if !Task.isCancelled { data = result }
+ }
+}
diff --git a/IPv64/Views/Domains/DomainDetailView.swift b/IPv64/Views/Domains/DomainDetailView.swift
new file mode 100644
index 0000000..c031cb7
--- /dev/null
+++ b/IPv64/Views/Domains/DomainDetailView.swift
@@ -0,0 +1,401 @@
+import SwiftUI
+import IPv64
+
+/// Domain detail (API v2): notice on IP mismatch, general info, actions, records grouped by type.
+struct DomainDetailView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ let name: String
+ /// Tells the list that this domain changed (it then re-checks only this domain).
+ let onChanged: () -> Void
+
+ @State private var detail: DomainDetail?
+ @State private var myV4 = DynDNSLogic.noIPv4
+ @State private var myV6 = DynDNSLogic.noIPv6
+ @State private var reloadToken = 0
+ @State private var busy = false
+ @State private var isLoading = false
+ @State private var error: ErrorText?
+ @State private var sheet: DetailSheet?
+ @State private var push: DetailPush?
+ @State private var confirm: DetailConfirm?
+ @State private var typedName = ""
+ /// Records removed from the list right away while their delete request runs (no spinner, like Mail).
+ @State private var deletedRecordIds: Set = []
+
+ enum DetailSheet: Identifiable {
+ case newRecord, dynDns, settings, rotated(String)
+ var id: String {
+ switch self {
+ case .newRecord: "record"
+ case .dynDns: "dyndns"
+ case .settings: "settings"
+ case .rotated: "rotated"
+ }
+ }
+ }
+
+ enum DetailPush: Hashable {
+ case record(String)
+ }
+
+ enum DetailConfirm: Identifiable {
+ case setIP, rotate, reset, delete, deleteRecord(Record)
+ var id: String {
+ switch self {
+ case .setIP: "ip"
+ case .rotate: "rotate"
+ case .reset: "reset"
+ case .delete: "delete"
+ case .deleteRecord(let record): "record-\(record.id)"
+ }
+ }
+ }
+
+ private var mismatchV4: Bool { DynDNSLogic.mismatchV4(detail, myV4: myV4) }
+ private var mismatchV6: Bool { DynDNSLogic.mismatchV6(detail, myV6: myV6) }
+ private var updateURL: String? { DynDNSLogic.updateURL(token: detail?.updateToken) }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(sheet != nil ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+
+ private var content: some View {
+ List {
+ if let detail {
+ notice
+ general(detail)
+ actions
+ records(detail)
+ }
+ }
+ .overlay {
+ if detail == nil && error == nil { ProgressView() }
+ }
+ // While loading or running an action everything is locked; the spinner sits in the toolbar.
+ .disabled(busy || isLoading)
+ .navigationTitle(name)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar { toolbar }
+ .refreshable { await load() }
+ .task(id: reloadToken) { await load() }
+ .sheet(item: $sheet) { sheet in
+ switch sheet {
+ case .newRecord: RecordNewSheet(domain: name) { changed() }
+ case .dynDns: DomainDynDnsSheet(domain: name) { changed() }
+ case .settings: NavigationStack { DomainSettingsView(name: name) { changed() } }.appReadableWidth()
+ case .rotated(let url): RotatedTokenSheet(url: url)
+ }
+ }
+ .navigationDestination(item: $push) { target in
+ switch target {
+ case .record(let id): RecordEditView(recordId: id) { changed() }
+ }
+ }
+ .alert(confirmTitle, isPresented: Binding(get: { confirm != nil }, set: { if !$0 { confirm = nil } }),
+ presenting: confirm, actions: confirmActions, message: { Text(confirmMessage($0)) })
+ .errorAlert($error)
+ }
+
+ // MARK: Sections
+
+ /// Same as before: shown when an A or AAAA record differs from this device's IP.
+ @ViewBuilder private var notice: some View {
+ if mismatchV4 || mismatchV6 {
+ Section("Notice") {
+ Text("Your A or AAAA record doesn't match your current IP! This could be due to an active cellular connection or the IP address being assigned a server address.")
+ Button(mismatchV4 && mismatchV6 ? "Set A and AAAA records to current IP?"
+ : mismatchV4 ? "Set A-Record to current IP?" : "Set AAAA-Record to current IP?") {
+ confirm = .setIP
+ }
+ .tint(.orange)
+ }
+ }
+ }
+
+ private func general(_ detail: DomainDetail) -> some View {
+ Section("General") {
+ LabeledContent("Status") {
+ if detail.active == false {
+ Text("Inactive").foregroundStyle(.secondary)
+ } else {
+ let status = DynDNSLogic.status(detail, myV4: myV4, myV6: myV6)
+ Text(status.label).foregroundStyle(status.color)
+ }
+ }
+ LabeledContent("Type", value: DynDNSLogic.kindLabel(detail.kind))
+ LabeledContent("Wildcard", value: detail.wildcard == true ? "yes" : "no")
+ LabeledContent("Updates", value: "\(detail.updateCount ?? 0)")
+ LabeledContent("Ignored on DynDNS updates", value: DynDNSLogic.ignoreLabel(detail.ignore))
+ LabeledContent("Fixed IPv6 prefix", value: detail.ipv6Prefix?.nonBlank ?? String(localized: "Off"))
+ if let created = detail.createdAt {
+ LabeledContent("Created", value: DynDNSLogic.germanTime(created))
+ }
+ }
+ }
+
+ private var actions: some View {
+ Section {
+ Button {
+ copyUpdateURL()
+ } label: {
+ Label("Copy update URL", systemImage: "doc.on.doc")
+ }
+ .disabled(updateURL == nil)
+ Button {
+ sheet = .dynDns
+ } label: {
+ Label("DynDNS update", systemImage: "arrow.triangle.2.circlepath")
+ }
+ Button {
+ sheet = .settings
+ } label: {
+ Label("Settings", systemImage: "slider.horizontal.3")
+ }
+ }
+ .tint(.primary)
+ }
+
+ @ViewBuilder private func records(_ detail: DomainDetail) -> some View {
+ let groups = DynDNSLogic.groupedRecords((detail.records ?? []).filter { !deletedRecordIds.contains($0.id) })
+ if groups.isEmpty {
+ Section { Text("No DNS records.").foregroundStyle(.secondary) }
+ }
+ ForEach(groups, id: \.type) { group in
+ Section("\(group.type) records (\(group.records.count))") {
+ ForEach(group.records) { record in
+ DomainRecordRow(record: record) {
+ push = .record(String(record.id))
+ } onDelete: {
+ confirm = .deleteRecord(record)
+ }
+ }
+ }
+ }
+ }
+
+ // MARK: Toolbar
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { sheet = .newRecord } label: { Label("New DNS record", systemImage: "plus") }
+ .disabled(detail == nil || busy || isLoading)
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ if busy || isLoading {
+ ProgressView()
+ } else {
+ moreMenu
+ }
+ }.appVerticalPreferred()
+ }
+
+ private var moreMenu: some View {
+ Menu {
+ Button("Rotate update token", systemImage: "key") { confirm = .rotate }
+ Divider()
+ DestructiveMenuButton("Reset domain", systemImage: "arrow.counterclockwise") { askTyped(.reset) }
+ DestructiveMenuButton("Delete domain", systemImage: "trash") { askTyped(.delete) }
+ } label: {
+ Label("More actions", systemImage: "ellipsis")
+ }
+ .disabled(detail == nil)
+ }
+
+ // MARK: Confirmations
+
+ private var confirmTitle: String {
+ switch confirm {
+ case .setIP: String(localized: "Update DNS record?")
+ case .rotate: String(localized: "Rotate update token?")
+ case .reset: String(localized: "Reset domain?")
+ case .delete: String(localized: "Delete domain?")
+ case .deleteRecord: String(localized: "Delete DNS record?")
+ case nil: ""
+ }
+ }
+
+ private func confirmMessage(_ confirm: DetailConfirm) -> String {
+ switch confirm {
+ case .setIP:
+ String(localized: "You can't undo this action. This will permanently change the A or AAAA DNS record from your domain.")
+ case .rotate:
+ String(localized: "A new update token is created and the old one stops working immediately. Routers and scripts using the old update URL stop updating until you enter the new URL.")
+ case .reset:
+ String(localized: "All active DNS records of \(name) are deleted and the zone is set up anew. This cannot be undone. Type the domain name to confirm.")
+ case .delete:
+ String(localized: "Do you really want to delete \(name) with all its DNS records? Type the domain name to confirm.")
+ case .deleteRecord(let record):
+ String(localized: "Do you really want to delete the \(record.type?.rawValue ?? "?") record \"\(DynDNSLogic.prefixLabel(record.prefix))\" (\(record.content ?? "–"))?")
+ }
+ }
+
+ @ViewBuilder private func confirmActions(_ confirm: DetailConfirm) -> some View {
+ switch confirm {
+ case .setIP:
+ Button("Update") { run(setToCurrentIP) }
+ case .rotate:
+ Button("Rotate", role: .destructive) { run(rotate) }
+ case .reset:
+ TextField(name, text: $typedName).textInputAutocapitalization(.never).autocorrectionDisabled()
+ Button("Reset", role: .destructive) { run(reset) }.disabled(typedName != name)
+ case .delete:
+ TextField(name, text: $typedName).textInputAutocapitalization(.never).autocorrectionDisabled()
+ Button("Delete", role: .destructive) { run(deleteDomain) }.disabled(typedName != name)
+ case .deleteRecord(let record):
+ Button("Delete", role: .destructive) { Task { await deleteRecord(record) } }
+ }
+ Button("Cancel", role: .cancel) {}
+ }
+
+ private func askTyped(_ request: DetailConfirm) {
+ typedName = ""
+ confirm = request
+ }
+
+ // MARK: Loading and actions
+
+ private func load() async {
+ isLoading = true
+ defer { isLoading = false }
+ let api = session.api
+ async let v4 = session.myIP(.v4)
+ async let v6 = session.myIP(.v6)
+ do {
+ detail = try await ipv64Retrying { try await api.domains.get(name) }
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ myV4 = await v4 ?? DynDNSLogic.noIPv4
+ myV6 = await v6 ?? DynDNSLogic.noIPv6
+ }
+
+ private func changed() {
+ onChanged()
+ reloadToken += 1
+ }
+
+ private func run(_ work: @escaping () async throws -> Void) {
+ Task {
+ busy = true
+ defer { busy = false }
+ do {
+ try await work()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+
+ private func copyUpdateURL() {
+ guard let updateURL else { return }
+ Clipboard.copy(updateURL, sensitive: true)
+ }
+
+ private func setToCurrentIP() async throws {
+ let v4 = mismatchV4 ? DynDNSLogic.knownIp(myV4) : nil
+ let v6 = mismatchV6 ? DynDNSLogic.knownIp(myV6) : nil
+ let result = try await session.api.domains.updateDynDNS(name, ipv4: v4, ipv6: v6)
+ let failed = (result.results ?? []).filter { DynDNSLogic.isFailure($0.result) }
+ if !failed.isEmpty {
+ error = ErrorText(title: String(localized: "Update error"), message: failed.map {
+ "\($0.type?.rawValue ?? "") \($0.ip ?? ""): \(DynDNSLogic.outcomeLabel($0.result))"
+ }.joined(separator: "\n"))
+ }
+ changed()
+ }
+
+ private func rotate() async throws {
+ let rotated = try await session.api.domains.rotateToken(name)
+ changed()
+ if let url = DynDNSLogic.updateURL(token: rotated.updateToken) {
+ sheet = .rotated(url)
+ }
+ }
+
+ private func reset() async throws {
+ detail = try await ipv64Retrying { try await session.api.domains.reset(name) }
+ changed()
+ }
+
+ private func deleteDomain() async throws {
+ do {
+ try await session.api.domains.delete(name)
+ onChanged()
+ dismiss()
+ } catch let e as IPv64Error where e.statusCode == 409 {
+ var text = String(localized: "DNS failover is active for this domain. Remove or pause the failover policy first.")
+ if case .api(let problem) = e, let detail = problem.detail.nonBlank { text = detail }
+ error = ErrorText(title: String(localized: "Domain cannot be deleted"), message: text)
+ }
+ }
+
+ /// The row disappears at once; on failure it comes back with the error.
+ private func deleteRecord(_ record: Record) async {
+ _ = withAnimation { deletedRecordIds.insert(record.id) }
+ do {
+ try await ipv64Retrying { try await session.api.records.delete(String(record.id)) }
+ changed()
+ } catch {
+ _ = withAnimation { deletedRecordIds.remove(record.id) }
+ self.error = ErrorText(error)
+ }
+ }
+}
+
+/// One DNS record: tap edits, swipe deletes; CDN/failover records are locked.
+struct DomainRecordRow: View {
+ let record: Record
+ let onEdit: () -> Void
+ let onDelete: () -> Void
+
+ private var locked: Bool { DynDNSLogic.isLocked(record.state) }
+
+ var body: some View {
+ let row = HStack(alignment: .top) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: DynDNSLogic.prefixLabel(record.prefix)).font(.headline)
+ Text(verbatim: record.content ?? "–").font(.subheadline.monospaced()).lineLimit(3)
+ Text(verbatim: "TTL \(record.ttl.map(String.init) ?? "–") · \(DynDNSLogic.germanTime(record.updatedAt))")
+ .font(.caption).foregroundStyle(.secondary)
+ if let reason = DynDNSLogic.lockReason(record.state) {
+ Text(reason).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ Spacer(minLength: 8)
+ if record.pendingDNS == true {
+ Text("DNS pending").font(.caption).foregroundStyle(.orange)
+ } else if let state = record.state, state != .active, let label = DynDNSLogic.stateLabel(state) {
+ Text(label).font(.caption).foregroundStyle(.secondary)
+ }
+ if locked {
+ Image(systemName: "lock.fill").foregroundStyle(.secondary).accessibilityLabel("Locked")
+ }
+ }
+ .contentShape(Rectangle())
+
+ if locked {
+ row
+ } else {
+ row
+ .onTapGesture(perform: onEdit)
+ .accessibilityAddTraits(.isButton)
+ .swipeActions {
+ Button("Delete", systemImage: "trash", role: .destructive, action: onDelete)
+ .tint(.red)
+ .labelStyle(.iconOnly)
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/Domains/DomainItemView.swift b/IPv64/Views/Domains/DomainItemView.swift
new file mode 100644
index 0000000..03494f8
--- /dev/null
+++ b/IPv64/Views/Domains/DomainItemView.swift
@@ -0,0 +1,57 @@
+import SwiftUI
+import IPv64
+
+/// Domain row (Android layout): name, updates and wildcard in one line, tag for the IP check.
+struct DomainItemView: View {
+ let row: DomainRow
+ let status: DynDNSLogic.IpStatus
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(row.name)
+ .font(.headline)
+ .lineLimit(1)
+ Text("Updates: \(row.updates) · Wildcard: \(row.wildcard ? "yes" : "no")")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Text(status.label)
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(status.color)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(status.color.opacity(0.15), in: Capsule())
+ .fixedSize()
+ }
+ }
+}
+
+extension DynDNSLogic.IpStatus {
+ var label: LocalizedStringKey {
+ switch self {
+ case .checking: "Checking"
+ case .noIp: "No IP"
+ case .unknown: "IP unknown"
+ case .differs: "IP differs"
+ case .matches: "IP matches"
+ }
+ }
+
+ var color: Color {
+ switch self {
+ case .differs: .red
+ case .matches: .green
+ default: .gray
+ }
+ }
+}
+
+#Preview {
+ List {
+ DomainItemView(row: DomainRow(name: "test.iot64.de", kind: .dyndns, wildcard: true, updates: 12), status: .matches)
+ DomainItemView(row: DomainRow(name: "nas.home64.de", kind: .dyndns, wildcard: false, updates: 0), status: .checking)
+ }
+}
diff --git a/IPv64/Views/Domains/DomainSettingsView.swift b/IPv64/Views/Domains/DomainSettingsView.swift
new file mode 100644
index 0000000..9e7d644
--- /dev/null
+++ b/IPv64/Views/Domains/DomainSettingsView.swift
@@ -0,0 +1,127 @@
+import SwiftUI
+import IPv64
+
+/// Domain settings (spec 02 A7).
+struct DomainSettingsView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ let name: String
+ let onSaved: () -> Void
+
+ @State private var original: DomainDetail?
+ @State private var wildcard = false
+ @State private var ignore = DomainIgnore.none
+ @State private var prefix = ""
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ private var prefixValid: Bool { DynDNSLogic.isValidIpv6Prefix(prefix) }
+
+ var body: some View {
+ Group {
+ if name.isEmpty {
+ ContentUnavailableView("No domain selected.", systemImage: "network")
+ } else if original == nil {
+ ProgressView()
+ } else {
+ form
+ }
+ }
+ .navigationTitle("Domain settings")
+ .navigationBarTitleDisplayMode(.inline)
+ .interactiveDismissDisabled(busy)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel", systemImage: "xmark") { dismiss() }.disabled(busy)
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if busy {
+ ProgressView()
+ } else {
+ Button("Save", systemImage: "checkmark") { Task { await save() } }
+ .disabled(original == nil || !prefixValid)
+ }
+ }.appVerticalPreferred()
+ }
+ .task { await load() }
+ .errorAlert($error)
+ }
+
+ private var form: some View {
+ Form {
+ Section { Text(verbatim: name) }
+ Section {
+ Toggle("Wildcard records", isOn: $wildcard)
+ } header: {
+ Text("Wildcard")
+ } footer: {
+ Text("Also resolve *.\(name) to the records of the domain.")
+ }
+ Section {
+ Picker("Ignored address family", selection: $ignore) {
+ Text("None").tag(DomainIgnore.none)
+ Text("Ignore IPv4").tag(DomainIgnore.ipv4)
+ Text("Ignore IPv6").tag(DomainIgnore.ipv6)
+ }
+ } header: {
+ Text("DynDNS updates")
+ } footer: {
+ Text("Updates of the ignored family are not applied (e.g. ignore IPv6 if your router reports an unwanted address).")
+ }
+ Section {
+ TextField("Fixed IPv6 prefix", text: $prefix, prompt: Text("2001:db8:1234:5600::/56"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.asciiCapable)
+ .onChange(of: prefix) { prefix = prefix.trimmingCharacters(in: .whitespaces) }
+ } header: {
+ Text("IPv6 prefix")
+ } footer: {
+ if prefixValid {
+ Text("Combined with the interface IDs of your records. Empty = off.")
+ } else {
+ Text("Expected e.g. 2001:db8:1234:5600::/56").foregroundStyle(.red)
+ }
+ }
+ }
+ .disabled(busy)
+ }
+
+ private func load() async {
+ guard !name.isEmpty else { return }
+ do {
+ let detail = try await ipv64Retrying { try await session.api.domains.get(name) }
+ guard original == nil else { return }
+ original = detail
+ wildcard = detail.wildcard == true
+ ignore = detail.ignore ?? .none
+ prefix = detail.ipv6Prefix ?? ""
+ } catch {
+ if !Task.isCancelled { self.error = ErrorText(error) }
+ }
+ }
+
+ private func save() async {
+ guard let original else { return }
+ let newPrefix = prefix.trimmingCharacters(in: .whitespaces)
+ let changedWildcard = wildcard != (original.wildcard == true)
+ let changedIgnore = ignore != (original.ignore ?? .none)
+ let changedPrefix = newPrefix != (original.ipv6Prefix ?? "")
+ guard changedWildcard || changedIgnore || changedPrefix else {
+ dismiss()
+ return
+ }
+ busy = true
+ defer { busy = false }
+ do {
+ _ = try await ipv64Retrying {
+ try await session.api.domains.update(
+ name, wildcard: changedWildcard ? wildcard : nil, ignore: changedIgnore ? ignore : nil,
+ ipv6Prefix: changedPrefix ? newPrefix : nil)
+ }
+ onSaved()
+ dismiss()
+ } catch {
+ if !Task.isCancelled { self.error = ErrorText(error) }
+ }
+ }
+}
diff --git a/IPv64/Views/Domains/DomainSheets.swift b/IPv64/Views/Domains/DomainSheets.swift
new file mode 100644
index 0000000..96fba0d
--- /dev/null
+++ b/IPv64/Views/Domains/DomainSheets.swift
@@ -0,0 +1,299 @@
+import SwiftUI
+import IPv64
+
+/// A form sheet: Cancel leading, confirm trailing, locked while busy.
+struct DynDNSSheet: View {
+ @Environment(\.dismiss) private var dismiss
+ let title: LocalizedStringKey
+ var subtitle: String?
+ var confirmLabel: LocalizedStringKey?
+ var confirmEnabled = true
+ var isBusy = false
+ var onConfirm: (() -> Void)?
+ @ViewBuilder let content: Content
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ if let subtitle { Section { Text(verbatim: subtitle).foregroundStyle(.secondary) } }
+ content
+ }
+ .navigationTitle(title)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if confirmLabel == nil {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Done", systemImage: "checkmark") { dismiss() }
+ }
+ } else {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel", systemImage: "xmark") { dismiss() }.disabled(isBusy)
+ }
+ }
+ if let onConfirm, let confirmLabel {
+ ToolbarItem(placement: .confirmationAction) {
+ if isBusy {
+ ProgressView()
+ } else {
+ Button(confirmLabel, systemImage: "checkmark", action: onConfirm).disabled(!confirmEnabled)
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ }
+ .appReadableWidth()
+ .interactiveDismissDisabled(isBusy)
+ }
+}
+
+/// Manual DynDNS update (spec 02 A4): form, then the result in the same sheet.
+struct DomainDynDnsSheet: View {
+ @Environment(Session.self) private var session
+ let domain: String
+ /// Called when the sheet closes after a successful update.
+ let onUpdated: () -> Void
+
+ @State private var ipv4 = ""
+ @State private var ipv6 = ""
+ @State private var prefix = ""
+ @State private var loadingFamily: Session.IPFamilyChoice?
+ @State private var hint: LocalizedStringKey?
+ @State private var busy = false
+ @State private var result: DynDNSResult?
+ @State private var error: ErrorText?
+
+ private var v4Error: Bool { !ipv4.isEmpty && !DynDNSLogic.isIpv4(ipv4) }
+ private var v6Error: Bool { !ipv6.isEmpty && !DynDNSLogic.isIpv6(ipv6) }
+
+ var body: some View {
+ Group {
+ if let result {
+ resultView(result)
+ } else {
+ form
+ }
+ }
+ .errorAlert($error)
+ .presentationDetents([.large])
+ }
+
+ private var form: some View {
+ DynDNSSheet(title: "Manual DynDNS update", confirmLabel: "Update",
+ confirmEnabled: !v4Error && !v6Error, isBusy: busy, onConfirm: { Task { await update() } }) {
+ Section {
+ Text("Sets the A/AAAA records of \(domain). Leave both addresses empty to use the address the request comes from. Only public addresses are accepted; missing records are created.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ Section("Addresses") {
+ field("IPv4 address", prompt: "e.g. 203.0.113.10", text: $ipv4, invalid: v4Error,
+ message: "Not a valid IPv4 address")
+ field("IPv6 address", prompt: "e.g. 2001:db8::10", text: $ipv6, invalid: v6Error,
+ message: "Not a valid IPv6 address")
+ HStack {
+ fill("My IPv4", family: .v4)
+ fill("My IPv6", family: .v6)
+ }
+ .buttonStyle(.bordered)
+ if let hint { Text(hint).font(.footnote).foregroundStyle(.orange) }
+ }
+ Section {
+ TextField("Prefix (optional)", text: $prefix, prompt: Text("e.g. nas"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .onChange(of: prefix) { prefix = prefix.trimmingCharacters(in: .whitespaces) }
+ } header: {
+ Text("Record")
+ } footer: {
+ Text("Empty = the domain itself")
+ }
+ }
+ }
+
+ private func field(_ title: LocalizedStringKey, prompt: LocalizedStringKey, text: Binding,
+ invalid: Bool, message: LocalizedStringKey) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ TextField(title, text: text, prompt: Text(prompt))
+ .keyboardType(.asciiCapable).textInputAutocapitalization(.never).autocorrectionDisabled()
+ .onChange(of: text.wrappedValue) { text.wrappedValue = text.wrappedValue.trimmingCharacters(in: .whitespaces) }
+ if invalid { Text(message).font(.caption).foregroundStyle(.red) }
+ }
+ }
+
+ private func fill(_ title: LocalizedStringKey, family: Session.IPFamilyChoice) -> some View {
+ Button {
+ Task { await fillMyIP(family) }
+ } label: {
+ HStack(spacing: 6) {
+ if loadingFamily == family { ProgressView().controlSize(.small) }
+ Text(title)
+ }
+ .frame(maxWidth: .infinity)
+ }
+ .disabled(loadingFamily == family)
+ }
+
+ private func resultView(_ result: DynDNSResult) -> some View {
+ DynDNSSheet(title: "DynDNS update") {
+ Section {
+ Text(result.changed == true ? "At least one record was changed." : "No record was changed.")
+ if (result.results ?? []).isEmpty {
+ Text("The server returned no results per IP.").foregroundStyle(.secondary)
+ }
+ }
+ Section {
+ ForEach(Array((result.results ?? []).enumerated()), id: \.offset) { _, entry in
+ HStack(alignment: .firstTextBaseline) {
+ Text(verbatim: entry.type?.rawValue ?? "?").font(.headline).frame(minWidth: 56, alignment: .leading)
+ VStack(alignment: .leading) {
+ Text(verbatim: entry.ip ?? "–").font(.body.monospaced())
+ Text(verbatim: DynDNSLogic.outcomeLabel(entry.result))
+ .font(.caption)
+ .foregroundStyle(DynDNSLogic.isFailure(entry.result) ? .red : Color.secondary)
+ }
+ }
+ }
+ }
+ }
+ .onDisappear(perform: onUpdated)
+ }
+
+ private func fillMyIP(_ family: Session.IPFamilyChoice) async {
+ hint = nil
+ loadingFamily = family
+ defer { loadingFamily = nil }
+ if let ip = await session.myIP(family) {
+ if family == .v4 { ipv4 = ip } else { ipv6 = ip }
+ } else {
+ hint = family == .v4 ? "No public IPv4 address found." : "No public IPv6 address found."
+ }
+ }
+
+ private func update() async {
+ busy = true
+ defer { busy = false }
+ do {
+ let r = try await session.api.domains.updateDynDNS(
+ domain, ipv4: ipv4.nonBlank, ipv6: ipv6.nonBlank, prefix: prefix.nonBlank)
+ result = r
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
+
+/// Shown after "Rotate update token" (spec 02 A3 RotatedTokenDialog): the URL stays in memory only.
+struct RotatedTokenSheet: View {
+ let url: String
+
+ var body: some View {
+ DynDNSSheet(title: "New update URL") {
+ Section {
+ Text("The update token was rotated. The old update URL no longer works. Enter the new URL in your router or update script.")
+ }
+ Section("Update URL") {
+ Text(verbatim: url).font(.callout.monospaced())
+ Button("Copy update URL", systemImage: "doc.on.doc") {
+ Clipboard.copy(url, sensitive: true)
+ }
+ }
+ }
+ .presentationDetents([.medium])
+ }
+}
+
+/// New domain (spec 02 A2).
+struct DomainNewSheet: View {
+ @Environment(Session.self) private var session
+ let onCreated: () -> Void
+
+ @State private var subdomain = ""
+ @State private var zone = "ipv64.net"
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ var body: some View {
+ DynDNSSheet(title: "New domain", confirmLabel: "Create",
+ confirmEnabled: !subdomain.trimmingCharacters(in: .whitespaces).isEmpty, isBusy: busy,
+ onConfirm: { Task { await create() } }) {
+ Section {
+ TextField("Subdomain", text: $subdomain, prompt: Text("homelab01"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ Picker("Domain", selection: $zone) {
+ ForEach(DynDNSLogic.zones.dropLast(), id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ }
+ }
+ .errorAlert($error)
+ .appReadableWidth()
+ .presentationDetents([.medium])
+ }
+
+ private func create() async {
+ let sub = subdomain.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard DynDNSLogic.isValidSubdomain(sub) else {
+ error = ErrorText(title: String(localized: "Invalid subdomain"),
+ message: String(localized: "Enter a single label without dots or spaces, e.g. homelab01."))
+ return
+ }
+ busy = true
+ defer { busy = false }
+ do {
+ _ = try await session.api.domains.create(name: "\(sub).\(zone)")
+ onCreated()
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
+
+/// New DNS record (spec 02 A5).
+struct RecordNewSheet: View {
+ @Environment(Session.self) private var session
+ let domain: String
+ let onCreated: () -> Void
+
+ @State private var prefix = ""
+ @State private var type = "A"
+ @State private var value = ""
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ var body: some View {
+ DynDNSSheet(title: "New DNS record", subtitle: domain, confirmLabel: "Create",
+ confirmEnabled: !value.trimmingCharacters(in: .whitespaces).isEmpty, isBusy: busy,
+ onConfirm: { Task { await create() } }) {
+ Section {
+ TextField("Name", text: $prefix, prompt: Text("dkim._domainkey"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ Picker("Type", selection: $type) {
+ ForEach(DynDNSLogic.newRecordTypes, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ TextField("Value", text: $value, prompt: Text("IP or TXT content"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ } footer: {
+ Text("Empty = the domain itself")
+ }
+ }
+ .errorAlert($error)
+ .appReadableWidth()
+ .presentationDetents([.medium])
+ }
+
+ private func create() async {
+ let prefix = prefix.trimmingCharacters(in: .whitespacesAndNewlines)
+ let value = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !value.isEmpty else {
+ error = ErrorText(title: String(localized: "Empty field"),
+ message: String(localized: "Please fill the DNS value field!"))
+ return
+ }
+ busy = true
+ defer { busy = false }
+ do {
+ _ = try await session.api.records.create(domain: domain, type: RecordType(rawValue: type),
+ prefix: prefix.isEmpty ? nil : prefix, content: value)
+ onCreated()
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
diff --git a/IPv64/Views/Domains/DomainView.swift b/IPv64/Views/Domains/DomainView.swift
new file mode 100644
index 0000000..038cb8d
--- /dev/null
+++ b/IPv64/Views/Domains/DomainView.swift
@@ -0,0 +1,158 @@
+import SwiftUI
+import IPv64
+
+/// Domain list (API v2), alphabetical, kind filter, IP status checked in the background from top to bottom.
+struct DomainView: View {
+ @Environment(Session.self) private var session
+ @Binding var popToRootTab: Tabs
+ @State private var rows: [DomainRow]?
+ @State private var details: [String: DomainDetail] = [:]
+ @State private var myV4 = DynDNSLogic.noIPv4
+ @State private var myV6 = DynDNSLogic.noIPv6
+ @State private var filter = DomainKindFilter.all
+ @State private var showNewDomainSheet = false
+ @State private var isDomainChanged = false
+ @State private var reloadVersion = 0
+ @State private var error: ErrorText?
+ /// Bumped after every list load; restarts the background IP check.
+ @State private var loadCount = 0
+
+ private var visible: [DomainRow] {
+ (rows ?? []).filter { filter.matches(kind: $0.kind, name: $0.name) }
+ }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView.setColorGradient(showNewDomainSheet ? .clear : .orange)
+ } else { listView }
+ }
+
+ private var listView: some View {
+ List(visible) { row in
+ NavigationLink(value: DomainRoute(name: row.name)) {
+ DomainItemView(row: row, status: status(of: row))
+ }
+ }
+ .overlay { emptyState }
+ .navigationTitle(Tabs.domain.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .navigationDestination(for: DomainRoute.self) { route in
+ DomainDetailView(name: route.name) {
+ // Only the changed domain is checked again; the others keep their result.
+ details[route.name] = nil
+ isDomainChanged = true
+ }
+ }
+ .toolbar { toolbar }
+ .refreshable { await reload() }
+ .task(id: reloadVersion) { await reload() }
+ .task(id: loadCount) { await checkIPs() }
+ .onChange(of: isDomainChanged) { _, changed in
+ guard changed else { return }
+ isDomainChanged = false
+ reloadVersion += 1
+ }
+ .sheet(isPresented: $showNewDomainSheet) {
+ DomainNewSheet {
+ showNewDomainSheet = false
+ isDomainChanged = true
+ }
+ }
+ .errorAlert($error)
+ }
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Menu {
+ Picker("Kind", selection: $filter) {
+ ForEach(DomainKindFilter.allCases) { Text($0.title).tag($0) }
+ }
+ } label: {
+ Label("Filter domains", systemImage: filter == .all
+ ? "line.3.horizontal.decrease" : "line.3.horizontal.decrease.circle.fill")
+ }
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { showNewDomainSheet = true } label: { Label("Add domain", image: "network.badge.plus") }
+ }
+ }
+
+ @ViewBuilder private var emptyState: some View {
+ if rows == nil {
+ ProgressView("Loading domains…")
+ } else if visible.isEmpty {
+ if rows?.isEmpty == true {
+ ContentUnavailableView {
+ Label("No domains yet", systemImage: "network")
+ } description: {
+ Text("Add your first domain to manage its DNS records.")
+ } actions: {
+ Button("Add domain") { showNewDomainSheet = true }
+ }
+ } else {
+ ContentUnavailableView("No domains of this kind", systemImage: "network")
+ }
+ }
+ }
+
+ private func status(of row: DomainRow) -> DynDNSLogic.IpStatus {
+ DynDNSLogic.status(details[row.name], myV4: myV4, myV6: myV6)
+ }
+
+ private func reload() async {
+ let api = session.api
+ async let v4 = session.myIP(.v4)
+ async let v6 = session.myIP(.v6)
+ do {
+ rows = try await ipv64Retrying { try await api.domains.list() }
+ .compactMap { domain in
+ domain.name?.nonBlank.map {
+ DomainRow(name: $0, kind: domain.kind, wildcard: domain.wildcard == true,
+ updates: domain.updateCount ?? 0)
+ }
+ }
+ .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
+ loadCount += 1
+ } catch is CancellationError {
+ } catch {
+ if rows == nil { rows = [] }
+ self.error = ErrorText(error)
+ }
+ myV4 = await v4 ?? DynDNSLogic.noIPv4
+ myV6 = await v6 ?? DynDNSLogic.noIPv6
+ }
+
+ /// Records come only with the detail: fetched one domain after another in list order, at most one per second.
+ private func checkIPs() async {
+ let api = session.api
+ for row in rows ?? [] where details[row.name] == nil {
+ let started = Date()
+ guard let detail = try? await ipv64Retrying({ try await api.domains.get(row.name) }) else {
+ if Task.isCancelled { return }
+ continue
+ }
+ details[row.name] = detail
+ let wait = started.addingTimeInterval(1).timeIntervalSinceNow
+ if wait > 0 { try? await Task.sleep(for: .seconds(wait)) }
+ if Task.isCancelled { return }
+ }
+ }
+}
+
+struct DomainRow: Identifiable, Hashable {
+ let name: String
+ let kind: DomainKind?
+ let wildcard: Bool
+ let updates: Int
+ var id: String { name }
+}
+
+struct DomainRoute: Hashable {
+ let name: String
+}
+
+#Preview { NavigationStack { DomainView(popToRootTab: .constant(.domain)) } }
diff --git a/IPv64/Views/Domains/RecordEditView.swift b/IPv64/Views/Domains/RecordEditView.swift
new file mode 100644
index 0000000..c0ad732
--- /dev/null
+++ b/IPv64/Views/Domains/RecordEditView.swift
@@ -0,0 +1,148 @@
+import SwiftUI
+import IPv64
+
+/// Record edit (spec 02 A6).
+struct RecordEditView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ let recordId: String
+ let onSaved: () -> Void
+
+ @State private var original: Record?
+ @State private var type = "A"
+ @State private var prefix = ""
+ @State private var content = ""
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ private var locked: Bool { DynDNSLogic.isLocked(original?.state) }
+ private var trimmedContent: String { content.trimmingCharacters(in: .whitespacesAndNewlines) }
+ private var trimmedPrefix: String { prefix.trimmingCharacters(in: .whitespacesAndNewlines) }
+
+ private var typeChanged: Bool { type != original?.type?.rawValue }
+ private var prefixChanged: Bool { trimmedPrefix != DynDNSLogic.editPrefix(original?.prefix) }
+ private var contentChanged: Bool { trimmedContent != original?.content }
+ private var isIpType: Bool { original?.type == .a || original?.type == .aaaa }
+ private var replaces: Bool { typeChanged || prefixChanged || (contentChanged && !isIpType) }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ screen.setColorGradient(.orange)
+ } else {
+ screen
+ }
+ }
+
+ private var screen: some View {
+ Group {
+ if recordId.isEmpty {
+ ContentUnavailableView("No record selected.", systemImage: "list.bullet")
+ } else if let original {
+ form(original)
+ } else {
+ ProgressView()
+ }
+ }
+ .navigationTitle("Edit record")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ if busy {
+ ProgressView()
+ } else {
+ Button("Save", systemImage: "checkmark") { Task { await save() } }
+ .disabled(original == nil || locked || trimmedContent.isEmpty)
+ }
+ }.appVerticalPreferred()
+ }
+ .task { await load() }
+ .errorAlert($error)
+ }
+
+ private func form(_ record: Record) -> some View {
+ Form {
+ Section {
+ LabeledContent("Name") {
+ Text(verbatim: record.fqdn ?? [record.prefix, record.domain].compactMap { $0?.nonBlank }.joined(separator: "."))
+ }
+ LabeledContent("TTL", value: "\(record.ttl.map(String.init) ?? "–") s")
+ if let label = DynDNSLogic.stateLabel(record.state) { LabeledContent("State", value: label) }
+ if record.pendingDNS == true { LabeledContent("DNS", value: "Change is being propagated") }
+ if let updated = record.updatedAt { LabeledContent("Last update", value: DynDNSLogic.germanTime(updated)) }
+ }
+ if locked {
+ Section("Locked") {
+ Text(verbatim: DynDNSLogic.lockReason(record.state) ?? String(localized: "This record cannot be edited."))
+ }
+ }
+ Section {
+ Picker("Type", selection: $type) {
+ ForEach(typeOptions, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ .disabled(locked)
+ TextField("Prefix", text: $prefix, prompt: Text("e.g. www"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .onChange(of: prefix) { prefix = prefix.trimmingCharacters(in: .whitespaces) }
+ .disabled(locked)
+ TextField("Value", text: $content, prompt: Text("e.g. IP, TXT record, MX \"10 mail.example.com\""),
+ axis: type == "TXT" ? .vertical : .horizontal)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .disabled(locked)
+ if trimmedContent.isEmpty { Text("Required").font(.caption).foregroundStyle(.red) }
+ } header: {
+ Text("Record")
+ } footer: {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Empty = the domain itself")
+ if !locked {
+ Text(replaces
+ ? "This change replaces the record: it gets a new ID and record token. Scripts that use the old record token must be updated."
+ : "Changing only the IP of an A/AAAA record keeps its ID and record token. Any other change replaces the record with a new ID and token.")
+ }
+ }
+ }
+ }
+ .disabled(busy)
+ }
+
+ private var typeOptions: [String] {
+ let current = original?.type?.rawValue
+ return DynDNSLogic.allRecordTypes + (current.map { DynDNSLogic.allRecordTypes.contains($0) ? [] : [$0] } ?? [])
+ }
+
+ private func load() async {
+ guard !recordId.isEmpty else { return }
+ do {
+ let record = try await ipv64Retrying { try await session.api.records.get(recordId) }
+ guard original == nil else { return }
+ original = record
+ type = record.type?.rawValue ?? "A"
+ prefix = DynDNSLogic.editPrefix(record.prefix)
+ content = record.content ?? ""
+ } catch {
+ if !Task.isCancelled { self.error = ErrorText(error) }
+ }
+ }
+
+ private func save() async {
+ guard let original else { return }
+ guard typeChanged || prefixChanged || contentChanged else {
+ dismiss()
+ return
+ }
+ busy = true
+ defer { busy = false }
+ do {
+ _ = try await ipv64Retrying {
+ try await session.api.records.update(
+ recordId, type: typeChanged ? RecordType(rawValue: type) : nil,
+ prefix: prefixChanged ? trimmedPrefix : nil, content: contentChanged ? trimmedContent : nil)
+ }
+ onSaved()
+ dismiss()
+ } catch {
+ if !Task.isCancelled { self.error = ErrorText(error) }
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckChannelPicker.swift b/IPv64/Views/Healthcheck/HealthcheckChannelPicker.swift
new file mode 100644
index 0000000..b3f5ffd
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckChannelPicker.swift
@@ -0,0 +1,85 @@
+import SwiftUI
+import IPv64
+
+/// Channel choice: default channels or a native multi-select list (pushed inside the sheet).
+/// Channels themselves are managed elsewhere.
+struct HealthcheckChannelPicker: View {
+ @Binding var useDefault: Bool
+ @Binding var selected: Set
+ let channels: [HC2Channel]
+ let types: [HC2ChannelType]?
+
+ private var summary: String {
+ if useDefault { return String(localized: "Default channels") }
+ let count = channels.filter { selected.contains($0.id) }.count
+ return count == 0 ? String(localized: "None") : String(localized: "\(count) channels")
+ }
+
+ var body: some View {
+ NavigationLink {
+ HealthcheckChannelList(useDefault: $useDefault, selected: $selected, channels: channels, types: types)
+ } label: {
+ LabeledContent("Channels") { Text(verbatim: summary).lineLimit(1) }
+ }
+ }
+}
+
+private struct HealthcheckChannelList: View {
+ @Binding var useDefault: Bool
+ @Binding var selected: Set
+ let channels: [HC2Channel]
+ let types: [HC2ChannelType]?
+
+ var body: some View {
+ List {
+ Section {
+ Toggle("Default channels", isOn: $useDefault)
+ } footer: {
+ Text("Notify all channels marked as default")
+ }
+ if !useDefault {
+ Section("Selected channels") {
+ if channels.isEmpty {
+ Text("No channels yet. Create one under Monitoring › Channels.").foregroundStyle(.secondary)
+ }
+ ForEach(channels.filter { $0.id >= 0 }) { channel in
+ Button {
+ if selected.contains(channel.id) { selected.remove(channel.id) } else { selected.insert(channel.id) }
+ } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: HcFormat.channelName(channel))
+ if let warning = warning(channel) {
+ Text(verbatim: warning).font(.caption).foregroundStyle(.red)
+ }
+ }
+ Spacer()
+ if selected.contains(channel.id) {
+ Image(systemName: "checkmark").foregroundStyle(Color.accentColor)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .tint(.primary)
+ .accessibilityAddTraits(selected.contains(channel.id) ? .isSelected : [])
+ }
+ }
+ }
+ }
+ .navigationTitle("Channels")
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ /// "Disabled" / "Not verified" joined by " · ".
+ private func warning(_ channel: HC2Channel) -> String? {
+ var parts: [String] = []
+ if channel.enabled == false { parts.append(String(localized: "Disabled")) }
+ if channel.verified != true && needsVerification(channel.type) { parts.append(String(localized: "Not verified")) }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ private func needsVerification(_ type: HC2ChannelKind?) -> Bool {
+ if let flag = types?.first(where: { $0.type == type })?.needsVerification { return flag }
+ return type == .ipv64Mail || type == .ipv64SMS
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckDetailSections.swift b/IPv64/Views/Healthcheck/HealthcheckDetailSections.swift
new file mode 100644
index 0000000..4947ccf
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckDetailSections.swift
@@ -0,0 +1,250 @@
+import SwiftUI
+import IPv64
+
+/// `LabeledContent` that disappears for blank values.
+struct HcInfoRow: View {
+ let label: LocalizedStringKey
+ let value: String?
+ var color: Color?
+
+ init(_ label: LocalizedStringKey, _ value: String?, color: Color? = nil) {
+ self.label = label
+ self.value = value?.nonBlank
+ self.color = color
+ }
+
+ var body: some View {
+ if let value {
+ LabeledContent(label) { Text(verbatim: value).foregroundStyle(color ?? .primary) }
+ }
+ }
+}
+
+struct HealthcheckStatusRows: View {
+ let detail: HC2CheckDetail
+ let state: HC2Check.State?
+
+ static func hasContent(detail: HC2CheckDetail, state: HC2Check.State?) -> Bool {
+ let texts = [HcFormat.time(state?.since), HcFormat.time(state?.lastCheckAt), state?.lastStatus?.rawValue,
+ state?.lastReason, state?.lastMessage, HcFormat.time(state?.downSince), HcFormat.time(state?.lastPushAt)]
+ return texts.contains { $0?.nonBlank != nil } || state?.lastLatencyMS != nil
+ || detail.availabilityPercent?.last24Hours != nil || detail.availabilityPercent?.last30Days != nil
+ || detail.availabilityPercent?.lastYear != nil
+ }
+
+ var body: some View {
+ HcInfoRow("Since", HcFormat.time(state?.since))
+ HcInfoRow("Last check", HcFormat.timeWithRelative(state?.lastCheckAt))
+ HcInfoRow("Last status", state?.lastStatus?.rawValue)
+ HcInfoRow("Latency", state?.lastLatencyMS.map { HcFormat.latency($0) })
+ HcInfoRow("Reason", state?.lastReason)
+ HcInfoRow("Message", state?.lastMessage)
+ HcInfoRow("Down since", HcFormat.time(state?.downSince), color: .red)
+ HcInfoRow("Last push", HcFormat.timeWithRelative(state?.lastPushAt))
+ HcInfoRow("Availability 24 h", detail.availabilityPercent?.last24Hours.map { HcFormat.percent($0) })
+ HcInfoRow("Availability 30 d", detail.availabilityPercent?.last30Days.map { HcFormat.percent($0) })
+ HcInfoRow("Availability 1 y", detail.availabilityPercent?.lastYear.map { HcFormat.percent($0) })
+ }
+}
+
+/// Title, multi-line subtitle and a state tag (events, incidents, measuring points).
+struct HcDetailRow: View {
+ let title: String
+ var subtitle: [String] = []
+ @ViewBuilder var tag: Tag
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: title)
+ if !subtitle.isEmpty {
+ Text(verbatim: subtitle.joined(separator: "\n")).font(.subheadline).foregroundStyle(.secondary)
+ }
+ }
+ Spacer(minLength: 8)
+ tag
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+struct HealthcheckSourceRows: View {
+ let sources: [HC2CheckDetail.SourceState]
+
+ var body: some View {
+ ForEach(Array(sources.enumerated()), id: \.offset) { _, source in
+ HcDetailRow(title: source.label?.nonBlank ?? source.source ?? "–", subtitle: subtitle(source)) {
+ HealthcheckStateTag(state: .from(state: source.state, paused: false))
+ }
+ }
+ }
+
+ private func subtitle(_ source: HC2CheckDetail.SourceState) -> [String] {
+ var first: [String] = []
+ if let value = source.lastLatencyMS { first.append(HcFormat.latency(value)) }
+ if let date = HcFormat.real(source.lastCheckAt) {
+ first.append(String(localized: "checked \(date.formatted(.relative(presentation: .named)))"))
+ }
+ if let n = source.consecutiveFail, n > 0 { first.append(String(localized: "\(n) failed in a row")) }
+ if let n = source.consecutiveOK, n > 0 { first.append(String(localized: "\(n) ok in a row")) }
+ return [first.isEmpty ? nil : first.joined(separator: " · "),
+ source.lastMessage?.nonBlank ?? source.lastReason?.nonBlank].compactMap { $0 }
+ }
+}
+
+/// Push endpoints: value, copy (sensitive) and share.
+struct HealthcheckPushRows: View {
+ let push: HC2Check.Push
+
+ var body: some View {
+ entry("Push URL", push.url)
+ entry("Hub URL", push.hubURL)
+ entry("Node path", push.nodePath)
+ }
+
+ @ViewBuilder private func entry(_ label: LocalizedStringKey, _ value: String?) -> some View {
+ if let value = value?.nonBlank {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(label).font(.subheadline).foregroundStyle(.secondary)
+ Text(verbatim: value).font(.callout.monospaced()).textSelection(.enabled)
+ HStack(spacing: 16) {
+ Button("Copy", systemImage: "doc.on.doc") { Clipboard.copy(value, sensitive: true) }
+ ShareLink(item: value) { Label("Share", systemImage: "square.and.arrow.up") }
+ }
+ .buttonStyle(.borderless)
+ .font(.subheadline)
+ }
+ }
+ }
+}
+
+struct HealthcheckConfigRows: View {
+ let detail: HC2CheckDetail
+ let channels: [HC2Channel]
+
+ private var executionText: String {
+ let node = (detail.nodeName ?? "").trimmingCharacters(in: .whitespaces)
+ let locations = (detail.locations ?? []).map(\.rawValue).joined(separator: ", ")
+ switch detail.execution {
+ case .local: return String(localized: "Node \(node)").trimmingCharacters(in: .whitespaces)
+ case .both: return String(localized: "Online (\(locations)) + node \(node)").trimmingCharacters(in: .whitespaces)
+ default: return locations.isEmpty ? String(localized: "Online") : String(localized: "Online (\(locations))")
+ }
+ }
+
+ private var channelsText: String {
+ let ids = detail.channels ?? []
+ if ids.isEmpty { return String(localized: "Default channels") }
+ let names = ids.compactMap { id in channels.first { $0.id == id }.map(HcFormat.channelName) }
+ return names.count == ids.count ? names.joined(separator: ", ") : String(localized: "\(ids.count) selected")
+ }
+
+ var body: some View {
+ HcInfoRow("Type", detail.type?.label)
+ HcInfoRow("Target", detail.target)
+ HcInfoRow("Interval", detail.intervalSeconds.map { HcFormat.duration(seconds: $0) })
+ HcInfoRow("Retry interval", detail.retryIntervalSeconds.map { HcFormat.duration(seconds: $0) })
+ HcInfoRow("Retries", detail.retries.map(String.init))
+ HcInfoRow("Timeout", detail.timeoutSeconds.map { HcFormat.seconds($0) })
+ HcInfoRow("Connect timeout", detail.connectTimeoutSeconds.map { HcFormat.seconds($0) })
+ HcInfoRow("Stabilize", detail.stabilize.map(String.init))
+ HcInfoRow("IP mode", detail.ipMode?.rawValue)
+ HcInfoRow("Invert result", HcFormat.yesNo(detail.invert))
+ HcInfoRow("Execution", executionText)
+ if (detail.locations?.count ?? 0) + (detail.nodes?.count ?? 0) > 1 { HcInfoRow("Policy", detail.policy?.rawValue) }
+ HcInfoRow("Notify down", HcFormat.yesNo(detail.notifyDown))
+ HcInfoRow("Notify up", HcFormat.yesNo(detail.notifyUp))
+ HcInfoRow("Notify degraded", HcFormat.yesNo(detail.notifyDegraded))
+ HcInfoRow("Critical", HcFormat.yesNo(detail.critical))
+ HcInfoRow("Reminder", detail.repeatMinutes.map(HcFormat.repeatMinutes))
+ HcInfoRow("Channels", channelsText)
+ HcInfoRow("Tags", (detail.tags ?? []).joined(separator: ", "))
+ HcInfoRow("Group", detail.group)
+ HcInfoRow("Description", detail.description)
+ HcInfoRow("Created", HcFormat.time(detail.createdAt))
+ HcInfoRow("Updated", HcFormat.time(detail.updatedAt))
+ }
+}
+
+/// Bar of the latest states, newest on the right. `states` newest first.
+struct StatusPillsBar: View {
+ let states: [Hc2StateUi]
+ let noun: String
+ @State private var width: CGFloat = 0
+
+ var body: some View {
+ // As many 10 pt pills (+3 pt gap) as fit, so wide windows show more history.
+ let fitting = width > 0 ? max(1, Int((width + 3) / 13)) : 30
+ let shown = Array(states.prefix(fitting).reversed())
+ HStack(spacing: 3) {
+ ForEach(Array(shown.enumerated()), id: \.offset) { _, state in
+ RoundedRectangle(cornerRadius: 3, style: .continuous).fill(state.color).frame(maxWidth: 10)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .frame(height: 32)
+ .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
+ .accessibilityElement()
+ .accessibilityLabel(shown.last.map { "Last \(shown.count) \(noun), latest: \($0.label.lowercased())" } ?? "No \(noun)")
+ }
+}
+
+struct HealthcheckEventRow: View {
+ let event: HC2Event
+
+ private var state: Hc2StateUi { HcFormat.eventState(kind: event.kind?.rawValue, to: event.toState) }
+
+ private var lines: [String] {
+ var lines: [String] = []
+ if event.fromState?.nonBlank != nil || event.toState?.nonBlank != nil {
+ lines.append("\(event.fromState?.nonBlank ?? "–") → \(event.toState?.nonBlank ?? "–")")
+ }
+ var meta: [String] = []
+ if let label = event.sourceLabel?.nonBlank { meta.append(label) }
+ if let seconds = event.durationSeconds { meta.append(String(localized: "after \(HcFormat.duration(seconds: seconds))")) }
+ if let flaps = event.flaps, flaps > 0 { meta.append(String(localized: "\(flaps) flaps")) }
+ if event.silent == true { meta.append(String(localized: "silent")) }
+ if !meta.isEmpty { lines.append(meta.joined(separator: " · ")) }
+ if let text = event.message?.nonBlank ?? event.reason?.nonBlank { lines.append(text) }
+ if let time = HcFormat.time(event.time) { lines.append(time) }
+ return lines
+ }
+
+ var body: some View {
+ HcDetailRow(title: HcFormat.eventTitle(kind: event.kind?.rawValue, fallback: state.label), subtitle: lines) {
+ HealthcheckStateTag(state: state)
+ }
+ }
+}
+
+struct HealthcheckIncidentRow: View {
+ let incident: HC2Incident
+
+ private var subtitle: String? {
+ var parts: [String] = []
+ if let s = incident.durationSeconds { parts.append(HcFormat.duration(seconds: s)) }
+ if let text = incident.message?.nonBlank ?? incident.reason?.nonBlank { parts.append(text) }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ var body: some View {
+ let open = incident.status == .open
+ HStack(spacing: 12) {
+ Image(systemName: open ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")
+ .foregroundStyle(open ? .red : .green)
+ .font(.title3)
+ .accessibilityLabel(open ? "Open incident" : "Resolved incident")
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: HcFormat.time(incident.startedAt) ?? "–")
+ if let subtitle {
+ Text(verbatim: subtitle).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
+ }
+ }
+ Spacer(minLength: 8)
+ if let started = HcFormat.real(incident.startedAt) {
+ Text(started.formatted(.relative(presentation: .named))).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckDetailView.swift b/IPv64/Views/Healthcheck/HealthcheckDetailView.swift
new file mode 100644
index 0000000..a017421
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckDetailView.swift
@@ -0,0 +1,364 @@
+import SwiftUI
+import IPv64
+
+/// Pushed from the list.
+struct HealthcheckRoute: Hashable {
+ let token: String
+}
+
+/// Healthcheck detail (API v2): status, actions, measuring points, configuration, statistics, incidents, events.
+struct HealthcheckDetailView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+ @Environment(\.openURL) private var openURL
+
+ let token: String
+ /// Tells the list that this check changed (pause, resume, delete).
+ let onChanged: () -> Void
+
+ @State private var detail: HC2CheckDetail?
+ @State private var pausedOverride: Bool?
+ @State private var stateOverride: HC2Check.State?
+ @State private var events: [HC2Event] = []
+ @State private var nextBefore: Int?
+ @State private var measurements: [HC2Measurement] = []
+ @State private var channels: [HC2Channel] = []
+ @State private var generation = 0
+ @State private var busy = false
+ @State private var isLoading = false
+ @State private var loadingMore = false
+ @State private var waiting: String?
+ @State private var confirmDelete = false
+ @State private var showEdit = false
+ @State private var error: ErrorText?
+ @State private var info: ErrorText?
+ // Statistics and incidents load only when opened.
+ @State private var statsRange = HC2StatsRange.last24Hours
+ @State private var statsCache: [HC2StatsRange: HC2Stats] = [:]
+ @State private var statsLoading = false
+ @State private var statsError: String?
+ @State private var eventsExpanded = false
+ @State private var statsExpanded = true
+ @State private var incidentsExpanded = false
+ @State private var incidents: [HC2Incident]?
+ @State private var incidentsLoading = false
+ @State private var incidentsError: String?
+
+ private struct StatsKey: Equatable { let range: HC2StatsRange, generation: Int }
+ private struct IncidentsKey: Equatable { let generation: Int }
+
+ private var paused: Bool { pausedOverride ?? detail?.paused ?? false }
+ private var state: HC2Check.State? { stateOverride ?? detail?.state }
+ private var runsOnNode: Bool { (detail?.execution ?? .online) != .online }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(confirmDelete || showEdit ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+
+ private var content: some View {
+ List {
+ if let detail {
+ recent
+ if HealthcheckStatusRows.hasContent(detail: detail, state: state) {
+ Section("Status") { HealthcheckStatusRows(detail: detail, state: state) }
+ }
+ actions(detail)
+ if let sources = detail.sources, !sources.isEmpty {
+ Section("Measuring points") { HealthcheckSourceRows(sources: sources) }
+ }
+ if detail.type == .push, let push = detail.push {
+ Section("Push endpoints") { HealthcheckPushRows(push: push) }
+ }
+ Section("Configuration") { HealthcheckConfigRows(detail: detail, channels: channels) }
+ if statsLoading || statsError != nil || statsCache[statsRange] != nil { statsSection }
+ incidentsSection
+ if !events.isEmpty { eventsSection }
+ }
+ }
+ .overlay {
+ if detail == nil && error == nil { ProgressView() }
+ }
+ // While loading or running an action everything is locked; the spinner sits in the toolbar.
+ .disabled(busy || isLoading)
+ .navigationTitle(detail?.name?.nonBlank ?? String(localized: "Healthcheck"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar { toolbar }
+ .refreshable { await load() }
+ .task { await load() }
+ .task(id: StatsKey(range: statsRange, generation: generation)) { await loadStats() }
+ .task(id: IncidentsKey(generation: generation)) { await loadIncidents() }
+ .sheet(isPresented: $showEdit) {
+ HealthcheckFormView(token: token) {
+ onChanged()
+ Task { await load() }
+ }
+ }
+ .alert("Delete healthcheck?", isPresented: $confirmDelete) {
+ Button("Delete", role: .destructive) { Task { await delete() } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Do you really want to delete \"\(detail?.name ?? token)\"? Its history is deleted as well.")
+ }
+ .errorAlert($error)
+ .errorAlert($info)
+ }
+
+ // MARK: Sections
+
+ private func actions(_ detail: HC2CheckDetail) -> some View {
+ Section {
+ Button {
+ Task { await togglePause() }
+ } label: {
+ Label(paused ? "Resume" : "Pause", systemImage: paused ? "play" : "pause")
+ }
+ Button {
+ Task { await runNow() }
+ } label: {
+ Label("Run now", systemImage: "arrow.clockwise")
+ }
+ if let url = HcFormat.browserURL(type: detail.type, target: detail.target) {
+ Button {
+ openURL(url)
+ } label: {
+ Label("Open in browser", systemImage: "safari")
+ }
+ }
+ } footer: {
+ if let waiting { Text(verbatim: waiting) }
+ }
+ .tint(.primary)
+ }
+
+ @ViewBuilder private var recent: some View {
+ if !measurements.isEmpty {
+ Section("Recent checks") {
+ StatusPillsBar(states: measurements.map { $0.status == .up ? .up : $0.status == .down ? .down : .pending },
+ noun: "checks")
+ }
+ } else if !events.isEmpty {
+ Section("Recent events") {
+ StatusPillsBar(states: events.map { HcFormat.eventState(kind: $0.kind?.rawValue, to: $0.toState) },
+ noun: "events")
+ }
+ }
+ }
+
+ private var statsSection: some View {
+ HcCollapsibleSection(title: "Statistics", isExpanded: $statsExpanded) {
+ Picker("Range", selection: $statsRange) {
+ Text("24 h").tag(HC2StatsRange.last24Hours)
+ Text("7 d").tag(HC2StatsRange.last7Days)
+ Text("30 d").tag(HC2StatsRange.last30Days)
+ Text("1 y").tag(HC2StatsRange.lastYear)
+ }
+ .pickerStyle(.segmented)
+ if let stats = statsCache[statsRange] {
+ HealthcheckStatsRows(stats: stats)
+ } else if let statsError {
+ Text(verbatim: statsError).foregroundStyle(.red)
+ } else {
+ ProgressView().frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ private var incidentsSection: some View {
+ HcCollapsibleSection(title: "Incidents", isExpanded: $incidentsExpanded) {
+ if let incidentsError {
+ Text(verbatim: incidentsError).foregroundStyle(.red)
+ } else if let incidents {
+ if incidents.isEmpty {
+ Text("No incidents").foregroundStyle(.secondary)
+ } else {
+ ForEach(incidents) { HealthcheckIncidentRow(incident: $0) }
+ }
+ } else {
+ ProgressView().frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ private var eventsSection: some View {
+ HcCollapsibleSection(title: "Events", isExpanded: $eventsExpanded) {
+ if events.isEmpty {
+ Text("No events").foregroundStyle(.secondary)
+ } else {
+ ForEach(events) { HealthcheckEventRow(event: $0) }
+ }
+ if nextBefore != nil {
+ Button(loadingMore ? "Loading..." : "Load more") { Task { await loadMore() } }
+ .disabled(loadingMore)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ // MARK: Toolbar
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Edit", systemImage: "pencil") { showEdit = true }
+ .disabled(detail == nil || busy || isLoading)
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ if busy || isLoading {
+ ProgressView()
+ } else {
+ Button("Delete healthcheck", systemImage: "trash", role: .destructive) { confirmDelete = true }
+ .tint(.red)
+ .disabled(detail == nil)
+ }
+ }.appVerticalPreferred()
+ }
+
+ // MARK: Loading
+
+ /// One after another (rate limit): detail, events, measurements and channels (the last two may fail silently).
+ private func load() async {
+ isLoading = true
+ defer { isLoading = false }
+ let api = session.api
+ do {
+ let loaded = try await ipv64Retrying { try await api.hc2.checks.get(token) }
+ let page = try await ipv64Retrying { try await api.hc2.checks.events(token, limit: 50) }
+ let list = (try? await ipv64Retrying { try await api.hc2.checks.measurements(token, limit: 100) }) ?? []
+ if let all = try? await ipv64Retrying({ try await api.hc2.channels.list() }) { channels = all }
+ detail = loaded
+ pausedOverride = nil
+ stateOverride = nil
+ events = page.items
+ nextBefore = page.meta?.hasMore == true ? page.meta?.nextBefore : nil
+ measurements = list
+ statsCache = [:]
+ incidents = nil
+ generation += 1
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func loadMore() async {
+ guard let before = nextBefore else { return }
+ loadingMore = true
+ defer { loadingMore = false }
+ let api = session.api
+ do {
+ let page = try await ipv64Retrying { try await api.hc2.checks.events(token, limit: 50, before: before) }
+ let known = Set(events.map(\.id))
+ events += page.items.filter { !known.contains($0.id) }
+ nextBefore = page.meta?.hasMore == true ? page.meta?.nextBefore : nil
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func loadStats() async {
+ guard detail != nil, statsCache[statsRange] == nil else { return }
+ let range = statsRange
+ let api = session.api
+ statsLoading = true
+ statsError = nil
+ defer { statsLoading = false }
+ do {
+ statsCache[range] = try await ipv64Retrying { try await api.hc2.checks.stats(token, range: range) }
+ } catch is CancellationError {
+ } catch {
+ statsError = ErrorText(error).message.nonBlank ?? String(localized: "Statistics could not be loaded")
+ }
+ }
+
+ private func loadIncidents() async {
+ guard detail != nil, incidents == nil else { return }
+ let api = session.api
+ incidentsLoading = true
+ incidentsError = nil
+ defer { incidentsLoading = false }
+ do {
+ incidents = try await ipv64Retrying { try await api.hc2.incidents.list(check: token, limit: 20) }
+ } catch is CancellationError {
+ } catch {
+ incidentsError = ErrorText(error).message.nonBlank ?? String(localized: "Incidents could not be loaded")
+ }
+ }
+
+ // MARK: Actions
+
+ private func togglePause() async {
+ busy = true
+ defer { busy = false }
+ let api = session.api
+ let wasPaused = paused
+ do {
+ let updated = try await ipv64Retrying {
+ wasPaused ? try await api.hc2.checks.resume(token) : try await api.hc2.checks.pause(token)
+ }
+ pausedOverride = updated.paused ?? !wasPaused
+ stateOverride = updated.state ?? state
+ onChanged()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ /// Online checks run at once; node checks are queued and polled every 3 s for up to 60 s.
+ private func runNow() async {
+ busy = true
+ defer { busy = false; waiting = nil }
+ let api = session.api
+ do {
+ let result = try await ipv64Retrying { try await api.hc2.checks.run(token) }
+ guard result.queued != false, let nodeId = result.nodeID, let commandID = result.commandID else {
+ let text = result.queued == false ? String(localized: "Run not queued") : String(localized: "Run queued")
+ info = ErrorText(title: String(localized: "Run now"), message: result.detail?.nonBlank ?? text)
+ return
+ }
+ waiting = String(localized: "Waiting for node \(detail?.nodeName ?? "")…")
+ var entry: HC2Command?
+ for _ in 0..<20 {
+ try await Task.sleep(for: .seconds(3))
+ let list = try await api.hc2.nodes.commands(nodeId, limit: 20)
+ entry = list.first { $0.commandID == commandID && $0.doneAt != nil }
+ if entry != nil { break }
+ }
+ guard let entry else {
+ info = ErrorText(title: String(localized: "Run now"), message: String(localized: "Node has not reported back yet"))
+ return
+ }
+ var text = entry.ok == false ? String(localized: "Run failed") : String(localized: "Run finished: OK")
+ if let output = HcFormat.commandOutput(entry.output) { text += "\n" + output }
+ info = ErrorText(title: String(localized: "Run now"), message: text)
+ onChanged()
+ waiting = nil
+ await load()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func delete() async {
+ busy = true
+ defer { busy = false }
+ let api = session.api
+ do {
+ try await ipv64Retrying { try await api.hc2.checks.delete(token) }
+ onChanged()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckFormFields.swift b/IPv64/Views/Healthcheck/HealthcheckFormFields.swift
new file mode 100644
index 0000000..14bc9ae
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckFormFields.swift
@@ -0,0 +1,173 @@
+import SwiftUI
+import IPv64
+
+/// Text input kinds of the check forms.
+enum HcFieldKind { case text, url, number, decimal, secure }
+
+/// Digits only (decimal: "," becomes ".", one dot).
+nonisolated func hcFilterNumber(_ text: String, decimal: Bool) -> String {
+ var seenDot = false
+ var out = ""
+ for ch in text.replacingOccurrences(of: ",", with: decimal ? "." : "") {
+ if ch.isASCII && ch.isNumber { out.append(ch) } else if decimal && ch == "." && !seenDot { seenDot = true; out.append(ch) }
+ }
+ return out
+}
+
+/// Label with the value right-aligned (like Settings); numbers get an optional unit suffix.
+struct HcFieldRow: View {
+ let label: LocalizedStringKey
+ @Binding var text: String
+ var kind: HcFieldKind = .text
+ var prompt = ""
+ var unit: LocalizedStringKey?
+
+ var body: some View {
+ LabeledContent(label) {
+ HStack(spacing: 4) {
+ input.multilineTextAlignment(.trailing)
+ if let unit { Text(unit).foregroundStyle(.secondary) }
+ }
+ }
+ .onChange(of: text) {
+ guard kind == .number || kind == .decimal else { return }
+ let filtered = hcFilterNumber(text, decimal: kind == .decimal)
+ if filtered != text { text = filtered }
+ }
+ }
+
+ @ViewBuilder private var input: some View {
+ switch kind {
+ case .secure: SecureField(prompt, text: $text)
+ case .number: TextField(prompt, text: $text).keyboardType(.numberPad)
+ case .decimal: TextField(prompt, text: $text).keyboardType(.decimalPad)
+ case .url: TextField(prompt, text: $text).keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled()
+ case .text: TextField(prompt, text: $text).textInputAutocapitalization(.never).autocorrectionDisabled()
+ }
+ }
+}
+
+/// Multi-line text with the label as placeholder.
+struct HcMultilineField: View {
+ let placeholder: LocalizedStringKey
+ @Binding var text: String
+
+ var body: some View {
+ TextField(placeholder, text: $text, axis: .vertical).lineLimit(2...8)
+ }
+}
+
+/// Optional whole number as a stepper; stepping below the minimum clears it (server default).
+struct HcStepperRow: View {
+ let label: LocalizedStringKey
+ @Binding var text: String
+ let range: ClosedRange
+
+ private var current: Int? { Int(text.trimmingCharacters(in: .whitespaces)) }
+
+ var body: some View {
+ Stepper {
+ LabeledContent(label) { Text(verbatim: current.map(String.init) ?? String(localized: "Default")) }
+ } onIncrement: {
+ text = String(min((current ?? range.lowerBound - 1) + 1, range.upperBound))
+ } onDecrement: {
+ guard let current else { return }
+ text = current <= range.lowerBound ? "" : String(current - 1)
+ }
+ }
+}
+
+/// Duration as presets (the loaded value is added when it is not a preset).
+struct HcDurationPicker: View {
+ let label: LocalizedStringKey
+ @Binding var value: String
+ @Binding var unit: Int
+ let presets: [Int]
+ var allowsDefault = true
+
+ private var seconds: Int? {
+ durationToSeconds(value, unitIdx: unit).flatMap { $0 > 0 ? $0 : nil }
+ }
+
+ private var options: [Int?] {
+ var list: [Int?] = presets.map { Optional($0) }
+ if let seconds, !presets.contains(seconds) { list.append(seconds); list.sort { ($0 ?? 0) < ($1 ?? 0) } }
+ return allowsDefault || seconds == nil ? [nil] + list : list
+ }
+
+ var body: some View {
+ Picker(label, selection: Binding(get: { seconds }, set: { new in
+ (value, unit) = secondsToDuration(new)
+ })) {
+ ForEach(options, id: \.self) { option in
+ Text(verbatim: option.map { HcFormat.duration(seconds: $0) } ?? String(localized: "Default")).tag(option)
+ }
+ }
+ }
+}
+
+/// Repeat reminder picker.
+struct HcRepeatPicker: View {
+ @Binding var minutes: Int?
+ /// Edit: "Default" is removed when the loaded check has a value.
+ var allowsDefault = true
+
+ private var options: [Int?] {
+ var list = healthcheckRepeatOptions.filter { allowsDefault || $0 != nil }
+ if let minutes, !list.contains(minutes) { list.append(minutes) }
+ return list
+ }
+
+ var body: some View {
+ Picker("Repeat reminder", selection: $minutes) {
+ ForEach(options, id: \.self) { option in
+ Text(verbatim: option.map(HcFormat.repeatMinutes) ?? String(localized: "Default")).tag(option)
+ }
+ }
+ }
+}
+
+/// Section footer: explanation in secondary, validation message in red.
+struct HcFooter: View {
+ var hint: LocalizedStringKey?
+ var error: String?
+
+ var body: some View {
+ if hint != nil || error != nil {
+ VStack(alignment: .leading, spacing: 4) {
+ if let hint { Text(hint) }
+ if let error { Text(verbatim: error).foregroundStyle(.red) }
+ }
+ }
+ }
+}
+
+/// Section whose header toggles it (header button with a rotating chevron, like Events in the detail).
+struct HcCollapsibleSection: View {
+ let title: LocalizedStringKey
+ @Binding var isExpanded: Bool
+ var hint: LocalizedStringKey?
+ var error: String?
+ @ViewBuilder var content: Content
+
+ var body: some View {
+ Section {
+ if isExpanded { content }
+ } header: {
+ Button {
+ withAnimation { isExpanded.toggle() }
+ } label: {
+ HStack {
+ Text(title)
+ Spacer()
+ Image(systemName: "chevron.right").rotationEffect(.degrees(isExpanded ? 90 : 0))
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityValue(isExpanded ? "Expanded" : "Collapsed")
+ } footer: {
+ HcFooter(hint: isExpanded ? hint : nil, error: error)
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckFormGroups.swift b/IPv64/Views/Healthcheck/HealthcheckFormGroups.swift
new file mode 100644
index 0000000..776975a
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckFormGroups.swift
@@ -0,0 +1,95 @@
+import SwiftUI
+import IPv64
+
+/// Collapsible "Advanced": type options, schedule, tolerance.
+struct HealthcheckAdvancedSection: View {
+ @Binding var f: HealthcheckFormState
+ @Binding var expanded: Bool
+ let editing: Bool
+ let detail: HC2CheckDetail?
+ var error: String?
+
+ private var ipModes: [HC2IPMode?] {
+ [nil, .auto, .ipv4, .ipv6, .both].filter { !(editing && detail?.ipMode != nil && $0 == nil) }
+ }
+
+ private var policies: [HC2Policy?] {
+ [nil, .all, .any, .majority].filter { !(editing && detail?.policy != nil && $0 == nil) }
+ }
+
+ private func policyLabel(_ policy: HC2Policy?) -> String {
+ let unit = f.execution == .both ? String(localized: "sources") : String(localized: "locations")
+ switch policy {
+ case .all: return String(localized: "Down if all \(unit) fail")
+ case .any: return String(localized: "Down if any of the \(unit) fails")
+ case .majority: return String(localized: "Down if most \(unit) fail")
+ default: return String(localized: "Default")
+ }
+ }
+
+ var body: some View {
+ HcCollapsibleSection(
+ title: "Advanced", isExpanded: $expanded,
+ hint: editing ? "Clearing a field keeps the current value; it cannot be reset to the default here."
+ : "Empty fields use the server default.",
+ error: error
+ ) {
+ if f.type.hasAdvancedParams {
+ HealthcheckAdvancedParams(s: $f.ps, type: f.type, ini: f.iniPs, editing: editing, online: f.online)
+ }
+ HcDurationPicker(label: "Interval", value: $f.intervalValue, unit: $f.intervalUnit,
+ presets: [20, 30, 60, 120, 300, 600, 900, 1800, 3600],
+ allowsDefault: !(editing && detail?.intervalSeconds != nil))
+ HcDurationPicker(label: "Retry interval", value: $f.retryValue, unit: $f.retryUnit,
+ presets: [5, 10, 30, 60, 120, 300],
+ allowsDefault: !(editing && detail?.retryIntervalSeconds != nil))
+ HcStepperRow(label: "Retries", text: $f.retries, range: 0...10)
+ HcFieldRow(label: "Timeout", text: $f.timeout, kind: .decimal, prompt: "Default", unit: "s")
+ HcFieldRow(label: "Connect timeout", text: $f.connectTimeout, kind: .decimal, prompt: "Default", unit: "s")
+ HcStepperRow(label: "Stabilize", text: $f.stabilize, range: 1...20)
+ Toggle("Invert result", isOn: $f.invert)
+ Picker("IP mode", selection: $f.ipMode) {
+ ForEach(ipModes, id: \.self) { Text(verbatim: $0?.rawValue ?? String(localized: "Default")).tag($0) }
+ }
+ if f.type != .push && f.policyApplies {
+ Picker("Overall rule", selection: $f.policy) {
+ ForEach(policies, id: \.self) { Text(verbatim: policyLabel($0)).tag($0) }
+ }
+ }
+ }
+ }
+}
+
+/// Collapsible "Notifications & organisation".
+struct HealthcheckNotificationsSection: View {
+ @Binding var f: HealthcheckFormState
+ @Binding var expanded: Bool
+ let editing: Bool
+ let detail: HC2CheckDetail?
+ let channels: [HC2Channel]
+ let channelTypes: [HC2ChannelType]?
+ var error: String?
+
+ var body: some View {
+ HcCollapsibleSection(
+ title: "Notifications & organisation", isExpanded: $expanded,
+ hint: "Degraded also notifies on partial failure. Critical ignores quiet hours.",
+ error: error
+ ) {
+ Toggle("Notify when down", isOn: $f.notifyDown)
+ Toggle("Notify when back up", isOn: $f.notifyUp)
+ Toggle("Notify when degraded", isOn: $f.notifyDegraded)
+ Toggle("Critical", isOn: $f.critical)
+ HcRepeatPicker(minutes: $f.repeatMinutes, allowsDefault: !(editing && detail?.repeatMinutes != nil))
+ HealthcheckChannelPicker(useDefault: $f.useDefaultChannels, selected: $f.channels,
+ channels: channels, types: channelTypes)
+ TextField("Tags, comma-separated", text: $f.tags)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ TextField("Group", text: $f.group)
+ HcMultilineField(placeholder: "Description", text: $f.description)
+ if !editing {
+ Toggle("Create paused", isOn: $f.createPaused)
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckFormSections.swift b/IPv64/Views/Healthcheck/HealthcheckFormSections.swift
new file mode 100644
index 0000000..749b03a
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckFormSections.swift
@@ -0,0 +1,170 @@
+import SwiftUI
+import IPv64
+
+/// First section: type, name and target.
+struct HealthcheckCheckSection: View {
+ @Binding var f: HealthcheckFormState
+ let editing: Bool
+ var error: String?
+
+ var body: some View {
+ Section {
+ if editing {
+ // A Label as LabeledContent value blows the row up in a Form; icon and text side by side instead.
+ LabeledContent("Type") {
+ HStack(spacing: 6) {
+ Image(systemName: f.type.symbol).foregroundStyle(.tint)
+ Text(f.type.label)
+ }
+ }
+ } else {
+ Picker("Type", selection: typeBinding) {
+ ForEach(healthcheckCreateTypes, id: \.self) { Label($0.label, systemImage: $0.symbol).tag($0) }
+ }
+ .pickerStyle(.navigationLink)
+ }
+ TextField("Name", text: $f.name)
+ if f.type != .push {
+ TextField(f.type.targetHint, text: $f.target)
+ .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled()
+ }
+ } footer: {
+ HcFooter(hint: f.type == .push && !editing ? "A push URL is created with the check." : nil, error: error)
+ }
+ }
+
+ /// Selecting a new type resets the parameters.
+ private var typeBinding: Binding {
+ Binding(get: { f.type }, set: { type in
+ guard type != f.type else { return }
+ f.type = type
+ f.ps = ParamsState.initial(type)
+ f.iniPs = f.ps
+ })
+ }
+}
+
+/// Where the check runs: online, on a node or both; node and locations.
+struct HealthcheckExecutionSection: View {
+ @Binding var f: HealthcheckFormState
+ let editing: Bool
+ let nodes: [HC2Node]
+ let account: HC2Account?
+ let detail: HC2CheckDetail?
+ var error: String?
+
+ private var maxLocations: Int? {
+ guard let n = account?.locationsPerCheck, n > 0 else { return nil }
+ return n
+ }
+
+ private var locationSummary: String {
+ let names = f.locations.map { code in
+ account?.locations?.first { $0.code == code }?.name?.nonBlank ?? code
+ }
+ switch names.count {
+ case 0: return String(localized: "None")
+ case 1: return names[0]
+ default: return String(localized: "\(names.count) locations")
+ }
+ }
+
+ var body: some View {
+ if f.type != .push {
+ Section {
+ if !nodes.isEmpty || !f.online {
+ Picker("Where it runs", selection: execBinding) {
+ Text("Online").tag(HC2Execution.online)
+ Text("Node").tag(HC2Execution.local)
+ Text("Online + node").tag(HC2Execution.both)
+ }
+ .pickerStyle(.segmented)
+ }
+ if !f.online {
+ Picker("Node", selection: $f.nodeId) {
+ Text("Select a node").tag(String?.none)
+ ForEach(nodeOptions, id: \.id) { Text(verbatim: $0.label).tag(Optional($0.id)) }
+ }
+ .pickerStyle(.navigationLink)
+ }
+ if f.usesLocations {
+ NavigationLink {
+ HealthcheckLocationList(selected: $f.locations, locations: account?.locations ?? [],
+ limit: maxLocations)
+ } label: {
+ LabeledContent("Locations") { Text(verbatim: locationSummary) }
+ }
+ }
+ } header: {
+ Text("Execution")
+ } footer: {
+ HcFooter(hint: editing ? "Changing where the check runs or its locations runs a test measurement first." : nil,
+ error: error)
+ }
+ }
+ }
+
+ private var execBinding: Binding {
+ Binding(get: { f.execSel }, set: { value in
+ f.execSel = value
+ if value != .online && f.nodeId == nil && nodes.count == 1 { f.nodeId = nodes.first?.nodeID }
+ })
+ }
+
+ private var nodeOptions: [(id: String, label: String)] {
+ var list = nodes.map { node -> (String, String) in
+ let name = node.name?.nonBlank ?? node.nodeID
+ switch node.online {
+ case true: return (node.nodeID, "\(name) (\(String(localized: "online")))")
+ case false: return (node.nodeID, "\(name) (\(String(localized: "offline")))")
+ default: return (node.nodeID, name)
+ }
+ }
+ if let current = f.nodeId, !list.contains(where: { $0.0 == current }) {
+ list.append((current, detail?.nodeName?.nonBlank ?? current))
+ }
+ return list.map { (id: $0.0, label: $0.1) }
+ }
+}
+
+/// Pushed checkmark list of the measuring locations.
+private struct HealthcheckLocationList: View {
+ @Binding var selected: [String]
+ let locations: [HC2Account.Location]
+ let limit: Int?
+
+ var body: some View {
+ List {
+ Section {
+ ForEach(locations, id: \.code) { location in
+ if let code = location.code {
+ Button {
+ toggle(code)
+ } label: {
+ HStack {
+ Text(verbatim: location.name?.nonBlank ?? code)
+ Spacer()
+ if selected.contains(code) { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
+ }
+ .contentShape(Rectangle())
+ }
+ .tint(.primary)
+ .accessibilityAddTraits(selected.contains(code) ? .isSelected : [])
+ }
+ }
+ } footer: {
+ if let limit { Text("Locations (up to \(limit))") }
+ }
+ }
+ .navigationTitle("Locations")
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private func toggle(_ code: String) {
+ if selected.contains(code) {
+ selected.removeAll { $0 == code }
+ } else if limit.map({ selected.count < $0 }) ?? true {
+ selected.append(code)
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckFormView.swift b/IPv64/Views/Healthcheck/HealthcheckFormView.swift
new file mode 100644
index 0000000..bbc0e8f
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckFormView.swift
@@ -0,0 +1,234 @@
+import SwiftUI
+import IPv64
+
+/// New / edit healthcheck, shown as a sheet: essentials on top, collapsible "Advanced" and "Notifications & organisation".
+struct HealthcheckFormView: View {
+ /// `nil` = new healthcheck.
+ let token: String?
+ /// Called after the check was created or changed.
+ let onSaved: () -> Void
+
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var f = HealthcheckFormState()
+ @State private var initial = HealthcheckFormState()
+ @State private var account: HC2Account?
+ @State private var channels: [HC2Channel] = []
+ @State private var channelTypes: [HC2ChannelType]?
+ @State private var nodes: [HC2Node] = []
+ @State private var detail: HC2CheckDetail?
+ @State private var loading = true
+ @State private var isSaving = false
+ @State private var error: ErrorText?
+ @State private var dismissAfterError = false
+ @State private var advancedOpen = false
+ @State private var notificationsOpen = false
+ @State private var pushUrl: PushUrlItem?
+
+ private var editing: Bool { token != nil }
+ private var maxLocations: Int? { account?.locationsPerCheck.flatMap { $0 > 0 ? $0 : nil } }
+ private var issue: (message: String, section: HealthcheckFormState.FormSection)? {
+ f.validate(maxLocations: maxLocations)
+ }
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ if loading {
+ ProgressView()
+ } else {
+ form
+ }
+ }
+ .navigationTitle(editing ? "Edit Healthcheck" : "New Healthcheck")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel", systemImage: "xmark") { dismiss() }.disabled(isSaving)
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if isSaving {
+ ProgressView()
+ } else {
+ Button(editing ? "Save" : "Create", systemImage: "checkmark") { Task { await save() } }
+ .disabled(loading || issue != nil)
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ .interactiveDismissDisabled(isSaving)
+ .task { await load() }
+ .errorAlert($error)
+ .onChange(of: error == nil) { _, isNil in
+ if isNil && dismissAfterError { dismissAfterError = false; dismiss() }
+ }
+ .sheet(item: $pushUrl) { item in
+ PushUrlSheet(url: item.url) { dismiss() }
+ }
+ }
+
+ private var form: some View {
+ Form {
+ HealthcheckCheckSection(f: $f, editing: editing, error: error(for: .main))
+ HealthcheckEssentialSection(s: $f.ps, type: f.type, error: error(for: .params))
+ HealthcheckExecutionSection(f: $f, editing: editing, nodes: nodes, account: account, detail: detail,
+ error: error(for: .execution))
+ HealthcheckAdvancedSection(f: $f, expanded: $advancedOpen, editing: editing, detail: detail,
+ error: error(for: .advanced))
+ HealthcheckNotificationsSection(f: $f, expanded: $notificationsOpen, editing: editing, detail: detail,
+ channels: channels, channelTypes: channelTypes, error: error(for: .notifications))
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .disabled(isSaving)
+ // A problem in a collapsed section opens it as soon as it appears after editing.
+ .onChange(of: shownIssueSection) { _, section in
+ if section == .advanced { advancedOpen = true }
+ if section == .notifications { notificationsOpen = true }
+ }
+ }
+
+ /// Validation messages only show once the user changed something.
+ private var shownIssueSection: HealthcheckFormState.FormSection? { f != initial ? issue?.section : nil }
+
+ private func error(for section: HealthcheckFormState.FormSection) -> String? {
+ shownIssueSection == section ? issue?.message : nil
+ }
+
+ // MARK: Loading
+
+ private func load() async {
+ let api = session.api
+ do {
+ let acc = try await ipv64Retrying { try await api.hc2.account() }
+ let list = try await ipv64Retrying { try await api.hc2.channels.list() }
+ channelTypes = try? await ipv64Retrying { try await api.hc2.channels.types() }
+ var state = HealthcheckFormState()
+ if let token {
+ let loaded = try await ipv64Retrying { try await api.hc2.checks.get(token) }
+ detail = loaded
+ state.apply(loaded, knownChannelIds: Set(list.map(\.id)))
+ } else if let code = acc.locations?.first?.code {
+ state.locations = [code]
+ }
+ if (acc.nodes?.total ?? 1) > 0 || state.execSel != .online {
+ nodes = (try? await ipv64Retrying { try await api.hc2.nodes.list() }) ?? []
+ }
+ account = acc
+ channels = list
+ f = state
+ initial = state
+ loading = false
+ } catch is CancellationError {
+ } catch {
+ dismissAfterError = true
+ self.error = ErrorText(error)
+ }
+ }
+
+ // MARK: Saving
+
+ private func save() async {
+ guard issue == nil else { return }
+ isSaving = true
+ defer { isSaving = false }
+ let api = session.api
+ do {
+ if let old = detail, let token {
+ try await saveEdit(token: token, old: old)
+ } else {
+ let input = f.createInput()
+ let created = try await ipv64Retrying { try await api.hc2.checks.create(input) }
+ onSaved()
+ if f.type == .push, let url = created.push?.url?.nonBlank ?? created.push?.hubURL?.nonBlank {
+ pushUrl = PushUrlItem(url: url)
+ } else {
+ dismiss()
+ }
+ }
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func saveEdit(token: String, old: HC2CheckDetail) async throws {
+ let api = session.api
+ let moveNeeded = f.moveNeeded(old: old)
+ let (input, changed) = f.updateInput(old: old, moveNeeded: moveNeeded)
+ var current = old
+ if changed {
+ current = try await ipv64Retrying { try await api.hc2.checks.update(token, input) }
+ detail = current
+ f.iniPs = f.ps
+ f.iniPs.basicPassword = ""
+ f.ps.basicPassword = ""
+ onSaved()
+ }
+ guard moveNeeded else {
+ dismiss()
+ return
+ }
+ let fields = executionFields(f.execution, nodeId: f.nodeId, locations: f.locations)
+ switch try await runHealthcheckMove(api: api, token: token, fields: fields) {
+ case .applied:
+ if f.policyApplies && f.policy != current.policy, let policy = f.policy {
+ var policyOnly = HC2CheckInput(name: f.name.hcTrimmed, type: current.type ?? f.type)
+ policyOnly.policy = policy
+ _ = try await ipv64Retrying { try await api.hc2.checks.update(token, policyOnly) }
+ }
+ onSaved()
+ dismiss()
+ case .failed(let message):
+ error = ErrorText(
+ title: String(localized: "Execution not changed"),
+ message: String(localized: "The test run failed, so the check keeps its previous settings. Other changes were saved.") + "\n\n" + message)
+ case .timedOut:
+ dismissAfterError = true
+ error = ErrorText(
+ title: String(localized: "Change pending"),
+ message: String(localized: "The test run did not finish within 60 seconds. Check the healthcheck details later to see whether the change was applied."))
+ }
+ }
+}
+
+struct PushUrlItem: Identifiable {
+ let id = UUID()
+ let url: String
+}
+
+/// Shown after creating a push check. Never swipe-dismissable; closes only via its button.
+struct PushUrlSheet: View {
+ let url: String
+ let onDone: () -> Void
+ @Environment(\.dismiss) private var dismiss
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ Section {
+ Text(verbatim: url).font(.callout.monospaced()).textSelection(.enabled)
+ Button("Copy", systemImage: "doc.on.doc") { Clipboard.copy(url, sensitive: true) }
+ ShareLink(item: url) { Label("Share", systemImage: "square.and.arrow.up") }
+ } footer: {
+ Text("Call this URL from your job or service to report that it is alive.")
+ }
+ }
+ .navigationTitle("Push URL")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Done", systemImage: "checkmark") {
+ dismiss()
+ onDone()
+ }
+ }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.medium])
+ .interactiveDismissDisabled()
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckItemView.swift b/IPv64/Views/Healthcheck/HealthcheckItemView.swift
new file mode 100644
index 0000000..54eb3e2
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckItemView.swift
@@ -0,0 +1,106 @@
+import SwiftUI
+import IPv64
+
+/// Healthcheck row (Android layout): name, type · target, last check, status tag.
+struct HealthcheckItemView: View {
+ let name: String?
+ let typeLine: String
+ let metaLine: String?
+ let tagText: String
+ let tagColor: Color
+ var isBusy = false
+
+ /// Account check.
+ init(check: HC2Check, isBusy: Bool = false) {
+ var meta: [String] = []
+ if let last = check.state?.lastCheckAt {
+ meta.append(String(localized: "Checked \(last.formatted(.relative(presentation: .named)))"))
+ }
+ if let latency = check.state?.lastLatencyMS { meta.append("\(Int(latency.rounded())) ms") }
+ if let node = check.nodeName?.nonBlank, (check.execution ?? .online) != .online { meta.append(node) }
+ self.init(name: check.name, type: check.type?.label, target: check.target, meta: meta,
+ state: Hc2StateUi.from(check), isBusy: isBusy)
+ }
+
+ /// Check of a connected node.
+ init(nodeCheck check: Node64.Check, isBusy: Bool = false) {
+ var meta: [String] = []
+ if let last = HcFormat.real(nodeDate(check.state?.lastCheckAt)) {
+ meta.append(String(localized: "Checked \(last.formatted(.relative(presentation: .named)))"))
+ }
+ if let latency = check.state?.lastLatencyMS { meta.append("\(Int(latency.rounded())) ms") }
+ self.init(name: check.name, type: check.type?.label, target: check.target, meta: meta,
+ state: check.uiState, isBusy: isBusy)
+ }
+
+ /// Monitor64 host of a connected node: "kind · address", then the host's text line.
+ init(monitor64Host host: Node64.Monitor64OverviewHost) {
+ let display = host.display
+ name = host.name
+ typeLine = [host.kind?.nonBlank, host.address?.nonBlank].compactMap { $0 }.joined(separator: " · ")
+ metaLine = host.text?.nonBlank?.m64Text
+ tagText = display.label
+ tagColor = display.color
+ }
+
+ private init(name: String?, type: String?, target: String?, meta: [String], state: Hc2StateUi, isBusy: Bool) {
+ self.name = name
+ let type = type ?? "Unknown"
+ typeLine = target?.nonBlank.map { "\(type) · \($0)" } ?? type
+ metaLine = meta.isEmpty ? nil : meta.joined(separator: " · ")
+ tagText = state.label
+ tagColor = state.color
+ self.isBusy = isBusy
+ }
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name?.nonBlank ?? String(localized: "(unnamed)"))
+ .font(.headline)
+ .lineLimit(1)
+ if !typeLine.isEmpty {
+ Text(typeLine)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ if let metaLine {
+ Text(metaLine)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if isBusy {
+ ProgressView()
+ } else {
+ HealthcheckTag(text: LocalizedStringKey(tagText), color: tagColor)
+ }
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Status capsule shared by the list row and the detail header.
+struct HealthcheckStateTag: View {
+ let state: Hc2StateUi
+
+ var body: some View { HealthcheckTag(text: LocalizedStringKey(state.label), color: state.color) }
+}
+
+struct HealthcheckTag: View {
+ let text: LocalizedStringKey
+ let color: Color
+
+ var body: some View {
+ Text(text)
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(color)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(color.opacity(0.15), in: Capsule())
+ .fixedSize()
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckParamsEditors.swift b/IPv64/Views/Healthcheck/HealthcheckParamsEditors.swift
new file mode 100644
index 0000000..4240adf
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckParamsEditors.swift
@@ -0,0 +1,72 @@
+import SwiftUI
+import IPv64
+
+/// Header rows (name and value in one row), swipe to delete, masked values unless shown.
+struct HeadersEditor: View {
+ @Binding var s: ParamsState
+ let ini: ParamsState
+ let editing: Bool
+ @State private var showValues = false
+
+ var body: some View {
+ ForEach($s.headers) { $row in
+ HStack {
+ TextField("Name", text: $row.key).textInputAutocapitalization(.never).autocorrectionDisabled()
+ if showValues {
+ TextField("Value", text: $row.value).textInputAutocapitalization(.never).autocorrectionDisabled()
+ .multilineTextAlignment(.trailing)
+ } else {
+ SecureField("Value", text: $row.value).multilineTextAlignment(.trailing)
+ }
+ }
+ .swipeActions {
+ Button("Remove header", systemImage: "trash", role: .destructive) {
+ s.headers.removeAll { $0.id == row.id }
+ }
+ .tint(.red)
+ .labelStyle(.iconOnly)
+ }
+ }
+ Button("Add header", systemImage: "plus") { s.headers.append(HeaderRow()) }
+ if !s.headers.isEmpty {
+ Toggle("Show header values", isOn: $showValues)
+ }
+ if editing && s.headersNeedReentry(ini) {
+ Text("Masked header values can't be sent back; re-enter them when you change headers")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ }
+}
+
+/// JSON rules (path, operator, value), swipe to delete.
+struct JsonRulesEditor: View {
+ @Binding var s: ParamsState
+
+ var body: some View {
+ ForEach($s.jsonRules) { $rule in
+ VStack(alignment: .leading) {
+ TextField("Path", text: $rule.path, prompt: Text(verbatim: "data.items[0].status"))
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ Picker("Operator", selection: $rule.op) {
+ ForEach(jsonRuleOperators, id: \.self) { Text(verbatim: $0.rawValue).tag($0) }
+ }
+ if rule.op.needsValue {
+ TextField("Value", text: $rule.value).textInputAutocapitalization(.never).autocorrectionDisabled()
+ }
+ }
+ .swipeActions {
+ Button("Remove rule", systemImage: "trash", role: .destructive) {
+ s.jsonRules.removeAll { $0.id == rule.id }
+ }
+ .tint(.red)
+ .labelStyle(.iconOnly)
+ }
+ }
+ if s.jsonRules.count < 10 {
+ Button("Add rule", systemImage: "plus") { s.jsonRules.append(JsonRuleRow()) }
+ }
+ if s.jsonRules.count > 1 {
+ Toggle("Any rule is enough", isOn: $s.jsonAny)
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckParamsFields.swift b/IPv64/Views/Healthcheck/HealthcheckParamsFields.swift
new file mode 100644
index 0000000..1b9c1e3
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckParamsFields.swift
@@ -0,0 +1,154 @@
+import SwiftUI
+import IPv64
+
+/// Core parameters of a check type, in their own section (none for http, icmp, cert, whois).
+struct HealthcheckEssentialSection: View {
+ @Binding var s: ParamsState
+ let type: HC2CheckType
+ var error: String?
+
+ private var header: LocalizedStringKey? {
+ switch type {
+ case .keyword: "Keyword"
+ case .json: "JSON rules"
+ case .dns: "DNS"
+ case .tcp, .port: "Port"
+ case .push: "Schedule"
+ default: nil
+ }
+ }
+
+ private var hint: LocalizedStringKey? {
+ switch type {
+ case .tcp, .port: "Or use host:port as target"
+ case .push: "Expected interval is the time between two pushes; the grace period is extra time before the check goes down."
+ case .json: s.jsonRules.count > 1 ? "Otherwise all rules must match" : nil
+ default: nil
+ }
+ }
+
+ var body: some View {
+ if type.hasEssentialParams, let header {
+ Section {
+ switch type {
+ case .keyword:
+ TextField("Keyword", text: $s.keyword).textInputAutocapitalization(.never).autocorrectionDisabled()
+ case .json:
+ JsonRulesEditor(s: $s)
+ case .dns:
+ Picker("Record type", selection: $s.recordType) {
+ ForEach(dnsRecordTypes, id: \.self) { Text(verbatim: $0.rawValue).tag($0) }
+ }
+ case .tcp:
+ HcFieldRow(label: "Port", text: $s.port, kind: .number, prompt: "443")
+ case .port:
+ HcFieldRow(label: "Port", text: $s.port, kind: .number, prompt: "443")
+ Picker("Expected state", selection: $s.expect) {
+ Text("Open").tag("open")
+ Text("Closed").tag("closed")
+ }
+ .pickerStyle(.segmented)
+ case .push:
+ HcDurationPicker(label: "Expected interval", value: $s.periodValue, unit: $s.periodUnit,
+ presets: [60, 300, 900, 1800, 3600, 21_600, 86_400])
+ HcDurationPicker(label: "Grace period", value: $s.graceValue, unit: $s.graceUnit,
+ presets: [30, 60, 300, 900, 3600])
+ default:
+ EmptyView()
+ }
+ } header: {
+ Text(header)
+ } footer: {
+ HcFooter(hint: hint, error: error)
+ }
+ }
+ }
+}
+
+/// Fine options of a check type (rows inside the "Advanced" section).
+struct HealthcheckAdvancedParams: View {
+ @Binding var s: ParamsState
+ let type: HC2CheckType
+ let ini: ParamsState
+ let editing: Bool
+ /// `false` = runs on a node (DNS `public_ip` allowed).
+ let online: Bool
+
+ var body: some View {
+ switch type {
+ case .http, .keyword, .json: http
+ case .dns: dns
+ case .icmp:
+ HcStepperRow(label: "Packets", text: $s.count, range: 1...20)
+ HcFieldRow(label: "Max packet loss", text: $s.maxLossPercent, kind: .number, prompt: "Default", unit: "%")
+ HcFieldRow(label: "Max latency (0 = off)", text: $s.maxLatencyMs, kind: .number, prompt: "Default", unit: "ms")
+ case .tcp:
+ HcFieldRow(label: "Data to send", text: $s.send, prompt: "Optional")
+ HcFieldRow(label: "Expected response start", text: $s.expect, prompt: "Optional")
+ Toggle("Use TLS", isOn: $s.tls)
+ case .cert:
+ HcFieldRow(label: "Port", text: $s.port, kind: .number, prompt: "443")
+ HcFieldRow(label: "Minimum remaining days", text: $s.minDays, kind: .number, prompt: "Default", unit: "days")
+ HcFieldRow(label: "Server name (SNI)", text: $s.serverName, prompt: "Optional")
+ Toggle("Skip chain validation", isOn: $s.skipChain)
+ Toggle("Skip hostname validation", isOn: $s.skipHostname)
+ default:
+ EmptyView()
+ }
+ }
+
+ // MARK: HTTP / keyword / JSON
+
+ private var methods: [String] { httpMethods.contains(s.method) ? httpMethods : httpMethods + [s.method] }
+
+ @ViewBuilder private var http: some View {
+ Picker("Method", selection: $s.method) {
+ ForEach(methods, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ HcFieldRow(label: "Accepted status codes", text: $s.acceptStatus, prompt: "200-299,301")
+ if type == .keyword {
+ Toggle("Keyword must be absent", isOn: $s.keywordAbsent)
+ }
+ Toggle("Follow redirects", isOn: $s.followRedirects)
+ if s.followRedirects {
+ HcFieldRow(label: "Max redirects", text: $s.maxRedirects, kind: .number, prompt: "Default")
+ }
+ HcFieldRow(label: "Basic auth user", text: $s.basicUser, prompt: "Optional")
+ HcFieldRow(label: "Basic auth password", text: $s.basicPassword, kind: .secure,
+ prompt: editing && ini.basicUser.nonBlank != nil ? "Unchanged" : "Optional")
+ HeadersEditor(s: $s, ini: ini, editing: editing)
+ HcMultilineField(placeholder: "Request body", text: $s.body)
+ Toggle("Ignore certificate errors", isOn: $s.insecureTls)
+ HcFieldRow(label: "Fail if certificate expires within", text: $s.certMinDays, kind: .number,
+ prompt: "Off", unit: "days")
+ }
+
+ // MARK: DNS
+
+ private var expectOptions: [String] {
+ var list = ["any", "contains", "equals", "regex", "nxdomain"]
+ if !online || s.expect == "public_ip" { list.append("public_ip") }
+ return list
+ }
+
+ @ViewBuilder private var dns: some View {
+ Picker("Resolver", selection: $s.resolver) {
+ Text("System").tag(HC2DNSResolver.system)
+ Text("Server").tag(HC2DNSResolver.server)
+ Text("Authoritative").tag(HC2DNSResolver.authoritative)
+ }
+ if s.resolver == .server {
+ HcFieldRow(label: "DNS server", text: $s.server, kind: .url, prompt: "1.1.1.1")
+ }
+ Picker("Expected answer", selection: $s.expect) {
+ ForEach(expectOptions, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ if s.expect == "contains" || s.expect == "equals" {
+ HcMultilineField(placeholder: "Expected values, one per line", text: $s.values)
+ } else if s.expect == "regex" {
+ HcMultilineField(placeholder: "Pattern", text: $s.values)
+ }
+ Toggle("Require DNSSEC", isOn: $s.dnssec)
+ HcFieldRow(label: "Minimum TTL (0 = any)", text: $s.minTtl, kind: .number, prompt: "Default", unit: "s")
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckStatsView.swift b/IPv64/Views/Healthcheck/HealthcheckStatsView.swift
new file mode 100644
index 0000000..668918b
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckStatsView.swift
@@ -0,0 +1,162 @@
+import SwiftUI
+import Charts
+import IPv64
+
+/// One latency line (a measuring point).
+nonisolated struct StatsLine: Identifiable, Hashable, Sendable {
+ let name: String
+ let points: [Point]
+ var id: String { name }
+
+ struct Point: Hashable, Sendable {
+ let time: Date
+ let value: Double
+ }
+
+ /// Series grouped by source; colour order is the sorted unique source names.
+ static func lines(_ stats: HC2Stats) -> [StatsLine] {
+ var labels: [String: String] = [:]
+ for source in stats.sources ?? [] {
+ if let key = source.source { labels[key] = source.label?.nonBlank ?? key }
+ }
+ let valid = (stats.series ?? []).compactMap { point -> (String, Point)? in
+ guard let time = point.time, let value = point.latencyAvgMS else { return nil }
+ return (point.source ?? "", Point(time: time, value: value))
+ }
+ return Set(labels.keys).union(valid.map(\.0)).sorted().compactMap { key in
+ let points = valid.filter { $0.0 == key }.map(\.1).sorted { $0.time < $1.time }
+ return points.isEmpty ? nil : StatsLine(name: labels[key] ?? key.nonBlank ?? "–", points: points)
+ }
+ }
+}
+
+func bucketTime(_ date: Date, dayBucket: Bool) -> String {
+ let gregorian = Calendar(identifier: .gregorian)
+ if dayBucket {
+ return date.formatted(Date.VerbatimFormatStyle(
+ format: "\(day: .twoDigits).\(month: .twoDigits).\(year: .padded(4))",
+ timeZone: .gmt, calendar: gregorian))
+ }
+ return date.formatted(Date.VerbatimFormatStyle(
+ format: "\(day: .twoDigits).\(month: .twoDigits).\(year: .padded(4)) \(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits)",
+ timeZone: .current, calendar: gregorian))
+}
+
+/// Latency line chart with touch readout (Swift Charts).
+struct LatencyChart: View {
+ let lines: [StatsLine]
+ let dayBucket: Bool
+ @State private var rawSelection: Date?
+
+ private static let palette: [Color] = [.blue, .orange, .green, .purple, .teal, .red, .pink, .indigo]
+ private var times: [Date] { Array(Set(lines.flatMap { $0.points.map(\.time) })).sorted() }
+ private var maxValue: Double { lines.flatMap { $0.points.map(\.value) }.max() ?? 0 }
+ private var multi: Bool { lines.count >= 2 }
+
+ private var selected: Date? {
+ guard let raw = rawSelection else { return nil }
+ return times.min { abs($0.timeIntervalSince(raw)) < abs($1.timeIntervalSince(raw)) }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Average latency (max \(HcFormat.latency(maxValue)))").font(.caption).foregroundStyle(.secondary)
+ readout
+ Chart {
+ ForEach(lines) { line in
+ ForEach(Array(line.points.enumerated()), id: \.offset) { _, p in
+ LineMark(x: .value("Time", p.time), y: .value("Latency", p.value))
+ .foregroundStyle(by: .value("Source", line.name))
+ if line.points.count == 1 {
+ PointMark(x: .value("Time", p.time), y: .value("Latency", p.value))
+ .foregroundStyle(by: .value("Source", line.name))
+ }
+ }
+ }
+ if let selected {
+ RuleMark(x: .value("Selected", selected)).foregroundStyle(.secondary.opacity(0.5))
+ // A dot on each line at the touched time.
+ ForEach(lines) { line in
+ if let p = line.points.first(where: { $0.time == selected }) {
+ PointMark(x: .value("Time", p.time), y: .value("Latency", p.value))
+ .foregroundStyle(by: .value("Source", line.name))
+ .symbolSize(70)
+ }
+ }
+ }
+ }
+ .chartForegroundStyleScale(domain: lines.map(\.name),
+ range: lines.indices.map { Self.palette[$0 % Self.palette.count] })
+ .chartLegend(multi ? .visible : .hidden)
+ .chartYScale(domain: 0...max(maxValue, 1))
+ .chartXAxis(.hidden)
+ .chartYAxis {
+ AxisMarks(values: .automatic(desiredCount: 3)) {
+ AxisGridLine().foregroundStyle(.secondary.opacity(0.2))
+ AxisValueLabel()
+ }
+ }
+ .chartXSelection(value: $rawSelection)
+ .frame(height: 140)
+ if let first = times.first, let last = times.last {
+ HStack {
+ Text(verbatim: bucketTime(first, dayBucket: dayBucket))
+ Spacer()
+ if last != first { Text(verbatim: bucketTime(last, dayBucket: dayBucket)) }
+ }
+ .font(.caption2).foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ @ViewBuilder private var readout: some View {
+ Group {
+ if let selected {
+ let values = lines.compactMap { line in
+ line.points.first { $0.time == selected }.map {
+ multi ? "\(line.name): \(HcFormat.latency($0.value))" : HcFormat.latency($0.value)
+ }
+ }
+ Text(verbatim: bucketTime(selected, dayBucket: dayBucket) + (multi ? "\n" : " · ") + values.joined(separator: " · "))
+ } else {
+ Text("Touch the chart for values")
+ }
+ }
+ .font(.caption)
+ .lineLimit(2, reservesSpace: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+/// Statistics block: large availability, latency chart, key figures; goes inside a List section.
+struct HealthcheckStatsRows: View {
+ let stats: HC2Stats
+
+ private var sources: [HC2Stats.Source] { stats.sources ?? [] }
+
+ private func mean(_ values: [Double]) -> Double? {
+ values.isEmpty ? nil : values.reduce(0, +) / Double(values.count)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: HcFormat.percent(stats.availabilityPercent))
+ .font(.system(size: 40, weight: .bold, design: .rounded))
+ Text("Availability").font(.caption).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ let lines = StatsLine.lines(stats)
+ if lines.flatMap(\.points).count >= 2 {
+ LatencyChart(lines: lines, dayBucket: stats.bucket == .day)
+ }
+ if let total = stats.measurements {
+ LabeledContent("Checks", value: total.formatted())
+ if let availability = stats.availabilityPercent {
+ LabeledContent("Failed checks", value: max(0, Int((Double(total) * (1 - availability / 100)).rounded())).formatted())
+ }
+ }
+ LabeledContent("Average latency", value: HcFormat.latency(mean(sources.compactMap { $0.latencyMS?.avg })))
+ LabeledContent("Maximum latency", value: HcFormat.latency(sources.compactMap { $0.latencyMS?.max }.max()))
+ }
+}
diff --git a/IPv64/Views/Healthcheck/HealthcheckView.swift b/IPv64/Views/Healthcheck/HealthcheckView.swift
new file mode 100644
index 0000000..21e3104
--- /dev/null
+++ b/IPv64/Views/Healthcheck/HealthcheckView.swift
@@ -0,0 +1,402 @@
+import SwiftUI
+import IPv64
+
+/// Healthchecks 2.0 of the account (API v2): compact rows with a status tag, status filter, swipe actions.
+struct HealthcheckView: View {
+ @Environment(Session.self) private var session
+ @Environment(ConnectedNodes.self) private var nodes
+ @Binding var popToRootTab: Tabs
+ @State private var checks: [HC2Check]?
+ @State private var status = HcStatusFilter.all
+ @State private var exec = HcExecFilter.all
+ @State private var busyTokens: Set = []
+ /// Removed at once while the delete request runs; back on failure.
+ @State private var deletedTokens: Set = []
+ @State private var confirmDelete: HC2Check?
+ @State private var showNew = false
+ @State private var showTargetChoice = false
+ /// Form to present once the target sheet has closed.
+ @State private var chosenTarget: HealthcheckTarget?
+ @State private var nodeForm: NodeFormTarget?
+ @State private var monitorForm: NodeFormTarget?
+ @State private var monitorData: [String: Monitor64ListData] = [:]
+ @State private var nodeData: [String: NodeChecksData] = [:]
+ @State private var confirmNodeDelete: NodeCheckRef?
+ @State private var error: ErrorText?
+
+ private struct NodeFormTarget: Identifiable {
+ let id: String
+ }
+
+ private struct NodeCheckRef: Identifiable {
+ let nodeId: String
+ let check: Node64.Check
+ var id: String { check.token }
+ }
+
+ /// Checks owned by a connected node are shown in its section instead.
+ private var hiddenTokens: Set { Set(nodeData.values.flatMap(\.owned).map(\.token)) }
+
+ private var all: [HC2Check] {
+ (checks ?? []).filter { !deletedTokens.contains($0.token) && !hiddenTokens.contains($0.token) }
+ }
+
+ /// Reachable nodes with the healthchecks module on.
+ private var offeringNodes: [(id: String, name: String)] {
+ nodes.ids.filter { nodeData[$0].map { $0.module == .on && $0.error == nil } ?? false }
+ .map { ($0, nodes.name(of: $0)) }
+ }
+
+ /// Nodes where Monitor64 answered (module on).
+ private var monitorNodes: [(id: String, name: String)] {
+ nodes.ids.filter { monitorData[$0] != nil && monitorData[$0]?.error == nil }.map { ($0, nodes.name(of: $0)) }
+ }
+
+ private func hostRows(_ id: String) -> [Node64.Monitor64OverviewHost] {
+ (monitorData[id]?.hosts ?? [])
+ .filter { $0.uid != nil && $0.display.matches(status) }
+ .sorted { ($0.name ?? "").localizedStandardCompare($1.name ?? "") == .orderedAscending }
+ }
+
+ private func nodeRows(_ id: String) -> [Node64.Check] {
+ (nodeData[id]?.owned ?? [])
+ .filter { !deletedTokens.contains($0.token) && status.matches($0.uiState) }
+ .sorted { ($0.name ?? "").localizedStandardCompare($1.name ?? "") == .orderedAscending }
+ }
+
+ private var hasNodeRows: Bool { nodes.ids.contains { !nodeRows($0).isEmpty || !hostRows($0).isEmpty } }
+
+ private var visible: [HC2Check] {
+ all.filter { status.matches(Hc2StateUi.from($0)) && exec.matches($0.execution) }
+ .sorted { ($0.name ?? "").localizedStandardCompare($1.name ?? "") == .orderedAscending }
+ }
+
+ private var showsExecFilter: Bool { all.contains { ($0.execution ?? .online) != .online } || exec != .all }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView.setColorGradient(confirmDelete != nil || confirmNodeDelete != nil || showNew || showTargetChoice || nodeForm != nil || monitorForm != nil ? .clear : .orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ List {
+ Section {
+ ForEach(visible) { check in
+ NavigationLink(value: HealthcheckRoute(token: check.token)) {
+ HealthcheckItemView(check: check, isBusy: busyTokens.contains(check.token))
+ }
+ .swipeActions {
+ swipeButtons(paused: check.paused == true,
+ delete: { confirmDelete = check },
+ setPaused: { paused in Task { await setPaused(check, paused) } })
+ }
+ }
+ } header: {
+ if !nodes.ids.isEmpty && !visible.isEmpty { Text("Account") }
+ }
+ ForEach(nodes.ids, id: \.self) { nodeSection($0) }
+ ForEach(nodes.ids, id: \.self) { monitorSection($0) }
+ }
+ .overlay { emptyState }
+ .navigationTitle(Tabs.healthcheck.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .navigationDestination(for: HealthcheckRoute.self) { route in
+ // The list re-reads once; the detail has already updated itself.
+ HealthcheckDetailView(token: route.token) { Task { await load() } }
+ }
+ .navigationDestination(for: NodeCheckRoute.self) { route in
+ NodeCheckDetailView(nodeId: route.nodeId, token: route.token) { Task { await loadNodes() } }
+ }
+ .navigationDestination(for: Monitor64HostRoute.self) { route in
+ Monitor64HostDetailView(nodeId: route.nodeId, uid: route.uid) { Task { await loadNodes() } }
+ }
+ .toolbar { toolbar }
+ .sheet(isPresented: $showNew) { HealthcheckFormView(token: nil) { Task { await load() } } }
+ .sheet(isPresented: $showTargetChoice, onDismiss: presentChosen) {
+ HealthcheckTargetSheet(nodes: offeringNodes, monitorNodes: monitorNodes) { chosenTarget = $0 }
+ }
+ .sheet(item: $nodeForm) { target in
+ NodeCheckFormView(nodeId: target.id, token: nil) { Task { await loadNodes() } }
+ }
+ .sheet(item: $monitorForm) { target in
+ Monitor64HostFormView(nodeId: target.id, uid: nil) { Task { await loadNodes() } }
+ }
+ .refreshable { await load() }
+ .task { await load() }
+ .task(id: nodes.ids) { await loadNodes() }
+ .alert("Delete healthcheck?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),
+ presenting: confirmDelete) { check in
+ Button("Delete", role: .destructive) { Task { await delete(check) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { check in
+ Text("Do you really want to delete \"\(check.name ?? check.token)\"? Its history is deleted as well.")
+ }
+ .alert("Delete healthcheck?", isPresented: Binding(get: { confirmNodeDelete != nil }, set: { if !$0 { confirmNodeDelete = nil } }),
+ presenting: confirmNodeDelete) { ref in
+ Button("Delete", role: .destructive) { Task { await deleteNodeCheck(ref) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { ref in
+ Text("Do you really want to delete \"\(ref.check.name ?? ref.check.token)\"? Its history is deleted as well.")
+ }
+ .errorAlert($error)
+ }
+
+ /// Icon only; delete is red.
+ private func swipeButtons(paused: Bool, delete: @escaping () -> Void, setPaused: @escaping (Bool) -> Void) -> some View {
+ Group {
+ Button("Delete", systemImage: "trash", role: .destructive, action: delete)
+ .tint(.red)
+ if paused {
+ Button("Resume", systemImage: "play") { setPaused(false) }
+ .tint(.green)
+ } else {
+ Button("Pause", systemImage: "pause") { setPaused(true) }
+ .tint(.teal)
+ }
+ }
+ .labelStyle(.iconOnly)
+ }
+
+ @ViewBuilder private func nodeSection(_ id: String) -> some View {
+ let name = nodes.name(of: id)
+ if let data = nodeData[id] {
+ if let message = data.error {
+ Section {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Node not reachable")
+ Text(verbatim: message).font(.subheadline).foregroundStyle(.secondary).lineLimit(4)
+ }
+ } header: {
+ Text(verbatim: name)
+ } footer: {
+ Text("Check the connection under More → Nodes.")
+ }
+ } else if data.module == .off {
+ Section {
+ } header: {
+ Text(verbatim: name)
+ } footer: {
+ Text("Healthchecks module is off on this node")
+ }
+ } else if data.module == .on {
+ let rows = nodeRows(id)
+ if !rows.isEmpty {
+ Section {
+ ForEach(rows) { check in
+ NavigationLink(value: NodeCheckRoute(nodeId: id, token: check.token)) {
+ HealthcheckItemView(nodeCheck: check, isBusy: busyTokens.contains(check.token))
+ }
+ .swipeActions {
+ swipeButtons(paused: check.uiState == .paused,
+ delete: { confirmNodeDelete = NodeCheckRef(nodeId: id, check: check) },
+ setPaused: { paused in Task { await setNodePaused(id, check, paused) } })
+ }
+ }
+ } header: {
+ Text(verbatim: name)
+ }
+ }
+ }
+ }
+ }
+
+ @ViewBuilder private func monitorSection(_ id: String) -> some View {
+ let title = "\(nodes.name(of: id)) · Monitor64"
+ if let message = monitorData[id]?.error {
+ Section {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Monitor64 not available")
+ Text(verbatim: message).font(.subheadline).foregroundStyle(.secondary).lineLimit(4)
+ }
+ } header: {
+ Text(verbatim: title)
+ }
+ }
+ let rows = hostRows(id)
+ if !rows.isEmpty {
+ Section {
+ ForEach(rows, id: \.uid) { host in
+ NavigationLink(value: Monitor64HostRoute(nodeId: id, uid: host.uid ?? "")) {
+ HealthcheckItemView(monitor64Host: host)
+ }
+ }
+ } header: {
+ Text(verbatim: title)
+ }
+ }
+ }
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Menu {
+ Picker("Status", selection: $status) {
+ ForEach(HcStatusFilter.allCases, id: \.self) { filter in
+ Text(verbatim: "\(filter.label) (\(count(filter)))").tag(filter)
+ }
+ }
+ if showsExecFilter {
+ Picker("Runs on", selection: $exec) {
+ ForEach(HcExecFilter.allCases, id: \.self) { Text($0.label).tag($0) }
+ }
+ }
+ } label: {
+ Label("Filter healthchecks", systemImage: status == .all && exec == .all
+ ? "line.3.horizontal.decrease" : "line.3.horizontal.decrease.circle.fill")
+ }
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { addTapped() } label: { Label("New healthcheck", systemImage: "plus") }
+ }
+ }
+
+ @ViewBuilder private var emptyState: some View {
+ if checks == nil {
+ ProgressView("Loading healthchecks…")
+ } else if visible.isEmpty && !hasNodeRows {
+ ContentUnavailableView(all.isEmpty ? "No healthchecks yet" : "No matching healthchecks",
+ systemImage: "bolt.heart")
+ }
+ }
+
+ private func count(_ filter: HcStatusFilter) -> Int {
+ all.filter { filter.matches(Hc2StateUi.from($0)) }.count
+ + nodes.ids.flatMap { nodeData[$0]?.owned ?? [] }.filter { !deletedTokens.contains($0.token) && filter.matches($0.uiState) }.count
+ + monitorData.values.flatMap(\.hosts).filter { $0.uid != nil && $0.display.matches(filter) }.count
+ }
+
+ /// First choose where the check runs when a reachable node offers checks.
+ private func addTapped() {
+ if offeringNodes.isEmpty && monitorNodes.isEmpty { showNew = true } else { showTargetChoice = true }
+ }
+
+ private func presentChosen() {
+ guard let chosen = chosenTarget else { return }
+ chosenTarget = nil
+ switch chosen {
+ case .account: showNew = true
+ case .nodeCheck(let id): nodeForm = NodeFormTarget(id: id)
+ case .monitor64Host(let id): monitorForm = NodeFormTarget(id: id)
+ }
+ }
+
+ private func load() async {
+ async let nodesLoad: Void = loadNodes()
+ await loadAccount()
+ await nodesLoad
+ }
+
+ /// Per node in parallel: status, module state, check list; a failing node never hides the account checks.
+ /// Monitor64 loads independently of the checks: 404 = module off (no section), other errors show in its own group.
+ private func loadNodes() async {
+ let clients = nodes.ids.compactMap { id in nodes.client(for: id).map { (id, $0) } }
+ var result: [String: NodeChecksData] = [:]
+ var monitor: [String: Monitor64ListData] = [:]
+ await withTaskGroup(of: (String, NodeChecksData, Monitor64ListData?).self) { group in
+ for (id, client) in clients {
+ group.addTask {
+ let data = await Self.loadNode(client)
+ // An unreachable node has no Monitor64 either.
+ return (id, data, data.error == nil ? await Self.loadMonitor(client) : nil)
+ }
+ }
+ for await (id, data, hosts) in group {
+ result[id] = data
+ monitor[id] = hosts
+ }
+ }
+ if !Task.isCancelled {
+ nodeData = result
+ monitorData = monitor
+ }
+ }
+
+ private nonisolated static func loadMonitor(_ client: Node64) async -> Monitor64ListData? {
+ do {
+ return Monitor64ListData(hosts: try await client.monitor64.hosts.list())
+ } catch {
+ return isNodeNotFound(error) ? nil : Monitor64ListData(error: ErrorText.node(error).message)
+ }
+ }
+
+ private nonisolated static func loadNode(_ client: Node64) async -> NodeChecksData {
+ do {
+ let module = nodeChecksModule(try await client.node.status().modules)
+ guard module == .on else { return NodeChecksData(module: module) }
+ return NodeChecksData(module: .on, checks: try await client.hc.checks.list())
+ } catch {
+ return NodeChecksData(module: .on, error: ErrorText.node(error).titledText)
+ }
+ }
+
+ private func setNodePaused(_ nodeId: String, _ check: Node64.Check, _ paused: Bool) async {
+ guard let client = nodes.client(for: nodeId) else { return }
+ busyTokens.insert(check.token)
+ defer { busyTokens.remove(check.token) }
+ do {
+ let updated = paused ? try await client.hc.checks.pause(check.token) : try await client.hc.checks.resume(check.token)
+ if let index = nodeData[nodeId]?.checks.firstIndex(where: { $0.token == check.token }) {
+ nodeData[nodeId]?.checks[index] = updated
+ }
+ } catch {
+ self.error = .node(error)
+ }
+ }
+
+ private func deleteNodeCheck(_ ref: NodeCheckRef) async {
+ guard let client = nodes.client(for: ref.nodeId) else { return }
+ _ = withAnimation { deletedTokens.insert(ref.check.token) }
+ do {
+ try await client.hc.checks.delete(ref.check.token)
+ nodeData[ref.nodeId]?.checks.removeAll { $0.token == ref.check.token }
+ } catch {
+ _ = withAnimation { deletedTokens.remove(ref.check.token) }
+ self.error = .node(error)
+ }
+ }
+
+ private func loadAccount() async {
+ let api = session.api
+ do {
+ checks = try await ipv64Retrying { try await api.hc2.checks.list() }
+ } catch is CancellationError {
+ } catch {
+ if checks == nil { checks = [] }
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func setPaused(_ check: HC2Check, _ paused: Bool) async {
+ let api = session.api
+ busyTokens.insert(check.token)
+ defer { busyTokens.remove(check.token) }
+ do {
+ let updated = try await ipv64Retrying {
+ paused ? try await api.hc2.checks.pause(check.token) : try await api.hc2.checks.resume(check.token)
+ }
+ if let index = checks?.firstIndex(where: { $0.token == check.token }) { checks?[index] = updated }
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func delete(_ check: HC2Check) async {
+ let api = session.api
+ _ = withAnimation { deletedTokens.insert(check.token) }
+ do {
+ try await ipv64Retrying { try await api.hc2.checks.delete(check.token) }
+ checks?.removeAll { $0.token == check.token }
+ } catch {
+ _ = withAnimation { deletedTokens.remove(check.token) }
+ self.error = ErrorText(error)
+ }
+ }
+}
+
+#Preview { NavigationStack { HealthcheckView(popToRootTab: .constant(.healthcheck)) } }
diff --git a/IPv64/Views/Healthcheck/Monitor64ChartView.swift b/IPv64/Views/Healthcheck/Monitor64ChartView.swift
new file mode 100644
index 0000000..56a53a6
--- /dev/null
+++ b/IPv64/Views/Healthcheck/Monitor64ChartView.swift
@@ -0,0 +1,90 @@
+import SwiftUI
+import Charts
+import IPv64
+
+/// Line chart of a Monitor64 host chart (average values, one line per series) with touch readout of time and values.
+struct Monitor64ChartView: View {
+ let title: String
+ let unit: String
+ /// Top of the y axis.
+ let top: Double
+ let lines: [StatsLine]
+ @State private var rawSelection: Date?
+
+ private static let palette: [Color] = [.blue, .orange, .green, .purple, .teal, .red, .pink, .indigo]
+ private var times: [Date] { Array(Set(lines.flatMap { $0.points.map(\.time) })).sorted() }
+ private var multi: Bool { lines.count >= 2 }
+
+ private var selected: Date? {
+ guard let raw = rawSelection else { return nil }
+ return times.min { abs($0.timeIntervalSince(raw)) < abs($1.timeIntervalSince(raw)) }
+ }
+
+ private func value(_ v: Double) -> String {
+ (v.formatted(.number.precision(.fractionLength(0...1)))) + (unit.isEmpty ? "" : " \(unit)")
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(verbatim: "\(title) (max \(value(top)))").font(.subheadline.weight(.semibold))
+ readout
+ Chart {
+ ForEach(lines) { line in
+ ForEach(Array(line.points.enumerated()), id: \.offset) { _, p in
+ LineMark(x: .value("Time", p.time), y: .value("Value", p.value))
+ .foregroundStyle(by: .value("Series", line.name))
+ }
+ }
+ if let selected {
+ RuleMark(x: .value("Selected", selected)).foregroundStyle(.secondary.opacity(0.5))
+ // A dot on each line at the touched time.
+ ForEach(lines) { line in
+ if let p = line.points.min(by: { abs($0.time.timeIntervalSince(selected)) < abs($1.time.timeIntervalSince(selected)) }) {
+ PointMark(x: .value("Time", p.time), y: .value("Value", p.value))
+ .foregroundStyle(by: .value("Series", line.name))
+ .symbolSize(70)
+ }
+ }
+ }
+ }
+ .chartForegroundStyleScale(domain: lines.map(\.name),
+ range: lines.indices.map { Self.palette[$0 % Self.palette.count] })
+ .chartLegend(multi ? .visible : .hidden)
+ .chartYScale(domain: 0...max(top, 1))
+ .chartXAxis(.hidden)
+ .chartYAxis {
+ AxisMarks(values: .automatic(desiredCount: 3)) {
+ AxisGridLine().foregroundStyle(.secondary.opacity(0.2))
+ AxisValueLabel()
+ }
+ }
+ .chartXSelection(value: $rawSelection)
+ .frame(height: 120)
+ if let first = times.first, let last = times.last {
+ HStack {
+ Text(verbatim: bucketTime(first, dayBucket: false))
+ Spacer()
+ if last != first { Text(verbatim: bucketTime(last, dayBucket: false)) }
+ }
+ .font(.caption2).foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ @ViewBuilder private var readout: some View {
+ Group {
+ if let selected {
+ let values = lines.compactMap { line in
+ line.points.min { abs($0.time.timeIntervalSince(selected)) < abs($1.time.timeIntervalSince(selected)) }
+ .map { multi ? "\(line.name) \(value($0.value))" : value($0.value) }
+ }
+ Text(verbatim: bucketTime(selected, dayBucket: false) + (multi ? "\n" : " · ") + values.joined(separator: " · "))
+ } else {
+ Text("Touch the chart for values")
+ }
+ }
+ .font(.caption)
+ .lineLimit(2, reservesSpace: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
diff --git a/IPv64/Views/Healthcheck/Monitor64HostDetailView.swift b/IPv64/Views/Healthcheck/Monitor64HostDetailView.swift
new file mode 100644
index 0000000..aa7c9c1
--- /dev/null
+++ b/IPv64/Views/Healthcheck/Monitor64HostDetailView.swift
@@ -0,0 +1,481 @@
+import SwiftUI
+import IPv64
+
+/// Detail of a Monitor64 host of a connected node (direct access).
+struct Monitor64HostDetailView: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+
+ let nodeId: String
+ let uid: String
+ /// Tells the list that this host changed (pause, edit, delete).
+ let onChanged: () -> Void
+
+ @State private var detail: Node64.Monitor64HostDetail?
+ @State private var problems: [Node64.Monitor64Problem] = []
+ @State private var problemsError: String?
+ @State private var range = Node64.Monitor64SeriesRange.day
+ @State private var charts: [String: [StatsLine]] = [:]
+ @State private var chartsLoaded = false
+ @State private var chartsOpen = true
+ @State private var problemsOpen = true
+ @State private var serviceChartsOpen = false
+ @State private var serviceChartLines: [String: [StatsLine]] = [:]
+ @State private var serviceChartsLoaded = false
+ @State private var generation = 0
+ @State private var busy = false
+ @State private var isLoading = false
+ @State private var confirmDelete = false
+ @State private var showEdit = false
+ @State private var error: ErrorText?
+
+ private struct ChartKey: Equatable { let range: Node64.Monitor64SeriesRange, generation: Int }
+ private struct ServiceChartKey: Equatable { let range: Node64.Monitor64SeriesRange, generation: Int, open: Bool }
+
+ /// One chart per service and unit, built from the service's current metrics.
+ private struct ServiceChart: Identifiable {
+ let id: String
+ let title: String
+ let unit: String
+ let top: Double?
+ let series: [(key: String, label: String)]
+ }
+
+ private static let ranges: [(Node64.Monitor64SeriesRange, LocalizedStringKey)] = [
+ (.sixHours, "6 h"), (.day, "24 h"), (.week, "7 d"), (.month, "30 d"),
+ ]
+
+ private var client: Node64? { nodes.client(for: nodeId) }
+ private var host: Node64.Monitor64Host? { detail?.host }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(confirmDelete || showEdit ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+
+ private var content: some View {
+ List {
+ if let detail {
+ stateSection(detail)
+ infoSection(detail)
+ actions
+ if !(detail.charts ?? []).isEmpty && (!charts.isEmpty || !chartsLoaded) { chartsSection(detail) }
+ serviceChartsSection(detail)
+ problemsSection
+ newServicesSection(detail)
+ ForEach(serviceGroups(detail), id: \.category) { group in
+ Section(group.category.prefix(1).uppercased() + group.category.dropFirst()) {
+ ForEach(group.services, id: \.key) { serviceRow($0) }
+ }
+ }
+ if !(detail.accesses ?? []).isEmpty {
+ Section("Accesses") { ForEach(detail.accesses ?? [], id: \.uid) { accessRow($0) } }
+ }
+ }
+ }
+ .overlay {
+ if detail == nil && error == nil { ProgressView() }
+ }
+ .disabled(busy || isLoading)
+ .navigationTitle(host?.name?.nonBlank ?? String(localized: "Monitor64 host"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar { toolbar }
+ .refreshable { await load() }
+ .task { await load() }
+ .task(id: ChartKey(range: range, generation: generation)) { await loadCharts() }
+ .task(id: ServiceChartKey(range: range, generation: generation, open: serviceChartsOpen)) { await loadServiceCharts() }
+ .sheet(isPresented: $showEdit) {
+ Monitor64HostFormView(nodeId: nodeId, uid: uid) {
+ onChanged()
+ Task { await load() }
+ }
+ }
+ .alert("Delete host?", isPresented: $confirmDelete) {
+ Button("Delete", role: .destructive) { Task { await delete() } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("\"\(host?.name ?? uid)\" will be removed from Monitor64. Its history is kept.")
+ }
+ .errorAlert($error)
+ }
+
+ // MARK: Sections
+
+ private func stateSection(_ d: Node64.Monitor64HostDetail) -> some View {
+ let display = Monitor64Display.host(view: d.view?.rawValue, paused: host?.paused)
+ return Section {
+ HcDetailRow(title: host?.name?.nonBlank ?? String(localized: "(unnamed)"),
+ subtitle: [host?.address].compactMap { $0?.nonBlank }) {
+ HealthcheckTag(text: LocalizedStringKey(display.label), color: display.color)
+ }
+ }
+ }
+
+ @ViewBuilder private func infoSection(_ d: Node64.Monitor64HostDetail) -> some View {
+ let maintenance = d.maint.map { m in
+ [m.reason?.nonBlank, HcFormat.time(m.end).map { String(localized: "until \($0)") }]
+ .compactMap { $0 }.joined(separator: " · ").nonBlank ?? String(localized: "Running")
+ }
+ let rows: [String?] = [host?.kind?.rawValue, host?.group, (host?.tags ?? []).joined(separator: ", "),
+ HcFormat.time(d.checked), d.unreach, maintenance, host?.notes]
+ if rows.contains(where: { $0?.nonBlank != nil }) || (host?.intervalSec ?? 0) > 0 {
+ Section("Host") {
+ HcInfoRow("Kind", host?.kind?.rawValue)
+ HcInfoRow("Group", host?.group)
+ HcInfoRow("Tags", (host?.tags ?? []).joined(separator: ", "))
+ HcInfoRow("Last check", HcFormat.timeWithRelative(d.checked))
+ HcInfoRow("Unreachable", d.unreach?.m64Text, color: .red)
+ HcInfoRow("Maintenance", maintenance)
+ HcInfoRow("Interval", host?.intervalSec.flatMap { $0 > 0 ? "\($0) s" : nil })
+ HcInfoRow("Notes", host?.notes)
+ }
+ }
+ }
+
+ private var actions: some View {
+ Section {
+ let paused = host?.paused == true
+ Button {
+ Task { await setPaused(!paused) }
+ } label: {
+ Label(paused ? "Resume" : "Pause", systemImage: paused ? "play" : "pause")
+ }
+ Button {
+ Task { await act { _ = try await $0.monitor64.hosts.discover(uid) } }
+ } label: {
+ Label("Discover services", systemImage: "arrow.clockwise")
+ }
+ }
+ .tint(.primary)
+ }
+
+ private var rangePicker: some View {
+ Picker("Range", selection: $range) {
+ ForEach(Self.ranges, id: \.0) { Text($0.1).tag($0.0) }
+ }
+ .pickerStyle(.segmented)
+ }
+
+ private func chartsSection(_ d: Node64.Monitor64HostDetail) -> some View {
+ HcCollapsibleSection(title: "Charts", isExpanded: $chartsOpen) {
+ rangePicker
+ ForEach(d.charts ?? [], id: \.id) { chart in
+ if let lines = charts[chart.id?.rawValue ?? ""] {
+ Monitor64ChartView(title: (chart.id?.rawValue ?? "").uppercased(), unit: chart.unit ?? "",
+ top: (chart.max ?? lines.flatMap(\.points).map(\.value).max() ?? 1).nonZero,
+ lines: lines)
+ }
+ }
+ if chartsLoaded && charts.isEmpty {
+ Text("No data in this range.").font(.footnote).foregroundStyle(.secondary)
+ } else if !chartsLoaded {
+ ProgressView().frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ /// Further charts from the numeric metrics of the services (only series that have a history in the range).
+ @ViewBuilder private func serviceChartsSection(_ d: Node64.Monitor64HostDetail) -> some View {
+ let list = serviceCharts(d)
+ if !list.isEmpty {
+ HcCollapsibleSection(title: "Service charts", isExpanded: $serviceChartsOpen) {
+ // The range picker sits in Charts; without host charts it is shown here.
+ if (d.charts ?? []).isEmpty || (chartsLoaded && charts.isEmpty) { rangePicker }
+ if !serviceChartsLoaded {
+ ProgressView().frame(maxWidth: .infinity)
+ } else if serviceChartLines.isEmpty {
+ Text("No data in this range.").font(.footnote).foregroundStyle(.secondary)
+ } else {
+ ForEach(list) { chart in
+ if let lines = serviceChartLines[chart.id] {
+ Monitor64ChartView(title: chart.title, unit: chart.unit,
+ top: (chart.top ?? lines.flatMap(\.points).map(\.value).max() ?? 1).nonZero,
+ lines: lines)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private var problemsSection: some View {
+ HcCollapsibleSection(title: "Problems", isExpanded: $problemsOpen) {
+ if let problemsError {
+ Text(verbatim: problemsError).foregroundStyle(.red)
+ } else if problems.isEmpty {
+ Text("No open problems")
+ } else {
+ ForEach(problems, id: \.uid) { problem in
+ let acked = problem.ack != nil
+ let display = Monitor64Display.host(view: problem.state?.rawValue, paused: false)
+ HcDetailRow(
+ title: problem.name?.nonBlank?.m64Text ?? String(localized: "Host unreachable"),
+ subtitle: [HcFormat.time(problem.opened).map { String(localized: "Since \($0)") },
+ acked ? String(localized: "Acknowledged") : nil].compactMap { $0 }
+ .joined(separator: " · ").nonBlank.map { [$0] } ?? []
+ ) { HealthcheckTag(text: LocalizedStringKey(display.label), color: display.color) }
+ HStack(spacing: 16) {
+ if !acked {
+ Button("Acknowledge") { Task { await problemAction(problem, .ack) } }
+ }
+ Button("Resolve") { Task { await problemAction(problem, .resolve) } }
+ }
+ .buttonStyle(.borderless)
+ }
+ }
+ }
+ }
+
+ @ViewBuilder private func newServicesSection(_ d: Node64.Monitor64HostDetail) -> some View {
+ let keys = (d.new ?? []).compactMap(\.key)
+ if !keys.isEmpty {
+ Section("New services") {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("\(keys.count) newly discovered")
+ Text(verbatim: (d.new ?? []).compactMap { $0.name?.nonBlank?.m64Text ?? $0.key }.prefix(5).joined(separator: ", ")
+ + (keys.count > 5 ? " …" : ""))
+ .font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
+ }
+ HStack(spacing: 16) {
+ Button("Adopt all") { Task { await adopt(keys, .adopt) } }
+ Button("Ignore all") { Task { await adopt(keys, .ignore) } }
+ }
+ .buttonStyle(.borderless)
+ }
+ }
+ }
+
+ private struct ServiceGroup {
+ let category: String
+ let services: [Node64.Monitor64HostService]
+ }
+
+ /// By category in order of first appearance.
+ private func serviceGroups(_ d: Node64.Monitor64HostDetail) -> [ServiceGroup] {
+ var seen = Set()
+ let services = (d.services ?? []).filter { $0.key != nil && seen.insert($0.key ?? "").inserted }
+ var order: [String] = []
+ for s in services where !order.contains(s.category?.rawValue ?? "other") { order.append(s.category?.rawValue ?? "other") }
+ return order.map { category in
+ ServiceGroup(category: category, services: services.filter { ($0.category?.rawValue ?? "other") == category })
+ }
+ }
+
+ /// Series already in the host charts are left out; `%` charts go up to 100, others to the metric's maximum (e.g. disk size).
+ private func serviceCharts(_ d: Node64.Monitor64HostDetail) -> [ServiceChart] {
+ let hostKeys = Set((d.charts ?? []).flatMap { $0.series ?? [] }.map { "\($0.svc ?? "")|\($0.metric ?? "")" })
+ return serviceGroups(d).flatMap(\.services).flatMap { s -> [ServiceChart] in
+ guard let key = s.key else { return [] }
+ let metrics = (s.metrics ?? []).filter { m in
+ guard m.value != nil, let name = m.name?.nonBlank else { return false }
+ return !hostKeys.contains("\(key)|\(name)")
+ }
+ var units: [String] = []
+ for m in metrics where !units.contains(m.unit ?? "") { units.append(m.unit ?? "") }
+ let title = (s.customName?.nonBlank ?? s.name?.nonBlank ?? key).m64Text
+ return units.map { unit in
+ let group = metrics.filter { ($0.unit ?? "") == unit }
+ return ServiceChart(id: "\(key)|\(unit)", title: units.count > 1 && !unit.isEmpty ? "\(title) (\(unit))" : title,
+ unit: unit, top: unit == "%" ? 100 : group.compactMap(\.max).max(),
+ series: group.map { ("\(key)|\($0.name ?? "")", $0.name ?? "") })
+ }
+ }
+ }
+
+ private func serviceRow(_ s: Node64.Monitor64HostService) -> some View {
+ let display = Monitor64Display.service(s.state?.rawValue)
+ let metrics = (s.metrics ?? []).compactMap { m -> String? in
+ guard let value = m.value else { return nil }
+ let number = value.formatted(.number.precision(.fractionLength(0...1)))
+ return "\(m.name ?? "") \(number)\(m.unit?.nonBlank.map { " \($0)" } ?? "")".trimmingCharacters(in: .whitespaces)
+ }.joined(separator: " · ")
+ return HcDetailRow(
+ title: (s.customName?.nonBlank ?? s.name?.nonBlank ?? s.key ?? "").m64Text,
+ subtitle: [s.text?.m64Text, metrics].compactMap { $0?.nonBlank }
+ ) { HealthcheckTag(text: LocalizedStringKey(display.label), color: display.color) }
+ }
+
+ private func accessRow(_ a: Node64.Monitor64AccessState) -> some View {
+ let (label, color): (String, Color) = {
+ if a.enabled == false { return ("Off", .gray) }
+ if a.known != true { return ("Unknown", .gray) }
+ return a.ok == true ? ("OK", .green) : ("Error", .red)
+ }()
+ return HcDetailRow(
+ title: (a.name?.nonBlank ?? a.type?.rawValue ?? "").m64Text,
+ subtitle: [a.type?.rawValue, a.error?.nonBlank?.m64Text].compactMap { $0 }
+ ) { HealthcheckTag(text: LocalizedStringKey(label), color: color) }
+ }
+
+ // MARK: Toolbar
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Edit", systemImage: "pencil") { showEdit = true }
+ .disabled(detail == nil || busy || isLoading)
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ if busy || isLoading {
+ ProgressView()
+ } else {
+ Button("Delete host", systemImage: "trash", role: .destructive) { confirmDelete = true }
+ .tint(.red)
+ .disabled(detail == nil)
+ }
+ }.appVerticalPreferred()
+ }
+
+ // MARK: Loading
+
+ private func load() async {
+ guard let client else {
+ error = ErrorText(title: String(localized: "Node not reachable"),
+ message: String(localized: "No local access stored for this node."))
+ return
+ }
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ detail = try await client.monitor64.hosts.get(uid)
+ generation += 1
+ } catch is CancellationError {
+ return
+ } catch {
+ self.error = hostError(error)
+ return
+ }
+ // A failing problem list shows its error inline.
+ do {
+ problems = try await client.monitor64.problems.list(status: .open, host: uid).problems ?? []
+ problemsError = nil
+ } catch is CancellationError {
+ } catch {
+ problemsError = ErrorText.node(error).message
+ }
+ }
+
+ /// Host charts of the range; an error only hides the charts.
+ private func loadCharts() async {
+ guard let client, let detail else { return }
+ chartsLoaded = false
+ defer { chartsLoaded = true }
+ let keys = (detail.charts ?? []).flatMap { $0.series ?? [] }.map { "\($0.svc ?? "")|\($0.metric ?? "")" }
+ let points = await fetchSeries(keys, client: client)
+ var lines: [String: [StatsLine]] = [:]
+ for chart in detail.charts ?? [] {
+ let chartLines = (chart.series ?? []).compactMap { series -> StatsLine? in
+ let key = "\(series.svc ?? "")|\(series.metric ?? "")"
+ guard let p = points[key] else { return nil }
+ return StatsLine(name: series.label?.nonBlank ?? key, points: p)
+ }
+ if !chartLines.isEmpty { lines[chart.id?.rawValue ?? ""] = chartLines }
+ }
+ charts = lines
+ }
+
+ /// Service charts, only while their section is open.
+ private func loadServiceCharts() async {
+ guard serviceChartsOpen, let client, let detail else { return }
+ serviceChartsLoaded = false
+ defer { serviceChartsLoaded = true }
+ let list = serviceCharts(detail)
+ // shortcut: at most 64 series (4 calls); load per chart on demand if hosts with more metrics are common.
+ let points = await fetchSeries(Array(list.flatMap { $0.series.map(\.key) }.prefix(64)), client: client)
+ var lines: [String: [StatsLine]] = [:]
+ for chart in list {
+ let chartLines = chart.series.compactMap { s in points[s.key].map { StatsLine(name: s.label, points: $0) } }
+ if !chartLines.isEmpty { lines[chart.id] = chartLines }
+ }
+ serviceChartLines = lines
+ }
+
+ /// Averages per `service|metric` key with at least two points, in calls of at most 16 series (server limit).
+ /// A failing call only drops its series.
+ private func fetchSeries(_ keys: [String], client: Node64) async -> [String: [StatsLine.Point]] {
+ var unique: [String] = []
+ for key in keys where !unique.contains(key) { unique.append(key) }
+ var result: [String: [StatsLine.Point]] = [:]
+ for start in stride(from: 0, to: unique.count, by: 16) {
+ let batch = Array(unique[start.. StatsLine.Point? in
+ guard let t = p.t, let avg = p.avg else { return nil }
+ return StatsLine.Point(time: Date(timeIntervalSince1970: TimeInterval(t)), value: avg)
+ }.sorted { $0.time < $1.time }
+ if points.count >= 2 { result[key] = points }
+ }
+ }
+ return result
+ }
+
+ // MARK: Actions
+
+ /// Runs an action with the spinner, then reloads.
+ private func act(_ block: (Node64) async throws -> Void) async {
+ guard let client else { return }
+ busy = true
+ defer { busy = false }
+ do {
+ try await block(client)
+ onChanged()
+ } catch is CancellationError {
+ return
+ } catch {
+ self.error = ErrorText.node(error)
+ return
+ }
+ await load()
+ }
+
+ private func setPaused(_ paused: Bool) async {
+ guard let h = host else { return }
+ // PUT replaces all fields: take over the values of the loaded host.
+ let input = Node64.Monitor64HostInput(
+ name: h.name ?? "", address: h.address ?? "", kind: h.kind, group: h.group, tags: h.tags,
+ intervalSec: h.intervalSec, notes: h.notes, paused: paused, agentAutoupdate: h.agentAutoupdate)
+ await act { _ = try await $0.monitor64.hosts.update(uid, input) }
+ }
+
+ private func problemAction(_ problem: Node64.Monitor64Problem, _ action: Node64.Monitor64ProblemActionAction) async {
+ await act { _ = try await $0.monitor64.problems.perform(.init(host: uid, key: problem.key, action: action)) }
+ }
+
+ private func adopt(_ keys: [String], _ state: Node64.Monitor64AdoptState) async {
+ await act { _ = try await $0.monitor64.hosts.adoptServices(host: uid, keys: keys, state: state) }
+ }
+
+ private func delete() async {
+ guard let client else { return }
+ busy = true
+ defer { busy = false }
+ do {
+ try await client.monitor64.hosts.delete(uid)
+ onChanged()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = hostError(error)
+ }
+ }
+}
+
+/// 404: host deleted or Monitor64 off; else the general node error text.
+func hostError(_ error: any Error) -> ErrorText {
+ isNodeNotFound(error)
+ ? ErrorText(title: String(localized: "Host not found"),
+ message: String(localized: "Host not found or Monitor64 is off on this node."))
+ : .node(error)
+}
+
+private extension Double {
+ var nonZero: Double { self > 0 ? self : 1 }
+}
diff --git a/IPv64/Views/Healthcheck/Monitor64HostFormView.swift b/IPv64/Views/Healthcheck/Monitor64HostFormView.swift
new file mode 100644
index 0000000..0439dd3
--- /dev/null
+++ b/IPv64/Views/Healthcheck/Monitor64HostFormView.swift
@@ -0,0 +1,436 @@
+import SwiftUI
+import IPv64
+
+/// New / edit Monitor64 host with its accesses, shown as a sheet (same look as `HealthcheckFormView`).
+struct Monitor64HostFormView: View {
+ let nodeId: String
+ /// `nil` = new host.
+ let uid: String?
+ let onSaved: () -> Void
+
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var loaded: Node64.Monitor64Host?
+ @State private var name = ""
+ @State private var address = ""
+ @State private var kind = Node64.Monitor64HostKind.unspecified
+ @State private var group = ""
+ @State private var tags = ""
+ @State private var interval = ""
+ @State private var notes = ""
+ @State private var paused = false
+ /// Access of a new host.
+ @State private var draft = Monitor64AccessDraft()
+ @State private var accesses: [Node64.Monitor64AccessState] = []
+ @State private var test = Monitor64AccessTestState()
+ @State private var accessEdit: Monitor64AccessDraft?
+ @State private var loading: Bool
+ @State private var isSaving = false
+ @State private var error: ErrorText?
+ @State private var dismissAfterError = false
+
+ init(nodeId: String, uid: String?, onSaved: @escaping () -> Void) {
+ self.nodeId = nodeId
+ self.uid = uid
+ self.onSaved = onSaved
+ _loading = State(initialValue: uid != nil)
+ }
+
+ private var editing: Bool { uid != nil }
+ private var client: Node64? { nodes.client(for: nodeId) }
+
+ private var intervalSeconds: Int? { interval.nonBlank.flatMap { Int($0.hcTrimmed) } }
+
+ private var issue: String? {
+ if name.nonBlank == nil { return String(localized: "Please enter a name.") }
+ if name.hcTrimmed.count > 100 { return String(localized: "The name can have at most 100 characters.") }
+ if address.nonBlank == nil { return String(localized: "Please enter an address.") }
+ if interval.nonBlank != nil, !(intervalSeconds.map { (30...900).contains($0) } ?? false) {
+ return String(localized: "Interval must be 30 to 900 seconds.")
+ }
+ return nil
+ }
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ if loading { ProgressView() } else { form }
+ }
+ .navigationTitle(editing ? "Edit Monitor64 host" : "New Monitor64 host")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel", systemImage: "xmark") { dismiss() }.disabled(isSaving)
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if isSaving {
+ ProgressView()
+ } else {
+ Button(editing ? "Save" : "Create", systemImage: "checkmark") { Task { await save() } }
+ .disabled(loading || issue != nil)
+ }
+ }.appVerticalPreferred()
+ }
+ .navigationDestination(item: $accessEdit) { edit in
+ Monitor64AccessEditView(nodeId: nodeId, hostUID: uid ?? "", address: address, draft: edit) {
+ Task { await reloadAccesses() }
+ }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ .interactiveDismissDisabled(isSaving)
+ .task { await load() }
+ .errorAlert($error)
+ .onChange(of: error == nil) { _, isNil in
+ if isNil && dismissAfterError { dismissAfterError = false; dismiss() }
+ }
+ }
+
+ private var form: some View {
+ Form {
+ Section {
+ TextField("Name", text: $name)
+ TextField("Address", text: $address)
+ .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled()
+ if editing {
+ LabeledContent("Kind") { Text(verbatim: kind.label) }
+ } else {
+ Picker("Kind", selection: $kind) {
+ ForEach(monitor64HostKinds, id: \.self) { Text(verbatim: $0.label).tag($0) }
+ }
+ }
+ } footer: {
+ HcFooter(hint: "Hostname, IPv4 or IPv6", error: touched ? issue : nil)
+ }
+ Section {
+ TextField("Group", text: $group)
+ TextField("Tags, comma-separated", text: $tags)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ HcFieldRow(label: "Interval", text: $interval, kind: .number, prompt: "Default", unit: "s")
+ HcMultilineField(placeholder: "Notes", text: $notes)
+ Toggle("Paused", isOn: $paused)
+ } footer: {
+ Text(editing ? "Interval: 30 to 900 seconds, empty = current node default"
+ : "Interval: 30 to 900 seconds, empty = node default")
+ }
+ if editing { accessesSection } else { newAccessSection }
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .disabled(isSaving)
+ }
+
+ /// Validation messages only show once something was typed.
+ private var touched: Bool { !name.isEmpty || !address.isEmpty || !interval.isEmpty }
+
+ private var accessesSection: some View {
+ Section("Accesses") {
+ ForEach(accesses, id: \.uid) { a in
+ Button {
+ accessEdit = Monitor64AccessDraft(a)
+ } label: {
+ HcDetailRow(
+ title: (a.name?.nonBlank ?? a.type?.rawValue ?? "").m64Text,
+ subtitle: [a.type?.rawValue, a.enabled == false ? String(localized: "Off") : nil,
+ a.error?.nonBlank?.m64Text].compactMap { $0 }
+ ) { Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(.tertiary) }
+ }
+ .tint(.primary)
+ }
+ Button("Add access", systemImage: "plus") { accessEdit = Monitor64AccessDraft(uid: nil, type: .agent) }
+ }
+ }
+
+ private var newAccessSection: some View {
+ Section {
+ Picker("Access", selection: $draft.type) {
+ Text("None (add later)").tag(Node64.Monitor64AccessType?.none)
+ ForEach(monitor64AccessTypes, id: \.self) { Text(verbatim: $0.rawValue).tag(Optional($0)) }
+ }
+ if draft.type != nil {
+ Monitor64AccessFields(draft: $draft, address: address, test: $test, client: client) { error = $0 }
+ }
+ } header: {
+ Text("Access")
+ }
+ }
+
+ // MARK: Loading and saving
+
+ private func load() async {
+ guard let uid, loading else { return }
+ guard let client else {
+ dismissAfterError = true
+ error = ErrorText(title: String(localized: "Node not reachable"),
+ message: String(localized: "No local access stored for this node."))
+ return
+ }
+ do {
+ let detail = try await client.monitor64.hosts.get(uid)
+ guard let h = detail.host else {
+ dismissAfterError = true
+ error = ErrorText(title: String(localized: "Host not found"),
+ message: String(localized: "The node returned no data for this host."))
+ return
+ }
+ loaded = h
+ accesses = detail.accesses ?? []
+ name = h.name ?? ""
+ address = h.address ?? ""
+ kind = h.kind ?? .unspecified
+ group = h.group ?? ""
+ tags = (h.tags ?? []).joined(separator: ", ")
+ notes = h.notes ?? ""
+ interval = h.intervalSec.flatMap { $0 > 0 ? String($0) : nil } ?? ""
+ paused = h.paused == true
+ loading = false
+ } catch is CancellationError {
+ } catch {
+ dismissAfterError = true
+ self.error = hostError(error)
+ }
+ }
+
+ private func reloadAccesses() async {
+ guard let uid, let client else { return }
+ if let detail = try? await client.monitor64.hosts.get(uid) { accesses = detail.accesses ?? [] }
+ onSaved()
+ }
+
+ private func save() async {
+ guard issue == nil, let client else { return }
+ isSaving = true
+ defer { isSaving = false }
+ let tagList = hcParseTags(tags)
+ do {
+ if let uid {
+ guard let loaded else { return }
+ // Empty interval: the API only knows "unchanged" on edit, so use the node default.
+ let seconds: Int?
+ if let given = intervalSeconds { seconds = given } else { seconds = try? await client.monitor64.settings().interval }
+ let input = Node64.Monitor64HostInput(
+ name: name.hcTrimmed, address: address.hcTrimmed, kind: loaded.kind, group: group.hcTrimmed, tags: tagList,
+ intervalSec: seconds, notes: notes.hcTrimmed, paused: paused, agentAutoupdate: loaded.agentAutoupdate)
+ _ = try await client.monitor64.hosts.update(uid, input)
+ } else {
+ // Services only after a successful test; the default ones are adopted right away.
+ let tested = draft.type != nil && test.result?.ok == true ? test.result?.services : nil
+ let create = Node64.Monitor64HostCreate(
+ name: name.hcTrimmed, address: address.hcTrimmed, kind: kind == .unspecified ? nil : kind,
+ group: group.nonBlank?.hcTrimmed, tags: tagList.isEmpty ? nil : tagList, intervalSec: intervalSeconds,
+ notes: notes.nonBlank?.hcTrimmed, paused: paused ? true : nil,
+ accesses: draft.input().map { [$0] },
+ services: tested.flatMap { $0.isEmpty ? nil : $0 },
+ adopt: tested.flatMap { list in
+ let keys = list.filter { $0.isDefault == true }.map(\.key)
+ return keys.isEmpty ? nil : keys
+ })
+ _ = try await client.monitor64.hosts.create(create)
+ }
+ onSaved()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = hostError(error)
+ }
+ }
+}
+
+/// Result of the connection test and the fingerprint waiting for confirmation.
+struct Monitor64AccessTestState: Equatable {
+ var result: Node64.Monitor64TestResult?
+ var askFingerprint: String?
+ var running = false
+}
+
+/// Fields of one access with the connection test and the fingerprint confirmation.
+struct Monitor64AccessFields: View {
+ @Binding var draft: Monitor64AccessDraft
+ let address: String
+ @Binding var test: Monitor64AccessTestState
+ let client: Node64?
+ let onError: (ErrorText) -> Void
+
+ var body: some View {
+ Group {
+ HcFieldRow(label: "Port", text: $draft.port, kind: .number, prompt: "Default")
+ HcFieldRow(label: "User", text: $draft.user, prompt: "")
+ HcFieldRow(label: "URL", text: $draft.url, kind: .url, prompt: "")
+ HcFieldRow(label: "Token ID", text: $draft.tokenId, prompt: "")
+ HcFieldRow(label: "Secret", text: $draft.secret, kind: .secure, prompt: "Password, token or key")
+ if draft.uid != nil { Toggle("Enabled", isOn: $draft.enabled) }
+ Button {
+ Task { await runTest() }
+ } label: {
+ HStack {
+ Text("Test connection")
+ Spacer()
+ if test.running { ProgressView() }
+ }
+ }
+ .disabled(test.running)
+ if let r = test.result {
+ Text(verbatim: resultText(r))
+ .font(.footnote)
+ .foregroundStyle(r.ok == true ? Color.secondary : Color.red)
+ }
+ }
+ // A changed target invalidates the test and a confirmed fingerprint.
+ .onChange(of: draft.targetKey) {
+ test.result = nil
+ draft.fingerprint = nil
+ }
+ .onChange(of: address) {
+ test.result = nil
+ draft.fingerprint = nil
+ }
+ .alert("Trust this fingerprint?", isPresented: Binding(
+ get: { test.askFingerprint != nil }, set: { if !$0 { test.askFingerprint = nil } }),
+ presenting: test.askFingerprint) { fingerprint in
+ Button("Trust and test again") {
+ draft.fingerprint = fingerprint
+ Task { await runTest() }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: { fingerprint in
+ Text(verbatim: fingerprint)
+ }
+ }
+
+ private func resultText(_ r: Node64.Monitor64TestResult) -> String {
+ if r.ok == true {
+ return [String(localized: "Connection OK"), r.summary?.nonBlank,
+ String(localized: "\(r.services?.count ?? 0) services found"), r.warning?.nonBlank]
+ .compactMap { $0 }.joined(separator: " · ").m64Text
+ }
+ return r.error?.nonBlank?.m64Text ?? String(localized: "Connection failed.")
+ }
+
+ private func runTest() async {
+ guard let client, let access = draft.input() else { return }
+ guard address.nonBlank != nil else {
+ onError(ErrorText(title: String(localized: "Check your input"), message: String(localized: "Please enter an address.")))
+ return
+ }
+ test.running = true
+ defer { test.running = false }
+ do {
+ // A saved access: empty fields (also the secret) count as saved.
+ let result = if let uid = draft.uid {
+ try await client.monitor64.access.test(uid, changes: access)
+ } else {
+ try await client.monitor64.test(Node64.Monitor64TestInput(address: address.hcTrimmed, access: access))
+ }
+ test.result = result
+ if result.needConfirm == true { test.askFingerprint = result.fingerprint }
+ } catch is CancellationError {
+ } catch {
+ onError(hostError(error))
+ }
+ }
+}
+
+/// Pushed in the host form: edit or add one access of a saved host.
+struct Monitor64AccessEditView: View {
+ let nodeId: String
+ let hostUID: String
+ let address: String
+ let onSaved: () -> Void
+
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var draft: Monitor64AccessDraft
+ @State private var test = Monitor64AccessTestState()
+ @State private var isSaving = false
+ @State private var confirmDelete = false
+ @State private var error: ErrorText?
+
+ init(nodeId: String, hostUID: String, address: String, draft: Monitor64AccessDraft, onSaved: @escaping () -> Void) {
+ self.nodeId = nodeId
+ self.hostUID = hostUID
+ self.address = address
+ self.onSaved = onSaved
+ _draft = State(initialValue: draft)
+ }
+
+ private var client: Node64? { nodes.client(for: nodeId) }
+
+ var body: some View {
+ Form {
+ Section {
+ if draft.uid == nil {
+ Picker("Access", selection: $draft.type) {
+ ForEach(monitor64AccessTypes, id: \.self) { Text(verbatim: $0.rawValue).tag(Optional($0)) }
+ }
+ } else {
+ LabeledContent("Access") { Text(verbatim: draft.type?.rawValue ?? "") }
+ }
+ Monitor64AccessFields(draft: $draft, address: address, test: $test, client: client) { error = $0 }
+ }
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .disabled(isSaving)
+ .navigationTitle(draft.uid == nil ? "New access" : "Edit access")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if draft.uid != nil {
+ ToolbarItem(placement: .topBarTrailing) {
+ Menu {
+ DestructiveMenuButton("Delete access", systemImage: "trash") { confirmDelete = true }
+ } label: {
+ Label("More actions", systemImage: "ellipsis")
+ }
+ .disabled(isSaving)
+ }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if isSaving {
+ ProgressView()
+ } else {
+ Button("Save", systemImage: "checkmark") { Task { await save() } }.disabled(draft.type == nil)
+ }
+ }.appVerticalPreferred()
+ }
+ .alert("Delete access?", isPresented: $confirmDelete) {
+ Button("Delete", role: .destructive) { Task { await delete() } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("The host can no longer be queried through this access.")
+ }
+ .errorAlert($error)
+ }
+
+ private func save() async {
+ guard let client, let input = draft.input() else { return }
+ isSaving = true
+ defer { isSaving = false }
+ do {
+ if let uid = draft.uid {
+ _ = try await client.monitor64.access.update(uid, input)
+ } else {
+ _ = try await client.monitor64.hosts.createAccess(host: hostUID, input)
+ }
+ onSaved()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = hostError(error)
+ }
+ }
+
+ private func delete() async {
+ guard let client, let uid = draft.uid else { return }
+ isSaving = true
+ defer { isSaving = false }
+ do {
+ try await client.monitor64.access.delete(uid)
+ onSaved()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = hostError(error)
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/NodeCheckDetailSections.swift b/IPv64/Views/Healthcheck/NodeCheckDetailSections.swift
new file mode 100644
index 0000000..e73585b
--- /dev/null
+++ b/IPv64/Views/Healthcheck/NodeCheckDetailSections.swift
@@ -0,0 +1,150 @@
+import SwiftUI
+import IPv64
+
+// Building blocks of the node check detail; the look is shared with the account check detail.
+
+struct NodeCheckStatusRows: View {
+ let check: Node64.Check
+
+ static func hasContent(_ check: Node64.Check) -> Bool {
+ guard let s = check.state else { return false }
+ return [s.since, s.lastCheckAt, s.lastStatus, s.lastReason, s.lastMessage, s.downSince, s.lastPushAt]
+ .contains { $0?.nonBlank != nil } || s.lastLatencyMS != nil
+ }
+
+ var body: some View {
+ let s = check.state
+ HcInfoRow("Since", HcFormat.time(nodeDate(s?.since)))
+ HcInfoRow("Last check", HcFormat.timeWithRelative(nodeDate(s?.lastCheckAt)))
+ HcInfoRow("Last status", s?.lastStatus)
+ HcInfoRow("Latency", s?.lastLatencyMS.map { HcFormat.latency($0) })
+ HcInfoRow("Reason", s?.lastReason)
+ HcInfoRow("Message", s?.lastMessage)
+ HcInfoRow("Down since", HcFormat.time(nodeDate(s?.downSince)), color: .red)
+ HcInfoRow("Last push", HcFormat.timeWithRelative(nodeDate(s?.lastPushAt)))
+ }
+}
+
+struct NodeCheckConfigRows: View {
+ let check: Node64.Check
+
+ var body: some View {
+ HcInfoRow("Type", check.type?.label)
+ HcInfoRow("Target", check.target)
+ HcInfoRow("Interval", check.intervalSeconds.map { HcFormat.duration(seconds: $0) })
+ HcInfoRow("Retry interval", check.retryIntervalSeconds.map { HcFormat.duration(seconds: $0) })
+ HcInfoRow("Retries", check.retries.map(String.init))
+ HcInfoRow("Timeout", check.timeoutSeconds.map { HcFormat.seconds($0) })
+ HcInfoRow("Connect timeout", check.connectTimeoutSeconds.map { HcFormat.seconds($0) })
+ HcInfoRow("Stabilize", check.stabilize.map(String.init))
+ HcInfoRow("IP mode", check.ipMode?.rawValue)
+ HcInfoRow("Invert result", HcFormat.yesNo(check.invert))
+ HcInfoRow("Notify down", HcFormat.yesNo(check.notifyDown))
+ HcInfoRow("Notify up", HcFormat.yesNo(check.notifyUp))
+ HcInfoRow("Notify degraded", HcFormat.yesNo(check.notifyDegraded))
+ HcInfoRow("Critical", HcFormat.yesNo(check.critical))
+ HcInfoRow("Reminder", check.repeatMinutes.map(HcFormat.repeatMinutes))
+ HcInfoRow("Tags", (check.tags ?? []).joined(separator: ", "))
+ HcInfoRow("Group", check.group)
+ HcInfoRow("Description", check.description)
+ HcInfoRow("Created", HcFormat.time(nodeDate(check.createdAt)))
+ HcInfoRow("Updated", HcFormat.time(nodeDate(check.updatedAt)))
+ }
+}
+
+/// Statistics block like the account check: large availability, latency chart, key figures.
+struct NodeCheckStatsRows: View {
+ let stats: Node64.CheckStats
+
+ private var line: [StatsLine] {
+ let points = (stats.series ?? []).compactMap { point -> StatsLine.Point? in
+ guard let time = nodeDate(point.time), let value = point.avgMS else { return nil }
+ return StatsLine.Point(time: time, value: value)
+ }.sorted { $0.time < $1.time }
+ return points.isEmpty ? [] : [StatsLine(name: "Latency", points: points)]
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: HcFormat.percent(stats.upPercent))
+ .font(.system(size: 40, weight: .bold, design: .rounded))
+ Text("Availability").font(.caption).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ let lines = line
+ if lines.flatMap(\.points).count >= 2 {
+ LatencyChart(lines: lines, dayBucket: (stats.bucketSeconds ?? 0) >= 86_400)
+ }
+ if let total = stats.count {
+ LabeledContent("Checks", value: total.formatted())
+ if let up = stats.upCount { LabeledContent("Failed checks", value: max(0, total - up).formatted()) }
+ }
+ LabeledContent("Average latency", value: HcFormat.latency(stats.avgMS))
+ LabeledContent("Maximum latency", value: HcFormat.latency(stats.maxMS))
+ }
+}
+
+struct NodeCheckEventRow: View {
+ let event: Node64.CheckEvent
+
+ private var state: Hc2StateUi { HcFormat.eventState(kind: event.kind, to: event.to) }
+
+ private var lines: [String] {
+ var lines: [String] = []
+ if event.from?.nonBlank != nil || event.to?.nonBlank != nil {
+ lines.append("\(event.from?.nonBlank ?? "–") → \(event.to?.nonBlank ?? "–")")
+ }
+ var meta: [String] = []
+ if let seconds = event.durationSeconds { meta.append(String(localized: "after \(HcFormat.duration(seconds: seconds))")) }
+ if let flaps = event.flaps, flaps > 0 { meta.append(String(localized: "\(flaps) flaps")) }
+ if event.silent == true { meta.append(String(localized: "silent")) }
+ if !meta.isEmpty { lines.append(meta.joined(separator: " · ")) }
+ if let text = event.message?.nonBlank ?? event.reason?.nonBlank { lines.append(text) }
+ if let time = HcFormat.time(nodeDate(event.time)) { lines.append(time) }
+ return lines
+ }
+
+ var body: some View {
+ HcDetailRow(title: HcFormat.eventTitle(kind: event.kind, fallback: state.label), subtitle: lines) {
+ HealthcheckStateTag(state: state)
+ }
+ }
+}
+
+struct NodeCheckIncidentRow: View {
+ let incident: Node64.CheckIncident
+
+ private var started: Date? { HcFormat.real(nodeDate(incident.startedAt)) }
+
+ private var subtitle: String? {
+ var parts: [String] = []
+ if let started {
+ let end = HcFormat.real(nodeDate(incident.endedAt)) ?? (incident.open == true ? Date() : nil)
+ if let end, end > started { parts.append(HcFormat.duration(seconds: Int(end.timeIntervalSince(started)))) }
+ }
+ if let text = incident.message?.nonBlank ?? incident.reason?.nonBlank { parts.append(text) }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ var body: some View {
+ let open = incident.open == true
+ HStack(spacing: 12) {
+ Image(systemName: open ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")
+ .foregroundStyle(open ? .red : .green)
+ .font(.title3)
+ .accessibilityLabel(open ? "Open incident" : "Resolved incident")
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: HcFormat.time(started) ?? "–")
+ if let subtitle {
+ Text(verbatim: subtitle).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
+ }
+ }
+ Spacer(minLength: 8)
+ if let started {
+ Text(started.formatted(.relative(presentation: .named))).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/IPv64/Views/Healthcheck/NodeCheckDetailView.swift b/IPv64/Views/Healthcheck/NodeCheckDetailView.swift
new file mode 100644
index 0000000..6188666
--- /dev/null
+++ b/IPv64/Views/Healthcheck/NodeCheckDetailView.swift
@@ -0,0 +1,306 @@
+import SwiftUI
+import IPv64
+
+/// Detail of a check of a connected node (direct access): same structure as the account check detail.
+struct NodeCheckDetailView: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+
+ let nodeId: String
+ let token: String
+ /// Tells the list that this check changed (pause, resume, delete, edit).
+ let onChanged: () -> Void
+
+ @State private var check: Node64.Check?
+ @State private var events: [Node64.CheckEvent] = []
+ @State private var hasMoreEvents = false
+ @State private var measurements: [Node64.CheckMeasurement] = []
+ @State private var generation = 0
+ @State private var busy = false
+ @State private var isLoading = false
+ @State private var loadingMore = false
+ @State private var confirmDelete = false
+ @State private var showEdit = false
+ @State private var error: ErrorText?
+ @State private var statsRange = Node64.CheckStatsRange.last24Hours
+ @State private var statsCache: [Node64.CheckStatsRange: Node64.CheckStats] = [:]
+ @State private var statsError: String?
+ @State private var eventsExpanded = false
+ @State private var statsExpanded = true
+ @State private var incidentsExpanded = false
+ @State private var incidents: [Node64.CheckIncident]?
+ @State private var incidentsError: String?
+
+ private static let pageSize = 50
+
+ private struct StatsKey: Equatable { let range: Node64.CheckStatsRange, generation: Int }
+
+ private var client: Node64? { nodes.client(for: nodeId) }
+ private var paused: Bool { check?.paused == true || check?.state?.state == .paused }
+ private var editable: Bool { check?.type.map(nodeCheckTypes.contains) ?? false }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(confirmDelete || showEdit ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+
+ private var content: some View {
+ List {
+ if let check {
+ recent
+ if NodeCheckStatusRows.hasContent(check) {
+ Section("Status") { NodeCheckStatusRows(check: check) }
+ }
+ actions
+ if check.type == .push, let url = check.pushURL?.nonBlank { pushSection(url) }
+ Section("Configuration") { NodeCheckConfigRows(check: check) }
+ if statsCache[statsRange] != nil || statsError != nil { statsSection }
+ incidentsSection
+ if !events.isEmpty { eventsSection }
+ }
+ }
+ .overlay {
+ if check == nil && error == nil { ProgressView() }
+ }
+ .disabled(busy || isLoading)
+ .navigationTitle(check?.name?.nonBlank ?? String(localized: "Healthcheck"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar { toolbar }
+ .refreshable { await load() }
+ .task { await load() }
+ .task(id: StatsKey(range: statsRange, generation: generation)) { await loadStats() }
+ .sheet(isPresented: $showEdit) {
+ NodeCheckFormView(nodeId: nodeId, token: token) {
+ onChanged()
+ Task { await load() }
+ }
+ }
+ .alert("Delete healthcheck?", isPresented: $confirmDelete) {
+ Button("Delete", role: .destructive) { Task { await delete() } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Do you really want to delete \"\(check?.name ?? token)\"? Its history is deleted as well.")
+ }
+ .errorAlert($error)
+ }
+
+ // MARK: Sections
+
+ private var actions: some View {
+ Section {
+ Button {
+ Task { await togglePause() }
+ } label: {
+ Label(paused ? "Resume" : "Pause", systemImage: paused ? "play" : "pause")
+ }
+ Button {
+ Task { await runNow() }
+ } label: {
+ Label("Run now", systemImage: "arrow.clockwise")
+ }
+ }
+ .tint(.primary)
+ }
+
+ private func pushSection(_ url: String) -> some View {
+ Section("Push endpoints") {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Push URL").font(.subheadline).foregroundStyle(.secondary)
+ Text(verbatim: url).font(.callout.monospaced()).textSelection(.enabled)
+ HStack(spacing: 16) {
+ Button("Copy", systemImage: "doc.on.doc") { Clipboard.copy(url, sensitive: true) }
+ ShareLink(item: url) { Label("Share", systemImage: "square.and.arrow.up") }
+ }
+ .buttonStyle(.borderless)
+ .font(.subheadline)
+ }
+ }
+ }
+
+ @ViewBuilder private var recent: some View {
+ if !measurements.isEmpty {
+ Section("Recent checks") {
+ StatusPillsBar(states: measurements.map { $0.status == .up ? .up : $0.status == .down ? .down : .pending },
+ noun: "checks")
+ }
+ } else if !events.isEmpty {
+ Section("Recent events") {
+ StatusPillsBar(states: events.map { HcFormat.eventState(kind: $0.kind, to: $0.to) }, noun: "events")
+ }
+ }
+ }
+
+ private var statsSection: some View {
+ HcCollapsibleSection(title: "Statistics", isExpanded: $statsExpanded) {
+ Picker("Range", selection: $statsRange) {
+ Text("1 h").tag(Node64.CheckStatsRange.lastHour)
+ Text("24 h").tag(Node64.CheckStatsRange.last24Hours)
+ Text("7 d").tag(Node64.CheckStatsRange.last7Days)
+ Text("30 d").tag(Node64.CheckStatsRange.last30Days)
+ Text("1 y").tag(Node64.CheckStatsRange.lastYear)
+ }
+ .pickerStyle(.segmented)
+ if let stats = statsCache[statsRange] {
+ NodeCheckStatsRows(stats: stats)
+ } else if let statsError {
+ Text(verbatim: statsError).foregroundStyle(.red)
+ } else {
+ ProgressView().frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ private var incidentsSection: some View {
+ HcCollapsibleSection(title: "Incidents", isExpanded: $incidentsExpanded) {
+ if let incidentsError {
+ Text(verbatim: incidentsError).foregroundStyle(.red)
+ } else if let incidents {
+ if incidents.isEmpty {
+ Text("No incidents").foregroundStyle(.secondary)
+ } else {
+ ForEach(incidents) { NodeCheckIncidentRow(incident: $0) }
+ }
+ } else {
+ ProgressView().frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ private var eventsSection: some View {
+ HcCollapsibleSection(title: "Events", isExpanded: $eventsExpanded) {
+ ForEach(events) { NodeCheckEventRow(event: $0) }
+ if hasMoreEvents {
+ Button(loadingMore ? "Loading..." : "Load more") { Task { await loadMore() } }
+ .disabled(loadingMore)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ }
+
+ // MARK: Toolbar
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Edit", systemImage: "pencil") { showEdit = true }
+ .disabled(check == nil || !editable || busy || isLoading)
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ if busy || isLoading {
+ ProgressView()
+ } else {
+ Button("Delete healthcheck", systemImage: "trash", role: .destructive) { confirmDelete = true }
+ .tint(.red)
+ .disabled(check == nil)
+ }
+ }.appVerticalPreferred()
+ }
+
+ // MARK: Loading
+
+ /// One after another; measurements, events and incidents may fail silently (the check itself must load).
+ private func load() async {
+ guard let client else {
+ error = ErrorText(title: String(localized: "Node not reachable"),
+ message: String(localized: "No local access stored for this node."))
+ return
+ }
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ let loaded = try await client.hc.checks.get(token)
+ let page = (try? await client.hc.checks.events(token, limit: Self.pageSize)) ?? []
+ let list = (try? await client.hc.checks.measurements(token, limit: 100)) ?? []
+ let incidentList = try? await client.hc.checks.incidents(token, limit: 20)
+ check = loaded
+ events = page
+ hasMoreEvents = page.count >= Self.pageSize
+ measurements = list
+ incidents = incidentList
+ incidentsError = incidentList == nil ? String(localized: "Incidents could not be loaded") : nil
+ statsCache = [:]
+ generation += 1
+ } catch is CancellationError {
+ } catch {
+ self.error = .node(error)
+ }
+ }
+
+ private func loadMore() async {
+ guard let client, let before = events.last?.id else { return }
+ loadingMore = true
+ defer { loadingMore = false }
+ do {
+ let page = try await client.hc.checks.events(token, limit: Self.pageSize, before: before)
+ let known = Set(events.map(\.id))
+ events += page.filter { !known.contains($0.id) }
+ hasMoreEvents = page.count >= Self.pageSize
+ } catch is CancellationError {
+ } catch {
+ self.error = .node(error)
+ }
+ }
+
+ private func loadStats() async {
+ guard let client, check != nil, statsCache[statsRange] == nil else { return }
+ let range = statsRange
+ statsError = nil
+ do {
+ statsCache[range] = try await client.hc.checks.stats(token, range: range)
+ } catch is CancellationError {
+ } catch {
+ statsError = ErrorText.node(error).message.nonBlank ?? String(localized: "Statistics could not be loaded")
+ }
+ }
+
+ // MARK: Actions
+
+ private func togglePause() async {
+ guard let client else { return }
+ busy = true
+ defer { busy = false }
+ do {
+ check = paused ? try await client.hc.checks.resume(token) : try await client.hc.checks.pause(token)
+ onChanged()
+ } catch is CancellationError {
+ } catch {
+ self.error = .node(error)
+ }
+ }
+
+ private func runNow() async {
+ guard let client else { return }
+ busy = true
+ defer { busy = false }
+ do {
+ try await client.hc.checks.run(token)
+ onChanged()
+ } catch is CancellationError {
+ return
+ } catch {
+ self.error = .node(error)
+ return
+ }
+ await load()
+ }
+
+ private func delete() async {
+ guard let client else { return }
+ busy = true
+ defer { busy = false }
+ do {
+ try await client.hc.checks.delete(token)
+ onChanged()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = .node(error)
+ }
+ }
+}
diff --git a/IPv64/Views/Healthcheck/NodeCheckFormView.swift b/IPv64/Views/Healthcheck/NodeCheckFormView.swift
new file mode 100644
index 0000000..8787a7b
--- /dev/null
+++ b/IPv64/Views/Healthcheck/NodeCheckFormView.swift
@@ -0,0 +1,252 @@
+import SwiftUI
+import IPv64
+
+/// New / edit node healthcheck, shown as a sheet (same look as `HealthcheckFormView`).
+struct NodeCheckFormView: View {
+ let nodeId: String
+ /// `nil` = new healthcheck.
+ let token: String?
+ /// Called after the check was created or changed.
+ let onSaved: () -> Void
+
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var f = NodeCheckFormState()
+ @State private var initial = NodeCheckFormState()
+ @State private var loading: Bool
+ @State private var isSaving = false
+ @State private var error: ErrorText?
+ @State private var dismissAfterError = false
+ @State private var advancedOpen = false
+ @State private var notificationsOpen = false
+
+ init(nodeId: String, token: String?, onSaved: @escaping () -> Void) {
+ self.nodeId = nodeId
+ self.token = token
+ self.onSaved = onSaved
+ _loading = State(initialValue: token != nil)
+ }
+
+ private var editing: Bool { token != nil }
+ private var client: Node64? { nodes.client(for: nodeId) }
+ private var issue: String? { f.validate() }
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ if loading { ProgressView() } else { form }
+ }
+ .navigationTitle(editing ? "Edit Healthcheck" : "New Healthcheck")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel", systemImage: "xmark") { dismiss() }.disabled(isSaving)
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if isSaving {
+ ProgressView()
+ } else {
+ Button(editing ? "Save" : "Create", systemImage: "checkmark") { Task { await save() } }
+ .disabled(loading || issue != nil)
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ .interactiveDismissDisabled(isSaving)
+ .task { await load() }
+ .errorAlert($error)
+ .onChange(of: error == nil) { _, isNil in
+ if isNil && dismissAfterError { dismissAfterError = false; dismiss() }
+ }
+ }
+
+ private var form: some View {
+ Form {
+ Section {
+ if editing {
+ LabeledContent("Type") {
+ HStack(spacing: 6) {
+ Image(systemName: f.type.hc2.symbol).foregroundStyle(.tint)
+ Text(f.type.label)
+ }
+ }
+ } else {
+ Picker("Type", selection: $f.type) {
+ ForEach(nodeCheckTypes, id: \.self) { Label($0.label, systemImage: $0.hc2.symbol).tag($0) }
+ }
+ .pickerStyle(.navigationLink)
+ }
+ TextField("Name", text: $f.name)
+ if f.type != .push {
+ TextField(f.type.hc2.targetHint, text: $f.target)
+ .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled()
+ }
+ } footer: {
+ HcFooter(hint: f.type == .push && !editing ? "A push URL is created with the check." : nil,
+ error: f != initial ? issue : nil)
+ }
+ essential
+ HcCollapsibleSection(
+ title: "Advanced", isExpanded: $advancedOpen,
+ hint: editing ? "Clearing a field keeps the current value; it cannot be reset to the default here."
+ : "Empty fields use the server default."
+ ) {
+ HcDurationPicker(label: "Interval", value: $f.intervalValue, unit: $f.intervalUnit,
+ presets: [20, 30, 60, 120, 300, 600, 900, 1800, 3600],
+ allowsDefault: !(editing && f.base?.intervalSeconds != nil))
+ HcDurationPicker(label: "Retry interval", value: $f.retryValue, unit: $f.retryUnit,
+ presets: [5, 10, 30, 60, 120, 300],
+ allowsDefault: !(editing && f.base?.retryIntervalSeconds != nil))
+ HcStepperRow(label: "Retries", text: $f.retries, range: 0...10)
+ HcFieldRow(label: "Timeout", text: $f.timeout, kind: .decimal, prompt: "Default", unit: "s")
+ HcFieldRow(label: "Connect timeout", text: $f.connectTimeout, kind: .decimal, prompt: "Default", unit: "s")
+ HcStepperRow(label: "Stabilize", text: $f.stabilize, range: 1...20)
+ Toggle("Invert result", isOn: $f.invert)
+ Picker("IP mode", selection: $f.ipMode) {
+ ForEach(ipModes, id: \.self) { Text(verbatim: $0?.rawValue ?? String(localized: "Default")).tag($0) }
+ }
+ }
+ HcCollapsibleSection(
+ title: "Notifications & organisation", isExpanded: $notificationsOpen,
+ hint: "Degraded also notifies on partial failure. Critical ignores quiet hours."
+ ) {
+ Toggle("Notify when down", isOn: $f.notifyDown)
+ Toggle("Notify when back up", isOn: $f.notifyUp)
+ Toggle("Notify when degraded", isOn: $f.notifyDegraded)
+ Toggle("Critical", isOn: $f.critical)
+ HcRepeatPicker(minutes: $f.repeatMinutes, allowsDefault: !(editing && f.base?.repeatMinutes != nil))
+ TextField("Tags, comma-separated", text: $f.tags)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ TextField("Group", text: $f.group)
+ HcMultilineField(placeholder: "Description", text: $f.description)
+ if !editing { Toggle("Create paused", isOn: $f.createPaused) }
+ }
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .disabled(isSaving)
+ }
+
+ private var ipModes: [Node64.CheckIPMode?] {
+ [nil, .auto, .ipv4, .ipv6, .both].filter { !($0 == nil && editing && f.base?.ipMode != nil) }
+ }
+
+ /// Core parameters of the type in their own section.
+ @ViewBuilder private var essential: some View {
+ switch f.type {
+ case .keyword:
+ Section("Keyword") {
+ TextField("Keyword", text: $f.keyword).textInputAutocapitalization(.never).autocorrectionDisabled()
+ }
+ case .dns:
+ Section("DNS") {
+ Picker("Record type", selection: $f.recordType) {
+ ForEach(dnsRecordTypes, id: \.self) { Text(verbatim: $0.rawValue).tag($0) }
+ }
+ }
+ case .tcp, .port, .cert:
+ Section {
+ HcFieldRow(label: "Port", text: $f.port, kind: .number, prompt: "443")
+ } header: {
+ Text("Port")
+ } footer: {
+ Text("Or use host:port as target")
+ }
+ default:
+ EmptyView()
+ }
+ }
+
+ // MARK: Loading and saving
+
+ private func load() async {
+ guard let token, loading else { return }
+ guard let client else {
+ dismissAfterError = true
+ error = ErrorText(title: String(localized: "Node not reachable"),
+ message: String(localized: "No local access stored for this node."))
+ return
+ }
+ do {
+ var state = NodeCheckFormState()
+ state.apply(try await client.hc.checks.get(token))
+ f = state
+ initial = state
+ loading = false
+ } catch is CancellationError {
+ } catch {
+ dismissAfterError = true
+ self.error = .node(error)
+ }
+ }
+
+ private func save() async {
+ guard issue == nil, let client else { return }
+ isSaving = true
+ defer { isSaving = false }
+ let input = f.input()
+ do {
+ if let token {
+ try await client.hc.checks.update(token, input)
+ } else {
+ try await client.hc.checks.create(input)
+ }
+ onSaved()
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = .node(error)
+ }
+ }
+}
+
+/// First sheet of "+": where the new healthcheck runs.
+struct HealthcheckTargetSheet: View {
+ @Environment(\.dismiss) private var dismiss
+ /// (nodeId, name) of the reachable nodes that offer checks.
+ let nodes: [(id: String, name: String)]
+ /// Nodes with Monitor64.
+ let monitorNodes: [(id: String, name: String)]
+ /// The caller presents the form after this sheet closed.
+ let onChoose: (HealthcheckTarget) -> Void
+
+ var body: some View {
+ NavigationStack {
+ List {
+ choice(title: "Account healthcheck", subtitle: "Runs from ipv64.net locations", symbol: "cloud", target: .account)
+ ForEach(nodes, id: \.id) { node in
+ choice(title: "On node \(node.name)", subtitle: "Runs locally on \(node.name)", symbol: "network",
+ target: .nodeCheck(node.id))
+ }
+ ForEach(monitorNodes, id: \.id) { node in
+ choice(title: "Monitor64 host on \(node.name)", subtitle: "Monitors a server or device from \(node.name)",
+ symbol: "server.rack", target: .monitor64Host(node.id))
+ }
+ }
+ .navigationTitle("New Healthcheck")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel", systemImage: "xmark") { dismiss() } }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.medium])
+ }
+
+ private func choice(title: LocalizedStringKey, subtitle: LocalizedStringKey, symbol: String, target: HealthcheckTarget) -> some View {
+ Button {
+ onChoose(target)
+ dismiss()
+ } label: {
+ Label {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title)
+ Text(subtitle).font(.subheadline).foregroundStyle(.secondary)
+ }
+ } icon: { Image(systemName: symbol) }
+ }
+ .tint(.primary)
+ }
+}
diff --git a/IPv64/Views/More/AccountLinksView.swift b/IPv64/Views/More/AccountLinksView.swift
new file mode 100644
index 0000000..6a2dec4
--- /dev/null
+++ b/IPv64/Views/More/AccountLinksView.swift
@@ -0,0 +1,69 @@
+import SwiftUI
+import IPv64
+
+/// "Account links" (read-only).
+struct AccountLinksView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.openURL) private var openURL
+
+ @State private var links: AccountLinks?
+ @State private var error: ErrorText?
+
+ var body: some View {
+ List {
+ if let links {
+ Section {
+ Text("Account links let another IPv64 account manage yours, or you manage theirs. Links are managed at ipv64.net.")
+ Button("Manage at ipv64.net", systemImage: "arrow.up.right.square") {
+ if let url = URL(string: "https://ipv64.net/account") { openURL(url) }
+ }
+ }
+ group("Can manage your account", links.sharedWith)
+ group("Accounts you manage", links.managed)
+ }
+ }
+ .overlay { if links == nil && error == nil { ProgressView() } }
+ .navigationTitle("Account links")
+ .navigationBarTitleDisplayMode(.inline)
+ .moreGradient()
+ .refreshable { await load() }
+ .task { await load() }
+ .errorAlert($error)
+ }
+
+ @ViewBuilder private func group(_ title: LocalizedStringKey, _ items: [AccountLink]?) -> some View {
+ if let items, !items.isEmpty {
+ Section(title) {
+ ForEach(items) { link in
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ Text(verbatim: link.email?.nonBlank ?? String(localized: "Unknown account")).font(.headline)
+ Spacer(minLength: 8)
+ if link.status == .active { MoreTag(String(localized: "Active"), .green) }
+ else if link.status == .pending { MoreTag(String(localized: "Pending"), .orange) }
+ }
+ Text(verbatim: subtitle(link)).font(.footnote).foregroundStyle(.secondary)
+ }
+ .accessibilityElement(children: .combine)
+ }
+ }
+ }
+ }
+
+ private func subtitle(_ link: AccountLink) -> String {
+ var lines: [String] = []
+ if let created = HcFormat.time(link.createdAt) { lines.append(String(localized: "Created \(created)")) }
+ let used = HcFormat.real(link.lastUsedAt).map { $0.formatted(.relative(presentation: .named)) } ?? "–"
+ lines.append(String(localized: "Last used: \(used)"))
+ return lines.joined(separator: "\n")
+ }
+
+ private func load() async {
+ do {
+ links = try await session.api.account.links()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
diff --git a/IPv64/Views/More/ApiKeysView.swift b/IPv64/Views/More/ApiKeysView.swift
new file mode 100644
index 0000000..b70c9f9
--- /dev/null
+++ b/IPv64/Views/More/ApiKeysView.swift
@@ -0,0 +1,227 @@
+import SwiftUI
+import IPv64
+
+/// "API keys": list, delete, create (the new key is shown once).
+struct ApiKeysView: View {
+ @Environment(Session.self) private var session
+
+ @State private var keys: [APIKey] = []
+ @State private var auth: Me.Auth?
+ @State private var loaded = false
+ @State private var busy = false
+ @State private var error: ErrorText?
+ @State private var showCreate = false
+ @State private var pendingSecret: APIKeyCreated?
+ @State private var secret: APIKeyCreated?
+ @State private var deleteKey: APIKey?
+
+ private var currentKeyId: Int? { auth?.type == .apiKey ? auth?.keyID : nil }
+
+ var body: some View {
+ content
+ .moreGradient(sheetShown: showCreate || secret != nil)
+ }
+
+ private var content: some View {
+ List {
+ if loaded {
+ Section {
+ Label {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(verbatim: infoTitle)
+ Text("A new key is shown only once after creating it. Keys give full access to your account; delete keys you no longer use.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ } icon: {
+ Image(systemName: "key")
+ }
+ }
+ if !keys.isEmpty {
+ Section("API keys (\(keys.count))") {
+ ForEach(keys) { row($0) }
+ }
+ }
+ }
+ }
+ .overlay {
+ if !loaded && error == nil { ProgressView() }
+ else if loaded && keys.isEmpty { ContentUnavailableView("No API keys yet.", systemImage: "key") }
+ }
+ .disabled(busy)
+ .navigationTitle("API keys")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if loaded {
+ ToolbarItem(placement: .primaryAction) {
+ if busy {
+ ProgressView()
+ } else {
+ Button("New API key", systemImage: "plus") { showCreate = true }
+ }
+ }.appVerticalPreferred()
+ }
+ }
+ .refreshable { await load() }
+ .task { await load() }
+ .alert("Delete API key?", isPresented: Binding(get: { deleteKey != nil }, set: { if !$0 { deleteKey = nil } }),
+ presenting: deleteKey) { key in
+ Button("Delete", role: .destructive) { Task { await delete(key) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { key in
+ Text("\"\(name(key))\" stops working immediately. Apps and scripts using it lose access.")
+ }
+ .sheet(isPresented: $showCreate, onDismiss: {
+ secret = pendingSecret
+ pendingSecret = nil
+ }) {
+ ApiKeyCreateSheet { created in
+ Task { await load() }
+ if created.token?.nonBlank == nil {
+ error = ErrorText(title: String(localized: "API key created"),
+ message: String(localized: "The server did not return the key. Delete it and try again."))
+ } else {
+ pendingSecret = created
+ }
+ }
+ }
+ .sheet(item: $secret) { created in
+ ApiKeySecretSheet(key: created)
+ }
+ .errorAlert($error)
+ }
+
+ private var infoTitle: String {
+ switch auth?.type {
+ case .apiKey:
+ let keyName = auth?.keyName?.nonBlank ?? "#" + (auth?.keyID.map(String.init) ?? "?")
+ return String(localized: "This app uses the API key \"\(keyName)\".")
+ case .accountKey: return String(localized: "This app uses your account key.")
+ default: return String(localized: "This app's key type is unknown.")
+ }
+ }
+
+ private func name(_ key: APIKey) -> String { key.name?.nonBlank ?? String(localized: "Unnamed key") }
+
+ private func row(_ key: APIKey) -> some View {
+ let current = key.id == currentKeyId
+ return VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ Text(verbatim: name(key)).font(.headline)
+ Spacer(minLength: 8)
+ if current { MoreTag(String(localized: "This app"), .blue) }
+ if key.expired == true { MoreTag(String(localized: "Expired"), .red) }
+ }
+ Text(verbatim: ApiKeyText.subtitle(key, current: current))
+ .font(.footnote.monospacedDigit()).foregroundStyle(.secondary)
+ }
+ .accessibilityElement(children: .combine)
+ .swipeActions(edge: .trailing, allowsFullSwipe: false) {
+ if !current {
+ Button("Delete API key", systemImage: "trash", role: .destructive) { deleteKey = key }
+ .labelStyle(.iconOnly)
+ .tint(.red)
+ }
+ }
+ }
+
+ private func delete(_ key: APIKey) async {
+ busy = true
+ defer { busy = false }
+ do {
+ try await session.api.apiKeys.delete(key.id)
+ keys.removeAll { $0.id == key.id }
+ } catch let failure as IPv64Error where failure.statusCode == 409 {
+ var detail = String(localized: "This key is used by this app and cannot be deleted.")
+ if case .api(let problem) = failure, let text = problem.detail.nonBlank { detail = text }
+ error = ErrorText(title: String(localized: "Key in use"), message: detail)
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func load() async {
+ do {
+ let me = try await session.api.account.me()
+ auth = me.auth
+ keys = try await session.api.apiKeys.list()
+ loaded = true
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
+
+/// "New API key" form sheet. Calls `onCreated` with the created key (including its one-time token).
+struct ApiKeyCreateSheet: View {
+ let onCreated: (APIKeyCreated) -> Void
+
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var name = ""
+ @State private var validity = ApiKeyText.defaultValidity
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ private var trimmed: String { name.trimmingCharacters(in: .whitespacesAndNewlines) }
+
+ var body: some View {
+ DynDNSSheet(title: "New API key", confirmLabel: "Create", confirmEnabled: !trimmed.isEmpty,
+ isBusy: busy, onConfirm: { Task { await create() } }) {
+ Section {
+ TextField("Name", text: $name, prompt: Text("e.g. Home Assistant"))
+ .onChange(of: name) { _, new in
+ if new.count > ApiKeyText.nameLimit { name = String(new.prefix(ApiKeyText.nameLimit)) }
+ }
+ } footer: {
+ Text(verbatim: "\(name.count) / \(ApiKeyText.nameLimit)")
+ }
+ Section {
+ Picker("Valid for", selection: $validity) {
+ ForEach(ApiKeyText.validity, id: \.seconds) { Text(verbatim: $0.label).tag($0.seconds) }
+ }
+ }
+ }
+ .errorAlert($error)
+ .appReadableWidth()
+ .presentationDetents([.medium, .large])
+ }
+
+ private func create() async {
+ busy = true
+ defer { busy = false }
+ do {
+ let created = try await session.api.apiKeys.create(name: trimmed, expiresIn: validity)
+ onCreated(created)
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
+
+/// Shows the new key exactly once; it cannot be swiped away, only closed with "Done".
+struct ApiKeySecretSheet: View {
+ let key: APIKeyCreated
+
+ var body: some View {
+ DynDNSSheet(title: "New API key") {
+ Section {
+ Label("Copy the key now and store it securely. It is shown only once and cannot be retrieved later.",
+ systemImage: "exclamationmark.triangle")
+ .foregroundStyle(.orange)
+ }
+ if let token = key.token?.nonBlank {
+ Section("Key") {
+ Text(verbatim: token).font(.body.monospaced()).textSelection(.enabled)
+ Button("Copy key", systemImage: "document.on.document") { Clipboard.copy(token, sensitive: true) }
+ }
+ }
+ }
+ .interactiveDismissDisabled()
+ .presentationDetents([.medium])
+ }
+}
diff --git a/IPv64/Views/More/HoneypotSections.swift b/IPv64/Views/More/HoneypotSections.swift
new file mode 100644
index 0000000..83712f8
--- /dev/null
+++ b/IPv64/Views/More/HoneypotSections.swift
@@ -0,0 +1,170 @@
+import SwiftUI
+import IPv64
+
+/// ipv64.net network numbers, charts and rankings. Empty sections stay hidden.
+struct HoneypotNetworkSections: View {
+ let stats: ThreatStats
+
+ var body: some View {
+ Section {
+ Grid(alignment: .topLeading, horizontalSpacing: 16, verticalSpacing: 12) {
+ GridRow {
+ MoreKpiTile("Sensors online", (stats.sensors?.online ?? 0).formatted())
+ MoreKpiTile("Attacks (24 h)", (stats.attacks24h?.events ?? 0).formatted())
+ }
+ Divider()
+ GridRow {
+ MoreKpiTile("Attacker IPs (24 h)", (stats.attacks24h?.sources ?? 0).formatted())
+ MoreKpiTile("Blocklist size", (stats.lists?["v64"] ?? 0).formatted())
+ }
+ }
+ .padding(.vertical, 4)
+ } header: {
+ Text("ipv64.net network")
+ }
+ let days = DayValue.parse((stats.timeline ?? []).map { ($0.day, $0.events) })
+ if !days.isEmpty { Section("Attacks per day (30 days)") { DayBarChart(days: days, color: .blue) } }
+ ranking("Most attacked ports (7 days)", (stats.topPorts ?? []).map {
+ ("\($0.service ?? "–") · \($0.port.map(String.init) ?? "–")", $0.events ?? 0, nil, false)
+ })
+ ranking("Most frequent attack kinds (7 days)", (stats.topKinds ?? []).map { ($0.kind ?? "–", $0.events ?? 0, nil, false) })
+ if let top = stats.top {
+ ranking("Origin of blocklist IPs", (top.countries ?? []).map {
+ (MoreLogic.countryFlag($0.country) ?? "–", $0.ips ?? 0, String(localized: "\($0.ips ?? 0) IPs"), false)
+ })
+ entries("User names", top.usernames, mono: true)
+ entries("Passwords", top.passwords, mono: true)
+ entries("Requested paths", top.paths, mono: true)
+ entries("User agents", top.userAgents, mono: false)
+ entries("Fingerprints (JA4/HASSH)", top.fingerprints, mono: true)
+ }
+ if let lists = stats.lists, !lists.isEmpty {
+ Section("List sizes") {
+ ForEach(lists.sorted { $0.key < $1.key }, id: \.key) { key, value in
+ LabeledContent(MoreLogic.prettyKey(key), value: value.formatted())
+ }
+ }
+ }
+ if stats.threshold?.accounts != nil || stats.info?.nonBlank != nil || stats.license?.nonBlank != nil {
+ Section {} footer: {
+ VStack(alignment: .leading, spacing: 4) {
+ if let accounts = stats.threshold?.accounts {
+ Text("Rankings and lists need at least \(accounts) reporting accounts.")
+ }
+ if let info = stats.info?.nonBlank { Text(verbatim: info) }
+ if let license = stats.license?.nonBlank { Text("License: \(license)") }
+ }
+ }
+ }
+ }
+
+ private func entries(_ title: LocalizedStringKey, _ list: [ThreatStatsEntry]?, mono: Bool) -> some View {
+ ranking(title, (list ?? []).compactMap { entry in
+ guard let value = entry.value?.nonBlank else { return nil }
+ var details = [String(localized: "\(entry.events ?? 0) attempts")]
+ if let accounts = entry.accounts { details.append(String(localized: "\(accounts) acc.")) }
+ return (value, entry.events ?? 0, details.joined(separator: " · "), mono)
+ })
+ }
+
+ @ViewBuilder private func ranking(_ title: LocalizedStringKey,
+ _ rows: [(label: String, value: Int, detail: String?, mono: Bool)]) -> some View {
+ if !rows.isEmpty {
+ let maxValue = rows.map(\.value).max() ?? 0
+ Section(title) {
+ ForEach(rows.indices, id: \.self) { i in
+ ModuleRankRow(label: rows[i].label, value: rows[i].value,
+ detail: rows[i].detail ?? rows[i].value.formatted(), maxValue: maxValue, mono: rows[i].mono)
+ }
+ }
+ }
+ }
+}
+
+/// Share of the own nodes that run the honeypot module.
+struct HoneypotNodeShare: View {
+ let nodes: [HC2Node]
+
+ var body: some View {
+ if !nodes.isEmpty {
+ let share = MoreLogic.honeypotShare(modules: nodes.map { $0.modules ?? [] })
+ Section("Your nodes") {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("\(share.active) of \(share.total) nodes run the honeypot").font(.subheadline.weight(.semibold))
+ ProgressView(value: share.fraction).tint(.orange)
+ }
+ .accessibilityElement(children: .combine)
+ }
+ }
+ }
+}
+
+/// Own contribution: numbers, daily chart and sensors.
+struct HoneypotContributionSections: View {
+ let stats: HoneypotStats
+ let sensors: [HoneypotSensor]
+
+ var body: some View {
+ Section {
+ HStack {
+ Text("Your contribution").font(.headline)
+ Spacer()
+ if stats.contributor == true { MoreTag(String(localized: "Contributor"), .green) }
+ else { MoreTag(String(localized: "Not contributing"), .gray) }
+ }
+ Grid(alignment: .topLeading, horizontalSpacing: 16, verticalSpacing: 12) {
+ GridRow {
+ MoreKpiTile("Sensors online", "\(stats.sensorsOnline ?? 0) / \(stats.sensors ?? 0)")
+ MoreKpiTile("Events (24 h)", (stats.events24h ?? 0).formatted())
+ }
+ Divider()
+ GridRow {
+ MoreKpiTile("Events (7 d)", (stats.events7d ?? 0).formatted())
+ MoreKpiTile("Sources (24 h)", (stats.sources24h ?? 0).formatted())
+ }
+ Divider()
+ GridRow {
+ MoreKpiTile("Sources (7 d)", (stats.sources7d ?? 0).formatted())
+ Color.clear.frame(height: 0)
+ }
+ }
+ .padding(.vertical, 4)
+ } footer: {
+ if let last = HcFormat.real(stats.lastReport) {
+ Text("Last report \(last.formatted(.relative(presentation: .named)))")
+ }
+ }
+ let days = DayValue.parse((stats.timeline ?? []).map { ($0.day, $0.events) })
+ if !days.isEmpty { Section("Events per day (7 days)") { DayBarChart(days: days, color: .orange) } }
+ if !sensors.isEmpty {
+ Section("Sensors") {
+ ForEach(sensors) { sensor in
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ Text(verbatim: MoreLogic.sensorTitle(sensor.id)).font(.headline)
+ Spacer(minLength: 8)
+ if sensor.disabled == true { MoreTag(String(localized: "Disabled"), .gray) }
+ else if sensor.online == true { MoreTag(String(localized: "Online"), .green) }
+ else { MoreTag(String(localized: "Offline"), .red) }
+ }
+ Text(verbatim: subtitle(sensor)).font(.footnote).foregroundStyle(.secondary)
+ }
+ .accessibilityElement(children: .combine)
+ }
+ }
+ }
+ }
+
+ private func subtitle(_ s: HoneypotSensor) -> String {
+ var lines: [String] = []
+ let profile = [s.profile, s.mode, s.version.map { "v\($0)" }].compactMap { $0?.nonBlank }.joined(separator: " · ")
+ if !profile.isEmpty { lines.append(String(localized: "Profile: \(profile)")) }
+ if let last = HcFormat.real(s.lastSeen) {
+ lines.append(String(localized: "Last report \(last.formatted(.relative(presentation: .named)))"))
+ }
+ lines.append(String(localized: "Reports: \(s.reports ?? 0)"))
+ lines.append(String(localized: "Events (24 h / 7 d): \(s.events24h ?? 0) / \(s.events7d ?? 0)"))
+ lines.append(String(localized: "Sources (24 h / 7 d): \(s.sources24h ?? 0) / \(s.sources7d ?? 0)"))
+ return lines.joined(separator: "\n")
+ }
+}
diff --git a/IPv64/Views/More/HoneypotView.swift b/IPv64/Views/More/HoneypotView.swift
new file mode 100644
index 0000000..0b784a4
--- /dev/null
+++ b/IPv64/Views/More/HoneypotView.swift
@@ -0,0 +1,128 @@
+import SwiftUI
+import IPv64
+
+/// "Honeypot": network numbers, own contribution, sensors and the list token (no live feed).
+struct HoneypotView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.scenePhase) private var scenePhase
+
+ @State private var cloud: ThreatStats?
+ @State private var nodes: [HC2Node]?
+ @State private var stats: HoneypotStats?
+ @State private var sensors: [HoneypotSensor] = []
+ @State private var loaded = false
+ @State private var error: ErrorText?
+
+ @State private var token: HoneypotListToken?
+ @State private var tokenRevealed = false
+ @State private var tokenBusy = false
+ @State private var tokenGeneration = 0
+ @State private var askToken = false
+
+ var body: some View {
+ List {
+ if loaded {
+ if let cloud { HoneypotNetworkSections(stats: cloud) }
+ if let nodes { HoneypotNodeShare(nodes: nodes) }
+ if let stats { HoneypotContributionSections(stats: stats, sensors: sensors) }
+ tokenSection
+ }
+ }
+ .overlay { if !loaded && error == nil { ProgressView() } }
+ .navigationTitle("Honeypot")
+ .navigationBarTitleDisplayMode(.inline)
+ .moreGradient()
+ .moreToolbarSpinner(tokenBusy)
+ .refreshable { await load() }
+ .task { await load() }
+ .onChange(of: scenePhase) { if scenePhase != .active { hideToken() } }
+ .onDisappear(perform: hideToken)
+ .alert("Show list token?", isPresented: $askToken) {
+ Button("Show token") { loadToken() }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("This creates your personal token if you do not have one yet. Keep it secret: anyone with the token can fetch your live blocklist.")
+ }
+ .errorAlert($error)
+ }
+
+ // MARK: Token
+
+ private var tokenSection: some View {
+ Section("Blocklist token") {
+ if let token {
+ HStack {
+ Text("List token").font(.subheadline.weight(.semibold))
+ Spacer()
+ if token.live { MoreTag(String(localized: "Live"), .green) } else { MoreTag(String(localized: "Daily list"), .orange) }
+ }
+ secretRow("Token", token.token)
+ if let url = MoreLogic.listURL(base: token.base) { secretRow("List URL", url) }
+ if !token.live {
+ Text("Live access is not available for your account right now. The list URL serves the daily state.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ Button("Hide", systemImage: "eye.slash", action: hideToken)
+ } else {
+ Text("Your personal token gives access to the live v64 blocklist.")
+ Button("Show list token", systemImage: "key") { askToken = true }.disabled(tokenBusy)
+ }
+ }
+ }
+
+ /// Masked until the eye is tapped; copying is always sensitive.
+ private func secretRow(_ label: LocalizedStringKey, _ value: String) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(label).font(.caption).foregroundStyle(.secondary)
+ HStack {
+ Text(verbatim: tokenRevealed ? value : String(repeating: "•", count: min(value.count, 24)))
+ .font(.body.monospaced()).lineLimit(3)
+ Spacer(minLength: 8)
+ Button(tokenRevealed ? "Hide" : "Show", systemImage: tokenRevealed ? "eye.slash" : "eye") { tokenRevealed.toggle() }
+ Button("Copy", systemImage: "document.on.document") { Clipboard.copy(value, sensitive: true) }
+ }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.borderless)
+ }
+ }
+
+ private func hideToken() {
+ tokenGeneration += 1
+ token = nil
+ tokenRevealed = false
+ tokenBusy = false
+ }
+
+ private func loadToken() {
+ tokenGeneration += 1
+ let mine = tokenGeneration
+ tokenBusy = true
+ Task {
+ defer { if mine == tokenGeneration { tokenBusy = false } }
+ do {
+ let result = try await ipv64Retrying { try await session.api.honeypot.listToken() }
+ if mine == tokenGeneration { token = result }
+ } catch is CancellationError {
+ } catch {
+ if mine == tokenGeneration { self.error = ErrorText(error) }
+ }
+ }
+ }
+
+ // MARK: Load
+
+ private func load() async {
+ do {
+ let own = try await ipv64Retrying { try await session.api.honeypot.stats() }
+ let list = try await ipv64Retrying { try await session.api.honeypot.sensors() }
+ stats = own
+ sensors = list
+ cloud = try? await session.api.threat.stats()
+ nodes = try? await session.api.hc2.nodes.list()
+ loaded = true
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+}
diff --git a/IPv64/Views/More/MoreComponents.swift b/IPv64/Views/More/MoreComponents.swift
new file mode 100644
index 0000000..2b35e93
--- /dev/null
+++ b/IPv64/Views/More/MoreComponents.swift
@@ -0,0 +1,178 @@
+import SwiftUI
+import Charts
+
+/// Gradient on full screens only; off while the screen presents a sheet.
+private struct MoreGradient: ViewModifier {
+ let sheetShown: Bool
+
+ func body(content: Content) -> some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(sheetShown ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+}
+
+extension View {
+ func moreGradient(sheetShown: Bool = false) -> some View { modifier(MoreGradient(sheetShown: sheetShown)) }
+
+ /// Spinner in the toolbar while something runs (loading again or an action).
+ func moreToolbarSpinner(_ busy: Bool) -> some View {
+ toolbar {
+ ToolbarItem(placement: .topBarTrailing) { if busy { ProgressView() } }.appVerticalPreferred()
+ }
+ }
+}
+
+struct MoreTag: View {
+ let text: String
+ let color: Color
+
+ init(_ text: String, _ color: Color) {
+ self.text = text
+ self.color = color
+ }
+
+ var body: some View {
+ Text(verbatim: text)
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(color)
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .background(color.opacity(0.15), in: Capsule())
+ .fixedSize()
+ }
+}
+
+/// KPI tile with a prominent number; stretches to the height of its grid row.
+struct MoreKpiTile: View {
+ let label: LocalizedStringKey
+ let value: String
+
+ init(_ label: LocalizedStringKey, _ value: String) {
+ self.label = label
+ self.value = value
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(label).font(.subheadline).foregroundStyle(.secondary)
+ Text(verbatim: value).font(.system(.title2, design: .rounded).weight(.bold)).lineLimit(1).minimumScaleFactor(0.6)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Wrapped, non-interactive capsule chips.
+struct MoreChips: View {
+ let values: [String]
+
+ var body: some View {
+ MoreWrapLayout(spacing: 6) {
+ ForEach(values, id: \.self) { value in
+ Text(verbatim: value).font(.subheadline)
+ .padding(.horizontal, 10).padding(.vertical, 4)
+ .background(Color(.tertiarySystemFill), in: Capsule())
+ }
+ }
+ }
+}
+
+private struct MoreWrapLayout: Layout {
+ var spacing: CGFloat
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ CGSize(width: proposal.width ?? 300, height: arrange(width: proposal.width ?? 300, subviews).height)
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ for (index, origin) in arrange(width: bounds.width, subviews).origins.enumerated() {
+ subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)
+ }
+ }
+
+ private func arrange(width: CGFloat, _ subviews: Subviews) -> (origins: [CGPoint], height: CGFloat) {
+ var origins: [CGPoint] = []
+ var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0
+ for subview in subviews {
+ let size = subview.sizeThatFits(.unspecified)
+ if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }
+ origins.append(CGPoint(x: x, y: y))
+ x += size.width + spacing
+ rowHeight = max(rowHeight, size.height)
+ }
+ return (origins, y + rowHeight)
+ }
+}
+
+struct DayValue: Identifiable {
+ let day: Date
+ let value: Int
+ var id: Date { day }
+
+ /// "2026-10-20" entries; unreadable days are skipped.
+ static func parse(_ entries: [(day: String?, events: Int?)]) -> [DayValue] {
+ let format = Date.ISO8601FormatStyle(timeZone: .gmt).year().month().day()
+ return entries.compactMap { entry in
+ guard let text = entry.day, let date = try? Date(text, strategy: format) else { return nil }
+ return DayValue(day: date, value: entry.events ?? 0)
+ }
+ .sorted { $0.day < $1.day }
+ }
+}
+
+private func moreDay(_ date: Date) -> String {
+ date.formatted(Date.VerbatimFormatStyle(format: "\(day: .twoDigits).\(month: .twoDigits).\(year: .padded(4))",
+ timeZone: .gmt, calendar: Calendar(identifier: .gregorian)))
+}
+
+/// Line per day; touching the chart shows the day and value above it and marks the point.
+struct DayBarChart: View {
+ let days: [DayValue]
+ let color: Color
+ @State private var rawSelection: Date?
+
+ private var selected: DayValue? {
+ guard let raw = rawSelection else { return nil }
+ return days.min { abs($0.day.timeIntervalSince(raw)) < abs($1.day.timeIntervalSince(raw)) }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Group {
+ if let selected {
+ Text(verbatim: "\(moreDay(selected.day)) · ") + Text("\(selected.value.formatted()) events")
+ } else {
+ Text("Touch the chart for values")
+ }
+ }
+ .font(.caption).foregroundStyle(.secondary)
+ Chart {
+ ForEach(days) { item in
+ BarMark(x: .value("Day", item.day, unit: .day), y: .value("Events", item.value))
+ .foregroundStyle(color.opacity(selected == nil || selected?.id == item.id ? 1 : 0.35))
+ }
+ }
+ .chartYScale(domain: 0...max(days.map(\.value).max() ?? 0, 1))
+ .chartXAxis(.hidden)
+ .chartYAxis {
+ AxisMarks(values: .automatic(desiredCount: 3)) {
+ AxisGridLine().foregroundStyle(.secondary.opacity(0.2))
+ AxisValueLabel()
+ }
+ }
+ .chartXSelection(value: $rawSelection)
+ .frame(height: 140)
+ .accessibilityLabel(Text("Line chart with \(days.count) values, maximum \((days.map(\.value).max() ?? 0).formatted())"))
+ if let first = days.first, let last = days.last {
+ HStack {
+ Text(verbatim: moreDay(first.day))
+ Spacer()
+ if last.day != first.day { Text(verbatim: moreDay(last.day)) }
+ }
+ .font(.caption2).foregroundStyle(.secondary)
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/More/PasswordCheckView.swift b/IPv64/Views/More/PasswordCheckView.swift
new file mode 100644
index 0000000..524f3b2
--- /dev/null
+++ b/IPv64/Views/More/PasswordCheckView.swift
@@ -0,0 +1,88 @@
+import SwiftUI
+import IPv64
+
+/// "Password check": SHA-1 on the device, only the first 5 characters of the hash are sent.
+struct PasswordCheckView: View {
+ @Environment(Session.self) private var session
+ @Environment(\.scenePhase) private var scenePhase
+
+ @State private var password = ""
+ @State private var revealed = false
+ @State private var result: Int?
+ @State private var busy = false
+ @State private var generation = 0
+ @State private var error: ErrorText?
+
+ var body: some View {
+ Form {
+ Section {
+ Text("Find out whether a password was tried by attackers at Honeypot64 sensors. The password is hashed on your device (SHA-1) and only the first 5 characters of the hash are sent. The password itself never leaves your device.")
+ .font(.subheadline).foregroundStyle(.secondary)
+ }
+ Section {
+ HStack {
+ Group {
+ if revealed { TextField("Password", text: $password) } else { SecureField("Password", text: $password) }
+ }
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .submitLabel(.search)
+ .onSubmit(check)
+ Button(revealed ? "Hide password" : "Show password", systemImage: revealed ? "eye.slash" : "eye") {
+ revealed.toggle()
+ }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.borderless)
+ }
+ Button("Check password", action: check).disabled(password.isEmpty || busy)
+ if !password.isEmpty {
+ Button("Clear", role: .destructive, action: clear)
+ }
+ }
+ if let result {
+ Section("Result") {
+ MoreTag(result > 0 ? String(localized: "Found in attacks") : String(localized: "Not found"),
+ result > 0 ? .red : .green)
+ Text(result > 0
+ ? "This password was used \(result.formatted()) times in attacks. Do not use it and change it everywhere you use it."
+ : "This password was not seen in the Honeypot64 data. That does not mean it is safe: use long, unique passwords and a password manager.")
+ }
+ }
+ }
+ .navigationTitle("Password check")
+ .navigationBarTitleDisplayMode(.inline)
+ .moreGradient()
+ .moreToolbarSpinner(busy)
+ .onChange(of: password) { result = nil }
+ .onChange(of: scenePhase) { if scenePhase != .active { clear() } }
+ .onDisappear(perform: clear)
+ .errorAlert($error)
+ }
+
+ private func clear() {
+ generation += 1
+ password = ""
+ revealed = false
+ result = nil
+ busy = false
+ }
+
+ private func check() {
+ guard !password.isEmpty, !busy else { return }
+ generation += 1
+ let mine = generation
+ let (prefix, suffix) = MoreLogic.prefixAndSuffix(password)
+ busy = true
+ Task {
+ defer { if mine == generation { busy = false } }
+ do {
+ let entries = try await ipv64Retrying { try await session.api.threat.passwordRangeEntries(prefix: prefix) }
+ guard mine == generation else { return }
+ result = MoreLogic.count(forSuffix: suffix, in: entries.map { ($0.suffix, $0.count) })
+ } catch is CancellationError {
+ } catch {
+ if mine == generation { self.error = ErrorText(error) }
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/More/ThreatLookupView.swift b/IPv64/Views/More/ThreatLookupView.swift
new file mode 100644
index 0000000..502038c
--- /dev/null
+++ b/IPv64/Views/More/ThreatLookupView.swift
@@ -0,0 +1,191 @@
+import SwiftUI
+import IPv64
+
+/// "IP lookup & My IP": own addresses on top, search below, result underneath.
+struct ThreatLookupView: View {
+ /// Looked up immediately when given.
+ var ip: String? = nil
+
+ @Environment(Session.self) private var session
+
+ @State private var ipv4: String?
+ @State private var ipv6: String?
+ @State private var loadingOwn = true
+ @State private var query = ""
+ @State private var fieldError: String?
+ @State private var result: ThreatIP?
+ @State private var isLooking = false
+ @State private var error: ErrorText?
+ @FocusState private var focused: Bool
+
+ var body: some View {
+ List {
+ Section("Your public IP") {
+ ownRow(ipv4, family: "IPv4")
+ ownRow(ipv6, family: "IPv6")
+ }
+ Section {
+ HStack {
+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
+ TextField("IP address", text: $query)
+ .keyboardType(.URL)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .submitLabel(.search)
+ .focused($focused)
+ .onSubmit { lookup(query) }
+ Button("Look up", systemImage: "arrow.right.circle") { lookup(query) }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.borderless)
+ .disabled(isLooking)
+ }
+ } footer: {
+ if let fieldError { Text(verbatim: fieldError).foregroundStyle(.red) }
+ }
+ if let result { ThreatResultSections(result: result) }
+ }
+ .navigationTitle("IP lookup & My IP")
+ .navigationBarTitleDisplayMode(.inline)
+ .moreGradient()
+ .moreToolbarSpinner(isLooking)
+ .task { await loadOwn() }
+ .task { if let ip { lookup(ip) } }
+ .errorAlert($error)
+ }
+
+ private func ownRow(_ address: String?, family: String) -> some View {
+ HStack(spacing: 20) {
+ VStack(alignment: .leading, spacing: 2) {
+ if let address {
+ Text(verbatim: address).font(.body.monospaced())
+ } else if loadingOwn {
+ ProgressView()
+ } else {
+ Text("Not available").foregroundStyle(.secondary)
+ }
+ Text(verbatim: family).font(.subheadline).foregroundStyle(.secondary)
+ }
+ Spacer()
+ if let address {
+ Button("Copy", systemImage: "document.on.document") { Clipboard.copy(address) }
+ .labelStyle(.iconOnly)
+ Button("Look up") { lookup(address) }
+ .disabled(isLooking)
+ }
+ }
+ .buttonStyle(.borderless)
+ }
+
+ private func loadOwn() async {
+ async let v4 = session.myIP(.v4)
+ async let v6 = session.myIP(.v6)
+ ipv4 = await v4
+ ipv6 = await v6
+ loadingOwn = false
+ }
+
+ private func lookup(_ raw: String) {
+ let normalized = MoreLogic.normalizeIpInput(raw)
+ guard MoreLogic.isValidIP(normalized) else {
+ fieldError = String(localized: "Enter a valid IPv4 or IPv6 address.")
+ return
+ }
+ fieldError = nil
+ result = nil
+ query = normalized
+ focused = false
+ isLooking = true
+ Task {
+ defer { isLooking = false }
+ do {
+ result = try await ipv64Retrying { try await session.api.threat.ip(normalized) }
+ } catch is CancellationError {
+ } catch let failure as IPv64Error where failure.statusCode == 422 {
+ var text = String(localized: "This is not a valid public IP address.")
+ if case .api(let problem) = failure, let detail = problem.detail.nonBlank { text = detail }
+ fieldError = text
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+}
+
+/// Result sections of an IP lookup; empty rows and sections stay hidden.
+struct ThreatResultSections: View {
+ let result: ThreatIP
+ @Environment(\.openURL) private var openURL
+
+ private var status: (text: String, color: Color) {
+ switch result.status {
+ case .listed: (String(localized: "Listed"), .red)
+ case .notListed: (String(localized: "Not listed"), .green)
+ case .released: (String(localized: "Released"), .orange)
+ case .allowlisted: (String(localized: "Allowlisted"), .teal)
+ default: result.listed == true ? (String(localized: "Listed"), .red) : (String(localized: "Not listed"), .green)
+ }
+ }
+
+ var body: some View {
+ Section("Result") {
+ HStack {
+ Text(verbatim: result.ip ?? "").font(.body.monospaced()).textSelection(.enabled)
+ Spacer()
+ MoreTag(status.text, status.color)
+ }
+ if let score = result.score {
+ let value = min(max(score, 0), 100)
+ VStack(alignment: .leading, spacing: 6) {
+ Text(verbatim: "\(value) / 100").font(.system(size: 40, weight: .bold, design: .rounded))
+ Text("Score").font(.caption).foregroundStyle(.secondary)
+ ProgressView(value: Double(value), total: 100).tint(status.color)
+ }
+ .accessibilityElement(children: .combine)
+ }
+ row("Family", result.family.map { "IPv\($0)" })
+ row("Reporting accounts", result.accounts.map { $0.formatted() })
+ row("Country", MoreLogic.countryFlag(result.country))
+ row("ASN", result.asn.map { "AS\($0)" })
+ row("First seen", result.firstSeen)
+ row("Last seen", result.lastSeen)
+ row("Release", releaseText)
+ row("Release valid until", HcFormat.time(result.release?.protectedUntil))
+ }
+ if let lists = result.lists, !lists.isEmpty { Section("Lists") { MoreChips(values: lists.map(\.rawValue)) } }
+ if let kinds = result.kinds, !kinds.isEmpty { Section("Attack kinds") { MoreChips(values: kinds) } }
+ if let ports = result.ports, !ports.isEmpty {
+ Section {
+ ForEach(Array(ports.enumerated()), id: \.offset) { _, port in
+ LabeledContent(port.service ?? "–") { Text(verbatim: port.port.map(String.init) ?? "–").font(.body.monospaced()) }
+ }
+ } header: {
+ Text("Attacked ports")
+ } footer: {
+ Text("Only ports reported by at least two accounts are shown.")
+ }
+ }
+ if result.status == .notListed, result.listed != true {
+ Section { Text("No further details are available for IPs that are not listed.").foregroundStyle(.secondary) }
+ }
+ if let details = result.details, details.hasPrefix("https://"), let url = URL(string: details) {
+ Section {
+ Button("Explanation and release request", systemImage: "arrow.up.right.square") { openURL(url) }
+ }
+ }
+ }
+
+ @ViewBuilder private func row(_ label: LocalizedStringKey, _ value: String?) -> some View {
+ if let value = value?.nonBlank { LabeledContent(label, value: value) }
+ }
+
+ private var releaseText: String? {
+ switch result.release?.status {
+ case .none?: String(localized: "No release")
+ case .inReview?: String(localized: "In review")
+ case .released?: String(localized: "Released")
+ case .allowlisted?: String(localized: "Allowlisted")
+ case .rejected?: String(localized: "Rejected")
+ default: nil
+ }
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeDetailActions.swift b/IPv64/Views/Nodes/NodeDetailActions.swift
new file mode 100644
index 0000000..2bc89a9
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeDetailActions.swift
@@ -0,0 +1,244 @@
+import SwiftUI
+import IPv64
+
+// Loading, live tick, modules, commands, forget and unlink of the node detail.
+extension NodeDetailView {
+ /// The first live request starts at once, next to the cloud request; the 5 s tick follows.
+ func start() async {
+ access = nodes.access(for: nodeId)
+ async let live: Void = tick(force: true)
+ await loadCloud()
+ await live
+ }
+
+ func loadCloud() async {
+ let api = session.api
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ let detail = try await ipv64Retrying { try await api.hc2.nodes.get(nodeId) }
+ info = NodeInfo(detail)
+ directOnly = false
+ planReason = nil
+ loadFailed = false
+ } catch is CancellationError {
+ } catch {
+ let status = (error as? IPv64Error)?.statusCode
+ if isLocal, status == 404 || status == 403 {
+ // Not linked to the account (or nodes not in the plan): a directly connected node only.
+ directOnly = true
+ if info == nil { info = NodeInfo(name: LocalNodeStore.name(nodeId)) }
+ loadFailed = false
+ } else if status == 403 {
+ if case .api(let problem)? = error as? IPv64Error, let detail = problem.detail.nonBlank {
+ planReason = detail
+ } else {
+ planReason = String(localized: "This feature is not available on your plan.")
+ }
+ } else {
+ if info == nil { loadFailed = true }
+ self.error = ErrorText(error)
+ }
+ }
+ }
+
+ /// Pull to refresh: cloud, live data and the open command history.
+ func refresh() async {
+ await loadCloud()
+ await tick(force: true)
+ if historyOpen && tracking == nil { await loadCommands() }
+ }
+
+ /// Alerts wait until the sheet is gone: a resolve command gets confirmed, the unlink result is shown.
+ func sheetClosed() {
+ if let command = pendingCommand {
+ pendingCommand = nil
+ confirmCommand = command
+ }
+ if let pendingError {
+ self.pendingError = nil
+ error = pendingError
+ }
+ if let pendingUnlink {
+ self.pendingUnlink = nil
+ unlinkText = pendingUnlink
+ }
+ }
+
+ /// After the connection sheet: a changed direct access is read again.
+ func reloadAccess() {
+ let stored = nodes.access(for: nodeId)
+ if stored != access {
+ access = stored
+ live = NodeLive()
+ }
+ }
+
+ // MARK: Live
+
+ /// Every 5 s (first at once) while the screen is visible and the app active.
+ func tickLoop() async {
+ guard isLocal, scenePhase == .active else { return }
+ // The first request comes from start() (or right here after returning to the app).
+ if live.lastOk != nil { await tick(force: false) }
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(5))
+ if Task.isCancelled { return }
+ await tick(force: false)
+ }
+ }
+
+ /// Silent live refresh: `status()` then `logs(100)`; skipped while an action or another refresh runs.
+ func tick(force: Bool) async {
+ guard let config = access, !isTicking, force || !busy,
+ let client = NodeClientFactory.client(for: config) else { return }
+ isTicking = true
+ defer { isTicking = false }
+ do {
+ // Status first: the screen shows the node as connected without waiting for the (slower) logs.
+ let status = try await client.node.status()
+ guard access == config else { return }
+ if let name = status.node?.name?.nonBlank, name != LocalNodeStore.name(nodeId) {
+ LocalNodeStore.setName(nodeId, name)
+ nodes.push(nodeId)
+ }
+ if let modules = status.modules { LocalNodeStore.saveModules(nodeId, modules: modules) }
+ nodes.refresh()
+ live = NodeLive(status: status, logs: live.logs, lastOk: .now, failing: false, rejected: nil)
+ if let logs = try? await client.node.logs(lines: 100).lines, access == config {
+ live.logs = logs.reversed().map(NodesLogic.logText)
+ }
+ } catch is CancellationError {
+ } catch {
+ guard access == config else { return }
+ live.failing = true
+ live.rejected = NodesLogic.isAuthRejection(error) ? ErrorText.node(error).title : nil
+ }
+ }
+
+ // MARK: Modules
+
+ func toggleModule(_ name: String, enable: Bool) {
+ if enable {
+ Task { await setModule(name, enable: true) }
+ } else {
+ confirmDisable = name
+ }
+ }
+
+ func setModule(_ name: String, enable: Bool) async {
+ guard let config = access, let client = NodeClientFactory.client(for: config) else { return }
+ busy = true
+ defer { busy = false }
+ do {
+ if enable {
+ _ = try await client.node.modules.enable(name)
+ } else {
+ _ = try await client.node.modules.disable(name)
+ }
+ let status = try await client.node.status()
+ guard access == config else { return }
+ if let modules = status.modules { LocalNodeStore.saveModules(nodeId, modules: modules) }
+ live.status = status
+ nodes.refresh()
+ await nodes.refreshModules()
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText.node(error)
+ }
+ }
+
+ // MARK: Commands
+
+ func send(_ command: NodeCommand) async {
+ let api = session.api
+ busy = true
+ defer { busy = false }
+ do {
+ let args = command.args == HC2CommandArguments() ? nil : command.args
+ let sent = try await ipv64Retrying { try await api.hc2.nodes.sendCommand(nodeId, name: command.name, arguments: args) }
+ historyOpen = true
+ historyLoaded = true
+ commands.insert(sent, at: 0)
+ tracking = sent.commandID
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ func loadCommands() async {
+ let api = session.api
+ historyLoading = true
+ defer { historyLoading = false }
+ do {
+ commands = try await ipv64Retrying { try await api.hc2.nodes.commands(nodeId, limit: 20) }
+ historyLoaded = true
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ /// Polls every 3 s for up to 60 s until the sent command is done; the screen stays usable meanwhile.
+ func trackCommand() async {
+ guard let id = tracking else { return }
+ let api = session.api
+ var finished: HC2Command?
+ do {
+ for _ in 0..<20 {
+ try await Task.sleep(for: .seconds(3))
+ let list = try await ipv64Retrying { try await api.hc2.nodes.commands(nodeId, limit: 20) }
+ commands = list
+ finished = list.first { $0.commandID == id && $0.doneAt != nil }
+ if finished != nil { break }
+ }
+ } catch is CancellationError {
+ return
+ } catch {
+ self.error = ErrorText(error)
+ tracking = nil
+ return
+ }
+ if let finished {
+ if finished.ok == false {
+ error = ErrorText(title: String(localized: "Command failed"),
+ message: HcFormat.commandOutput(finished.output) ?? String(localized: "The node reported an error."))
+ }
+ } else {
+ error = ErrorText(title: String(localized: "Command still pending"),
+ message: String(localized: "The node has not reported back yet. It runs the command as soon as it syncs. Open the command history later to see the result."))
+ }
+ await loadCloud()
+ // Last: clearing `tracking` cancels this task.
+ tracking = nil
+ }
+
+ // MARK: Forget / unlink
+
+ func forget() {
+ nodes.forget(nodeId)
+ nodes.refresh()
+ onChanged()
+ if directOnly {
+ dismiss()
+ } else {
+ access = nil
+ live = NodeLive()
+ }
+ }
+
+ func handleUnlink(_ result: HC2NodeUnlinkResult) {
+ if result.unlinked == false {
+ pendingError = ErrorText(title: String(localized: "Node not unlinked"),
+ message: String(localized: "The server did not unlink the node. Please try again."))
+ return
+ }
+ tracking = nil
+ // The stored direct access stays; live updates stop.
+ access = nil
+ live = NodeLive()
+ onChanged()
+ pendingUnlink = NodesLogic.unlinkSummary(kept: result.checksKeptOnline ?? 0, deleted: result.checksDeleted ?? 0)
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeDetailModels.swift b/IPv64/Views/Nodes/NodeDetailModels.swift
new file mode 100644
index 0000000..0ca282b
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeDetailModels.swift
@@ -0,0 +1,92 @@
+import Foundation
+import IPv64
+
+/// Pushed from the Nodes list.
+struct NodeRoute: Hashable {
+ let id: String
+}
+
+/// Display data of a node: cloud detail (or a placeholder for direct-only nodes), merged with edits.
+struct NodeInfo: Equatable {
+ var name: String?
+ var location: String?
+ var timezone: String?
+ var version: String?
+ var hub: String?
+ var modules: [String] = []
+ var remote: String?
+ var online: Bool?
+ var lastSeen: Date?
+ var lastSync: Date?
+ var linkedAt: Date?
+ var outbox: Int?
+ var conflicts: Int?
+ var checks: [HC2Check] = []
+
+ init(name: String?) { self.name = name }
+
+ init(_ d: HC2NodeDetail) {
+ name = d.name; location = d.location; timezone = d.timezone; version = d.version; hub = d.hub
+ modules = d.modules ?? []; remote = d.remoteMgmt?.rawValue; online = d.online
+ lastSeen = d.lastSeen; lastSync = d.lastSync; linkedAt = d.linkedAt
+ outbox = d.outboxSize; conflicts = d.conflicts; checks = d.checks ?? []
+ }
+
+ /// Android `withUpdate`: response values win, missing keep the old; modules only if non-empty.
+ func merged(with n: HC2Node) -> NodeInfo {
+ var copy = self
+ copy.name = n.name ?? name
+ copy.location = n.location ?? location
+ copy.timezone = n.timezone ?? timezone
+ copy.version = n.version ?? version
+ copy.hub = n.hub ?? hub
+ if let modules = n.modules, !modules.isEmpty { copy.modules = modules }
+ copy.remote = n.remoteMgmt?.rawValue ?? remote
+ copy.online = n.online ?? online
+ copy.lastSeen = n.lastSeen ?? lastSeen
+ copy.lastSync = n.lastSync ?? lastSync
+ copy.outbox = n.outboxSize ?? outbox
+ copy.conflicts = n.conflicts ?? conflicts
+ return copy
+ }
+}
+
+/// Live data over the stored direct connection.
+struct NodeLive: Equatable {
+ var status: Node64.NodeStatus?
+ /// Newest first.
+ var logs: [String] = []
+ var lastOk: Date?
+ var failing = false
+ /// Title of the last 401/403 error ("API key rejected"), if that was the last failure.
+ var rejected: String?
+}
+
+/// A command to send; `targetLabel` is the check name used in texts.
+struct NodeCommand: Identifiable {
+ let id = UUID()
+ let name: HC2CommandName
+ var args = HC2CommandArguments()
+ var targetLabel: String?
+
+ var label: String { NodesLogic.commandLabel(name.rawValue) }
+
+ func confirmText(nodeName: String) -> String {
+ let target = targetLabel ?? "…"
+ switch name {
+ case .runCheck: return String(localized: "\(nodeName) is asked to run the check \"\(target)\" now.")
+ case .pause: return String(localized: "\(nodeName) is asked to pause the check \"\(target)\". It stays paused until you resume it.")
+ case .resume: return String(localized: "\(nodeName) is asked to resume the check \"\(target)\".")
+ case .repair: return String(localized: "\(nodeName) is asked to run its repair routine.")
+ default:
+ let number = args.id.map(String.init) ?? "?"
+ let side = args.keep?.rawValue ?? "server"
+ return String(localized: "Conflict #\(number) is resolved by keeping the \(side) version. The other version is discarded.")
+ }
+ }
+
+ static func forCheck(_ name: HC2CommandName, _ check: HC2Check) -> NodeCommand {
+ NodeCommand(name: name, args: HC2CommandArguments(token: check.token),
+ targetLabel: check.name?.nonBlank ?? "…" + String(check.token.suffix(4)))
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeDetailSections.swift b/IPv64/Views/Nodes/NodeDetailSections.swift
new file mode 100644
index 0000000..1cdcf91
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeDetailSections.swift
@@ -0,0 +1,371 @@
+import SwiftUI
+import IPv64
+
+// List sections of the node detail; empty sections are left out.
+extension NodeDetailView {
+ @ViewBuilder func sections(_ info: NodeInfo) -> some View {
+ headerSection(info)
+ statusSection(info)
+ modulesSection(info)
+ if !directOnly && !info.checks.isEmpty { checksSection(info) }
+ if isLocal, live.status != nil, !live.logs.isEmpty { NodeLogsSection(lines: live.logs) }
+ if !directOnly { commandsSection(info) }
+ detailsSection(info)
+ }
+
+ // MARK: Header
+
+ private func headerSection(_ info: NodeInfo) -> some View {
+ let version = (localNode?.version?.nonBlank ?? info.version?.nonBlank).map { "v" + $0 }
+ let source: String? = if let config = access {
+ String(localized: "Direct \(LocalNodeURL.host(of: config.url) ?? config.url)")
+ } else {
+ [String(localized: "Cloud"),
+ HcFormat.real(info.lastSeen).map { String(localized: "seen \($0.formatted(.relative(presentation: .named)))") }]
+ .compactMap { $0 }.joined(separator: " · ")
+ }
+ let subtitle = [version, source].compactMap { $0 }.joined(separator: " · ")
+ return Section {
+ if isLocal && live.failing {
+ Text(live.rejected ?? String(localized: "Connection lost — retrying…")).foregroundStyle(.red)
+ }
+ if let other = otherNodeId {
+ Text("This address belongs to another node (\(other)). Forget the direct connection and connect again.")
+ .foregroundStyle(.red)
+ }
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(displayName).font(.headline)
+ Text(subtitle).font(.subheadline).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ headerTag(info)
+ }
+ .accessibilityElement(children: .combine)
+ if isLocal { liveLines }
+ }
+ }
+
+ @ViewBuilder private func headerTag(_ info: NodeInfo) -> some View {
+ if isLocal {
+ switch NodesLogic.LiveState.from(lastOk: live.lastOk, active: scenePhase == .active, failing: live.failing) {
+ case .connecting: HealthcheckTag(text: "Connecting", color: .gray)
+ case .paused: HealthcheckTag(text: "Paused", color: .gray)
+ case .offline: HealthcheckTag(text: "Offline", color: .red)
+ case .live: HealthcheckTag(text: "Live", color: .green)
+ }
+ } else if info.online == true {
+ HealthcheckTag(text: "Online", color: .green)
+ } else {
+ HealthcheckTag(text: "Offline", color: .gray)
+ }
+ }
+
+ @ViewBuilder private var liveLines: some View {
+ if let lastOk = live.lastOk {
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ Text(NodesLogic.updatedText(since: lastOk, now: context.date)).font(.footnote).foregroundStyle(.secondary)
+ }
+ }
+ if let lastError = live.status?.link?.lastError?.nonBlank {
+ Text("Last error: \(lastError)").font(.footnote).foregroundStyle(.red)
+ }
+ }
+
+ // MARK: Status (prominent value + rows, like the healthcheck statistics)
+
+ private func statusSection(_ info: NodeInfo) -> some View {
+ let outbox = live.status?.link?.outbox ?? info.outbox
+ let conflictCount = live.status?.link?.conflicts ?? info.conflicts
+ let main: (value: String, label: LocalizedStringKey) = isLocal
+ ? (localNode?.uptimeSeconds.map { HcFormat.duration(seconds: $0) } ?? "–", "Uptime")
+ : (HcFormat.real(info.lastSync).map { $0.formatted(.relative(presentation: .named)) } ?? "–", "Last sync")
+ return Section("Status") {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(main.value).font(.system(size: 40, weight: .bold, design: .rounded)).lineLimit(1).minimumScaleFactor(0.5)
+ Text(main.label).font(.caption).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ if !directOnly { LabeledContent("Checks", value: info.checks.count.formatted()) }
+ if let outbox { LabeledContent("Outbox", value: outbox.formatted()) }
+ if let conflictCount {
+ LabeledContent("Conflicts") {
+ Text(conflictCount.formatted()).foregroundStyle(conflictCount > 0 ? Color.red : Color.secondary)
+ }
+ }
+ }
+ }
+
+ // MARK: Modules
+
+ @ViewBuilder private func modulesSection(_ info: NodeInfo) -> some View {
+ if isLocal, let modules = live.status?.modules, !modules.isEmpty {
+ Section("Modules (\(modules.count))") {
+ ForEach(modules) { module in
+ let screen = NodeModuleView.hasScreen(module.name) && module.enabled == true && otherNodeId == nil
+ NodeModuleRow(module: module, disabled: busy || otherNodeId != nil,
+ onOpen: screen ? { moduleScreen = module.name } : nil) { toggleModule(module.name, enable: $0) }
+ }
+ }
+ } else if !info.modules.isEmpty {
+ Section {
+ ForEach(info.modules, id: \.self) { Text($0) }
+ } header: {
+ Text("Modules (\(info.modules.count))")
+ } footer: {
+ if !isLocal { Text("Set up direct access to switch modules.") }
+ }
+ }
+ }
+
+ // MARK: Checks
+
+ private func checksSection(_ info: NodeInfo) -> some View {
+ Section {
+ ForEach(info.checks) { check in
+ NavigationLink(value: HealthcheckRoute(token: check.token)) { HealthcheckItemView(check: check) }
+ .swipeActions {
+ if canCommand {
+ Group {
+ Button("Run check", systemImage: "arrow.clockwise") { confirmCommand = .forCheck(.runCheck, check) }
+ .tint(.blue)
+ if check.paused == true {
+ Button("Resume check", systemImage: "play") { confirmCommand = .forCheck(.resume, check) }
+ .tint(.green)
+ } else {
+ Button("Pause check", systemImage: "pause") { confirmCommand = .forCheck(.pause, check) }
+ .tint(.teal)
+ }
+ }
+ .labelStyle(.iconOnly)
+ .disabled(tracking != nil)
+ }
+ }
+ }
+ } header: {
+ Text("Checks (\(info.checks.count))")
+ } footer: {
+ if canCommand && info.online != true {
+ Text("The node is offline. Commands are picked up when it reconnects.")
+ }
+ }
+ }
+
+ // MARK: Commands
+
+ @ViewBuilder private func commandsSection(_ info: NodeInfo) -> some View {
+ if tracking != nil {
+ Section {
+ HStack(spacing: 8) {
+ ProgressView()
+ Text("Waiting for the node to run the command…").foregroundStyle(.secondary)
+ }
+ }
+ }
+ HcCollapsibleSection(title: "Command history", isExpanded: $historyOpen) {
+ if historyLoading && !historyLoaded {
+ ProgressView().frame(maxWidth: .infinity)
+ } else if commands.isEmpty {
+ Text("No commands sent yet.").foregroundStyle(.secondary)
+ }
+ ForEach(commands) { command in
+ NodeCommandRow(command: command) { token in
+ info.checks.first { $0.token == token }?.name?.nonBlank ?? String(localized: "Unknown check …\(String(token.suffix(4)))")
+ }
+ }
+ }
+ }
+
+ // MARK: Details
+
+ private func detailsSection(_ info: NodeInfo) -> some View {
+ HcCollapsibleSection(title: "Details", isExpanded: $detailsOpen) {
+ NodeInfoRow("Node ID", nodeId, copyable: true)
+ NodeInfoRow("Location", localNode?.location?.nonBlank ?? info.location)
+ NodeInfoRow("Time zone", localNode?.timezone?.nonBlank ?? info.timezone)
+ NodeInfoRow("Hub", info.hub)
+ NodeInfoRow("Linked", HcFormat.time(info.linkedAt))
+ NodeInfoRow("Remote management", directOnly ? nil : NodesLogic.remoteLabel(info.remote))
+ NodeInfoRow("Started", HcFormat.time(localNode?.startedAt))
+ NodeInfoRow("Database", localNode?.databaseBytes.map { Int64($0).formatted(.byteCount(style: .file)) })
+ NodeInfoRow("Direct address", access?.url, copyable: true)
+ }
+ }
+}
+
+// MARK: - Rows
+
+/// `LabeledContent` that disappears for blank values; copyable ones are monospaced with a Copy menu.
+private struct NodeInfoRow: View {
+ let label: LocalizedStringKey
+ let value: String?
+ var copyable = false
+
+ init(_ label: LocalizedStringKey, _ value: String?, copyable: Bool = false) {
+ self.label = label
+ self.value = value?.nonBlank
+ self.copyable = copyable
+ }
+
+ var body: some View {
+ if let value {
+ LabeledContent(label) {
+ Text(value).font(copyable ? .footnote.monospaced() : .body).textSelection(.enabled)
+ }
+ .contextMenu {
+ if copyable { Button("Copy", systemImage: "doc.on.doc") { Clipboard.copy(value) } }
+ }
+ }
+ }
+}
+
+private struct NodeModuleRow: View {
+ let module: Node64.ModuleStatus
+ let disabled: Bool
+ /// `nil` = the module has no screen here.
+ let onOpen: (() -> Void)?
+ let onToggle: (Bool) -> Void
+
+ private var state: (text: LocalizedStringKey, color: Color) {
+ if module.enabled == false { return ("Disabled", .secondary) }
+ return module.running == true ? ("Running", .green) : ("Not running", .orange)
+ }
+
+ private var label: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(module.name.nonBlank ?? "–")
+ HStack(spacing: 4) {
+ if let version = module.version?.nonBlank { Text(verbatim: "v\(version) ·").foregroundStyle(.secondary) }
+ Text(state.text).foregroundStyle(state.color)
+ }
+ .font(.subheadline)
+ if let error = module.lastError?.nonBlank { Text(error).font(.footnote).foregroundStyle(.red) }
+ }
+ }
+
+ private var toggle: Binding { Binding(get: { module.enabled == true }, set: onToggle) }
+
+ var body: some View {
+ if let onOpen {
+ // Borderless button and switch side by side: the row opens the module, the switch toggles it.
+ HStack(spacing: 12) {
+ Button(action: onOpen) {
+ HStack {
+ label
+ Spacer(minLength: 8)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.borderless)
+ .tint(.primary)
+ Toggle(module.name, isOn: toggle)
+ .labelsHidden()
+ .disabled(disabled || module.name.nonBlank == nil)
+ Button(action: onOpen) {
+ Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(.tertiary)
+ }
+ .buttonStyle(.borderless)
+ .accessibilityLabel("Open")
+ }
+ } else {
+ Toggle(isOn: toggle) { label }
+ .disabled(disabled || module.name.nonBlank == nil)
+ }
+ }
+}
+
+private struct NodeCommandRow: View {
+ let command: HC2Command
+ let checkName: (String) -> String
+
+ private var subtitle: String? {
+ let times = [
+ HcFormat.real(command.createdAt).map { String(localized: "sent \($0.formatted(.relative(presentation: .named)))") },
+ HcFormat.time(command.doneAt).map { String(localized: "finished \($0)") },
+ ].compactMap { $0 }.joined(separator: " · ")
+ return [NodesLogic.commandArgsText(command.args, checkName: checkName), times.nonBlank]
+ .compactMap { $0 }.joined(separator: "\n").nonBlank
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(NodesLogic.commandLabel(command.name))
+ if let subtitle { Text(subtitle).font(.subheadline).foregroundStyle(.secondary) }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if command.doneAt == nil {
+ HealthcheckTag(text: "Pending", color: .orange)
+ } else if command.ok == true {
+ HealthcheckTag(text: "OK", color: .green)
+ } else if command.ok == false {
+ HealthcheckTag(text: "Failed", color: .red)
+ } else {
+ HealthcheckTag(text: "Done", color: .gray)
+ }
+ }
+ if let output = HcFormat.commandOutput(command.output) {
+ Text(output).font(.caption.monospaced()).foregroundStyle(.secondary).lineLimit(6)
+ }
+ }
+ }
+}
+
+private struct NodeLogsSection: View {
+ let lines: [String]
+ @State private var showAll = false
+
+ var body: some View {
+ Section("Logs") {
+ let shown = showAll ? lines : Array(lines.prefix(5))
+ ForEach(shown.indices, id: \.self) { NodeLogRow(line: shown[$0]) }
+ if lines.count > 5 {
+ Button {
+ withAnimation { showAll.toggle() }
+ } label: {
+ Label(showAll ? "Show fewer logs" : "Show all logs", systemImage: showAll ? "chevron.up" : "chevron.down")
+ }
+ .tint(.primary)
+ }
+ }
+ }
+}
+
+/// Parsed logfmt line (time, level, module, message); a tap shows the raw line.
+private struct NodeLogRow: View {
+ let line: String
+ @State private var showRaw = false
+
+ private var entry: NodesLogic.LogEntry? { NodesLogic.parseLogLine(line) }
+
+ private func color(_ level: String?) -> Color {
+ switch level {
+ case "DEBUG": .secondary
+ case "WARN", "WARNING": .orange
+ case "ERROR": .red
+ default: .primary
+ }
+ }
+
+ var body: some View {
+ if let entry {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ if let time = NodesLogic.logClock(entry.time) { Text(time).foregroundStyle(.secondary) }
+ if let level = entry.level { Text(level).fontWeight(.semibold).foregroundStyle(color(level)) }
+ if let module = entry.module { Text(module).foregroundStyle(.secondary) }
+ }
+ .font(.caption)
+ if let msg = entry.msg { Text(msg).font(.footnote).foregroundStyle(color(entry.level)) }
+ if showRaw { Text(line).font(.caption.monospaced()).foregroundStyle(.secondary).textSelection(.enabled) }
+ }
+ .frame(maxWidth: .infinity, minHeight: 36, alignment: .leading)
+ .contentShape(Rectangle())
+ .onTapGesture { withAnimation { showRaw.toggle() } }
+ } else {
+ Text(line).font(.footnote.monospaced()).foregroundStyle(.secondary)
+ }
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeDetailSheets.swift b/IPv64/Views/Nodes/NodeDetailSheets.swift
new file mode 100644
index 0000000..3e652b6
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeDetailSheets.swift
@@ -0,0 +1,168 @@
+import SwiftUI
+import IPv64
+
+/// "Edit node" (cloud nodes): name, location, remote management. Sends only changed values.
+struct NodeEditSheet: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ let nodeId: String
+ let info: NodeInfo
+ let onSaved: (HC2Node) -> Void
+
+ @State private var name: String
+ @State private var location: String
+ @State private var remote: String
+ @State private var inlineError: String?
+ @State private var isSaving = false
+
+ init(nodeId: String, info: NodeInfo, onSaved: @escaping (HC2Node) -> Void) {
+ self.nodeId = nodeId
+ self.info = info
+ self.onSaved = onSaved
+ _name = State(initialValue: info.name ?? "")
+ _location = State(initialValue: info.location ?? "")
+ _remote = State(initialValue: info.remote ?? "full")
+ }
+
+ private var newName: String { name.trimmingCharacters(in: .whitespaces) }
+ private var newLocation: String { location.trimmingCharacters(in: .whitespaces) }
+
+ private var changed: Bool {
+ newName != (info.name ?? "") || newLocation != (info.location ?? "") || remote != (info.remote ?? "full")
+ }
+
+ var body: some View {
+ DynDNSSheet(title: "Edit node", confirmLabel: "Save", confirmEnabled: changed && newName.nonBlank != nil,
+ isBusy: isSaving, onConfirm: { Task { await save() } }) {
+ Section("Node") {
+ TextField("Name", text: $name)
+ TextField("Location", text: $location)
+ }
+ .disabled(isSaving)
+ Section {
+ Picker("Remote management", selection: $remote) {
+ Text("Full").tag("full")
+ Text("Read only").tag("read")
+ Text("Off").tag("off")
+ }
+ } footer: {
+ Text(NodesLogic.remoteDescription(remote))
+ }
+ .disabled(isSaving)
+ if let inlineError {
+ Section { Text(inlineError).font(.footnote).foregroundStyle(.red) }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ }
+
+ private func save() async {
+ let api = session.api
+ let name = newName != (info.name ?? "") ? newName : nil
+ let location = newLocation != (info.location ?? "") ? newLocation : nil
+ let remote = remote != (info.remote ?? "full") ? HC2RemoteManagement(rawValue: remote) : nil
+ isSaving = true
+ defer { isSaving = false }
+ do {
+ let updated = try await ipv64Retrying {
+ try await api.hc2.nodes.update(nodeId, name: name, location: location, remoteManagement: remote)
+ }
+ onSaved(updated)
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ inlineError = ErrorText(error).message.nonBlank ?? error.localizedDescription
+ }
+ }
+}
+
+/// "Resolve conflict": conflict number and side; the detail then asks for confirmation.
+struct ResolveConflictSheet: View {
+ @Environment(\.dismiss) private var dismiss
+ let onContinue: (NodeCommand) -> Void
+
+ @State private var number = ""
+ @State private var keep = HC2ConflictResolution.server
+
+ var body: some View {
+ DynDNSSheet(title: "Resolve conflict",
+ subtitle: String(localized: "Enter the conflict number shown on the node and choose which version to keep."),
+ confirmLabel: "Continue", confirmEnabled: Int(number) != nil, onConfirm: {
+ guard let id = Int(number) else { return }
+ onContinue(NodeCommand(name: .resolveConflict, args: HC2CommandArguments(id: id, keep: keep)))
+ dismiss()
+ }) {
+ Section {
+ TextField("Conflict number", text: $number)
+ .keyboardType(.numberPad)
+ .onChange(of: number) { _, new in
+ let digits = new.filter(\.isNumber)
+ if digits != new { number = digits }
+ }
+ Picker("Keep", selection: $keep) {
+ Text("Server version (ipv64.net)").tag(HC2ConflictResolution.server)
+ Text("Local version (node)").tag(HC2ConflictResolution.local)
+ }
+ }
+ }
+ .presentationDetents([.medium])
+ }
+}
+
+/// "Unlink node?" with a typed confirmation and the keep-checks switch.
+struct NodeUnlinkSheet: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ let nodeId: String
+ let name: String
+ let onResult: (HC2NodeUnlinkResult) -> Void
+
+ @State private var keepChecks = true
+ @State private var typed = ""
+ @State private var inlineError: String?
+ @State private var isUnlinking = false
+
+ private var phrase: String { name.trimmingCharacters(in: .whitespaces).nonBlank ?? "unlink" }
+
+ var body: some View {
+ DynDNSSheet(title: "Unlink node?",
+ subtitle: String(localized: "The access token of \"\(name)\" is revoked. The node keeps running standalone but no longer syncs with ipv64.net. This cannot be undone."),
+ confirmLabel: "Unlink", confirmEnabled: typed.trimmingCharacters(in: .whitespaces) == phrase,
+ isBusy: isUnlinking, onConfirm: { Task { await unlink() } }) {
+ Section {
+ Toggle("Keep checks as online checks", isOn: $keepChecks)
+ } footer: {
+ Text(keepChecks ? "Checks with a public target continue as online checks."
+ : "The checks of this node are not continued and will be deleted.")
+ }
+ .disabled(isUnlinking)
+ Section {
+ TextField(phrase, text: $typed).textInputAutocapitalization(.never).autocorrectionDisabled()
+ } footer: {
+ Text("Type \"\(phrase)\" to confirm.")
+ }
+ .disabled(isUnlinking)
+ if let inlineError {
+ Section { Text(inlineError).font(.footnote).foregroundStyle(.red) }
+ }
+ }
+ .presentationDetents([.large])
+ }
+
+ private func unlink() async {
+ let api = session.api
+ isUnlinking = true
+ defer { isUnlinking = false }
+ do {
+ let result = try await ipv64Retrying { try await api.hc2.nodes.unlink(nodeId, keepChecks: keepChecks) }
+ onResult(result)
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ inlineError = ErrorText(error).message.nonBlank ?? error.localizedDescription
+ }
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeDetailView.swift b/IPv64/Views/Nodes/NodeDetailView.swift
new file mode 100644
index 0000000..253fd86
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeDetailView.swift
@@ -0,0 +1,207 @@
+import SwiftUI
+import IPv64
+
+/// Node detail: cloud data (`hc2.nodes.get`) plus live data over the stored direct connection, if any.
+/// Direct-only nodes (unknown to the account) show no checks, commands, cloud edit or unlink.
+struct NodeDetailView: View {
+ @Environment(Session.self) var session
+ @Environment(ConnectedNodes.self) var nodes
+ @Environment(\.scenePhase) var scenePhase
+ @Environment(\.dismiss) var dismiss
+
+ let nodeId: String
+ /// Tells the list that this node changed (edit, unlink, forget).
+ let onChanged: () -> Void
+
+ @State var info: NodeInfo?
+ @State var loadFailed = false
+ @State var planReason: String?
+ @State var directOnly = false
+ @State var access: LocalNodeStore.Access?
+ @State var live = NodeLive()
+ @State var busy = false
+ @State var isLoading = false
+ /// Mutex of the silent live refresh.
+ @State var isTicking = false
+ @State var error: ErrorText?
+ @State var unlinkText: String?
+ @State var pendingUnlink: String?
+ @State var pendingError: ErrorText?
+ @State var sheet: DetailSheet?
+ @State var pendingCommand: NodeCommand?
+ @State var confirmCommand: NodeCommand?
+ @State var confirmDisable: String?
+ @State var confirmForget = false
+ @State var commands: [HC2Command] = []
+ @State var historyOpen = false
+ @State var historyLoading = false
+ @State var historyLoaded = false
+ @State var detailsOpen = false
+ @State var tracking: Int?
+ /// Name of the module whose screen is pushed.
+ @State var moduleScreen: String?
+
+ enum DetailSheet: String, Identifiable {
+ case edit, connection, resolve, unlink
+ var id: String { rawValue }
+ }
+
+ private struct TickKey: Equatable {
+ let hasAccess: Bool
+ let active: Bool
+ }
+
+ // MARK: Derived
+
+ var isLocal: Bool { access != nil }
+ var localNode: Node64.NodeStatusNode? { live.status?.node }
+ /// Node id reported by the address, if it differs from this node.
+ var otherNodeId: String? {
+ guard let id = localNode?.id?.nonBlank, id != nodeId else { return nil }
+ return id
+ }
+ var displayName: String {
+ let name = directOnly ? (localNode?.name?.nonBlank ?? info?.name?.nonBlank ?? LocalNodeStore.name(nodeId)) : info?.name
+ return NodesLogic.nodeName(name, nodeId: nodeId)
+ }
+ var canCommand: Bool { info?.remote == "full" && !directOnly }
+ var conflicts: Int { live.status?.link?.conflicts ?? info?.conflicts ?? 0 }
+ /// Cloud data there and, with direct access, the first live answer (or its failure).
+ var loaded: Bool { info != nil && !(isLocal && live.status == nil && !live.failing) }
+ var locked: Bool { busy || isLoading || !loaded }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(sheet != nil || confirmCommand != nil || confirmDisable != nil || confirmForget ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+
+ private var screen: some View {
+ List {
+ if loaded, let info { sections(info) }
+ }
+ .overlay { overlay }
+ // While loading or running an action everything is locked; the spinner sits in the toolbar.
+ .disabled(locked)
+ .navigationTitle(info == nil ? String(localized: "Node") : displayName)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar { toolbar }
+ .navigationDestination(for: HealthcheckRoute.self) { route in
+ HealthcheckDetailView(token: route.token) { Task { await loadCloud() } }
+ }
+ .navigationDestination(item: $moduleScreen) { module in
+ NodeModuleView(nodeId: nodeId, module: module)
+ }
+ .task { await start() }
+ .task(id: TickKey(hasAccess: isLocal, active: scenePhase == .active)) { await tickLoop() }
+ .task(id: tracking) { await trackCommand() }
+ .onChange(of: historyOpen) { if historyOpen && !historyLoaded { Task { await loadCommands() } } }
+ .refreshable { await refresh() }
+ .sheet(item: $sheet, onDismiss: sheetClosed) { sheet in
+ switch sheet {
+ case .edit:
+ NodeEditSheet(nodeId: nodeId, info: info ?? NodeInfo(name: nil)) { updated in
+ info = info?.merged(with: updated)
+ onChanged()
+ }
+ case .connection:
+ NodeLocalSheet(nodeId: nodeId).onDisappear(perform: reloadAccess)
+ case .resolve:
+ ResolveConflictSheet { pendingCommand = $0 }
+ case .unlink:
+ NodeUnlinkSheet(nodeId: nodeId, name: displayName) { handleUnlink($0) }
+ }
+ }
+ }
+
+ private var content: some View {
+ screen
+ .alert(confirmCommand.map { "\($0.label)?" } ?? "", isPresented: Binding(
+ get: { confirmCommand != nil }, set: { if !$0 { confirmCommand = nil } }), presenting: confirmCommand) { command in
+ Button("Send", role: command.name == .resolveConflict ? .destructive : nil) { Task { await send(command) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { command in
+ Text(command.confirmText(nodeName: displayName))
+ }
+ .alert(confirmDisable.map { String(localized: "Disable \($0)?") } ?? "", isPresented: Binding(
+ get: { confirmDisable != nil }, set: { if !$0 { confirmDisable = nil } }), presenting: confirmDisable) { name in
+ Button("Disable", role: .destructive) { Task { await setModule(name, enable: false) } }
+ Button("Cancel", role: .cancel) {}
+ } message: { name in
+ Text("Disable \(name)? Services of this module stop on the node, e.g. DNS for your network.")
+ }
+ .alert("Forget access?", isPresented: $confirmForget) {
+ Button("Forget", role: .destructive) { forget() }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("The address and API key are removed from this device. The node itself is not changed.")
+ }
+ .alert("Node unlinked", isPresented: Binding(get: { unlinkText != nil }, set: { if !$0 { unlinkText = nil } }),
+ presenting: unlinkText) { _ in
+ Button("OK") { dismiss() }
+ } message: { text in
+ Text(text)
+ }
+ .errorAlert($error)
+ }
+
+ @ViewBuilder private var overlay: some View {
+ if let planReason, !isLocal {
+ ContentUnavailableView("Nodes not available", systemImage: "point.3.connected.trianglepath.dotted",
+ description: Text(planReason))
+ } else if loadFailed {
+ ContentUnavailableView {
+ Label("Node could not be loaded", systemImage: "exclamationmark.triangle")
+ } actions: {
+ Button("Retry") { Task { await loadCloud() } }
+ }
+ } else if !loaded {
+ ProgressView()
+ }
+ }
+
+ @ToolbarContentBuilder private var toolbar: some ToolbarContent {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button(directOnly ? "Edit connection" : "Edit", systemImage: "pencil") {
+ sheet = directOnly ? .connection : .edit
+ }
+ .disabled(locked)
+ }
+ if #available(iOS 26.0, *) {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ if busy || isLoading {
+ ProgressView()
+ } else {
+ moreMenu.disabled(!loaded)
+ }
+ }.appVerticalPreferred()
+ }
+
+ private var moreMenu: some View {
+ Menu {
+ if !directOnly {
+ Button(isLocal ? "Edit direct connection" : "Set up direct access", systemImage: "network") { sheet = .connection }
+ }
+ if canCommand {
+ Button("Repair", systemImage: "wrench.and.screwdriver") { confirmCommand = NodeCommand(name: .repair) }
+ .disabled(tracking != nil)
+ if conflicts > 0 {
+ Button("Resolve conflict", systemImage: "arrow.triangle.merge") { sheet = .resolve }
+ }
+ }
+ Divider()
+ if isLocal {
+ DestructiveMenuButton("Forget access", systemImage: "network.slash") { confirmForget = true }
+ }
+ if !directOnly {
+ DestructiveMenuButton("Unlink node", systemImage: "minus.circle") { sheet = .unlink }
+ }
+ } label: {
+ Label("More actions", systemImage: "ellipsis")
+ }
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeLinkSheet.swift b/IPv64/Views/Nodes/NodeLinkSheet.swift
new file mode 100644
index 0000000..5df6d6f
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeLinkSheet.swift
@@ -0,0 +1,90 @@
+import SwiftUI
+import IPv64
+
+/// "Link node": code from `ipv64 link`, location, remote management. Locked while linking.
+struct NodeLinkSheet: View {
+ @Environment(Session.self) private var session
+ @Environment(\.dismiss) private var dismiss
+
+ /// Called after the code was accepted, with the `linkedAt` of every node taken before linking.
+ let onLinked: ([String: Date?]) -> Void
+
+ @State private var code = ""
+ @State private var location = ""
+ @State private var remote = "full"
+ @State private var inlineError: String?
+ @State private var isLinking = false
+
+ private var raw: String { NodesLogic.rawLinkCode(code) }
+
+ var body: some View {
+ DynDNSSheet(title: "Link node",
+ subtitle: String(localized: "Open \"ipv64 link\" on your Node64 to get an 8-character code. After linking, the node fetches its access token by itself."),
+ confirmLabel: "Link", confirmEnabled: raw.count == 8, isBusy: isLinking,
+ onConfirm: { Task { await link() } }) {
+ Section("Node") {
+ TextField("Code", text: $code, prompt: Text(verbatim: "ABCD-EFGH"))
+ .font(.body.monospaced())
+ .textInputAutocapitalization(.characters)
+ .autocorrectionDisabled()
+ .onChange(of: code) { _, new in
+ let masked = NodesLogic.maskedLinkCode(NodesLogic.rawLinkCode(new))
+ if masked != new { code = masked }
+ inlineError = nil
+ }
+ }
+ .disabled(isLinking)
+ Section {
+ TextField("Location (optional)", text: $location)
+ Picker("Remote management", selection: $remote) {
+ Text("Full").tag("full")
+ Text("Read only").tag("read")
+ Text("Off").tag("off")
+ }
+ } header: {
+ Text("Options")
+ } footer: {
+ Text(NodesLogic.remoteDescription(remote))
+ }
+ .disabled(isLinking)
+ if isLinking {
+ Section {
+ HStack(spacing: 8) {
+ ProgressView()
+ Text("Linking...").foregroundStyle(.secondary)
+ }
+ }
+ }
+ if let inlineError {
+ Section { Text(inlineError).font(.footnote).foregroundStyle(.red) }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ }
+
+ private func link() async {
+ let api = session.api
+ isLinking = true
+ inlineError = nil
+ defer { isLinking = false }
+ do {
+ let list = try await ipv64Retrying { try await api.hc2.nodes.list() }
+ let before = Dictionary(list.map { ($0.nodeID, $0.linkedAt) }, uniquingKeysWith: { first, _ in first })
+ let result = try await ipv64Retrying {
+ try await api.hc2.nodes.link(
+ code: NodesLogic.maskedLinkCode(raw), location: location.trimmingCharacters(in: .whitespaces).nonBlank,
+ remoteManagement: HC2RemoteManagement(rawValue: remote))
+ }
+ if result.accepted == false {
+ inlineError = result.detail?.nonBlank ?? String(localized: "The code was not accepted.")
+ return
+ }
+ onLinked(before)
+ dismiss()
+ } catch is CancellationError {
+ } catch {
+ inlineError = ErrorText(error).message.nonBlank ?? error.localizedDescription
+ }
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeLocalSheet.swift b/IPv64/Views/Nodes/NodeLocalSheet.swift
new file mode 100644
index 0000000..a802a27
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeLocalSheet.swift
@@ -0,0 +1,172 @@
+import SwiftUI
+import IPv64
+
+/// Direct access to a node by address and node API key (Android `NodeLocalSheet`).
+/// `nodeId == nil` connects a new node, otherwise it edits the stored access of that node.
+struct NodeLocalSheet: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+ var nodeId: String?
+
+ @State private var address = ""
+ @State private var apiKey = ""
+ @State private var inlineError: String?
+ @State private var isConnecting = false
+ @State private var storedKeyExists = false
+ @State private var differentNode: DifferentNode?
+
+ private struct DifferentNode {
+ let id: String
+ let remoteId: String
+ }
+
+ private var isNew: Bool { nodeId == nil }
+
+ /// Normalised address when it differs from the input (shown under the field).
+ private var preview: String? {
+ guard let url = LocalNodeURL.normalizeLocalNodeUrl(address),
+ url != address.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil }
+ return url
+ }
+
+ private var intro: String {
+ isNew
+ ? String(localized: "Add a node without linking it to your account: connect to it by its local IP or by its link (e.g. https://node.example.com/api). Create an API key in the node's web interface on the API tab.")
+ : String(localized: "Connect directly to this node by its local IP or by its link (e.g. https://node.example.com/api). Create an API key in the node's web interface on the API tab.")
+ }
+
+ var body: some View {
+ DynDNSSheet(title: isNew ? "Connect directly" : "Direct access", subtitle: intro, confirmLabel: "Connect",
+ confirmEnabled: address.nonBlank != nil && (apiKey.nonBlank != nil || storedKeyExists),
+ isBusy: isConnecting, onConfirm: { Task { await connect() } }) {
+ Section {
+ TextField("Address", text: $address, prompt: Text(verbatim: "http://192.168.1.10:8080/api"))
+ .keyboardType(.URL)
+ .textContentType(.URL)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ } header: {
+ Text("Address")
+ } footer: {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Local or public IP (http, port 8080 added) or link (https); /api is added if missing.")
+ if let preview { Text("Connects to \(preview)") }
+ }
+ }
+ .disabled(isConnecting)
+ Section {
+ SecureField("API key", text: $apiKey, prompt: Text(verbatim: "node64_…"))
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ } header: {
+ Text("API key")
+ } footer: {
+ if storedKeyExists { Text("Leave empty to keep the saved key.") }
+ }
+ .disabled(isConnecting)
+ warning
+ if isConnecting {
+ Section {
+ HStack(spacing: 8) {
+ ProgressView()
+ Text("Connecting...").foregroundStyle(.secondary)
+ }
+ }
+ }
+ if let inlineError {
+ Section { Text(inlineError).font(.footnote).foregroundStyle(.red) }
+ }
+ }
+ .onChange(of: address) { inlineError = nil }
+ .onChange(of: apiKey) { inlineError = nil }
+ .task { load() }
+ .alert("Different node?", isPresented: Binding(get: { differentNode != nil }, set: { if !$0 { differentNode = nil } }),
+ presenting: differentNode) { _ in
+ Button("OK") { Task { await finish() } }
+ } message: { node in
+ Text("The node at this address reports the ID \(node.remoteId) instead of \(node.id). The connection was saved anyway — check the address if this is unexpected.")
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ }
+
+ @ViewBuilder private var warning: some View {
+ switch NodesLogic.insecureWarning(for: address) {
+ case .none:
+ EmptyView()
+ case .local:
+ Section { Text("The key is sent unencrypted on your local network.").font(.footnote).foregroundStyle(.orange) }
+ case .internet:
+ Section {
+ Text("The API key is sent unencrypted over the internet. Use https:// or a VPN if you can.")
+ .font(.footnote).foregroundStyle(.red)
+ }
+ }
+ }
+
+ private func load() {
+ guard let nodeId, let access = nodes.access(for: nodeId) else { return }
+ if address.isEmpty { address = access.url }
+ storedKeyExists = true
+ }
+
+ private func connect() async {
+ guard let url = LocalNodeURL.normalizeLocalNodeUrl(address) else {
+ inlineError = LocalNodeURL.invalidInputMessage(address)
+ return
+ }
+ let typed = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let key = typed.isEmpty ? (nodeId.flatMap { nodes.access(for: $0)?.key } ?? "") : typed
+ guard NodesLogic.isValidApiKey(key) else {
+ inlineError = String(localized: "The API key contains invalid characters.")
+ return
+ }
+ guard let client = NodeClientFactory.client(url: url, key: key) else {
+ inlineError = LocalNodeURL.invalidInputMessage(address)
+ return
+ }
+ address = url
+ inlineError = nil
+ isConnecting = true
+ defer { isConnecting = false }
+ do {
+ _ = try await client.node.health()
+ let status = try await client.node.status()
+ let remoteId = status.node?.id?.nonBlank
+ let id: String
+ if let nodeId {
+ id = nodeId
+ try LocalNodeStore.save(id: nodeId, url: url, key: key, owner: nodes.owner)
+ } else {
+ guard let remoteId else {
+ inlineError = String(localized: "The node did not report its ID. Update Node64 and try again.")
+ return
+ }
+ id = remoteId
+ try LocalNodeStore.save(id: remoteId, url: url, key: key, owner: nodes.owner, name: status.node?.name?.nonBlank)
+ }
+ if let modules = status.modules { LocalNodeStore.saveModules(id, modules: modules) }
+ nodes.push(id)
+ apiKey = ""
+ if let remoteId, remoteId != id {
+ differentNode = DifferentNode(id: id, remoteId: remoteId)
+ } else {
+ await finish()
+ }
+ } catch is CancellationError {
+ } catch let error as SecureStore.StoreError {
+ inlineError = error.localizedDescription
+ } catch {
+ inlineError = ErrorText.node(error).titledText
+ }
+ }
+
+ /// Updates the tab flags, then closes the sheet.
+ private func finish() async {
+ isConnecting = true
+ nodes.refresh()
+ await nodes.refreshModules()
+ isConnecting = false
+ dismiss()
+ }
+}
diff --git a/IPv64/Views/Nodes/NodeModuleView.swift b/IPv64/Views/Nodes/NodeModuleView.swift
new file mode 100644
index 0000000..1d70a12
--- /dev/null
+++ b/IPv64/Views/Nodes/NodeModuleView.swift
@@ -0,0 +1,374 @@
+import SwiftUI
+import Charts
+import IPv64
+
+/// Read-only module screen over the stored direct connection (DNS64 and Honeypot only).
+struct NodeModuleView: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ let nodeId: String
+ let module: String
+
+ static func hasScreen(_ name: String) -> Bool { ["dns64", "honeypot"].contains(name.lowercased()) }
+
+ private var isDns: Bool { module.lowercased() == "dns64" }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(.orange)
+ } else {
+ content
+ }
+ }
+
+ @ViewBuilder private var content: some View {
+ Group {
+ if let client = nodes.client(for: nodeId) {
+ if isDns { Dns64ModuleList(client: client) } else { HoneypotModuleList(client: client) }
+ } else {
+ ContentUnavailableView("No direct connection to this node.", systemImage: "network.slash")
+ }
+ }
+ .navigationTitle(isDns ? String(localized: "DNS64") : String(localized: "Honeypot"))
+ .navigationBarTitleDisplayMode(.inline)
+ }
+}
+
+/// Runs one request of a module screen; a failure becomes a value so the other requests go on.
+private nonisolated func attempt(_ operation: @Sendable () async throws -> T) async -> Result {
+ do { return .success(try await operation()) } catch { return .failure(error) }
+}
+
+private func moduleErrorText(_ error: any Error) -> String {
+ if (error as? Node64Error)?.statusCode == 404 { return String(localized: "Not available on this node.") }
+ return ErrorText.node(error).titledText
+}
+
+// MARK: - DNS64
+
+private struct Dns64ModuleList: View {
+ let client: Node64
+
+ @State private var status: Result?
+ @State private var summary: Result?
+ @State private var blocked: Result<[Node64.DNS64TopItem], any Error>?
+ @State private var allowed: Result<[Node64.DNS64TopItem], any Error>?
+ @State private var clients: Result<[Node64.DNS64TopItem], any Error>?
+ @State private var loaded = false
+
+ var body: some View {
+ List {
+ if loaded {
+ if let status { statusSection(status) }
+ if let summary { summarySection(summary) }
+ if let blocked { topSection("Top blocked domains", blocked) }
+ if let allowed { topSection("Top queried domains", allowed) }
+ if let clients { topSection("Top clients", clients) }
+ }
+ }
+ .overlay { if !loaded { ProgressView() } }
+ .refreshable { await load() }
+ .task { await load() }
+ }
+
+ @ViewBuilder private func statusSection(_ result: Result) -> some View {
+ switch result {
+ case .failure(let error):
+ ModuleErrorSection(title: "Status", error: error)
+ case .success(let s):
+ Section("Status") {
+ ModuleInfoRow("Version", s.version)
+ ModuleInfoRow("Listen", s.listen, mono: true)
+ ModuleInfoRow("Filtering", s.blocking?.paused == true ? String(localized: "Paused") : String(localized: "Active"))
+ ModuleInfoRow("Running since", HcFormat.time(s.startedAt))
+ }
+ }
+ }
+
+ @ViewBuilder private func summarySection(_ result: Result) -> some View {
+ switch result {
+ case .failure(let error):
+ ModuleErrorSection(title: "Last 24 hours", error: error)
+ case .success(let value):
+ let s = value.summary
+ let total = s?.total ?? 0
+ Section("Last 24 hours") {
+ ModuleBigNumber(value: total.formatted(), label: "Queries")
+ LabeledContent("Blocked", value: (s?.blocked ?? 0).formatted())
+ LabeledContent("Blocked %", value: NodesLogic.blockedPercent(total: total, blocked: s?.blocked ?? 0))
+ LabeledContent("Clients", value: (s?.clients ?? 0).formatted())
+ }
+ }
+ }
+
+ @ViewBuilder private func topSection(_ title: LocalizedStringKey, _ result: Result<[Node64.DNS64TopItem], any Error>) -> some View {
+ switch result {
+ case .failure(let error):
+ ModuleErrorSection(title: title, error: error)
+ case .success(let items) where !items.isEmpty:
+ let maxValue = items.compactMap(\.count).max() ?? 0
+ Section(title) {
+ ForEach(items.indices, id: \.self) { i in
+ let item = items[i]
+ ModuleRankRow(label: item.name?.nonBlank ?? item.hostname?.nonBlank ?? "–",
+ subtitle: item.name?.nonBlank != nil ? item.hostname?.nonBlank : nil,
+ value: item.count ?? 0, detail: (item.count ?? 0).formatted(), maxValue: maxValue, mono: true)
+ }
+ }
+ case .success:
+ EmptyView()
+ }
+ }
+
+ private func load() async {
+ let dns = client.dns64
+ async let status = attempt { try await dns.status() }
+ async let summary = attempt { try await dns.summary(range: .last24Hours) }
+ async let blocked = attempt { try await dns.top(kind: .blocked, range: .last24Hours, limit: 10) }
+ async let allowed = attempt { try await dns.top(kind: .allowed, range: .last24Hours, limit: 10) }
+ async let clients = attempt { try await dns.top(kind: .clients, range: .last24Hours, limit: 10) }
+ let results = await (status, summary, blocked, allowed, clients)
+ if Task.isCancelled { return }
+ (self.status, self.summary, self.blocked, self.allowed, self.clients) = results
+ loaded = true
+ }
+}
+
+// MARK: - Honeypot
+
+private struct HoneypotModuleList: View {
+ let client: Node64
+
+ @State private var status: Result?
+ @State private var stats: Result?
+ @State private var events: Result<[Node64.Honeypot64Event], any Error>?
+ @State private var loaded = false
+
+ private struct Bar: Identifiable {
+ let time: Date
+ let events: Int
+ var id: Date { time }
+ }
+
+ var body: some View {
+ List {
+ if loaded {
+ if let status { statusSection(status) }
+ if let stats { statsSections(stats) }
+ if let events { eventsSection(events) }
+ }
+ }
+ .overlay { if !loaded { ProgressView() } }
+ .refreshable { await load() }
+ .task { await load() }
+ }
+
+ @ViewBuilder private func statusSection(_ result: Result) -> some View {
+ switch result {
+ case .failure(let error):
+ ModuleErrorSection(title: "Status", error: error)
+ case .success(let s):
+ Section("Status") {
+ LabeledContent("State") {
+ Text(s.running == true ? "Running" : "Not running").foregroundStyle(s.running == true ? .green : .orange)
+ }
+ ModuleInfoRow("Version", s.version)
+ ModuleInfoRow("Profile", s.profile)
+ ModuleInfoRow("Services", s.services.map { $0.count.formatted() })
+ ModuleInfoRow("Connections", s.counters?.connections?.formatted())
+ ModuleInfoRow("Logins", s.counters?.logins?.formatted())
+ }
+ }
+ }
+
+ @ViewBuilder private func statsSections(_ result: Result) -> some View {
+ switch result {
+ case .failure(let error):
+ ModuleErrorSection(title: "Last 24 hours", error: error)
+ case .success(let s):
+ Section("Last 24 hours") {
+ ModuleBigNumber(value: (s.events ?? 0).formatted(), label: "Events")
+ LabeledContent("Sources", value: (s.sources ?? 0).formatted())
+ LabeledContent("Logins", value: (s.logins ?? 0).formatted())
+ }
+ let bars = (s.timeline ?? []).compactMap { point in point.time.map { Bar(time: $0, events: point.events ?? 0) } }
+ if bars.contains(where: { $0.events > 0 }) {
+ Section("Attacks (last 24 h)") {
+ HoneypotAttacksChart(bars: bars.map { ($0.time, $0.events) })
+ }
+ }
+ rankSection("Top attackers", (s.topSources ?? []).map {
+ ($0.key ?? "–", $0.count ?? 0,
+ [($0.count ?? 0).formatted(), NodesLogic.countryFlag($0.country)].compactMap { $0 }.joined(separator: " · "))
+ })
+ rankSection("Top ports", counts(s.byPort))
+ rankSection("Top countries", (s.byCountry ?? []).map {
+ ([NodesLogic.countryFlag($0.key), $0.key].compactMap { $0 }.joined(separator: " ").nonBlank ?? "–", $0.count ?? 0,
+ String(localized: "\(($0.count ?? 0).formatted()) · \($0.sources ?? 0) sources"))
+ })
+ rankSection("Services", counts(s.byService))
+ rankSection("Attack kinds", counts(s.byKind))
+ rankSection("Usernames", counts(s.topUsers), mono: true)
+ rankSection("Passwords", counts(s.topPasswords), mono: true)
+ rankSection("Paths", counts(s.topPaths), mono: true)
+ rankSection("User agents", counts(s.topUserAgents))
+ }
+ }
+
+ private func counts(_ list: [Node64.Honeypot64Count]?) -> [(String, Int, String)] {
+ (list ?? []).map { ($0.key ?? "–", $0.count ?? 0, ($0.count ?? 0).formatted()) }
+ }
+
+ @ViewBuilder private func rankSection(_ title: LocalizedStringKey, _ rows: [(String, Int, String)], mono: Bool = false) -> some View {
+ if !rows.isEmpty {
+ let top = Array(rows.prefix(10))
+ let maxValue = top.map(\.1).max() ?? 0
+ Section(title) {
+ ForEach(top.indices, id: \.self) { i in
+ ModuleRankRow(label: top[i].0, value: top[i].1, detail: top[i].2, maxValue: maxValue, mono: mono)
+ }
+ }
+ }
+ }
+
+ @ViewBuilder private func eventsSection(_ result: Result<[Node64.Honeypot64Event], any Error>) -> some View {
+ switch result {
+ case .failure(let error):
+ ModuleErrorSection(title: "Recent events", error: error)
+ case .success(let list) where !list.isEmpty:
+ Section("Recent events") {
+ ForEach(list.indices, id: \.self) { i in
+ let e = list[i]
+ VStack(alignment: .leading, spacing: 2) {
+ Text(e.src?.nonBlank ?? "–").font(.body.monospaced())
+ Text([HcFormat.real(e.time).map { $0.formatted(.relative(presentation: .named)) },
+ e.service?.nonBlank ?? e.port.map { "port \($0)" }, NodesLogic.countryFlag(e.country)]
+ .compactMap { $0 }.joined(separator: " · "))
+ .font(.subheadline).foregroundStyle(.secondary)
+ }
+ .accessibilityElement(children: .combine)
+ }
+ }
+ case .success:
+ EmptyView()
+ }
+ }
+
+ private func load() async {
+ let honeypot = client.honeypot
+ async let status = attempt { try await honeypot.status() }
+ async let stats = attempt { try await honeypot.stats(top: 10) }
+ async let events = attempt { try await honeypot.events(limit: 20) }
+ let results = await (status, stats, events)
+ if Task.isCancelled { return }
+ (self.status, self.stats, self.events) = results
+ loaded = true
+ }
+}
+
+// MARK: - Rows
+
+/// Prominent value with a caption (like the healthcheck statistics).
+private struct ModuleBigNumber: View {
+ let value: String
+ let label: LocalizedStringKey
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(value).font(.system(size: 40, weight: .bold, design: .rounded)).lineLimit(1).minimumScaleFactor(0.5)
+ Text(label).font(.caption).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// `LabeledContent` that disappears for blank values.
+private struct ModuleInfoRow: View {
+ let label: LocalizedStringKey
+ let value: String?
+ var mono = false
+
+ init(_ label: LocalizedStringKey, _ value: String?, mono: Bool = false) {
+ self.label = label
+ self.value = value?.nonBlank
+ self.mono = mono
+ }
+
+ var body: some View {
+ if let value {
+ LabeledContent(label) { Text(value).font(mono ? .body.monospaced() : .body).textSelection(.enabled) }
+ }
+ }
+}
+
+private struct ModuleErrorSection: View {
+ let title: LocalizedStringKey
+ let error: any Error
+
+ var body: some View {
+ Section(title) { Text(moduleErrorText(error)).foregroundStyle(.red) }
+ }
+}
+
+/// Ranking row: label, count, bar relative to the largest value.
+struct ModuleRankRow: View {
+ let label: String
+ var subtitle: String?
+ let value: Int
+ let detail: String
+ let maxValue: Int
+ var mono = false
+
+ private var fraction: Double {
+ value == 0 || maxValue == 0 ? 0 : min(max(Double(value) / Double(maxValue), 0.02), 1)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(label).font(mono ? .body.monospaced() : .body).lineLimit(2)
+ if let subtitle { Text(subtitle).font(.subheadline).foregroundStyle(.secondary).lineLimit(1) }
+ }
+ Spacer(minLength: 8)
+ Text(detail).font(.subheadline).foregroundStyle(.secondary).monospacedDigit()
+ }
+ ProgressView(value: fraction).tint(.orange)
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Hourly attack bars; touching a bar shows its hour and count above the chart (like the healthcheck chart).
+private struct HoneypotAttacksChart: View {
+ let bars: [(time: Date, events: Int)]
+ @State private var rawSelection: Date?
+
+ /// The hour bucket under the finger.
+ private var selected: (time: Date, events: Int)? {
+ guard let raw = rawSelection else { return nil }
+ return bars.min { abs($0.time.timeIntervalSince(raw)) < abs($1.time.timeIntervalSince(raw)) }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Group {
+ if let selected {
+ Text(verbatim: "\(selected.time.formatted(date: .abbreviated, time: .shortened)) · ")
+ + Text("\(selected.events) events")
+ } else {
+ Text("Touch the chart for values")
+ }
+ }
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ Chart(bars.indices, id: \.self) { i in
+ BarMark(x: .value("Time", bars[i].time, unit: .hour), y: .value("Events", bars[i].events))
+ .foregroundStyle(Color.orange.opacity(selected == nil || selected?.time == bars[i].time ? 1 : 0.35))
+ }
+ .chartXSelection(value: $rawSelection)
+ .frame(height: 140)
+ .accessibilityLabel("Bar chart with \(bars.count) values, maximum \(bars.map(\.events).max() ?? 0)")
+ }
+ }
+}
diff --git a/IPv64/Views/Nodes/NodesView.swift b/IPv64/Views/Nodes/NodesView.swift
new file mode 100644
index 0000000..49651cf
--- /dev/null
+++ b/IPv64/Views/Nodes/NodesView.swift
@@ -0,0 +1,297 @@
+import SwiftUI
+import IPv64
+
+/// Nodes (pushed from More): cloud-linked nodes of the account and nodes connected directly from this device.
+struct NodesView: View {
+ static let route = "settings.nodes"
+
+ @Environment(Session.self) private var session
+ @Environment(ConnectedNodes.self) private var nodes
+ @State private var cloud: [HC2Node]?
+ /// Set when the plan does not include nodes (HTTP 403).
+ @State private var planReason: String?
+ @State private var sheet: NodesSheet?
+ @State private var confirmForget: String?
+ @State private var error: ErrorText?
+ /// Set after a code was accepted: the list is polled until the node shows up.
+ @State private var wait: WaitRequest?
+
+ enum NodesSheet: String, Identifiable {
+ case add, link, direct
+ var id: String { rawValue }
+ }
+
+ private struct WaitRequest: Equatable {
+ let id = UUID()
+ /// `linkedAt` per node id before linking.
+ let before: [String: Date?]
+ }
+
+ private var cloudNodes: [HC2Node] {
+ (cloud ?? []).sorted {
+ NodesLogic.nodeName($0.name, nodeId: $0.nodeID)
+ .localizedStandardCompare(NodesLogic.nodeName($1.name, nodeId: $1.nodeID)) == .orderedAscending
+ }
+ }
+
+ /// Directly connected nodes that are not linked to the account (linked ones show as cloud rows).
+ private var directIds: [String] {
+ let cloudIds = Set((cloud ?? []).map(\.nodeID))
+ return nodes.ids.filter { !cloudIds.contains($0) }
+ }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView.setColorGradient(sheet != nil || confirmForget != nil ? .clear : .orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ List {
+ if wait != nil { waitingSection }
+ ForEach(cloudNodes) { node in
+ NavigationLink(value: NodeRoute(id: node.nodeID)) { CloudNodeRow(node: node) }
+ }
+ ForEach(directIds, id: \.self) { id in
+ NavigationLink(value: NodeRoute(id: id)) {
+ DirectNodeRow(name: nodes.name(of: id), host: NodesLogic.directSubtitle(url: LocalNodeStore.url(id)),
+ version: nodes.versions[id])
+ }
+ .swipeActions {
+ Button("Forget access", systemImage: "network.slash", role: .destructive) { confirmForget = id }
+ .labelStyle(.iconOnly)
+ .tint(.red)
+ }
+ }
+ }
+ .overlay { emptyState }
+ .navigationTitle("Nodes")
+ .navigationBarTitleDisplayMode(.inline)
+ .navigationDestination(for: NodeRoute.self) { route in
+ NodeDetailView(nodeId: route.id) { Task { await load() } }
+ }
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { sheet = .add } label: { Label("Add node", systemImage: "plus") }
+ }
+ }
+ .refreshable { await load() }
+ .task { await load() }
+ .task(id: wait?.id) { await waitForNode() }
+ .onAppear { nodes.refresh() }
+ .sheet(item: $sheet) { sheet in
+ switch sheet {
+ // Switching the item closes this sheet and opens the form.
+ case .add: AddNodeSheet(planBlocked: planReason != nil, onLink: { self.sheet = .link },
+ onDirect: { self.sheet = .direct })
+ case .link: NodeLinkSheet { wait = WaitRequest(before: $0) }
+ case .direct: NodeLocalSheet()
+ }
+ }
+ .alert("Forget access?", isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }),
+ presenting: confirmForget) { id in
+ Button("Forget", role: .destructive) { forget(id) }
+ Button("Cancel", role: .cancel) {}
+ } message: { id in
+ Text("The address and API key of \"\(nodes.name(of: id))\" are removed from this device. The node itself is not changed.")
+ }
+ .errorAlert($error)
+ }
+
+ private var waitingSection: some View {
+ Section {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ ProgressView()
+ Text("Waiting for the node").font(.headline)
+ }
+ Text("The node fetches its token itself. This usually takes less than a minute.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ .padding(.vertical, 4)
+ }
+ }
+
+ @ViewBuilder private var emptyState: some View {
+ if wait != nil {
+ EmptyView()
+ } else if cloud == nil && directIds.isEmpty {
+ ProgressView("Loading nodes…")
+ } else if cloudNodes.isEmpty && directIds.isEmpty {
+ if let planReason {
+ ContentUnavailableView("Nodes not available", systemImage: "point.3.connected.trianglepath.dotted",
+ description: Text(planReason))
+ } else {
+ ContentUnavailableView {
+ Label("No nodes yet", systemImage: "point.3.connected.trianglepath.dotted")
+ } description: {
+ Text("Tap + to link a node with the code your Node64 shows under \"ipv64 link\", or connect to one directly.")
+ } actions: {
+ Button("Add node") { sheet = .add }
+ }
+ }
+ }
+ }
+
+ private func load() async {
+ let api = session.api
+ do {
+ cloud = try await ipv64Retrying { try await api.hc2.nodes.list() }
+ planReason = nil
+ } catch is CancellationError {
+ } catch let apiError as IPv64Error where apiError.statusCode == 403 {
+ cloud = []
+ if case .api(let problem) = apiError, let detail = problem.detail.nonBlank {
+ planReason = detail
+ } else {
+ planReason = String(localized: "This feature is not available on your plan.")
+ }
+ } catch {
+ if cloud == nil { cloud = [] }
+ self.error = ErrorText(error)
+ }
+ nodes.refresh()
+ await nodes.refreshModules()
+ }
+
+ /// Polls the list every 5 s for up to 60 s until a new node (or a changed `linkedAt`) appears; one network
+ /// error is tolerated, a second one ends the wait.
+ private func waitForNode() async {
+ guard let request = wait else { return }
+ let api = session.api
+ var failures = 0
+ var found = false
+ for _ in 0..<12 {
+ do {
+ try await Task.sleep(for: .seconds(5))
+ } catch {
+ return
+ }
+ do {
+ let list = try await ipv64Retrying { try await api.hc2.nodes.list() }
+ cloud = list
+ found = list.contains { node in request.before[node.nodeID].map { $0 != node.linkedAt } ?? true }
+ if found { break }
+ } catch is CancellationError {
+ return
+ } catch {
+ failures += 1
+ if failures > 1 {
+ self.error = ErrorText(error)
+ break
+ }
+ }
+ }
+ if !found && error == nil {
+ error = ErrorText(title: String(localized: "Node not visible yet"),
+ message: String(localized: "The node has not fetched its token yet. Make sure it is online and has internet access, then pull down to refresh."))
+ }
+ nodes.refresh()
+ // Last: clearing `wait` cancels this task.
+ wait = nil
+ }
+
+ private func forget(_ id: String) {
+ nodes.forget(id)
+ withAnimation { nodes.refresh() }
+ }
+}
+
+private struct CloudNodeRow: View {
+ let node: HC2Node
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(NodesLogic.nodeName(node.name, nodeId: node.nodeID))
+ .font(.headline)
+ .lineLimit(1)
+ if let meta = NodesLogic.cloudMeta(location: node.location, version: node.version, lastSeen: node.lastSeen) {
+ Text(meta)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ Text(NodesLogic.remoteLine(node.remoteMgmt?.rawValue, conflicts: node.conflicts))
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if node.online == true {
+ HealthcheckTag(text: "Online", color: .green)
+ } else {
+ HealthcheckTag(text: "Offline", color: .gray)
+ }
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+private struct DirectNodeRow: View {
+ let name: String
+ let host: String
+ let version: String?
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name)
+ .font(.headline)
+ .lineLimit(1)
+ Text(verbatim: [version.map { "v" + $0 }, host.nonBlank].compactMap { $0 }.joined(separator: " · "))
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ HealthcheckTag(text: "Direct", color: .blue)
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// "Add node": link with a code (later step) or connect directly.
+private struct AddNodeSheet: View {
+ let planBlocked: Bool
+ let onLink: () -> Void
+ let onDirect: () -> Void
+
+ var body: some View {
+ DynDNSSheet(title: "Add node") {
+ Section {
+ option("Link node", subtitle: planBlocked ? "Not available on your plan"
+ : "Link it to your account with the code from \"ipv64 link\"", systemImage: "link", action: onLink)
+ .disabled(planBlocked)
+ }
+ Section {
+ option("Connect directly", subtitle: "By IP or link and API key, without linking", systemImage: "network",
+ action: onDirect)
+ }
+ }
+ .presentationDetents([.medium])
+ }
+
+ private func option(_ title: LocalizedStringKey, subtitle: LocalizedStringKey, systemImage: String,
+ action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Label {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title)
+ Text(subtitle).font(.subheadline).foregroundStyle(.secondary)
+ }
+ } icon: {
+ Image(systemName: systemImage)
+ }
+ }
+ .tint(.primary)
+ }
+}
+
+#Preview {
+ NavigationStack { NodesView() }
+ .environment(Session())
+ .environment(ConnectedNodes())
+}
diff --git a/IPv64/Views/Proxy/CdnModeSheet.swift b/IPv64/Views/Proxy/CdnModeSheet.swift
new file mode 100644
index 0000000..eecf80c
--- /dev/null
+++ b/IPv64/Views/Proxy/CdnModeSheet.swift
@@ -0,0 +1,129 @@
+import SwiftUI
+
+/// Mode and healthcheck choice for enabling CDN64 on one host. Modes 1 and 2 are selectable, 3 is info only.
+/// Owns the busy state: `enable` runs while the sheet shows a spinner and cannot be dismissed.
+struct CdnModeForm: View {
+ @Environment(\.dismiss) private var dismiss
+ let hostLabel: String?
+ let enable: (_ mode: Int, _ healthcheck: Bool) async -> Void
+
+ @State private var mode = 1
+ @State private var healthcheck = false
+ @State private var busy = false
+
+ var body: some View {
+ Form {
+ Section {
+ if let hostLabel { Text(verbatim: hostLabel).font(.headline) }
+ Text("Makes this host reachable from the internet via the ipv64 CDN64 servers, over IPv4 and IPv6. The node builds a tunnel outwards; no port needs to be open at home.")
+ .font(.subheadline).foregroundStyle(.secondary)
+ }
+ Section {
+ ForEach([1, 2], id: \.self) { m in
+ Button { mode = m } label: {
+ HStack(alignment: .top, spacing: 12) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(verbatim: ProxyLogic.modeShort(m) + " · " + ProxyLogic.cdnModeTitle(m))
+ .font(.body).foregroundStyle(.primary)
+ Text(verbatim: ProxyLogic.cdnModeDescription(m)).font(.subheadline).foregroundStyle(.secondary)
+ }
+ Spacer(minLength: 0)
+ if mode == m { Image(systemName: "checkmark").foregroundStyle(.tint) }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(mode == m ? .isSelected : [])
+ }
+ VStack(alignment: .leading, spacing: 4) {
+ Text(verbatim: ProxyLogic.modeShort(3) + " · " + ProxyLogic.cdnModeTitle(3)).font(.body)
+ Text(verbatim: ProxyLogic.cdnModeDescription(3)).font(.subheadline)
+ if let url = URL(string: "https://ipv64.net/cdn64") {
+ Link("ipv64.net/cdn64", destination: url).font(.subheadline)
+ }
+ }
+ .foregroundStyle(.secondary)
+ }
+ Section {
+ Toggle("Create healthcheck", isOn: $healthcheck)
+ }
+ }
+ .disabled(busy)
+ .navigationTitle("Enable CDN64")
+ .navigationBarTitleDisplayMode(.inline)
+ .navigationBarBackButtonHidden(busy)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ if busy {
+ ProgressView()
+ } else {
+ Button("Enable", systemImage: "checkmark") {
+ busy = true
+ Task {
+ await enable(mode, healthcheck)
+ dismiss()
+ }
+ }
+ }
+ }.appVerticalPreferred()
+ }
+ .interactiveDismissDisabled(busy)
+ }
+}
+
+/// Sheet for one known host.
+struct CdnModeSheet: View {
+ @Environment(\.dismiss) private var dismiss
+ let hostLabel: String?
+ let enable: (_ mode: Int, _ healthcheck: Bool) async -> Void
+
+ var body: some View {
+ NavigationStack {
+ CdnModeForm(hostLabel: hostLabel, enable: enable)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel", systemImage: "xmark") { dismiss() } }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ }
+}
+
+/// Host picker, then the mode form.
+struct CdnEnableFlow: View {
+ @Environment(\.dismiss) private var dismiss
+ let choices: [CdnHostChoice]
+ let enable: (CdnHostChoice, Int, Bool) async -> Void
+
+ @State private var picked: CdnHostChoice?
+
+ var body: some View {
+ NavigationStack {
+ List {
+ if choices.isEmpty {
+ Text("All proxy hosts already use CDN64.").foregroundStyle(.secondary)
+ }
+ ForEach(choices) { choice in
+ Button { picked = choice } label: {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: choice.label).font(.headline).foregroundStyle(.primary)
+ Text(verbatim: choice.nodeName).font(.subheadline).foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+ .navigationTitle("Enable CDN64 for a proxy host")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel", systemImage: "xmark") { dismiss() } }
+ }
+ .navigationDestination(item: $picked) { choice in
+ CdnModeForm(hostLabel: choice.label) { mode, healthcheck in
+ await enable(choice, mode, healthcheck)
+ }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.large])
+ }
+}
diff --git a/IPv64/Views/Proxy/ProxyHostEditView.swift b/IPv64/Views/Proxy/ProxyHostEditView.swift
new file mode 100644
index 0000000..45e60a5
--- /dev/null
+++ b/IPv64/Views/Proxy/ProxyHostEditView.swift
@@ -0,0 +1,221 @@
+import SwiftUI
+import IPv64
+
+/// Pushed from Proxy64: one proxy host of a node. `hostId == nil` creates a host.
+struct ProxyHostRoute: Hashable, Identifiable {
+ let nodeId: String
+ let hostId: Int?
+ var id: String { "\(nodeId)/\(hostId.map(String.init) ?? "new")" }
+}
+
+/// Proxy host editor: header, actions, host/target/options/advanced; save, delete.
+struct ProxyHostEditView: View {
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.dismiss) private var dismiss
+
+ let route: ProxyHostRoute
+ /// Tells Proxy64 that this node changed.
+ let onChanged: () -> Void
+
+ @State private var loaded: Node64.ProxyHost?
+ @State private var didLoad = false
+ @State private var form = ProxyHostForm()
+ /// State after loading (new host: empty form); Save is offered only when `form` differs.
+ @State private var initial = ProxyHostForm()
+ @State private var accessLists: [Int: String] = [:]
+ @State private var certificates: [Int: String] = [:]
+ @State private var cdnName: Node64.CDNOnlineName?
+ @State private var edges: [Node64.CDNOnlineEdge] = []
+ @State private var advanced = false
+ @State private var submitted = false
+ @State private var showMode = false
+ @State private var confirm: Confirm?
+ @State private var busy = false
+ @State private var error: ErrorText?
+
+ private enum Confirm { case delete, disableCdn }
+
+ private var hostId: Int? { route.hostId }
+ private var create: Bool { hostId == nil }
+ private var ready: Bool { create || loaded != nil }
+ private var changed: Bool { didLoad && ready && form != initial }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content.setColorGradient(showMode || confirm != nil || error != nil ? .clear : .orange)
+ } else { content }
+ }
+
+ private var content: some View {
+ Form {
+ if let loaded, !create {
+ Section { ProxyHostRow(host: loaded, cdn: cdnName, edges: edges) }
+ actions(loaded)
+ }
+ ProxyHostFormSections(form: $form, errors: submitted ? form.errors : nil, create: create,
+ offersDefaultTLS: loaded?.minTLS == nil,
+ accessLists: accessLists, certificates: certificates, advanced: $advanced)
+ }
+ .disabled(busy || !didLoad)
+ .overlay { if !didLoad { ProgressView() } }
+ .navigationTitle(create ? "New proxy host" : "Proxy host")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar { toolbar }
+ .sheet(isPresented: $showMode) {
+ CdnModeSheet(hostLabel: form.firstName.nonBlank) { mode, healthcheck in
+ await enableCdn(mode: mode, healthcheck: healthcheck)
+ }
+ }
+ .alert(confirm == .delete ? "Delete proxy host?" : "Disable CDN64?",
+ isPresented: Binding(get: { confirm != nil }, set: { if !$0 { confirm = nil } }), presenting: confirm) { item in
+ switch item {
+ case .delete: Button("Delete", role: .destructive) { Task { await delete() } }
+ case .disableCdn: Button("Disable", role: .destructive) { Task { await disableCdn() } }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: { item in
+ switch item {
+ case .delete: Text("\(form.firstName) will be removed from the node.")
+ case .disableCdn: Text("\(form.firstName) will no longer be reachable via the CDN64 servers.")
+ }
+ }
+ .errorAlert($error)
+ .task { await load() }
+ }
+
+ private func actions(_ host: Node64.ProxyHost) -> some View {
+ let on = host.enabled != false
+ return Section {
+ Button { Task { await toggleEnabled(on: on) } } label: {
+ Label(on ? "Disable host" : "Enable host", systemImage: on ? "pause.circle" : "play.circle")
+ }
+ Button { toggleCdn() } label: {
+ Label(cdnName == nil ? "Enable CDN64" : "Disable CDN64", systemImage: cdnName == nil ? "icloud" : "icloud.slash")
+ }
+ }
+ .tint(.primary)
+ }
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ if !create {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Delete", systemImage: "trash", role: .destructive) { confirm = .delete }
+ .tint(.red)
+ .disabled(busy || loaded == nil)
+ }
+ if #available(iOS 26.0, *), changed || busy {
+ ToolbarSpacer(.fixed, placement: .topBarTrailing)
+ }
+ }
+ // Only offered once something changed; invalid input is reported inline and in an alert on tap.
+ if changed || busy {
+ ToolbarItem(placement: .confirmationAction) {
+ if busy {
+ ProgressView()
+ } else {
+ Button("Save", systemImage: "checkmark") { Task { await save() } }
+ }
+ }.appVerticalPreferred()
+ }
+ }
+
+ // MARK: Actions
+
+ private func run(_ block: (Node64) async throws -> Void) async {
+ guard let node = nodes.client(for: route.nodeId) else {
+ error = ErrorText(title: String(localized: "No access"), message: String(localized: "No access saved for this node."))
+ return
+ }
+ busy = true
+ defer { busy = false }
+ do {
+ try await block(node)
+ } catch is CancellationError {
+ } catch {
+ self.error = ErrorText.node(error)
+ }
+ }
+
+ private func load() async {
+ await run { node in
+ if let hostId {
+ let host = try await node.proxy64.hosts.get(hostId)
+ loaded = host
+ form = ProxyHostForm(host: host)
+ initial = form
+ }
+ // Choices are optional: a failure only leaves them out.
+ if let lists = try? await node.proxy64.accessLists.list() {
+ accessLists = Dictionary(lists.compactMap { $0.accessList }.map { ($0.id, $0.name ?? "#\($0.id)") },
+ uniquingKeysWith: { a, _ in a })
+ }
+ if let certs = try? await node.certificates.list() {
+ certificates = Dictionary(certs.map { ($0.id, ($0.names ?? []).joined(separator: ", ").nonBlank ?? "#\($0.id)") },
+ uniquingKeysWith: { a, _ in a })
+ }
+ if let hostId { await refreshCdn(node, hostId) }
+ }
+ didLoad = true
+ }
+
+ private func refreshCdn(_ node: Node64, _ hostId: Int) async {
+ let status = try? await node.proxy64.online.status()
+ cdnName = status?.names?.first { $0.hostID == hostId }
+ edges = status?.edges ?? []
+ }
+
+ private func save() async {
+ submitted = true
+ if let message = form.errors.first {
+ error = ErrorText(title: String(localized: "Check your input"), message: message)
+ return
+ }
+ let input = form.input(create: create)
+ await run { node in
+ if let hostId { _ = try await node.proxy64.hosts.update(hostId, input) } else { _ = try await node.proxy64.hosts.create(input) }
+ onChanged()
+ dismiss()
+ }
+ }
+
+ private func delete() async {
+ guard let hostId else { return }
+ await run { node in
+ try await node.proxy64.hosts.delete(hostId)
+ onChanged()
+ dismiss()
+ }
+ }
+
+ private func toggleEnabled(on: Bool) async {
+ guard let hostId else { return }
+ await run { node in
+ loaded = on ? try await node.proxy64.hosts.disable(hostId) : try await node.proxy64.hosts.enable(hostId)
+ onChanged()
+ }
+ }
+
+ private func toggleCdn() {
+ if cdnName == nil { showMode = true } else { confirm = .disableCdn }
+ }
+
+ private func disableCdn() async {
+ guard let hostId else { return }
+ await run { node in
+ try await node.proxy64.online.disable(host: hostId)
+ await refreshCdn(node, hostId)
+ onChanged()
+ }
+ }
+
+ private func enableCdn(mode: Int, healthcheck: Bool) async {
+ guard let hostId else { return }
+ let choice = CdnHostChoice(nodeId: route.nodeId, nodeName: "", hostId: hostId, label: form.firstName)
+ busy = true
+ defer { busy = false }
+ if let failure = await nodes.enableCdn64(choice, mode: mode, healthcheck: healthcheck) { error = failure }
+ if let node = nodes.client(for: route.nodeId) { await refreshCdn(node, hostId) }
+ onChanged()
+ }
+}
diff --git a/IPv64/Views/Proxy/ProxyHostFormSections.swift b/IPv64/Views/Proxy/ProxyHostFormSections.swift
new file mode 100644
index 0000000..7a65208
--- /dev/null
+++ b/IPv64/Views/Proxy/ProxyHostFormSections.swift
@@ -0,0 +1,127 @@
+import SwiftUI
+import IPv64
+
+/// Form sections of the proxy host editor: Host, Target or Redirect, Options, Advanced (collapsible).
+struct ProxyHostFormSections: View {
+ @Binding var form: ProxyHostForm
+ /// Inline messages, `nil` until the first Save attempt.
+ let errors: ProxyHostForm.Errors?
+ let create: Bool
+ /// "Default" TLS is only offered while the loaded host has no value (nil would not be sent).
+ let offersDefaultTLS: Bool
+ let accessLists: [Int: String]
+ let certificates: [Int: String]
+ @Binding var advanced: Bool
+
+ var body: some View {
+ Section {
+ if create {
+ Picker("Type", selection: $form.kind) {
+ Text("Proxy").tag(Node64.ProxyHostKind.proxy)
+ Text("Redirect").tag(Node64.ProxyHostKind.redirect)
+ Text("TLS passthrough").tag(Node64.ProxyHostKind.passthrough)
+ Text("Status page").tag(Node64.ProxyHostKind.status)
+ }
+ }
+ TextField("Domain names", text: $form.names, axis: .vertical)
+ .lineLimit(2...6)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ if create { Toggle("Enabled", isOn: $form.enabled) }
+ } header: {
+ Text("Host")
+ } footer: {
+ HcFooter(hint: "One per line", error: errors?.names)
+ }
+
+ if form.isStatus {
+ Section {
+ LabeledContent("Status page ID") {
+ TextField("1", text: $form.statusPageID).multilineTextAlignment(.trailing).keyboardType(.numberPad)
+ }
+ } header: {
+ Text("Status page")
+ } footer: {
+ HcFooter(error: errors?.target)
+ }
+ }
+ if form.hasTarget {
+ Section {
+ if form.isProxy {
+ Picker("Scheme", selection: $form.scheme) {
+ Text("http").tag(Node64.ProxyHostScheme.http)
+ Text("https").tag(Node64.ProxyHostScheme.https)
+ }
+ }
+ LabeledContent("Target host") {
+ TextField("192.168.1.10", text: $form.host)
+ .multilineTextAlignment(.trailing)
+ .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)
+ }
+ LabeledContent("Target port") {
+ TextField("80", text: $form.port).multilineTextAlignment(.trailing).keyboardType(.numberPad)
+ }
+ } header: {
+ Text("Target")
+ } footer: {
+ HcFooter(error: errors?.target)
+ }
+ }
+ if form.isRedirect {
+ Section {
+ LabeledContent("Redirect target") {
+ TextField("example.com/path", text: $form.redirectTarget)
+ .multilineTextAlignment(.trailing)
+ .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)
+ }
+ Picker("Redirect scheme", selection: $form.redirectScheme) {
+ Text("auto").tag(Node64.ProxyHostRedirectScheme.auto)
+ Text("http").tag(Node64.ProxyHostRedirectScheme.http)
+ Text("https").tag(Node64.ProxyHostRedirectScheme.https)
+ }
+ Picker("Redirect code", selection: $form.redirectCode) {
+ ForEach(ProxyHostForm.redirectCodes, id: \.self) { Text(verbatim: "\($0)").tag($0) }
+ }
+ Toggle("Preserve path", isOn: $form.preservePath)
+ } header: {
+ Text("Redirect")
+ } footer: {
+ HcFooter(hint: "domain[:port][/path]", error: errors?.redirect)
+ }
+ }
+ if form.editable {
+ Section("Options") {
+ Toggle("Force HTTPS", isOn: $form.forceSSL)
+ if form.isProxy {
+ Toggle("WebSockets", isOn: $form.websockets)
+ Toggle("Block exploits", isOn: $form.blockExploits)
+ Toggle("Cache assets", isOn: $form.cacheAssets)
+ }
+ }
+ HcCollapsibleSection(title: "Advanced", isExpanded: $advanced) {
+ Toggle("HTTP/2", isOn: $form.http2)
+ Toggle("HTTP/3", isOn: $form.http3)
+ Toggle("HSTS", isOn: $form.hsts)
+ if form.hsts { Toggle("HSTS for subdomains", isOn: $form.hstsSubdomains) }
+ Picker("Minimum TLS", selection: $form.minTLS) {
+ if offersDefaultTLS { Text("Default").tag(Node64.ProxyHostMinTLS?.none) }
+ Text("1.2").tag(Node64.ProxyHostMinTLS?.some(.tls12))
+ Text("1.3").tag(Node64.ProxyHostMinTLS?.some(.tls13))
+ }
+ if form.isProxy { Toggle("Verify target certificate", isOn: $form.verifyTarget) }
+ Picker("Access list", selection: $form.accessListID) {
+ Text("None (public)").tag(0)
+ ForEach(accessLists.keys.sorted().filter { $0 != 0 }, id: \.self) { id in
+ Text(verbatim: accessLists[id] ?? "#\(id)").tag(id)
+ }
+ }
+ Picker("Certificate", selection: $form.certID) {
+ Text("Automatic (matching name)").tag(0)
+ Text("None (HTTP only)").tag(-1)
+ ForEach(certificates.keys.sorted().filter { $0 > 0 }, id: \.self) { id in
+ Text(verbatim: certificates[id] ?? "#\(id)").tag(id)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/Proxy/ProxyHostRow.swift b/IPv64/Views/Proxy/ProxyHostRow.swift
new file mode 100644
index 0000000..b287cc4
--- /dev/null
+++ b/IPv64/Views/Proxy/ProxyHostRow.swift
@@ -0,0 +1,91 @@
+import SwiftUI
+import IPv64
+
+/// Proxy host row: names bold, target secondary, reachability tag trailing, SSL and CDN64 tags below,
+/// options and counters as one secondary line.
+struct ProxyHostRow: View {
+ let host: Node64.ProxyHost
+ let cdn: Node64.CDNOnlineName?
+ var edges: [Node64.CDNOnlineEdge] = []
+
+ private var reach: ProxyLogic.Tag {
+ ProxyLogic.reachTag(enabled: host.enabled, state: host.reach?.state?.rawValue, ms: host.reach?.ms)
+ }
+
+ private var extraTags: [ProxyLogic.Tag] {
+ var list: [ProxyLogic.Tag] = []
+ if let ssl = ProxyLogic.sslTag(state: host.certificate?.state?.rawValue, daysLeft: host.certificate?.daysLeft) {
+ list.append(ssl)
+ }
+ if let cdn {
+ list.append(ProxyLogic.cdnTag(mode: cdn.mode, edgeCount: edges.count, up: edges.filter { $0.connected == true }.count))
+ }
+ return list
+ }
+
+ private var subtitle: String {
+ ProxyLogic.hostSubtitle(kind: host.kind?.rawValue, scheme: host.scheme?.rawValue, targetHost: host.targetHost,
+ targetPort: host.targetPort, redirectTarget: host.redirectTarget)
+ }
+
+ private var detailLine: String? {
+ let options = ProxyLogic.optionsLine(
+ websockets: host.websockets, blockExploits: host.blockExploits, cacheAssets: host.cacheAssets,
+ forceSSL: host.forceSSL, http2: host.http2, http3: host.http3, hsts: host.hsts, accessListID: host.accessListID)
+ let counters = ProxyLogic.counterLine(requests: host.stats?.requests, errors: host.stats?.errors, blocked: host.stats?.blocked)
+ let line = [options, counters].compactMap { $0 }.joined(separator: " · ")
+ return line.isEmpty ? nil : line
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: (host.names ?? []).joined(separator: ", ").nonBlank ?? "–").font(.headline).lineLimit(2)
+ if !subtitle.isEmpty {
+ Text(verbatim: subtitle).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ ProxyTag(tag: reach)
+ }
+ if !extraTags.isEmpty {
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 6) { ForEach(extraTags, id: \.text) { ProxyTag(tag: $0) } }
+ VStack(alignment: .leading, spacing: 4) { ForEach(extraTags, id: \.text) { ProxyTag(tag: $0) } }
+ }
+ }
+ if let detailLine {
+ Text(verbatim: detailLine).font(.caption).foregroundStyle(.secondary)
+ }
+ if let error = (host.routeError ?? host.certificateError)?.nonBlank {
+ Text(verbatim: error).font(.caption).foregroundStyle(.red)
+ }
+ }
+ .padding(.vertical, 2)
+ }
+}
+
+/// Capsule tag in the style of the other lists.
+struct ProxyTag: View {
+ let tag: ProxyLogic.Tag
+
+ private var color: Color {
+ switch tag.tone {
+ case .gray: .gray
+ case .green: .green
+ case .orange: .orange
+ case .red: .red
+ }
+ }
+
+ var body: some View {
+ Text(verbatim: tag.text)
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(color)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(color.opacity(0.15), in: Capsule())
+ .fixedSize()
+ }
+}
diff --git a/IPv64/Views/Proxy/ProxyUsageSection.swift b/IPv64/Views/Proxy/ProxyUsageSection.swift
new file mode 100644
index 0000000..153e3d5
--- /dev/null
+++ b/IPv64/Views/Proxy/ProxyUsageSection.swift
@@ -0,0 +1,76 @@
+import SwiftUI
+import IPv64
+
+/// CDN64 usage in the style of Health / Screen Time, domains and traffic side by side. The node's quota is
+/// preferred, else the account's usage. Limit 0 or missing = unlimited.
+struct ProxyUsageSection: View {
+ let usage: Me.Usage?
+ let quota: Node64.CDNOnlineQuota?
+
+ private var blocks: (domains: UsageBlock, traffic: UsageBlock)? {
+ if let quota {
+ let domains = quota.domains
+ let domainLimit = ProxyLogic.limit(domains?.limit)
+ let used = quota.trafficMB?.used ?? 0
+ let trafficLimit = ProxyLogic.limit(quota.trafficMB?.limit)
+ return (
+ UsageBlock(title: "CDN domains", value: "\(domains?.used ?? 0)",
+ limit: domainLimit.map { String(localized: "of \($0)") } ?? String(localized: "unlimited"),
+ fraction: ProxyLogic.fraction(used: Double(domains?.used ?? 0), limit: domainLimit)),
+ UsageBlock(title: "Traffic this month", value: ProxyLogic.megabytes(used),
+ limit: trafficLimit.map { String(localized: "of \(ProxyLogic.megabytes(Double($0)))") } ?? String(localized: "unlimited"),
+ fraction: ProxyLogic.fraction(used: used, limit: trafficLimit),
+ hint: quota.bandwidthMbit.map {
+ $0 > 0 ? String(localized: "Bandwidth: \($0) Mbit/s") : String(localized: "Bandwidth: unlimited")
+ }))
+ }
+ guard usage?.cdnDomains != nil || usage?.cdnTrafficGB != nil else { return nil }
+ let d = usage?.cdnDomains, t = usage?.cdnTrafficGB
+ let domainLimit = ProxyLogic.limit(d?.limit)
+ let trafficLimit = ProxyLogic.limit(t?.limit)
+ return (
+ UsageBlock(title: "CDN domains", value: "\(Int(d?.used ?? 0))",
+ limit: domainLimit.map { String(localized: "of \($0)") } ?? String(localized: "unlimited"),
+ fraction: ProxyLogic.fraction(used: d?.used, limit: domainLimit)),
+ UsageBlock(title: "Traffic this month", value: ProxyLogic.megabytes((t?.used ?? 0) * 1024),
+ limit: trafficLimit.map { String(localized: "of \(ProxyLogic.megabytes(Double($0) * 1024))") } ?? String(localized: "unlimited"),
+ fraction: ProxyLogic.fraction(used: t?.used, limit: trafficLimit)))
+ }
+
+ var body: some View {
+ if let blocks {
+ Section("Usage") {
+ HStack(alignment: .top, spacing: 16) {
+ blocks.domains
+ blocks.traffic
+ }
+ .padding(.vertical, 4)
+ }
+ }
+ }
+}
+
+/// One number block of a usage section: title, number, limit text, progress bar and optional small hint.
+struct UsageBlock: View {
+ let title: LocalizedStringKey
+ let value: String
+ let limit: String
+ let fraction: Double?
+ var hint: String?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
+ Text(verbatim: value)
+ .font(.system(.title, design: .rounded, weight: .semibold))
+ .lineLimit(1).minimumScaleFactor(0.6)
+ Text(verbatim: limit).font(.footnote).foregroundStyle(.secondary).lineLimit(1)
+ if let fraction {
+ ProgressView(value: fraction).tint(fraction >= 1 ? .red : fraction >= 0.8 ? .orange : .accentColor)
+ }
+ if let hint { Text(verbatim: hint).font(.caption).foregroundStyle(.secondary) }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/IPv64/Views/Proxy/ProxyView.swift b/IPv64/Views/Proxy/ProxyView.swift
new file mode 100644
index 0000000..68dd59b
--- /dev/null
+++ b/IPv64/Views/Proxy/ProxyView.swift
@@ -0,0 +1,166 @@
+import SwiftUI
+import IPv64
+
+/// Proxy64 tab: usage, entry to CDN64, proxy hosts per connected node.
+struct ProxyView: View {
+ @Environment(Session.self) private var session
+ @Environment(ConnectedNodes.self) private var nodes
+ @Binding var popToRootTab: Tabs
+ @State private var groups: [ProxyNodeData]?
+ @State private var usage: Me.Usage?
+ @State private var sheet: ProxySheet?
+ @State private var newHost: ProxyHostRoute?
+ @State private var error: ErrorText?
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView.setColorGradient(sheet != nil ? .clear : .orange)
+ } else { listView }
+ }
+
+ private var listView: some View {
+ List {
+ if groups != nil {
+ ProxyUsageSection(usage: usage, quota: groups?.lazy.compactMap { $0.online?.quota }.first)
+ cdnSection
+ ForEach(groups ?? []) { group in
+ Section(group.name) {
+ if let error = group.error {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: error.title)
+ Text(verbatim: error.message).font(.subheadline).foregroundStyle(.secondary)
+ Text("Check the connection under More → Nodes.").font(.subheadline).foregroundStyle(.secondary)
+ }
+ } else if group.hosts.isEmpty {
+ Text("No hosts.").foregroundStyle(.secondary)
+ }
+ ForEach(group.hosts) { host in
+ NavigationLink(value: ProxyHostRoute(nodeId: group.id, hostId: host.id)) {
+ ProxyHostRow(host: host, cdn: group.cdn[host.id], edges: group.online?.edges ?? [])
+ }
+ .swipeActions {
+ if group.cdn[host.id] == nil && group.error == nil {
+ Button("Enable CDN64", systemImage: "cloud") {
+ sheet = .enableCdn(CdnHostChoice(nodeId: group.id, nodeName: group.name, hostId: host.id,
+ label: (host.names ?? []).joined(separator: ", ").nonBlank ?? "#\(host.id)"))
+ }
+ .labelStyle(.iconOnly)
+ .tint(.blue)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ .overlay { if groups == nil { ProgressView("Loading Proxy64…") } }
+ .navigationTitle(Tabs.proxy64.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { addHost() } label: { Label("New proxy host", systemImage: "plus") }
+ .disabled(groups == nil || nodes.proxyIds.isEmpty)
+ }
+ }
+ .navigationDestination(for: ProxyHostRoute.self) { editor($0) }
+ .navigationDestination(item: $newHost) { editor($0) }
+ .refreshable { await load() }
+ .task(id: nodes.proxyIds) { await load() }
+ .sheet(item: $sheet) { sheet in
+ switch sheet {
+ case .enableFlow(let choices):
+ CdnEnableFlow(choices: choices) { choice, mode, healthcheck in
+ if let failure = await nodes.enableCdn64(choice, mode: mode, healthcheck: healthcheck) { error = failure }
+ await reload(node: choice.nodeId)
+ }
+ case .pickNode:
+ DynDNSSheet(title: "Select node") {
+ Section {
+ ForEach(nodes.proxyIds, id: \.self) { id in
+ Button(nodes.name(of: id)) {
+ self.sheet = nil
+ newHost = ProxyHostRoute(nodeId: id, hostId: nil)
+ }
+ .foregroundStyle(.primary)
+ }
+ }
+ }
+ .appReadableWidth()
+ .presentationDetents([.medium])
+ case .enableCdn(let choice):
+ CdnModeSheet(hostLabel: choice.label) { mode, healthcheck in
+ if let failure = await nodes.enableCdn64(choice, mode: mode, healthcheck: healthcheck) { error = failure }
+ await reload(node: choice.nodeId)
+ }
+ }
+ }
+ .errorAlert($error)
+ }
+
+ private var cdnNameCount: Int { (groups ?? []).reduce(0) { $0 + ($1.online?.names?.count ?? 0) } }
+
+ private var cdnSection: some View {
+ Section("CDN64") {
+ NavigationLink {
+ CdnView(popToRootTab: $popToRootTab)
+ } label: {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("CDN64")
+ Text("\(cdnNameCount) names")
+ .font(.subheadline).foregroundStyle(.secondary)
+ }
+ }
+ Button { addCdn() } label: { Label("Add domain to CDN64", systemImage: "plus.circle") }
+ }
+ }
+
+ private func editor(_ route: ProxyHostRoute) -> some View {
+ ProxyHostEditView(route: route) { Task { await reload(node: route.nodeId) } }
+ }
+
+ /// Node API only: hosts of the reachable nodes that are not in CDN64 yet.
+ private func addCdn() {
+ let reachable = (groups ?? []).filter { $0.error == nil }
+ if reachable.isEmpty {
+ error = ProxyLogic.noNodeError
+ } else {
+ sheet = .enableFlow(reachable.flatMap(\.cdnChoices))
+ }
+ }
+
+ private func addHost() {
+ if nodes.proxyIds.count == 1, let id = nodes.proxyIds.first {
+ newHost = ProxyHostRoute(nodeId: id, hostId: nil)
+ } else if nodes.proxyIds.count > 1 {
+ sheet = .pickNode
+ }
+ }
+
+ /// Only the changed node is loaded again.
+ private func reload(node id: String) async {
+ let fresh = await nodes.loadProxyNode(id, withHosts: true)
+ if let index = groups?.firstIndex(where: { $0.id == id }) { groups?[index] = fresh } else { await load() }
+ }
+
+ private func load() async {
+ let api = session.api
+ async let me = try? ipv64Retrying { try await api.account.me() }
+ let loaded = await nodes.loadProxyNodes(withHosts: true)
+ usage = await me?.usage
+ if !Task.isCancelled { groups = loaded }
+ }
+}
+
+private enum ProxySheet: Identifiable {
+ case pickNode
+ case enableCdn(CdnHostChoice)
+ case enableFlow([CdnHostChoice])
+
+ var id: String {
+ switch self {
+ case .enableFlow: "flow"
+ case .pickNode: "node"
+ case .enableCdn(let choice): "cdn/" + choice.id
+ }
+ }
+}
diff --git a/IPv64/Views/Push/NotificationPermission.swift b/IPv64/Views/Push/NotificationPermission.swift
new file mode 100644
index 0000000..ebb1e36
--- /dev/null
+++ b/IPv64/Views/Push/NotificationPermission.swift
@@ -0,0 +1,81 @@
+import SwiftUI
+import UserNotifications
+
+/// System notification permission (Android `rememberNotificationPermissionState`), re-read on every foreground.
+enum NotificationPermission: Equatable {
+ case unknown, canRequest, allowed, denied
+
+ var isAllowed: Bool { self == .allowed }
+
+ static func current() async -> NotificationPermission {
+ switch await UNUserNotificationCenter.current().notificationSettings().authorizationStatus {
+ case .notDetermined: .canRequest
+ case .authorized, .provisional, .ephemeral: .allowed
+ default: .denied
+ }
+ }
+
+ static func request() async -> NotificationPermission {
+ _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])
+ UIApplication.shared.registerForRemoteNotifications()
+ return await current()
+ }
+}
+
+extension View {
+ /// Keeps `permission` current while the view is visible (Android: re-evaluated on ON_RESUME).
+ func trackingNotificationPermission(_ permission: Binding) -> some View {
+ modifier(NotificationPermissionTracker(permission: permission))
+ }
+}
+
+private struct NotificationPermissionTracker: ViewModifier {
+ @Environment(\.scenePhase) private var scenePhase
+ @Binding var permission: NotificationPermission
+
+ func body(content: Content) -> some View {
+ content.task(id: scenePhase) {
+ if scenePhase == .active { permission = await NotificationPermission.current() }
+ }
+ }
+}
+
+/// Android `NotificationPermissionActions` (spec 04 §6.7): text + "Allow notifications"/"Settings" or "Open settings".
+struct NotificationPermissionActions: View {
+ @Environment(\.openURL) private var openURL
+ @Binding var permission: NotificationPermission
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if permission == .canRequest {
+ Text("Allow IPv64.net to show notifications so alerts can reach you.")
+ ViewThatFits(in: .horizontal) {
+ HStack { permissionButtons }
+ VStack(alignment: .leading) { permissionButtons }
+ }
+ } else {
+ Text("Notifications are turned off for IPv64.net. Turn them on in the system settings.")
+ Button("Open settings", systemImage: "gear", action: openSettings)
+ .buttonStyle(.borderedProminent)
+ }
+ }
+ .font(.subheadline)
+ .padding(.vertical, 4)
+ }
+
+ @ViewBuilder private var permissionButtons: some View {
+ // Text only: an SF Symbol in a bordered button inside a list row leaves an empty icon gap.
+ Button("Allow notifications", action: allow)
+ .buttonStyle(.borderedProminent)
+ Button("Settings", action: openSettings)
+ .buttonStyle(.bordered)
+ }
+
+ private func allow() {
+ Task { permission = await NotificationPermission.request() }
+ }
+
+ private func openSettings() {
+ if let url = URL(string: UIApplication.openNotificationSettingsURLString) { openURL(url) }
+ }
+}
diff --git a/IPv64/Views/Push/PushSetupSteps.swift b/IPv64/Views/Push/PushSetupSteps.swift
new file mode 100644
index 0000000..60270f0
--- /dev/null
+++ b/IPv64/Views/Push/PushSetupSteps.swift
@@ -0,0 +1,115 @@
+import SwiftUI
+import IPv64
+
+/// Numbered step header; a green seal replaces the number when the step is done.
+private struct StepHeader: View {
+ let number: Int
+ let title: LocalizedStringKey
+ let done: Bool
+
+ var body: some View {
+ HStack(spacing: 8) {
+ if done {
+ Image(systemName: "checkmark.seal.fill").foregroundStyle(Color.green)
+ .accessibilityLabel(Text("Done"))
+ } else {
+ Text(verbatim: "\(number)")
+ .font(.caption.weight(.bold))
+ .foregroundStyle(.white)
+ .frame(width: 20, height: 20)
+ .background(Circle().fill(Color.accentColor))
+ }
+ Text(title)
+ }
+ }
+}
+
+/// Step 1 "Allow notifications".
+struct AllowStep: View {
+ @Binding var permission: NotificationPermission
+
+ var body: some View {
+ Section {
+ switch permission {
+ case .allowed: Text("Notifications are allowed.")
+ case .unknown: ProgressView()
+ case .canRequest, .denied: NotificationPermissionActions(permission: $permission)
+ }
+ } header: {
+ StepHeader(number: 1, title: "Allow notifications", done: permission.isAllowed)
+ }
+ }
+}
+
+/// Step 2 "Register this device": name prefilled with the SecNtfy model, editable until registered.
+struct RegisterStep: View {
+ @Binding var deviceName: String
+ let permissionAllowed: Bool
+ let registeredText: String?
+ let appSupported: Bool?
+ let isRegistering: Bool
+ let canRegister: Bool
+ let onRegister: () -> Void
+
+ var body: some View {
+ Section {
+ if let registeredText {
+ Text(verbatim: registeredText)
+ } else if appSupported == false {
+ Text("Push notifications to the IPv64 app are not supported by the server yet. You can skip this step.")
+ } else {
+ TextField("Device name", text: $deviceName)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .submitLabel(.done)
+ if isRegistering {
+ HStack {
+ ProgressView()
+ Text("Registering this device...")
+ }
+ } else {
+ Button("Register this device", systemImage: "iphone.badge.play", action: onRegister)
+ .disabled(!canRegister)
+ }
+ if !permissionAllowed {
+ Text("Allow notifications first.").foregroundStyle(.secondary)
+ }
+ }
+ } header: {
+ StepHeader(number: 2, title: "Register this device", done: registeredText != nil)
+ }
+ }
+}
+
+/// Step 3 "Send a test" (dimmed until registered).
+struct TestStep: View {
+ let registered: Bool
+ let notificationsAllowed: Bool
+ let resultText: String?
+ let isSending: Bool
+ let onTest: () -> Void
+ let onDone: () -> Void
+
+ var body: some View {
+ Section {
+ if registered {
+ if !notificationsAllowed {
+ Text("Notifications are not allowed yet, so the test push won't be shown.")
+ .foregroundStyle(Color.orange)
+ }
+ Button("Send test notification", systemImage: "paperplane", action: onTest)
+ .disabled(isSending)
+ if let resultText { Text(verbatim: resultText).font(.footnote) }
+ Button(action: onDone) {
+ Text("Done").frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.borderedProminent)
+ } else {
+ Text("Register this device first.").foregroundStyle(.secondary)
+ }
+ } header: {
+ StepHeader(number: 3, title: "Send a test", done: false)
+ }
+ .opacity(registered ? 1 : 0.6)
+ }
+}
diff --git a/IPv64/Views/Push/PushSetupView.swift b/IPv64/Views/Push/PushSetupView.swift
new file mode 100644
index 0000000..df1e81b
--- /dev/null
+++ b/IPv64/Views/Push/PushSetupView.swift
@@ -0,0 +1,131 @@
+import SwiftUI
+import IPv64
+
+/// Push notifications setup (spec 04 §7): 1 allow notifications, 2 register this device, 3 send a test.
+/// Shown pushed (Route.pushSetup) or full screen after the first login; Skip / Done call
+/// `PushSetupStore.markDone(apiKey:)` before closing (otherwise the start trigger fires again).
+struct PushSetupView: View {
+ @Environment(Session.self) private var session
+ @Environment(PushRegistrar.self) private var registrar
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var permission = NotificationPermission.unknown
+ @State private var appSupported: Bool?
+ @State private var deviceChannel: HC2Channel?
+ @State private var detectedOnOpen = false
+ @State private var initialLoadDone = false
+ @State private var isRegistering = false
+ @State private var deviceName = PushRegistrar.defaultDeviceName
+ @State private var testText: String?
+ @State private var isSendingTest = false
+ @State private var error: ErrorText?
+ @State private var message: ErrorText?
+ @State private var finished = false
+
+ private var registeredText: String? {
+ guard let channel = deviceChannel else { return nil }
+ let name = ChannelLogic.displayName(channel)
+ if detectedOnOpen { return String(localized: "Already registered as “\(name)”. Its existing settings are kept.") }
+ return String(localized: "Registered as “\(name)”.")
+ }
+
+ private var canRegister: Bool {
+ permission.isAllowed && initialLoadDone && !isRegistering && deviceName.nonBlank != nil
+ }
+
+ // Shown as a sheet: no colour gradient (see CLAUDE.md).
+ var body: some View {
+ Form {
+ Section {
+ Label("Get a push notification on this device when a healthcheck goes down or recovers.", systemImage: "bell.badge")
+ }
+ AllowStep(permission: $permission)
+ RegisterStep(deviceName: $deviceName, permissionAllowed: permission.isAllowed,
+ registeredText: registeredText, appSupported: appSupported,
+ isRegistering: isRegistering, canRegister: canRegister) {
+ // Spinner at once and keyboard away; the first registration can take a while.
+ isRegistering = true
+ UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
+ Task { await register() }
+ }
+ TestStep(registered: deviceChannel != nil, notificationsAllowed: permission.isAllowed, resultText: testText,
+ isSending: isSendingTest, onTest: sendTest, onDone: finish)
+ }
+ .navigationTitle("Push notifications")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button(deviceChannel != nil ? "Done" : "Skip", action: finish)
+ }
+ }
+ .interactiveDismissDisabled()
+ .appHorizontalBars()
+ .trackingNotificationPermission($permission)
+ .task { await initialLoad() }
+ .errorAlert($error)
+ .errorAlert($message)
+ }
+
+ /// Mark done BEFORE closing; a second tap must not close twice.
+ private func finish() {
+ guard !finished else { return }
+ finished = true
+ PushSetupStore.markDone(apiKey: session.apiKey)
+ dismiss()
+ }
+
+ /// Detects this device's channel (stored id or same token); failures surface when registering.
+ private func initialLoad() async {
+ defer { initialLoadDone = true }
+ await registrar.ensureAccountId()
+ let client = session.api
+ guard let list = try? await ipv64Retrying({ try await client.hc2.channels.list() }) else { return }
+ let types = try? await ipv64Retrying { try await client.hc2.channels.types() }
+ appSupported = types.map { PushTokenLogic.appType($0) != nil }
+ _ = try? await registrar.syncTokenIfChanged(channels: list)
+ if deviceChannel == nil {
+ deviceChannel = registrar.detectThisDevice(list, types: types)
+ detectedOnOpen = deviceChannel != nil
+ }
+ }
+
+ /// Always a new channel for this device, notifying on down and up and used as default.
+ private func register() async {
+ guard let name = deviceName.nonBlank?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
+ let settings = DeviceChannelSettings(name: name, isDefault: true, notifyDown: true,
+ notifyUp: true, lang: ChannelLogic.systemLanguage)
+ isRegistering = true
+ defer { isRegistering = false }
+ do {
+ if case .registered(let channel, _) = try await registrar.registerThisDevice(settings, createNew: true) {
+ deviceChannel = channel
+ detectedOnOpen = false
+ testText = nil
+ }
+ } catch is CancellationError {
+ // Sheet closed while registering: nothing to report.
+ } catch let error as URLError where error.code == .cancelled {
+ } catch let failure as PushRegistrationError {
+ message = ErrorText(title: failure.title, message: failure.message)
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+
+ private func sendTest() {
+ guard let id = deviceChannel?.id else { return }
+ let client = session.api
+ Task {
+ isSendingTest = true
+ defer { isSendingTest = false }
+ do {
+ let result = try await ipv64Retrying { try await client.hc2.channels.sendTest(id) }
+ testText = result.sent == true ? String(localized: "Sent – you should get a push now.")
+ : result.queuedAtNode == true ? String(localized: "Queued – you should get a push shortly.")
+ : String(localized: "The server did not send the test notification.")
+ } catch {
+ self.error = ErrorText(error)
+ }
+ }
+ }
+}
diff --git a/IPv64/Views/Settings/AboutView.swift b/IPv64/Views/Settings/AboutView.swift
new file mode 100644
index 0000000..0b1ed8b
--- /dev/null
+++ b/IPv64/Views/Settings/AboutView.swift
@@ -0,0 +1,100 @@
+//
+// AboutView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import SwiftUI
+
+struct AboutView: View {
+
+ @Binding var popToRootTab: Tabs
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView
+ .setColorGradient(.orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ List {
+ Section("Help") {
+ HStack {
+ Image(systemName: "circle.fill")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 10, height: 10)
+ .foregroundStyle(.red)
+ .padding(.trailing, 5)
+ Text("A-Record or AAAA-Record didn't match")
+ .multilineTextAlignment(.leading)
+ }
+ HStack {
+ Image(systemName: "circle.fill")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 10, height: 10)
+ .foregroundStyle(.green)
+ .padding(.trailing, 5)
+ Text("A-Record or AAAA-Record match")
+ .multilineTextAlignment(.leading)
+ }
+ HStack {
+ Image(systemName: "circle.fill")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 10, height: 10)
+ .foregroundStyle(.gray)
+ .padding(.trailing, 5)
+ Text("IP unknown")
+ .multilineTextAlignment(.leading)
+ }
+ HStack {
+ Image(systemName: "circle.fill")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 10, height: 10)
+ .foregroundStyle(.gray)
+ .padding(.trailing, 5)
+ Text("No IP")
+ .multilineTextAlignment(.leading)
+ }
+ }
+ Section("What is IPv64.net?") {
+ Text("IPv64 is of course not a new Internet Protocol (64), but simply a deduplicated short form of IPv6 and IPv4. On the IPv64 site you will find a Dynamic DNS service (DynDNS) and many other useful tools for your daily internet experience.\n\nWith the dynamic DNS service of IPv64 you can register and use free subdomains. The update of the domain is done automatically by your own router or alternative hardware / software. Besides updating IP addresses, simple Let's Encrypt DNS challenges are also possible.\n\nOwn domains can be added and benefit from all IPv64.net features like DynDNS services, GEO load balancing, DDoS protection, DynDNS2 and SSL encryption.")
+ }
+ Section("Contact") {
+ Text("IPv64.net - A product of x64 GmbH\n\nInformation according to Section § 5 DDG\nx64 GmbH\nAm Eisenstein 10\n45470 Mülheim an der Ruhr\n\nEmail: info@ipv64.net\n\nRepresented by\nDennis Schröder (Managing Director)\n\nRegistry court: Amtsgericht Duisburg\nRegister number: HRB 35106\nUst-IdNr.: DE350434683")
+ }
+ Section("About the App") {
+ Text("This app was created with the help of the Raspberry Pi Cloud community. All rights reserved by Dennis Schröder.")
+ Button(action: {
+ if let url = URL(string: "https://github.com/androidseb25") {
+ UIApplication.shared.open(url)
+ }
+ }) {
+ Text("Visit me on GitHub (androidseb25)")
+ }
+ Button(action: {
+ if let url = URL(string: "https://github.com/androidseb25/IPv64-Android") {
+ UIApplication.shared.open(url)
+ }
+ }) {
+ Text("Visit the project on GitHub")
+ }
+ }
+ }
+ .navigationTitle(Tabs.about.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+}
+
+#Preview {
+ NavigationStack {
+ AboutView(popToRootTab: .constant(.domain))
+ }
+}
diff --git a/IPv64/Views/Settings/LogItemView.swift b/IPv64/Views/Settings/LogItemView.swift
new file mode 100644
index 0000000..d6baed6
--- /dev/null
+++ b/IPv64/Views/Settings/LogItemView.swift
@@ -0,0 +1,34 @@
+//
+// LogItemView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 24.10.25.
+//
+
+import Foundation
+import SwiftUI
+import IPv64
+
+struct LogItemView: View {
+ let log: LogEntry
+
+ var body: some View {
+ VStack {
+ Text(log.title ?? "")
+ .font(.title2)
+ .fontWeight(.bold)
+ .multilineTextAlignment(.leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Text(log.message ?? "")
+ .multilineTextAlignment(.leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.bottom, 5)
+ Text(log.time?.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits).second(.twoDigits).day(.twoDigits).month(.twoDigits).year().locale(Locale(identifier: "de_DE"))) ?? "")
+ .font(.subheadline)
+ .multilineTextAlignment(.leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .foregroundStyle(.gray)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
diff --git a/IPv64/Views/Settings/LogView.swift b/IPv64/Views/Settings/LogView.swift
new file mode 100644
index 0000000..08c8590
--- /dev/null
+++ b/IPv64/Views/Settings/LogView.swift
@@ -0,0 +1,74 @@
+//
+// LogView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import SwiftUI
+import IPv64
+
+struct LogView: View {
+
+ @Binding var popToRootTab: Tabs
+
+ @Environment(Session.self) private var session
+ @State private var logs: [LogEntry] = []
+ @State private var nextBefore: Int?
+ @State private var isLoading = false
+ @State private var error: ErrorText?
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView
+ .setColorGradient(.orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ List {
+ Section {
+ if logs.isEmpty {
+ if !isLoading {
+ ContentUnavailableView("No logs found", systemImage: "magnifyingglass")
+ }
+ } else {
+ ForEach(logs) { log in
+ LogItemView(log: log)
+ .onAppear {
+ if log.id == logs.last?.id { Task { await load(more: true) } }
+ }
+ }
+ }
+ }
+ }
+ .showLoading(.constant(isLoading && logs.isEmpty))
+ .errorAlert($error)
+ .navigationTitle(Tabs.log.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .task { await load(more: false) }
+ }
+
+ private func load(more: Bool) async {
+ guard !isLoading, !more || nextBefore != nil else { return }
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ let before = more ? nextBefore : nil
+ let page = try await ipv64Retrying { try await session.api.account.logs(before: before) }
+ if Task.isCancelled { return }
+ logs = more ? logs + page.items : page.items
+ nextBefore = page.meta?.nextBefore
+ } catch {
+ if !Task.isCancelled { self.error = ErrorText(error) }
+ }
+ }
+}
+
+#Preview {
+ NavigationStack {
+ LogView(popToRootTab: .constant(.domain))
+ }
+}
diff --git a/IPv64/Views/Settings/LoggerView.swift b/IPv64/Views/Settings/LoggerView.swift
new file mode 100644
index 0000000..e0d38f9
--- /dev/null
+++ b/IPv64/Views/Settings/LoggerView.swift
@@ -0,0 +1,97 @@
+//
+// LoggerView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 06.11.25.
+//
+
+import SwiftUI
+import SwiftyBeaver
+
+struct LoggerView: View {
+
+ @Environment(\.colorScheme) var systemColorScheme
+
+ @Binding var popToRootTab: Tabs
+
+ @State var showToolbar: Bool
+
+ @Environment(\.dismiss) var dismiss
+ @State private var selectedLog = ""
+ @State private var showLog = false
+ @State private var logFiles: [String] = []
+ @State private var showDeleteAlert = false
+
+ var body: some View {
+ VStack {
+ if #available(iOS 26.0, *) {
+ listContent
+ .setColorGradient(.orange)
+ } else {
+ listContent
+ }
+ }
+ .navigationDestination(isPresented: $showLog) {
+ LoggerViewDetail(selectedLog: selectedLog)
+ }
+ .alert("Do you really delete?", isPresented: $showDeleteAlert) {
+ Button("Delete now", role: .destructive) {
+ Task {
+ let result = await iLogger.removeLogFile(file: selectedLog)
+ if (result) {
+ iLogger.log.info("File: \"\(selectedLog)\" successfully deleted!")
+ logFiles = await iLogger.getFileList()
+ }
+ }
+ }
+ } message: {
+ Text("Are you sure you want to delete the file: \n\'\(selectedLog)\' \n\nThe file cannot be restored!")
+ }
+ }
+
+ private var listContent: some View {
+ return List {
+ ForEach(logFiles, id: \.self) { file in
+ Button(action: {
+ selectedLog = file
+ showLog.toggle()
+ }) {
+ NavigationLink(file, value: file)
+ .foregroundStyle(systemColorScheme == .dark ? Color.white : Color.black)
+ }
+ .swipeActions {
+ Button(action: {
+ withAnimation {
+ selectedLog = file
+ showDeleteAlert.toggle()
+ }
+ }) {
+ Image(systemName: "trash")
+ .resizable()
+ .symbolRenderingMode(.hierarchical)
+ }
+ .tint(.red)
+ }
+ }
+ }
+ .navigationTitle(Tabs.syslog.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar(content: {
+ if (showToolbar) {
+ ToolbarItem(placement: .primaryAction) {
+ Button("Close", systemImage: "xmark") { dismiss() }
+ .tint(systemColorScheme == .dark ? .white : .black)
+ }
+ }
+ })
+ .onAppear {
+ Task {
+ logFiles = await iLogger.getFileList()
+ }
+ }
+ }
+}
+
+#Preview {
+ LoggerView(popToRootTab: .constant(Tabs.syslog), showToolbar: false)
+}
diff --git a/IPv64/Views/Settings/LoggerViewDetail.swift b/IPv64/Views/Settings/LoggerViewDetail.swift
new file mode 100644
index 0000000..7e429d0
--- /dev/null
+++ b/IPv64/Views/Settings/LoggerViewDetail.swift
@@ -0,0 +1,58 @@
+//
+// LoggerViewDetail.swift
+// IPv64
+//
+// Created by Sebastian Rank on 06.11.25.
+//
+
+import SwiftUI
+
+struct LoggerViewDetail: View {
+
+ @Environment(\.colorScheme) var colorScheme: ColorScheme
+
+ @State var selectedLog: String
+
+ @State private var log = ""
+
+ var body: some View {
+ VStack {
+ if #available(iOS 26.0, *) {
+ content
+ .setColorGradient(.orange)
+ } else {
+ content
+ }
+ }
+ .showLoading(.constant(log.isEmpty))
+ .navigationTitle(selectedLog)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar(content: {
+ ToolbarItem(placement: .primaryAction) {
+ Button(action: {
+ Clipboard.copy(log)
+ }) {
+ Label("Copy log", systemImage: "doc.on.doc")
+ }
+ .tint(colorScheme == .dark ? .white : .black)
+ }
+ })
+ .task {
+ log = await iLogger.readLogFile(log: selectedLog)
+ }
+ }
+
+ private var content: some View {
+ return ScrollView {
+ LazyVStack {
+ Text(log)
+ .font(.callout)
+ .padding()
+ }
+ }
+ }
+}
+
+#Preview {
+ LoggerViewDetail(selectedLog: "test.log")
+}
diff --git a/IPv64/Views/Settings/SettingsView.swift b/IPv64/Views/Settings/SettingsView.swift
new file mode 100644
index 0000000..dc0e03e
--- /dev/null
+++ b/IPv64/Views/Settings/SettingsView.swift
@@ -0,0 +1,171 @@
+//
+// SettingsView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import SwiftUI
+
+struct SettingsView: View {
+
+ @Environment(\.colorScheme) var systemColorScheme
+
+ @Binding var popToRootTab: Tabs
+
+ @StateObject private var userStorage = UserStorage.shared
+
+ @State private var alertType: AlertType?
+ @Environment(ConnectedNodes.self) private var nodes
+ @AppStorage(NodeSyncStore.enabledKey, store: UserStorage.sharedDefault) private var syncNodes = true
+
+ private static let apiKeysRoute = "settings.apikeys"
+ private static let accountLinksRoute = "settings.accountlinks"
+ private static let notificationSettingsRoute = "settings.notificationsettings"
+ private static let passwordCheckRoute = "settings.passwordcheck"
+ private static let honeypotRoute = "settings.honeypot"
+
+ private func open(_ link: String) {
+ if let url = URL(string: link) { UIApplication.shared.open(url) }
+ }
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView
+ .setColorGradient(.orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ // Groups and order as in Android 2.1.0 (More); plain rows as in the 2.0 app.
+ List {
+ Section("Account") {
+ NavigationLink(value: Tabs.account.route) { Text("Account") }
+ NavigationLink(value: Self.apiKeysRoute) { Text("API keys") }
+ NavigationLink(value: Self.accountLinksRoute) { Text("Account links") }
+ }
+
+ Section {
+ NavigationLink(value: NodesView.route) { Text("Nodes") }
+ Toggle("Sync with iCloud", isOn: $syncNodes)
+ .onChange(of: syncNodes) { _, on in if on { nodes.syncWithCloud(force: true) } }
+ } footer: {
+ Text("Node URLs and API keys sync end-to-end encrypted through your iCloud Keychain.")
+ }
+
+ Section("Notifications") {
+ NavigationLink(value: Tabs.notification.route) { Text("Channels") }
+ NavigationLink(value: Self.notificationSettingsRoute) { Text("Notification settings") }
+ }
+
+ Section("Security") {
+ NavigationLink(value: Tabs.myip.route) { Text("IP lookup & My IP") }
+ NavigationLink(value: Self.passwordCheckRoute) { Text("Password check") }
+ NavigationLink(value: Self.honeypotRoute) { Text("Honeypot") }
+ }
+
+ Section("Tools") {
+ NavigationLink(value: Tabs.log.route) { Text("Logs") }
+ NavigationLink(value: Tabs.syslog.route) { Text("System Logs") }
+ }
+
+ Section("App") {
+ Toggle("Lockscreen \(userStorage.EnableLogscreen ? "enabled" : "disabled")", isOn: $userStorage.EnableLogscreen)
+ Toggle("Screenshot protection", isOn: $userStorage.ScreenshotProtection)
+ LabeledContent("Version", value: "\(Bundle.main.versionNumber) (\(Bundle.main.buildNumber))")
+ NavigationLink(value: Tabs.about.route) { Text("About") }
+ Button { open("https://www.youtube.com/c/RaspberryPiCloud") } label: { ExternalLinkRow(title: "YouTube") }
+ .tint(.primary)
+ Button { open("https://discord.gg/rpicloud") } label: { ExternalLinkRow(title: "Discord") }
+ .tint(.primary)
+ }
+
+ Section {
+ Button(role: .destructive) {
+ withAnimation {
+ alertType = .logout
+ }
+ } label: {
+ Text("Logout")
+ }
+ }
+ }
+ .navigationTitle(Tabs.settings.labelNew)
+ .navigationBarTitleDisplayMode(.inline).navigationDestination(for: String.self) { route in
+ switch route {
+ case Tabs.account.route:
+ Tabs.account.makeContentView(popToRootTab: $popToRootTab)
+ case Tabs.notification.route:
+ Tabs.notification.makeContentView(popToRootTab: $popToRootTab)
+ case Tabs.log.route:
+ Tabs.log.makeContentView(popToRootTab: $popToRootTab)
+ case Tabs.myip.route:
+ Tabs.myip.makeContentView(popToRootTab: $popToRootTab)
+ case Tabs.about.route:
+ Tabs.about.makeContentView(popToRootTab: $popToRootTab)
+ case NodesView.route:
+ NodesView()
+ case Self.apiKeysRoute:
+ ApiKeysView()
+ case Self.accountLinksRoute:
+ AccountLinksView()
+ case Self.notificationSettingsRoute:
+ NotificationSettingsView()
+ case Self.passwordCheckRoute:
+ PasswordCheckView()
+ case Self.honeypotRoute:
+ HoneypotView()
+ case Tabs.syslog.route:
+ Tabs.syslog.makeContentView(popToRootTab: $popToRootTab)
+ default:
+ EmptyView()
+ }
+ }
+ .alert(item: $alertType) { type in
+ switch type {
+ case .logout:
+ return Alert(
+ title: Text("Are you sure you want to logout?"),
+ message: Text("You will need to sign in again to access your account."),
+ primaryButton: .destructive(Text("Logout")) {
+ withAnimation {
+ if(performLogout()) {
+ if (!User.empty.list.isEmpty) {
+ self.alertType = .logoutSuccess
+ }
+ }
+ }
+ },
+ secondaryButton: .cancel()
+ )
+ case .logoutSuccess:
+ return Alert(title: Text("Successfully logged out."), message: Text("The app selected the first available user in the list."), dismissButton: .cancel(Text("OK")))
+ default:
+ return Alert(title: Text(""))
+ }
+ }
+ }
+}
+
+#Preview {
+ SettingsView(popToRootTab: .constant(.settings))
+ .environment(ConnectedNodes())
+}
+
+/// Row label for a link that leaves the app: title plus the trailing external-link arrow.
+private struct ExternalLinkRow: View {
+ let title: LocalizedStringKey
+
+ var body: some View {
+ HStack {
+ Text(title)
+ Spacer()
+ Image(systemName: "arrow.up.right")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(.tertiary)
+ .accessibilityHidden(true)
+ }
+ }
+}
diff --git a/IPv64/Views/Startup/BiometricsLockView.swift b/IPv64/Views/Startup/BiometricsLockView.swift
new file mode 100644
index 0000000..ef811ac
--- /dev/null
+++ b/IPv64/Views/Startup/BiometricsLockView.swift
@@ -0,0 +1,100 @@
+//
+// BiometricsLockView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 03.11.25.
+//
+
+import SwiftUI
+
+struct BiometricsLockView: View {
+
+ @EnvironmentObject var bio: Biometrics
+ @StateObject private var userStorage = UserStorage.shared
+
+ var body: some View {
+ ZStack {
+ VStack(alignment: .center) {
+ Image(systemName: Biometrics.GetBiometricSymbol())
+ .resizable()
+ .scaledToFit()
+ .foregroundColor(.orange)
+ .symbolRenderingMode(.hierarchical)
+ .frame(width: 75, height: 75, alignment: .center)
+ .padding(.bottom, 25)
+ Text("Please use \(Biometrics.GetBiometricText()) to unlock the app")
+ .font(.system(.callout, design: .rounded))
+ .padding(.bottom)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: .infinity, alignment: .center)
+ if #available(iOS 26.0, *) {
+ authBtn
+ .glassEffect(.regular.tint(.orange).interactive(true))
+ } else {
+ authBtn
+ .background(RoundedRectangle(cornerRadius: 24).fill(.orange))
+ }
+ }
+ .padding(.horizontal)
+ .onAppear {
+ print(userStorage.InAppSwitcher)
+ if (!userStorage.InAppSwitcher) {
+ bio.disableFields = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
+ bio.tryToAuthenticatePIN()
+ }
+ } else {
+ bio.disableFields = false
+ }
+ //bio.tryToAuthenticatePIN()
+ }
+ .onChange(of: bio.isAuthenticated) { _, value in
+ withAnimation {
+ if bio.isAuthenticated {
+ let generator = UINotificationFeedbackGenerator()
+ generator.notificationOccurred(.success)
+ }
+ }
+ }
+ .onChange(of: userStorage.InAppSwitcher) { _, value in
+ withAnimation {
+ if (!userStorage.InAppSwitcher) {
+ bio.disableFields = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
+ bio.tryToAuthenticatePIN()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private var authBtn: some View {
+ Button (action: {
+ withAnimation {
+ bio.disableFields = true
+ bio.tryToAuthenticatePIN()
+ }
+ }) {
+ if bio.disableFields {
+ Spinner(isAnimating: true, style: .medium, color: UIColor.white)
+ .frame(minWidth: 0, maxWidth: 500)
+ .padding(16)
+ } else {
+ Text("Unlock")
+ .font(.system(.callout, design: .rounded))
+ .foregroundStyle(.white)
+ .fontWeight(.bold)
+ .textCase(.uppercase)
+ .frame(minWidth: 0, maxWidth: 500)
+ .padding(16)
+ }
+ }
+ .disabled(bio.disableFields)
+ }
+}
+
+#Preview {
+ BiometricsLockView()
+ .environmentObject(Biometrics())
+}
diff --git a/IPv64/Views/Startup/LoginView.swift b/IPv64/Views/Startup/LoginView.swift
new file mode 100644
index 0000000..d3ab4b0
--- /dev/null
+++ b/IPv64/Views/Startup/LoginView.swift
@@ -0,0 +1,233 @@
+//
+// LoginView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import SwiftUI
+import IPv64
+
+struct LoginView: View {
+ @Environment(\.colorScheme) private var systemColorScheme
+ @Environment(\.presentationMode) var presentationMode
+
+ @StateObject private var userStorage = UserStorage.shared
+
+ @State var isFromAddUser: Bool = false
+
+ @State private var showQrSheet = false
+ @State private var showSpinner = false
+ @State private var showDeniedAlert = false
+ @State private var isAuthorized = false
+
+ @State private var isLoading = false
+ @State private var error: ErrorText?
+ @State private var loginTask: Task?
+ @State private var apiKey = ""
+ @State private var scannedKey: String?
+
+ @State private var user = User.empty
+
+ var body: some View {
+ VStack {
+ if #available(iOS 26.0, *) {
+ content
+ .setColorGradient((showQrSheet || isFromAddUser) ? .clear : .orange)
+ } else {
+ content
+ }
+ }
+ .errorAlert($error)
+ .onDisappear { loginTask?.cancel() }
+ .navigationTitle("Login")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem {
+ if #available(iOS 26.0, *) {
+ scannBtn
+ } else {
+ scannBtn
+ .tint(systemColorScheme == .dark ? .white : .black)
+ }
+ }
+ }
+ // Login after the scanner is gone, so its spinner and any error alert show on this screen.
+ .sheet(isPresented: $showQrSheet.animation(), onDismiss: {
+ guard let key = scannedKey else { return }
+ scannedKey = nil
+ loginTask?.cancel()
+ loginTask = Task { await login(key) }
+ }) {
+ QRScannerView() { key in
+ apiKey = key
+ scannedKey = key
+ }.onDisappear {
+ withAnimation {
+ showQrSheet = false
+ showSpinner = false
+ }
+ }
+ }
+ .task {
+ await permissisenCheck()
+ }
+ .alert("No Camera Permission", isPresented: $showDeniedAlert) {
+ Button("Open Settings") {
+ if let url = URL(string: UIApplication.openSettingsURLString) {
+ UIApplication.shared.open(url)
+ }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Please allow camera access in Settings to use this feature.")
+ }
+ .overlay(alignment: .bottom) {
+ VStack {
+ if #available(iOS 26.0, *) {
+ letsgoBtn
+ .glassEffect(.regular.tint(.orange).interactive(true))
+ } else {
+ letsgoBtn
+ .background(RoundedRectangle(cornerRadius: 24).fill(.orange))
+ }
+ }
+ .padding()
+ }
+ }
+
+ private var content: some View {
+ return List {
+ Text("How do you log in to IPv64.net?")
+ .fontWeight(.bold)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .listRowBackground(Color.clear)
+ .listRowSeparator(.hidden)
+
+ VStack(spacing: 5) {
+ Text("**1.** Go to ipv64.net and log in to your account.")
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Text("**2.** Select the **Account** button at the top.")
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Text("**3.** A drop-down menu will open. Select **API**.")
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Text("**4.** You will now see a list of API keys (if you have already created more than one). Select the one you want to use by tapping the QR code button.")
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Text("**5.** Open the QR code scanner in this app and scan the QR code.")
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Text("**6.** Done! You are now logged in.")
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .font(.footnote)
+ .listRowBackground(Color.clear)
+
+ Section {
+ TextField("API Key", text: $apiKey)
+ .multilineTextAlignment(.leading)
+ .keyboardType(.default)
+ .lineLimit(3)
+ .tint(.orange)
+ }
+ }
+ }
+
+ private var letsgoBtn: some View {
+ return Button (action: {
+ loginTask?.cancel()
+ loginTask = Task { await login(apiKey) }
+ }) {
+ Text("Login")
+ .font(.system(.callout, design: .rounded))
+ .foregroundStyle(.white)
+ .fontWeight(.bold)
+ .textCase(.uppercase)
+ .frame(minWidth: 0, maxWidth: 500) // capped on iPad, full width on iPhone
+ .padding(16)
+ }
+ .disabled(isLoading || apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ .overlay { if isLoading { ProgressView() } }
+ }
+
+ private func login(_ rawKey: String) async {
+ let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !key.isEmpty, !isLoading else { return }
+ isLoading = true
+ defer { isLoading = false }
+ let me: Me
+ do {
+ me = try await ipv64Retrying { try await AppConfig.cloudClient(apiKey: key).account.me() }
+ } catch {
+ guard !Task.isCancelled else { return }
+ // 401/403 = key rejected or account inactive; anything else keeps the server text.
+ if let status = (error as? IPv64Error)?.statusCode, status == 401 || status == 403 {
+ self.error = ErrorText(title: String(localized: "Request failed"), message: String(localized: "This API key does not belong to an active account."))
+ } else {
+ self.error = ErrorText(error)
+ }
+ return
+ }
+ guard !Task.isCancelled else { return }
+ if !user.list.contains(where: { $0.ApiKey == key }) {
+ user = User(Username: me.email ?? me.username ?? "", ApiKey: key, Information: "")
+ user.save()
+ guard user.list.contains(where: { $0.ApiKey == key }) else { return }
+ }
+ userStorage.ApiKey = key
+ guard userStorage.ApiKey == key else { return }
+ if userStorage.ApiKeyWidget.isEmpty { userStorage.ApiKeyWidget = key }
+ if isFromAddUser { presentationMode.wrappedValue.dismiss() }
+ else { userStorage.ShowLoginView = false }
+ }
+
+ private var scannBtn: some View {
+ return Button (action: {
+ if (!isAuthorized) {
+ Task {
+ await permissisenCheck(true)
+ }
+ } else {
+ withAnimation {
+ showQrSheet = true
+ showSpinner = true
+ }
+ }
+ }) {
+ if (showSpinner) {
+ Spinner(isAnimating: true, style: .medium, color: .white)
+ } else {
+ Label("Show QR Scanner", systemImage: "qrcode")
+ }
+ }
+ }
+
+ private func permissisenCheck(_ isFromButton: Bool = false) async {
+ switch CameraPermission.status() {
+ case .authorized:
+ isAuthorized = true
+ case .notDetermined:
+ let newStatus = await CameraPermission.request()
+ isAuthorized = (newStatus == .authorized)
+ showDeniedAlert = (newStatus != .authorized)
+ if (isFromButton && isAuthorized) {
+ withAnimation {
+ showQrSheet = true
+ showSpinner = true
+ }
+ }
+ case .denied, .restricted:
+ showDeniedAlert = true
+ }
+ }
+}
+
+#Preview {
+ NavigationStack {
+ LoginView()
+
+ }
+}
diff --git a/IPv64/Views/Startup/NoConnectionView.swift b/IPv64/Views/Startup/NoConnectionView.swift
new file mode 100644
index 0000000..39a8142
--- /dev/null
+++ b/IPv64/Views/Startup/NoConnectionView.swift
@@ -0,0 +1,36 @@
+//
+// NoConnectionView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 03.11.25.
+//
+
+import SwiftUI
+
+struct NoConnectionView: View {
+
+ var body: some View {
+ VStack {
+ Image(systemName: "wifi.slash")
+ .symbolRenderingMode(.hierarchical)
+ .foregroundStyle(.red)
+ .font(.largeTitle)
+
+ Text("No internet connection")
+ .fontDesign(.rounded)
+ .padding(.top)
+ .font(.title3)
+ .fontWeight(.bold)
+
+ Text("The network connection appears to be offline. \nPlease check your connection.")
+ .fontDesign(.rounded)
+ .multilineTextAlignment(.center)
+ .padding(.vertical)
+ }
+ .padding(.horizontal)
+ }
+}
+
+#Preview {
+ NoConnectionView()
+}
diff --git a/IPv64/Views/Startup/QRScannerView.swift b/IPv64/Views/Startup/QRScannerView.swift
new file mode 100644
index 0000000..fc4f5e6
--- /dev/null
+++ b/IPv64/Views/Startup/QRScannerView.swift
@@ -0,0 +1,234 @@
+//
+// QRScannerView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+
+import SwiftUI
+import AVFoundation
+import Combine
+
+// MARK: - Public SwiftUI View
+
+/// Vollbild QR-Code Scanner, mit zentraler "Frosted-Glass"-Kachel und rotem Rahmen wie im Screenshot.
+/// Usage:
+/// QRScannerView { payload in
+/// print("Scanned:", payload)
+/// }
+
+public struct QRScannerView: View {
+
+ @Environment(\.dismiss) private var dismiss
+
+ @StateObject private var scanner = QRScanner()
+
+ public var onScanned: (String) -> Void
+
+ public init(onScanned: @escaping (String) -> Void) {
+ self.onScanned = onScanned
+ }
+
+ public var body: some View {
+ ZStack {
+ CameraPreview(session: scanner.session)
+ .ignoresSafeArea()
+
+ // The cutout is only a visual guide: the whole camera frame is scanned (no rectOfInterest, which
+ // silently stopped all detection when converted before the preview had its size or rotation).
+ GeometryReader { geo in
+ ScannerCutoutOverlay(side: min(geo.size.width, geo.size.height) * 0.62)
+ .ignoresSafeArea()
+ }
+ .allowsHitTesting(false)
+ }
+ .task {
+ await scanner.start { code in
+ let generator = UINotificationFeedbackGenerator()
+ generator.notificationOccurred(.success)
+ onScanned(code)
+ Task {
+ await scanner.stop()
+ dismiss()
+ } // async separat
+ }
+ }
+ .onDisappear {
+ Task { await scanner.stop() }
+ }
+ }
+}
+
+private struct ScannerCutoutOverlay: View {
+ let side: CGFloat
+
+ var body: some View {
+ GeometryReader { geo in
+ let w = geo.size.width
+ let h = geo.size.height
+ let cx = w / 2
+ let cy = h / 2
+ let cutout = CGRect(x: cx - side/2, y: cy - side/2, width: side, height: side)
+ let corner = side * 0.10
+
+ // Frosted Außenbereich (even-odd)
+ Path { path in
+ path.addRect(CGRect(origin: .zero, size: geo.size))
+ path.addPath(RoundedRectangle(cornerRadius: corner, style: .continuous).path(in: cutout))
+ }
+ .fill(.ultraThinMaterial, style: FillStyle(eoFill: true))
+ .ignoresSafeArea()
+
+ // Roter Rahmen um das Scan-Fenster
+ RoundedRectangle(cornerRadius: corner, style: .continuous)
+ .stroke(Color.red, lineWidth: max(2, side * 0.012))
+ .frame(width: cutout.width, height: cutout.height)
+ .position(x: cx, y: cy)
+ .shadow(radius: side * 0.04, y: side * 0.02)
+ }
+ }
+}
+
+// MARK: - Camera Preview (AVCaptureVideoPreviewLayer in SwiftUI)
+
+private struct CameraPreview: UIViewRepresentable {
+ final class VideoView: UIView {
+ override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }
+ var previewLayer: AVCaptureVideoPreviewLayer { layer as! AVCaptureVideoPreviewLayer }
+ private var coordinator: AVCaptureDevice.RotationCoordinator?
+ private var observation: NSKeyValueObservation?
+
+ /// Keeps the preview upright in every orientation and window size (iPad landscape, Split View).
+ func followRotation() {
+ guard coordinator == nil,
+ let device = (previewLayer.session?.inputs.first as? AVCaptureDeviceInput)?.device else { return }
+ let coordinator = AVCaptureDevice.RotationCoordinator(device: device, previewLayer: previewLayer)
+ self.coordinator = coordinator
+ apply(coordinator.videoRotationAngleForHorizonLevelPreview)
+ observation = coordinator.observe(\.videoRotationAngleForHorizonLevelPreview, options: [.new]) { [weak self] _, change in
+ guard let angle = change.newValue else { return }
+ let view = self
+ Task { @MainActor in view?.apply(angle) }
+ }
+ }
+
+ private func apply(_ angle: CGFloat) {
+ guard let connection = previewLayer.connection, connection.isVideoRotationAngleSupported(angle) else { return }
+ connection.videoRotationAngle = angle
+ }
+ }
+
+ let session: AVCaptureSession
+
+ func makeUIView(context: Context) -> VideoView {
+ let v = VideoView()
+ v.previewLayer.session = session
+ v.previewLayer.videoGravity = .resizeAspectFill
+ v.followRotation()
+ return v
+ }
+
+ func updateUIView(_ uiView: VideoView, context: Context) {
+ uiView.followRotation() // the camera input may be added after the view was made
+ }
+}
+
+// MARK: - Scanner Core
+final class QRScanner: NSObject, ObservableObject, AVCaptureMetadataOutputObjectsDelegate {
+ let session = AVCaptureSession()
+
+ private let sessionQueue = DispatchQueue(label: "qr.scanner.session") // ⬅️ neu
+
+ private var onCode: ((String) -> Void)?
+ private var isRunning = false
+
+ private let metadataOutput = AVCaptureMetadataOutput()
+
+ // MARK: Public API
+
+ func start(onCode: @escaping (String) -> Void) async {
+ self.onCode = onCode
+ if isRunning { return }
+
+ await withCheckedContinuation { cont in
+ sessionQueue.async {
+ self.configureSessionIfNeeded() // ⬅️ auf der Queue
+ self.session.startRunning() // ⬅️ auf der Queue
+ self.isRunning = true
+ cont.resume()
+ }
+ }
+ }
+
+ func stop() async {
+ guard isRunning else { return }
+ await withCheckedContinuation { cont in
+ sessionQueue.async {
+ self.session.stopRunning() // ⬅️ auf der Queue
+ self.isRunning = false
+ cont.resume()
+ }
+ }
+ }
+
+ // MARK: Session Setup
+
+ private func configureSessionIfNeeded() {
+ guard session.inputs.isEmpty && session.outputs.isEmpty else { return }
+
+ session.beginConfiguration()
+ session.sessionPreset = .high
+ // Keep scanning while other apps share the screen (Split View, Slide Over, Stage Manager).
+ if session.isMultitaskingCameraAccessSupported { session.isMultitaskingCameraAccessEnabled = true }
+
+ // Input
+ guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
+ let input = try? AVCaptureDeviceInput(device: device),
+ session.canAddInput(input) else {
+ session.commitConfiguration()
+ return
+ }
+ session.addInput(input)
+
+ // Output
+ guard session.canAddOutput(metadataOutput) else {
+ session.commitConfiguration()
+ return
+ }
+ session.addOutput(metadataOutput)
+ metadataOutput.setMetadataObjectsDelegate(self, queue: .main)
+
+ if metadataOutput.availableMetadataObjectTypes.contains(.qr) {
+ metadataOutput.metadataObjectTypes = [.qr]
+ } else {
+ metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes
+ }
+
+ session.commitConfiguration()
+
+ // Autofokus
+ try? device.lockForConfiguration()
+ if device.isFocusModeSupported(.continuousAutoFocus) {
+ device.focusMode = .continuousAutoFocus
+ }
+ device.unlockForConfiguration()
+ }
+
+ // MARK: Delegate
+
+ func metadataOutput(_ output: AVCaptureMetadataOutput,
+ didOutput metadataObjects: [AVMetadataObject],
+ from connection: AVCaptureConnection) {
+ guard let obj = metadataObjects.first as? AVMetadataMachineReadableCodeObject,
+ obj.type == .qr,
+ let value = obj.stringValue,
+ !value.isEmpty else { return }
+ onCode?(value)
+ onCode = nil
+ }
+}
+
+#Preview {
+ QRScannerView() { _ in }
+}
diff --git a/IPv64/Views/Startup/TabbarView.swift b/IPv64/Views/Startup/TabbarView.swift
new file mode 100644
index 0000000..130352a
--- /dev/null
+++ b/IPv64/Views/Startup/TabbarView.swift
@@ -0,0 +1,67 @@
+import SwiftUI
+
+struct TabbarView: View {
+ /// Per window (iPad multi-window): each scene keeps its own tab.
+ @SceneStorage("CURRENT_TAB") private var selectedTab: Tabs = .domain
+ @Environment(ConnectedNodes.self) private var nodes
+ @Environment(\.scenePhase) private var scenePhase
+ @State private var paths: [Tabs: NavigationPath] = [:]
+
+ private var visibleTabs: [Tabs] { Tabs.tabList(proxyActive: nodes.proxyActive, dnsActive: !nodes.dnsIds.isEmpty) }
+
+ private var selection: Binding {
+ Binding(get: { selectedTab }, set: { tab in
+ if tab == selectedTab { paths[tab] = NavigationPath() }
+ selectedTab = tab
+ })
+ }
+
+ var body: some View {
+ // No default sidebar placement: on iPhone (also landscape) always the tab bar.
+ if #available(iOS 26.0, *) {
+ tabs.tabBarMinimizeBehavior(.onScrollDown)
+ } else {
+ tabs
+ }
+ }
+
+ private var tabs: some View {
+ TabView(selection: selection) {
+ ForEach(visibleTabs) { tab in
+ Tab(tab.labelNew, systemImage: tab.iconName, value: tab) { root(tab) }
+ }
+ }
+ // Tab bar on iPhone, tab bar or sidebar on iPad, following the available width.
+ .tabViewStyle(.sidebarAdaptable)
+ .onAppear(perform: fixSelection)
+ .onChange(of: visibleTabs) { fixSelection() }
+ // The view is rebuilt per account (`.id(sessionID)`), so this re-reads the nodes of the new account.
+ .task { nodes.refresh() }
+ .task(id: nodes.ids) { await nodes.refreshModules() }
+ .onChange(of: scenePhase) { _, phase in
+ if phase == .active { Task { await nodes.refreshModules() } }
+ }
+ }
+
+ /// A tab that left the bar (module switched off, old stored value) falls back to its slot or to Domains.
+ private func fixSelection() {
+ guard !visibleTabs.contains(selectedTab) else { return }
+ switch selectedTab {
+ case .cdn where nodes.proxyActive: selectedTab = .proxy64
+ case .proxy64: selectedTab = .cdn
+ case .account, .notification, .dns64: selectedTab = .settings
+ default: selectedTab = .domain
+ }
+ }
+
+ private func root(_ tab: Tabs) -> some View {
+ NavigationStack(path: Binding(get: { paths[tab] ?? NavigationPath() }, set: { paths[tab] = $0 })) {
+ tab.makeContentView(popToRootTab: .constant(.other))
+ }
+ .appReadableWidth()
+ }
+}
+
+typealias TabbarView18 = TabbarView
+
+#Preview { TabbarView().environment(ConnectedNodes()) }
diff --git a/IPv64/Views/Startup/WelcomeView.swift b/IPv64/Views/Startup/WelcomeView.swift
new file mode 100644
index 0000000..855ca0f
--- /dev/null
+++ b/IPv64/Views/Startup/WelcomeView.swift
@@ -0,0 +1,88 @@
+//
+// WelcomeView.swift
+// IPv64
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import SwiftUI
+
+struct WelcomeView: View {
+ @Environment(\.colorScheme) var systemColorScheme
+ @StateObject private var userStorage = UserStorage.shared
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ content
+ .setColorGradient(.orange)
+ } else {
+ content
+ }
+ }
+
+ private var content: some View {
+ return VStack {
+ VStack(alignment: .leading, spacing: 0) {
+ Spacer()
+ VStack(alignment: .leading, spacing: 0) {
+ Image(uiImage: UIImage(named: "v64-logo") ?? UIImage())
+ .resizable()
+ .scaledToFit()
+ .frame(width: 84)
+ .padding(.bottom)
+
+ Text("Welcome to")
+ .fontDesign(.rounded)
+ .font(.largeTitle)
+ .fontWeight(.bold)
+
+ Text("IPv64.net")
+ .foregroundStyle(.orange)
+ .fontDesign(.rounded)
+ .font(.largeTitle)
+ .fontWeight(.bold)
+
+ Text("The App for the Free DynDNS2 Service from Dennis Schröder")
+ .fontDesign(.rounded)
+ .padding(.top)
+ }
+ .frame(maxWidth: .infinity)
+ Spacer()
+
+ Spacer()
+
+ if #available(iOS 26.0, *) {
+ letsgoBtn
+ .glassEffect(.regular.tint(.orange).interactive(true))
+ } else {
+ letsgoBtn
+ .background(RoundedRectangle(cornerRadius: 24).fill(.orange))
+ }
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal)
+ }
+ .padding()
+ }
+
+ private var letsgoBtn: some View {
+ return Button (action: {
+ withAnimation {
+ userStorage.ShowWelcomeView = false
+ userStorage.ShowLoginView = true
+ }
+ }) {
+ Text("Let's go!")
+ .font(.system(.callout, design: .rounded))
+ .foregroundStyle(.white)
+ .fontWeight(.bold)
+ .textCase(.uppercase)
+ .frame(minWidth: 0, maxWidth: 500) // capped on iPad, full width on iPhone
+ .padding(16)
+ }
+ }
+}
+
+#Preview {
+ WelcomeView()
+}
diff --git a/IPv64/Views/User/AccountView.swift b/IPv64/Views/User/AccountView.swift
new file mode 100644
index 0000000..d826c5f
--- /dev/null
+++ b/IPv64/Views/User/AccountView.swift
@@ -0,0 +1,194 @@
+//
+// AccountView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 20.10.25.
+//
+
+import SwiftUI
+import IPv64
+
+struct AccountView: View {
+
+ @Environment(\.colorScheme) var systemColorScheme
+
+ @Binding var popToRootTab: Tabs
+
+ @StateObject private var userStorage = UserStorage.shared
+ @Environment(Session.self) private var session
+ @State private var me: Me?
+ @State private var isLoading = false
+ @State private var error: ErrorText?
+ @State private var user: User = .empty
+ @State private var showUserSheet = false
+
+ var body: some View {
+ if #available(iOS 26.0, *) {
+ listView
+ .setColorGradient(showUserSheet ? .clear : .orange)
+ } else {
+ listView
+ }
+ }
+
+ private var listView: some View {
+ List {
+ accountSelectionView
+
+ // Rows and texts as in Android 2.1.0 (AccountView).
+ Section("Account") {
+ labeled("Username", badge: me?.username?.nonBlank ?? "none", color: .gray)
+ labeled("Account Plan", badge: me?.plan?.name?.nonBlank ?? "none", color: .yellow)
+ labeled("Plan valid until", badge: planValidUntil, color: .gray)
+ labeled("E-Mail", badge: me?.email?.nonBlank ?? "none", color: .gray)
+ labeled("Registered since", badge: dateText(me?.registeredAt), color: .gray)
+ labeled("Last login", badge: dateText(me?.lastLoginAt), color: .gray)
+ }
+
+ Section("DynDNS") {
+ quota("Own Domain", usage?.ownDomains)
+ quota("DynDNS Domains", usage?.dyndnsDomains)
+ quota("DynDNS Update Limit / 24h", usage?.dyndnsUpdates24h)
+ }
+
+ Section("Healthcheck") {
+ quota("Healthchecks", usage?.healthchecks)
+ quota("Healthchecks Updates / 24h", usage?.healthcheckPings24h)
+ quota("SMS Limit / 24h", usage?.sms24h)
+ }
+
+ Section("Failover") {
+ quota("Failover Policies", usage?.failoverPolicies)
+ quota("Failover Monitors", usage?.failoverMonitors)
+ quota("Failover Rules", usage?.failoverRules)
+ }
+
+ Section("CDN") {
+ quota("CDN Domains", usage?.cdnDomains)
+ quota("CDN Traffic (GB)", usage?.cdnTrafficGB)
+ }
+
+ Section("VPN / DNS64") {
+ labeled("VPN Traffic (GB)", badge: vpnTraffic, color: usage?.vpnTrafficGB?.limited == true ? .red : .green)
+ quota("DNS64 Clients", usage?.dns64Clients)
+ }
+
+ Section("API") {
+ HStack {
+ Text("API Key")
+ Spacer()
+ Text("swipe")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ .swipeActions {
+ Button {
+ Clipboard.copy(userStorage.ApiKey, sensitive: true)
+ } label: {
+ Label("Copy", systemImage: "document.on.document")
+ }
+ .tint(.blue)
+ .labelStyle(.iconOnly)
+ }
+ }
+ }
+ .showLoading(.constant(isLoading))
+ .errorAlert($error)
+ .navigationTitle(Tabs.account.labelNew)
+ .navigationBarTitleDisplayMode(.inline)
+ .task { await load() }
+ .sheet(isPresented: $showUserSheet.animation()) {
+ UserView().onDisappear {
+ Task { await load() }
+ }
+ }
+ }
+
+ private var accountSelectionView: some View {
+ Button(action: {
+ withAnimation {
+ showUserSheet.toggle()
+ }
+ }) {
+ HStack {
+ Image(systemName: "person.crop.circle")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 55, height: 55)
+ VStack(alignment: .leading) {
+ Text(user.current?.Username ?? "No User found")
+ .lineLimit(1)
+ .multilineTextAlignment(.leading)
+ .font(.title3)
+ .fontWeight(.bold)
+ Text(user.current?.Information ?? "No Information")
+ .lineLimit(1)
+ .multilineTextAlignment(.leading)
+ }
+ .padding(.leading, 8)
+ }
+ .padding(.horizontal, 8)
+ .foregroundStyle(systemColorScheme == .dark ? .white : .black)
+ }
+ }
+
+ private var usage: Me.Usage? { me?.usage }
+
+ /// Android `formatGermanTime`, "none" when missing.
+ private func dateText(_ date: Date?) -> String {
+ date.map { DynDNSLogic.germanTime($0) } ?? "none"
+ }
+
+ /// No plan: "–"; plan without end (free plan): "unlimited".
+ private var planValidUntil: String {
+ guard let plan = me?.plan else { return "–" }
+ return plan.validUntil.map { DynDNSLogic.germanTime($0) } ?? "unlimited"
+ }
+
+ /// Android `VpnTrafficUsage.usageText`: "used / limit", "(limit reached)" when limited, "–" without data.
+ private var vpnTraffic: String {
+ guard let q = usage?.vpnTrafficGB, let limit = q.limit else { return "–" }
+ let text = "\((q.used ?? 0).formatted(.number.precision(.fractionLength(0...2)))) / \(limit.formatted())"
+ return q.limited == true ? text + " (limit reached)" : text
+ }
+
+ private func load() async {
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ let result = try await ipv64Retrying { try await session.api.account.me() }
+ if !Task.isCancelled { me = result }
+ } catch {
+ if !Task.isCancelled { self.error = ErrorText(error) }
+ }
+ }
+
+ /// "used / limit", ∞ without limit; green below 70 %, yellow below 90 %, otherwise red.
+ private func quota(_ title: String, _ q: Me.Quota?) -> some View {
+ let used = Int(q?.used ?? 0)
+ let text: String
+ var color = Color.green
+ if let limit = q?.limit, limit > 0 {
+ text = "\(used.formatted()) / \(limit.formatted())"
+ let ratio = Double(used) / Double(limit)
+ color = ratio < 0.7 ? .green : ratio < 0.9 ? .yellow : .red
+ } else {
+ text = "\(used.formatted()) / ∞"
+ }
+ return labeled(title, badge: text, color: color)
+ }
+
+ @ViewBuilder
+ private func labeled(_ title: String, badge: String, color: Color? = nil) -> some View {
+ LabeledContent(title) {
+ Text(badge)
+ .foregroundStyle(color ?? .primary)
+ }
+ }
+}
+
+#Preview {
+ NavigationStack {
+ AccountView(popToRootTab: .constant(.account))
+ }
+}
diff --git a/IPv64/Views/User/UserEditView.swift b/IPv64/Views/User/UserEditView.swift
new file mode 100644
index 0000000..d19c5ac
--- /dev/null
+++ b/IPv64/Views/User/UserEditView.swift
@@ -0,0 +1,59 @@
+//
+// UserEditView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 25.10.25.
+//
+
+import SwiftUI
+import WidgetKit
+
+struct UserEditView: View {
+
+ @Environment(\.dismiss) var dismiss
+
+ @Binding var user: User
+
+ var body: some View {
+ NavigationStack {
+ List {
+ Section("Username") {
+ TextField("Username", text: $user.Username)
+ }
+ Section("Information") {
+ TextField("Information", text: $user.Information)
+ }
+ Section("Widgets") {
+ Toggle("Use this User for the Widgets", isOn: Binding(get: { UserStorage.shared.ApiKeyWidget == self.user.ApiKey }, set: {
+ if ($0) {
+ UserStorage.shared.ApiKeyWidget = self.user.ApiKey
+ Task {
+ _ = try? await ClearHealthCheckCacheIntent().perform()
+ }
+ }
+ })).disabled(UserStorage.shared.ApiKeyWidget == self.user.ApiKey)
+ Button("Force Refresh") {
+ Task { _ = try? await ClearHealthCheckCacheIntent().perform() }
+ }
+ }
+ }
+ .navigationTitle(Text("Edit User"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .navigationBarTrailing) {
+ Button(action: {
+ user.update()
+ dismiss()
+ }, label: {
+ Label("Save", systemImage: "checkmark")
+ })
+ }
+ }
+ }
+ .appReadableWidth()
+ }
+}
+
+#Preview {
+ UserEditView(user: .constant(User(Username: "Default User", ApiKey: "", Information: "")))
+}
diff --git a/IPv64/Views/User/UserItemView.swift b/IPv64/Views/User/UserItemView.swift
new file mode 100644
index 0000000..d32932f
--- /dev/null
+++ b/IPv64/Views/User/UserItemView.swift
@@ -0,0 +1,55 @@
+//
+// UserItemView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 22.10.25.
+//
+
+import SwiftUI
+
+struct UserItemView: View {
+
+ @Environment(\.dismiss) var dismiss
+ @Environment(\.colorScheme) var systemColorScheme
+
+ @Binding var user: User
+
+ var body: some View {
+ Button(action: {
+ withAnimation {
+ UserStorage.shared.ApiKey = user.ApiKey
+ dismiss()
+ }
+ }) {
+ HStack {
+ VStack(alignment: .leading) {
+ Text(user.Username)
+ .lineLimit(1)
+ .multilineTextAlignment(.leading)
+ .font(.title3)
+ .fontWeight(.bold)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Text(user.Information.isEmpty ? "No Information" : user.Information)
+ .lineLimit(1)
+ .multilineTextAlignment(.leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(.trailing, 8)
+ Image(systemName: user.ApiKey == UserStorage.shared.ApiKey ? "largecircle.fill.circle" : "circle")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 24, height: 24)
+ .foregroundStyle(.orange)
+ }
+ .padding(.horizontal, 8)
+ }
+ .foregroundStyle(systemColorScheme == .dark ? .white : .black)
+ }
+}
+
+#Preview {
+ let user = User(Username: "Test", ApiKey: "Test", Information: "Test")
+ List {
+ UserItemView(user: .constant(user))
+ }
+}
diff --git a/IPv64/Views/User/UserView.swift b/IPv64/Views/User/UserView.swift
new file mode 100644
index 0000000..f359bd0
--- /dev/null
+++ b/IPv64/Views/User/UserView.swift
@@ -0,0 +1,68 @@
+//
+// UserView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 22.10.25.
+//
+
+import SwiftUI
+
+struct UserView: View {
+
+ @Environment(\.dismiss) var dismiss
+ @Environment(\.colorScheme) var systemColorScheme
+
+ @State private var user: User = .empty
+ @State private var selectedUser: User = .empty
+ @State private var showEditUserSheet: Bool = false
+
+ var body: some View {
+ NavigationStack {
+ VStack {
+ List {
+ ForEach(user.list, id: \.uuid) { u in
+ UserItemView(user: Binding(
+ get: { u },
+ set: { _ = $0 } // ← schreibt zurück in die Quelle
+ ))
+ .swipeActions {
+ Button {
+ selectedUser = u
+ showEditUserSheet.toggle()
+ } label: {
+ Label("Edit", systemImage: "pencil")
+ }
+ .tint(.orange)
+ .labelStyle(.iconOnly)
+ }
+ }
+ }
+ }
+ .padding(.horizontal, 5)
+ .frame(maxWidth: .infinity)
+ .navigationTitle("Users")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem {
+ NavigationLink(destination: LoginView(isFromAddUser: true), label: {
+ Label("Add", systemImage: "person.badge.plus")
+ })
+ .tint(systemColorScheme == .dark ? .white : .black)
+ }
+ }
+ }
+ .appReadableWidth()
+ .sheet(isPresented: $showEditUserSheet.animation()) {
+ UserEditView(user: $selectedUser).onDisappear {
+ selectedUser = .empty
+ }
+ }
+ }
+}
+
+
+#Preview {
+ NavigationStack {
+ UserView()
+ }
+}
diff --git a/IPv64/Views/Whatsnew/WhatsNewItemView.swift b/IPv64/Views/Whatsnew/WhatsNewItemView.swift
new file mode 100644
index 0000000..850b99b
--- /dev/null
+++ b/IPv64/Views/Whatsnew/WhatsNewItemView.swift
@@ -0,0 +1,141 @@
+//
+// WhatsNewItemView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 13.02.26.
+//
+
+import SwiftUI
+
+struct WhatsNewItemView: View {
+
+ @State var whatsNewItem: WhatsNew
+ @State private var animate = false
+
+ var body: some View {
+ VStack(alignment: .leading)
+ {
+ HStack(alignment: .top) {
+ if #available(iOS 17.0, *) {
+ if (whatsNewItem.imageName == "fireworks") {
+ Image(systemName: whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.horizontal)
+ .foregroundStyle(.green, .yellow)
+ .symbolRenderingMode(.palette)
+ // .symbolEffect(.bounce.up.byLayer, options: .speed(0.4).repeating, value: animate)
+ } else if (whatsNewItem.assetIcon) {
+ Image(whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.horizontal)
+ .foregroundColor(.orange)
+ .symbolRenderingMode(.hierarchical)
+ } else {
+ Image(systemName: whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.horizontal)
+ .foregroundColor(.orange)
+ .symbolRenderingMode(.hierarchical)
+ }
+ } else {
+ Image(systemName: whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.horizontal)
+ .foregroundColor(.orange)
+ .symbolRenderingMode(.hierarchical)
+ }
+ VStack(alignment: .leading, spacing: 5) {
+ Text(whatsNewItem.title)
+ .font(.system(.headline, design: .rounded))
+ .fontWeight(.bold)
+ Text(whatsNewItem.subtitle)
+ .font(.system(.footnote, design: .rounded))
+ .foregroundColor(.gray)
+ }
+ .padding(.trailing)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(.horizontal)
+ .padding(.bottom)
+ .frame(maxWidth: .infinity)
+ }
+ .onAppear {
+ animate = true
+ }
+ }
+}
+
+struct WhatsNewItemView26: View {
+
+ @State var whatsNewItem: WhatsNew
+ @State private var animate = false
+
+ var body: some View {
+ VStack(alignment: .leading)
+ {
+ HStack(alignment: .top) {
+ if #available(iOS 17.0, *) {
+ if (whatsNewItem.imageName == "fireworks") {
+ Image(systemName: whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.trailing, 8)
+ .foregroundStyle(.green, .yellow)
+ .symbolRenderingMode(.palette)
+ // .symbolEffect(.bounce.up.byLayer, options: .speed(0.4).repeating, value: animate)
+ } else if (whatsNewItem.assetIcon) {
+ Image(whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.trailing)
+ .foregroundColor(.orange)
+ .symbolRenderingMode(.hierarchical)
+ } else {
+ Image(systemName: whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.trailing, 8)
+ .foregroundColor(.orange)
+ }
+ } else {
+ Image(systemName: whatsNewItem.imageName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 35, height: 35)
+ .padding(.trailing, 8)
+ .foregroundColor(.orange)
+ }
+ VStack(alignment: .leading, spacing: 5) {
+ Text(whatsNewItem.title)
+ .font(.system(.body))
+ .fontWeight(.bold)
+ Text(whatsNewItem.subtitle)
+ .font(.system(.callout))
+ .foregroundColor(.gray)
+ }
+ .padding(.trailing)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(.bottom)
+ .frame(maxWidth: .infinity)
+ }
+ .onAppear {
+ animate = true
+ }
+ }
+}
+
+#Preview {
+ WhatsNewItemView26(whatsNewItem: WhatsNew(imageName: "appstore", title: "Was ist Neu?", subtitle: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren", assetIcon: true))
+}
diff --git a/IPv64/Views/Whatsnew/WhatsNewView.swift b/IPv64/Views/Whatsnew/WhatsNewView.swift
new file mode 100644
index 0000000..832a659
--- /dev/null
+++ b/IPv64/Views/Whatsnew/WhatsNewView.swift
@@ -0,0 +1,121 @@
+//
+// WhatsNewView.swift
+// IPv64.net
+//
+// Created by Sebastian Rank on 13.02.26.
+//
+
+import SwiftUI
+import Combine
+
+struct WhatsNewView: View {
+
+ @Environment(\.dismiss) var dismiss
+ @ObservedObject private var userStorage = UserStorage.shared
+ @Binding var activeSheet: ActiveSheet?
+ @Binding var isPresented: Bool
+ var isFromSetting = false
+
+ var whatsNewList = WhatsNew.current
+
+ var body: some View {
+ VStack {
+ VStack {
+ Text("What's new?")
+ .font(.system(.largeTitle, design: .rounded))
+ .fontWeight(.bold)
+ .frame(maxWidth: .infinity, alignment: .center)
+ Text("In the version \(Bundle.main.versionNumber) (\(Bundle.main.buildNumber)) are these changes implemented and bugs have been resolved:")
+ .font(.system(.body, design: .rounded))
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal)
+ .padding(.top, 1)
+ }
+ .padding(.vertical, 27.5)
+
+ ScrollView {
+ ForEach(whatsNewList, id: \.id) { item in
+ WhatsNewItemView(whatsNewItem: item)
+ }
+ }.offset(y: -10)
+
+ Button(action: {
+ withAnimation {
+ let buildNumber = Bundle.main.buildNumber
+ userStorage.LAST_BUILD_NUMBER = buildNumber
+ activeSheet = nil
+ dismiss()
+ }
+ }) {
+ Text(isFromSetting ? "Close" : "Continue").font(.headline)
+ .foregroundColor(.white)
+ .padding()
+ .frame(maxWidth: .infinity, minHeight: 50, idealHeight: 50, maxHeight: 50, alignment: .center)
+ .background(.orange)
+ .cornerRadius(8.0)
+ }
+ .padding(.horizontal, 27.5)
+ .padding(.bottom, 8)
+
+ }
+ .navigationTitle("")
+ .navigationBarTitleDisplayMode(.inline)
+ .interactiveDismissDisabled(!isFromSetting)
+ }
+}
+
+@available(iOS 26.0, *)
+struct WhatsNewView26: View {
+
+ @Environment(\.dismiss) var dismiss
+ @ObservedObject private var userStorage = UserStorage.shared
+ @Binding var activeSheet: ActiveSheet?
+ @Binding var isPresented: Bool
+ var isFromSetting = false
+
+ var whatsNewList = WhatsNew.current
+
+ var body: some View {
+ VStack(alignment: .leading) {
+ Text("What's new in IPv64.net \nv\(Bundle.main.versionNumber) (\(Bundle.main.buildNumber))")
+ .font(.system(.title3, weight: .bold))
+ .padding(.bottom)
+
+ ScrollView {
+ ForEach(whatsNewList, id: \.id) { item in
+ WhatsNewItemView26(whatsNewItem: item)
+ }
+ }
+
+ Button (action: {
+ withAnimation {
+ let buildNumber = Bundle.main.buildNumber
+ userStorage.LAST_BUILD_NUMBER = buildNumber
+ activeSheet = nil
+ dismiss()
+ }
+ }) {
+ Text(isFromSetting ? "Close" : "Continue")
+ .font(.system(.callout))
+ .foregroundStyle(.white)
+ .fontWeight(.bold)
+ .frame(minWidth: 0, maxWidth: .infinity)
+ .padding(16)
+ }
+ .glassEffect(.regular.tint(.orange).interactive(true))
+ }
+ .padding([.top, .horizontal], 50)
+ .interactiveDismissDisabled(!isFromSetting)
+ }
+}
+
+#Preview {
+ VStack { }
+ .sheet(item: .constant(ActiveSheet.whatsnew)) { _ in
+ if #available(iOS 26.0, *) {
+ WhatsNewView26(activeSheet: .constant(nil), isPresented: .constant(true))
+ } else {
+ WhatsNewView(activeSheet: .constant(nil), isPresented: .constant(true))
+ }
+ }
+}
diff --git a/NotificationService/NotificationService.entitlements b/IPv64NotificationService/IPv64NotificationService.entitlements
similarity index 72%
rename from NotificationService/NotificationService.entitlements
rename to IPv64NotificationService/IPv64NotificationService.entitlements
index 550c609..3974490 100644
--- a/NotificationService/NotificationService.entitlements
+++ b/IPv64NotificationService/IPv64NotificationService.entitlements
@@ -6,5 +6,9 @@
group.ipv64.net
+ keychain-access-groups
+
+ $(AppIdentifierPrefix)group.ipv64.net
+
diff --git a/NotificationService/Info.plist b/IPv64NotificationService/Info.plist
similarity index 100%
rename from NotificationService/Info.plist
rename to IPv64NotificationService/Info.plist
diff --git a/IPv64NotificationService/NotificationPayload.swift b/IPv64NotificationService/NotificationPayload.swift
new file mode 100644
index 0000000..f6ea79a
--- /dev/null
+++ b/IPv64NotificationService/NotificationPayload.swift
@@ -0,0 +1,39 @@
+import Foundation
+
+/// SecNtfy push content (Android `SecNtfyMessagingService.processNotification`): RSA-encrypted title, body and
+/// optional image URL, plus the message id for the receipt.
+struct NotificationPayload: Equatable, Sendable {
+ var title: String
+ var body: String
+ var image: String
+ var messageId: String
+
+ /// Message id keys in order: SecNtfy's APNs payload sends `msgId` (String or number); `messageId` | `id` as on Android.
+ static let idKeys = ["msgId", "messageId", "id"]
+
+ /// Title/body come from `aps.alert` (already parsed by the system); image and id from custom keys
+ /// (top level of `userInfo` or inside `data`).
+ static func parse(title: String, body: String, userInfo: [AnyHashable: Any]) -> NotificationPayload {
+ let places = [userInfo, userInfo["data"] as? [AnyHashable: Any] ?? [:]]
+ func string(_ key: String) -> String? {
+ places.lazy.compactMap { $0[key] }.first
+ .map { String(describing: $0).trimmingCharacters(in: .whitespacesAndNewlines) }
+ .flatMap { $0.isEmpty ? nil : $0 }
+ }
+ return NotificationPayload(title: title, body: body, image: string("image") ?? "",
+ messageId: idKeys.lazy.compactMap(string).first ?? "")
+ }
+
+ /// Key names of the payload (nested as `data.x`), without values, for the log when no id is found.
+ static func keyNames(_ userInfo: [AnyHashable: Any]) -> String {
+ userInfo.flatMap { key, value -> [String] in
+ let name = String(describing: key)
+ guard let nested = value as? [AnyHashable: Any] else { return [name] }
+ return nested.keys.map { "\(name).\($0)" }
+ }.sorted().joined(separator: ", ")
+ }
+
+ /// Shown until decryption succeeds (Android defaults).
+ static let defaultTitle = "IPv64.net Notification"
+ static let defaultBody = "New notification received"
+}
diff --git a/IPv64NotificationService/NotificationService.swift b/IPv64NotificationService/NotificationService.swift
new file mode 100644
index 0000000..8830021
--- /dev/null
+++ b/IPv64NotificationService/NotificationService.swift
@@ -0,0 +1,190 @@
+import UserNotifications
+import UniformTypeIdentifiers
+import SecNtfy
+@preconcurrency import SwiftyBeaver
+
+/// Decrypts SecNtfy pushes (needs `mutable-content: 1`), sends the receipt and attaches an image if the payload has one.
+/// Flow as in iGotify: readable fallback first, decrypt, then receipt (`Status 201` = already received → delivered
+/// silently, no badge), then the image. Keys come from the App Group the app passes to `SecNtfySwifty.initialize`.
+///
+/// `@unchecked Sendable` invariant: `handler`, `fallback`, `finished` and `task` are only touched while holding
+/// `lock`; processing and `serviceExtensionTimeWillExpire` may race, `deliverOnce` hands content over exactly once.
+final class NotificationService: UNNotificationServiceExtension, @unchecked Sendable {
+ private static let appGroup = "group.ipv64.net"
+
+ /// Writes into the app's daily log file (More → Tools → System Logs; name as in `iLogger.defaultLogFileURL`,
+ /// the app rotates it). Synchronous writes: the process may be frozen right after the handler is called.
+ /// Never log message contents, keys or tokens.
+ private static let log: SwiftyBeaver.Type = {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyyMMdd"
+ if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)?
+ .appendingPathComponent("app_\(formatter.string(from: Date()))_latest.log") {
+ let file = FileDestination(logFileURL: url)
+ file.asynchronously = false
+ SwiftyBeaver.addDestination(file)
+ }
+ return SwiftyBeaver.self
+ }()
+
+ private let lock = NSLock()
+ private var handler: ((UNNotificationContent) -> Void)?
+ private var fallback: UNNotificationContent?
+ private var finished = false
+ private var task: Task?
+
+ override func didReceive(_ request: UNNotificationRequest,
+ withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
+ guard let content = request.content.mutableCopy() as? UNMutableNotificationContent else {
+ contentHandler(request.content)
+ return
+ }
+ let payload = NotificationPayload.parse(title: content.title, body: content.body, userInfo: content.userInfo)
+ // Readable text before any work, so the expiration path never shows ciphertext.
+ content.title = NotificationPayload.defaultTitle
+ content.body = NotificationPayload.defaultBody
+ lock.withLock {
+ handler = contentHandler
+ fallback = content.copy() as? UNNotificationContent
+ finished = false
+ }
+ // Handed over to the task: didReceive doesn't touch `content` after this point.
+ nonisolated(unsafe) let owned = content
+ let work = Task { [weak self] in
+ guard let self else { return }
+ await process(payload, content: owned)
+ }
+ lock.withLock { if finished { work.cancel() } else { task = work } }
+ }
+
+ override func serviceExtensionTimeWillExpire() {
+ Self.log.warning("Push extension: time expired")
+ if let content = lock.withLock({ fallback }) { deliverOnce(content, reason: "time expired") }
+ }
+
+ private func process(_ payload: NotificationPayload, content: UNMutableNotificationContent) async {
+ guard !payload.messageId.isEmpty else {
+ Self.log.error("Push extension: no message id (payload keys: \(NotificationPayload.keyNames(content.userInfo)))")
+ deliverOnce(content, reason: "missing message id")
+ return
+ }
+ let id = payload.messageId
+ Self.log.info("Push extension: received \(id)")
+ guard let title = decrypt(payload.title), let body = decrypt(payload.body) else {
+ Self.log.error("Push extension: decryption failed for \(id)")
+ deliverOnce(content, reason: "decryption failed")
+ return
+ }
+ content.title = title
+ content.body = body
+ snapshot(content)
+
+ // Receipt only after decryption, so a failed decrypt never consumes the message id.
+ let duplicate = await Self.receipt(id)
+ if Task.isCancelled { return }
+ if duplicate {
+ content.sound = nil
+ content.badge = nil
+ content.interruptionLevel = .passive
+ deliverOnce(content, reason: "duplicate")
+ return
+ }
+ content.badge = NSNumber(value: Self.nextBadgeCount())
+ snapshot(content)
+
+ if let image = decrypt(payload.image), image.lowercased().hasPrefix("https://"), let url = URL(string: image) {
+ if let attachment = await Self.downloadAttachment(url) {
+ content.attachments = [attachment]
+ } else {
+ Self.log.warning("Push extension: image could not be loaded for \(id)")
+ }
+ }
+ if Task.isCancelled { return }
+ deliverOnce(content, reason: "delivered")
+ }
+
+ private func decrypt(_ text: String) -> String? {
+ text.isEmpty ? nil : SecNtfySwifty.OfflineDecryption(text, Self.appGroup)
+ }
+
+ /// `POST /Message/Receive/{id}`; returns whether SecNtfy already had it (`Status 201`). Errors count as new.
+ private static func receipt(_ id: String) async -> Bool {
+ guard let defaults = UserDefaults(suiteName: appGroup),
+ let apiURL = defaults.string(forKey: "NTFY_API_URL"), let base = URL(string: apiURL),
+ let device = defaults.string(forKey: "NTFY_DEVICE_TOKEN"), !device.isEmpty else {
+ log.error("Push extension: receipt configuration missing")
+ return false
+ }
+ var request = URLRequest(url: base.appendingPathComponent("Message").appendingPathComponent("Receive")
+ .appendingPathComponent(id))
+ request.httpMethod = "POST"
+ request.timeoutInterval = 5
+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
+ request.setValue(device, forHTTPHeaderField: "X-NTFYME-DEVICE-KEY")
+ do {
+ let (data, response) = try await URLSession.shared.data(for: request)
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard (200...299).contains(code) else {
+ log.error("Push extension: receipt failed for \(id), HTTP \(code)")
+ return false
+ }
+ let duplicate = (try? JSONDecoder().decode(ReceiptResponse.self, from: data))?.status == 201
+ log.info("Push extension: receipt sent for \(id)\(duplicate ? " (already received)" : "")")
+ return duplicate
+ } catch {
+ log.error("Push extension: receipt failed for \(id): \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ private struct ReceiptResponse: Decodable {
+ let status: Int
+ enum CodingKeys: String, CodingKey { case status = "Status" }
+ }
+
+ /// Unread counter shared with the app (App Group key `BADGE_COUNT`); the app resets it when it is opened.
+ private static func nextBadgeCount() -> Int {
+ let defaults = UserDefaults(suiteName: appGroup)
+ let count = (defaults?.integer(forKey: "BADGE_COUNT") ?? 0) + 1
+ defaults?.set(count, forKey: "BADGE_COUNT")
+ return count
+ }
+
+ /// Latest state for the expiration path.
+ private func snapshot(_ content: UNNotificationContent) {
+ guard let copy = content.copy() as? UNNotificationContent else { return }
+ lock.withLock { if !finished { fallback = copy } }
+ }
+
+ private func deliverOnce(_ content: UNNotificationContent, reason: String) {
+ let taken: (handler: (UNNotificationContent) -> Void, task: Task?)? = lock.withLock {
+ guard !finished, let handler else { return nil }
+ finished = true
+ self.handler = nil
+ let task = self.task
+ self.task = nil
+ return (handler, task)
+ }
+ guard let taken else { return }
+ taken.task?.cancel()
+ Self.log.info("Push extension: completed (\(reason))")
+ taken.handler(content)
+ }
+
+ /// Android: 4 s connect/read timeouts; the file needs a type extension for the attachment.
+ private static func downloadAttachment(_ url: URL) async -> UNNotificationAttachment? {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 4
+ let session = URLSession(configuration: configuration)
+ defer { session.finishTasksAndInvalidate() }
+ guard let (file, response) = try? await session.download(from: url),
+ (response as? HTTPURLResponse)?.statusCode == 200 else { return nil }
+ let ext = response.mimeType.flatMap { UTType(mimeType: $0)?.preferredFilenameExtension }
+ ?? (url.pathExtension.isEmpty ? "jpg" : url.pathExtension)
+ let target = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString).appendingPathExtension(ext)
+ guard (try? FileManager.default.moveItem(at: file, to: target)) != nil else { return nil }
+ return try? UNNotificationAttachment(identifier: "image", url: target)
+ }
+}
diff --git a/IPv64Widget/AppIntent.swift b/IPv64Widget/AppIntent.swift
new file mode 100644
index 0000000..0a9fc4e
--- /dev/null
+++ b/IPv64Widget/AppIntent.swift
@@ -0,0 +1,34 @@
+//
+// AppIntent.swift
+// IPv64Widget
+//
+// Created by Sebastian Rank on 07.11.25.
+//
+
+import WidgetKit
+import AppIntents
+
+struct ConfigurationAppIntent: WidgetConfigurationIntent {
+ static var title: LocalizedStringResource { "Configuration" }
+ static var description: IntentDescription { "This is an example widget." }
+
+ // An example configurable parameter.
+ @Parameter(title: "Favorite Emoji", default: "😃")
+ var favoriteEmoji: String
+}
+
+/// One intent for every size: small shows the first 2 checks, medium 4, large 10.
+struct HealthchecksIntent: WidgetConfigurationIntent {
+ static var title: LocalizedStringResource = "Healthchecks"
+ static var description = IntentDescription("Choose up to 10 healthchecks: small shows 2, medium 4, large 10.")
+ @Parameter(title: "HC 1") var hc1: HealthCheckEntity?
+ @Parameter(title: "HC 2") var hc2: HealthCheckEntity?
+ @Parameter(title: "HC 3") var hc3: HealthCheckEntity?
+ @Parameter(title: "HC 4") var hc4: HealthCheckEntity?
+ @Parameter(title: "HC 5") var hc5: HealthCheckEntity?
+ @Parameter(title: "HC 6") var hc6: HealthCheckEntity?
+ @Parameter(title: "HC 7") var hc7: HealthCheckEntity?
+ @Parameter(title: "HC 8") var hc8: HealthCheckEntity?
+ @Parameter(title: "HC 9") var hc9: HealthCheckEntity?
+ @Parameter(title: "HC 10") var hc10: HealthCheckEntity?
+}
diff --git a/HealthcheckWidget/Assets.xcassets/AccentColor.colorset/Contents.json b/IPv64Widget/Assets.xcassets/AccentColor.colorset/Contents.json
similarity index 100%
rename from HealthcheckWidget/Assets.xcassets/AccentColor.colorset/Contents.json
rename to IPv64Widget/Assets.xcassets/AccentColor.colorset/Contents.json
diff --git a/IPv64Widget/Assets.xcassets/AppIcon.appiconset/Contents.json b/IPv64Widget/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 0000000..ffdfe15
--- /dev/null
+++ b/IPv64Widget/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,85 @@
+{
+ "images" : [
+ {
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "tinted"
+ }
+ ],
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "16x16"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "16x16"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "32x32"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "32x32"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "128x128"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "128x128"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "256x256"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "256x256"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "512x512"
+ },
+ {
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "512x512"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/HealthcheckWidget/Assets.xcassets/Contents.json b/IPv64Widget/Assets.xcassets/Contents.json
similarity index 100%
rename from HealthcheckWidget/Assets.xcassets/Contents.json
rename to IPv64Widget/Assets.xcassets/Contents.json
diff --git a/HealthcheckWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json b/IPv64Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json
similarity index 100%
rename from HealthcheckWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json
rename to IPv64Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json
diff --git a/IPv64Widget/DNS64Intents.swift b/IPv64Widget/DNS64Intents.swift
new file mode 100644
index 0000000..17bd339
--- /dev/null
+++ b/IPv64Widget/DNS64Intents.swift
@@ -0,0 +1,177 @@
+import Foundation
+import AppIntents
+import WidgetKit
+import SwiftUI
+import IPv64
+
+// MARK: - Nodes of the widget account
+
+/// A directly connected node with DNS64 (LocalNodeStore id + display name).
+struct DNS64NodeEntity: AppEntity {
+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "DNS64 node"
+ static let defaultQuery = DNS64NodeQuery()
+
+ let id: String
+ let name: String
+
+ var displayRepresentation: DisplayRepresentation { .init(title: "\(name)") }
+}
+
+struct DNS64NodeQuery: EntityQuery {
+ func entities(for identifiers: [String]) async throws -> [DNS64NodeEntity] {
+ DNS64Nodes.all().filter { identifiers.contains($0.id) }
+ }
+
+ func suggestedEntities() async throws -> [DNS64NodeEntity] { DNS64Nodes.all() }
+
+ func defaultResult() async -> DNS64NodeEntity? { DNS64Nodes.all().first }
+}
+
+/// Node access for the widget. Only nodes stored for the widget account (Keychain `API_KEY_WIDGET`) are used;
+/// keys come from the shared Keychain via `LocalNodeStore` and go only to the node, through the app's hardened `NodeTransport`.
+nonisolated enum DNS64Nodes {
+ private struct Account: Decodable {
+ let uuid: String?
+ let ApiKey: String
+ }
+
+ /// `LocalNodeStore` owner of the widget account (`User.uuid` of the stored account with the widget key).
+ static func owner() -> String? {
+ guard let key = try? SecureStore.readString("API_KEY_WIDGET"), !key.isEmpty,
+ let data = try? SecureStore.read("USER_ACCOUNTS"),
+ let accounts = try? JSONDecoder().decode([Account].self, from: data) else { return nil }
+ return accounts.first { $0.ApiKey == key }?.uuid
+ }
+
+ /// Nodes of the widget account whose last known status had DNS64 enabled (same set as the app's DNS64 tab).
+ static func all() -> [DNS64NodeEntity] {
+ guard let owner = owner() else { return [] }
+ return LocalNodeStore.list(owner: owner).filter(LocalNodeStore.dnsActive).map {
+ DNS64NodeEntity(id: $0, name: LocalNodeStore.name($0)?.trimmingCharacters(in: .whitespaces).nilIfEmpty
+ ?? "Node …" + String($0.suffix(4)))
+ }
+ }
+
+ /// The configured node, or the first one; `nil` when the account has no DNS64 node.
+ static func resolve(_ id: String?) -> (node: DNS64NodeEntity, client: Node64)? {
+ guard let owner = owner() else { return nil }
+ let nodes = all()
+ guard let node = nodes.first(where: { $0.id == id }) ?? nodes.first,
+ let access = LocalNodeStore.get(node.id, owner: owner),
+ let client = NodeClientFactory.client(for: access) else { return nil }
+ return (node, client)
+ }
+
+ static func client(_ id: String?) throws -> Node64 {
+ guard let client = resolve(id)?.client else { throw DNS64IntentError.noNode }
+ return client
+ }
+
+ /// Widget and Control show the new state right away.
+ static func reload() {
+ WidgetCenter.shared.reloadTimelines(ofKind: AppConfig.dns64WidgetKind)
+ ControlCenter.shared.reloadControls(ofKind: AppConfig.dns64ControlKind)
+ }
+}
+
+enum DNS64IntentError: Error, CustomLocalizedStringResourceConvertible {
+ case noNode
+
+ var localizedStringResource: LocalizedStringResource { "Connect a node with DNS64 in the app first." }
+}
+
+private extension String {
+ nonisolated var nilIfEmpty: String? { isEmpty ? nil : self }
+}
+
+// MARK: - Intents
+
+struct DNS64WidgetIntent: WidgetConfigurationIntent {
+ static let title: LocalizedStringResource = "DNS64"
+ static let description = IntentDescription("Blocking status of a DNS64 node.")
+ @Parameter(title: "Node") var node: DNS64NodeEntity?
+}
+
+struct DNS64ControlIntent: ControlConfigurationIntent {
+ static let title: LocalizedStringResource = "DNS64 Blocking"
+ @Parameter(title: "Node") var node: DNS64NodeEntity?
+}
+
+struct PauseDNS64Intent: AppIntent {
+ static let title: LocalizedStringResource = "Pause DNS64 Blocking"
+ @Parameter(title: "Node") var node: DNS64NodeEntity?
+ /// 1-1440, 0 = until resumed.
+ @Parameter(title: "Minutes", default: 15) var minutes: Int
+
+ init() {}
+ init(node: DNS64NodeEntity?, minutes: Int) {
+ self.node = node
+ self.minutes = minutes
+ }
+
+ func perform() async throws -> some IntentResult {
+ try await DNS64Nodes.client(node?.id).dns64.pause(minutes: minutes)
+ DNS64Nodes.reload()
+ return .result()
+ }
+}
+
+struct ResumeDNS64Intent: AppIntent {
+ static let title: LocalizedStringResource = "Resume DNS64 Blocking"
+ @Parameter(title: "Node") var node: DNS64NodeEntity?
+
+ init() {}
+ init(node: DNS64NodeEntity?) { self.node = node }
+
+ func perform() async throws -> some IntentResult {
+ try await DNS64Nodes.client(node?.id).dns64.resume()
+ DNS64Nodes.reload()
+ return .result()
+ }
+}
+
+/// Control toggle: on = blocking active; off pauses until resumed, so the toggle state is exact.
+struct SetDNS64BlockingIntent: SetValueIntent {
+ static let title: LocalizedStringResource = "Set DNS64 Blocking"
+ @Parameter(title: "Node") var node: DNS64NodeEntity?
+ @Parameter(title: "Blocking") var value: Bool
+
+ init() {}
+ init(node: DNS64NodeEntity?) { self.node = node }
+
+ func perform() async throws -> some IntentResult {
+ let dns = try DNS64Nodes.client(node?.id).dns64
+ if value { try await dns.resume() } else { try await dns.pause(minutes: 0) }
+ DNS64Nodes.reload()
+ return .result()
+ }
+}
+
+// MARK: - Control (iOS 18)
+
+struct DNS64BlockingControl: ControlWidget {
+ struct Value {
+ let isOn: Bool
+ let node: DNS64NodeEntity?
+ }
+
+ struct Provider: AppIntentControlValueProvider {
+ func previewValue(configuration: DNS64ControlIntent) -> Value { Value(isOn: true, node: configuration.node) }
+
+ func currentValue(configuration: DNS64ControlIntent) async throws -> Value {
+ guard let resolved = DNS64Nodes.resolve(configuration.node?.id) else { throw DNS64IntentError.noNode }
+ let blocking = try await resolved.client.dns64.status().blocking
+ return Value(isOn: blocking?.paused != true, node: resolved.node)
+ }
+ }
+
+ var body: some ControlWidgetConfiguration {
+ AppIntentControlConfiguration(kind: AppConfig.dns64ControlKind, provider: Provider()) { value in
+ ControlWidgetToggle("DNS64 Blocking", isOn: value.isOn, action: SetDNS64BlockingIntent(node: value.node)) { isOn in
+ Label(isOn ? "Active" : "Paused", systemImage: isOn ? "shield.lefthalf.filled" : "pause.circle")
+ }
+ }
+ .displayName("DNS64 Blocking")
+ .description("Pause or resume DNS64 blocking.")
+ }
+}
diff --git a/IPv64Widget/DNS64Widget.swift b/IPv64Widget/DNS64Widget.swift
new file mode 100644
index 0000000..3cb9991
--- /dev/null
+++ b/IPv64Widget/DNS64Widget.swift
@@ -0,0 +1,245 @@
+import Foundation
+import WidgetKit
+import AppIntents
+import SwiftUI
+import Charts
+import IPv64
+
+struct DNS64Entry: TimelineEntry {
+ enum Status {
+ /// The widget account has no directly connected node with DNS64.
+ case noNode
+ case unreachable
+ /// `pausedUntil` nil while paused = until resumed.
+ case loaded(paused: Bool, pausedUntil: Date?, queries: Int?, blocked: Int?)
+ }
+
+ /// One timeline bucket of the last 24 h; Allowed = max(total - blocked, 0) as in the app's `dns64Bars`.
+ struct Bar: Identifiable {
+ let index: Int
+ let allowed: Int
+ let blocked: Int
+ var id: Int { index }
+ }
+
+ let date: Date
+ let node: DNS64NodeEntity?
+ let status: Status
+ /// Empty = no chart (small size, or the timeline request failed).
+ var bars: [Bar] = []
+
+ static let sampleBars = (0..<48).map { i in Bar(index: i, allowed: 200 + (i * 37) % 180, blocked: 20 + (i * 13) % 60) }
+}
+
+struct DNS64Provider: AppIntentTimelineProvider {
+ func placeholder(in context: Context) -> DNS64Entry {
+ DNS64Entry(date: .now, node: DNS64NodeEntity(id: "preview", name: "Node64"),
+ status: .loaded(paused: false, pausedUntil: nil, queries: 12_345, blocked: 1_234),
+ bars: context.family == .systemSmall ? [] : DNS64Entry.sampleBars)
+ }
+
+ func snapshot(for configuration: DNS64WidgetIntent, in context: Context) async -> DNS64Entry {
+ context.isPreview ? placeholder(in: context) : await load(configuration, chart: context.family != .systemSmall)
+ }
+
+ func timeline(for configuration: DNS64WidgetIntent, in context: Context) async -> Timeline {
+ let entry = await load(configuration, chart: context.family != .systemSmall)
+ var next = Date.now.addingTimeInterval(15 * 60)
+ // A timed pause ends on the node by itself; refresh right after it.
+ if case .loaded(true, let until?, _, _) = entry.status, until < next { next = until.addingTimeInterval(5) }
+ return Timeline(entries: [entry], policy: .after(next))
+ }
+
+ private func load(_ configuration: DNS64WidgetIntent, chart: Bool) async -> DNS64Entry {
+ guard let resolved = DNS64Nodes.resolve(configuration.node?.id) else {
+ return DNS64Entry(date: .now, node: nil, status: .noNode)
+ }
+ let dns = resolved.client.dns64
+ async let status = try? dns.status()
+ // The counters are optional decoration; the blocking state decides reachability.
+ async let summary = try? dns.summary()
+ async let timeline: Node64.DNS64Timeline? = chart ? (try? await dns.timeline(range: .last24Hours)) : nil
+ guard let blocking = await status.map(\.blocking) else {
+ return DNS64Entry(date: .now, node: resolved.node, status: .unreachable)
+ }
+ let totals = await summary?.summary
+ let bars = (await timeline?.buckets ?? []).enumerated().map { i, bucket in
+ let blocked = bucket.blocked ?? 0
+ return DNS64Entry.Bar(index: i, allowed: max((bucket.total ?? 0) - blocked, 0), blocked: blocked)
+ }
+ let paused = blocking?.paused == true
+ // Go zero dates count as "no date" (like `HcFormat.real` in the app).
+ let until = blocking?.untilResumed == true ? nil : blocking?.pausedUntil.flatMap { $0.timeIntervalSince1970 > 0 ? $0 : nil }
+ return DNS64Entry(date: .now, node: resolved.node,
+ status: .loaded(paused: paused, pausedUntil: paused ? until : nil,
+ queries: totals?.total, blocked: totals?.blocked),
+ bars: bars)
+ }
+}
+
+struct DNS64WidgetView: View {
+ @Environment(\.widgetFamily) private var widgetFamily
+ let entry: DNS64Entry
+
+ /// Blocking state when loaded, `nil` without node data (no buttons then).
+ private var paused: Bool? {
+ if case .loaded(let paused, _, _, _) = entry.status { return paused }
+ return nil
+ }
+
+ var body: some View {
+ Group {
+ switch widgetFamily {
+ case .systemLarge:
+ VStack(alignment: .leading, spacing: 10) {
+ info
+ chart
+ if let paused { buttons(paused: paused) }
+ }
+ case .systemMedium:
+ HStack(alignment: .top, spacing: 12) {
+ VStack(alignment: .leading, spacing: 4) {
+ info
+ chart
+ }
+ if let paused { buttons(paused: paused) }
+ }
+ default:
+ VStack(alignment: .leading, spacing: 0) {
+ info
+ Spacer(minLength: 0)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .containerBackground(for: .widget) { Color(.systemBackground) }
+ }
+
+ /// Fills the remaining height; nothing when there are no bars.
+ @ViewBuilder private var chart: some View {
+ if entry.bars.isEmpty {
+ Spacer(minLength: 0)
+ } else {
+ DNS64QueriesChart(bars: entry.bars)
+ }
+ }
+
+ private var info: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Label("DNS64", systemImage: "shield.lefthalf.filled")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ if let node = entry.node {
+ Text(node.name)
+ .font(.system(.title3, design: .rounded))
+ .lineLimit(1)
+ }
+ switch entry.status {
+ case .noNode:
+ Text("Connect a node with DNS64 in the app.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ case .unreachable:
+ Text("Node not reachable")
+ .font(.subheadline)
+ .foregroundStyle(.red)
+ case .loaded(let paused, let until, let queries, let blocked):
+ stateText(paused: paused, until: until)
+ .font(.headline)
+ .foregroundStyle(paused ? .orange : .green)
+ .lineLimit(widgetFamily == .systemMedium ? 1 : 2)
+ .minimumScaleFactor(0.8)
+ if let queries, let blocked {
+ // Medium shares its height with the chart: one line there.
+ let layout = widgetFamily == .systemMedium ? AnyLayout(HStackLayout(spacing: 4)) : AnyLayout(VStackLayout(alignment: .leading, spacing: 0))
+ layout {
+ Text("\(queries) queries")
+ Text("\(blocked) blocked · 24 h")
+ }
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private func stateText(paused: Bool, until: Date?) -> Text {
+ guard paused else { return Text("Active") }
+ guard let until else { return Text("Paused until resumed") }
+ return Text("Paused until \(until.formatted(date: .omitted, time: .shortened))")
+ }
+
+ /// A column next to the status in medium, a row below the chart in large.
+ private func buttons(paused: Bool) -> some View {
+ let large = widgetFamily == .systemLarge
+ let layout = large ? AnyLayout(HStackLayout(spacing: 8)) : AnyLayout(VStackLayout(spacing: 6))
+ return layout {
+ if paused {
+ Button(intent: ResumeDNS64Intent(node: entry.node)) {
+ Label("Resume", systemImage: "play.fill").frame(maxWidth: .infinity)
+ }
+ .tint(.green)
+ } else {
+ Button(intent: PauseDNS64Intent(node: entry.node, minutes: 15)) {
+ Label("15 min", systemImage: "pause.fill").frame(maxWidth: .infinity)
+ }
+ Button(intent: PauseDNS64Intent(node: entry.node, minutes: 60)) {
+ Label("1 h", systemImage: "pause.fill").frame(maxWidth: .infinity)
+ }
+ }
+ }
+ .font(.caption)
+ .buttonStyle(.bordered)
+ .tint(.orange)
+ .frame(width: large ? nil : 110)
+ }
+}
+
+/// Stacked Allowed (green) / Blocked (red) bars of the last 24 h; no axes, only a "max N" label (no touch readout in widgets).
+struct DNS64QueriesChart: View {
+ let bars: [DNS64Entry.Bar]
+
+ var body: some View {
+ let maxValue = max(bars.map { $0.allowed + $0.blocked }.max() ?? 0, 1)
+ VStack(alignment: .leading, spacing: 2) {
+ Chart(bars) { bar in
+ BarMark(x: .value("Time", String(bar.index)), y: .value("Queries", bar.allowed))
+ .foregroundStyle(.green)
+ BarMark(x: .value("Time", String(bar.index)), y: .value("Queries", bar.blocked))
+ .foregroundStyle(.red)
+ }
+ .chartXAxis(.hidden)
+ .chartYAxis(.hidden)
+ .chartYScale(domain: 0...maxValue)
+ .frame(minHeight: 24, maxHeight: .infinity)
+ .accessibilityLabel("Queries of the last 24 hours, \(bars.count) bars, maximum \(maxValue.formatted())")
+ Text("max \(maxValue.formatted()) · 24 h")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ }
+ }
+}
+
+struct DNS64Widget: Widget {
+ var body: some WidgetConfiguration {
+ AppIntentConfiguration(kind: AppConfig.dns64WidgetKind, intent: DNS64WidgetIntent.self, provider: DNS64Provider()) { entry in
+ DNS64WidgetView(entry: entry)
+ }
+ .configurationDisplayName("DNS64")
+ .description("Blocking status of a directly connected node; chart and pause/resume in the medium and large sizes.")
+ .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
+ }
+}
+
+#Preview(as: .systemMedium) {
+ DNS64Widget()
+} timeline: {
+ DNS64Entry(date: .now, node: DNS64NodeEntity(id: "1", name: "Node64"),
+ status: .loaded(paused: false, pausedUntil: nil, queries: 12_345, blocked: 1_234), bars: DNS64Entry.sampleBars)
+ DNS64Entry(date: .now, node: DNS64NodeEntity(id: "1", name: "Node64"),
+ status: .loaded(paused: true, pausedUntil: .now.addingTimeInterval(900), queries: 12_345, blocked: 1_234))
+ DNS64Entry(date: .now, node: DNS64NodeEntity(id: "1", name: "Node64"), status: .unreachable)
+}
diff --git a/IPv64Widget/HealthProvider.swift b/IPv64Widget/HealthProvider.swift
new file mode 100644
index 0000000..a80b290
--- /dev/null
+++ b/IPv64Widget/HealthProvider.swift
@@ -0,0 +1,88 @@
+//
+// HealthProvider.swift
+// IPv64WidgetExtension
+//
+// Created by Sebastian Rank on 07.11.25.
+//
+
+import Foundation
+import WidgetKit
+import AppIntents
+import OSLog
+
+struct HealthEntry: TimelineEntry {
+ let date: Date
+ let configuration: HealthchecksIntent
+ let items: [HealthCheckEntity]
+ var updatedAt: Date? = nil
+ var isStale: Bool = false
+}
+
+struct HealthProvider: AppIntentTimelineProvider {
+ typealias Entry = HealthEntry
+ typealias I = HealthchecksIntent
+
+ let refreshMinutes: Int = 15
+
+ /// Slots the layout of a family shows (as the former per-size widgets).
+ static func slots(_ family: WidgetFamily) -> Int {
+ switch family {
+ case .systemLarge: 10
+ case .systemMedium: 4
+ default: 2
+ }
+ }
+
+ /// Picked checks of the first `slots` slots, without empty ones.
+ private func extract(_ i: I, _ family: WidgetFamily) -> [HealthCheckEntity] {
+ [i.hc1, i.hc2, i.hc3, i.hc4, i.hc5, i.hc6, i.hc7, i.hc8, i.hc9, i.hc10]
+ .prefix(Self.slots(family))
+ .compactMap { value in
+ guard let value, value.id != HealthCheckEntity.noneID else { return nil }
+ return value
+ }
+ }
+
+ func placeholder(in context: Context) -> Entry {
+ .init(date: .now, configuration: I(), items: Array(HealthCheckEntity.sampleList.prefix(Self.slots(context.family))))
+ }
+
+ func snapshot(for configuration: I, in context: Context) async -> Entry {
+ let selected = extract(configuration, context.family)
+ Logger(subsystem: "net.ipv64.widget", category: "configuration").notice("Snapshot family=\(String(describing: context.family), privacy: .public) selected=\(selected.count)")
+ return .init(date: .now, configuration: configuration, items: selected)
+ }
+
+ func timeline(for configuration: I, in context: Context) async -> Timeline {
+ let selected = extract(configuration, context.family)
+ Logger(subsystem: "net.ipv64.widget", category: "configuration").notice("Timeline family=\(String(describing: context.family), privacy: .public) selected=\(selected.count)")
+ // An empty configuration is an intentional empty widget. Returning a
+ // fresh entry immediately prevents WidgetKit from keeping the prior
+ // selection while a cache or network request is running.
+ guard !selected.isEmpty else {
+ return Timeline(entries: [Entry(date: .now, configuration: configuration, items: [])], policy: .never)
+ }
+
+ guard let snapshot = await HealthCheckCache.shared.fetchOrCached() else {
+ // Configuration entities can outlive their account; do not show their old status as current.
+ let unavailable = selected.map { HealthCheckEntity(id: $0.id, name: $0.name, states: []) }
+ let entry = Entry(date: .now, configuration: configuration, items: unavailable, isStale: true)
+ return Timeline(entries: [entry], policy: .after(nextRefresh()))
+ }
+
+ let recent = await ApiServiceWidget.fetchRecentStates(tokens: selected.map(\.id))
+ let byID = Dictionary(snapshot.checks.map {
+ ($0.token, HealthCheckEntity(id: $0.token, name: $0.name, states: recent[$0.token] ?? $0.states))
+ }, uniquingKeysWith: { first, _ in first })
+ // Preserve every slot, including its own fallback when that check is unavailable.
+ let items = selected.map { byID[$0.id] ?? HealthCheckEntity(id: $0.id, name: $0.name, states: []) }
+ let hasMissingCheck = selected.contains { byID[$0.id] == nil }
+ let entry = Entry(date: .now, configuration: configuration, items: items,
+ updatedAt: snapshot.updatedAt, isStale: snapshot.isStale || hasMissingCheck)
+ return Timeline(entries: [entry], policy: .after(nextRefresh()))
+ }
+
+ private func nextRefresh() -> Date {
+ .now.addingTimeInterval(TimeInterval(refreshMinutes * 60))
+ }
+}
diff --git a/IPv64Widget/HealthcheckEventView.swift b/IPv64Widget/HealthcheckEventView.swift
new file mode 100644
index 0000000..d43f41a
--- /dev/null
+++ b/IPv64Widget/HealthcheckEventView.swift
@@ -0,0 +1,40 @@
+import SwiftUI
+
+struct HealthcheckEventView: View {
+ var showSmall: Bool = true
+ /// Raw `HC2CheckState` values, newest first.
+ let states: [String]
+
+ var body: some View {
+ GeometryReader { geometry in
+ let barWidth: CGFloat = showSmall ? 5 : 7
+ let barSpacing: CGFloat = 5
+ let maxCount = Int(geometry.size.width / (barWidth + barSpacing))
+
+ HStack(spacing: barSpacing) {
+ ForEach(Array(states.prefix(maxCount).reversed().enumerated()), id: \.offset) { _, state in
+ RoundedRectangle(cornerRadius: 5)
+ .fill(Self.color(state))
+ .frame(width: barWidth, height: showSmall ? 20 : 34)
+ }
+ }
+ .frame(width: geometry.size.width, alignment: .leading)
+ }
+ .frame(height: showSmall ? 20 : 34)
+ }
+
+ /// Same colours as the app's `Hc2StateUi`.
+ static func color(_ state: String) -> Color {
+ switch state {
+ case "up": .green
+ case "down": .red
+ case "degraded", "flapping": .orange
+ case "paused": .teal
+ default: .gray
+ }
+ }
+}
+
+#Preview {
+ HealthcheckEventView(states: ["up", "up", "down", "degraded", "up", "paused", "pending", "up", "up", "up"])
+}
diff --git a/IPv64Widget/HealthcheckWidgetView.swift b/IPv64Widget/HealthcheckWidgetView.swift
new file mode 100644
index 0000000..63daff7
--- /dev/null
+++ b/IPv64Widget/HealthcheckWidgetView.swift
@@ -0,0 +1,152 @@
+//
+// HealthcheckWidgetView.swift
+// IPv64WidgetExtension
+//
+// Created by Sebastian Rank on 07.11.25.
+//
+
+import Foundation
+import SwiftUI
+import WidgetKit
+import SwiftyBeaver
+
+struct HealthcheckWidgetView: View {
+
+ @Environment(\.widgetFamily) var widgetFamily
+
+ let items: [HealthCheckEntity]
+ var updatedAt: Date? = nil
+ var isStale = false
+
+ var body: some View {
+ VStack(spacing: 4) {
+ if items.isEmpty {
+ Text("Choose healthchecks in Edit Widget")
+ } else {
+ if widgetFamily == .systemSmall { smallWidget }
+ else { mediumLargeWidget }
+ HStack(spacing: 3) {
+ if isStale { Image(systemName: "exclamationmark.arrow.trianglehead.2.clockwise.rotate.90") }
+ if let updatedAt {
+ Text("Updated")
+ Text(updatedAt, style: .time)
+ } else { Text("Waiting for update") }
+ }
+ .font(.caption2)
+ .foregroundStyle(isStale ? .orange : .secondary)
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ }
+ }
+ .containerBackground(for: .widget) { Color(.systemBackground) }
+ }
+
+ private var mediumLargeWidget: some View {
+ HStack(alignment: .top) {
+ let startFirst = 0
+ let endFirst = widgetFamily == .systemLarge ? 4 : 1
+ let startSecond = widgetFamily == .systemLarge ? 5 : 2
+ let endSecond = widgetFamily == .systemLarge ? 9 : 3
+ let firstColumn = GetColumn(start: startFirst, end: endFirst)
+ let secondColumn = GetColumn(start: startSecond, end: endSecond)
+
+ VStack {
+ ForEach(firstColumn, id:\.id) { hc in
+ container(hc)
+
+ if (firstColumn.count < startSecond) {
+ Spacer()
+ }
+ }
+ }
+ .padding(.top, GetPadding(firstColumn.count, isFirst: true))
+
+ VStack {
+ ForEach(secondColumn, id:\.id) { hc in
+ container(hc)
+ }
+
+ if (secondColumn.count < startSecond) {
+ Spacer()
+ }
+ }
+ .padding(.top, GetPadding(secondColumn.count, isFirst: false))
+ }
+ .containerBackground(for: .widget) {
+ // 👇 Hintergrund für System-Widget-Rendering
+ Color(.systemBackground)
+ }
+ }
+
+ private var smallWidget: some View {
+ VStack(alignment: .leading) {
+ let firstColumn = GetColumn(start: 0, end: 1)
+ ForEach(firstColumn, id: \.id) { hc in
+ container(hc)
+
+ if (firstColumn.count < 2) {
+ Spacer()
+ }
+ }
+ }
+ .containerBackground(for: .widget) {
+ // 👇 Hintergrund für System-Widget-Rendering
+ Color(.systemBackground)
+ }
+ }
+
+ private func GetPadding(_ columnCount: Int, isFirst: Bool) -> CGFloat {
+ if (widgetFamily == .systemLarge) {
+ if (isFirst && columnCount < 5) {
+ return 4
+ }
+ return 0
+ } else {
+ if (isFirst && columnCount == 1) {
+ return 3
+ }
+ return 0
+ }
+ }
+
+ private func container(_ hc: HealthCheckEntity) -> some View {
+ LazyVStack(alignment: .leading, spacing: 5) {
+ Text(hc.name)
+ .font(.system(.title3, design: .rounded))
+ .lineLimit(1)
+ HealthcheckEventView(showSmall: true, states: hc.states)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ fileprivate func GetColumn(start: Int, end: Int) -> ArraySlice {
+ if (items.count < start) {
+ iLogger.log.info("items.count < start")
+ return []
+ }
+ if (items.count > end) {
+ iLogger.log.info("items.count > end")
+ return items[start...end]
+ }
+ if (items.count == 1) {
+ iLogger.log.info("items.count == 1")
+ return items[start...start]
+ }
+ if (items.count == 0) {
+ iLogger.log.info("items.count == 0")
+ return []
+ }
+ if (items.count < end) {
+ iLogger.log.info("items.count < end")
+ if (items.count == start) {
+ iLogger.log.info("items.count == start")
+ return []
+ }
+ iLogger.log.info("items[start...items.count-1]")
+ return items[start...items.count-1]
+ } else {
+ iLogger.log.info("items[start...end-1]")
+ return items[start...end-1]
+ }
+ }
+}
diff --git a/IPv64Widget/IPv64Widget.swift b/IPv64Widget/IPv64Widget.swift
new file mode 100644
index 0000000..b4cc22d
--- /dev/null
+++ b/IPv64Widget/IPv64Widget.swift
@@ -0,0 +1,27 @@
+//
+// IPv64Widget.swift
+// IPv64Widget
+//
+// Created by Sebastian Rank on 07.11.25.
+//
+
+import WidgetKit
+import SwiftUI
+
+/// One kind for every size; the layout follows the family (small 2, medium 4, large 10 checks).
+struct HealthcheckWidget: Widget {
+ var body: some WidgetConfiguration {
+ AppIntentConfiguration(kind: "HealthcheckWidget", intent: HealthchecksIntent.self, provider: HealthProvider()) { entry in
+ HealthcheckWidgetView(items: entry.items, updatedAt: entry.updatedAt, isStale: entry.isStale)
+ }
+ .configurationDisplayName("Healthchecks")
+ .description("Show up to 2 (small), 4 (medium) or 10 (large) healthchecks.")
+ .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
+ }
+}
+
+#Preview(as: .systemSmall) {
+ HealthcheckWidget()
+} timeline: {
+ HealthEntry(date: .now, configuration: HealthchecksIntent(), items: HealthCheckEntity.sampleList)
+}
diff --git a/IPv64Widget/IPv64WidgetBundle.swift b/IPv64Widget/IPv64WidgetBundle.swift
new file mode 100644
index 0000000..9ca89f3
--- /dev/null
+++ b/IPv64Widget/IPv64WidgetBundle.swift
@@ -0,0 +1,18 @@
+//
+// IPv64WidgetBundle.swift
+// IPv64Widget
+//
+// Created by Sebastian Rank on 07.11.25.
+//
+
+import WidgetKit
+import SwiftUI
+
+@main
+struct IPv64WidgetBundle: WidgetBundle {
+ var body: some Widget {
+ HealthcheckWidget()
+ DNS64Widget()
+ DNS64BlockingControl()
+ }
+}
diff --git a/IPv64Widget/Info.plist b/IPv64Widget/Info.plist
new file mode 100644
index 0000000..608b18f
--- /dev/null
+++ b/IPv64Widget/Info.plist
@@ -0,0 +1,38 @@
+
+
+
+
+ NSAppTransportSecurity
+
+
+ NSAllowsArbitraryLoads
+
+ NSExceptionDomains
+
+ ipv64.net
+
+ NSIncludesSubdomains
+
+ NSExceptionAllowsInsecureHTTPLoads
+
+
+
+
+ NSLocalNetworkUsageDescription
+ IPv64.net connects directly to your Node64 nodes in your local network.
+ SecureKeychainAccessGroup
+ $(AppIdentifierPrefix)group.ipv64.net
+ NSExtension
+
+ NSExtensionAttributes
+
+ IntentsSupported
+
+ ClearHealthCheckCacheIntent
+
+
+ NSExtensionPointIdentifier
+ com.apple.widgetkit-extension
+
+
+
\ No newline at end of file
diff --git a/IPv64Widget/Service/ApiServiceWidget.swift b/IPv64Widget/Service/ApiServiceWidget.swift
new file mode 100644
index 0000000..683d08f
--- /dev/null
+++ b/IPv64Widget/Service/ApiServiceWidget.swift
@@ -0,0 +1,53 @@
+import Foundation
+import IPv64
+
+/// Healthchecks 2.0 data of the widget account (Keychain `API_KEY_WIDGET`).
+nonisolated enum ApiServiceWidget {
+ static let maxBars = 30
+
+ /// Checks with their recent state changes; nil when there is no key or the check list cannot be loaded.
+ @concurrent
+ static func fetchChecks() async -> [WidgetCheck]? {
+ guard let key = try? SecureStore.readString("API_KEY_WIDGET"), !key.isEmpty else { return nil }
+ let api = IPv64(apiKey: key)
+ do {
+ async let checks = api.hc2.checks.list()
+ // Events only decorate the bars; a failure still yields the current state.
+ async let events = try? api.hc2.events(limit: 100).items
+ let (list, recent) = try await (checks, events ?? [])
+ // The key may have changed while the request ran.
+ guard key == (try? SecureStore.readString("API_KEY_WIDGET")) else { return nil }
+ var byToken: [String: [String]] = [:]
+ for event in recent {
+ guard let token = event.token, let state = event.toState else { continue }
+ byToken[token, default: []].append(state)
+ }
+ return list.map { check in
+ var states = Array((byToken[check.token] ?? []).prefix(maxBars))
+ if states.isEmpty { states = [check.paused == true ? "paused" : check.state?.state?.rawValue ?? "pending"] }
+ return WidgetCheck(token: check.token, name: check.name ?? check.token, states: states)
+ }
+ } catch {
+ return nil
+ }
+ }
+
+ /// Latest measurements of the shown checks (newest first), like "Recent checks" in the app.
+ /// Checks whose request fails are missing; they keep the state-change bars of `fetchChecks`.
+ @concurrent
+ static func fetchRecentStates(tokens: [String]) async -> [String: [String]] {
+ guard let key = try? SecureStore.readString("API_KEY_WIDGET"), !key.isEmpty else { return [:] }
+ let api = IPv64(apiKey: key)
+ return await withTaskGroup(of: (String, [String])?.self) { group in
+ for token in Set(tokens) {
+ group.addTask {
+ guard let list = try? await api.hc2.checks.measurements(token, limit: maxBars), !list.isEmpty else { return nil }
+ return (token, list.map { $0.status == .up ? "up" : $0.status == .down ? "down" : "pending" })
+ }
+ }
+ var result: [String: [String]] = [:]
+ for await case let (token, states)? in group { result[token] = states }
+ return result
+ }
+ }
+}
diff --git a/IPv64Widget/Service/HealthCheckEntity.swift b/IPv64Widget/Service/HealthCheckEntity.swift
new file mode 100644
index 0000000..907911c
--- /dev/null
+++ b/IPv64Widget/Service/HealthCheckEntity.swift
@@ -0,0 +1,232 @@
+//
+// HealthCheckEntity.swift
+// IPv64WidgetExtension
+//
+// Created by Sebastian Rank on 07.11.25.
+//
+
+import Foundation
+import AppIntents
+import SwiftUI
+import WidgetKit
+import OSLog
+
+struct HealthCheckEntity: AppEntity, Identifiable, Hashable {
+ static let noneID = "__ipv64_none__"
+ static let none = HealthCheckEntity(id: noneID, name: "Keine Auswahl", states: [])
+
+ static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Healthcheck")
+ static var defaultQuery = HealthCheckQuery()
+
+ var id: String
+ var name: String
+ var states: [String]
+
+ static var defaultDisplayRepresentation: DisplayRepresentation {
+ .init(title: "No entry")
+ }
+
+ var displayRepresentation: DisplayRepresentation {
+ .init(title: id == Self.noneID ? "Keine Auswahl" : "\(name)")
+ }
+
+ static let sampleList: [HealthCheckEntity] = (1...10).map { i in
+ HealthCheckEntity(id: "\(i)", name: i == 1 ? "API" : "DB\(i)",
+ states: ["up", "down", "degraded", "up", "paused", "up", "up", "down", "up", "up", "pending", "up"])
+ }
+}
+
+// MARK: - Shared, account-scoped cache
+
+nonisolated struct HealthCheckSnapshot: Sendable {
+ let checks: [WidgetCheck]
+ let updatedAt: Date
+ let isStale: Bool
+}
+
+public actor HealthCheckCache {
+ public static let shared = HealthCheckCache()
+
+ private let ttl: TimeInterval = 60 * 5
+ private var payload: PersistedPayload?
+ private var loadedRevision: String?
+ private var loadedAccount: String?
+ private var inFlight: (id: UUID, account: String, task: Task<[WidgetCheck]?, Never>)?
+
+ private typealias PersistedPayload = WidgetHealthCachePayload
+
+ /// One shared request serves simultaneous widget sizes and intent queries.
+ func fetchOrCached() async -> HealthCheckSnapshot? {
+ let defaults = UserDefaults(suiteName: WidgetHealthCacheStore.suiteName)
+ let revision = defaults?.string(forKey: WidgetHealthCacheStore.revisionKey) ?? "initial"
+ let account = Self.accountFingerprint()
+ if loadedRevision != revision || loadedAccount != account {
+ invalidateMemory()
+ loadedRevision = revision
+ loadedAccount = account
+ if let data = defaults?.data(forKey: WidgetHealthCacheStore.cacheKey),
+ let stored = try? JSONDecoder().decode(PersistedPayload.self, from: data),
+ account == nil || stored.account == account {
+ payload = stored
+ }
+ }
+ // The old payload used asymmetric API encoding and cannot be reliably restored.
+ defaults?.removeObject(forKey: "HealthCheckCache_Data_v1")
+
+ if let payload, account == nil {
+ return snapshot(payload, isStale: true)
+ }
+ guard let account else { return nil }
+ if let payload, Date().timeIntervalSince(payload.updatedAt) < ttl {
+ return snapshot(payload, isStale: false)
+ }
+
+ let request: (id: UUID, account: String, task: Task<[WidgetCheck]?, Never>)
+ if let existing = inFlight, existing.account == account {
+ request = existing
+ } else {
+ let task = Task { await ApiServiceWidget.fetchChecks() }
+ request = (UUID(), account, task)
+ inFlight = request
+ }
+ let response = await request.task.value
+
+ // Account changes and manual refreshes may occur while the actor is suspended.
+ guard !Task.isCancelled, !request.task.isCancelled,
+ Self.accountFingerprint() == account,
+ loadedRevision == revision,
+ (defaults?.string(forKey: WidgetHealthCacheStore.revisionKey) ?? "initial") == revision else { return nil }
+
+ if inFlight?.id == request.id {
+ inFlight = nil
+ if let response {
+ let fresh = PersistedPayload(account: account, checks: response, updatedAt: .now)
+ payload = fresh
+ if let data = try? JSONEncoder().encode(fresh) {
+ defaults?.set(data, forKey: WidgetHealthCacheStore.cacheKey)
+ }
+ }
+ }
+ guard let payload, payload.account == account else { return nil }
+ return snapshot(payload, isStale: Date().timeIntervalSince(payload.updatedAt) >= ttl)
+ }
+
+ public func clear() {
+ invalidateMemory()
+ let defaults = UserDefaults(suiteName: WidgetHealthCacheStore.suiteName)
+ let revision = UUID().uuidString
+ loadedRevision = revision
+ defaults?.set(revision, forKey: WidgetHealthCacheStore.revisionKey)
+ defaults?.removeObject(forKey: WidgetHealthCacheStore.cacheKey)
+ defaults?.removeObject(forKey: "HealthCheckCache_Data_v1")
+ }
+
+ private func invalidateMemory() {
+ inFlight?.task.cancel()
+ inFlight = nil
+ payload = nil
+ loadedAccount = nil
+ }
+
+ private func snapshot(_ payload: PersistedPayload, isStale: Bool) -> HealthCheckSnapshot {
+ HealthCheckSnapshot(checks: payload.checks, updatedAt: payload.updatedAt, isStale: isStale)
+ }
+
+ private static func accountFingerprint() -> String? { WidgetHealthCacheStore.accountFingerprint() }
+}
+
+struct ClearHealthCheckCacheIntent: AppIntent {
+ static var title: LocalizedStringResource = "Clear Widget Cache"
+
+ func perform() async throws -> some IntentResult {
+ await HealthCheckCache.shared.clear()
+ WidgetCenter.shared.reloadAllTimelines()
+ return .result()
+ }
+}
+
+
+struct HealthCheckQuery: EntityQuery {
+
+ private func fetchOrCached() async -> HealthCheckSnapshot? {
+ await HealthCheckCache.shared.fetchOrCached()
+ }
+
+ private func mapAll(_ snapshot: HealthCheckSnapshot) -> [HealthCheckEntity] {
+ // Keep real checks first. WidgetKit uses the first suggested entity as
+ // the initial value for an unconfigured slot; putting the empty
+ // sentinel first would make every new or reloaded widget appear empty.
+ let checks = snapshot.checks.sortedWidget(by: \.name).map {
+ HealthCheckEntity(id: $0.token, name: $0.name, states: $0.states)
+ }
+ return checks + [HealthCheckEntity.none]
+ }
+
+ // MARK: - EntityQuery
+
+ func entities(for identifiers: [String]) async throws -> [HealthCheckEntity] {
+ Logger(subsystem: "net.ipv64.widget", category: "query").notice("Resolving entities count=\(identifiers.count) empty=\(identifiers.filter { $0 == HealthCheckEntity.noneID }.count)")
+ guard let res = await fetchOrCached() else {
+ // Keep an existing widget configuration resolvable even when the
+ // cache/API is temporarily unavailable. The timeline provider can
+ // refresh the values later without losing the selected IDs.
+ return identifiers.compactMap { id in
+ id == HealthCheckEntity.noneID
+ ? HealthCheckEntity.none
+ : HealthCheckEntity(id: id, name: id, states: [])
+ }
+ }
+ let set = Set(identifiers)
+ let filtered = res.checks.filter { set.contains($0.token) }
+ Logger(subsystem: "net.ipv64.widget", category: "query").notice("Available checks=\(res.checks.count) matched=\(filtered.count)")
+ var result = filtered.map { HealthCheckEntity(id: $0.token, name: $0.name, states: $0.states) }
+ if set.contains(HealthCheckEntity.noneID) { result.insert(.none, at: 0) }
+ return result
+ }
+
+ func suggestedEntities() async throws -> [HealthCheckEntity] {
+ guard let res = await fetchOrCached() else { return [.none] }
+ return mapAll(res)
+ }
+
+ func entities(matching string: String) async throws -> [HealthCheckEntity] {
+ guard let res = await fetchOrCached() else {
+ return HealthCheckEntity.none.name.localizedCaseInsensitiveContains(string) ? [.none] : []
+ }
+ let all = mapAll(res)
+ guard !string.isEmpty else { return all }
+ return all.filter { $0.name.localizedCaseInsensitiveContains(string) }
+ }
+}
+
+extension Array where Element == HealthCheckEntity {
+ nonisolated func filteringOut(ids: Set) -> [HealthCheckEntity] {
+ filter { $0.id == HealthCheckEntity.noneID || !ids.contains($0.id) }
+ }
+}
+
+extension HealthCheckQuery {
+ // One intent for all sizes; hide checks already picked in another slot.
+ func suggestedEntities(for intent: HealthchecksIntent) async throws -> [HealthCheckEntity] {
+ guard let res = await fetchOrCached() else { return [.none] }
+ let selected = Set([intent.hc1?.id, intent.hc2?.id, intent.hc3?.id, intent.hc4?.id, intent.hc5?.id, intent.hc6?.id, intent.hc7?.id, intent.hc8?.id, intent.hc9?.id, intent.hc10?.id].compactMap { $0 })
+ return mapAll(res).filteringOut(ids: selected)
+ }
+
+ func entities(matching string: String, for intent: HealthchecksIntent) async throws -> [HealthCheckEntity] {
+ guard let res = await fetchOrCached() else {
+ return HealthCheckEntity.none.name.localizedCaseInsensitiveContains(string) ? [.none] : []
+ }
+ let selected = Set([intent.hc1?.id, intent.hc2?.id, intent.hc3?.id, intent.hc4?.id, intent.hc5?.id, intent.hc6?.id, intent.hc7?.id, intent.hc8?.id, intent.hc9?.id, intent.hc10?.id].compactMap { $0 })
+ let all = mapAll(res).filteringOut(ids: selected)
+ guard !string.isEmpty else { return all }
+ return all.filter { $0.name.localizedCaseInsensitiveContains(string) }
+ }
+}
+
+
+extension Sequence {
+ func sortedWidget(by keyPath: KeyPath) -> [Element] {
+ sorted { ($0[keyPath: keyPath]).lowercased() < ($1[keyPath: keyPath]).lowercased() }
+ }
+}
diff --git a/HealthcheckIntents/HealthcheckIntents.entitlements b/IPv64WidgetExtension.entitlements
similarity index 73%
rename from HealthcheckIntents/HealthcheckIntents.entitlements
rename to IPv64WidgetExtension.entitlements
index 550c609..6c71fdd 100644
--- a/HealthcheckIntents/HealthcheckIntents.entitlements
+++ b/IPv64WidgetExtension.entitlements
@@ -2,6 +2,8 @@
+ keychain-access-groups
+ $(AppIdentifierPrefix)group.ipv64.net
com.apple.security.application-groups
group.ipv64.net
diff --git a/NotificationService/NotificationService.swift b/NotificationService/NotificationService.swift
deleted file mode 100644
index f4ed3d8..0000000
--- a/NotificationService/NotificationService.swift
+++ /dev/null
@@ -1,75 +0,0 @@
-//
-// NotificationService.swift
-// NotificationService
-//
-// Created by Sebastian Rank on 02.02.23.
-//
-
-import UserNotifications
-
-class NotificationService: UNNotificationServiceExtension {
-
- var contentHandler: ((UNNotificationContent) -> Void)?
- var bestAttemptContent: UNMutableNotificationContent?
-
- override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
- self.contentHandler = contentHandler
- bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
-
- if let bestAttemptContent = bestAttemptContent {
- // Modify the notification content here...
- bestAttemptContent.title = "\(bestAttemptContent.title)"
- var badgeCount = SetupPrefs.readPreference(mKey: "BADGE_COUNT", mDefaultValue: 0) as! Int
- badgeCount = badgeCount + 1
- bestAttemptContent.badge = (badgeCount) as NSNumber
- SetupPrefs.setPreference(mKey: "BADGE_COUNT", mValue: badgeCount)
- var isImageAvailable = true
- guard let body = bestAttemptContent.userInfo["fcm_options"] as? Dictionary, let imageUrl = body["image"] as? String
- else {
- isImageAvailable = false
- return
- //fatalError("Image Link not found")
- }
-
- if (isImageAvailable) {
- print(imageUrl)
- downloadImageFrom(url: imageUrl) { (attachment) in
- if let attachment = attachment {
- bestAttemptContent.attachments = [attachment]
- //bestAttemptContent.categoryIdentifier = "myNotificationCategory" // Comment it for now
- contentHandler(bestAttemptContent)
- }
- }
- } else {
- contentHandler(bestAttemptContent)
- }
- }
- }
-
- override func serviceExtensionTimeWillExpire() {
- // Called just before the extension will be terminated by the system.
- // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
- if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
- contentHandler(bestAttemptContent)
- }
- }
-
- private func downloadImageFrom(url: String, handler: @escaping (UNNotificationAttachment?) -> Void) {
- let task = URLSession.shared.downloadTask(with: URL(string: url)!) { (downloadedUrl, response, error) in
- guard let downloadedUrl = downloadedUrl else { handler(nil) ; return } // RETURNING NIL IF IMAGE NOT FOUND
- var urlPath = URL(fileURLWithPath: NSTemporaryDirectory())
- let uniqueUrlEnding = ProcessInfo.processInfo.globallyUniqueString + ".jpg"
- urlPath = urlPath.appendingPathComponent(uniqueUrlEnding)
- try? FileManager.default.moveItem(at: downloadedUrl, to: urlPath)
- do {
- let attachment = try UNNotificationAttachment(identifier: "picture", url: urlPath, options: nil)
- handler(attachment) // RETURNING ATTACHEMENT HAVING THE IMAGE URL SUCCESSFULLY
- } catch {
- print("attachment error")
- handler(nil)
- }
- }
- task.resume()
- }
-
-}
diff --git a/PrivacyInfo.xcprivacy b/PrivacyInfo.xcprivacy
deleted file mode 100644
index ec09e23..0000000
--- a/PrivacyInfo.xcprivacy
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
diff --git a/Tests/CoreRegressionTests.swift b/Tests/CoreRegressionTests.swift
new file mode 100644
index 0000000..0aa5abe
--- /dev/null
+++ b/Tests/CoreRegressionTests.swift
@@ -0,0 +1,218 @@
+import Foundation
+import Synchronization
+
+private struct TestFailure: Error, CustomStringConvertible {
+ let description: String
+}
+
+private func require(_ condition: @autoclosure () -> Bool, _ message: String) throws {
+ if !condition() { throw TestFailure(description: message) }
+}
+
+/// URLSession's protocol requests are immutable; all test-owned shared state is locked.
+private final class MockURLProtocol: URLProtocol, @unchecked Sendable {
+ private struct State {
+ var lastRequest: URLRequest?
+ var lastBody: Data?
+ var active = 0
+ var maximumActive = 0
+ }
+ private static let state = Mutex(State())
+ private let completed = Mutex(false)
+
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+
+ static var lastRequest: URLRequest? { state.withLock { $0.lastRequest } }
+ static var lastBody: Data? { state.withLock { $0.lastBody } }
+ static var maximumActive: Int { state.withLock { $0.maximumActive } }
+ static func resetConcurrency() { state.withLock { $0.maximumActive = $0.active } }
+
+ override func startLoading() {
+ let body: Data?
+ if let data = request.httpBody {
+ body = data
+ } else if let stream = request.httpBodyStream {
+ stream.open()
+ defer { stream.close() }
+ var data = Data()
+ var buffer = [UInt8](repeating: 0, count: 1024)
+ while stream.hasBytesAvailable {
+ let count = stream.read(&buffer, maxLength: buffer.count)
+ guard count > 0 else { break }
+ data.append(buffer, count: count)
+ }
+ body = data
+ } else {
+ body = nil
+ }
+ Self.state.withLock {
+ $0.lastRequest = request
+ $0.lastBody = body
+ $0.active += 1
+ $0.maximumActive = max($0.maximumActive, $0.active)
+ }
+ let delay: TimeInterval = request.url!.path == "/delay" ? 0.150 : 0
+ DispatchQueue.global().asyncAfter(deadline: .now() + delay) { [self] in
+ guard finishOnce() else { return }
+ deliverResponse()
+ }
+ }
+
+ override func stopLoading() { _ = finishOnce() }
+
+ private func finishOnce() -> Bool {
+ let first = completed.withLock { done in
+ if done { return false }
+ done = true
+ return true
+ }
+ if first { Self.state.withLock { $0.active -= 1 } }
+ return first
+ }
+
+ private func deliverResponse() {
+ let url = request.url!
+ if url.path == "/offline" || url.path == "/timeout" {
+ client?.urlProtocol(self, didFailWithError: URLError(url.path == "/offline" ? .notConnectedToInternet : .timedOut))
+ return
+ }
+ let code: Int
+ switch url.path {
+ case "/unauthorized": code = 401
+ case "/forbidden": code = 403
+ case "/rate-limit": code = 429
+ case "/server-error": code = 500
+ default: code = 200
+ }
+ let response: URLResponse = url.path == "/invalid-response"
+ ? URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
+ : HTTPURLResponse(url: url, statusCode: code, httpVersion: "HTTP/1.1", headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ let logicalStatus = url.path == "/logical-unauthorized" ? "401" : url.path == "/logical-rate-limit" ? "429" : "200"
+ client?.urlProtocol(self, didLoad: Data("{\"status\":\"\(logicalStatus)\"}".utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+@main
+private struct CoreRegressionTests {
+ static func main() async throws {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [MockURLProtocol.self]
+ let session = URLSession(configuration: config)
+ defer { session.invalidateAndCancel() }
+ try testCodable()
+ try await testRequest(session)
+ try await testErrors(session)
+ try await testCancellation(session)
+ try await benchmarkConcurrentRequests(session)
+ print("PASS: all core regression checks; no external network or account access")
+ }
+
+ private static func url(_ path: String) -> URL { URL(string: "https://tests.invalid\(path)")! }
+
+ private static func testRequest(_ session: URLSession) async throws {
+ let fields = ["name": "a+b &= %/?#", "unicode": "Grüße"]
+ let expected = "name=a%2Bb%20%26%3D%20%25%2F%3F%23&unicode=Gr%C3%BC%C3%9Fe"
+ try require(String(data: APITransport.formBody(fields), encoding: .utf8) == expected, "Form escaping changed reserved characters")
+ let response = try await APITransport.data(url: url("/success"), token: "test-token", method: "POST", fields: fields, session: session)
+ try require(String(data: response, encoding: .utf8) == "{\"status\":\"200\"}", "Successful response changed")
+ try require(MockURLProtocol.lastRequest?.value(forHTTPHeaderField: "Authorization") == "Bearer test-token", "Authorization header is invalid")
+ try require(MockURLProtocol.lastRequest?.httpMethod == "POST", "HTTP method changed")
+ try require(MockURLProtocol.lastRequest?.value(forHTTPHeaderField: "Content-Type") == "application/x-www-form-urlencoded; charset=utf-8", "Form content type is invalid")
+ try require(MockURLProtocol.lastBody == Data(expected.utf8), "URLSession request body differs from encoded form")
+ _ = try await APITransport.data(url: url("/success"), session: session)
+ try require(MockURLProtocol.lastRequest?.value(forHTTPHeaderField: "Authorization") == nil, "Anonymous request inherited credentials")
+ print("PASS: form escaping, request body, authorization, anonymous request")
+ }
+
+ private static func testErrors(_ session: URLSession) async throws {
+ let cases: [(String, (Error) -> Bool)] = [
+ ("/unauthorized", { if case APIError.unauthorized = $0 { return true }; return false }),
+ ("/forbidden", { if case APIError.unauthorized = $0 { return true }; return false }),
+ ("/rate-limit", { if case APIError.rateLimited = $0 { return true }; return false }),
+ ("/server-error", { if case APIError.http(500) = $0 { return true }; return false }),
+ ("/logical-unauthorized", { if case APIError.unauthorized = $0 { return true }; return false }),
+ ("/logical-rate-limit", { if case APIError.rateLimited = $0 { return true }; return false }),
+ ("/invalid-response", { if case APIError.invalidResponse = $0 { return true }; return false }),
+ ("/offline", { ($0 as? URLError)?.code == .notConnectedToInternet }),
+ ("/timeout", { ($0 as? URLError)?.code == .timedOut })
+ ]
+ for (path, matches) in cases {
+ do {
+ _ = try await APITransport.data(url: url(path), token: "test-token", session: session)
+ throw TestFailure(description: "Expected failure for \(path)")
+ } catch {
+ try require(matches(error), "Wrong error for \(path): \(error)")
+ }
+ }
+ do {
+ _ = try await APITransport.data(url: url("/success"), token: "", session: session)
+ throw TestFailure(description: "Empty API key accepted")
+ } catch APIError.unauthorized { }
+ try require(APITransport.message(for: URLError(.timedOut)).contains("timed out"), "Timeout guidance missing")
+ try require(APITransport.message(for: URLError(.notConnectedToInternet)).contains("Connection unavailable"), "Offline guidance missing")
+ print("PASS: HTTP 401/403/429/500, API-level errors, invalid response, offline, timeout, empty key")
+ }
+
+ private static func testCancellation(_ session: URLSession) async throws {
+ let task = Task { try await APITransport.data(url: url("/delay"), session: session) }
+ try await Task.sleep(for: .milliseconds(10))
+ task.cancel()
+ do {
+ _ = try await task.value
+ throw TestFailure(description: "Cancelled request completed successfully")
+ } catch {
+ try require(APITransport.isCancellation(error), "Cancellation misclassified: \(error)")
+ }
+ print("PASS: request cancellation")
+ }
+
+ private static func testCodable() throws {
+ try require(APITransport.isSuccessStatus("200"), "Numeric success status rejected")
+ try require(APITransport.isSuccessStatus("200 OK"), "HTTP-style success status rejected")
+ try require(APITransport.isSuccessStatus("success"), "Text success status rejected")
+ try require(!APITransport.isSuccessStatus("401 Unauthorized"), "Unauthorized status accepted")
+ try require(APITransport.statusCode("401 Unauthorized") == 401, "HTTP-style error status not parsed")
+ let encoder = JSONEncoder()
+ let decoder = JSONDecoder()
+ let event = HealthEvents(event_time: nil, status: 4, text: "Alarm")
+ let restoredEvent = try decoder.decode(HealthEvents.self, from: encoder.encode(event))
+ // UUID is a transient UI identity; compare persisted event fields.
+ try require(restoredEvent.event_time == nil && restoredEvent.status == 4 && restoredEvent.text == "Alarm", "HealthEvents roundtrip failed")
+ var check = HealthCheck(name: "API", healthstatus: 4, healthtoken: "test-check", add_time: nil,
+ last_update_time: nil, alarm_time: nil, events: [event])
+ check.keyInd = "original-key"
+ let restored = try decoder.decode(HealthCheck.self, from: encoder.encode(check))
+ try require(restored.add_time == nil && restored.last_update_time == nil && restored.alarm_time == nil, "Optional dates were lost")
+ try require(restored.healthtoken == check.healthtoken && restored.keyInd == "original-key", "Root object identity roundtrip failed")
+ let restoredArray = try decoder.decode([HealthCheck].self, from: encoder.encode([check]))
+ try require(restoredArray.first?.keyInd == "original-key" && restoredArray.first?.events.first?.status == 4, "Cache array roundtrip failed")
+ var apiCheck = try JSONSerialization.jsonObject(with: encoder.encode(check)) as! [String: Any]
+ apiCheck.removeValue(forKey: "keyInd")
+ apiCheck["add_time"] = NSNull()
+ let payload: [String: Any] = ["api-check-key": apiCheck, "info": "ok", "status": "200", "get_account_info": ""]
+ let apiResult = try decoder.decode(HealthCheckResult.self, from: JSONSerialization.data(withJSONObject: payload))
+ try require(apiResult.domain.count == 1 && apiResult.domain[0].keyInd == "api-check-key", "Dynamic API key decoding failed")
+ try require(apiResult.domain[0].add_time == nil && apiResult.status == "200", "API null date or status decoding failed")
+ print("PASS: event/check Codable, optional dates, root/cache identity, dynamic API decoding")
+ }
+
+ private static func benchmarkConcurrentRequests(_ session: URLSession) async throws {
+ MockURLProtocol.resetConcurrency()
+ let serialStart = ContinuousClock.now
+ for _ in 0..<3 { _ = try await APITransport.data(url: url("/delay"), session: session) }
+ let serial = serialStart.duration(to: .now)
+ try require(MockURLProtocol.maximumActive == 1, "Serial benchmark unexpectedly overlapped")
+ MockURLProtocol.resetConcurrency()
+ let parallelStart = ContinuousClock.now
+ async let first = APITransport.data(url: url("/delay"), session: session)
+ async let second = APITransport.data(url: url("/delay"), session: session)
+ async let third = APITransport.data(url: url("/delay"), session: session)
+ _ = try await (first, second, third)
+ let parallel = parallelStart.duration(to: .now)
+ try require(MockURLProtocol.maximumActive == 3, "Independent requests did not overlap")
+ print("MOCK BENCHMARK (three 150 ms responses, not production): serial=\(serial), parallel=\(parallel)")
+ }
+}
diff --git a/Tests/NodeSyncPlanTests.swift b/Tests/NodeSyncPlanTests.swift
new file mode 100644
index 0000000..5ea2d18
--- /dev/null
+++ b/Tests/NodeSyncPlanTests.swift
@@ -0,0 +1,45 @@
+// Run: Tests/run-node-sync-tests.sh — checks the merge rules that decide what the iCloud node sync deletes.
+import Foundation
+
+@main
+struct NodeSyncPlanTests {
+ typealias E = NodeSyncPlan.Entry
+ static func e(_ url: String, _ key: String = "k1", deleted: Bool? = nil) -> E {
+ E(url: url, key: key, name: nil, updatedAt: .distantPast, deleted: deleted)
+ }
+
+ static func main() {
+ let tomb = e("", "", deleted: true)
+ // New device: cloud entry imported.
+ var r = NodeSyncPlan.plan(local: [:], synced: ["a": e("u")], dirty: [], otherOwner: [])
+ precondition(r.upsert.keys.sorted() == ["a"] && r.push.isEmpty && r.remove.isEmpty)
+ // Existing node never synced: pushed, nothing removed.
+ r = NodeSyncPlan.plan(local: ["a": e("u")], synced: [:], dirty: [], otherOwner: [])
+ precondition(r.push == ["a"] && r.remove.isEmpty && r.upsert.isEmpty)
+ // iCloud Keychain wiped (items missing): re-pushed, never removed.
+ r = NodeSyncPlan.plan(local: ["a": e("u"), "b": e("v")], synced: [:], dirty: [], otherOwner: [])
+ precondition(r.remove.isEmpty && r.push == ["a", "b"])
+ // Forgotten on another device: removed here.
+ r = NodeSyncPlan.plan(local: ["a": e("u")], synced: ["a": tomb], dirty: [], otherOwner: [])
+ precondition(r.remove == ["a"] && r.push.isEmpty)
+ // Re-added here after a forget elsewhere: pushed, not removed.
+ r = NodeSyncPlan.plan(local: ["a": e("u")], synced: ["a": tomb], dirty: ["a"], otherOwner: [])
+ precondition(r.remove.isEmpty && r.push == ["a"])
+ // Key changed here offline: local wins, cloud copy not imported.
+ r = NodeSyncPlan.plan(local: ["a": e("u", "new")], synced: ["a": e("u", "old")], dirty: ["a"], otherOwner: [])
+ precondition(r.push == ["a"] && r.upsert.isEmpty)
+ // Key changed on another device: imported.
+ r = NodeSyncPlan.plan(local: ["a": e("u", "old")], synced: ["a": e("u", "new")], dirty: [], otherOwner: [])
+ precondition(r.upsert["a"]?.key == "new" && r.push.isEmpty)
+ // Identical: only marked as in sync.
+ r = NodeSyncPlan.plan(local: ["a": e("u")], synced: ["a": e("u")], dirty: [], otherOwner: [])
+ precondition(r.inSync == ["a"] && r.push.isEmpty && r.upsert.isEmpty && r.remove.isEmpty)
+ // Deletion marker of a node not stored here: nothing to import.
+ r = NodeSyncPlan.plan(local: [:], synced: ["a": tomb], dirty: [], otherOwner: [])
+ precondition(r.upsert.isEmpty && r.remove.isEmpty)
+ // Node id stored for another account on this device: not taken over.
+ r = NodeSyncPlan.plan(local: [:], synced: ["a": e("u")], dirty: [], otherOwner: ["a"])
+ precondition(r.upsert.isEmpty)
+ print("NodeSyncPlan: all checks passed")
+ }
+}
diff --git a/Tests/run-core-tests.sh b/Tests/run-core-tests.sh
new file mode 100755
index 0000000..4c3befb
--- /dev/null
+++ b/Tests/run-core-tests.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+set -euo pipefail
+
+PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+TEST_DIR="$(mktemp -d /tmp/ipv64-core-tests.XXXXXX)"
+trap 'rm -rf "$TEST_DIR"' EXIT
+
+xcrun swiftc -parse-as-library -swift-version 5 \
+ -module-cache-path "$TEST_DIR/module-cache" \
+ "$PROJECT_DIR/IPv64/Helpers/APITransport.swift" \
+ "$PROJECT_DIR/IPv64/Models/HealthCheck.swift" \
+ "$PROJECT_DIR/IPv64/Models/HealthEvents.swift" \
+ "$PROJECT_DIR/IPv64/Models/HealthCheckResult.swift" \
+ "$PROJECT_DIR/IPv64/Models/Enum.swift" \
+ "$PROJECT_DIR/IPv64/Helpers/SharedExtensions.swift" \
+ "$PROJECT_DIR/Tests/CoreRegressionTests.swift" \
+ -o "$TEST_DIR/core-regressions"
+"$TEST_DIR/core-regressions"
diff --git a/Tests/run-node-sync-tests.sh b/Tests/run-node-sync-tests.sh
new file mode 100755
index 0000000..e53fb79
--- /dev/null
+++ b/Tests/run-node-sync-tests.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+set -euo pipefail
+PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+TEST_DIR="$(mktemp -d /tmp/ipv64-node-sync-tests.XXXXXX)"
+trap 'rm -rf "$TEST_DIR"' EXIT
+xcrun swiftc -parse-as-library -swift-version 5 -module-cache-path "$TEST_DIR/module-cache" \
+ "$PROJECT_DIR/IPv64/Helpers/Nodes/NodeSyncPlan.swift" "$PROJECT_DIR/Tests/NodeSyncPlanTests.swift" \
+ -o "$TEST_DIR/node-sync-tests"
+"$TEST_DIR/node-sync-tests"
diff --git a/ipv64.icon/Assets/v 64-Logo.svg b/ipv64.icon/Assets/v 64-Logo.svg
new file mode 100644
index 0000000..97cf6e7
--- /dev/null
+++ b/ipv64.icon/Assets/v 64-Logo.svg
@@ -0,0 +1,12 @@
+
+
+
diff --git a/ipv64.icon/icon.json b/ipv64.icon/icon.json
new file mode 100644
index 0000000..22fd3a9
--- /dev/null
+++ b/ipv64.icon/icon.json
@@ -0,0 +1,50 @@
+{
+ "fill" : {
+ "automatic-gradient" : "display-p3:0.94510,0.60392,0.21961,1.00000"
+ },
+ "groups" : [
+ {
+ "layers" : [
+ {
+ "image-name" : "v 64-Logo.svg",
+ "name" : "v64",
+ "position-specializations" : [
+ {
+ "value" : {
+ "scale" : 0.47,
+ "translation-in-points" : [
+ 0,
+ 0
+ ]
+ }
+ },
+ {
+ "idiom" : "watchOS",
+ "value" : {
+ "scale" : 0.4,
+ "translation-in-points" : [
+ 0,
+ 0
+ ]
+ }
+ }
+ ]
+ }
+ ],
+ "shadow" : {
+ "kind" : "neutral",
+ "opacity" : 0.5
+ },
+ "translucency" : {
+ "enabled" : true,
+ "value" : 0.5
+ }
+ }
+ ],
+ "supported-platforms" : {
+ "circles" : [
+ "watchOS"
+ ],
+ "squares" : "shared"
+ }
+}
\ No newline at end of file
diff --git a/ipv64_beta.icon/Assets/beta_tag 2.png b/ipv64_beta.icon/Assets/beta_tag 2.png
new file mode 100644
index 0000000..38df3aa
Binary files /dev/null and b/ipv64_beta.icon/Assets/beta_tag 2.png differ
diff --git a/ipv64_beta.icon/Assets/v 64-Logo.svg b/ipv64_beta.icon/Assets/v 64-Logo.svg
new file mode 100644
index 0000000..97cf6e7
--- /dev/null
+++ b/ipv64_beta.icon/Assets/v 64-Logo.svg
@@ -0,0 +1,12 @@
+
+
+
diff --git a/ipv64_beta.icon/icon.json b/ipv64_beta.icon/icon.json
new file mode 100644
index 0000000..1e9a47d
--- /dev/null
+++ b/ipv64_beta.icon/icon.json
@@ -0,0 +1,97 @@
+{
+ "fill" : {
+ "automatic-gradient" : "display-p3:0.94510,0.60392,0.21961,1.00000"
+ },
+ "groups" : [
+ {
+ "layers" : [
+ {
+ "blend-mode" : "normal",
+ "fill-specializations" : [
+ {
+ "value" : {
+ "automatic-gradient" : "extended-gray:0.00000,1.00000"
+ }
+ },
+ {
+ "appearance" : "dark",
+ "value" : {
+ "solid" : "extended-gray:1.00000,1.00000"
+ }
+ },
+ {
+ "appearance" : "tinted",
+ "value" : {
+ "automatic-gradient" : "extended-gray:0.50000,1.00000"
+ }
+ }
+ ],
+ "glass" : true,
+ "hidden" : false,
+ "image-name" : "beta_tag 2.png",
+ "name" : "beta_tag 2",
+ "position-specializations" : [
+ {
+ "value" : {
+ "scale" : 0.71,
+ "translation-in-points" : [
+ 130.0078125,
+ 274.9921875
+ ]
+ }
+ },
+ {
+ "idiom" : "watchOS",
+ "value" : {
+ "scale" : 0.6,
+ "translation-in-points" : [
+ 175,
+ 254.9921875
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "image-name" : "v 64-Logo.svg",
+ "name" : "v 64-Logo",
+ "position-specializations" : [
+ {
+ "value" : {
+ "scale" : 0.47,
+ "translation-in-points" : [
+ 0,
+ 0
+ ]
+ }
+ },
+ {
+ "idiom" : "watchOS",
+ "value" : {
+ "scale" : 0.4,
+ "translation-in-points" : [
+ 0,
+ 0
+ ]
+ }
+ }
+ ]
+ }
+ ],
+ "shadow" : {
+ "kind" : "neutral",
+ "opacity" : 0.5
+ },
+ "translucency" : {
+ "enabled" : true,
+ "value" : 0.5
+ }
+ }
+ ],
+ "supported-platforms" : {
+ "circles" : [
+ "watchOS"
+ ],
+ "squares" : "shared"
+ }
+}
\ No newline at end of file