Repository Public
1// SP Notes iOS2// File: Features/Inbox/InboxModel.swift3// Description: Triage of the inbox. The list is the server's captures when it can be reached (`InboxRepository.items`), merged4// with the inbox pages of the device (captures made offline, as in 1.0); offline it is the last list plus the5// device's pages. Each action — file, archive, delete, turn into a task — goes to the server with an undo6// (`actionId`); when the server cannot be reached the 1.0 local path is used instead (the action is queued and7// sent at the next sync), so an action is never lost.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Observation13import SPNotesCore1415struct InboxEntry: Identifiable, Equatable, Sendable {16 var id: String17 var title: String18 var excerpt: String19 var date: Date?20 /// The server's capture kind (`note`, `link`, `photo`, `audio`…), when known.21 var kind: String?22 var tags: [String] = []23 /// The page is in the local database: it can be opened, and triaged offline.24 var isOnDevice: Bool25 /// Not (yet) in the server's list: captured on this device and waiting to be sent, or the list is older than the page.26 var isDeviceOnly: Bool27}2829enum InboxTriage: Equatable, Sendable {30 case file(section: String)31 case archive32 case trash33 /// Turn the capture into a task.34 case task3536 var serverAction: InboxAction {37 switch self {38 case .file(let section): return .keep(section: PageSection(rawValue: section))39 case .archive: return .archive40 case .trash: return .trash41 case .task: return .task()42 }43 }44}4546/// How a triage can be reversed.47enum InboxUndo: Equatable, Sendable {48 /// Done by the server: its journal reverses it.49 case server(actionId: String)50 /// Done on the device and queued: reversed on the device (the queued action is withdrawn).51 case local(InboxTriage, snapshot: PageSummary, taskId: String?)52}5354struct InboxOutcome: Equatable, Sendable {55 var message: String56 var undo: InboxUndo?57 /// True when the action was written on the device and waits for the network.58 var queued: Bool59}6061/// Where the list shown comes from.62enum InboxOrigin: Equatable, Sendable {63 case server64 /// The last list the server gave, with its date.65 case cache(Date)66 /// The inbox pages of this device only.67 case device68}6970/// The 1.0 local operations the triage falls back to (implemented over `AppModel`; a closure set so the model is testable).71struct InboxLocal: Sendable {72 var summaries: @Sendable () async -> [PageSummary]73 var summary: @Sendable (String) async -> PageSummary?74 var file: @MainActor @Sendable (_ id: String, _ section: String) async throws -> Void75 /// Withdraws a queued filing and puts the page back in the inbox. False when the action was already sent.76 var unfile: @MainActor @Sendable (_ id: String, _ snapshot: PageSummary) async throws -> Bool77 var setArchived: @MainActor @Sendable (_ id: String, _ archived: Bool) async throws -> Void78 var trash: @MainActor @Sendable (_ id: String) async throws -> Void79 var restore: @MainActor @Sendable (_ id: String) async throws -> Void80 var createTask: @MainActor @Sendable (_ title: String, _ pageId: String) async throws -> String81 var deleteTask: @MainActor @Sendable (_ id: String) async throws -> Void82}8384extension InboxLocal {85 @MainActor static func live(_ app: AppModel) -> InboxLocal {86 let store = app.store87 return InboxLocal(88 summaries: { (try? await store.summaries(list: .inbox, limit: 500)) ?? [] },89 summary: { id in (try? await store.summary(id: id)).flatMap { $0 } },90 file: { [weak app] id, section in _ = try await app?.fileInboxItem(id, section: section) },91 unfile: { [weak app] id, snapshot in try await app?.unfileInboxItem(id, restoring: snapshot) ?? false },92 setArchived: { [weak app] id, value in _ = try await app?.setArchived(id, value) },93 trash: { [weak app] id in _ = try await app?.trash(id) },94 restore: { [weak app] id in _ = try await app?.restore(id) },95 createTask: { [weak app] title, pageId in try await app?.repositories.tasks.create(title: title, pageId: pageId).id ?? "" },96 deleteTask: { [weak app] id in _ = try await app?.repositories.tasks.delete(id: id) })97 }98}99100extension AppModel {101 /// Undo of `fileInboxItem` while its action is still queued: the action is withdrawn and the page returns to the inbox, where102 /// it was. Returns false when the action already left for the server (nothing is changed then).103 func unfileInboxItem(_ id: String, restoring snapshot: PageSummary) async throws -> Bool {104 guard let op = try await store.queuedOps().last(where: { $0.kind == "triage" && $0.targetId == id }) else { return false }105 try await store.completeOp(id: op.id)106 _ = try await store.setInbox(id: id, at: snapshot.inboxAt ?? Date())107 _ = try await store.move(id: id, parentId: snapshot.parentId, section: snapshot.section)108 syncNow()109 return true110 }111}112113@MainActor114@Observable115final class InboxModel {116 private(set) var entries: [InboxEntry] = []117 private(set) var origin: InboxOrigin = .device118 private(set) var isLoaded = false119 /// A failure to tell the user; cleared by the screen once shown.120 var notice: String?121122 @ObservationIgnored private let repository: InboxRepository123 @ObservationIgnored private let local: InboxLocal124 /// True when a request to the server makes sense (signed in and the network is up). The server is never called otherwise.125 @ObservationIgnored private let canReachServer: @MainActor () -> Bool126127 init(repository: InboxRepository, local: InboxLocal, canReachServer: @escaping @MainActor () -> Bool) {128 self.repository = repository129 self.local = local130 self.canReachServer = canReachServer131 }132133 convenience init(app: AppModel) {134 self.init(repository: app.repositories.inbox, local: .live(app), canReachServer: { [weak app] in135 guard let app else { return false }136 return app.session == .signedIn && app.network.isOnline137 })138 }139140 // MARK: reading141142 func load() async {143 var listed: Cached<[InboxItem]>?144 if canReachServer() { listed = try? await repository.items(policy: .networkFirst) }145 if listed == nil { listed = try? await repository.items(policy: .cacheOnly) }146 let device = await local.summaries()147 var merged: [InboxEntry] = []148 var seen = Set<String>()149 for item in listed?.value ?? [] {150 let page = await local.summary(item.id)151 // the device is ahead of the list: triaged here (queued), trashed or archived152 if let page, page.inboxAt == nil || page.deletedAt != nil || page.archived { continue }153 seen.insert(item.id)154 merged.append(InboxEntry(id: item.id, title: page?.title ?? item.title, excerpt: item.excerpt ?? page?.preview ?? "", date: item.inboxAt ?? page?.inboxAt,155 kind: item.kind, tags: item.tags ?? page?.tags ?? [], isOnDevice: page != nil, isDeviceOnly: false))156 }157 for page in device where !seen.contains(page.id) && page.deletedAt == nil && !page.archived {158 merged.append(InboxEntry(id: page.id, title: page.title, excerpt: page.preview, date: page.inboxAt, kind: nil, tags: page.tags, isOnDevice: true, isDeviceOnly: listed != nil))159 }160 merged.sort { ($0.date ?? .distantPast) > ($1.date ?? .distantPast) }161 entries = merged162 if let listed { origin = listed.source == .network ? .server : .cache(listed.fetchedAt) } else { origin = .device }163 isLoaded = true164 }165166 // MARK: triage167168 /// Applies an action. Returns what to tell the user (with the undo), or nil when nothing was done (see `notice`).169 @discardableResult170 func perform(_ triage: InboxTriage, on entry: InboxEntry) async -> InboxOutcome? {171 if canReachServer() {172 do {173 let result = try await repository.triage(id: entry.id, triage.serverAction)174 entries.removeAll { $0.id == entry.id }175 return InboxOutcome(message: Self.message(triage, queued: false), undo: .server(actionId: result.actionId), queued: false)176 } catch let error as RepositoryError {177 switch error {178 case .offline, .signedOut, .notFound: break // the device does it and queues it (a page captured offline is not on the server yet)179 case .server(let api) where api.isNotFound: break180 default:181 notice = error.errorDescription182 await load()183 return nil184 }185 } catch {186 notice = AppModel.describe(error)187 return nil188 }189 }190 return await performLocally(triage, on: entry)191 }192193 private func performLocally(_ triage: InboxTriage, on entry: InboxEntry) async -> InboxOutcome? {194 guard let snapshot = await local.summary(entry.id) else {195 notice = String(localized: "Cette capture n’est pas encore sur cet appareil : l’action sera possible une fois la synchronisation faite.")196 return nil197 }198 do {199 var taskId: String?200 switch triage {201 case .file(let section): try await local.file(entry.id, section)202 case .archive: try await local.setArchived(entry.id, true)203 case .trash: try await local.trash(entry.id)204 case .task:205 // offline equivalent of the server's action: a task linked to the capture, the capture filed in Notes206 taskId = try await local.createTask(NoteTitle.display(snapshot.title), entry.id)207 try await local.file(entry.id, "notes")208 }209 entries.removeAll { $0.id == entry.id }210 return InboxOutcome(message: Self.message(triage, queued: true), undo: .local(triage, snapshot: snapshot, taskId: taskId), queued: true)211 } catch let error as RepositoryError {212 notice = error.errorDescription213 return nil214 } catch {215 notice = AppModel.describe(error)216 return nil217 }218 }219220 /// Reverses a triage. Returns false (with a notice) when it could not be reversed.221 @discardableResult222 func undo(_ undo: InboxUndo) async -> Bool {223 do {224 switch undo {225 case .server(let actionId):226 _ = try await repository.undo(actionId: actionId)227 case .local(let triage, let snapshot, let taskId):228 switch triage {229 case .file, .task:230 if let taskId { try await local.deleteTask(taskId) }231 guard try await local.unfile(snapshot.id, snapshot) else {232 notice = String(localized: "L’action était déjà envoyée au serveur : elle ne peut plus être annulée ici.")233 await load()234 return false235 }236 case .archive: try await local.setArchived(snapshot.id, false)237 case .trash: try await local.restore(snapshot.id)238 }239 }240 await load()241 return true242 } catch let error as RepositoryError {243 notice = error == .offline ? String(localized: "L’annulation demande une connexion. Rien n’a été modifié.") : error.errorDescription244 return false245 } catch {246 notice = AppModel.describe(error)247 return false248 }249 }250251 static func message(_ triage: InboxTriage, queued: Bool) -> String {252 let base: String253 switch triage {254 case .file(let section): base = String(localized: "Classée dans \(NoteSection.title(section))")255 case .archive: base = String(localized: "Capture archivée")256 case .trash: base = String(localized: "Déplacée dans la corbeille")257 case .task: base = String(localized: "Convertie en tâche")258 }259 return queued ? base + String(localized: " — sera envoyé au retour du réseau") : base260 }261}262