Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: FileProviderExtension/FileProviderManager.swift3// Description: The application's side of the Finder integration: registering and removing the SP Drive location, signalling changes, asking for downloads (offline pins), freeing local space, locating items in the Finder. Compiled into the application.4import AppKit5import FileProvider6import Foundation7import SPDriveCore89final class DriveDomain: Sendable {10 static let shared = DriveDomain()11 private var domain: NSFileProviderDomain { NSFileProviderDomain(identifier: AppEnvironment.domainIdentifier, displayName: AppEnvironment.variant.isEmpty ? "" : "Dev") }12 private var manager: NSFileProviderManager? { NSFileProviderManager(for: domain) }1314 /// True when the SP Drive location exists in the Finder.15 func isRegistered() async -> Bool { ((try? await NSFileProviderManager.domains()) ?? []).contains { $0.identifier == AppEnvironment.domainIdentifier } }16 /// Whether the location exists, and whether the person has turned it on. macOS keeps a new location off until the17 /// person enables it in System Settings › General › Login Items & Extensions › File Providers: that consent is theirs alone.18 func state() async -> (registered: Bool, enabled: Bool) {19 guard let d = ((try? await NSFileProviderManager.domains()) ?? []).first(where: { $0.identifier == AppEnvironment.domainIdentifier }) else { return (false, false) }20 return (true, d.userEnabled)21 }22 /// Opens System Settings where File Provider locations are turned on.23 @MainActor func openSystemSettings() {24 for s in ["x-apple.systempreferences:com.apple.LoginItems-Settings.extension?ExtensionItems", "x-apple.systempreferences:com.apple.LoginItems-Settings.extension"] {25 if let u = URL(string: s), NSWorkspace.shared.open(u) { return }26 }27 }28 /// Adds the location to the Finder (idempotent).29 func register() async throws {30 if await isRegistered() { return }31 try await NSFileProviderManager.add(domain)32 }33 /// Removes the location. Files edited on this Mac and not yet sent are kept by the system in a folder the person can open: nothing unsynced is destroyed.34 @discardableResult func remove() async throws -> URL? {35 guard await isRegistered() else { return nil }36 return try await NSFileProviderManager.remove(domain, mode: .preserveDirtyUserData)37 }38 /// The mirror changed: the system asks the extension for what is new.39 func signalChanges() {40 manager?.signalEnumerator(for: .workingSet) { error in if let error { AppEnvironment.log.info("signal: \(error.localizedDescription, privacy: .public)") } }41 }42 /// A condition that blocked syncing is over (signed in again, server reachable again): the system retries what it was holding.43 func signalResolved(_ code: NSFileProviderError.Code) {44 manager?.signalErrorResolved(NSFileProviderError(code)) { _ in }45 }46 /// Address of an item inside the Finder location (the file may still be a placeholder without content).47 func url(for item: DriveItem, rootID: String?) async -> URL? {48 guard let manager else { return nil }49 let id: NSFileProviderItemIdentifier = item.id == rootID ? .rootContainer : NSFileProviderItemIdentifier(item.id)50 return try? await manager.getUserVisibleURL(for: id)51 }52 func rootURL() async -> URL? { guard let manager else { return nil }; return try? await manager.getUserVisibleURL(for: .rootContainer) }53 /// Starts downloading an item now (it is also kept up to date when pinned).54 func requestDownload(_ id: String) async throws {55 guard let manager else { return }56 try await manager.requestDownloadForItem(withIdentifier: NSFileProviderItemIdentifier(id), requestedRange: NSRange(location: NSNotFound, length: 0))57 }58 /// Downloads a file now by reading it through the Finder location. `requestDownload` only queues the download in a59 /// system activity that macOS defers (on battery, under load); a coordinated read makes the system fetch at once.60 func materialize(_ id: String) async throws {61 guard let manager else { return }62 let url = try await manager.getUserVisibleURL(for: NSFileProviderItemIdentifier(id))63 try await Task.detached(priority: .utility) {64 let scoped = url.startAccessingSecurityScopedResource()65 defer { if scoped { url.stopAccessingSecurityScopedResource() } }66 var coordination: NSError?, inner: Error?67 NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &coordination) { actual in68 do { let h = try FileHandle(forReadingFrom: actual); _ = try h.read(upToCount: 1); try h.close() } catch { inner = error }69 }70 if let e = coordination ?? inner { throw e }71 }.value72 }73 /// Copies a file of the Finder location into the app's container (coordinated read; an APFS clone when possible) and74 /// checks it against the expected SHA-256 — a copy that does not match is removed and an error thrown.75 func copyOut(_ url: URL, to destination: URL, sha256: String) async throws {76 try await Task.detached(priority: .userInitiated) {77 let scoped = url.startAccessingSecurityScopedResource()78 defer { if scoped { url.stopAccessingSecurityScopedResource() } }79 var coordination: NSError?, inner: Error?80 NSFileCoordinator().coordinate(readingItemAt: url, options: [.withoutChanges], error: &coordination) { actual in81 do {82 try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)83 try? FileManager.default.removeItem(at: destination)84 try FileManager.default.copyItem(at: actual, to: destination)85 } catch { inner = error }86 }87 if let e = coordination ?? inner { throw e }88 if !sha256.isEmpty, (try Hashing.sha256Hex(of: destination)).sha256 != sha256.lowercased() {89 try? FileManager.default.removeItem(at: destination)90 throw DriveError.integrity("la copie locale ne correspond pas à la version du serveur")91 }92 }.value93 }94 /// Removes the local copy of an item and keeps the item itself. The system refuses when the copy is pinned or holds changes not yet sent.95 func evict(_ id: String) async throws {96 guard let manager else { return }97 try await manager.evictItem(identifier: NSFileProviderItemIdentifier(id))98 }99 /// Waits until the system has nothing left to send or fetch for this location.100 func waitForStabilization() async throws { try await manager?.waitForStabilization() }101 @MainActor func openInFinder() async { if let u = await rootURL() { NSWorkspace.shared.open(u) } }102 @MainActor func reveal(_ item: DriveItem, rootID: String?) async -> Bool {103 guard let u = await url(for: item, rootID: rootID) else { return false }104 NSWorkspace.shared.activateFileViewerSelecting([u]); return true105 }106}107