Files
Kisani/App/NASBackupApp.swift

54 lines
1.9 KiB
Swift
Raw Normal View History

import SwiftUI
import Photos
@main
struct NASBackupApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject private var store = ConnectionStore.shared
@StateObject private var engine = BackupEngine.shared
@StateObject private var lanMonitor = LANMonitor.shared
Add live backup status reconciliation with NAS manifest BackupStatusService (new singleton, ObservableObject, PHPhotoLibraryChangeObserver): - Loads cached BackupStatusSnapshot instantly from UserDefaults on init - Full reconcile: fetch phone assets → connect NAS → load/build manifest → compare → enforce invariant (alreadySafe ≤ phoneTotal), persist result - Debounced (30s) for photo library changes; force=true bypasses debounce - If NAS unreachable: keeps last cached numbers, marks connectionState = .offline - PHPhotoLibraryChangeObserver triggers refresh on any library change BackupManifest (new): - Stored at {remotePath}/.kisani.json on NAS - Indexed by localIdentifier (PHAsset stable ID); filename fallback for legacy entries - Built from directory listing if manifest missing (bootstrap for existing backups) - merged/updated after each backup run via NASTransferProtocol.writeData BackupStatusSnapshot (new): - Single source of truth: phoneTotal, alreadySafe, needBackup (derived), nasArchiveTotal, lastCheckedAt, connectionState - Invariant enforced in service: alreadySafe = min(safe, phoneTotal) Protocol / services: - NASTransferProtocol: adds writeData(_ data: Data, to remotePath: String) - SMBService: implements writeData via temp file + SMBClient.upload - SFTPService: implements writeData via SFTP ByteBuffer write BackupEngine: - Tracks ManifestEntry per successful upload during backup loop - After backup: calls BackupStatusService.refreshAfterBackup(entries:connection:) which applies optimistic UI update then writes manifest + triggers reconcile BackupView: - Reads all stats from BackupStatusService.snapshot (not vm/nasFileCount) - Stats labels: "NAS Archive" / "On iPhone" / "Need Backup" / "Already Safe" - Live refresh triggers: .task (force), scenePhase.active (force), nasReachable change (force), remotePath change (force), backup completed (+2s) - Subtle status row below stats: "Checking…" spinner or "Updated X ago" with wifi-slash icon when NAS offline; tap refresh button for forced reconcile - AppMenuView sheet now correctly passes engine EnvironmentObject BackupViewModel: stripped to auth-only (photosAuthStatus + requestPhotosAccess) Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 12:51:03 +03:00
@StateObject private var statusService = BackupStatusService.shared
feat: automatic backup on launch, foreground, and photo library change AutoBackupCoordinator (new): - @MainActor singleton that owns all auto-backup decisions - Phase model: idle / checking / autoBackingUp / disconnected - idle: nothing pending or destination not set - checking: reconciliation in progress before decision - autoBackingUp: coordinator-triggered BackupEngine run active - disconnected: NAS offline, pending count queued for retry - Combine subscription on BackupStatusService.$isRefreshing fires handleReconciliationComplete() on every reconcile completion — the single entry point for all auto-backup decisions - Combine subscription on LANMonitor.$nasReachable fires handleNASReachable() which retries only when phase == .disconnected - Guards: autoBackupEnabled, quiet hours, chargingOnlyMode + battery state - canAutoBackup also blocks when engine.job.status.isActive to prevent double-start from concurrent photo library change + foreground events BackupView: - .task + .onChange(of: scenePhase) now call coordinator.onActive() instead of statusService.refresh() directly — coordinator decides whether to also start a backup after reconciliation completes - ringContentID includes coordinator phase suffix → ring animates on checking/disconnected transitions - ringCenterContent case 0: when engine is idle, shows: - disconnectedRingView if phase == .disconnected and needBackup > 0 (wifi.slash icon, "Waiting for NAS", queued count) - checkingRingView if phase == .checking (spinner, "Checking…") - existing ringMainView otherwise - ringColor: dim orange (0.35 opacity) when disconnected with pending items - Pull-to-refresh reconciliation triggers auto-backup via Combine chain ConnectionStore: - autoBackupEnabled: Bool, default true, UserDefaults-persisted SettingsView: - AUTO BACKUP section at top with autoBackupEnabled toggle BackgroundTaskManager: - BGProcessingTask: quiet-hours guard, requiresExternalPower mirrors chargingOnlyMode, expiration handler calls engine.cancel() for clean exit - BGAppRefreshTask: lightweight refresh only (no upload in background refresh) - Both tasks reschedule themselves before doing any work AppDelegate: - UIDevice.current.isBatteryMonitoringEnabled = true for battery checks NASBackupApp: - AutoBackupCoordinator.shared injected as @StateObject + environmentObject Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 17:28:11 +03:00
@StateObject private var coordinator = AutoBackupCoordinator.shared
var body: some Scene {
WindowGroup {
RootView()
.environmentObject(store)
.environmentObject(engine)
.environmentObject(lanMonitor)
Add live backup status reconciliation with NAS manifest BackupStatusService (new singleton, ObservableObject, PHPhotoLibraryChangeObserver): - Loads cached BackupStatusSnapshot instantly from UserDefaults on init - Full reconcile: fetch phone assets → connect NAS → load/build manifest → compare → enforce invariant (alreadySafe ≤ phoneTotal), persist result - Debounced (30s) for photo library changes; force=true bypasses debounce - If NAS unreachable: keeps last cached numbers, marks connectionState = .offline - PHPhotoLibraryChangeObserver triggers refresh on any library change BackupManifest (new): - Stored at {remotePath}/.kisani.json on NAS - Indexed by localIdentifier (PHAsset stable ID); filename fallback for legacy entries - Built from directory listing if manifest missing (bootstrap for existing backups) - merged/updated after each backup run via NASTransferProtocol.writeData BackupStatusSnapshot (new): - Single source of truth: phoneTotal, alreadySafe, needBackup (derived), nasArchiveTotal, lastCheckedAt, connectionState - Invariant enforced in service: alreadySafe = min(safe, phoneTotal) Protocol / services: - NASTransferProtocol: adds writeData(_ data: Data, to remotePath: String) - SMBService: implements writeData via temp file + SMBClient.upload - SFTPService: implements writeData via SFTP ByteBuffer write BackupEngine: - Tracks ManifestEntry per successful upload during backup loop - After backup: calls BackupStatusService.refreshAfterBackup(entries:connection:) which applies optimistic UI update then writes manifest + triggers reconcile BackupView: - Reads all stats from BackupStatusService.snapshot (not vm/nasFileCount) - Stats labels: "NAS Archive" / "On iPhone" / "Need Backup" / "Already Safe" - Live refresh triggers: .task (force), scenePhase.active (force), nasReachable change (force), remotePath change (force), backup completed (+2s) - Subtle status row below stats: "Checking…" spinner or "Updated X ago" with wifi-slash icon when NAS offline; tap refresh button for forced reconcile - AppMenuView sheet now correctly passes engine EnvironmentObject BackupViewModel: stripped to auth-only (photosAuthStatus + requestPhotosAccess) Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 12:51:03 +03:00
.environmentObject(statusService)
feat: automatic backup on launch, foreground, and photo library change AutoBackupCoordinator (new): - @MainActor singleton that owns all auto-backup decisions - Phase model: idle / checking / autoBackingUp / disconnected - idle: nothing pending or destination not set - checking: reconciliation in progress before decision - autoBackingUp: coordinator-triggered BackupEngine run active - disconnected: NAS offline, pending count queued for retry - Combine subscription on BackupStatusService.$isRefreshing fires handleReconciliationComplete() on every reconcile completion — the single entry point for all auto-backup decisions - Combine subscription on LANMonitor.$nasReachable fires handleNASReachable() which retries only when phase == .disconnected - Guards: autoBackupEnabled, quiet hours, chargingOnlyMode + battery state - canAutoBackup also blocks when engine.job.status.isActive to prevent double-start from concurrent photo library change + foreground events BackupView: - .task + .onChange(of: scenePhase) now call coordinator.onActive() instead of statusService.refresh() directly — coordinator decides whether to also start a backup after reconciliation completes - ringContentID includes coordinator phase suffix → ring animates on checking/disconnected transitions - ringCenterContent case 0: when engine is idle, shows: - disconnectedRingView if phase == .disconnected and needBackup > 0 (wifi.slash icon, "Waiting for NAS", queued count) - checkingRingView if phase == .checking (spinner, "Checking…") - existing ringMainView otherwise - ringColor: dim orange (0.35 opacity) when disconnected with pending items - Pull-to-refresh reconciliation triggers auto-backup via Combine chain ConnectionStore: - autoBackupEnabled: Bool, default true, UserDefaults-persisted SettingsView: - AUTO BACKUP section at top with autoBackupEnabled toggle BackgroundTaskManager: - BGProcessingTask: quiet-hours guard, requiresExternalPower mirrors chargingOnlyMode, expiration handler calls engine.cancel() for clean exit - BGAppRefreshTask: lightweight refresh only (no upload in background refresh) - Both tasks reschedule themselves before doing any work AppDelegate: - UIDevice.current.isBatteryMonitoringEnabled = true for battery checks NASBackupApp: - AutoBackupCoordinator.shared injected as @StateObject + environmentObject Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 17:28:11 +03:00
.environmentObject(coordinator)
.preferredColorScheme(store.appearanceMode.resolvedScheme)
}
}
}
struct RootView: View {
@EnvironmentObject var store: ConnectionStore
@EnvironmentObject var lanMonitor: LANMonitor
var body: some View {
Group {
if store.savedConnection == nil {
ConnectView()
} else if !store.isSessionActive {
LoginView()
} else if store.savedConnection?.remotePath == "/" {
FolderSetupView()
} else if !store.onboardingPhotoShown {
PhotoPermissionView()
} else {
MainTabView()
}
}
.animation(.spring(response: 0.4, dampingFraction: 0.85), value: store.isSessionActive)
.animation(.spring(response: 0.4, dampingFraction: 0.85), value: store.savedConnection?.remotePath)
.animation(.spring(response: 0.4, dampingFraction: 0.85), value: store.onboardingPhotoShown)
.task(id: store.isSessionActive) {
guard store.isSessionActive, let conn = store.savedConnection else { return }
await lanMonitor.checkNASReachability(host: conn.host, port: conn.port)
}
}
}