SPB Git

Repository Public

DriveServices.swift 5.4 KB 94 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: FileProviderExtension/DriveServices.swift3// Description: The engine objects of the File Provider extension for the signed-in account (API, mirror, transfer engines), and the translation between SP Drive errors and the errors the system understands.4import FileProvider5import Foundation6import OSLog7import SPDriveCore8import SPDriveSync910final class DriveServices: Sendable {11    let api: APIClient12    let store: MetadataStore13    let uploader: UploadEngine14    let downloader: DownloadEngine15    let detector: ChangeDetector16    let conflicts: ConflictResolver17    static let log = Logger(subsystem: AppEnvironment.appBundleID, category: "fileprovider")1819    /// Throws `.notAuthenticated` when nobody is signed in on this Mac: the system then shows the location as needing sign-in.20    init() throws {21        guard let store = try AppEnvironment.openStore(), (try? AppEnvironment.tokens.readToken()) != nil else { throw NSFileProviderError(.notAuthenticated) }22        self.store = store23        api = try AppEnvironment.makeAPI()24        uploader = UploadEngine(api: api, store: store, deviceName: AppEnvironment.deviceName)25        downloader = DownloadEngine(api: api)26        detector = ChangeDetector(api: api, store: store)27        conflicts = ConflictResolver(api: api, store: store)28    }2930    var rootID: String? { store.rootID }31    func requireRoot() async throws -> String {32        if let r = store.rootID { return r }33        let c = try await api.syncCursor()34        try store.setMeta("root", c.rootId)35        return c.rootId36    }37    func fpItem(_ item: DriveItem) -> FileProviderItem? {38        guard let root = store.rootID else { return nil }39        return FileProviderItem(item, rootID: root, pinned: (try? store.isPinned(item.id)) ?? false, shared: sharedIDs().contains(item.id))40    }41    /// Items with an active share link, as last written by the application (`shared_ids` in the mirror); re-read at most every two seconds.42    private let sharedCache = SharedCache()43    final class SharedCache: @unchecked Sendable { let lock = NSLock(); var ids: Set<String> = []; var at = Date.distantPast }44    func sharedIDs() -> Set<String> {45        sharedCache.lock.withLock {46            if Date().timeIntervalSince(sharedCache.at) > 2 {47                sharedCache.ids = Set(((try? store.meta("shared_ids")) ?? nil ?? "").split(separator: ",").map(String.init)); sharedCache.at = Date()48            }49            return sharedCache.ids50        }51    }52    func forgetSharedCache() { sharedCache.lock.withLock { sharedCache.at = .distantPast } }53    /// Refreshes the mirror from the server when it is reachable; silent otherwise (the mirror then answers as it is).54    func pull() async {55        do { try await detector.pull() } catch { DriveServices.log.info("pull skipped: \(DriveError.wrap(error).code, privacy: .public)") }56    }57    /// Current description of an item: from the server when reachable, from the mirror otherwise.58    func fresh(_ id: String, kind: ItemKind? = nil) async throws -> DriveItem {59        do {60            let sel = kind == .file ? Selection(fileIds: [id]) : kind == .folder ? Selection(folderIds: [id]) : Selection(fileIds: [id], folderIds: [id])61            guard let item = try await api.items(sel).all.first else { try? store.remove([id]); throw DriveError.server(status: 404, code: "not_found", message: "", extra: [:]) }62            try store.upsert([item])63            return item64        } catch {65            let e = DriveError.wrap(error)66            if e.isTransient, let known = try store.item(id) { return known }67            throw e68        }69    }7071    /// The error the system should see. It decides what the system does next: retry later, ask to sign in, re-create the item…72    func fpError(_ error: Error) -> NSError {73        if let ns = error as NSError?, ns.domain == NSFileProviderErrorDomain || ns.domain == NSCocoaErrorDomain { return ns }74        let e = DriveError.wrap(error)75        switch e {76        case .offline: return NSFileProviderError(.serverUnreachable) as NSError77        case .unauthenticated: return NSFileProviderError(.notAuthenticated) as NSError78        case .cancelled: return NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError)79        case .integrity: return NSFileProviderError(.cannotSynchronize, userInfo: [NSLocalizedDescriptionKey: e.errorDescription ?? ""]) as NSError80        case .server(let status, let code, _, _):81            if code == "not_found" { return NSFileProviderError(.noSuchItem) as NSError }82            if code == "quota_exceeded" || code == "file_too_large" { return NSFileProviderError(.insufficientQuota) as NSError }83            if status >= 500 || status == 429 { return NSFileProviderError(.serverUnreachable) as NSError }84            return NSFileProviderError(.cannotSynchronize, userInfo: [NSLocalizedDescriptionKey: e.errorDescription ?? code]) as NSError85        default: return NSFileProviderError(.cannotSynchronize, userInfo: [NSLocalizedDescriptionKey: e.errorDescription ?? e.code]) as NSError86        }87    }88    /// Names the system and applications create next to documents and that must never travel: they stay on this Mac.89    static func isExcluded(_ name: String) -> Bool {90        let lower = name.lowercased()91        return name.hasPrefix(".") || name.hasPrefix("~$") || lower == "icon\r" || lower == "thumbs.db" || lower == "desktop.ini" || lower.hasSuffix(".tmp") || lower.hasSuffix(".sb-") || name.contains(".sb-")92    }93}94
Files main
Menu

Theme