From 1afcbaff96284c0bac38fb33cbf8688b00a2f2fd Mon Sep 17 00:00:00 2001 From: Robin Kutesa Date: Sun, 17 May 2026 23:28:29 +0300 Subject: [PATCH] perf: eliminate full rescans with local caches; add queue tracking, notifications, SyncView redesign MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Co-Authored-By: Sentry --- App/AppDelegate.swift | 5 + Core/Models/BackupQueueItem.swift | 34 ++ Features/Browse/GalleryViewModel.swift | 11 +- Features/Sync/SyncView.swift | 573 ++++++++++++------------- Kisani.xcodeproj/project.pbxproj | 16 + Services/AutoBackupCoordinator.swift | 7 +- Services/BackupEngine.swift | 93 +++- Services/BackupStatusService.swift | 72 +++- Services/LocalPhotoIndex.swift | 163 +++++++ Services/NASManifestCache.swift | 72 ++++ Services/NotificationService.swift | 65 +++ 11 files changed, 786 insertions(+), 325 deletions(-) create mode 100644 Core/Models/BackupQueueItem.swift create mode 100644 Services/LocalPhotoIndex.swift create mode 100644 Services/NASManifestCache.swift create mode 100644 Services/NotificationService.swift diff --git a/App/AppDelegate.swift b/App/AppDelegate.swift index 615d57d..78697c0 100644 --- a/App/AppDelegate.swift +++ b/App/AppDelegate.swift @@ -11,6 +11,11 @@ final class AppDelegate: NSObject, UIApplicationDelegate { BackgroundTaskManager.registerTasks() requestNotificationPermission() setupLANMonitor() + // Bootstrap local indexes in the background — non-blocking. + // After first build they're loaded from disk in microseconds. + Task(priority: .utility) { + await LocalPhotoIndex.shared.loadOrBuild() + } return true } diff --git a/Core/Models/BackupQueueItem.swift b/Core/Models/BackupQueueItem.swift new file mode 100644 index 0000000..208cc9e --- /dev/null +++ b/Core/Models/BackupQueueItem.swift @@ -0,0 +1,34 @@ +import Foundation + +struct BackupQueueItem: Identifiable, Codable, Sendable { + let id: String // = asset localIdentifier + var filename: String + var nasPath: String + var status: Status + var bytesUploaded: Int64 + var totalBytes: Int64 + var speedBytesPerSec: Double + var error: UploadError? + var retryCount: Int + var queuedAt: Date + var completedAt: Date? + + enum Status: String, Codable, Sendable { + case queued, uploading, uploaded, skipped, failed + } + + struct UploadError: Codable, Sendable { + var code: String + var message: String + var timestamp: Date + } + + var progress: Double { + guard totalBytes > 0 else { + return (status == .uploaded || status == .skipped) ? 1.0 : 0.0 + } + return min(1.0, Double(bytesUploaded) / Double(totalBytes)) + } + + var isFinished: Bool { status == .uploaded || status == .skipped || status == .failed } +} diff --git a/Features/Browse/GalleryViewModel.swift b/Features/Browse/GalleryViewModel.swift index dbe05f3..1cdcb38 100644 --- a/Features/Browse/GalleryViewModel.swift +++ b/Features/Browse/GalleryViewModel.swift @@ -38,7 +38,16 @@ final class GalleryViewModel: ObservableObject { isLoading = true nasError = nil - let manifestEntries = statusService.lastManifest?.entries ?? [] + // Prefer the in-memory lastManifest (most recent reconcile), fall back to + // disk-cached NASManifestCache (survives launches without NAS connection). + let manifestEntries: [ManifestEntry] + if let m = statusService.lastManifest { + manifestEntries = m.entries + } else if let cached = await NASManifestCache.shared.manifest { + manifestEntries = cached.entries + } else { + manifestEntries = [] + } let phoneAssets = await Task.detached(priority: .userInitiated) { Self.fetchPhoneAssets() diff --git a/Features/Sync/SyncView.swift b/Features/Sync/SyncView.swift index 8be8f02..514aaee 100644 --- a/Features/Sync/SyncView.swift +++ b/Features/Sync/SyncView.swift @@ -3,43 +3,175 @@ import SwiftUI struct SyncView: View { @EnvironmentObject var store: ConnectionStore @EnvironmentObject var lanMonitor: LANMonitor - - @State private var files: [NASItem] = [] - @State private var isLoading = false - @State private var error: String? = nil - @State private var appeared = false + @EnvironmentObject var engine: BackupEngine + @EnvironmentObject var statusService: BackupStatusService private var connection: NASConnection? { store.savedConnection } + private var queueItems: [BackupQueueItem] { engine.queueItems } + + private var uploadingItems: [BackupQueueItem] { queueItems.filter { $0.status == .uploading } } + private var queuedItems: [BackupQueueItem] { queueItems.filter { $0.status == .queued } } + private var completedItems: [BackupQueueItem] { queueItems.filter { $0.status == .uploaded || $0.status == .skipped } } + private var failedItems: [BackupQueueItem] { queueItems.filter { $0.status == .failed } } var body: some View { ZStack { AppTheme.background.ignoresSafeArea() - if connection == nil { noConnectionState - } else if isLoading && files.isEmpty { - loadingState - } else if let err = error { - errorState(err) - } else if files.isEmpty && !isLoading { - emptyState } else { - fileList + contentList } } .navigationTitle("Sync") .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .navigationBarTrailing) { - nasStatusChip + } + + // MARK: — Main content + + private var contentList: some View { + ScrollView { + LazyVStack(spacing: 0, pinnedViews: []) { + nasHeader + .padding(.horizontal, AppTheme.hPad) + .padding(.vertical, 14) + + Divider() + .padding(.horizontal, AppTheme.hPad) + + if queueItems.isEmpty { + idleState + .padding(.top, 48) + } else { + queueContent + } + + freeUpSpaceSection + .padding(.horizontal, AppTheme.hPad) + .padding(.top, 32) + .padding(.bottom, 48) } } - .task { await loadFiles() } - .refreshable { await loadFiles() } + .refreshable { + // Pull-to-refresh: show latest queue from engine (already live) + } + } + + // MARK: — NAS header (no pill, no border) + + private var nasHeader: some View { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 3) { + if let conn = connection { + Text(conn.host) + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(AppTheme.ink) + Text(conn.remotePath) + .font(AppTheme.micro()) + .foregroundStyle(AppTheme.inkTertiary) + .lineLimit(1) + Text(conn.nasProtocol == .smb ? "SMB" : "SFTP") + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(AppTheme.inkQuaternary) + } + } + Spacer() + HStack(spacing: 5) { + Circle() + .fill(nasColor) + .frame(width: 6, height: 6) + .animation(.spring(response: 0.3, dampingFraction: 0.8), value: lanMonitor.nasReachable) + Text(nasLabel) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(nasColor) + } + } + } + + private var nasColor: Color { + switch lanMonitor.nasReachable { + case true: AppTheme.positive + case false: AppTheme.destructive.opacity(0.8) + case nil: AppTheme.inkTertiary + } + } + + private var nasLabel: String { + switch lanMonitor.nasReachable { + case true: "Online" + case false: "Offline" + case nil: "Checking…" + } + } + + // MARK: — Queue content + + @ViewBuilder + private var queueContent: some View { + // Active / uploading + if !uploadingItems.isEmpty || !queuedItems.isEmpty { + sectionHeader("ACTIVE", count: uploadingItems.count + queuedItems.count) + ForEach(uploadingItems + queuedItems) { item in + QueueFileRow(item: item) + Divider().padding(.leading, 58) + } + } + + // Failed + if !failedItems.isEmpty { + sectionHeader("FAILED", count: failedItems.count) + ForEach(failedItems) { item in + QueueFileRow(item: item) + Divider().padding(.leading, 58) + } + } + + // Completed + if !completedItems.isEmpty { + sectionHeader("COMPLETED", count: completedItems.count) + ForEach(completedItems.prefix(30)) { item in + QueueFileRow(item: item) + Divider().padding(.leading, 58) + } + } + } + + private func sectionHeader(_ title: String, count: Int) -> some View { + HStack { + Text(title) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(AppTheme.inkTertiary) + .kerning(0.8) + Spacer() + Text("\(count)") + .font(AppTheme.micro()) + .foregroundStyle(AppTheme.inkQuaternary) + } + .padding(.horizontal, AppTheme.hPad) + .padding(.top, 20) + .padding(.bottom, 6) } // MARK: — States + private var idleState: some View { + VStack(spacing: 14) { + Image(systemName: statusService.snapshot.alreadySafe > 0 ? "checkmark.circle" : "arrow.up.doc") + .font(.system(size: 32, weight: .ultraLight)) + .foregroundStyle(AppTheme.inkQuaternary) + VStack(spacing: 5) { + Text(statusService.snapshot.alreadySafe > 0 ? "All caught up" : "No backup run yet") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(AppTheme.inkSecondary) + if statusService.snapshot.nasArchiveTotal > 0 { + Text("\(statusService.snapshot.nasArchiveTotal) files on NAS") + .font(AppTheme.caption()) + .foregroundStyle(AppTheme.inkTertiary) + } + } + } + } + private var noConnectionState: some View { VStack(spacing: 16) { Image(systemName: "externaldrive.badge.xmark") @@ -49,184 +181,53 @@ struct SyncView: View { Text("No NAS connected") .font(.system(size: 15, weight: .medium)) .foregroundStyle(AppTheme.inkSecondary) - Text("Connect to a NAS to see synced files") + Text("Connect to a NAS to see sync activity") .font(AppTheme.caption()) .foregroundStyle(AppTheme.inkTertiary) } } } - private var loadingState: some View { - VStack(spacing: 12) { - ProgressView().tint(AppTheme.inkTertiary) - Text("Loading files…") - .font(AppTheme.caption()) - .foregroundStyle(AppTheme.inkTertiary) - } - } - - private func errorState(_ message: String) -> some View { - VStack(spacing: 20) { - ZStack { - Circle().fill(AppTheme.surfaceSunken).frame(width: 64, height: 64) - Image(systemName: "wifi.exclamationmark") - .font(.system(size: 24, weight: .light)) - .foregroundStyle(AppTheme.inkSecondary) - } - VStack(spacing: 6) { - Text("Couldn't load files") - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(AppTheme.ink) - Text(message) - .font(AppTheme.caption()) - .foregroundStyle(AppTheme.inkTertiary) - .multilineTextAlignment(.center) - .padding(.horizontal, 40) - } - Button(action: { Task { await loadFiles() } }) { - HStack(spacing: 5) { - Image(systemName: "arrow.clockwise").font(.system(size: 12, weight: .medium)) - Text("Retry").font(.system(size: 13, weight: .medium)) - } - .foregroundStyle(AppTheme.ink) - .padding(.horizontal, 16).padding(.vertical, 8) - .background(AppTheme.surfaceSunken) - .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) - } - .buttonStyle(ScaleButtonStyle()) - } - } - - private var emptyState: some View { - VStack(spacing: 14) { - Image(systemName: "checkmark.circle") - .font(.system(size: 32, weight: .ultraLight)) - .foregroundStyle(AppTheme.inkQuaternary) - VStack(spacing: 5) { - Text("Nothing backed up yet") - .font(.system(size: 15, weight: .medium)) - .foregroundStyle(AppTheme.inkSecondary) - if let conn = connection { - Text(conn.remotePath) - .font(AppTheme.caption()) - .foregroundStyle(AppTheme.inkTertiary) - } - } - } - } - - // MARK: — File list - - private var fileList: some View { - ScrollView { - LazyVStack(spacing: 0) { - // Header strip - headerStrip - .padding(.horizontal, AppTheme.hPad) - .padding(.vertical, 14) - - Rectangle() - .fill(AppTheme.separator) - .frame(height: 0.5) - .padding(.horizontal, AppTheme.hPad) - - ForEach(Array(files.enumerated()), id: \.element.id) { idx, file in - SyncFileRow(item: file) - .opacity(appeared ? 1 : 0) - .offset(y: appeared ? 0 : 6) - .animation( - .spring(response: 0.38, dampingFraction: 0.82) - .delay(Double(min(idx, 12)) * 0.03), - value: appeared - ) - - if idx < files.count - 1 { - Rectangle() - .fill(AppTheme.separator) - .frame(height: 0.5) - .padding(.leading, 60) - } - } - - // Free Up Space section - freeUpSpaceSection - .padding(.horizontal, AppTheme.hPad) - .padding(.top, 28) - .padding(.bottom, 48) - } - } - .onAppear { appeared = true } - } - - private var headerStrip: some View { - HStack { - VStack(alignment: .leading, spacing: 3) { - Text("\(files.count) files backed up") - .font(.system(size: 14, weight: .semibold)) - .foregroundStyle(AppTheme.ink) - if let conn = connection { - Text(conn.remotePath) - .font(AppTheme.micro()) - .foregroundStyle(AppTheme.inkTertiary) - .lineLimit(1) - } - } - Spacer() - HStack(spacing: 5) { - Circle() - .fill(reachableColor) - .frame(width: 6, height: 6) - .animation(.spring(response: 0.3, dampingFraction: 0.8), value: lanMonitor.nasReachable) - Text(reachableLabel) - .font(AppTheme.micro()) - .foregroundStyle(reachableColor) - .animation(.spring(response: 0.3, dampingFraction: 0.8), value: lanMonitor.nasReachable) - } - } - } - // MARK: — Free Up Space private var freeUpSpaceSection: some View { VStack(alignment: .leading, spacing: 8) { - sectionLabel("FREE UP SPACE") + Text("FREE UP SPACE") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(AppTheme.inkTertiary) + .kerning(0.8) + .padding(.horizontal, 2) VStack(spacing: 0) { - // Explanation HStack(spacing: 12) { Image(systemName: "iphone.and.arrow.forward") - .font(.system(size: 14, weight: .regular)) + .font(.system(size: 14)) .foregroundStyle(AppTheme.inkSecondary) .frame(width: 20) VStack(alignment: .leading, spacing: 2) { Text("Delete local copies after backup") .font(AppTheme.body()) .foregroundStyle(AppTheme.ink) - Text("Photos and videos already on your NAS") + Text("Files already on your NAS") .font(AppTheme.caption()) .foregroundStyle(AppTheme.inkTertiary) } Spacer() } - .padding(.horizontal, AppTheme.cardPad) - .padding(.vertical, 12) + .padding(AppTheme.cardPad) - Rectangle() - .fill(AppTheme.separator) - .frame(height: 0.5) - .padding(.leading, AppTheme.cardPad) + Divider().padding(.leading, AppTheme.cardPad) - // Retention picker HStack { Text("Delete after") .font(AppTheme.body()) .foregroundStyle(AppTheme.ink) Spacer() Menu { - Button("Never (keep all)") { store.localRetentionDays = 0 } - Button("After 60 days") { store.localRetentionDays = 60 } - Button("After 90 days") { store.localRetentionDays = 90 } - Button("After 1 year") { store.localRetentionDays = 365 } + Button("Never") { store.localRetentionDays = 0 } + Button("60 days") { store.localRetentionDays = 60 } + Button("90 days") { store.localRetentionDays = 90 } + Button("1 year") { store.localRetentionDays = 365 } } label: { HStack(spacing: 4) { Text(retentionLabel) @@ -238,172 +239,162 @@ struct SyncView: View { } } } - .padding(.horizontal, AppTheme.cardPad) - .padding(.vertical, 12) - - if store.localRetentionDays > 0 { - Rectangle() - .fill(AppTheme.separator) - .frame(height: 0.5) - .padding(.leading, AppTheme.cardPad) - - HStack(spacing: 8) { - Image(systemName: "info.circle") - .font(.system(size: 12, weight: .regular)) - .foregroundStyle(AppTheme.inkTertiary) - Text("Files will be removed from this device \(retentionLabel.lowercased()) they were successfully backed up. They remain on your NAS.") - .font(AppTheme.micro()) - .foregroundStyle(AppTheme.inkTertiary) - } - .padding(.horizontal, AppTheme.cardPad) - .padding(.vertical, 10) - } + .padding(AppTheme.cardPad) } .background(AppTheme.surfaceRaised) .clipShape(RoundedRectangle(cornerRadius: AppTheme.radius, style: .continuous)) .shadow(color: AppTheme.cardShadow, radius: 12, x: 0, y: 2) - .animation(.spring(response: 0.3, dampingFraction: 0.8), value: store.localRetentionDays > 0) } } private var retentionLabel: String { switch store.localRetentionDays { - case 0: return "Never" - case 60: return "60 days" - case 90: return "90 days" - case 365: return "1 year" - default: return "\(store.localRetentionDays) days" + case 0: "Never" + case 60: "60 days" + case 90: "90 days" + case 365: "1 year" + default: "\(store.localRetentionDays) days" } } - - private var reachableColor: Color { - switch lanMonitor.nasReachable { - case true: return AppTheme.positive - case false: return AppTheme.destructive.opacity(0.7) - case nil: return AppTheme.inkQuaternary - } - } - - private var reachableLabel: String { - switch lanMonitor.nasReachable { - case true: return "Online" - case false: return "Offline" - case nil: return "Checking…" - } - } - - // MARK: — Toolbar chip - - private var nasStatusChip: some View { - HStack(spacing: 5) { - Circle() - .fill(lanMonitor.nasReachable == true ? AppTheme.positive : AppTheme.inkQuaternary) - .frame(width: 5, height: 5) - .animation(.spring(response: 0.3, dampingFraction: 0.8), value: lanMonitor.nasReachable) - Text(connection?.host ?? "NAS") - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(AppTheme.inkSecondary) - } - } - - // MARK: — Data - - private func loadFiles() async { - guard let conn = connection else { return } - isLoading = true - error = nil - do { - let s: any NASTransferProtocol = conn.nasProtocol == .smb ? SMBService() : SFTPService() - try await s.connect(to: conn.host, port: conn.port, - username: conn.username, password: conn.password) - files = try await s.listDirectory(at: conn.remotePath) - .filter { !$0.isDirectory } - .sorted { ($0.modifiedDate ?? .distantPast) > ($1.modifiedDate ?? .distantPast) } - s.disconnect() - } catch let e as BackupError { - self.error = e.errorDescription - } catch { - self.error = error.localizedDescription - } - isLoading = false - } } -// MARK: — File Row +// MARK: — Per-file row -struct SyncFileRow: View { - let item: NASItem +struct QueueFileRow: View { + let item: BackupQueueItem - private var ext: String { (item.name as NSString).pathExtension.lowercased() } + private var ext: String { (item.filename as NSString).pathExtension.lowercased() } private var fileIcon: String { switch ext { - case "jpg", "jpeg", "png", "heic", "heif", "gif", "webp": return "photo" - case "mp4", "mov", "m4v", "avi": return "play.rectangle" - case "raw", "dng", "cr2", "nef", "arw": return "camera.aperture" - case "pdf": return "doc.richtext" - default: return "doc" + case "jpg","jpeg","png","heic","heif","gif","webp": "photo" + case "mp4","mov","m4v","avi": "play.rectangle" + case "raw","dng","cr2","nef","arw": "camera.aperture" + case "pdf": "doc.richtext" + default: "doc" } } private var iconColor: Color { switch ext { - case "jpg", "jpeg", "png", "heic", "heif", "gif", "webp": return AppTheme.interactive - case "mp4", "mov", "m4v", "avi": return AppTheme.destructive - case "raw", "dng", "cr2", "nef", "arw": return AppTheme.inkSecondary - default: return AppTheme.inkTertiary + case "jpg","jpeg","png","heic","heif","gif","webp": AppTheme.interactive + case "mp4","mov","m4v","avi": AppTheme.destructive + case "raw","dng","cr2","nef","arw": AppTheme.inkSecondary + default: AppTheme.inkTertiary } } var body: some View { - HStack(spacing: 12) { - // File type icon - ZStack { - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(iconColor.opacity(0.1)) - .frame(width: 38, height: 38) - Image(systemName: fileIcon) - .font(.system(size: 15, weight: .regular)) - .foregroundStyle(iconColor) + VStack(spacing: 0) { + HStack(spacing: 12) { + ZStack { + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(iconColor.opacity(0.1)) + .frame(width: 38, height: 38) + Image(systemName: fileIcon) + .font(.system(size: 14, weight: .regular)) + .foregroundStyle(iconColor) + } + + VStack(alignment: .leading, spacing: 3) { + Text(item.filename) + .font(.system(size: 13, weight: .regular)) + .foregroundStyle(AppTheme.ink) + .lineLimit(1) + statusRow + } + + Spacer() + + statusBadge } + .padding(.horizontal, AppTheme.hPad) + .padding(.vertical, 10) - // Name + meta - VStack(alignment: .leading, spacing: 3) { - Text(item.name) - .font(.system(size: 14, weight: .regular)) - .foregroundStyle(AppTheme.ink) - .lineLimit(1) - - HStack(spacing: 6) { - if let date = item.modifiedDate { - Text(date, format: .dateTime.month(.abbreviated).day().year()) - .foregroundStyle(AppTheme.inkTertiary) + // Progress bar for uploading + if item.status == .uploading && item.totalBytes > 0 { + GeometryReader { geo in + ZStack(alignment: .leading) { + Rectangle() + .fill(AppTheme.surfaceSunken) + .frame(height: 2) + Rectangle() + .fill(AppTheme.interactive) + .frame(width: geo.size.width * CGFloat(item.progress), height: 2) + .animation(.linear(duration: 0.1), value: item.progress) } - if item.size > 0 { - Text("·").foregroundStyle(AppTheme.inkQuaternary) - Text(formatBytes(item.size)) - .foregroundStyle(AppTheme.inkTertiary) + } + .frame(height: 2) + .padding(.horizontal, AppTheme.hPad) + .padding(.bottom, 8) + } + } + } + + @ViewBuilder + private var statusRow: some View { + switch item.status { + case .uploading: + if item.totalBytes > 0 { + HStack(spacing: 4) { + Text("\(formatBytes(item.bytesUploaded)) / \(formatBytes(item.totalBytes))") + if item.speedBytesPerSec > 0 { + Text("·") + Text("\(formatBytes(Int64(item.speedBytesPerSec)))/s") } } .font(.system(size: 11, weight: .regular)) + .foregroundStyle(AppTheme.inkTertiary) + } else { + Text("Uploading…") + .font(.system(size: 11)).foregroundStyle(AppTheme.inkTertiary) } - - Spacer() - - // Synced badge - Image(systemName: "checkmark.circle.fill") - .font(.system(size: 14)) - .foregroundStyle(AppTheme.positive.opacity(0.7)) + case .queued: + Text("Queued") + .font(.system(size: 11)).foregroundStyle(AppTheme.inkTertiary) + case .uploaded, .skipped: + if let date = item.completedAt { + Text(date, format: .dateTime.month(.abbreviated).day().hour().minute()) + .font(.system(size: 11)).foregroundStyle(AppTheme.inkTertiary) + } + case .failed: + Text(item.error?.message ?? "Upload failed") + .font(.system(size: 11)) + .foregroundStyle(AppTheme.destructive.opacity(0.85)) + .lineLimit(1) + } + } + + @ViewBuilder + private var statusBadge: some View { + switch item.status { + case .uploading: + ProgressView() + .scaleEffect(0.7) + .tint(AppTheme.interactive) + case .queued: + Image(systemName: "clock") + .font(.system(size: 13)) + .foregroundStyle(AppTheme.inkQuaternary) + case .uploaded: + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 15)) + .foregroundStyle(AppTheme.positive.opacity(0.8)) + case .skipped: + Image(systemName: "arrow.forward.circle") + .font(.system(size: 15)) + .foregroundStyle(AppTheme.inkTertiary) + case .failed: + Image(systemName: "xmark.circle.fill") + .font(.system(size: 15)) + .foregroundStyle(AppTheme.destructive.opacity(0.8)) } - .padding(.horizontal, AppTheme.hPad) - .padding(.vertical, 11) } private func formatBytes(_ bytes: Int64) -> String { - let gb = Double(bytes) / 1_073_741_824 - if gb >= 1 { return String(format: "%.1f GB", gb) } let mb = Double(bytes) / 1_048_576 - if mb >= 1 { return String(format: "%.0f MB", mb) } - return String(format: "%.0f KB", Double(bytes) / 1024) + if mb < 1 { return "\(max(0, bytes / 1024)) KB" } + if mb < 1000 { return String(format: "%.1f MB", mb) } + return String(format: "%.1f GB", mb / 1024) } } diff --git a/Kisani.xcodeproj/project.pbxproj b/Kisani.xcodeproj/project.pbxproj index 0438d39..990066f 100644 --- a/Kisani.xcodeproj/project.pbxproj +++ b/Kisani.xcodeproj/project.pbxproj @@ -21,6 +21,7 @@ 19CB72B2DCA08EC8C8EB3103 /* UGreenCompatibilityBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B4A0DF226AB4C5EE9E0D16 /* UGreenCompatibilityBadge.swift */; }; 1AEF3190A6F5D3AB43CC521D /* BackupEngineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35A5F6ABBD052F931949B2FA /* BackupEngineTests.swift */; }; 20F9E76FDA60BA806980E44A /* ToggleRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 674029116718AB4525AD9450 /* ToggleRow.swift */; }; + 210BF39897CC8E966A72698C /* BackupQueueItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF4EDDA4B02ABF0F17BE86D5 /* BackupQueueItem.swift */; }; 218313D06E536CC541620B1A /* GalleryDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18ADB8B4D428026420CCA46B /* GalleryDetailView.swift */; }; 24B0F2FC039AF5898BF3ADAE /* Date+.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57448AD7D80B10985B8A222B /* Date+.swift */; }; 280D31F6A61529FB13A06EA4 /* SMBClient in Frameworks */ = {isa = PBXBuildFile; productRef = BD0A57EC048DFE706E440152 /* SMBClient */; }; @@ -50,6 +51,7 @@ 8CA733E7E328A54503A06728 /* ConnectionStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 101678CDEDFF343DCC880C2F /* ConnectionStore.swift */; }; 957976696AD0F01A7BA054DE /* BackgroundTaskManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AC6E57C1203C70B43C3A789 /* BackgroundTaskManager.swift */; }; 97E28F8EF7418C7D7A4797B1 /* AppTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = E309F9924060F6C3C2FE36D4 /* AppTheme.swift */; }; + 9B1A3CDC25CC5F058086A08E /* NASManifestCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = E317DD286568B85367A66AD3 /* NASManifestCache.swift */; }; A12ED84B089F39AF5A26F246 /* PhotoLibraryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDB76E9F93340DD33C5572DB /* PhotoLibraryService.swift */; }; A30DD79EAA22C33F029FE4E4 /* LANTriggerSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D7C31A6C73BBF5B8CBDCF2 /* LANTriggerSection.swift */; }; A43FF80A5C7FC09E07294B60 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 628B4A8E8DDB28CDF5AE4284 /* AppDelegate.swift */; }; @@ -60,8 +62,10 @@ C172F81135C5C7EDBED90E98 /* MainTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3306187119851CE3E989408 /* MainTabView.swift */; }; D18F0F1DCFEB945F2AD6DC20 /* ConnectView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C29AB7B029DBC37E189C81D6 /* ConnectView.swift */; }; D2EB2844309ECB331955F2A9 /* SFTPService.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF029B56DE72F2D5D7977D95 /* SFTPService.swift */; }; + D3CEB99B305997997AFEE0D9 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2145CC30FC82AE2E0703EBCE /* NotificationService.swift */; }; D7C3444EF261573E590725E9 /* MockNASService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B1138B91494A6B3BF4515C0 /* MockNASService.swift */; }; D8247C4721601698EB006C86 /* GalleryItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEE62B5210F46415531D531D /* GalleryItem.swift */; }; + D917AA4FEDD50459938E7CD3 /* LocalPhotoIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E0B91084FBA758D1963CB1E /* LocalPhotoIndex.swift */; }; E6E8A98506D79BB36771FA16 /* GalleryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AB509370FEEE38EA8732FDE /* GalleryView.swift */; }; EAD70575AAC91030698676E1 /* KisaniLogoMark.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0987D44494F1385E8D4876F /* KisaniLogoMark.swift */; }; EE8AE9228AC7BA87E0985BDF /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1DAA26CE0A4DFFDD90370F2 /* PrivacyInfo.xcprivacy */; }; @@ -87,6 +91,7 @@ 18ADB8B4D428026420CCA46B /* GalleryDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalleryDetailView.swift; sourceTree = ""; }; 1AB509370FEEE38EA8732FDE /* GalleryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalleryView.swift; sourceTree = ""; }; 1AF29317285580DD2246F54F /* ThumbnailCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThumbnailCache.swift; sourceTree = ""; }; + 2145CC30FC82AE2E0703EBCE /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = ""; }; 22BF6D1FB493F75096805690 /* FolderSetupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderSetupView.swift; sourceTree = ""; }; 248BF8DA762BB74955255511 /* ConnectViewModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectViewModelTests.swift; sourceTree = ""; }; 2B1138B91494A6B3BF4515C0 /* MockNASService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockNASService.swift; sourceTree = ""; }; @@ -103,6 +108,7 @@ 4512EE2A2DE276DB46690E06 /* ButtonStyles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ButtonStyles.swift; sourceTree = ""; }; 57448AD7D80B10985B8A222B /* Date+.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Date+.swift"; sourceTree = ""; }; 5AA5C090CF766ED8E3AF77D1 /* KeychainStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainStore.swift; sourceTree = ""; }; + 5E0B91084FBA758D1963CB1E /* LocalPhotoIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalPhotoIndex.swift; sourceTree = ""; }; 6004FE7B107CC60894EDC434 /* BrowseView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowseView.swift; sourceTree = ""; }; 628B4A8E8DDB28CDF5AE4284 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 63B4A0DF226AB4C5EE9E0D16 /* UGreenCompatibilityBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UGreenCompatibilityBadge.swift; sourceTree = ""; }; @@ -130,10 +136,12 @@ DAF503BCE3AEDC25F4D35083 /* NASConnection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NASConnection.swift; sourceTree = ""; }; DEFC3DC5AA3C7B7258C9155A /* BackupJob.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupJob.swift; sourceTree = ""; }; E309F9924060F6C3C2FE36D4 /* AppTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppTheme.swift; sourceTree = ""; }; + E317DD286568B85367A66AD3 /* NASManifestCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NASManifestCache.swift; sourceTree = ""; }; E956B8562EDB9259034CF8FF /* AppMenuView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppMenuView.swift; sourceTree = ""; }; E987653F4F7129568656EFDE /* BackupResult.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupResult.swift; sourceTree = ""; }; ED5F358675A200A5C0FF2289 /* NASBackup.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = NASBackup.app; sourceTree = BUILT_PRODUCTS_DIR; }; EF029B56DE72F2D5D7977D95 /* SFTPService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SFTPService.swift; sourceTree = ""; }; + EF4EDDA4B02ABF0F17BE86D5 /* BackupQueueItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupQueueItem.swift; sourceTree = ""; }; F052EE8B0A757532E4BCBCCD /* LoginView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginView.swift; sourceTree = ""; }; F0987D44494F1385E8D4876F /* KisaniLogoMark.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KisaniLogoMark.swift; sourceTree = ""; }; F13BE4A26BEF38CE3043CBB5 /* FolderRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderRow.swift; sourceTree = ""; }; @@ -244,6 +252,7 @@ children = ( DEFC3DC5AA3C7B7258C9155A /* BackupJob.swift */, 966927456571CE45600BEF75 /* BackupManifest.swift */, + EF4EDDA4B02ABF0F17BE86D5 /* BackupQueueItem.swift */, E987653F4F7129568656EFDE /* BackupResult.swift */, 2EDEAE39E0AFC06D0C169589 /* BackupStatusSnapshot.swift */, CEE62B5210F46415531D531D /* GalleryItem.swift */, @@ -260,6 +269,9 @@ 75FEBDDA82656772FE30609D /* BackupEngine.swift */, FC516E4CBDFA09B6D04937D6 /* BackupStatusService.swift */, D008AD85FA9B690DAFECCC34 /* LANMonitor.swift */, + 5E0B91084FBA758D1963CB1E /* LocalPhotoIndex.swift */, + E317DD286568B85367A66AD3 /* NASManifestCache.swift */, + 2145CC30FC82AE2E0703EBCE /* NotificationService.swift */, FDB76E9F93340DD33C5572DB /* PhotoLibraryService.swift */, EF029B56DE72F2D5D7977D95 /* SFTPService.swift */, 3E4F11D9683F64A06B855649 /* SMBService.swift */, @@ -509,6 +521,7 @@ 67149DE0D19696D9327AEBAB /* BackupError.swift in Sources */, 42BF90A0F061C3183D5FD5D4 /* BackupJob.swift in Sources */, 0E446A91CD30C2905B8E215F /* BackupManifest.swift in Sources */, + 210BF39897CC8E966A72698C /* BackupQueueItem.swift in Sources */, 48A1C445346B6E84BB4955D3 /* BackupResult.swift in Sources */, 3C588AE6212D742D71A67A4C /* BackupStatusService.swift in Sources */, 405026F5EC0DD0D4CC636F0F /* BackupStatusSnapshot.swift in Sources */, @@ -531,12 +544,15 @@ EAD70575AAC91030698676E1 /* KisaniLogoMark.swift in Sources */, 42CB7416A94CFEBC290D0E49 /* LANMonitor.swift in Sources */, A30DD79EAA22C33F029FE4E4 /* LANTriggerSection.swift in Sources */, + D917AA4FEDD50459938E7CD3 /* LocalPhotoIndex.swift in Sources */, 0E4948C8E3326DF859341942 /* LoginView.swift in Sources */, F5ED0D561D6F61180B4672FA /* LoginViewModel.swift in Sources */, C172F81135C5C7EDBED90E98 /* MainTabView.swift in Sources */, 6A0D1B9133CBA5CBE403AB6A /* NASBackupApp.swift in Sources */, 01610BD782FA7F00787E8CB5 /* NASConnection.swift in Sources */, + 9B1A3CDC25CC5F058086A08E /* NASManifestCache.swift in Sources */, 6D7C0DABECF5694E95B1F2F9 /* NASTransferProtocol.swift in Sources */, + D3CEB99B305997997AFEE0D9 /* NotificationService.swift in Sources */, 1157E530A5E3EC4563D20C32 /* PHAsset+.swift in Sources */, 0555485F0FD9D1D724B98B0D /* PhotoLibraryProtocol.swift in Sources */, A12ED84B089F39AF5A26F246 /* PhotoLibraryService.swift in Sources */, diff --git a/Services/AutoBackupCoordinator.swift b/Services/AutoBackupCoordinator.swift index 3244d76..dfa1614 100644 --- a/Services/AutoBackupCoordinator.swift +++ b/Services/AutoBackupCoordinator.swift @@ -71,9 +71,12 @@ final class AutoBackupCoordinator: ObservableObject { func onActive() { guard !engine.job.status.isActive else { return } guard store.savedConnection != nil else { return } + guard phase == .idle else { return } // Don't interrupt an in-progress check phase = .checking - statusService.refresh(force: true) - // handleReconciliationComplete() fires via Combine when the refresh settles + // force: false — BackupStatusService's 30-second debounce prevents expensive + // rescans on rapid foreground/background cycles. The cached snapshot is shown + // immediately; reconciliation only runs when truly stale. + statusService.refresh(force: false) } // MARK: — Combine handlers diff --git a/Services/BackupEngine.swift b/Services/BackupEngine.swift index 87b6725..876cfd8 100644 --- a/Services/BackupEngine.swift +++ b/Services/BackupEngine.swift @@ -1,5 +1,4 @@ import Foundation -import UserNotifications import Photos import os.log @@ -11,12 +10,18 @@ final class BackupEngine: ObservableObject { static let shared = BackupEngine() @Published private(set) var job: BackupJob = BackupJob() + @Published private(set) var queueItems: [BackupQueueItem] = [] private let photoService: PhotoLibraryProtocol private let transferFactory: (NASProtocol) -> any NASTransferProtocol private var activeTransfer: (any NASTransferProtocol)? private var isCancelled = false + private static let queueCacheURL: URL = { + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + return caches.appendingPathComponent("kisani_last_queue.json") + }() + private init( photos: PhotoLibraryProtocol = PhotoLibraryService(), transferFactory: @escaping (NASProtocol) -> any NASTransferProtocol = { proto in @@ -28,6 +33,11 @@ final class BackupEngine: ObservableObject { ) { self.photoService = photos self.transferFactory = transferFactory + // Load last session's queue so SyncView has data to show on next launch. + if let data = try? Data(contentsOf: Self.queueCacheURL), + let items = try? JSONDecoder.kisani.decode([BackupQueueItem].self, from: data) { + self.queueItems = items + } } static func testInstance( @@ -121,10 +131,19 @@ final class BackupEngine: ObservableObject { } // ── 5. Upload loop ───────────────────────────────────────────────── - // The main actor is released at every `await`. Progress UI is throttled - // to 8 Hz — without throttling, one Task { @MainActor } is fired per - // progress callback which causes continuous SwiftUI full-tree re-renders. job.start(totalFiles: pendingAssets.count, totalBytes: 0) + NotificationService.notifyBackupStarted(count: pendingAssets.count) + + // Build initial queue (all queued) for SyncView + queueItems = pendingAssets.map { asset in + BackupQueueItem( + id: asset.localIdentifier, + filename: asset.filename, + nasPath: "\(connection.remotePath)/\(asset.filename)", + status: .queued, bytesUploaded: 0, totalBytes: 0, speedBytesPerSec: 0, + error: nil, retryCount: 0, queuedAt: Date(), completedAt: nil + ) + } var uploaded = 0 var skipped = 0 @@ -137,7 +156,7 @@ final class BackupEngine: ObservableObject { let spUpload = signposter.beginInterval("UploadLoop", "\(pendingAssets.count) files") - for asset in pendingAssets { + for (assetIdx, asset) in pendingAssets.enumerated() { if isCancelled { break } while case .paused = job.status { try await Task.sleep(nanoseconds: 500_000_000) @@ -145,9 +164,18 @@ final class BackupEngine: ObservableObject { let remotePath = "\(connection.remotePath)/\(asset.filename)" + // Mark as uploading + if assetIdx < queueItems.count { + queueItems[assetIdx].status = .uploading + } + if (try? await transfer.fileExists(at: remotePath)) == true { job.fileCompleted(skipped: true) skipped += 1 + if assetIdx < queueItems.count { + queueItems[assetIdx].status = .skipped + queueItems[assetIdx].completedAt = Date() + } logger.debug("Skipped (NAS exists): \(asset.filename, privacy: .public)") continue } @@ -160,20 +188,28 @@ final class BackupEngine: ObservableObject { let fileSize = (try? localURL.resourceValues(forKeys: [.fileSizeKey]).fileSize) .flatMap { Int64($0) } ?? 0 - // Capture totalBytes by value so the progress closure doesn't capture - // the mutable var — avoids a data race warning and is semantically correct. let bytesSoFar = totalBytes + let capturedIdx = assetIdx + + if capturedIdx < queueItems.count { + queueItems[capturedIdx].totalBytes = fileSize + } try await transfer.upload(localURL: localURL, remotePath: remotePath) { sent, _ in let speed = speedTracker.update(bytesSent: sent) guard throttle.shouldUpdate() else { return } Task { @MainActor [weak self] in - self?.job.updateProgress( + guard let self else { return } + self.job.updateProgress( fileName: asset.filename, fileSize: fileSize, bytesTransferred: bytesSoFar + sent, speed: speed ) + if capturedIdx < self.queueItems.count { + self.queueItems[capturedIdx].bytesUploaded = sent + self.queueItems[capturedIdx].speedBytesPerSec = speed + } } } @@ -182,6 +218,12 @@ final class BackupEngine: ObservableObject { job.fileCompleted(skipped: false) uploaded += 1 + if assetIdx < queueItems.count { + queueItems[assetIdx].status = .uploaded + queueItems[assetIdx].bytesUploaded = fileSize + queueItems[assetIdx].completedAt = Date() + } + manifestEntries.append(ManifestEntry( localIdentifier: asset.localIdentifier, filename: asset.filename, @@ -194,6 +236,15 @@ final class BackupEngine: ObservableObject { logger.error("Upload failed for \(asset.filename, privacy: .public): \(error.localizedDescription, privacy: .public)") job.fileFailed() failed += 1 + if assetIdx < queueItems.count { + queueItems[assetIdx].status = .failed + queueItems[assetIdx].completedAt = Date() + queueItems[assetIdx].error = BackupQueueItem.UploadError( + code: (error as NSError).domain, + message: error.localizedDescription, + timestamp: Date() + ) + } } } @@ -214,7 +265,23 @@ final class BackupEngine: ObservableObject { let entry = BackupHistoryEntry(result: result, nasHost: host, triggeredByLAN: triggeredByLAN) store.appendHistoryEntry(entry) - await sendCompletionNotification(result: result) + + // Notifications + if result.failedCount > 0 { + NotificationService.notifyBackupFailed(count: result.failedCount) + } else { + NotificationService.notifyBackupCompleted( + uploaded: result.uploadedCount, + total: BackupStatusService.shared.snapshot.phoneTotal + ) + } + + // Persist queue so SyncView shows last session on next launch + let snapshot = queueItems + Task.detached(priority: .utility) { [snapshot, url = Self.queueCacheURL] in + guard let data = try? JSONEncoder.kisani.encode(snapshot) else { return } + try? data.write(to: url, options: .atomic) + } return result } @@ -235,14 +302,6 @@ final class BackupEngine: ObservableObject { func resolveSuccess() { job.resolveSuccess() } - private func sendCompletionNotification(result: BackupResult) async { - let content = UNMutableNotificationContent() - content.title = result.hasErrors ? "Backup completed with errors" : "Backup complete" - content.body = "\(result.uploadedCount) uploaded · \(result.skippedCount) skipped · \(result.failedCount) errors" - content.sound = .default - let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil) - try? await UNUserNotificationCenter.current().add(request) - } } // MARK: — SpeedTracker diff --git a/Services/BackupStatusService.swift b/Services/BackupStatusService.swift index 3b5fb2f..e431d45 100644 --- a/Services/BackupStatusService.swift +++ b/Services/BackupStatusService.swift @@ -129,9 +129,35 @@ final class BackupStatusService: NSObject, ObservableObject { let store = ConnectionStore.shared guard let conn = store.savedConnection else { return } - // ── Step 1: Phone count ─────────────────────────────────────────── - // PHFetchResult.count is O(1) after the initial index build — fast on main actor. let filter = store.backupFilter + + // ── 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 + + if !manifestCacheIsStale, let cached = await NASManifestCache.shared.manifest, localIndexCount > 0 { + let index = await Task.detached(priority: .utility) { + ManifestIndex(manifest: cached) + }.value + let safe = await LocalPhotoIndex.shared.countSafe(against: index, filter: filter) + let phoneTotal = await LocalPhotoIndex.shared.totalCount + var updated = BackupStatusSnapshot() + updated.phoneTotal = phoneTotal + updated.alreadySafe = min(safe, phoneTotal) + updated.nasArchiveTotal = index.totalCount + updated.connectionState = .connected + updated.lastCheckedAt = Date() + snapshot = updated + saveSnapshot() + log.info("Reconcile (cached): \(phoneTotal) phone, \(safe) safe, \(index.totalCount) NAS") + 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)") @@ -159,27 +185,29 @@ final class BackupStatusService: NSObject, ObservableObject { try Task.checkCancellation() // ── Step 3: Load ManifestIndex ──────────────────────────────────── - // Download suspends main actor (good). JSON decode + Set construction - // is CPU-bound O(N) — runs in a background task so touch/animation remain smooth. let spManifest = signposter.beginInterval("ManifestLoad") 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)") - log.info("Manifest index built — \(index.totalCount) NAS entries, filename-only=\(index.isFilenameOnly)") + log.info("Manifest index built — \(index.totalCount) NAS entries") try Task.checkCancellation() - // ── Step 4: Count safe assets — off main actor ──────────────────── - // Batch enumeration of PHFetchResult is CPU-bound (up to N/150 batches). - // Running it in a detached task keeps the main thread free for the UI - // while the count is in progress. Task.yield() inside countSafe lets other - // async work interleave between batches. + // ── 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") - let 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 + 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") @@ -212,6 +240,8 @@ final class BackupStatusService: NSObject, ObservableObject { }.value if let (index, manifest) = decoded { lastManifest = manifest + // Persist to local cache so future launches skip the NAS round-trip. + Task { await NASManifestCache.shared.update(manifest) } return index } } catch { @@ -346,6 +376,20 @@ final class BackupStatusService: NSObject, ObservableObject { extension BackupStatusService: PHPhotoLibraryChangeObserver { nonisolated func photoLibraryDidChange(_ changeInstance: PHChange) { + // 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() + } + } Task { @MainActor [weak self] in guard let self else { return } self.debounceTask?.cancel() diff --git a/Services/LocalPhotoIndex.swift b/Services/LocalPhotoIndex.swift new file mode 100644 index 0000000..d79aa3f --- /dev/null +++ b/Services/LocalPhotoIndex.swift @@ -0,0 +1,163 @@ +import Foundation +import Photos +import os.log + +private let log = Logger(subsystem: "com.albert.nasbackup", category: "LocalPhotoIndex") + +/// On-device index of phone asset metadata — eliminates full PHFetchResult +/// enumeration for status counts after the initial build. +/// +/// Build cost: O(N) on first launch, then zero on every subsequent open. +/// Update cost: O(changed) via PHPhotoLibraryChangeObserver. +/// Memory: ~100 bytes × asset count (≈1 MB for 10 k photos). +actor LocalPhotoIndex { + static let shared = LocalPhotoIndex() + + struct Record: Codable, Sendable { + let localIdentifier: String + var filename: String + var creationDate: Date? + var mediaType: Int // PHAssetMediaType.rawValue + var isScreenshot: Bool + var isRAW: Bool + } + + private var records: [String: Record] = [:] + private let diskURL: URL + private var needsSave = false + + private init() { + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + diskURL = caches.appendingPathComponent("kisani_local_index.json") + } + + // MARK: — Lifecycle + + /// Load from disk if available; otherwise build from PHFetchResult in background. + /// Safe to call multiple times — subsequent calls are no-ops if records are loaded. + func loadOrBuild() async { + guard records.isEmpty else { return } + if let loaded = await Self.loadFromDisk(url: diskURL) { + records = loaded + log.info("LocalPhotoIndex: loaded \(self.records.count) records from disk") + return + } + log.info("LocalPhotoIndex: building from scratch (first launch)") + await buildFromLibrary() + } + + // MARK: — Queries + + var totalCount: Int { records.count } + + func allRecords() -> [Record] { Array(records.values) } + + func countSafe(against index: ManifestIndex, filter: BackupFilter) -> Int { + var safe = 0 + for record in records.values { + guard passes(record, filter: filter) else { continue } + if index.matches(localIdentifier: record.localIdentifier) { + safe += 1 + } else if index.isFilenameOnly && index.matches(filename: record.filename) { + safe += 1 + } + } + return safe + } + + /// Returns localIdentifiers for assets not yet in the manifest (pending upload). + func pendingIDs(against index: ManifestIndex, filter: BackupFilter) -> [String] { + records.values.compactMap { record in + guard passes(record, filter: filter) else { return nil } + let alreadyBacked = + index.matches(localIdentifier: record.localIdentifier) || + (index.isFilenameOnly && index.matches(filename: record.filename)) + return alreadyBacked ? nil : record.localIdentifier + } + } + + // MARK: — Incremental updates (from PHPhotoLibraryChangeObserver) + + func apply(inserted: [PHAsset], removed: [PHAsset], changed: [PHAsset]) { + for asset in removed { records.removeValue(forKey: asset.localIdentifier) } + for asset in inserted + changed { + records[asset.localIdentifier] = Self.makeRecord(asset) + } + needsSave = true + log.debug("LocalPhotoIndex: +\(inserted.count) -\(removed.count) ~\(changed.count)") + } + + func flush() async { + guard needsSave else { return } + needsSave = false + let snapshot = records + let url = diskURL + await Task.detached(priority: .utility) { + guard let data = try? JSONEncoder.kisani.encode(snapshot) else { return } + try? data.write(to: url, options: .atomic) + }.value + log.debug("LocalPhotoIndex: flushed \(snapshot.count) records") + } + + // MARK: — Private helpers + + private func passes(_ record: Record, filter: BackupFilter) -> Bool { + let img = PHAssetMediaType.image.rawValue + let vid = PHAssetMediaType.video.rawValue + if !filter.includePhotos && record.mediaType == img { return false } + if !filter.includeVideos && record.mediaType == vid { return false } + if !filter.includeScreenshots && record.isScreenshot { return false } + if !filter.includeRAW && record.isRAW { return false } + return true + } + + private func buildFromLibrary() async { + let opts = PHFetchOptions() + opts.includeAssetSourceTypes = [.typeUserLibrary, .typeCloudShared, .typeiTunesSynced] + let built: [String: Record] = await Task.detached(priority: .userInitiated) { + let result = PHAsset.fetchAssets(with: opts) + var map = [String: Record](minimumCapacity: result.count) + let batchSize = 200 + var i = 0 + while i < result.count { + autoreleasepool { + let end = min(i + batchSize, result.count) + for j in i.. [String: Record]? { + await Task.detached(priority: .utility) { + guard let data = try? Data(contentsOf: url) else { return nil } + return try? JSONDecoder.kisani.decode([String: Record].self, from: data) + }.value + } + + nonisolated static func makeRecord(_ asset: PHAsset) -> Record { + let resources = PHAssetResource.assetResources(for: asset) + let filename = resources.first?.originalFilename + ?? "\(asset.localIdentifier.prefix(8)).jpg" + let isRAW = resources.contains { $0.type == .alternatePhoto } + let isScreenshot = asset.mediaSubtypes.contains(.photoScreenshot) + return Record( + localIdentifier: asset.localIdentifier, + filename: filename, + creationDate: asset.creationDate, + mediaType: asset.mediaType.rawValue, + isScreenshot: isScreenshot, + isRAW: isRAW + ) + } +} diff --git a/Services/NASManifestCache.swift b/Services/NASManifestCache.swift new file mode 100644 index 0000000..96542f6 --- /dev/null +++ b/Services/NASManifestCache.swift @@ -0,0 +1,72 @@ +import Foundation +import os.log + +private let log = Logger(subsystem: "com.albert.nasbackup", category: "ManifestCache") + +/// Persists a copy of the NAS backup manifest on-device so reconciliation can +/// skip the NAS network round-trip when the cache is still fresh. +/// +/// Cache is updated after every successful manifest download and after every +/// completed backup. Stale threshold = 5 minutes. The actor serialises all +/// reads and writes so the cache is safe to use across tasks and threads. +actor NASManifestCache { + static let shared = NASManifestCache() + + private var cached: CachedEntry? + private let diskURL: URL + private static let staleInterval: TimeInterval = 5 * 60 + + private struct CachedEntry: Codable { + var manifest: BackupManifest + var savedAt: Date + } + + private init() { + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + diskURL = caches.appendingPathComponent("kisani_manifest_cache.json") + // Load from disk immediately so the first `manifest` access is instant. + if let data = try? Data(contentsOf: diskURL), + let entry = try? JSONDecoder.kisani.decode(CachedEntry.self, from: data) { + cached = entry + log.info("ManifestCache: loaded \(entry.manifest.entries.count) entries from disk") + } + } + + /// Returns the cached manifest without any I/O. Never nil after first reconcile. + var manifest: BackupManifest? { cached?.manifest } + + /// True when the cache is absent or older than the stale threshold. + var isStale: Bool { + guard let c = cached else { return true } + return Date().timeIntervalSince(c.savedAt) > NASManifestCache.staleInterval + } + + /// Persist a freshly-downloaded manifest. Call after every successful NAS download. + func update(_ manifest: BackupManifest) { + let entry = CachedEntry(manifest: manifest, savedAt: Date()) + cached = entry + log.info("ManifestCache: updated — \(manifest.entries.count) entries") + Task.detached(priority: .utility) { [entry, url = diskURL] in + guard let data = try? JSONEncoder.kisani.encode(entry) else { return } + try? data.write(to: url, options: .atomic) + } + } +} + +// MARK: — Shared encoder/decoder + +extension JSONEncoder { + static let kisani: JSONEncoder = { + let e = JSONEncoder() + e.dateEncodingStrategy = .iso8601 + return e + }() +} + +extension JSONDecoder { + static let kisani: JSONDecoder = { + let d = JSONDecoder() + d.dateDecodingStrategy = .iso8601 + return d + }() +} diff --git a/Services/NotificationService.swift b/Services/NotificationService.swift new file mode 100644 index 0000000..5519e6a --- /dev/null +++ b/Services/NotificationService.swift @@ -0,0 +1,65 @@ +import UserNotifications +import Foundation + +/// Centralised local-notification sender. +/// +/// Uses notification identifiers as categories — posting the same id replaces +/// any previous notification in that category, preventing stale banners from +/// stacking up. +enum NotificationService { + static func notifyBackupStarted(count: Int) { + guard count > 0 else { return } + post( + id: "kisani.backup.started", + title: "Backup started", + body: "Kisani is backing up \(count) new \(count == 1 ? "item" : "items")." + ) + } + + static func notifyBackupCompleted(uploaded: Int, total: Int) { + post( + id: "kisani.backup.completed", + title: "Backup complete", + body: total > 0 + ? "All \(total) photos are safe." + : "\(uploaded) \(uploaded == 1 ? "item" : "items") backed up." + ) + } + + static func notifyBackupPaused(pendingCount: Int) { + post( + id: "kisani.backup.paused", + title: "Backup paused", + body: pendingCount > 0 + ? "Kisani will continue \(pendingCount) \(pendingCount == 1 ? "item" : "items") when your NAS is reachable." + : "Kisani will continue when your NAS is reachable." + ) + } + + static func notifyBackupFailed(count: Int) { + post( + id: "kisani.backup.failed", + title: "Backup failed", + body: "\(count) \(count == 1 ? "item" : "items") could not be backed up. Tap to review." + ) + } + + static func notifyNASOffline() { + post( + id: "kisani.nas.offline", + title: "NAS unreachable", + body: "Kisani will resume backup when your NAS is back online." + ) + } + + // MARK: — Private + + private static func post(id: String, title: String, body: String) { + let content = UNMutableNotificationContent() + content.title = title + content.body = body + content.sound = .default + let request = UNNotificationRequest(identifier: id, content: content, trigger: nil) + UNUserNotificationCenter.current().add(request) { _ in } + } +}