Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/AppModel.swift3// Description: State and actions of the application: session (passkey, device link, lock), the sync engine of the signed-in account, reads of the local mirror for the views, and every action a person can take — each one recorded in the offline journal or the transfer queue, never done only in memory.4import AppKit5import Foundation6import LocalAuthentication7import Observation8import SPDriveCore9import SPDriveNext10import SPDriveSync1112struct Banner: Equatable, Identifiable { let id = UUID(); var text: String; var isError: Bool }1314@MainActor @Observable final class AppModel {15 enum Phase: Equatable { case launching, signedOut, signedIn }16 var phase = Phase.launching17 var locked = false18 var account: Account?19 var quota: Quota?20 var status = SyncStatus()21 var transfers: [Transfer] = []22 var conflicts: [SyncConflict] = []23 /// Grows each time the local mirror changed: views that read the mirror depend on it.24 var revision = 025 var banner: Banner?26 var link: DeviceLinkStart?27 var signingIn = false28 var loginError: String?29 var finderRegistered = false30 /// The person turned the Finder location on in System Settings (macOS keeps a new location off until then).31 var finderEnabled = false32 /// The Finder location exists and is on: local copies, offline pins and opening through the Finder work.33 var finderReady: Bool { finderRegistered && finderEnabled }34 /// Items that have an active share link.35 var sharedIDs: Set<String> = []36 var shares: [DriveShare] = []37 var online = true38 var pendingInFinder = 039 let settings = AppSettings()40 let notifier = Notifier()41 /// The navigator of the first window; also the one test tooling and the menu bar act on. Other windows have their own.42 let nav = Navigator()43 private var primaryNavigatorClaimed = false44 /// The navigator of the key window: menu commands act on it.45 var activeNav: Navigator?46 let menuBridge = MenuBridge()47 /// Keeps the menus in step with the key window: recomputed whenever anything it reads changes.48 func trackMenus() {49 let focus = withObservationTracking { menuFocus } onChange: { [weak self] in Task { @MainActor in self?.trackMenus() } }50 if menuBridge.focus != focus { menuBridge.focus = focus }51 }52 /// What the menus need to know to enable their commands; nil when no signed-in window can receive them.53 var menuFocus: WindowFocus? {54 guard phase == .signedIn else { return nil }55 let n = activeNav ?? nav56 return WindowFocus(section: n.section, folderID: n.folderID, hasFolder: n.section == .drive && rootID != nil, selectionCount: n.selection.count,57 selectionHasTrashed: n.selection.contains { item($0)?.isTrashed == true }, canGoBack: n.canGoBack, canGoForward: n.canGoForward,58 locked: locked, paused: settings.syncPaused, finderReady: finderReady)59 }60 /// What the transfer queue currently allows and why (shown by the transfer centre and the menu bar).61 var policy = TransferQueue.Policy()62 var power = PowerState.unconstrained63 let thumbnails = ThumbnailStore()64 // SP Drive 2.065 /// The 2.0 endpoints (SPDriveNext) on the same server and token; nil when signed out.66 private(set) var next: NextClient?67 /// What the connected server can do (`GET /meta`); a 1.0 server has no feature.68 var meta = ServerMeta.v169 var collections: [SmartCollection] = []70 var grants: [SharedGrant] = []71 func has(_ f: ServerMeta.Feature) -> Bool { meta.has(f) }72 var isAdmin: Bool { account?.role == "admin" }73 /// A section is offered only when the server can serve it: no empty promise.74 func isAvailable(_ s: SidebarItem) -> Bool {75 switch s {76 case .collections: has(.collections); case .sharedWithMe: has(.collab); case .activity: has(.activity); case .admin: isAdmin && meta.api >= 277 default: true78 }79 }80 /// Reads the server's capabilities, plugs the event stream in when it has one, and loads what the sidebar shows.81 func refreshNext() async {82 guard let next, let api, let engine else { return }83 guard let m = try? await next.meta() else { return } // unreachable: keep what we knew84 let had = meta.has(.events)85 meta = m86 if m.has(.events), !had { await engine.setEventSource(NextEventSource(api: api)) } else if !m.has(.events), had { await engine.setEventSource(nil) }87 await refreshCollections(); await refreshGrants()88 }89 func refreshCollections() async { if has(.collections), let next, let c = try? await next.collections() { collections = c } }90 func refreshGrants() async { if has(.collab), let next, let g = try? await next.sharedWithMe() { grants = g } }91 private func serverNotified(_ kind: String) async {92 if kind.hasPrefix("collab.") { await refreshGrants() }93 lastDepositCheck = .distantPast; await checkDeposits()94 }95 private let powerSource = SystemPowerSource()9697 private(set) var api: APIClient?98 private(set) var store: MetadataStore?99 private(set) var engine: SyncEngine?100 private let passkeys = PasskeyPresenter()101 private let network = NetworkMonitor()102 private var tasks: [Task<Void, Never>] = []103 private var linkTask: Task<Void, Never>?104 private var pinTask: Task<Void, Never>?105 private var finishedInBatch = (uploads: 0, downloads: 0, lastName: "")106 private var lastDepositCheck = Date.distantPast107 private var lastActive = Date()108109 // MARK: Windows110 /// The first window takes the shared navigator; each further window gets its own.111 func claimNavigator() -> Navigator {112 if !primaryNavigatorClaimed { primaryNavigatorClaimed = true; return nav }113 let n = Navigator(); n.folderID = nav.folderID114 return n115 }116 func releaseNavigator(_ n: Navigator) { if n === nav { primaryNavigatorClaimed = false }; if activeNav === n { activeNav = nil } }117118 // MARK: Session119 private var bootstrapped = false120 func bootstrap() async {121 guard !bootstrapped else { return } // every window calls this; only the first does the work122 bootstrapped = true123 trackMenus()124 do { api = try AppEnvironment.makeAPI() } catch { loginError = error.localizedDescription; phase = .signedOut; return }125 guard let api, (try? AppEnvironment.tokens.readToken()) != nil else { phase = .signedOut; autoLinkIfAsked(); return }126 do {127 let s = try await api.authState()128 if s.authenticated, let user = s.user { await enter(user, quota: s.quota) }129 else { try? AppEnvironment.tokens.deleteToken(); loginError = "La session de cet appareil a été fermée. Reconnectez-vous."; phase = .signedOut; autoLinkIfAsked() }130 } catch {131 // no server right now: the person keeps working on what this Mac already has132 if let data = AppEnvironment.defaults.data(forKey: "account"), let cached = try? JSONDecoder().decode(Account.self, from: data), AppEnvironment.currentAccount == cached.id { await enter(cached, quota: nil) }133 else { loginError = DriveError.wrap(error).errorDescription; phase = .signedOut }134 }135 }136 private func autoLinkIfAsked() {137 #if SPD_DEV138 // development variant only: start linking at launch so that test scripts can approve the code139 if ProcessInfo.processInfo.arguments.contains("-spdAutoLink") { startDeviceLink() }140 #endif141 }142 func signInWithPasskey() async {143 guard let api, !signingIn else { return }144 signingIn = true; loginError = nil145 defer { signingIn = false }146 do {147 let challenge = try await api.loginChallenge()148 let assertion = try await passkeys.assert(challenge)149 try await api.completeLogin(challenge, assertion: assertion, deviceName: AppEnvironment.deviceName)150 await finishSignIn()151 } catch { let e = DriveError.wrap(error); if e != .cancelled { loginError = e.errorDescription } }152 }153 /// Fallback without a passkey on this Mac: show a code, wait for a signed-in browser to approve it.154 func startDeviceLink() {155 guard let api, link == nil else { return }156 loginError = nil157 linkTask = Task {158 do {159 let l = try await api.startDeviceLink(deviceName: AppEnvironment.deviceName)160 link = l161 #if SPD_DEV162 try? l.userCode.write(to: AppEnvironment.containerURL.appendingPathComponent("devlink.txt"), atomically: true, encoding: .utf8)163 #endif164 let deadline = Date().addingTimeInterval(Double(l.expiresInS))165 while !Task.isCancelled, Date() < deadline {166 try await Task.sleep(nanoseconds: UInt64(max(l.intervalS, 1)) * 1_000_000_000)167 switch try await api.pollDeviceLink(l.deviceCode) {168 case .approved: link = nil; await finishSignIn(); return169 case .denied: link = nil; loginError = "La demande a été refusée dans le navigateur."; return170 case .expired: link = nil; loginError = "Le code a expiré. Recommencez."; return171 case .pending: continue172 }173 }174 link = nil175 } catch { link = nil; let e = DriveError.wrap(error); if e != .cancelled { loginError = e.errorDescription } }176 }177 }178 func cancelDeviceLink() { linkTask?.cancel(); linkTask = nil; link = nil }179 private func finishSignIn() async {180 guard let api else { return }181 do {182 let s = try await api.authState()183 guard s.authenticated, let user = s.user else { throw DriveError.unauthenticated }184 await enter(user, quota: s.quota)185 } catch { loginError = DriveError.wrap(error).errorDescription }186 }187 private func enter(_ user: Account, quota q: Quota?) async {188 guard let api else { return }189 await leave()190 do {191 AppEnvironment.currentAccount = user.id192 AppEnvironment.defaults.set(try? JSONEncoder().encode(user), forKey: "account")193 let store = try MetadataStore(url: AppEnvironment.databaseURL(account: user.id))194 let engine = SyncEngine(api: api, store: store, network: network, workDirectory: AppEnvironment.workDirectory, deviceName: AppEnvironment.deviceName, power: powerSource)195 self.store = store; self.engine = engine; account = user; quota = q196 next = NextClient(APIClientTransport(api: api))197 await engine.setNotifyHandler { [weak self] kind in await self?.serverNotified(kind) }198 thumbnails.configure(api: api, directory: cacheDirectory.appendingPathComponent("thumbnails", isDirectory: true))199 await engine.setRemoteChangeHandler { [weak self] changes in await self?.remoteChanged(changes) }200 await applyTransferSettings()201 if settings.syncPaused { await engine.pause() }202 await engine.start()203 tasks.append(Task { [weak self] in for await s in await engine.statusStream() { self?.statusChanged(s) } })204 tasks.append(Task { [weak self] in for await e in await engine.transfers.events() { await self?.transferEvent(e) } })205 tasks.append(Task { [weak self, network] in for await s in network.changes() { self?.online = s.online; if s.online { DriveDomain.shared.signalResolved(.serverUnreachable) } } })206 tasks.append(Task { [weak self] in while !Task.isCancelled { await self?.refreshPolicy(); try? await Task.sleep(nanoseconds: 5_000_000_000) } }) // power changes without any transfer event207 observeSharedDatabase()208 phase = .signedIn; loginError = nil209 if settings.biometricLock { locked = true }210 // the Finder location holds a replica of ONE account's tree. Entering as another account without having211 // signed out (session closed, then another person signs in) must not reuse it: the system would reconcile212 // one account's files against the other's. Remove it (unsent edits are preserved by the system), then add a fresh one.213 let replicaOwner = AppEnvironment.defaults.string(forKey: "finderDomainAccount")214 if let replicaOwner, replicaOwner != user.id, let kept = try? await DriveDomain.shared.remove() {215 banner = Banner(text: "L’emplacement Finder appartenait à un autre compte : il a été recréé. Les modifications non envoyées sont conservées dans \(kept.path).", isError: false)216 }217 AppEnvironment.defaults.set(user.id, forKey: "finderDomainAccount")218 await applyFinderIntegration()219 DriveDomain.shared.signalResolved(.notAuthenticated)220 notifier.requestAuthorization()221 await reloadLists()222 Task { await self.refreshShares() }223 consumeFinderRequest() // the app may have been opened by the Finder action itself224 await refreshNext()225 applyDevArguments()226 DropZoneController.shared.update(model: self)227 Task { await SpotlightIndexer.shared.sync(model: self) }228 #if SPD_DEV229 if UserDefaults.standard.bool(forKey: "spdSelfTest") { Task { await DevSelfTest.run(self) } }230 if UserDefaults.standard.bool(forKey: "spdMenuProbe") { Task { await DevSelfTest.menuProbe(self) } }231 if UserDefaults.standard.bool(forKey: "spdPerf") { Task { await DevSelfTest.perfProbe(self) } }232 if UserDefaults.standard.bool(forKey: "spdOnScreen") { Task { await DevSelfTest.onScreenOnly(self) } }233 if UserDefaults.standard.bool(forKey: "spdTour") { Task { await DevTour.run(self, into: AppEnvironment.containerURL.appendingPathComponent("tour")) } } // inside the sandbox234 #endif235 } catch { loginError = "Impossible d’ouvrir la base locale : \(error.localizedDescription)"; phase = .signedOut }236 }237 /// Development variant only: launch arguments that put the window in a given state for visual checks.238 private func applyDevArguments() {239 #if SPD_DEV240 let d = UserDefaults.standard241 if let s = d.string(forKey: "spdSection"), let section = SidebarItem(rawValue: s), isAvailable(section) { nav.section = section }242 if d.object(forKey: "spdGrid") != nil { settings.gridView = d.bool(forKey: "spdGrid") }243 if let name = d.string(forKey: "spdFolder"), let root = rootID, let f = children(of: root).first(where: { $0.name == name }) { nav.folderID = f.id }244 if let path = d.string(forKey: "spdPath"), var at = rootID { // "Atelier/Photos de chantier"245 for name in path.split(separator: "/") { if let f = children(of: at).first(where: { $0.name == name && $0.isFolder }) { at = f.id } }246 if at != rootID { nav.folderID = at }247 }248 if let q = d.string(forKey: "spdSearch") { nav.searchText = q }249 if d.bool(forKey: "spdSemantic") { nav.searchSemantic = true }250 let items = nav.section == .trash ? trash() : children(of: nav.folderID ?? rootID ?? "")251 let target = d.string(forKey: "spdSelect").flatMap { n in items.first { $0.name == n } } ?? (d.bool(forKey: "spdSelectFirst") ? items.first : nil)252 if let target { nav.selection = [target.id] }253 if d.bool(forKey: "spdSignOut") { Task { await signOut(); try? "done".write(to: AppEnvironment.containerURL.appendingPathComponent("signedout.txt"), atomically: true, encoding: .utf8) }; return } // leaves the Mac clean after a test campaign254 if d.bool(forKey: "spdInspector") { nav.showInspector = true }255 if let t = target, d.object(forKey: "spdPin") != nil { let on = d.bool(forKey: "spdPin"); Task { await refreshFinderState(); await setPinned([t], on) } }256 if let t = target, d.bool(forKey: "spdEvict") { Task { await refreshFinderState(); let r = await freeUpSpace([t.id]); AppEnvironment.log.info("evict: freed \(r.freed) kept \(r.kept)") } }257 switch d.string(forKey: "spdSheet") {258 case "share": if let t = target { nav.sheet = .share(t) }259 case "versions": if let t = target { nav.sheet = .versions(t) }260 case "portal": if let t = target ?? rootID.flatMap({ item($0) }) { nav.sheet = .portal(folder: t) }261 case "rename": if let t = target { nav.sheet = .rename(t) }262 case "move": if let t = target { nav.sheet = .move([t]) }263 case "newFolder": if let r = nav.folderID ?? rootID { nav.sheet = .newFolder(parent: r) }264 case "conflict": if let c = conflicts.first(where: \.isOpen) { nav.sheet = .conflict(c) }265 case "ask": nav.sheet = .ask(target)266 case "members": if let t = target ?? nav.folderID.flatMap({ item($0) }) { nav.sheet = .members(t) }267 case "collection": nav.sheet = .collection(collections.first)268 case "suggest": nav.sheet = .suggest(items.filter { !$0.isFolder }.prefix(3).map { $0 })269 default: break270 }271 if d.bool(forKey: "spdPalette") { nav.showPalette = true }272 // the app's own appearance for visual checks (the system setting is not touched): -spdAppearance dark|light273 if let a = d.string(forKey: "spdAppearance") { NSApp.appearance = NSAppearance(named: a == "dark" ? .darkAqua : .aqua) }274 #endif275 }276 private func leave() async {277 for t in tasks { t.cancel() }; tasks.removeAll()278 await engine?.stop()279 engine = nil; store = nil; next = nil; meta = .v1; collections = []; grants = []280 thumbnails.reset()281 DropZoneController.shared.hide()282 }283 /// Signs out: the device session is revoked, the Finder location removed (unsent edits are preserved by the system), the local mirror erased.284 func signOut() async {285 let id = account?.id286 await leave()287 await api?.signOut()288 if let kept = try? await DriveDomain.shared.remove() { banner = Banner(text: "Des modifications non envoyées ont été conservées dans \(kept.path).", isError: false) }289 finderRegistered = false; finderEnabled = false290 await SpotlightIndexer.shared.removeAll() // nothing about the account stays searchable on this Mac291 if let id { try? FileManager.default.removeItem(at: AppEnvironment.databaseURL(account: id).deletingLastPathComponent()) }292 try? FileManager.default.removeItem(at: AppEnvironment.workDirectory)293 try? FileManager.default.removeItem(at: cacheDirectory)294 AppEnvironment.currentAccount = nil; AppEnvironment.defaults.removeObject(forKey: "account"); AppEnvironment.defaults.removeObject(forKey: "finderDomainAccount")295 account = nil; quota = nil; transfers = []; conflicts = []; shares = []; sharedIDs = []; status = SyncStatus(); phase = .signedOut296 }297 /// Number of local decisions and transfers the server has not confirmed yet (shown before signing out).298 var unsyncedCount: Int { status.pendingOperations + status.transfers.running + status.transfers.queued + status.transfers.paused + pendingInFinder }299300 /// Shows an item in the window: its folder, with the item selected (Spotlight result, Finder action, notification).301 func reveal(itemID: String, sheet: ((DriveItem) -> SheetKind)? = nil) {302 guard phase == .signedIn, let item = item(itemID), !item.isTrashed else { return }303 if item.isFolder && sheet == nil { nav.go(to: item.isRoot ? nil : item.id) }304 else { nav.go(to: item.parentID == rootID ? nil : item.parentID); nav.selection = [item.id] }305 if let sheet { nav.sheet = sheet(item) }306 AppDelegate.showMainWindow()307 }308309 // MARK: Lock310 func unlock() async {311 let ctx = LAContext()312 var err: NSError?313 guard ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: &err) else { locked = false; return } // a Mac without any way to authenticate cannot be locked out of its own data314 if (try? await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "déverrouiller SP Drive")) == true { locked = false; lastActive = Date() }315 }316 func appBecameActive() { Task { await refreshFinderState() }; if settings.biometricLock, phase == .signedIn, Date().timeIntervalSince(lastActive) > 120 { locked = true }; Task { await engine?.poke() } }317 func appResignedActive() { lastActive = Date() }318319 // MARK: Engine events320 private func statusChanged(_ s: SyncStatus) {321 let was = status322 status = s323 // the server answers again: the system retries what it was holding for the Finder location324 if was.phase == .offline, s.phase == .idle || s.phase == .syncing { DriveDomain.shared.signalResolved(.serverUnreachable); DriveDomain.shared.signalChanges() }325 if s.phase == .needsLogin, was.phase != .needsLogin {326 // the session was revoked elsewhere: local work stays in the journal for the next sign-in327 loginError = "La session de cet appareil a été fermée. Reconnectez-vous : vos modifications en attente sont conservées."328 phase = .signedOut329 }330 if case .error(let m) = s.phase, was.phase != s.phase { banner = Banner(text: m, isError: true) }331 }332 private func remoteChanged(_ changes: [DetectedChange]) async {333 revision += 1334 DriveDomain.shared.signalChanges()335 await reloadLists()336 await refreshAccount()337 await checkDeposits()338 await SpotlightIndexer.shared.sync(model: self)339 }340 func refreshPolicy() async {341 guard let engine else { return }342 let p = await engine.transfers.policy()343 if p != policy { policy = p }344 let s = powerSource.state345 if s != power { power = s }346 }347 private func transferEvent(_ e: TransferEvent) async {348 if let engine { transfers = await engine.transfers.list() }349 await refreshPolicy()350 switch e {351 case .finished(let t, _):352 if t.direction == .upload { finishedInBatch.uploads += 1; revision += 1; DriveDomain.shared.signalChanges() } else { finishedInBatch.downloads += 1 }353 finishedInBatch.lastName = t.name354 if let s = await engine?.transfers.summary(), s.running + s.queued == 0 { announceBatch() }355 case .conflict(let c):356 await reloadLists()357 if settings.notifyConflicts { notifier.post(id: "conflict-\(c.id)", title: "Conflit de versions", body: "« \(c.itemName) » a été modifié sur deux appareils. Les deux versions sont conservées ; choisissez laquelle garder.") }358 case .failed(let t, let persistent):359 if t.error?.contains("insuffisant") == true { notifier.post(id: "quota", title: "Espace de stockage insuffisant", body: "« \(t.name) » n’a pas pu être envoyé : SP Drive est plein.") }360 else if persistent { notifier.post(id: "sync-error", title: "Erreur de synchronisation persistante", body: "« \(t.name) » : \(t.error ?? "échec répété"). SP Drive continue d’essayer.") }361 else { banner = Banner(text: "« \(t.name) » : \(t.error ?? "échec")", isError: true) }362 case .changed, .removed: break363 }364 }365 private func announceBatch() {366 let b = finishedInBatch; finishedInBatch = (0, 0, "")367 guard settings.notifyTransfers else { return }368 if b.uploads == 1, b.downloads == 0 { notifier.post(id: "batch", title: "Téléversement terminé", body: "« \(b.lastName) » est sur SP Drive.") }369 else if b.uploads > 1, b.downloads == 0 { notifier.post(id: "batch", title: "Téléversements terminés", body: "\(b.uploads) fichiers sont sur SP Drive.") }370 else if b.downloads == 1, b.uploads == 0 { notifier.post(id: "batch", title: "Téléchargement terminé", body: "« \(b.lastName) » est dans Téléchargements.") }371 else if b.downloads + b.uploads > 0 { notifier.post(id: "batch", title: "Transferts terminés", body: "\(b.uploads) envoyé(s), \(b.downloads) téléchargé(s).") }372 }373 private func observeSharedDatabase() {374 // the File Provider extension writes the same database from the Finder: it tells us with a Darwin notification375 let name = AppEnvironment.changedNotification376 tasks.append(Task { [weak self] in377 for await _ in DarwinNotifications.stream(name) {378 guard let self else { return }379 let before = self.conflicts.filter(\.isOpen).count380 self.revision += 1381 self.consumeFinderRequest()382 await self.reloadLists()383 let open = self.conflicts.filter(\.isOpen)384 if open.count > before, self.settings.notifyConflicts, let c = open.first {385 self.notifier.post(id: "conflict-\(c.id)", title: "Conflit de versions", body: "« \(c.itemName) » a été modifié sur deux appareils. Les deux versions sont conservées ; choisissez laquelle garder.")386 }387 await self.engine?.poke()388 }389 })390 }391 /// Something asked for in the Finder's context menu that only the app can show (version history).392 private func consumeFinderRequest() {393 guard let store, let raw = (try? store.meta("ui_request")) ?? nil else { return }394 try? store.setMeta("ui_request", nil)395 let parts = raw.split(separator: "|").map(String.init)396 guard parts.count == 3, let at = Double(parts[2]), Date().timeIntervalSince1970 - at < 120 else { return }397 if parts[0] == "versions" { reveal(itemID: parts[1]) { .versions($0) } }398 Task { await refreshShares() }399 }400 func reloadLists() async {401 guard let engine, let store else { return }402 transfers = await engine.transfers.list()403 conflicts = (try? engine.conflicts.conflicts()) ?? []404 pendingInFinder = Int((try? store.meta("fp_pending")).flatMap { $0 } ?? "0") ?? 0405 }406 func refreshAccount() async {407 guard let api, let s = try? await api.authState(), s.authenticated else { return }408 quota = s.quota; if let u = s.user { account = u }409 }410 func refreshShares() async {411 guard let api, let all = try? await api.shares() else { return }412 shares = all; sharedIDs = Set(all.filter(\.isActive).compactMap(\.targetId))413 // the Finder shows "shared" on these items: the extension reads the list from the mirror414 let joined = sharedIDs.sorted().joined(separator: ",")415 if let store, ((try? store.meta("shared_ids")) ?? nil ?? "") != joined {416 let before = Set(((try? store.meta("shared_ids")) ?? nil ?? "").split(separator: ",").map(String.init))417 try? store.setMeta("shared_ids", joined); try? store.touch(Array(before.symmetricDifference(sharedIDs)))418 DriveDomain.shared.signalChanges()419 }420 }421 private func checkDeposits() async {422 guard settings.notifyDeposits, let api, Date().timeIntervalSince(lastDepositCheck) > 60 else { return }423 lastDepositCheck = Date()424 guard let notes = try? await api.notifications() else { return }425 var seen = Set(AppEnvironment.defaults.stringArray(forKey: "seenNotifications") ?? [])426 let firstRun = AppEnvironment.defaults.object(forKey: "seenNotifications") == nil427 for n in notes where n.kind == "request.submission" && !seen.contains(n.id) {428 seen.insert(n.id)429 if !firstRun, !n.read { notifier.post(id: "deposit-\(n.id)", title: "Nouveau dépôt reçu", body: "\(n.data["name"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? "Quelqu’un") a déposé \(n.data["placed"]?.int ?? 0) fichier(s) dans « \(n.data["title"]?.string ?? "un portail") ».") }430 }431 AppEnvironment.defaults.set(Array(seen.suffix(500)), forKey: "seenNotifications")432 }433434 // MARK: Settings that act435 func applyTransferSettings() async {436 guard let engine else { return }437 await engine.transfers.setLimits(uploadBytesPerSecond: Int64(settings.uploadLimitKB) * 1024, downloadBytesPerSecond: Int64(settings.downloadLimitKB) * 1024)438 await engine.transfers.setManualConcurrency(settings.parallelTransfers > 0 ? settings.parallelTransfers : nil)439 await engine.transfers.setPowerAware(settings.respectPower)440 await refreshPolicy()441 }442 func applyFinderIntegration() async {443 do {444 if settings.finderIntegration { try await DriveDomain.shared.register() } else { _ = try await DriveDomain.shared.remove() }445 } catch { banner = Banner(text: "Intégration au Finder : \(error.localizedDescription)", isError: true) }446 await refreshFinderState()447 }448 /// Reads the state of the Finder location; when it has just been turned on, the system is told to start syncing.449 func refreshFinderState() async {450 let was = finderReady451 let s = await DriveDomain.shared.state()452 finderRegistered = s.registered; finderEnabled = s.enabled453 if finderReady, !was { DriveDomain.shared.signalResolved(.notAuthenticated); DriveDomain.shared.signalResolved(.serverUnreachable); DriveDomain.shared.signalChanges(); revision += 1 }454 }455 /// While the location waits to be turned on, look again every few seconds (stops as soon as it is on).456 func watchFinderState() async {457 while !Task.isCancelled, phase == .signedIn, finderRegistered, !finderEnabled {458 try? await Task.sleep(nanoseconds: 3_000_000_000)459 await refreshFinderState()460 }461 }462 func setPaused(_ paused: Bool) async {463 settings.syncPaused = paused464 if paused { await engine?.pause() } else { await engine?.resume() }465 }466 func syncNow() async { await engine?.poke() }467468 // MARK: Reading the mirror469 var rootID: String? { store?.rootID }470 func children(of folder: String) -> [DriveItem] { (try? store?.children(of: folder)) ?? [] }471 func item(_ id: String) -> DriveItem? { (try? store?.item(id)) ?? nil }472 func path(to id: String) -> [DriveItem] { (try? store?.path(to: id)) ?? [] }473 func recent() -> [DriveItem] { (try? store?.recent()) ?? [] }474 func starred() -> [DriveItem] { (try? store?.starred()) ?? [] }475 func pinned() -> [DriveItem] { (try? store?.pinnedItems()) ?? [] }476 func trash() -> [DriveItem] { (try? store?.trashRoots()) ?? [] }477 func search(_ q: LocalSearch) -> [DriveItem] { (try? store?.search(q)) ?? [] }478 func isPinned(_ id: String) -> Bool { (try? store?.isPinned(id)) ?? false }479 func isPinnedItself(_ id: String) -> Bool { (try? store?.isPinnedItself(id)) ?? false }480 func isLocal(_ id: String) -> Bool { (try? store?.isMaterialized(id)) ?? false }481 func isPending(_ id: String) -> Bool { OperationJournal.isLocal(id) }482483 // MARK: Actions on the tree (journaled: they work offline and survive a restart)484 private func act(_ what: String, _ body: (OperationJournal) throws -> Void) {485 guard let engine else { return }486 do { try body(engine.journal); changed() }487 catch { banner = Banner(text: "\(what) : \(DriveError.wrap(error).errorDescription ?? "échec")", isError: true) }488 }489 private func changed() {490 revision += 1491 DriveDomain.shared.signalChanges()492 Task { await engine?.poke(); await reloadLists() }493 }494 @discardableResult func createFolder(in parent: String, name: String) -> DriveItem? {495 var made: DriveItem?496 act("Nouveau dossier") { made = try $0.createFolder(parent: parent, name: name) }497 return made498 }499 func rename(_ item: DriveItem, to name: String) { act("Renommer") { try $0.rename(item, to: name) } }500 func move(_ items: [DriveItem], to destination: String) { act("Déplacer") { try $0.move(items, to: destination) } }501 func trash(_ items: [DriveItem]) { act("Supprimer") { try $0.trash(items) } }502 func restore(_ items: [DriveItem]) { act("Restaurer") { try $0.restore(items) } }503 func setStarred(_ items: [DriveItem], _ on: Bool) { act("Favoris") { for i in items { try $0.setStarred(i, on) } } }504 func duplicate(_ items: [DriveItem]) {505 act("Dupliquer") { j in506 for (parent, group) in Dictionary(grouping: items, by: { $0.parentID ?? "" }) where !parent.isEmpty { try j.copy(group, to: parent) }507 }508 }509 /// Deletes for good, from the trash only, after the person confirmed. Needs the server: a destruction is never queued blindly.510 func purge(_ items: [DriveItem]) async {511 guard let api else { return }512 do { try await api.purge(Selection(items)); try store?.remove(items.flatMap { (try? store?.subtreeIDs(of: $0.id, includeTrashed: true)) ?? [$0.id] }); changed() }513 catch { banner = Banner(text: "Suppression définitive : \(DriveError.wrap(error).errorDescription ?? "échec")", isError: true) }514 }515 func emptyTrash() async {516 guard let api else { return }517 do { try await api.emptyTrash(); await engine?.poke(); changed() }518 catch { banner = Banner(text: "Vider la corbeille : \(DriveError.wrap(error).errorDescription ?? "échec")", isError: true) }519 }520521 // MARK: Transfers522 /// Queues files and folders for upload into `parent`. Folders are re-created (journaled), their files queued inside.523 func upload(_ urls: [URL], to parent: String) async {524 guard let engine else { return }525 var failed = 0526 for url in urls {527 let scoped = url.startAccessingSecurityScopedResource()528 defer { if scoped { url.stopAccessingSecurityScopedResource() } }529 await uploadOne(url, to: parent, engine: engine, failed: &failed)530 }531 if failed > 0 { banner = Banner(text: "\(failed) élément(s) n’ont pas pu être ajoutés à la file d’envoi.", isError: true) }532 changed()533 }534 private func uploadOne(_ url: URL, to parent: String, engine: SyncEngine, failed: inout Int) async {535 let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey, .isPackageKey])536 if values?.isSymbolicLink == true || url.lastPathComponent.hasPrefix(".") { return } // links and hidden files stay on this Mac537 if values?.isDirectory == true {538 guard let folder = try? engine.journal.createFolder(parent: parent, name: url.lastPathComponent) else { failed += 1; return }539 let kids = (try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isDirectoryKey])) ?? []540 for k in kids.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { await uploadOne(k, to: folder.id, engine: engine, failed: &failed) }541 } else {542 do { _ = try await engine.transfers.enqueueUpload(file: url, parent: parent, priority: TransferPriority.userInitiated) } catch { failed += 1 }543 }544 }545 /// Sends a local file as a new version of an existing file (the version history keeps the previous one). The upload546 /// names the version this Mac knows: if another device replaced it meanwhile, a conflict is raised instead of a silent overwrite.547 func uploadNewVersion(of item: DriveItem, from url: URL) async {548 guard let engine else { return }549 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }550 do { _ = try await engine.transfers.enqueueUpload(file: url, parent: item.parentID ?? "root", replacing: item, baseVersionID: item.versionID, priority: TransferPriority.userInitiated); changed() }551 catch { banner = Banner(text: "Nouvelle version : \(error.localizedDescription)", isError: true) }552 }553 var downloadsFolder: URL { FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0] }554 private func uniqueURL(in dir: URL, name: String) -> URL {555 let taken = Set(((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []).map { NameRules.key($0) })556 return dir.appendingPathComponent(NameRules.nextFree(NameRules.sanitize(name)) { taken.contains($0) })557 }558 /// Queues downloads into the Downloads folder (folders are re-created with their content).559 func download(_ items: [DriveItem], version: FileVersion? = nil) async {560 guard let engine, let store else { return }561 for item in items {562 do {563 if item.isFolder {564 let base = uniqueURL(in: downloadsFolder, name: item.name)565 try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)566 let depth = try store.path(to: item.id).count567 for f in try store.subtreeFiles(of: item.id) {568 var dir = base569 for comp in try store.path(to: f.id).dropFirst(depth).dropLast() { dir = try PathSafety.child(of: dir, named: NameRules.sanitize(comp.name)) }570 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)571 _ = try await engine.transfers.enqueueDownload(f, to: try PathSafety.child(of: dir, named: NameRules.sanitize(f.name)), priority: TransferPriority.userInitiated)572 }573 } else {574 let name = version.map { v in let (s, e) = NameRules.splitExtension(item.name); return "\(s) (version \(v.seq))\(e)" } ?? item.name575 _ = try await engine.transfers.enqueueDownload(item, version: version, to: uniqueURL(in: downloadsFolder, name: name), priority: TransferPriority.userInitiated)576 }577 } catch { banner = Banner(text: "Téléchargement de « \(item.name) » : \(DriveError.wrap(error).errorDescription ?? "échec")", isError: true) }578 }579 await reloadLists()580 }581 func pauseTransfer(_ id: String) async { await engine?.transfers.pause(id); await reloadLists() }582 func resumeTransfer(_ id: String) async { await engine?.transfers.resume(id); await reloadLists() }583 func cancelTransfer(_ id: String) async { await engine?.transfers.cancel(id); await reloadLists() }584 func removeTransfer(_ id: String) async { await engine?.transfers.remove(id); await reloadLists() }585 func clearFinishedTransfers() async { await engine?.transfers.clearFinished(); await reloadLists() }586 /// "Send this one first".587 func prioritizeTransfer(_ id: String) async { await engine?.transfers.setPriority(id, TransferPriority.urgent); await reloadLists() }588 func retryAllFailed() async { for t in transfers where t.state == .failed { await engine?.transfers.resume(t.id) }; await reloadLists() }589 /// Seconds left for everything in flight at the current speed; nil when it cannot be known honestly.590 var secondsRemaining: Double? {591 let s = status.transfers592 guard s.speed > 1024, s.bytesLeft > 0, s.running > 0 else { return nil }593 return Double(s.bytesLeft) / s.speed594 }595596 // MARK: Opening and previewing597 var cacheDirectory: URL { AppEnvironment.containerURL.appendingPathComponent("cache", isDirectory: true) }598 /// A local, verified copy of a file for preview: the Finder copy when it is on this Mac, a cached download otherwise.599 /// - Parameter inContainer: always answer with a copy inside the app's own container (what Quick Look and a drag to600 /// another app are given: they cannot be handed a file of the Finder location from this sandbox). The copy of a601 /// file already on this Mac is an APFS clone: no bytes are duplicated, nothing is downloaded.602 func localCopy(of item: DriveItem, inContainer: Bool = false) async throws -> URL {603 guard !item.isFolder, let api else { throw DriveError.local("pas de contenu à afficher") }604 let dir = cacheDirectory.appendingPathComponent("\(item.id)-\(item.versionID ?? item.sha256)", isDirectory: true)605 let dest = try PathSafety.child(of: dir, named: NameRules.sanitize(item.name))606 if inContainer, FileManager.default.fileExists(atPath: dest.path) { return dest }607 if finderReady, isLocal(item.id), let u = await DriveDomain.shared.url(for: item, rootID: rootID) {608 guard inContainer else { return u }609 if (try? await DriveDomain.shared.copyOut(u, to: dest, sha256: item.sha256)) != nil { return dest } // otherwise fall through to a verified download610 }611 if FileManager.default.fileExists(atPath: dest.path) { return dest }612 try await DownloadEngine(api: api).download(fileID: item.id, versionID: item.versionID, sha256: item.sha256, size: item.size, to: dest, partial: dir.appendingPathComponent(".part"))613 return dest614 }615 /// The verified copy already made for a preview, when there is one (never downloads).616 func existingLocalCopy(of item: DriveItem) -> URL? {617 guard !item.isFolder, let dest = try? PathSafety.child(of: cacheDirectory.appendingPathComponent("\(item.id)-\(item.versionID ?? item.sha256)", isDirectory: true), named: NameRules.sanitize(item.name)) else { return nil }618 return FileManager.default.fileExists(atPath: dest.path) ? dest : nil619 }620 /// Opens a file in its application. Through the Finder location when it exists, so that edits are synced back.621 func open(_ item: DriveItem) async {622 if finderReady, let u = await DriveDomain.shared.url(for: item, rootID: rootID) { NSWorkspace.shared.open(u); return }623 do { NSWorkspace.shared.open(try await localCopy(of: item)) }624 catch { banner = Banner(text: "Ouverture de « \(item.name) » : \(DriveError.wrap(error).errorDescription ?? "échec")", isError: true) }625 }626 func revealInFinder(_ item: DriveItem) async {627 if await !(finderReady ? DriveDomain.shared.reveal(item, rootID: rootID) : false) { banner = Banner(text: "Activez l’intégration au Finder dans les réglages pour afficher cet élément dans le Finder.", isError: false) }628 }629630 // MARK: Offline631 /// Keeps items available offline (pinned): downloaded now, kept up to date, never evicted. Requires the Finder location, which holds the local copies.632 func setPinned(_ items: [DriveItem], _ on: Bool) async {633 guard let store else { return }634 guard finderReady || !on else { banner = Banner(text: "La disponibilité hors ligne utilise l’emplacement SP Drive du Finder : activez-le dans les réglages.", isError: false); return }635 for i in items { try? store.setPinned(i.id, on) }636 revision += 1637 DriveDomain.shared.signalChanges()638 if on {639 // the policy makes the system keep these files; reading them now makes it fetch them now (in the background, two at a time)640 let files = items.flatMap { i in i.isFolder ? ((try? store.subtreeFiles(of: i.id)) ?? []) : [i] }.filter { !isLocal($0.id) }641 pinTask = Task.detached(priority: .utility) { [weak self] in642 var failed = 0643 await withTaskGroup(of: Bool.self) { group in644 var running = 0645 for f in files {646 if running >= 2 { if await group.next() == false { failed += 1 }; running -= 1 }647 group.addTask { do { try await DriveDomain.shared.materialize(f.id); return true } catch { AppEnvironment.log.notice("pinned item not fetched yet: \(String(describing: error), privacy: .public)"); return false } }648 running += 1649 }650 for await ok in group where !ok { failed += 1 }651 }652 let n = failed653 await MainActor.run { [weak self] in654 self?.revision += 1655 if n > 0 { self?.banner = Banner(text: "\(n) élément(s) épinglé(s) n’ont pas encore pu être téléchargés ; macOS réessaiera.", isError: false) }656 }657 }658 }659 }660 /// Removes the local copies and keeps the items on SP Drive. Pinned items and unsent edits are refused by the system.661 @discardableResult func freeUpSpace(_ ids: [String]) async -> (freed: Int, kept: Int) {662 var freed = 0, kept = 0663 for id in ids { do { try await DriveDomain.shared.evict(id); freed += 1 } catch { kept += 1 } }664 revision += 1665 return (freed, kept)666 }667 func freeUpAllUnpinned() async -> (freed: Int, kept: Int) { await freeUpSpace((try? store?.evictableIDs()) ?? []) }668 func cacheBytes() -> Int64 {669 var total: Int64 = 0670 for dir in [cacheDirectory, AppEnvironment.workDirectory] {671 guard let e = FileManager.default.enumerator(at: dir, includingPropertiesForKeys: [.fileSizeKey]) else { continue }672 for case let u as URL in e { total += Int64((try? u.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }673 }674 return total675 }676 /// Empties the preview cache. Staged uploads still waiting in the queue are not touched.677 func clearCache() { try? FileManager.default.removeItem(at: cacheDirectory); revision += 1 }678679 // MARK: Conflicts680 /// The person's decision on a conflict. `.mineAsVersion` makes this Mac's content the new current version of the file681 /// (the server's version stays in the history); nothing is ever replaced without having been named.682 enum ConflictDecision { case keepBoth, mineAsVersion, server }683 @discardableResult func resolve(_ c: SyncConflict, _ decision: ConflictDecision) async -> Bool {684 guard let engine else { return false }685 do {686 switch decision {687 case .keepBoth: try await engine.conflicts.resolve(c, .keepBoth)688 case .server: try await engine.conflicts.resolve(c, .keepServer)689 case .mineAsVersion: try await engine.conflicts.resolveKeepingMineAsNewVersion(c, workDirectory: AppEnvironment.workDirectory, deviceName: AppEnvironment.deviceName)690 }691 await engine.poke(); await reloadLists(); revision += 1; DriveDomain.shared.signalChanges()692 return true693 } catch {694 let e = DriveError.wrap(error)695 banner = Banner(text: e.code == "version_conflict" ? "Le fichier a encore changé sur le serveur : rien n’a été remplacé. Regardez de nouveau les deux versions." : "Conflit : \(e.errorDescription ?? "échec")", isError: true)696 await engine.poke(); await reloadLists()697 return false698 }699 }700 func resolve(_ c: SyncConflict, _ choice: ConflictChoice) async { await resolve(c, choice == .keepBoth ? .keepBoth : choice == .keepServer ? .server : .mineAsVersion) }701}702703/// Darwin notifications (cross-process, no payload) as an async stream.704enum DarwinNotifications {705 static func stream(_ name: String) -> AsyncStream<Void> {706 AsyncStream { continuation in707 let box = Unmanaged.passRetained(Box(continuation))708 CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), box.toOpaque(), { _, observer, _, _, _ in709 guard let observer else { return }710 Unmanaged<Box>.fromOpaque(observer).takeUnretainedValue().continuation.yield()711 }, name as CFString, nil, .deliverImmediately)712 continuation.onTermination = { _ in713 CFNotificationCenterRemoveEveryObserver(CFNotificationCenterGetDarwinNotifyCenter(), box.toOpaque()); box.release()714 }715 }716 }717 private final class Box: @unchecked Sendable { let continuation: AsyncStream<Void>.Continuation; init(_ c: AsyncStream<Void>.Continuation) { continuation = c } }718}719