SPB Git

Repository Public

ConflictResolver.swift 7.4 KB 141 lines swift

1// SP Drive iOS2// File: Sync/ConflictResolver.swift3// Description: Resolution of conflicts, always by an explicit choice of the user. Whatever is chosen, no version is destroyed silently:4//              the server keeps its history, and « keep both » stores the device's content as a separate file.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public enum ConflictChoice: Sendable {11    /// Store this device's content as a separate file next to the original, and take the server's version of the original.12    case keepBoth13    /// Make this device's content the new current version (the server's version stays in the file's history).14    case keepMine15    /// Give up the edits made on this device and take the server's version.16    case keepServer17}1819/// The two versions of a file in conflict, for the screen where the user chooses.20public struct ConflictSides: Sendable, Equatable {21    public struct Local: Sendable, Equatable {22        public var url: URL23        public var size: Int6424        public var modifiedAt: Date?25        /// The version of the Drive this edit started from.26        public var baseVersionID: String?27    }28    public struct Server: Sendable, Equatable {29        public var item: DriveItem30        public var size: Int64 { item.size }31        public var modifiedAt: Date { item.updatedAt }32        public var versionSeq: Int { item.versionSeq }33    }34    public var conflict: ConflictRecord35    public var local: Local?36    /// nil when the file no longer exists on the Drive (or the server cannot be reached: see `serverReachable`).37    public var server: Server?38    public var serverReachable: Bool39}4041extension SyncEngine {42    public nonisolated func conflicts() -> [ConflictRecord] { store.conflicts() }4344    /// Describes both sides of a conflict: this device's edited copy (from the file system) and the Drive's current version (asked from the45    /// server; from the mirror when it cannot be reached).46    public func conflictSides(_ conflictID: Int64) async -> ConflictSides? {47        guard let c = store.conflicts().first(where: { $0.id == conflictID }) else { return nil }48        var sides = ConflictSides(conflict: c, local: nil, server: nil, serverReachable: true)49        if let ls = store.localState(c.itemID), let url = files.url(for: ls), FileManager.default.fileExists(atPath: url.path) {50            let modified = (try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]) as? Date51            sides.local = .init(url: url, size: IntegrityVerifier.size(of: url), modifiedAt: modified, baseVersionID: ls.baseVersionID)52        }53        do {54            let fresh = try await remote.item(id: c.itemID, isFolder: false)55            if !fresh.isTrashed { sides.server = .init(item: fresh) }56        } catch RemoteError.notFound {57        } catch {58            sides.serverReachable = false59            if c.reason == .bothModified, let known = store.item(c.itemID) { sides.server = .init(item: known) }60        }61        return sides62    }6364    /// Name of a conflict copy: "rapport (conflit iPhone 2026-11-18 14.32).pdf".65    static func conflictName(_ name: String, device: String, date: Date = .now) -> String {66        let ext = (name as NSString).pathExtension67        let stem = (name as NSString).deletingPathExtension68        let stamp = date.formatted(.iso8601.year().month().day().dateSeparator(.dash)) + " " + date.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits)).replacingOccurrences(of: ":", with: ".")69        let d = LocalFiles.safeName(device).prefix(40)70        return "\(stem) (conflit \(d) \(stamp))" + (ext.isEmpty ? "" : ".\(ext)")71    }7273    public func resolve(_ conflictID: Int64, choice: ConflictChoice, deviceName: String) async throws {74        guard let c = store.conflicts().first(where: { $0.id == conflictID }) else { return }75        guard let item = store.item(c.itemID), var ls = store.localState(c.itemID), let localURL = files.url(for: ls) else {76            store.deleteConflict(c.id)77            emit(.conflictsChanged)78            return79        }80        let failedOps = store.ops().filter { $0.itemID == c.itemID && $0.kind == .uploadVersion }81        let staleTransfers = store.transfers().filter { $0.itemID == c.itemID && $0.kind == .upload && $0.state != .done }82        func clearPending(abortServerUpload: Bool) async {83            for op in failedOps { store.deleteOp(op.id) }84            for t in staleTransfers {85                inFlight.remove(t.id)86                await driver.cancel(tag: t.id)87                if abortServerUpload, let up = t.uploadID { try? await remote.abortUpload(id: up) }88                files.removeTransferFiles(t.id)89                store.deleteTransfer(t.id)90            }91        }9293        switch (c.reason, choice) {94        case (.bothModified, .keepMine):95            // rebase the edit on the server's current version, then send it again as the newest version96            let current = try await remote.item(id: item.id, isFolder: false)97            await clearPending(abortServerUpload: true)98            try store.upsert(current)99            ls.baseVersionID = current.versionID100            ls.dirty = true101            try store.saveLocalState(ls)102            try store.appendOp(.uploadVersion, itemID: item.id)103104        case (.bothModified, .keepBoth), (.remoteDeleted, .keepBoth), (.remoteDeleted, .keepMine):105            // the device's content becomes a file of its own; it is copied before anything else changes106            let parent = store.item(item.parentID ?? "").flatMap { $0.isTrashed ? nil : $0.id } ?? store.rootID ?? item.parentID ?? ""107            let name = c.reason == .bothModified ? Self.conflictName(item.name, device: deviceName) : item.name108            _ = try importFile(at: localURL, named: name, into: parent, move: false)109            await clearPending(abortServerUpload: true)110            try await discardLocalEdit(item, ls, refetch: c.reason == .bothModified)111112        case (_, .keepServer):113            await clearPending(abortServerUpload: true)114            try await discardLocalEdit(item, ls, refetch: c.reason == .bothModified)115        }116        _ = try? store.db.run("DELETE FROM conflicts WHERE item_id = ?", c.itemID)117        emit(.conflictsChanged)118        emit(.transfersChanged)119        emit(.itemsChanged)120        await sync()121    }122123    /// Drops the edited copy of an item. With `refetch`, the server's current content takes its place when the item is kept offline.124    func discardLocalEdit(_ item: DriveItem, _ ls: LocalState, refetch: Bool) async throws {125        var ls = ls126        if let loc = ls.location { files.removeCopy(itemID: item.id, location: loc) }127        ls.location = nil; ls.fileName = nil; ls.baseSHA = nil; ls.baseVersionID = nil; ls.localSize = 0; ls.dirty = false; ls.downloadedAt = nil128        if refetch {129            if ls.pinned { try store.saveLocalState(ls) } else { try store.deleteLocalState(item.id) }130            if let fresh = try? await remote.item(id: item.id, isFolder: false) {131                try store.upsert(fresh)132                if isEffectivelyPinned(fresh.id) { enqueueDownload(fresh, priority: .pin) }133            }134        } else {135            // the item no longer exists on the server: its ghost leaves the device's records too136            try store.deleteLocalState(item.id)137            if let fresh = try? await remote.item(id: item.id, isFolder: false) { try store.upsert(fresh) } else { try store.deleteItem(item.id) }138        }139    }140}141
Files main
Menu

Theme