BackupJob: fix finish() — failedCount > 0 now correctly sets .failed instead of .completed in both branches. BackupEngine: replace filename-only fileExists check with a 3-layer dedup strategy. For each asset: (1) check ManifestIndex by localIdentifier O(1); (2) filename fallback for bootstrap manifests; (3) NAS fileExists for files not yet in manifest. Never overwrite an existing NAS file. Manifest index is built once after connect and held in a local let for the loop — Data+BackupManifest are released immediately after. BackupView — ring color: active (running/preparing/paused) → orange always failed → destructive needBackup == 0 && phoneTotal > 0 → green default → neutral gray Ring is no longer permanently green after .completed. BackupView — CTA button: Default color is always black (AppTheme.ink). On .completed: briefly flashes green for 2.5 s then smoothly reverts to black. ctaFlashGreen state drives the color. BackupView — Already Safe invariant: alreadySafeDisplayCount = min(base + uploadedFiles, phoneTotal) during active backup; min(base, phoneTotal) otherwise. Adding skippedFiles was removed — they are already counted in snapshot.alreadySafe from the last reconcile. notBackedUpDisplayCount is derived from alreadySafeDisplayCount to keep the invariant alreadySafe + needBackup == phoneTotal. Co-Authored-By: Kutesir <kutesir@provoc.ug> Co-Authored-By: Sentry <sentry@provoc.ug>
238 lines
8.7 KiB
Swift
238 lines
8.7 KiB
Swift
import Foundation
|
|
import UserNotifications
|
|
import os.log
|
|
|
|
private let logger = Logger(subsystem: "com.albert.nasbackup", category: "BackupEngine")
|
|
|
|
@MainActor
|
|
final class BackupEngine: ObservableObject {
|
|
static let shared = BackupEngine()
|
|
|
|
@Published private(set) var job: BackupJob = BackupJob()
|
|
|
|
private let photoService: PhotoLibraryProtocol
|
|
private let transferFactory: (NASProtocol) -> any NASTransferProtocol
|
|
private var activeTransfer: (any NASTransferProtocol)?
|
|
private var isCancelled = false
|
|
|
|
private init(
|
|
photos: PhotoLibraryProtocol = PhotoLibraryService(),
|
|
transferFactory: @escaping (NASProtocol) -> any NASTransferProtocol = { proto in
|
|
switch proto {
|
|
case .smb: return SMBService()
|
|
case .sftp: return SFTPService()
|
|
}
|
|
}
|
|
) {
|
|
self.photoService = photos
|
|
self.transferFactory = transferFactory
|
|
}
|
|
|
|
static func testInstance(
|
|
transfer: any NASTransferProtocol,
|
|
photos: PhotoLibraryProtocol
|
|
) -> BackupEngine {
|
|
BackupEngine(photos: photos, transferFactory: { _ in transfer })
|
|
}
|
|
|
|
func run(
|
|
connection: NASConnection,
|
|
filter: BackupFilter,
|
|
triggeredByLAN: Bool = false
|
|
) async throws -> BackupResult {
|
|
isCancelled = false
|
|
let startDate = Date()
|
|
let store = ConnectionStore.shared
|
|
let lan = LANMonitor.shared
|
|
|
|
// Gate: block cellular unless user opted in (never block on LAN trigger)
|
|
if !triggeredByLAN && lan.isOnCellular && !store.allowCellularBackup {
|
|
throw BackupError.networkUnavailable
|
|
}
|
|
|
|
// Resolve effective host: use Tailscale when remote and tunnel is active
|
|
let host = resolveHost(connection: connection, store: store, lan: lan)
|
|
|
|
// 1. Fetch assets
|
|
job.prepare()
|
|
let assets = photoService.fetchAssets(filter: filter)
|
|
|
|
// 2. Connect to NAS
|
|
let transfer = transferFactory(connection.nasProtocol)
|
|
|
|
try await transfer.connect(
|
|
to: host,
|
|
port: connection.port,
|
|
username: connection.username,
|
|
password: connection.password
|
|
)
|
|
activeTransfer = transfer
|
|
|
|
defer {
|
|
transfer.disconnect()
|
|
activeTransfer = nil
|
|
}
|
|
|
|
// 3. Load manifest → build index (manifest Data+struct released after this block)
|
|
let manifestPath = "\(connection.remotePath)/\(BackupManifest.remoteFilename)"
|
|
let index: ManifestIndex
|
|
if let data = try? await transfer.downloadData(at: manifestPath),
|
|
let manifest = try? JSONDecoder().decode(BackupManifest.self, from: data) {
|
|
index = ManifestIndex(manifest: manifest)
|
|
logger.info("Manifest loaded — \(index.totalCount) entries, filename-only=\(index.isFilenameOnly)")
|
|
} else {
|
|
index = ManifestIndex(nasListing: [])
|
|
logger.info("No manifest — will check NAS file existence per asset")
|
|
}
|
|
|
|
// 4. Start job tracking
|
|
job.start(totalFiles: assets.count, totalBytes: 0)
|
|
|
|
var uploaded = 0
|
|
var skipped = 0
|
|
var failed = 0
|
|
var totalBytes: Int64 = 0
|
|
var speedTracker = SpeedTracker()
|
|
var manifestEntries: [ManifestEntry] = []
|
|
|
|
// 5. Transfer loop
|
|
for asset in assets {
|
|
if isCancelled { break }
|
|
while case .paused = job.status {
|
|
try await Task.sleep(nanoseconds: 500_000_000)
|
|
}
|
|
|
|
// ── Primary dedup: manifest localIdentifier (O(1), no network call) ──
|
|
if index.matches(localIdentifier: asset.localIdentifier) {
|
|
job.fileCompleted(skipped: true)
|
|
skipped += 1
|
|
logger.debug("Skipped (manifest id): \(asset.filename, privacy: .public)")
|
|
continue
|
|
}
|
|
|
|
// ── Filename fallback: bootstrap manifest has no localIdentifiers ──
|
|
if index.isFilenameOnly && index.matches(filename: asset.filename) {
|
|
job.fileCompleted(skipped: true)
|
|
skipped += 1
|
|
logger.debug("Skipped (manifest filename): \(asset.filename, privacy: .public)")
|
|
continue
|
|
}
|
|
|
|
// ── NAS file existence check — never overwrite ──
|
|
let baseRemotePath = "\(connection.remotePath)/\(asset.filename)"
|
|
let fileAlreadyExists = (try? await transfer.fileExists(at: baseRemotePath)) == true
|
|
if fileAlreadyExists {
|
|
job.fileCompleted(skipped: true)
|
|
skipped += 1
|
|
logger.debug("Skipped (NAS exists, no-overwrite): \(asset.filename, privacy: .public)")
|
|
continue
|
|
}
|
|
|
|
// ── Upload ──
|
|
do {
|
|
let localURL = try await photoService.exportAsset(asset)
|
|
defer { try? FileManager.default.removeItem(at: localURL) }
|
|
|
|
let fileSize = (try? localURL.resourceValues(forKeys: [.fileSizeKey]).fileSize)
|
|
.flatMap { Int64($0) } ?? 0
|
|
|
|
try await transfer.upload(localURL: localURL, remotePath: baseRemotePath) { sent, total in
|
|
let speed = speedTracker.update(bytesSent: sent)
|
|
Task { @MainActor [weak self] in
|
|
self?.job.updateProgress(
|
|
fileName: asset.filename,
|
|
fileSize: total,
|
|
bytesTransferred: totalBytes + sent,
|
|
speed: speed
|
|
)
|
|
}
|
|
}
|
|
|
|
totalBytes += fileSize
|
|
job.fileCompleted(skipped: false)
|
|
uploaded += 1
|
|
|
|
manifestEntries.append(ManifestEntry(
|
|
localIdentifier: asset.localIdentifier,
|
|
filename: asset.filename,
|
|
creationDate: asset.creationDate,
|
|
fileSize: fileSize,
|
|
remotePath: baseRemotePath,
|
|
uploadedAt: Date()
|
|
))
|
|
} catch {
|
|
logger.error("Upload failed for \(asset.filename, privacy: .public): \(error.localizedDescription, privacy: .public)")
|
|
job.fileFailed()
|
|
failed += 1
|
|
}
|
|
}
|
|
|
|
let duration = Date().timeIntervalSince(startDate)
|
|
let result = BackupResult(
|
|
uploadedCount: uploaded,
|
|
skippedCount: skipped,
|
|
failedCount: failed,
|
|
duration: duration,
|
|
totalBytes: totalBytes,
|
|
date: startDate
|
|
)
|
|
|
|
job.finish(result: result)
|
|
|
|
// Update manifest and dashboard status
|
|
BackupStatusService.shared.refreshAfterBackup(entries: manifestEntries, connection: connection)
|
|
|
|
let entry = BackupHistoryEntry(result: result, nasHost: host, triggeredByLAN: triggeredByLAN)
|
|
store.appendHistoryEntry(entry)
|
|
|
|
await sendCompletionNotification(result: result)
|
|
|
|
return result
|
|
}
|
|
|
|
// Returns the Tailscale host when outside the trusted network and tunnel is up,
|
|
// otherwise falls back to the saved local host.
|
|
private func resolveHost(connection: NASConnection, store: ConnectionStore, lan: LANMonitor) -> String {
|
|
let onTrustedLAN = store.trustedSSIDs.contains(lan.currentSSID ?? "")
|
|
guard !onTrustedLAN,
|
|
store.useTailscaleWhenRemote,
|
|
!store.tailscaleHost.isEmpty,
|
|
lan.isTailscaleActive else {
|
|
return connection.host
|
|
}
|
|
return store.tailscaleHost
|
|
}
|
|
|
|
func cancel() {
|
|
isCancelled = true
|
|
job.cancel()
|
|
}
|
|
|
|
func pause() { job.pause() }
|
|
func resume() { job.resume() }
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
private struct SpeedTracker {
|
|
private var lastBytes: Int64 = 0
|
|
private var lastTime: Date = Date()
|
|
|
|
mutating func update(bytesSent: Int64) -> Double {
|
|
let now = Date()
|
|
let elapsed = now.timeIntervalSince(lastTime)
|
|
guard elapsed > 0.1 else { return 0 }
|
|
let speed = Double(bytesSent - lastBytes) / elapsed
|
|
lastBytes = bytesSent
|
|
lastTime = now
|
|
return max(0, speed)
|
|
}
|
|
}
|