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>
This commit is contained in:
@@ -5,13 +5,14 @@ struct BackupView: View {
|
||||
@EnvironmentObject var engine: BackupEngine
|
||||
@EnvironmentObject var store: ConnectionStore
|
||||
@EnvironmentObject var lanMonitor: LANMonitor
|
||||
@EnvironmentObject var statusService: BackupStatusService
|
||||
@StateObject private var vm = BackupViewModel()
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
@State private var showMenu = false
|
||||
@State private var showDestinationPicker = false
|
||||
@State private var pickerPath: String = "/"
|
||||
@State private var ringPage = 0
|
||||
@State private var nasFileCount: Int? = nil
|
||||
|
||||
private let ringPageCount = 4
|
||||
|
||||
@@ -95,6 +96,7 @@ struct BackupView: View {
|
||||
AppMenuView()
|
||||
.environmentObject(store)
|
||||
.environmentObject(lanMonitor)
|
||||
.environmentObject(engine)
|
||||
}
|
||||
.sheet(isPresented: $showDestinationPicker, onDismiss: {
|
||||
guard pickerPath != "/", var conn = store.savedConnection else { return }
|
||||
@@ -108,8 +110,26 @@ struct BackupView: View {
|
||||
.animation(.spring(response: 0.35, dampingFraction: 0.82), value: engine.job.status == .completed)
|
||||
.animation(.spring(response: 0.35, dampingFraction: 0.82), value: vm.photosAuthStatus == .authorized)
|
||||
.task {
|
||||
vm.loadPhotoCount(filter: store.backupFilter)
|
||||
await loadNASAndCompare()
|
||||
statusService.refresh(force: true)
|
||||
}
|
||||
.onChange(of: scenePhase) { phase in
|
||||
if phase == .active { statusService.refresh(force: true) }
|
||||
}
|
||||
.onChange(of: lanMonitor.nasReachable) { reachable in
|
||||
if reachable == true { statusService.refresh(force: true) }
|
||||
}
|
||||
.onChange(of: store.savedConnection?.remotePath) { _ in
|
||||
statusService.refresh(force: true)
|
||||
}
|
||||
.onChange(of: engine.job.status) { status in
|
||||
// After backup completes, the engine already calls refreshAfterBackup
|
||||
// but also do a delayed full reconcile to catch any stragglers
|
||||
if status == .completed {
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
statusService.refresh(force: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,14 +222,14 @@ struct BackupView: View {
|
||||
case 0:
|
||||
ringMainView
|
||||
|
||||
case 1: // Not backed up
|
||||
case 1: // Need backup
|
||||
VStack(spacing: 4) {
|
||||
Text("\(notBackedUpDisplayCount)")
|
||||
.font(.system(size: 44, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(AppTheme.ink)
|
||||
.contentTransition(.numericText())
|
||||
.monospacedDigit()
|
||||
Text("not backed up")
|
||||
Text("need backup")
|
||||
.font(AppTheme.caption())
|
||||
.foregroundStyle(AppTheme.inkTertiary)
|
||||
}
|
||||
@@ -245,8 +265,7 @@ struct BackupView: View {
|
||||
private var ringMainView: some View {
|
||||
switch engine.job.status {
|
||||
case .idle, .cancelled:
|
||||
if vm.totalPhotoCount > 0 && vm.notBackedUpCount == 0 {
|
||||
// All phone photos already exist in NAS
|
||||
if statusService.snapshot.phoneTotal > 0 && statusService.snapshot.needBackup == 0 {
|
||||
VStack(spacing: 8) {
|
||||
Image(systemName: "checkmark")
|
||||
.font(.system(size: 30, weight: .medium))
|
||||
@@ -257,12 +276,12 @@ struct BackupView: View {
|
||||
}
|
||||
} else {
|
||||
VStack(spacing: 6) {
|
||||
Text("\(vm.notBackedUpCount)")
|
||||
Text("\(statusService.snapshot.needBackup)")
|
||||
.font(.system(size: 44, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(AppTheme.ink)
|
||||
.contentTransition(.numericText())
|
||||
.monospacedDigit()
|
||||
Text(vm.totalPhotoCount == 0 ? "No photos found" : "not backed up")
|
||||
Text(statusService.snapshot.phoneTotal == 0 ? "No photos found" : "need backup")
|
||||
.font(AppTheme.caption())
|
||||
.foregroundStyle(AppTheme.inkTertiary)
|
||||
}
|
||||
@@ -345,27 +364,26 @@ struct BackupView: View {
|
||||
|
||||
// MARK: — Compact stats strip
|
||||
|
||||
// Photos from the phone set that are NOT yet in the NAS.
|
||||
// Idle: derived from NAS comparison scan.
|
||||
// Active: live remaining from engine job counters.
|
||||
// Live "need backup" count: optimistic during active backup, service-derived otherwise.
|
||||
// Invariant: needBackup + alreadySafe == phoneTotal always.
|
||||
private var notBackedUpDisplayCount: Int {
|
||||
switch engine.job.status {
|
||||
case .running, .paused, .preparing:
|
||||
return max(0, engine.job.totalFiles - engine.job.uploadedFiles
|
||||
- engine.job.skippedFiles - engine.job.failedFiles)
|
||||
case .completed: return 0
|
||||
default: return vm.notBackedUpCount
|
||||
default: return statusService.snapshot.needBackup
|
||||
}
|
||||
}
|
||||
|
||||
// Photos from the phone set that ARE already safe in the NAS.
|
||||
// Grows during backup as uploads + engine-skipped files are confirmed present.
|
||||
private var alreadySafeDisplayCount: Int {
|
||||
switch engine.job.status {
|
||||
case .running, .paused, .preparing, .completed:
|
||||
return vm.alreadySafeCount + engine.job.uploadedFiles + engine.job.skippedFiles
|
||||
// Optimistic: base from service + newly confirmed uploads this session
|
||||
return statusService.snapshot.alreadySafe
|
||||
+ engine.job.uploadedFiles + engine.job.skippedFiles
|
||||
default:
|
||||
return vm.alreadySafeCount
|
||||
return statusService.snapshot.alreadySafe
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,20 +391,20 @@ struct BackupView: View {
|
||||
VStack(spacing: 7) {
|
||||
HStack(spacing: 0) {
|
||||
compactStat(
|
||||
nasFileCount.map { "\($0)" } ?? "–",
|
||||
label: "In NAS",
|
||||
"\(statusService.snapshot.nasArchiveTotal)",
|
||||
label: "NAS Archive",
|
||||
color: AppTheme.interactive
|
||||
)
|
||||
thinDivider
|
||||
compactStat(
|
||||
"\(vm.totalPhotoCount)",
|
||||
"\(statusService.snapshot.phoneTotal)",
|
||||
label: "On iPhone",
|
||||
color: AppTheme.inkSecondary
|
||||
)
|
||||
thinDivider
|
||||
compactStat(
|
||||
"\(notBackedUpDisplayCount)",
|
||||
label: "Not Backed Up",
|
||||
label: "Need Backup",
|
||||
color: AppTheme.inkSecondary
|
||||
)
|
||||
thinDivider
|
||||
@@ -401,6 +419,39 @@ struct BackupView: View {
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
|
||||
|
||||
pageIndicator
|
||||
|
||||
// Subtle refresh status
|
||||
HStack(spacing: 5) {
|
||||
if statusService.isRefreshing {
|
||||
ProgressView()
|
||||
.scaleEffect(0.5)
|
||||
.tint(AppTheme.inkQuaternary)
|
||||
Text("Checking…")
|
||||
.font(.system(size: 10, weight: .regular))
|
||||
.foregroundStyle(AppTheme.inkQuaternary)
|
||||
} else if let checked = statusService.snapshot.lastCheckedAt {
|
||||
Image(systemName: statusService.snapshot.connectionState == .offline
|
||||
? "wifi.slash" : "checkmark.circle")
|
||||
.font(.system(size: 9, weight: .regular))
|
||||
.foregroundStyle(statusService.snapshot.connectionState == .offline
|
||||
? .orange : AppTheme.inkQuaternary)
|
||||
Text(checked, style: .relative)
|
||||
.font(.system(size: 10, weight: .regular))
|
||||
.foregroundStyle(AppTheme.inkQuaternary)
|
||||
+ Text(" ago")
|
||||
.font(.system(size: 10, weight: .regular))
|
||||
.foregroundStyle(AppTheme.inkQuaternary)
|
||||
}
|
||||
Spacer()
|
||||
Button {
|
||||
statusService.refresh(force: true)
|
||||
} label: {
|
||||
Image(systemName: "arrow.clockwise")
|
||||
.font(.system(size: 11, weight: .regular))
|
||||
.foregroundStyle(AppTheme.inkQuaternary)
|
||||
}
|
||||
}
|
||||
.frame(height: 16)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,22 +476,6 @@ struct BackupView: View {
|
||||
.frame(width: 0.5, height: 18)
|
||||
}
|
||||
|
||||
private func loadNASAndCompare() async {
|
||||
guard let conn = store.savedConnection else { return }
|
||||
do {
|
||||
let s: any NASTransferProtocol = conn.nasProtocol == .smb ? SMBService() : SFTPService()
|
||||
try await s.connect(to: conn.host, port: conn.port,
|
||||
username: conn.username, password: conn.password)
|
||||
let items = try await s.listDirectory(at: conn.remotePath)
|
||||
nasFileCount = items.filter { !$0.isDirectory }.count
|
||||
vm.compareWithNAS(nasItems: items)
|
||||
s.disconnect()
|
||||
} catch {
|
||||
nasFileCount = nil
|
||||
// On failure: notBackedUpCount stays at totalPhotoCount (conservative — show all as pending)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: — Destination row
|
||||
|
||||
private var destinationRow: some View {
|
||||
|
||||
@@ -3,42 +3,9 @@ import Photos
|
||||
|
||||
@MainActor
|
||||
final class BackupViewModel: ObservableObject {
|
||||
@Published var totalPhotoCount: Int = 0
|
||||
@Published var alreadySafeCount: Int = 0
|
||||
@Published var notBackedUpCount: Int = 0
|
||||
@Published var photosAuthStatus: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
|
||||
|
||||
private let photoService = PhotoLibraryService()
|
||||
private var fetchedAssets: [PhotoAsset] = []
|
||||
|
||||
func loadPhotoCount(filter: BackupFilter) {
|
||||
let assets = photoService.fetchAssets(filter: filter)
|
||||
fetchedAssets = assets
|
||||
totalPhotoCount = assets.count
|
||||
// Conservative initial state until NAS scan completes
|
||||
alreadySafeCount = 0
|
||||
notBackedUpCount = assets.count
|
||||
}
|
||||
|
||||
// Called after NAS directory listing loads.
|
||||
// Matches by lowercased filename — same heuristic BackupEngine uses for skip checks.
|
||||
// This gives an accurate pre-scan "Already Safe / Not Backed Up" split before
|
||||
// the user ever taps Start Backup.
|
||||
func compareWithNAS(nasItems: [NASItem]) {
|
||||
let nasFilenames = Set(
|
||||
nasItems
|
||||
.filter { !$0.isDirectory }
|
||||
.map { $0.name.lowercased() }
|
||||
)
|
||||
var safe = 0
|
||||
for asset in fetchedAssets {
|
||||
if nasFilenames.contains(asset.filename.lowercased()) {
|
||||
safe += 1
|
||||
}
|
||||
}
|
||||
alreadySafeCount = safe
|
||||
notBackedUpCount = totalPhotoCount - safe
|
||||
}
|
||||
|
||||
func requestPhotosAccess() async {
|
||||
photosAuthStatus = await photoService.requestAuthorization()
|
||||
|
||||
Reference in New Issue
Block a user