Files
Kisani/Services/BackupStatusService.swift

543 lines
25 KiB
Swift
Raw Permalink Normal View History

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
import Foundation
import Photos
import UIKit
import os.log
private let log = Logger(subsystem: "com.albert.nasbackup", category: "BackupStatus")
private let signposter = OSSignposter(subsystem: "com.albert.nasbackup", category: "BackupStatus")
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
@MainActor
final class BackupStatusService: NSObject, ObservableObject {
static let shared = BackupStatusService()
@Published private(set) var snapshot: BackupStatusSnapshot = .empty
@Published private(set) var isRefreshing: Bool = false
@Published private(set) var refreshError: String?
@Published private(set) var lastManifest: BackupManifest?
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
private let photoService = PhotoLibraryService()
private let cacheKey = "backupStatusSnapshot_v2"
// One active reconciliation task at a time cancelled before starting a new one.
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
private var refreshTask: Task<Void, Never>?
private var debounceTask: Task<Void, Never>?
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
private var lastFullRefresh: Date?
private static let debounceInterval: TimeInterval = 4
private static let minRefreshInterval: TimeInterval = 30
// MARK: Init
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
private override init() {
super.init()
loadCachedSnapshot()
PHPhotoLibrary.shared().register(self)
NotificationCenter.default.addObserver(
self,
selector: #selector(handleMemoryWarning),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil
)
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
}
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
NotificationCenter.default.removeObserver(self)
}
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
@objc private func handleMemoryWarning() {
log.warning("Memory warning — cancelling in-flight refresh")
cancelAll()
isRefreshing = false
}
// MARK: Public API
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
func refresh(force: Bool = false) {
cancelAll()
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
refreshTask = Task { [weak self] in
await self?.performRefresh(force: force)
}
}
func refreshAndWait(force: Bool = true) async {
cancelAll()
await performRefresh(force: force)
}
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
func refreshAfterBackup(entries: [ManifestEntry], connection: NASConnection) {
let safe = entries.count
// Only count files actually uploaded (fileSize > 0) toward nasArchiveTotal.
// Collision-skipped and fileExists-skipped entries have fileSize 0 and were
// already counted in the last directory scan adding them would double-count.
let newlyOnNAS = entries.filter { $0.fileSize > 0 }.count
snapshot.alreadySafe = min(snapshot.phoneTotal, snapshot.alreadySafe + safe)
snapshot.nasArchiveTotal += newlyOnNAS
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
saveSnapshot()
log.info("Post-backup optimistic update: +\(safe) safe, +\(newlyOnNAS) NAS")
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
Task {
await writeManifest(entries: entries, connection: connection)
refresh(force: true)
}
}
// MARK: Refresh lifecycle
private func cancelAll() {
refreshTask?.cancel()
refreshTask = nil
debounceTask?.cancel()
debounceTask = nil
}
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
private func performRefresh(force: Bool) async {
guard !isRefreshing else {
log.debug("Refresh skipped — already in progress")
return
}
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
if !force, let last = lastFullRefresh,
Date().timeIntervalSince(last) < Self.minRefreshInterval {
log.debug("Refresh debounced — updating phone count only")
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
updatePhoneCountOnly()
return
}
// Ensure LocalPhotoIndex is loaded from disk before reconcile.
// loadOrBuild() is a fast no-op when already in memory; on cold launch it
// reads the cached JSON so the fast path (skip NAS roundtrip) can fire.
await LocalPhotoIndex.shared.loadOrBuild()
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
lastFullRefresh = Date()
isRefreshing = true
refreshError = nil
log.info("Refresh started (force=\(force))")
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
do {
try await reconcile()
log.info("Refresh completed — phone=\(self.snapshot.phoneTotal) safe=\(self.snapshot.alreadySafe)")
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
} catch is CancellationError {
log.info("Refresh cancelled")
} catch BackupError.timeout {
// NAS did not respond within the timeout window.
// Retain cached counts so the UI shows useful data instead of zeroes.
log.warning("Refresh timed out — retaining cached state")
refreshError = "NAS not responding — using last known state"
snapshot.lastCheckedAt = Date()
saveSnapshot()
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
} catch {
log.error("Refresh failed: \(error.localizedDescription)")
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
refreshError = error.localizedDescription
snapshot.connectionState = .offline
snapshot.lastCheckedAt = Date()
saveSnapshot()
}
isRefreshing = false
}
// MARK: Reconciliation
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
private func reconcile() async throws {
let spReconcile = signposter.beginInterval("Reconcile")
defer { signposter.endInterval("Reconcile", spReconcile) }
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
let store = ConnectionStore.shared
guard let conn = store.savedConnection else { return }
let filter = store.backupFilter
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
log.info("""
[reconcile] host=\(conn.host, privacy: .public) remotePath=\(conn.remotePath, privacy: .public) \
manifestPath=\(conn.remotePath, privacy: .public)/\(BackupManifest.remoteFilename, privacy: .public) \
filter=photos:\(filter.includePhotos) videos:\(filter.includeVideos) \
screenshots:\(filter.includeScreenshots) raw:\(filter.includeRAW) \
autoBackupEnabled=\(store.autoBackupEnabled) autoBackupOnOpen=\(store.autoBackupOnOpen)
""")
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
// Fast path: use local caches when both are warm
// Skips NAS connection + PHFetchResult batch enumeration entirely.
// Triggered when: manifest cache < 5 min old AND LocalPhotoIndex has data.
let manifestCacheIsStale = await NASManifestCache.shared.isStale
let localIndexCount = await LocalPhotoIndex.shared.totalCount
fastPath: if !manifestCacheIsStale, let cached = await NASManifestCache.shared.manifest, localIndexCount > 0 {
let dirCount = await NASManifestCache.shared.directoryCount ?? 0
let index: ManifestIndex
if dirCount > cached.entries.count {
// NAS has more files than the manifest tracks. Build a hybrid index that keeps
// manifest localIdentifiers (for Kisani uploads) and adds all cached NAS
// filenames as a filename-fallback. If filenames aren't cached yet, fall
// through to a full NAS reconcile so they get populated.
guard let filenames = await NASManifestCache.shared.directoryFilenames else {
log.info("Reconcile (cached): NAS dir(\(dirCount)) > manifest(\(cached.entries.count)) — no cached filenames, falling to full reconcile")
break fastPath
}
index = await Task.detached(priority: .utility) {
ManifestIndex(manifest: cached, nasFilenames: filenames, totalCount: dirCount)
}.value
} else {
index = await Task.detached(priority: .utility) {
ManifestIndex(manifest: cached)
}.value
}
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
let safe = await LocalPhotoIndex.shared.countSafe(against: index, filter: filter)
let phoneTotal = await LocalPhotoIndex.shared.count(filter: filter)
let nasTotal = max(index.totalCount, dirCount)
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
var updated = BackupStatusSnapshot()
updated.phoneTotal = phoneTotal
updated.alreadySafe = min(safe, phoneTotal)
updated.nasArchiveTotal = nasTotal
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
updated.connectionState = .connected
updated.lastCheckedAt = Date()
snapshot = updated
saveSnapshot()
log.info("Reconcile (cached): phone=\(phoneTotal) safe=\(safe) NAS=\(nasTotal) (manifest=\(index.totalCount) dir=\(dirCount))")
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
return
}
// Full path: connect to NAS and download fresh manifest
// Step 1: Phone count (O(1) PHFetchResult.count)
let fetchResult = photoService.fetchResultForReconciliation(filter: filter)
let phoneTotal = fetchResult.count
log.info("PHFetchResult count: \(phoneTotal)")
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
try Task.checkCancellation()
// Step 2: NAS connection
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
let transfer: any NASTransferProtocol = conn.nasProtocol == .smb ? SMBService() : SFTPService()
do {
try await Self.withTimeout(15) {
try await transfer.connect(
to: conn.host, port: conn.port,
username: conn.username, password: conn.password
)
}
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
} catch {
let reason: String
if case BackupError.timeout = error {
reason = "NAS not responding — using last known state"
} else {
reason = (error as? BackupError).flatMap { $0.errorDescription } ?? error.localizedDescription
}
Fix backup loop, NAS Archive regression, and manifest validity check - AutoBackupCoordinator: add 55s debounce to onActive() so repeated .task and scenePhase triggers (navigation appear, rapid foreground cycles) are no-ops; start a 60s periodic recheck timer on first active call; stop timer and reset debounce on willResignActiveNotification so each new foreground session always gets an immediate fresh status check - BackupView: remove the redundant lanMonitor.nasReachable onChange that was calling statusService.refresh() directly — coordinator already handles this via its Combine $nasReachable subscriber, avoiding a double reconcile that could bypass the autoBackupOnOpen gate with the wrong lastTriggerWasLAN value - BackupStatusService: when NAS connect fails, restore nasArchiveTotal from NASManifestCache before writing the offline snapshot — prevents the count from showing 0 when the NAS is temporarily unreachable but the cache is warm - BackupStatusService: manifest validity check — if the decoded manifest has ≤ 1 entries (corrupt or newly created), scan the NAS directory and use the real file count as the display floor for nasArchiveTotal without adding orphan entries to the manifest (that was the 7421 regression) - BackupManifest: add ManifestIndex.init(manifest:overrideTotalCount:) for the validity check path — keeps localIdentifier matching intact while correcting the displayed archive count - SMBService: add os.log around connect/auth/listDirectory with actual error reason instead of always surfacing authenticationFailed; distinguish network errors (timeout, host unreachable) from auth errors in thrown BackupError Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-18 16:07:41 +03:00
log.warning("NAS connect failed: \(reason, privacy: .public) — retaining cached counts")
refreshError = reason
// Restore last-known NAS archive count so the dashboard
Fix backup loop, NAS Archive regression, and manifest validity check - AutoBackupCoordinator: add 55s debounce to onActive() so repeated .task and scenePhase triggers (navigation appear, rapid foreground cycles) are no-ops; start a 60s periodic recheck timer on first active call; stop timer and reset debounce on willResignActiveNotification so each new foreground session always gets an immediate fresh status check - BackupView: remove the redundant lanMonitor.nasReachable onChange that was calling statusService.refresh() directly — coordinator already handles this via its Combine $nasReachable subscriber, avoiding a double reconcile that could bypass the autoBackupOnOpen gate with the wrong lastTriggerWasLAN value - BackupStatusService: when NAS connect fails, restore nasArchiveTotal from NASManifestCache before writing the offline snapshot — prevents the count from showing 0 when the NAS is temporarily unreachable but the cache is warm - BackupStatusService: manifest validity check — if the decoded manifest has ≤ 1 entries (corrupt or newly created), scan the NAS directory and use the real file count as the display floor for nasArchiveTotal without adding orphan entries to the manifest (that was the 7421 regression) - BackupManifest: add ManifestIndex.init(manifest:overrideTotalCount:) for the validity check path — keeps localIdentifier matching intact while correcting the displayed archive count - SMBService: add os.log around connect/auth/listDirectory with actual error reason instead of always surfacing authenticationFailed; distinguish network errors (timeout, host unreachable) from auth errors in thrown BackupError Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-18 16:07:41 +03:00
// doesn't show 0 when the NAS is temporarily offline.
let cachedCount = (await NASManifestCache.shared.manifest).map { ManifestIndex(manifest: $0).totalCount } ?? 0
let cachedDirCount = await NASManifestCache.shared.directoryCount ?? 0
snapshot.nasArchiveTotal = max(snapshot.nasArchiveTotal, cachedCount, cachedDirCount)
log.info("NAS offline — restored nasArchiveTotal=\(self.snapshot.nasArchiveTotal) (manifest=\(cachedCount) dir=\(cachedDirCount))")
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
snapshot.phoneTotal = phoneTotal
snapshot.alreadySafe = min(snapshot.alreadySafe, phoneTotal)
snapshot.connectionState = .offline
snapshot.lastCheckedAt = Date()
saveSnapshot()
return
}
defer { transfer.disconnect() }
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
try Task.checkCancellation()
// Step 3: Load ManifestIndex
let spManifest = signposter.beginInterval("ManifestLoad")
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
let manifestPath = "\(conn.remotePath)/\(BackupManifest.remoteFilename)"
let index = await buildManifestIndex(transfer: transfer, path: manifestPath, conn: conn)
signposter.endInterval("ManifestLoad", spManifest,
"\(index.totalCount) entries, filename-only=\(index.isFilenameOnly)")
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
log.info("Manifest index built — \(index.totalCount) NAS entries")
try Task.checkCancellation()
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
// Step 4: Count safe assets
// Prefer LocalPhotoIndex (pure in-memory, no CoreData) if populated;
// otherwise fall back to batch PHFetchResult enumeration.
let spCount = signposter.beginInterval("CountSafe")
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
let localCount = await LocalPhotoIndex.shared.totalCount
let safe: Int
if localCount > 0 {
safe = await LocalPhotoIndex.shared.countSafe(against: index, filter: filter)
} else {
safe = try await Task.detached(priority: .userInitiated) { [weak self, fetchResult, index] in
guard let self else { throw CancellationError() }
return try await self.countSafe(in: fetchResult, against: index)
}.value
}
signposter.endInterval("CountSafe", spCount, "\(safe)/\(phoneTotal) safe")
log.info("Comparison complete — \(safe)/\(phoneTotal) already safe")
// Step 5: Commit
let dirCount = await NASManifestCache.shared.directoryCount ?? 0
let nasTotal = max(index.totalCount, dirCount)
var updated = BackupStatusSnapshot()
updated.phoneTotal = phoneTotal
updated.alreadySafe = min(safe, phoneTotal)
updated.nasArchiveTotal = nasTotal
updated.connectionState = .connected
updated.lastCheckedAt = Date()
snapshot = updated
saveSnapshot()
log.info("Reconcile (full): phone=\(phoneTotal) safe=\(safe) NAS=\(nasTotal) (manifest=\(index.totalCount) dir=\(dirCount))")
// Invariant check alreadySafe + needBackup must always equal phoneTotal
let inv = updated.alreadySafe + updated.needBackup
if inv != updated.phoneTotal {
log.error("Invariant broken: alreadySafe(\(updated.alreadySafe)) + needBackup(\(updated.needBackup)) = \(inv) ≠ phoneTotal(\(updated.phoneTotal))")
}
}
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
/// Builds a ManifestIndex from NAS.
/// - The download suspends the main actor.
/// - JSON decode and Set construction run in a background task.
private func buildManifestIndex(
transfer: any NASTransferProtocol,
path: String,
conn: NASConnection
) async -> ManifestIndex {
log.info("buildManifestIndex: remotePath=\(conn.remotePath, privacy: .public) manifestFile=\(path, privacy: .public)")
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
do {
let data = try await Self.withTimeout(12) { try await transfer.downloadData(at: path) }
log.info("buildManifestIndex: manifest downloaded — \(data.count) bytes")
// Decode and build index off main actor JSONDecoder is not cheap for large manifests.
let decoded: (ManifestIndex, BackupManifest)? = await Task.detached(priority: .utility) {
guard let manifest = try? JSONDecoder.kisani.decode(BackupManifest.self, from: data)
else { return nil }
return (ManifestIndex(manifest: manifest), manifest)
}.value
if let (index, manifest) = decoded {
log.info("buildManifestIndex: decoded \(index.totalCount) entries (isFilenameOnly=\(index.isFilenameOnly))")
lastManifest = manifest
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
Task { await NASManifestCache.shared.update(manifest) }
Fix backup loop, NAS Archive regression, and manifest validity check - AutoBackupCoordinator: add 55s debounce to onActive() so repeated .task and scenePhase triggers (navigation appear, rapid foreground cycles) are no-ops; start a 60s periodic recheck timer on first active call; stop timer and reset debounce on willResignActiveNotification so each new foreground session always gets an immediate fresh status check - BackupView: remove the redundant lanMonitor.nasReachable onChange that was calling statusService.refresh() directly — coordinator already handles this via its Combine $nasReachable subscriber, avoiding a double reconcile that could bypass the autoBackupOnOpen gate with the wrong lastTriggerWasLAN value - BackupStatusService: when NAS connect fails, restore nasArchiveTotal from NASManifestCache before writing the offline snapshot — prevents the count from showing 0 when the NAS is temporarily unreachable but the cache is warm - BackupStatusService: manifest validity check — if the decoded manifest has ≤ 1 entries (corrupt or newly created), scan the NAS directory and use the real file count as the display floor for nasArchiveTotal without adding orphan entries to the manifest (that was the 7421 regression) - BackupManifest: add ManifestIndex.init(manifest:overrideTotalCount:) for the validity check path — keeps localIdentifier matching intact while correcting the displayed archive count - SMBService: add os.log around connect/auth/listDirectory with actual error reason instead of always surfacing authenticationFailed; distinguish network errors (timeout, host unreachable) from auth errors in thrown BackupError Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-18 16:07:41 +03:00
// Always scan directory so the NAS Archive count is accurate on every
// full reconcile (not just when the manifest is new/sparse).
// When the directory has more files than the manifest (uploaded by other
// tools), switch to filename-based matching so countSafe reflects real
// NAS coverage instead of only Kisani-tracked files.
let items = (try? await Self.withTimeout(12) { try await transfer.listDirectory(at: conn.remotePath) }) ?? []
let filteredItems = items.filter {
!$0.isDirectory && !$0.name.hasPrefix(".") && $0.name != BackupManifest.remoteFilename
}
let dirCount = filteredItems.count
log.info("buildManifestIndex: dir=\(dirCount) manifest=\(index.totalCount)")
if dirCount > index.totalCount {
// NAS has more files than manifest: keep manifest localIdentifiers
// for Kisani-tracked uploads and add all NAS filenames as fallback.
// This prevents discarding accumulated localIdentifier history.
let nasNames = filteredItems.map { $0.name }
await NASManifestCache.shared.setDirectoryFilenames(nasNames)
return await Task.detached(priority: .utility) {
ManifestIndex(manifest: manifest, nasFilenames: nasNames, totalCount: dirCount)
}.value
} else {
await NASManifestCache.shared.setDirectoryCount(dirCount)
return index
Fix backup loop, NAS Archive regression, and manifest validity check - AutoBackupCoordinator: add 55s debounce to onActive() so repeated .task and scenePhase triggers (navigation appear, rapid foreground cycles) are no-ops; start a 60s periodic recheck timer on first active call; stop timer and reset debounce on willResignActiveNotification so each new foreground session always gets an immediate fresh status check - BackupView: remove the redundant lanMonitor.nasReachable onChange that was calling statusService.refresh() directly — coordinator already handles this via its Combine $nasReachable subscriber, avoiding a double reconcile that could bypass the autoBackupOnOpen gate with the wrong lastTriggerWasLAN value - BackupStatusService: when NAS connect fails, restore nasArchiveTotal from NASManifestCache before writing the offline snapshot — prevents the count from showing 0 when the NAS is temporarily unreachable but the cache is warm - BackupStatusService: manifest validity check — if the decoded manifest has ≤ 1 entries (corrupt or newly created), scan the NAS directory and use the real file count as the display floor for nasArchiveTotal without adding orphan entries to the manifest (that was the 7421 regression) - BackupManifest: add ManifestIndex.init(manifest:overrideTotalCount:) for the validity check path — keeps localIdentifier matching intact while correcting the displayed archive count - SMBService: add os.log around connect/auth/listDirectory with actual error reason instead of always surfacing authenticationFailed; distinguish network errors (timeout, host unreachable) from auth errors in thrown BackupError Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-18 16:07:41 +03:00
}
}
log.warning("buildManifestIndex: manifest downloaded but failed to decode (\(data.count) bytes)")
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
} catch {
log.info("buildManifestIndex: manifest not found at \(path, privacy: .public)\(error.localizedDescription, privacy: .public) — falling back to directory listing")
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
}
// Bootstrap: list NAS directory and build filename-only index in background.
let items = (try? await Self.withTimeout(12) { try await transfer.listDirectory(at: conn.remotePath) }) ?? []
log.info("buildManifestIndex: bootstrap from \(items.count) items in \(conn.remotePath, privacy: .public)")
let bootstrapIndex = await Task.detached(priority: .utility) {
ManifestIndex(nasListing: items)
}.value
await NASManifestCache.shared.setDirectoryCount(bootstrapIndex.totalCount)
return bootstrapIndex
}
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
/// Enumerates a PHFetchResult in batches using autoreleasepool.
/// Marked nonisolated so it can be called from a background Task without
/// requiring main-actor scheduling it accesses no @MainActor state.
private nonisolated func countSafe(
in result: PHFetchResult<PHAsset>,
against index: ManifestIndex,
batchSize: Int = 150
) async throws -> Int {
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
var safe = 0
let total = result.count
var processed = 0
while processed < total {
try Task.checkCancellation()
let batchEnd = min(processed + batchSize, total)
// autoreleasepool releases PHAsset objects and PHAssetResource arrays
// created during this batch before moving to the next.
let batchSafe: Int = autoreleasepool {
var count = 0
for i in processed..<batchEnd {
let asset = result.object(at: i)
if index.matches(localIdentifier: asset.localIdentifier) {
count += 1
} else {
let resources = PHAssetResource.assetResources(for: asset)
if let name = resources.first?.originalFilename,
index.matches(filename: name) {
count += 1
}
}
}
return count
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
}
safe += batchSafe
processed = batchEnd
await Task.yield()
}
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
return safe
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
}
// MARK: Phone-only lightweight update (no NAS connection)
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
private func updatePhoneCountOnly() {
let result = photoService.fetchResultForReconciliation(
filter: ConnectionStore.shared.backupFilter
)
let phoneTotal = result.count
guard phoneTotal != snapshot.phoneTotal else { return }
snapshot.phoneTotal = phoneTotal
snapshot.alreadySafe = min(snapshot.alreadySafe, phoneTotal)
saveSnapshot()
log.debug("Phone-only update: \(phoneTotal) assets")
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
}
// MARK: Manifest write (non-blocking, background only)
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
func writeManifest(entries: [ManifestEntry], connection: NASConnection) async {
guard !entries.isEmpty else { return }
// Capture cache before connecting used as fallback if NAS download fails.
// This prevents discarding accumulated history when the connection is flaky.
let cacheBase = await NASManifestCache.shared.manifest
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
let transfer: any NASTransferProtocol = connection.nasProtocol == .smb ? SMBService() : SFTPService()
do {
try await transfer.connect(
to: connection.host, port: connection.port,
username: connection.username, password: connection.password
)
defer { transfer.disconnect() }
let manifestPath = "\(connection.remotePath)/\(BackupManifest.remoteFilename)"
log.info("writeManifest: path=\(manifestPath, privacy: .public) entries=\(entries.count)")
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
// Try NAS download authoritative if successful.
let existingData = try? await transfer.downloadData(at: manifestPath)
// Merge + JSON encode off main actor can be slow for large manifests.
// Use the manifest with more entries as the merge base so history is never lost
// if the NAS manifest has fewer entries than the local cache (e.g. 1 vs 264).
let result: (data: Data, manifest: BackupManifest)? = await Task.detached(priority: .utility) {
let nasManifest = existingData.flatMap { try? JSONDecoder.kisani.decode(BackupManifest.self, from: $0) }
let nasCount = nasManifest?.entries.count ?? 0
let cacheCount = cacheBase?.entries.count ?? 0
var manifest: BackupManifest
if nasCount > 0, nasCount >= cacheCount {
manifest = nasManifest! // NAS at least as current authoritative
} else if cacheCount > 0 {
manifest = cacheBase! // Cache has more history preserve it
} else {
manifest = BackupManifest()
}
manifest.merge(entries: entries)
guard let encoded = try? JSONEncoder.kisani.encode(manifest) else { return nil }
return (encoded, manifest)
}.value
guard let (encoded, mergedManifest) = result else { return }
// Update local cache BEFORE the NAS write decouples reconcile correctness
// from NAS write success. If the write fails/times out, the next fast-path
// reconcile still reads the correct merged manifest from local cache.
await NASManifestCache.shared.update(mergedManifest)
lastManifest = mergedManifest
try await transfer.writeData(encoded, to: manifestPath)
log.info("writeManifest: done — \(entries.count) new, total=\(mergedManifest.entries.count)")
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
} catch {
log.error("writeManifest failed (non-fatal): \(error.localizedDescription)")
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
}
}
// MARK: Timeout helper
/// Runs `work` and throws `BackupError.timeout` if it doesn't finish within `seconds`.
/// Uses a racing task group so the timeout fires even when the underlying SMB/SFTP
/// stack doesn't propagate Swift cooperative cancellation.
private nonisolated static func withTimeout<T: Sendable>(
_ seconds: TimeInterval,
work: @Sendable @escaping () async throws -> T
) async throws -> T {
try await withThrowingTaskGroup(of: T.self) { group in
group.addTask(priority: .userInitiated) { try await work() }
group.addTask(priority: .utility) {
try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
throw BackupError.timeout
}
defer { group.cancelAll() }
guard let result = try await group.next() else { throw BackupError.timeout }
return result
}
}
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
// MARK: Cache
private func loadCachedSnapshot() {
guard let data = UserDefaults.standard.data(forKey: cacheKey),
let cached = try? JSONDecoder().decode(BackupStatusSnapshot.self, from: data)
else { return }
snapshot = cached
}
private func saveSnapshot() {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
if let data = try? encoder.encode(snapshot) {
UserDefaults.standard.set(data, forKey: cacheKey)
}
}
}
// MARK: PHPhotoLibraryChangeObserver
extension BackupStatusService: PHPhotoLibraryChangeObserver {
nonisolated func photoLibraryDidChange(_ changeInstance: PHChange) {
perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign Cached indexes: - NASManifestCache: actor-based disk cache for the NAS manifest (kisani_manifest_cache.json) Avoids NAS network round-trip when cache < 5 min old. Updated after every manifest download. - LocalPhotoIndex: actor-based disk cache of phone asset metadata (kisani_local_index.json) Built once on first launch, then updated incrementally via PHPhotoLibraryChangeObserver. O(1) countSafe via in-memory dict (vs PHFetchResult batch enumeration + CoreData calls). Fast path reconcile: When both caches are warm, reconcile() skips NAS connection + PHFetchResult enumeration entirely and returns in microseconds. Falls through to full NAS path only when stale. AutoBackupCoordinator.onActive(): Changed force: true → force: false so the 30-second debounce prevents expensive rescans on rapid app foreground/background cycles. Dashboard appears instantly from cached snapshot. BackupQueueItem + queue tracking: BackupEngine publishes queueItems: [BackupQueueItem] with per-file status, progress, speed, error details. Queue is persisted to disk and reloaded on next launch so SyncView always has data to show even after restart. NotificationService: Centralised local notification sender replacing the inline UNMutableNotificationContent blocks. Sends for: backup started, completed, failed, paused, NAS offline. Uses category identifiers so same-type notifications replace each other. SyncView redesign: - Removed pill/chip around NAS IP — replaced with plain "Online/Offline/Checking" dot+text - No live NAS directory listing (was expensive NAS connection on every tab open) - Shows engine.queueItems grouped into Active / Failed / Completed sections - Per-file rows with inline progress bar + bytes/speed for uploading items, error text for failed - Idle state shows archive count from statusService snapshot GalleryViewModel: NAS tab and All tab now use NASManifestCache as fallback when statusService.lastManifest is nil (offline launch). Gallery shows NAS items even when NAS is unreachable. AppDelegate: Bootstraps LocalPhotoIndex.loadOrBuild() in background on launch (non-blocking). Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 23:28:29 +03:00
// Update LocalPhotoIndex incrementally avoids full rebuild on every change.
// We need the fetch result for change details; rebuild from scratch if unavailable.
Task(priority: .utility) {
let opts = PHFetchOptions()
let allAssets = PHAsset.fetchAssets(with: opts)
if let details = changeInstance.changeDetails(for: allAssets) {
await LocalPhotoIndex.shared.apply(
inserted: details.insertedObjects,
removed: details.removedObjects,
changed: details.changedObjects
)
await LocalPhotoIndex.shared.flush()
}
}
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
Task { @MainActor [weak self] in
guard let self else { return }
self.debounceTask?.cancel()
self.debounceTask = Task {
do {
try await Task.sleep(nanoseconds: UInt64(BackupStatusService.debounceInterval * 1_000_000_000))
self.refresh()
} catch {
// Cancelled a newer change event took over
}
}
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
}
}
}