Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/NextSettings.swift3// Description: Settings panes that used to exist on the web only — storage (server quota per mailbox, what this device keeps), the vacation4// responder (written into the mailbox's single « spmail » Sieve script, exactly as the web client does, so delivery rules stay active),5// and rules: the delivery filters (read-only here, edited on the web) and the automation rules (enable / disable, run history).6import SPMailCore7import SwiftUI89extension AppConfig {10 /// Where delivery filters and automation rules are edited in this release.11 static var webSettingsURL: URL { baseURL.appendingPathComponent("settings") }12}1314/// The mailbox a per-mailbox settings pane is about.15private struct MailboxPicker: View {16 let model: AppModel17 @Binding var account: String18 var body: some View {19 if model.accounts.count > 1 { Picker("Boîte", selection: $account) { ForEach(model.accounts) { Text($0.address).tag($0.id) } } }20 }21}2223// MARK: - storage2425struct StorageSettings: View {26 @Bindable var model: AppModel27 @State private var quotas: [String: [Quota]] = [:]28 @State private var cached: [String: Int] = [:]29 @State private var attachmentCache = 030 @State private var loading = true31 @State private var offline = false3233 var body: some View {34 Form {35 Section {36 ForEach(model.accounts) { box in37 let quota = quotas[box.id]?.first { $0.resourceType == "octets" } ?? quotas[box.id]?.first38 let fallback = model.next.dashboard?.storage.first { $0.mailboxId == box.id }39 if let quota { StorageMeter(title: box.address, used: quota.used, quota: quota.hardLimit) } else if let fallback { StorageMeter(title: box.address, used: fallback.usedBytes, quota: fallback.quotaBytes) } else {40 LabeledContent(box.address, value: loading ? L("Chargement") : L("Indisponible"))41 }42 }43 } header: { Text("Sur le serveur") } footer: {44 Text(offline ? L("Hors ligne — dernières valeurs connues, quand il y en a.") : L("Espace occupé par chaque boîte sur le serveur de courrier, et son quota quand il y en a un."))45 }46 Section {47 ForEach(model.accounts) { box in LabeledContent(box.address, value: L("\(cached[box.id] ?? 0) messages en cache")) }48 LabeledContent("Pièces jointes en cache", value: attachmentCache.byteLabel)49 Button("Vider le cache des pièces jointes") { Task { try? await model.store?.purgeAttachmentCache(); await loadLocal() } }.disabled(attachmentCache == 0)50 } header: { Text("Sur cet appareil") } footer: {51 Text("Le cache est chiffré sur cet appareil. Le vider ne supprime rien sur le serveur : les pièces jointes seront retéléchargées à la demande.")52 }53 }54 .formStyle(.grouped)55 .task { await load() }56 }5758 private func loadLocal() async {59 guard let store = model.store else { return }60 attachmentCache = (try? await store.attachmentCacheSize()) ?? 061 for box in model.accounts { cached[box.id] = (try? await store.emailCount(box.id)) ?? 0 }62 }63 private func load() async {64 await loadLocal()65 loading = true66 for box in model.accounts {67 do { quotas[box.id] = try await model.engines[box.id]?.quota() ?? [] } catch { if (error as? APIError)?.isOffline == true { offline = true } }68 }69 if model.next.dashboard == nil { _ = await model.next.loadDashboard() }70 loading = false71 }72}7374// MARK: - vacation responder7576struct VacationSettings: View {77 @Bindable var model: AppModel78 @State private var account = ""79 @State private var state: SieveState?80 @State private var vacation = VacationConfig()81 @State private var hasStart = false82 @State private var hasEnd = false83 @State private var start = Date()84 @State private var end = Date().addingTimeInterval(7 * 86_400)85 @State private var status: String?86 @State private var failure: String?87 @State private var loading = true88 @State private var saving = false8990 private var editable: Bool { state != nil && state?.custom != true && !loading && !saving && model.isOnline }91 private var current: VacationConfig {92 var v = vacation93 v.from = hasStart ? VacationConfig.day(start) : nil94 v.to = hasEnd ? VacationConfig.day(end) : nil95 return v96 }97 private var isDirty: Bool { state.map { $0.config.vacation != current } ?? false }9899 var body: some View {100 Form {101 MailboxPicker(model: model, account: $account)102 if let state, state.custom {103 Section {104 Label("Cette boîte utilise un script de filtrage écrit à la main. Pour ne pas l’écraser, la réponse automatique se règle sur le web.", systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.warn)105 Link(destination: AppConfig.webSettingsURL) { Label("Ouvrir les réglages sur le web", systemImage: "arrow.up.forward.app") }106 }107 } else {108 Section {109 Toggle("Répondre automatiquement", isOn: $vacation.enabled)110 TextField("Objet (facultatif)", text: $vacation.subject)111 VStack(alignment: .leading) {112 Text("Message").font(.subheadline).foregroundStyle(.secondary)113 TextEditor(text: $vacation.text).frame(minHeight: 110).font(.body).accessibilityLabel(Text("Message de réponse automatique"))114 }115 if vacation.enabled, vacation.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { Text("Sans message, aucune réponse n’est envoyée.").font(.footnote).foregroundStyle(SPColor.warn) }116 } footer: { Text("Chaque expéditeur reçoit au plus une réponse par période ; les listes de diffusion et les messages automatiques n’en reçoivent pas.") }117 Section("Période") {118 Toggle("À partir du", isOn: $hasStart)119 if hasStart { DatePicker("Premier jour", selection: $start, displayedComponents: .date) }120 Toggle("Jusqu’au", isOn: $hasEnd)121 if hasEnd { DatePicker("Dernier jour (inclus)", selection: $end, in: (hasStart ? start : .distantPast)..., displayedComponents: .date) }122 Stepper("Au plus une réponse tous les \(vacation.days) jours par expéditeur", value: $vacation.days, in: 1...30)123 }124 Section {125 Button(saving ? L("Enregistrement…") : L("Enregistrer")) { Task { await save() } }.disabled(!editable || !isDirty)126 if state?.legacyVacation == true { Text("Une réponse automatique créée par une autre application est active ; elle sera remplacée par celle-ci à l’enregistrement.").font(.footnote).foregroundStyle(.secondary) }127 if let rules = state?.config.rules.count, rules > 0 { Text("Les \(rules) filtres de cette boîte sont conservés tels quels.").font(.footnote).foregroundStyle(.secondary) }128 if let status { Label(status, systemImage: "checkmark.circle").foregroundStyle(SPColor.ok) }129 if let failure { Text(failure).foregroundStyle(SPColor.danger) }130 if !model.isOnline { Label("Hors ligne : la réponse automatique se règle en ligne.", systemImage: "wifi.slash").foregroundStyle(.secondary) }131 }132 }133 }134 .formStyle(.grouped)135 .disabled(loading && state == nil)136 .overlay { if loading, state == nil { ProgressView() } }137 .task { if account.isEmpty { account = model.currentAccount ?? model.accounts.first?.id ?? "" }; await load() }138 .onChange(of: account) { _, _ in Task { await load() } }139 }140141 private func adopt(_ s: SieveState) {142 state = s143 vacation = s.config.vacation144 hasStart = VacationConfig.isDate(vacation.from); hasEnd = VacationConfig.isDate(vacation.to)145 if let d = VacationConfig.date(vacation.from) { start = d }146 if let d = VacationConfig.date(vacation.to) { end = d }147 }148149 private func load() async {150 guard let engine = model.engines[account] else { loading = false; return }151 loading = true; status = nil; failure = nil152 defer { loading = false }153 do { adopt(try await SieveService(jmap: engine.jmap).load()) } catch { state = nil; failure = model.describe(error) }154 }155156 private func save() async {157 guard let engine = model.engines[account], let previous = state else { return }158 saving = true; status = nil; failure = nil159 defer { saving = false }160 var config = previous.config161 config.vacation = current162 let trash = model.mailboxes(for: account).first { $0.knownRole == .trash }?.name ?? "Deleted Items"163 do {164 adopt(try await SieveService(jmap: engine.jmap).save(config, previous: previous, trashFolder: trash))165 status = current.isEffective ? L("Réponse automatique activée sur le serveur") : L("Réponse automatique désactivée")166 } catch let e as JMAPMethodError { failure = L("Le serveur a refusé le script : ") + (e.errorDescription ?? e.type) } catch { failure = model.describe(error) }167 }168}169170// MARK: - rules171172extension SieveRule {173 /// « De contient x ou Objet est y → déplacer vers Compta, marquer comme lu ».174 var summary: String {175 let tests = conditions.map { c in176 let field = c.field == "from" ? L("De") : c.field == "to" ? L("À") : c.field == "subject" ? L("Objet") : c.field177 return "\(field) \(c.op == "is" ? L("est") : L("contient")) « \(c.value) »"178 }.joined(separator: match == "any" ? L(" ou ") : L(" et "))179 let effects = actions.map { a in180 switch a { case .move(let f): L("déplacer vers \(f)"); case .markRead: L("marquer comme lu"); case .flag: L("ajouter un drapeau"); case .trash: L("mettre à la corbeille"); case .unknown(let t): t }181 }.joined(separator: ", ")182 return "\(tests) → \(effects)"183 }184}185186extension MailRule {187 @MainActor func summary(labels: [MailLabel]) -> String {188 let tests = conditions.map { c -> String in189 switch c {190 case .text(let field, let op, let value):191 let f = field == .from ? L("De") : field == .to ? L("À") : field == .subject ? L("Objet") : L("Liste")192 return "\(f) \(op == .equals ? L("est") : op == .matchesDomain ? L("du domaine") : L("contient")) « \(value) »"193 case .hasAttachment(let b): return b ? L("avec pièce jointe") : L("sans pièce jointe")194 case .isNewsletter(let b): return b ? L("infolettre") : L("pas une infolettre")195 case .aiCategory(let c): return L("catégorie \(TriageCategory(tolerant: c).title)")196 case .sizeGreaterThan(let n): return L("plus de \(n.byteLabel)")197 case .unknown: return L("condition non reconnue")198 }199 }.joined(separator: match == .any ? L(" ou ") : L(" et "))200 let effects = actions.map { a -> String in201 switch a {202 case .label(let id): return L("libellé \(labels.first { $0.id == id }?.name ?? "?")")203 case .star: return L("ajouter un drapeau"); case .markRead: return L("marquer comme lu"); case .pin: return L("épingler")204 case .snooze: return L("mettre en veille"); case .remind(let h): return L("rappel après \(Int(h)) h"); case .event(let n): return L("événement \(n)")205 case .notifyApp(let app): return L("notifier \(app)"); case .draftReply: return L("préparer un brouillon de réponse"); case .extract: return L("extraire des champs")206 case .unknown: return L("action non reconnue")207 }208 }.joined(separator: ", ")209 return tests.isEmpty ? effects : "\(tests) → \(effects)"210 }211}212213extension RuleRunStatus {214 var label: (text: String, icon: String, color: SPToken) {215 switch self {216 case .ok: (L("Exécutée"), "checkmark.circle", SPColor.ok); case .partial: (L("Partielle"), "exclamationmark.circle", SPColor.warn); case .error: (L("Échec"), "xmark.octagon", SPColor.danger)217 case .running: (L("En cours"), "arrow.triangle.2.circlepath", SPColor.text3); case .interrupted: (L("Interrompue"), "pause.circle", SPColor.warn); case .unknown: (L("Inconnu"), "questionmark.circle", SPColor.text3)218 }219 }220}221222struct RulesSettings: View {223 @Bindable var model: AppModel224 @State private var account = ""225 @State private var sieve: SieveState?226 @State private var sieveError: String?227 @State private var rules: [MailRule] = []228 @State private var rulesError: String?229 @State private var runs: [String: [RuleRun]] = [:]230 @State private var expanded: Set<String> = []231 @State private var loading = true232233 var body: some View {234 Form {235 Section {236 MailboxPicker(model: model, account: $account)237 if let sieve {238 if sieve.custom { Label("Script écrit à la main : il s’affiche et se modifie sur le web.", systemImage: "doc.plaintext").foregroundStyle(.secondary) }239 ForEach(sieve.config.rules) { rule in240 VStack(alignment: .leading, spacing: 2) {241 HStack { Text(rule.name.isEmpty ? L("Filtre sans nom") : rule.name); Spacer(); if !rule.enabled { Text("Désactivé").font(.caption).foregroundStyle(.secondary) } }242 Text(rule.summary).font(.footnote).foregroundStyle(.secondary)243 }244 .accessibilityElement(children: .combine)245 }246 if sieve.config.rules.isEmpty, !sieve.custom { Text("Aucun filtre pour cette boîte").foregroundStyle(.secondary) }247 if !sieve.active, sieve.scriptId != nil { Label("Ce script n’est pas celui que le serveur exécute actuellement.", systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(SPColor.warn) }248 } else if let sieveError { Text(sieveError).foregroundStyle(.secondary) } else if loading { ProgressView().controlSize(.small) }249 Link(destination: AppConfig.webSettingsURL) { Label("Modifier les filtres sur le web", systemImage: "arrow.up.forward.app") }250 } header: { Text("Filtres à la livraison") } footer: {251 Text("Les filtres (Sieve) s’exécutent sur le serveur à l’arrivée du courrier : classer, marquer, supprimer. Ils se lisent ici et se modifient sur le web dans cette version.")252 }253 if model.next.has(.rules) {254 Section {255 ForEach(rules) { rule in256 DisclosureGroup(isExpanded: Binding(get: { expanded.contains(rule.id) }, set: { open in if open { expanded.insert(rule.id); Task { await loadRuns(rule) } } else { expanded.remove(rule.id) } })) {257 if let list = runs[rule.id] {258 if list.isEmpty { Text("Aucune exécution pour l’instant").font(.footnote).foregroundStyle(.secondary) }259 ForEach(list) { run in260 let label = run.status.label261 HStack(spacing: SPSpacing.m) {262 Image(systemName: label.icon).foregroundStyle(label.color)263 VStack(alignment: .leading, spacing: 0) {264 Text(run.subject?.isEmpty == false ? run.subject! : label.text).font(.callout).lineLimit(1)265 Text([label.text, run.at?.formatted(date: .abbreviated, time: .shortened), run.error].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary).lineLimit(2)266 }267 }268 .accessibilityElement(children: .combine)269 }270 } else { ProgressView().controlSize(.small) }271 } label: {272 Toggle(isOn: Binding(get: { rule.enabled }, set: { on in Task { await setEnabled(rule, on) } })) {273 VStack(alignment: .leading, spacing: 2) {274 Text(rule.name.isEmpty ? L("Règle sans nom") : rule.name)275 Text(rule.summary(labels: model.next.labels)).font(.footnote).foregroundStyle(.secondary)276 if rule.needsAI, !model.next.ai.isEnabled(.triage) { Text("Demande l’intelligence, actuellement désactivée.").font(.caption).foregroundStyle(SPColor.warn) }277 }278 }279 .disabled(!model.isOnline)280 }281 }282 if rules.isEmpty { Text(rulesError ?? (loading ? L("Chargement") : L("Aucune règle d’automatisation"))).foregroundStyle(.secondary) }283 Link(destination: AppConfig.webSettingsURL) { Label("Créer ou modifier une règle sur le web", systemImage: "arrow.up.forward.app") }284 } header: { Text("Règles d’automatisation") } footer: {285 Text("Les règles s’exécutent après la livraison : libellés, mise en veille, rappels, brouillons. Une règle n’envoie jamais de courrier. Activez-les, désactivez-les et consultez leur historique ici ; la création reste sur le web dans cette version.")286 }287 }288 }289 .formStyle(.grouped)290 .task { if account.isEmpty { account = model.currentAccount ?? model.accounts.first?.id ?? "" }; await load() }291 .onChange(of: account) { _, _ in Task { await loadSieve() } }292 }293294 private func loadSieve() async {295 guard let engine = model.engines[account] else { return }296 sieve = nil; sieveError = nil297 do { sieve = try await SieveService(jmap: engine.jmap).load() } catch { sieveError = (error as? APIError)?.isOffline == true ? L("Les filtres ne sont visibles qu’en ligne.") : model.describe(error) }298 }299 private func load() async {300 loading = true301 await loadSieve()302 if model.next.has(.rules) {303 do { rules = try await model.next.api.rules().sorted { $0.position < $1.position }; rulesError = nil } catch { rulesError = NextError.isOffline(error) ? L("Les règles ne sont visibles qu’en ligne.") : model.next.describe(error) }304 }305 loading = false306 }307 private func loadRuns(_ rule: MailRule) async { runs[rule.id] = (try? await model.next.api.ruleRuns(id: rule.id, limit: 10)) ?? [] }308 private func setEnabled(_ rule: MailRule, _ on: Bool) async {309 do {310 let updated = try await model.next.api.setRule(id: rule.id, enabled: on)311 if let n = rules.firstIndex(where: { $0.id == rule.id }) { rules[n] = updated }312 } catch { rulesError = model.next.describe(error); model.toast = Toast(message: model.next.describe(error) ?? "", kind: .error) }313 }314}315