Repository Public
1// SP Drive iOS2// File: Sync/ChangeDetector.swift3// Description: What a change coming from the server means for the copies held on this device. Content is compared by hash and version,4// never by date; a copy holding unsent edits is never replaced or removed.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension SyncEngine {11 func remoteChanged(old: DriveItem?, new: DriveItem) {12 if new.isFolder {13 // a folder restored or moved under a pinned folder brings its files along14 if !new.isTrashed, old.map({ $0.isTrashed || $0.parentID != new.parentID }) ?? false, isEffectivelyPinned(new.id) {15 for f in store.descendants(of: new.id, filesOnly: true) { enqueueDownload(f, priority: .pin) }16 }17 return18 }19 let ls = store.localState(new.id)20 if new.isTrashed {21 guard let ls, ls.hasCopy else { return }22 if ls.dirty { flagRemoteDeletion(new) } else { dropCopy(new.id, ls) }23 return24 }25 let pinned = isEffectivelyPinned(new.id)26 guard let ls, ls.hasCopy else {27 if pinned { enqueueDownload(new, priority: .pin) }28 return29 }30 if ls.baseSHA == new.sha256 {31 // same content: only make sure the version the copy is based on is known32 if ls.baseVersionID != new.versionID, !ls.dirty { var l = ls; l.baseVersionID = new.versionID; try? store.saveLocalState(l) }33 return34 }35 if ls.dirty { return } // edited here and changed there: the pending upload will be refused and raise the conflict36 if pinned { enqueueDownload(new, priority: .pin) } else { dropCopy(new.id, ls) } // a stale cached copy is not kept37 }3839 func remoteDeleted(_ item: DriveItem) {40 guard !item.isFolder, let ls = store.localState(item.id) else { return }41 if ls.dirty, ls.hasCopy {42 // keep the item visible (in the device's records only) until the user decides what to do with the edits43 var ghost = item44 ghost.trashedAt = ghost.trashedAt ?? .now45 ghost.pending = true46 try? store.upsert(ghost)47 flagRemoteDeletion(ghost)48 } else {49 if let t = store.activeTransfer(itemID: item.id, kind: .download) { Task { await self.cancel(t.id) } }50 if let loc = ls.location { files.removeCopy(itemID: item.id, location: loc) }51 try? store.deleteLocalState(item.id)52 }53 }5455 func dropCopy(_ id: String, _ ls: LocalState) {56 var ls = ls57 if let loc = ls.location { files.removeCopy(itemID: id, location: loc) }58 ls.location = nil; ls.fileName = nil; ls.baseSHA = nil; ls.baseVersionID = nil; ls.localSize = 0; ls.downloadedAt = nil59 if ls.pinned { try? store.saveLocalState(ls) } else { try? store.deleteLocalState(id) }60 }6162 func flagRemoteDeletion(_ item: DriveItem) {63 guard store.conflict(itemID: item.id) == nil else { return }64 try? store.addConflict(itemID: item.id, name: item.name, reason: .remoteDeleted, uploadID: nil)65 emit(.conflictsChanged)66 emit(.conflictDetected(name: item.name))67 }68}69