SPB Git

Repository Public

AppModel.swift 21.4 KB 436 lines swift

1// SP Notes iOS2// File: App/AppModel.swift3// Description: The application model: owns the local store, the session, the sync engine and the attachment files, and exposes4//              every note operation to the screens. Each operation is written to the local database first (offline first) and5//              then scheduled for synchronisation; no screen ever waits for the network to save.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesCore12import SwiftUI13import UIKit14import WidgetKit1516extension AttachmentFiles: AttachmentFileLocating {}1718enum SessionState: Equatable {19    /// No session on this device and no local data: the welcome screen.20    case signedOut21    /// Signed in (the token may still turn out to be expired at the next request).22    case signedIn23    /// The session ended (expired, revoked elsewhere) but notes are on the device: the app keeps working offline and asks to sign in again.24    case expired25}2627@MainActor28@Observable29final class AppModel {30    let configuration: AppConfiguration31    let store: NotesStore32    let api: NotesAPI33    let auth: AuthService34    let engine: SyncEngine35    let files: AttachmentFiles36    let lock: AppLock37    let network = NetworkMonitor()38    let reminders = ReminderScheduler()3940    private(set) var session: SessionState41    private(set) var syncStatus = SyncStatus()42    /// Scoped change counters: screens reload their queries with `.task(id: app.feed.<scope>)` (2.0; replaces the global `revision`).43    let feed: ChangeFeed44    /// Debounced WidgetKit reloads (2.0; 1.0 reloaded every timeline at every store change).45    let widgets: WidgetRefresher46    /// What happened when the database file was opened (a migration from schema v1, the pre-migration copy).47    let openReport: StoreOpenReport?48    /// The 2.0 repositories (tasks, inbox, graph, research…) on top of the same store, client and engine.49    let repositories: NotesRepositories50    private(set) var ownerName: String?51    /// A message for the user that is not tied to a screen (failed import, sync problem needing attention).52    var banner: String?53    /// Navigation requests coming from outside the screens (deep links, widgets, Siri, notifications): delivered once, to one54    /// window (2.0; see `RouteCoordinator`). Setting `pendingRoute` dispatches; reading it gives the route still waiting.55    @ObservationIgnored let routes = RouteCoordinator()56    var pendingRoute: AppRoute? {57        get { routes.pending }58        set { if let newValue { routes.dispatch(newValue) } else { routes.clearPending() } }59    }6061    private var attachmentPaths: [String: String] = [:]62    private var started = false63    private var isImportingShared = false6465    /// Throws `StoreOpenError` when the database file cannot be opened or migrated: the caller shows a blocking screen. There is66    /// deliberately no fallback to an empty in-memory store (the user would see an empty library and lose what is typed).67    init(configuration: AppConfiguration = .current, feed: ChangeFeed? = nil, widgets: WidgetRefresher? = nil) throws {68        self.configuration = configuration69        self.feed = feed ?? ChangeFeed()70        self.widgets = widgets ?? WidgetRefresher { WidgetCenter.shared.reloadAllTimelines() }71        let container = configuration.dataDirectory72        if configuration.inMemoryStore {73            // explicit test configuration only (SPNOTES_STORE=memory, unit tests): never chosen as a substitute for a failing file74            store = try NotesStore.inMemory()75            openReport = nil76            // a throw-away store starts without the Quick Capture draft of an earlier run (UI tests)77            UserDefaults.standard.removeObject(forKey: "capture.draft.v1")78        } else {79            let url = container.appendingPathComponent("notes.sqlite")80            do { try FileManager.default.createDirectory(at: container, withIntermediateDirectories: true) }81            catch { throw StoreOpenError.storage(error.localizedDescription) }82            switch NotesStore.open(url: url) {83            case .opened(let opened, let report): store = opened; openReport = report84            case .failed(let error): throw error85            }86        }87        files = AttachmentFiles(directory: container.appendingPathComponent("Attachments", isDirectory: true))88        let tokenStore: any SessionTokenStore = configuration.injectedToken != nil || configuration.inMemoryStore89            ? InMemoryTokenStore(token: configuration.injectedToken)90            : KeychainTokenStore(configuration: configuration.api)91        let client = HTTPClient(configuration: configuration.api, tokenStore: tokenStore, sessionConfiguration: AppModel.testSessionConfiguration?() ?? .ephemeral)92        api = NotesAPI(client: client)93        auth = AuthService(api: api, authorizer: SystemPasskeyAuthorizer(fallbackRelyingParty: configuration.api.relyingPartyID) { AppModel.presentationAnchor() })94        engine = SyncEngine(store: store, api: api, files: files)95        repositories = NotesRepositories(store: store, api: api, engine: engine)96        lock = AppLock()97        session = tokenStore.load() != nil ? .signedIn : (UserDefaults.standard.bool(forKey: Keys.hadSession) ? .expired : .signedOut)98        if configuration.injectedToken != nil { UserDefaults.standard.set(true, forKey: Keys.hadSession) }99        #if DEBUG100        // UI tests without any server: the app is used locally, as after a session that ended.101        if ProcessInfo.processInfo.environment["SPNOTES_SESSION"] == "local" { session = .expired }102        #endif103        routes.isAccepting = { [weak self] in self?.session != .signedOut }104    }105106    private enum Keys { static let hadSession = "session.had" }107108    static func presentationAnchor() -> UIWindow {109        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }110        let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first111        return scene?.keyWindow ?? scene?.windows.first ?? UIWindow()112    }113114    // MARK: lifecycle115116    /// Starts the observers (store changes, sync status, session events, network). Idempotent.117    func start() {118        guard !started else { return }119        started = true120        Task { [weak self, store] in121            for await change in await store.changes() { self?.storeDidChange(change) }122        }123        Task { [weak self, engine] in124            for await status in await engine.statusUpdates() { self?.syncStatus = status }125        }126        Task { [weak self, api] in127            for await event in await api.client.sessionEvents() { self?.sessionDidChange(event) }128        }129        network.onReconnect = { [weak self] in self?.syncNow() }130        network.start()131        MediaTemp.purge()132        NoteExporter.purgeTemporaryFiles()133        Task {134            if configuration.seedSampleNotes { await SampleData.seed(into: self) }135            #if DEBUG136            openDebugRoute()   // SPNOTES_OPEN=note/<id>[#<blockId>] (UI tests, screenshots) — Features/Editor/NoteEditorModel+Blocks.swift137            #endif138            await loadOwner(); await importSharedItems(); syncNow()139        }140    }141142    private func storeDidChange(_ change: StoreChange) {143        switch change {144        case .attachments(let ids): for id in ids { attachmentPaths[id] = nil }145        case .meta(let key): if key.hasPrefix("user.") || key.hasPrefix("workspace.") { Task { await loadOwner() } }146        default: break147        }148        feed.receive(change)149        widgets.noteChange(change)150    }151152    private func sessionDidChange(_ event: SessionEvent) {153        switch event {154        case .signedIn:155            session = .signedIn156            UserDefaults.standard.set(true, forKey: Keys.hadSession)157            routes.flush()158        case .tokenRotated: break159        case .signedOut: if session == .signedIn { session = .expired }160        }161    }162163    private func loadOwner() async { ownerName = try? await store.meta("user.displayName") }164165    /// The app leaves the foreground: what was being coalesced is delivered now (lists, Home Screen widgets).166    func sceneDidLeaveForeground() {167        feed.flush()168        widgets.flush()169    }170171    func sceneDidBecomeActive() {172        Task { await importSharedItems(); await store.noteExternalChange() }173        syncNow()174    }175176    // MARK: session177178    func signIn() async throws {179        _ = try await auth.signIn()180        session = .signedIn181        UserDefaults.standard.set(true, forKey: Keys.hadSession)182        routes.flush()183        syncNow()184    }185186    /// Ends the session. The notes stay on the device unless `erase` is true (then the local database and files are wiped).187    func signOut(erase: Bool) async {188        await auth.signOut()189        if erase {190            try? await store.wipeAll()191            files.removeAll()192            attachmentPaths.removeAll()193            reminders.cancelAll()194            UserDefaults.standard.set(false, forKey: Keys.hadSession)195            session = .signedOut196        } else {197            session = .expired198        }199        await engine.refreshCounts()200    }201202    // MARK: sync203204    func syncNow() {205        guard session == .signedIn else { return }206        Task { await engine.sync() }207    }208209    @discardableResult210    func syncAndWait() async -> SyncOutcome {211        guard session == .signedIn else { return .signedOut }212        return await engine.sync()213    }214215    private func didWrite() {216        guard session == .signedIn else { Task { await engine.refreshCounts() }; return }217        Task { await engine.schedule() }218    }219220    // MARK: notes — every write is local first221222    /// Creates a note. `markdown` gives its initial content; `isFolder` makes it a folder page.223    @discardableResult224    func createNote(title: String = "", parentId: String? = nil, section: String? = nil, document: NoteDocument? = nil, isFolder: Bool = false, tags: [String] = []) async throws -> String {225        var document = document ?? NoteDocument()226        if document.lines.isEmpty { document = NoteDocument(markdown: "") }227        document.ensureBlockIds()228        let digest = ContentDigest(document: document)229        var parentSection = section230        if parentSection == nil, let parentId, let parent = try await store.summary(id: parentId) { parentSection = parent.section }231        var draft = NewPage(parentId: parentId, section: parentSection ?? "notes", title: title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? Self.untitled : title,232                            content: try document.jsonData(), properties: Data((isFolder ? #"{"folder":true}"# : "{}").utf8),233                            plainText: digest.plainText, wordCount: digest.wordCount, preview: digest.preview, tags: tags)234        if isFolder { draft.icon = "📁" }235        let page = try await store.createPage(draft)236        didWrite()237        return page.id238    }239240    /// The server's name for a note without a title (kept identical so both sides agree).241    static let untitled = "Untitled"242    static func displayTitle(_ title: String) -> String { title == untitled || title.isEmpty ? String(localized: "Sans titre") : title }243244    /// Saves the title and content of a note (autosave of the editor). Returns true when something changed.245    @discardableResult246    /// `fromEditor` marks the autosave of the note being typed (with the title the editor last saved): the lists then catch up247    /// after a pause instead of re-querying at each save, and the editor does not reload its own text.248    func save(noteId: String, title: String, document: NoteDocument, fromEditor: Bool = false, knownTitle: String? = nil) async throws -> Bool {249        var document = document250        document.ensureBlockIds()251        let digest = ContentDigest(document: document)252        let cleanTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)253        let content = try document.jsonData()254        let storedTitle = cleanTitle.isEmpty ? Self.untitled : cleanTitle255        if fromEditor { feed.expectOwnSave(of: noteId, titleChanged: knownTitle.map { $0 != storedTitle } ?? true) }256        let changed: Bool257        do {258            changed = try await store.updateContent(id: noteId, title: storedTitle, content: content,259                                                    plainText: digest.plainText, wordCount: digest.wordCount, preview: digest.preview)260        } catch {261            if fromEditor { feed.cancelOwnSave(of: noteId) }262            throw error263        }264        if changed { didWrite() } else if fromEditor { feed.cancelOwnSave(of: noteId) }265        return changed266    }267268    func rename(_ id: String, to title: String) async throws {269        guard let page = try await store.page(id: id) else { return }270        let clean = title.trimmingCharacters(in: .whitespacesAndNewlines)271        if try await store.updateContent(id: id, title: clean.isEmpty ? Self.untitled : clean, content: nil, plainText: page.plainText, wordCount: page.wordCount, preview: page.preview) { didWrite() }272    }273274    func setPinned(_ id: String, _ value: Bool) async throws { if try await store.setPinned(id: id, value) { didWrite() } }275    func setFavorite(_ id: String, _ value: Bool) async throws { if try await store.setFavorite(id: id, value) { didWrite() } }276    func setArchived(_ id: String, _ value: Bool) async throws { if try await store.setArchived(id: id, value) { didWrite() } }277    func setTags(_ id: String, _ tags: [String]) async throws { if try await store.setTags(id: id, names: tags) { didWrite() } }278    func move(_ id: String, toParent parentId: String?, section: String? = nil) async throws { if try await store.move(id: id, parentId: parentId, section: section) { didWrite() } }279280    func trash(_ id: String) async throws {281        for trashed in try await store.trash(id: id) { reminders.cancel(forNote: trashed) }282        didWrite()283    }284    func restore(_ id: String) async throws { _ = try await store.restore(id: id); didWrite() }285286    /// Permanent deletion. On the server it needs a fresh passkey verification: the request is queued and `syncStatus.needsReauth`287    /// tells the screens to offer the verification.288    func purge(_ id: String) async throws {289        let result = try await store.purge(id: id)290        for path in result.orphanedFiles { files.remove(relativePath: path) }291        didWrite()292    }293294    @discardableResult295    func duplicate(_ id: String) async throws -> String {296        let copy = try await store.duplicate(id: id)297        didWrite()298        return copy.id299    }300301    /// Files an inbox capture as a regular note (optionally in a section).302    func fileInboxItem(_ id: String, section: String = "notes") async throws {303        _ = try await store.setInbox(id: id, at: nil)304        _ = try await store.move(id: id, parentId: nil, section: section)305        _ = try await store.enqueueOp(kind: "triage", targetId: id, payload: try JSONEncoder().encode(QueuedTriage(action: "keep", section: section)))306        didWrite()307    }308309    func markOpened(_ id: String) async { try? await store.markOpened(id: id) }310311    /// Confirms with the passkey so queued permanent deletions can go through, then syncs.312    func confirmPendingDeletions() async throws {313        _ = try await auth.stepUp()314        syncNow()315    }316317    // MARK: attachments318319    /// Adds a file to a note: copied into the app's storage, recorded as waiting for upload. Returns the document node to insert.320    func attach(fileAt url: URL, to noteId: String, filename: String? = nil, mime: String? = nil) async throws -> PMNode {321        let imported = try files.importFile(at: url, filename: filename, mime: mime)322        return try await record(imported, noteId: noteId)323    }324325    func attach(data: Data, filename: String, mime: String? = nil, to noteId: String) async throws -> PMNode {326        let imported = try files.importData(data, filename: filename, mime: mime)327        return try await record(imported, noteId: noteId)328    }329330    private func record(_ imported: ImportedFile, noteId: String) async throws -> PMNode {331        guard imported.size <= 200 << 20 else {332            files.remove(relativePath: imported.relativePath)333            throw AppError.fileTooLarge334        }335        guard !AppModel.refusedMimeTypes.contains(imported.mime) else {336            files.remove(relativePath: imported.relativePath)337            throw AppError.fileTypeRefused338        }339        _ = try await store.addLocalAttachment(id: imported.id, pageId: noteId, filename: imported.filename, mime: imported.mime, size: imported.size, sha256: imported.sha256, localPath: imported.relativePath)340        attachmentPaths[imported.id] = imported.relativePath341        didWrite()342        let src = AttachmentFiles.source(forAttachmentID: imported.id)343        if imported.mime.hasPrefix("image/") { return PMNode.image(src: src, alt: imported.filename, title: imported.filename) }344        return PMNode.fileBlock(src: src, name: imported.filename, size: Int(imported.size), mime: imported.mime, attachmentId: imported.id)345    }346347    /// Types the server refuses (same list): refused here too so nothing waits forever in the upload queue.348    static let refusedMimeTypes: Set<String> = ["application/x-msdownload", "application/x-sh", "text/html", "application/javascript"]349350    /// Makes the files of a note known to the synchronous lookups used while drawing the editor.351    func prepareAttachments(forNote noteId: String) async {352        for record in (try? await store.attachments(pageId: noteId)) ?? [] { if let path = record.localPath { attachmentPaths[record.id] = path } }353    }354355    /// The picture for a document `src`, when it is on the device (synchronous: used while drawing).356    func image(forSource src: String) -> UIImage? {357        guard let id = AttachmentFiles.attachmentID(fromSource: src), let path = attachmentPaths[id] else { return nil }358        return files.image(relativePath: path)359    }360361    /// The local file of an attachment, downloading it if needed.362    func localFile(forAttachment id: String) async throws -> URL {363        if let record = try await store.attachment(id: id), let path = record.localPath, files.exists(relativePath: path) {364            attachmentPaths[id] = path365            try? await store.touchAttachment(id: id)366            return files.url(relativePath: path)367        }368        let url = try await engine.download(attachmentId: id)369        if let record = try await store.attachment(id: id), let path = record.localPath { attachmentPaths[id] = path }370        return url371    }372373    /// Looks a missing picture up (and downloads it); returns true when it is now on the device.374    func resolveImage(source src: String) async -> Bool {375        guard let id = AttachmentFiles.attachmentID(fromSource: src) else { return false }376        return (try? await localFile(forAttachment: id)) != nil377    }378379    func deleteAttachment(_ id: String) async throws {380        if let path = try await store.markAttachmentDeleted(id: id) { files.remove(relativePath: path) }381        attachmentPaths[id] = nil382        didWrite()383    }384385    // MARK: share extension hand-off386387    /// Items saved by the share extension while the app was not running are turned into notes here. One import at a time; an item388    /// is removed from the hand-off folder as soon as its note exists, so a failure on one of its files can never create the note twice.389    func importSharedItems() async {390        guard !isImportingShared else { return }391        isImportingShared = true392        defer { isImportingShared = false }393        let inbox = SharedInbox(container: configuration.dataDirectory)394        for item in inbox.pending() {395            // 2.0: a shared item is an inbox capture with its kind (link, photo, file, note), created under the item's own id:396            // an item whose removal was interrupted finds its page and creates nothing.397            let files = item.files.map { CaptureFile(url: inbox.fileURL(item: item, name: $0), filename: $0) }398            let kind = item.url.flatMap(CaptureKinds.httpURL) != nil ? CaptureKindName.link : CaptureKinds.kind(forFiles: files)399            let draft = CaptureDraft(kind: kind, text: item.text, url: kind == CaptureKindName.link ? item.url : nil)400            guard let outcome = try? await capture(draft, title: item.title, id: item.id, files: files, at: item.createdAt) else {401                banner = String(localized: "Un élément partagé n’a pas pu être importé.")402                continue // the item stays in the folder: nothing was created, the next activation tries again403            }404            inbox.remove(item)405            if outcome.failedFiles > 0 { banner = String(localized: "Un fichier partagé n’a pas pu être joint à la note.") }406        }407    }408}409410enum AppError: LocalizedError {411    case fileTooLarge, fileTypeRefused, noteNotFound412    var errorDescription: String? {413        switch self {414        case .fileTooLarge: return String(localized: "Ce fichier dépasse 200 Mo, la limite du serveur.")415        case .fileTypeRefused: return String(localized: "Ce type de fichier n’est pas accepté.")416        case .noteNotFound: return String(localized: "Cette note n’existe plus.")417        }418    }419}420421/// Where the app can be asked to go from outside its screens.422enum AppRoute: Equatable {423    /// A note, optionally at one of its blocks (2.0: the editor scrolls to the block and flashes it).424    case note(String, blockId: String? = nil)425    case newNote426    case search(String)427    // 2.0 destinations428    case today429    case tasks430    case inbox431    /// Quick capture (`DeepLink.CaptureKind` raw value, nil = the default capture).432    case capture(kind: String? = nil)433    /// A section hosted from `SPNotesFeatures` (`HostedSection.id`: graph, timeline, databases…).434    case section(String)435}436
Files main
Menu

Theme