Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/AppEnvironment.swift3// Description: Dependency container of the app: launch options, server configuration, API client, local store, attachment files, synchronisation, account, library, open note sessions.4import SwiftUI5import Network6import CryptoKit7import SPNotesCore8import SPNotesDocument9import SPNotesStore10import SPNotesAPI11import SPNotesSync1213/// What the process was asked to do at launch. Overrides exist for development and automated tests only: a14/// non-production server must be a loopback address, and a session can be injected only in DEBUG builds.15struct LaunchOptions {16 var server = URL(string: "https://note.spboucher.ai")!17 var dataDirectory: URL?18 var injectedSessionToken: String?19 var inMemory = false20 var isUITest = false21 var isHostedTest = false22 /// The network is treated as unreachable (offline scenario of the test plan). Can be toggled at run time in DEBUG.23 var forceOffline = false24 var openNote: String?25 var route: String?26 /// DEBUG: the main window is put on screen without activating the application (screenshots never take the keyboard).27 var noActivate = false28 /// Tests and DEBUG screenshots: behave as if the database could not be opened (the blocking screen, nothing written).29 var simulatedStoreFailure: StoreOpenError?30 /// Tests: the URL session of the API client (an in-memory fake of the backend behind a URLProtocol).31 var sessionConfiguration: URLSessionConfiguration?32 /// Tests: preferences in a throw-away suite, never the application's own defaults.33 var isolatedPreferences = false34 /// DEBUG: sample library for screenshots (only with -SPNotesInMemory), and a forced appearance.35 var demo = false36 var appearance: String?3738 static func current(arguments: [String] = ProcessInfo.processInfo.arguments, environment: [String: String] = ProcessInfo.processInfo.environment) -> LaunchOptions {39 var o = LaunchOptions()40 func value(_ flag: String) -> String? { arguments.firstIndex(of: flag).flatMap { arguments.indices.contains($0 + 1) ? arguments[$0 + 1] : nil } }41 #if DEBUG42 if let s = value("-SPNotesServer") ?? environment["SPNOTES_SERVER"], let url = URL(string: s), let host = url.host, host == "localhost" || host == "127.0.0.1" { o.server = url }43 o.injectedSessionToken = environment["SPNOTES_SESSION_TOKEN"]44 o.isUITest = arguments.contains("-SPNotesUITest")45 o.forceOffline = arguments.contains("-SPNotesOffline")46 o.openNote = value("-SPNotesOpen"); o.route = value("-SPNotesRoute")47 o.noActivate = arguments.contains("-SPNotesNoActivate")48 o.demo = arguments.contains("-SPNotesDemo"); o.appearance = value("-SPNotesAppearance")49 if o.demo, o.openNote == nil, o.route == nil { o.openNote = DemoLibrary.noteId }50 if arguments.contains("-SPNotesStoreFailure") { o.simulatedStoreFailure = .migrationFailed(from: 1, to: 2, reason: "simulated", backupURL: nil) }51 #endif52 if let d = value("-SPNotesDataDir") { o.dataDirectory = URL(fileURLWithPath: (d as NSString).expandingTildeInPath, isDirectory: true) }53 o.inMemory = arguments.contains("-SPNotesInMemory")54 // hosting unit tests: the app process must not open the production UI, the Keychain or the network on its own55 if environment["XCTestConfigurationFilePath"] != nil, !o.isUITest { o.isHostedTest = true; o.inMemory = true }56 return o57 }58}5960/// Network reachability (NWPathMonitor). Used to pause and resume synchronisation — never to block local work.61@Observable final class Connectivity {62 private(set) var isOnline = true63 /// Development / test switch: behaves as if the Mac had no network.64 var forcedOffline = false { didSet { onChange?() } }65 var reachable: Bool { isOnline && !forcedOffline }66 @ObservationIgnored var onChange: (() -> Void)?67 @ObservationIgnored private let monitor = NWPathMonitor()6869 init() {70 monitor.pathUpdateHandler = { [weak self] path in71 let online = path.status == .satisfied72 Task { @MainActor in guard let self, self.isOnline != online else { return }; self.isOnline = online; self.onChange?() }73 }74 monitor.start(queue: DispatchQueue(label: "ai.spboucher.spnotes.connectivity"))75 }76 deinit { monitor.cancel() }77}7879/// Where attachment files live: `<data>/files/<id>.<ext>`, relative paths stored in the database.80nonisolated struct AttachmentFiles: AttachmentFileLocating {81 let directory: URL82 init(directory: URL) { self.directory = directory; try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) }83 func url(relativePath: String) -> URL {84 // a path from the database is never trusted to stay inside the directory85 let name = (relativePath as NSString).lastPathComponent86 return directory.appendingPathComponent(name.isEmpty || name == "." || name == ".." ? "invalid" : name)87 }88 func relativePath(id: String, filename: String) -> String {89 let ext = (filename as NSString).pathExtension.lowercased().filter { $0.isLetter || $0.isNumber }.prefix(8)90 let safeId = id.lowercased().filter { $0.isHexDigit || $0 == "-" }91 return ext.isEmpty ? safeId : "\(safeId).\(ext)"92 }93 func remove(relativePath: String) { try? FileManager.default.removeItem(at: url(relativePath: relativePath)) }94 static func sha256(of url: URL) -> String? {95 guard let h = try? FileHandle(forReadingFrom: url) else { return nil }96 defer { try? h.close() }97 var hasher = SHA256()98 while let chunk = try? h.read(upToCount: 1 << 20), !chunk.isEmpty { hasher.update(data: chunk) }99 return hasher.finalize().map { String(format: "%02x", $0) }.joined()100 }101}102103@Observable final class AppEnvironment {104 let options: LaunchOptions105 let configuration: APIConfiguration106 let http: HTTPClient107 let api: NotesAPI108 let auth: AuthService109 let store: NotesStore110 let files: AttachmentFiles111 let sync: SyncEngine112 let preferences: Preferences113 let connectivity = Connectivity()114 let toasts = ToastCenter()115 let account: AccountModel116 let library: LibraryModel117 let syncMonitor: SyncMonitor118 let lock: AppLock119 let dataDirectory: URL120 @ObservationIgnored private var sessions: [String: NoteSession] = [:]121 @ObservationIgnored var started = false122 /// Place that the front window should show (deep link, quick note, Spotlight, notification).123 var navigationRequest: NavigationRequest?124 struct NavigationRequest: Equatable { enum Target: Equatable { case page(Route), destination(Destination) }; let id = UUID(); let target: Target }125 /// Repositories of SPNotesCore 2.0 (tasks, inbox, graph, search…) over this store, client and engine.126 let repositories: NotesRepositories127 let tasks: TasksModel128 let inbox: InboxModel129 let platform: PlatformServices130 /// Provider of the feature screens (see `FeatureHosting`).131 var features: any FeatureHosting = FeaturesHost()132 /// What the server supports (`GET /api/meta`), nil while it was never asked (local use, 2.x server unknown yet). The133 /// sidebar lists a server screen only when its feature is announced.134 private(set) var serverMeta: ServerMeta?135 func refreshServerFeatures() async { let m = await repositories.features(); if m != serverMeta { serverMeta = m } }136 /// Provider of the detail views of the 3.0 blocks (see `BlockDetailProviding`).137 var blockDetails: any BlockDetailProviding = FeaturesBlockDetails()138 /// The one command registry of the application (SPNotesFeatures) and what goes with it.139 let featureServices = FeatureServices()140141 init(options: LaunchOptions = .current()) {142 self.options = options143 let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "2.0.0"144 configuration = APIConfiguration(baseURL: options.server, userAgent: APIConfiguration.userAgent(appVersion: version))145 let transient = options.inMemory || options.isUITest146 let tokens: any SessionTokenStore = transient || options.injectedSessionToken != nil ? InMemoryTokenStore(token: options.injectedSessionToken) : SessionKeychain.store(configuration: configuration)147 let apiConfiguration = configuration148 if let session = options.sessionConfiguration { http = HTTPClient(configuration: apiConfiguration, tokenStore: tokens, sessionConfiguration: session) } else { http = HTTPClient(configuration: apiConfiguration, tokenStore: tokens) }149 api = NotesAPI(client: http)150 auth = AuthService(api: api, authorizer: SystemPasskeyAuthorizer(fallbackRelyingParty: configuration.relyingPartyID) { NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible } ?? ASPresentationAnchorFallback.window })151152 let base = options.dataDirectory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("SPNotes", isDirectory: true)153 let dir = transient && options.dataDirectory == nil ? FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-\(UUID().uuidString)", isDirectory: true) : base154 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)155 dataDirectory = dir156 let host = options.server.host ?? "local"157 // The store is the user's data. A file that cannot be opened (damaged, written by a newer version, failed migration,158 // full disk) is NEVER replaced by an empty one the owner could type into: `storeFailure` blocks the whole interface159 // (StoreFailureView), nothing starts, nothing is written. The placeholder below only exists because the object graph160 // needs a store; every entry point that could write checks `isBlocked` first.161 let storeURL = dir.appendingPathComponent("notes-\(host).sqlite")162 self.storeURL = storeURL163 switch NotesStore.open(url: storeURL, backupRetention: Self.backupRetention) {164 case .opened(let opened, let report): store = opened; storeReport = report; storeFailure = options.simulatedStoreFailure165 case .failed(let error):166 NSLog("SPNotes: cannot open the local store: %@", String(describing: error))167 store = try! NotesStore.inMemory(); storeReport = nil; storeFailure = error168 }169 files = AttachmentFiles(directory: dir.appendingPathComponent("files-\(host)", isDirectory: true))170 sync = SyncEngine(store: store, api: api, files: files)171172 let transientSuite = "ai.spboucher.spnotes.transient.\(UUID().uuidString)"173 preferences = Preferences(defaults: transient || options.isolatedPreferences ? (UserDefaults(suiteName: transientSuite) ?? .standard) : .standard)174 if transient || options.isolatedPreferences { UserDefaults.standard.removePersistentDomain(forName: transientSuite) }175 connectivity.forcedOffline = options.forceOffline176 if let a = options.appearance.flatMap(AppearanceMode.init(rawValue:)) { preferences.appearance = a }177 if options.demo, options.route != "welcome" { preferences.welcomeDone = true }178 account = AccountModel(http: http, api: api, auth: auth, hasToken: tokens.load() != nil)179 library = LibraryModel(store: store, preferences: preferences)180 syncMonitor = SyncMonitor(engine: sync, store: store)181 lock = AppLock(preferences: preferences)182 repositories = NotesRepositories(store: store, api: api, engine: sync)183 tasks = TasksModel(repositories: repositories); inbox = InboxModel(store: store, repositories: repositories); platform = PlatformServices()184 library.env = self; syncMonitor.env = self; account.env = self; tasks.env = self; inbox.env = self; platform.env = self185 connectivity.onChange = { [weak self] in self?.syncMonitor.connectivityChanged() }186 }187 /// Why the local database could not be opened; non-nil means the application shows the blocking error screen only.188 let storeFailure: StoreOpenError?189 /// What opening the database did (migration, pre-migration backup); nil when it failed.190 let storeReport: StoreOpenReport?191 let storeURL: URL192 var isBlocked: Bool { storeFailure != nil }193 /// The copy made before a schema migration is kept 30 days (Core's default is 10 minutes): it is what lets the owner go194 /// back to SP Notes 1.x, which cannot open a migrated file.195 static let backupRetention: TimeInterval = 30 * 86_400196197 /// One session per note, shared by every window that shows it (two windows on one note edit the same text view model).198 func session(for id: String) async -> NoteSession? {199 guard !isBlocked else { return nil }200 if let s = sessions[id] { return s }201 guard let page = try? await store.page(id: id) else { return nil }202 if let s = sessions[id] { return s }203 let s = NoteSession(page: page, env: self)204 sessions[id] = s205 return s206 }207 func existingSession(_ id: String) -> NoteSession? { sessions[id] }208 var openSessions: [NoteSession] { Array(sessions.values) }209 func forget(noteId: String) { sessions[noteId] = nil }210211 /// Writes every pending keystroke to disk (window closing, application quitting, lock, forced save).212 func flushAll() async { for s in sessions.values { await s.saveNow(reason: nil) } }213214 func open(noteId: String) { open(Route(pageId: noteId)) }215 func open(_ route: Route) { navigationRequest = NavigationRequest(target: .page(route)) }216 func show(_ destination: Destination) { navigationRequest = NavigationRequest(target: .destination(destination)) }217218 /// Local file of an attachment referenced by a document source (`/api/files/<id>`), when it is on this Mac.219 func localImage(for src: String) -> NSImage? { ImageCache.shared.image(src: src, env: self) }220}221222enum ASPresentationAnchorFallback { @MainActor static let window = NSWindow() }223